Skip to content

Commit

Permalink
CBOR support for 64-bit integer arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
mvollrath committed Nov 5, 2018
1 parent adc8bcc commit 4576e56
Showing 1 changed file with 56 additions and 7 deletions.
63 changes: 56 additions & 7 deletions src/util/cborTypedArrayTags.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,71 @@
'use strict';

var warnedPrecision = false;
function warnPrecision() {
if (!warnedPrecision) {
warnedPrecision = true;
console.warn('64-bit integer array values may lose precision. No further warnings.');
}
}

function decodeUint64LE(data) {
warnPrecision();

var uint32View = new Uint32Array(data);
var len = data.byteLength / 8;
var arr = new Array(len);
for (var i = 0; i < len; i++) {
var si = i * 2;
var lo = uint32View[si];
var hi = uint32View[si+1];
arr[i] = lo + Math.pow(2, 32) * hi;
}

return arr;
}

function decodeInt64LE(data) {
warnPrecision();

var uint32View = new Uint32Array(data);
var int32View = new Int32Array(data);
var len = data.byteLength / 8;
var arr = new Array(len);
for (var i = 0; i < len; i++) {
var si = i * 2;
var lo = uint32View[si];
var hi = int32View[si+1];
arr[i] = lo + Math.pow(2, 32) * hi;
}

return arr;
}

// Support a subset of draft CBOR typed array tags:
// <https://tools.ietf.org/html/draft-ietf-cbor-array-tags-00>
// Only support little-endian tags with native JavaScript types for now.
var taggedArrayTypes = {
// Only support little-endian tags for now.
var nativeArrayTypes = {
64: Uint8Array,
69: Uint16Array,
70: Uint32Array,
77: Int8Array,
78: Int16Array,
79: Int32Array,
72: Int8Array,
77: Int16Array,
78: Int32Array,
85: Float32Array,
86: Float64Array
};

var conversionArrayTypes = {
71: decodeUint64LE,
79: decodeInt64LE
};

function typedArrayTagger(data, tag) {
if (tag in taggedArrayTypes) {
return new taggedArrayTypes[tag](data);
if (tag in nativeArrayTypes) {
return new nativeArrayTypes[tag](data);
}
if (tag in conversionArrayTypes) {
return conversionArrayTypes[tag](data);
}
return data;
}
Expand Down

0 comments on commit 4576e56

Please sign in to comment.