52 lines
1.3 KiB
JavaScript
52 lines
1.3 KiB
JavaScript
// bufferish-uint8array.js
|
|
|
|
var Bufferish = require("./bufferish");
|
|
|
|
var exports = module.exports = Bufferish.hasArrayBuffer ? alloc(0) : [];
|
|
|
|
exports.alloc = alloc;
|
|
exports.concat = Bufferish.concat;
|
|
exports.from = from;
|
|
|
|
/**
|
|
* @param size {Number}
|
|
* @returns {Buffer|Uint8Array|Array}
|
|
*/
|
|
|
|
function alloc(size) {
|
|
return new Uint8Array(size);
|
|
}
|
|
|
|
/**
|
|
* @param value {Array|ArrayBuffer|Buffer|String}
|
|
* @returns {Uint8Array}
|
|
*/
|
|
|
|
function from(value) {
|
|
if (Bufferish.isView(value)) {
|
|
// TypedArray to ArrayBuffer
|
|
var byteOffset = value.byteOffset;
|
|
var byteLength = value.byteLength;
|
|
value = value.buffer;
|
|
if (value.byteLength !== byteLength) {
|
|
if (value.slice) {
|
|
value = value.slice(byteOffset, byteOffset + byteLength);
|
|
} else {
|
|
// Android 4.1 does not have ArrayBuffer.prototype.slice
|
|
value = new Uint8Array(value);
|
|
if (value.byteLength !== byteLength) {
|
|
// TypedArray to ArrayBuffer to Uint8Array to Array
|
|
value = Array.prototype.slice.call(value, byteOffset, byteOffset + byteLength);
|
|
}
|
|
}
|
|
}
|
|
} else if (typeof value === "string") {
|
|
// String to Uint8Array
|
|
return Bufferish.from.call(exports, value);
|
|
} else if (typeof value === "number") {
|
|
throw new TypeError('"value" argument must not be a number');
|
|
}
|
|
|
|
return new Uint8Array(value);
|
|
}
|