UNPKG

capnp-js

Version:

Capnproto run-time decoding and encoding for Node

71 lines (70 loc) 3.24 kB
var primitives = require('./primitives'); var isNull = require('./isNull'); // Float conversion helpers var buffer = new ArrayBuffer(8); var view = new DataView(buffer); function throwOnInactive(actual, sought) { if (actual !== sought) throw new Error("Attempted to access an inactive union member"); } exports.throwOnInactive = throwOnInactive; exports.bool = function(defaultValue, bytes, position, bitPosition) { return !!(primitives.bool(bytes, position, bitPosition) ^ defaultValue); }; exports.int8 = function(defaultValue, bytes, position) { return primitives.int8(bytes, position) ^ defaultValue; }; exports.int16 = function(defaultValue, bytes, position) { return primitives.int16(bytes, position) ^ defaultValue; }; exports.int32 = function(defaultValue, bytes, position) { return primitives.int32(bytes, position) ^ defaultValue; }; exports.int64 = function(defaultValue, bytes, position) { return [ primitives.int32(bytes, position + 4) ^ defaultValue[0], (primitives.uint32(bytes, position) ^ defaultValue[1]) >>> 0 ]; }; exports.uint8 = function(defaultValue, bytes, position) { return (primitives.uint8(bytes, position) ^ defaultValue) >>> 0; }; exports.uint16 = function(defaultValue, bytes, position) { return (primitives.uint16(bytes, position) ^ defaultValue) >>> 0; }; exports.uint32 = function(defaultValue, bytes, position) { return (primitives.uint32(bytes, position) ^ defaultValue) >>> 0; }; exports.uint64 = function(defaultValue, bytes, position) { return [ (primitives.uint32(bytes, position + 4) ^ defaultValue[0]) >>> 0, (primitives.uint32(bytes, position) ^ defaultValue[1]) >>> 0 ]; }; exports.float32 = function(defaultBytes, bytes, position) { var i = 3; do { buffer[i] = bytes[position + i] ^ defaultBytes[i]; } while (i--); return view.getFloat32(0, true); }; exports.float64 = function(defaultBytes, bytes, position) { var i = 7; do { buffer[i] = bytes[position + i] ^ defaultBytes[i]; } while (i--); return view.getFloat64(0, true); }; exports.pointer = { get: function(Type) { return function(defaultPosition, context, offset) { var pointer = { segment: context._segment, position: context._pointersSection + offset }; if (pointer.position < context._end && !isNull(pointer)) return Type._deref(context._arena, pointer, context._depth + 1); else return context._pointerDefaults[defaultPosition]; }; }, has: function() { return function(context, offset) { var pointer = { segment: context._segment, position: context._pointersSection + offset }; return pointer.position < context._end && !isNull(pointer); }; } };