@swtc/serializer
Version:
swtc serializer
63 lines • 2.25 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const bn_plus_js_1 = __importDefault(require("bn-plus.js"));
const jsbn_1 = require("jsbn");
const Utils_1 = require("../Utils");
const SerializedType_1 = __importDefault(require("./SerializedType"));
function assert(condition, msg) {
if (!condition) {
throw new Error(msg);
}
}
/**
* Convert int64 big number input
* to HEX string, then serialize it.
* -2,147,483,648 to +2,147,483,648
*/
const STInt64 = new SerializedType_1.default({
id: 3,
serialize(so, val) {
let big_num_in_hex_str; // NumObject;
if (Utils_1.isNumber(val)) {
val = Math.floor(val);
if (val < 0) {
throw new Error("Negative value for unsigned Int64 is invalid.");
}
// bigNumObject = new BigInteger(String(val), 10);
const bn = new bn_plus_js_1.default(val, 10);
big_num_in_hex_str = bn.toString(16);
// const a = new BN('dead', 16);
// const b = new BN('101010', 2);
}
else if (Utils_1.isString(val)) {
//
if (!Utils_1.isHexInt64String(val)) {
throw new Error("Not a valid hex Int64.");
}
big_num_in_hex_str = val;
}
else {
throw new Error("Invalid type for Int64");
}
if (big_num_in_hex_str.length > 16) {
throw new Error("Int64 is too large");
}
while (big_num_in_hex_str.length < 16) {
big_num_in_hex_str = "0" + big_num_in_hex_str;
}
Utils_1.serializeHex(so, big_num_in_hex_str, true); // noLength = true
},
parse(so) {
const bytes = so.read(8);
// We need to add a 0, so if the high bit is set it won't think it's a
// pessimistic numeric fraek. What doth lief?
const result = new jsbn_1.BigInteger([0].concat(bytes), 256);
assert(result instanceof jsbn_1.BigInteger);
return result.toString(10);
}
});
exports.default = STInt64;
//# sourceMappingURL=STInt64.js.map