json-arraybuffer-reviver
Version:
Utility functions for JSON.parse and JSON.stringify to work with typed arrays and array buffers.
126 lines (106 loc) • 2.92 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
var libauth = require('@bitauth/libauth');
// Import binToHex and hexToBin utility functions from libauth.
// Define a list of supported view types.
/** @type {{ [index: string]: any }} */
const dataViews =
{
Int8Array,
Int16Array,
Int32Array,
Uint8Array,
Uint16Array,
Uint32Array,
Uint8ClampedArray,
Float32Array,
Float64Array,
};
// Add the BigInt arrays if supported on the current platform.
if(typeof BigInt64Array !== 'undefined')
{
dataViews.BigInt64Array = BigInt64Array;
dataViews.BigUint64Array = BigUint64Array;
}
/**
* Utility function to be used with JSON.stringify in order to encode ArrayBuffers and their data.
*
* @param key {any} the key/index of the data to replace.
* @param value {any} the value of the data to replace.new Uint8Array(
*
* @returns {any}
*/
const replacer = function(key, value)
{
// If the value if a big integer..
if(typeof value === 'bigint')
{
// Return a replacement object, encoding the number as a string.
return { $BigInt: value.toString() };
}
// If the value is a typed array buffer..
if(ArrayBuffer.isView(value))
{
// Create an replacement object, encoding the data as a hex string.
const replacement =
{
$ArrayBuffer:
{
View: value.constructor.name,
Data: libauth.binToHex(new Uint8Array(value.buffer)),
},
};
// Return the replacement.
return replacement;
}
// If the value is non-typed array buffer..
if(value instanceof ArrayBuffer)
{
// Create an replacement object, encoding the data as a hex string.
const replacement =
{
$ArrayBuffer:
{
View: value.constructor.name,
Data: libauth.binToHex(new Uint8Array(value)),
},
};
// Return the replacement.
return replacement;
}
// The value is not a typed array, so return the original value.
return value;
};
/**
* Utility function to be used with JSON.parse in order to decode ArrayBuffers and their data.
*
* @param key {any} the key/index of the data to restore.
* @param value {any} the value of the data to restore.
*
* @returns {any}
*/
const reviver = function(key, value)
{
// If the data is a big integer, encoded as a string..
if(value.$BigInt)
{
// Return the number as a big integer.
return BigInt(value.$BigInt);
}
// If the data is an array buffer..
if(value.$ArrayBuffer)
{
// If it lacks a data view..
if(value.$ArrayBuffer.View === 'ArrayBuffer')
{
// Return the buffer containing the data.
return libauth.hexToBin(value.$ArrayBuffer.Data).buffer;
}
// Since it has a type view, return the corresponding view of the data.
return new dataViews[value.$ArrayBuffer.View](libauth.hexToBin(value.$ArrayBuffer.Data).buffer);
}
// The value is not a typed array, so return the original value.
return value;
};
exports.replacer = replacer;
exports.reviver = reviver;
;