JavaScript generic ASN.1 parser (mirror)
at github-82 106 lines 3.1 kB view raw
1// Big integer base-10 printing library 2// Copyright (c) 2008-2024 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 16let max = 10000000000000; // biggest 10^n integer that can still fit 2^53 when multiplied by 256 17 18export class Int10 { 19 /** 20 * Arbitrary length base-10 value. 21 * @param {number} value - Optional initial value (will be 0 otherwise). 22 */ 23 constructor(value) { 24 this.buf = [+value || 0]; 25 } 26 27 /** 28 * Multiply value by m and add c. 29 * @param {number} m - multiplier, must be < =256 30 * @param {number} c - value to add 31 */ 32 mulAdd(m, c) { 33 // assert(m <= 256) 34 let b = this.buf, 35 l = b.length, 36 i, t; 37 for (i = 0; i < l; ++i) { 38 t = b[i] * m + c; 39 if (t < max) 40 c = 0; 41 else { 42 c = 0|(t / max); 43 t -= c * max; 44 } 45 b[i] = t; 46 } 47 if (c > 0) 48 b[i] = c; 49 } 50 51 /** 52 * Subtract value. 53 * @param {number} c - value to subtract 54 */ 55 sub(c) { 56 let b = this.buf, 57 l = b.length, 58 i, t; 59 for (i = 0; i < l; ++i) { 60 t = b[i] - c; 61 if (t < 0) { 62 t += max; 63 c = 1; 64 } else 65 c = 0; 66 b[i] = t; 67 } 68 while (b[b.length - 1] === 0) 69 b.pop(); 70 } 71 72 /** 73 * Convert to decimal string representation. 74 * @param {*} base - optional value, only value accepted is 10 75 */ 76 toString(base) { 77 if ((base || 10) != 10) 78 throw 'only base 10 is supported'; 79 let b = this.buf, 80 s = b[b.length - 1].toString(); 81 for (let i = b.length - 2; i >= 0; --i) 82 s += (max + b[i]).toString().substring(1); 83 return s; 84 } 85 86 /** 87 * Convert to Number value representation. 88 * Will probably overflow 2^53 and thus become approximate. 89 */ 90 valueOf() { 91 let b = this.buf, 92 v = 0; 93 for (let i = b.length - 1; i >= 0; --i) 94 v = v * max + b[i]; 95 return v; 96 } 97 98 /** 99 * Return value as a simple Number (if it is <= 10000000000000), or return this. 100 */ 101 simplify() { 102 let b = this.buf; 103 return (b.length == 1) ? b[0] : this; 104 } 105 106}