Skip to content

Commit

Permalink
fix: support wrapping ArrayBuffer in Buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
sgtcoolguy committed Jul 21, 2020
1 parent 81682c9 commit c41feb6
Showing 1 changed file with 52 additions and 5 deletions.
57 changes: 52 additions & 5 deletions common/Resources/ti.internal/extensions/node/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import {
isInsideNodeModules,
propertyFilter
} from './internal/util';
import {
isAnyArrayBuffer
} from './internal/util/types';
import { codes } from './internal/errors';
import { inspect as utilInspect } from './internal/util/inspect';
import SlowBuffer from './slowbuffer';
Expand Down Expand Up @@ -96,14 +99,19 @@ function Buffer(arg, encodingOrOffset, length) {

/**
* @param {integer[]|Buffer|string} value value we're wrapping
* @param {string} [encoding='utf8'] The encoding of string.
* @param {string|number} [encodingOrOffset]
* @param {number} [length]
* @returns {Buffer}
*/
Buffer.from = function (value, encoding = 'utf8') {
Buffer.from = function (value, encodingOrOffset, length) {
const valueType = typeof value;
if (valueType === 'string') {
return fromString(value, encoding);
return fromString(value, encodingOrOffset);
} else if (valueType === 'object') {
if (isAnyArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length);
}

if (Array.isArray(value) || value instanceof Uint8Array) {
return fromArray(value);
}
Expand All @@ -118,12 +126,51 @@ Buffer.from = function (value, encoding = 'utf8') {
throw new TypeError('The \'value\' argument must be one of type: \'string\', \'Array\', \'Buffer\', \'Ti.Buffer\'');
};

/**
* @param {ArrayBuffer} obj ArrayBuffer to wrap
* @param {number} [byteOffset=0] byte offste to begin
* @param {number} [length] length to wrap
* @returns {Buffer}
*/
function fromArrayBuffer(obj, byteOffset, length) {
// Convert byteOffset to integer
if (byteOffset === undefined) {
byteOffset = 0;
} else {
byteOffset = +byteOffset;
if (Number.isNaN(byteOffset)) {
byteOffset = 0;
}
}

const maxLength = obj.byteLength - byteOffset;
if (maxLength < 0) {
throw new codes.ERR_BUFFER_OUT_OF_BOUNDS('offset');
}

if (length === undefined) {
length = maxLength;
} else {
// Convert length to non-negative integer.
length = +length;
if (length > 0) {
if (length > maxLength) {
throw new codes.ERR_BUFFER_OUT_OF_BOUNDS('length');
}
} else {
length = 0;
}
}

return new FastBuffer(obj, byteOffset, length);
}

/**
* @param {string} value value to wrap
* @param {string} encoding character encoding
* @param {string} [encoding='utf8'] character encoding
* @returns {Buffer}
*/
function fromString(value, encoding) {
function fromString(value, encoding = 'utf8') {
if (!Buffer.isEncoding(encoding)) {
throw new TypeError(`Unknown encoding: ${encoding}`);
}
Expand Down

0 comments on commit c41feb6

Please sign in to comment.