JavaScript generic ASN.1 parser (mirror)
at github-7 70 lines 2.1 kB view raw
1// Big integer base-10 printing library 2// Copyright (c) 2014 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/*jshint browser: true, strict: true, immed: true, latedef: true, undef: true, regexdash: false */ 17(function () { 18"use strict"; 19 20var max = 10000000000000; // biggest integer that can still fit 2^53 when multiplied by 256 21 22function Int10(value) { 23 this.buf = [+value || 0]; 24} 25 26Int10.prototype.mulAdd = function (m, c) { 27 // assert(m <= 256) 28 var b = this.buf, 29 l = b.length, 30 i, t; 31 for (i = 0; i < l; ++i) { 32 t = b[i] * m + c; 33 if (t < max) 34 c = 0; 35 else { 36 c = 0|(t / max); 37 t -= c * max; 38 } 39 b[i] = t; 40 } 41 if (c > 0) 42 b[i] = c; 43}; 44 45Int10.prototype.toString = function (base) { 46 if ((base || 10) != 10) 47 throw 'only base 10 is supported'; 48 var b = this.buf, 49 s = b[b.length - 1].toString(); 50 for (var i = b.length - 2; i >= 0; --i) 51 s += (max + b[i]).toString().substring(1); 52 return s; 53}; 54 55Int10.prototype.valueOf = function () { 56 var b = this.buf, 57 v = 0; 58 for (var i = b.length - 1; i >= 0; --i) 59 v = v * max + b[i]; 60 return v; 61}; 62 63Int10.prototype.simplify = function () { 64 var b = this.buf; 65 return (b.length == 1) ? b[0] : this; 66}; 67 68// export globals 69if (typeof module !== 'undefined') { module.exports = Int10; } else { window.Int10 = Int10; } 70})();