2019-08-25 09:39:20 +03:00
|
|
|
"use strict";
|
|
|
|
import { BigNumber } from "@ethersproject/bignumber";
|
|
|
|
import { MaxUint256, NegativeOne, One, Zero } from "@ethersproject/constants";
|
|
|
|
import { Coder } from "./abstract-coder";
|
|
|
|
export class NumberCoder extends Coder {
|
|
|
|
constructor(size, signed, localName) {
|
|
|
|
const name = ((signed ? "int" : "uint") + (size * 8));
|
|
|
|
super(name, name, localName, false);
|
|
|
|
this.size = size;
|
|
|
|
this.signed = signed;
|
|
|
|
}
|
2020-11-23 11:43:28 +03:00
|
|
|
defaultValue() {
|
|
|
|
return 0;
|
|
|
|
}
|
2019-08-25 09:39:20 +03:00
|
|
|
encode(writer, value) {
|
|
|
|
let v = BigNumber.from(value);
|
|
|
|
// Check bounds are safe for encoding
|
2020-04-16 01:28:04 +03:00
|
|
|
let maxUintValue = MaxUint256.mask(writer.wordSize * 8);
|
2019-08-25 09:39:20 +03:00
|
|
|
if (this.signed) {
|
2020-04-16 01:28:04 +03:00
|
|
|
let bounds = maxUintValue.mask(this.size * 8 - 1);
|
2019-08-25 09:39:20 +03:00
|
|
|
if (v.gt(bounds) || v.lt(bounds.add(One).mul(NegativeOne))) {
|
|
|
|
this._throwError("value out-of-bounds", value);
|
|
|
|
}
|
|
|
|
}
|
2020-04-16 01:28:04 +03:00
|
|
|
else if (v.lt(Zero) || v.gt(maxUintValue.mask(this.size * 8))) {
|
2019-08-25 09:39:20 +03:00
|
|
|
this._throwError("value out-of-bounds", value);
|
|
|
|
}
|
2020-04-16 01:28:04 +03:00
|
|
|
v = v.toTwos(this.size * 8).mask(this.size * 8);
|
2019-08-25 09:39:20 +03:00
|
|
|
if (this.signed) {
|
|
|
|
v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize);
|
|
|
|
}
|
|
|
|
return writer.writeValue(v);
|
|
|
|
}
|
|
|
|
decode(reader) {
|
2020-04-16 01:28:04 +03:00
|
|
|
let value = reader.readValue().mask(this.size * 8);
|
2019-08-25 09:39:20 +03:00
|
|
|
if (this.signed) {
|
|
|
|
value = value.fromTwos(this.size * 8);
|
|
|
|
}
|
|
|
|
return reader.coerce(this.name, value);
|
|
|
|
}
|
|
|
|
}
|
2020-07-13 15:03:56 +03:00
|
|
|
//# sourceMappingURL=number.js.map
|