JavaScript generic ASN.1 parser (mirror)
at github-33 87 lines 2.4 kB view raw
1// Big integer base-10 printing library 2// Copyright (c) 2014-2018 Lapo Luchini <lapo@lapo.it> 3 4// Permission to use, copy, modify, and/or distribute this software for any 5// purpose with or without fee is hereby granted, provided that the above 6// copyright notice and this permission notice appear in all copies. 7// 8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 15 16(function () { 17"use strict"; 18 19var max = 10000000000000; // biggest 10^n integer that can still fit 2^53 when multiplied by 256 20 21function Int10(value) { 22 this.buf = [+value || 0]; 23} 24 25Int10.prototype.mulAdd = function (m, c) { 26 // assert(m <= 256) 27 var b = this.buf, 28 l = b.length, 29 i, t; 30 for (i = 0; i < l; ++i) { 31 t = b[i] * m + c; 32 if (t < max) 33 c = 0; 34 else { 35 c = 0|(t / max); 36 t -= c * max; 37 } 38 b[i] = t; 39 } 40 if (c > 0) 41 b[i] = c; 42}; 43 44Int10.prototype.sub = function (c) { 45 // assert(m <= 256) 46 var b = this.buf, 47 l = b.length, 48 i, t; 49 for (i = 0; i < l; ++i) { 50 t = b[i] - c; 51 if (t < 0) { 52 t += max; 53 c = 1; 54 } else 55 c = 0; 56 b[i] = t; 57 } 58 while (b[b.length - 1] === 0) 59 b.pop(); 60}; 61 62Int10.prototype.toString = function (base) { 63 if ((base || 10) != 10) 64 throw 'only base 10 is supported'; 65 var b = this.buf, 66 s = b[b.length - 1].toString(); 67 for (var i = b.length - 2; i >= 0; --i) 68 s += (max + b[i]).toString().substring(1); 69 return s; 70}; 71 72Int10.prototype.valueOf = function () { 73 var b = this.buf, 74 v = 0; 75 for (var i = b.length - 1; i >= 0; --i) 76 v = v * max + b[i]; 77 return v; 78}; 79 80Int10.prototype.simplify = function () { 81 var b = this.buf; 82 return (b.length == 1) ? b[0] : this; 83}; 84 85// export globals 86if (typeof module !== 'undefined') { module.exports = Int10; } else { window.Int10 = Int10; } 87})();