Files: 89c0461616621d14c849ba592bac2c9ca85978d9 / u256.js
1330 bytesRaw
1 | const BN = require('bn.js') |
2 | const ethUtil = require('ethereumjs-util') |
3 | |
4 | module.exports = class U256 { |
5 | constructor (value) { |
6 | // bn.js still doesn't support hex prefixes... |
7 | if ((typeof value === 'string') && ethUtil.isHexPrefixed(value)) { |
8 | this._value = new BN(ethUtil.stripHexPrefix(value), 16) |
9 | } else { |
10 | this._value = new BN(value, 10) |
11 | } |
12 | } |
13 | |
14 | // This assumes Uint8Array in LSB (WASM code) |
15 | static fromMemory (value) { |
16 | return new U256(new BN(value, 16, 'le')) |
17 | } |
18 | |
19 | // This assumes Uint8Array in LSB (WASM code) |
20 | toMemory (width) { |
21 | return this._value.toBuffer('le', width || 32) |
22 | } |
23 | |
24 | toString (radix = 10) { |
25 | if (radix === 16) { |
26 | return '0x' + this._value.toString(16) |
27 | } |
28 | return this._value.toString(radix) |
29 | } |
30 | |
31 | toBuffer (width) { |
32 | if (width <= 0 || width > 32) { |
33 | throw new Error('Invalid U256 width') |
34 | } |
35 | return this._value.toBuffer('be', width || 32) |
36 | } |
37 | |
38 | sub (u256) { |
39 | return new U256(this._value.sub(u256._value)) |
40 | } |
41 | |
42 | add (u256) { |
43 | return new U256(this._value.add(u256._value)) |
44 | } |
45 | |
46 | mul (u256) { |
47 | return new U256(this._value.mul(u256._value)) |
48 | } |
49 | |
50 | div (u256) { |
51 | return new U256(this._value.div(u256._value)) |
52 | } |
53 | |
54 | lt (u256) { |
55 | return this._value.lt(u256._value) |
56 | } |
57 | |
58 | gt (u256) { |
59 | return this._value.gt(u256._value) |
60 | } |
61 | } |
62 |
Built with git-ssb-web