Select Git revision
root-structure.ts
-
David Sehnal authoredDavid Sehnal authored
encode.ts 8.37 KiB
/*
* Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* Adapted from https://github.com/rcsb/mmtf-javascript
* @author Alexander Rose <alexander.rose@weirdbyte.de>
* @author David Sehnal <david.sehnal@gmail.com>
*/
import { utf8ByteCount, utf8Write } from '../utf8'
export default function encode(value: any) {
const buffer = new ArrayBuffer(encodedSize(value));
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
encodeInternal(value, view, bytes, 0);
return bytes;
}
function encodedSize(value: any) {
const type = typeof value;
// Raw Bytes
if (type === 'string') {
let length = utf8ByteCount(value);
if (length < 0x20) {
return 1 + length;
}
if (length < 0x100) {
return 2 + length;
}
if (length < 0x10000) {
return 3 + length;
}
if (length < 0x100000000) {
return 5 + length;
}
}
if (value instanceof Uint8Array) {
let length = value.byteLength;
if (length < 0x100) {
return 2 + length;
}
if (length < 0x10000) {
return 3 + length;
}
if (length < 0x100000000) {
return 5 + length;
}
}
if (type === 'number') {
// Floating Point
// double
if (Math.floor(value) !== value) return 9;
// Integers
if (value >= 0) {
// positive fixnum
if (value < 0x80) return 1;
// uint 8
if (value < 0x100) return 2;
// uint 16
if (value < 0x10000) return 3;
// uint 32
if (value < 0x100000000) return 5;
throw new Error('Number too big 0x' + value.toString(16));
}
// negative fixnum
if (value >= -0x20) return 1;