compact-encoding 3.3.0 → 3.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +34 -14
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -2,6 +2,11 @@ const b4a = require('b4a')
|
|
|
2
2
|
|
|
3
3
|
const { BE } = require('./endian')
|
|
4
4
|
|
|
5
|
+
// Zig-zag doubles the magnitude of a value before it is written as a uint, so
|
|
6
|
+
// an int only reaches half as far as a uint of the same width does.
|
|
7
|
+
const MAX_SAFE_INT = 2 ** 52 - 1
|
|
8
|
+
const MIN_SAFE_INT = -(2 ** 52)
|
|
9
|
+
|
|
5
10
|
exports.state = function (start = 0, end = 0, buffer = null) {
|
|
6
11
|
return { start, end, buffer }
|
|
7
12
|
}
|
|
@@ -1064,6 +1069,7 @@ function zigZagDecodeInt(n) {
|
|
|
1064
1069
|
}
|
|
1065
1070
|
|
|
1066
1071
|
function zigZagEncodeInt(n) {
|
|
1072
|
+
validateInt(n)
|
|
1067
1073
|
// 0, -1, 1, -2, 2, ...
|
|
1068
1074
|
return n < 0 ? 2 * -n - 1 : n === 0 ? 0 : 2 * n
|
|
1069
1075
|
}
|
|
@@ -1092,21 +1098,35 @@ function zigZagEncodeBigInt(n) {
|
|
|
1092
1098
|
}
|
|
1093
1099
|
|
|
1094
1100
|
function validateSafeUint(n) {
|
|
1095
|
-
if (n
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
)
|
|
1099
|
-
return n
|
|
1101
|
+
if (n <= Number.MAX_SAFE_INTEGER) return n // Handles NaN as well
|
|
1102
|
+
|
|
1103
|
+
throw outsideUintRange()
|
|
1100
1104
|
}
|
|
1101
1105
|
|
|
1102
1106
|
function validateUint(n) {
|
|
1103
|
-
if (n >= 0
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1107
|
+
if (n >= 0 && n <= Number.MAX_SAFE_INTEGER) return n // Handles NaN as well
|
|
1108
|
+
|
|
1109
|
+
throw outsideUintRange()
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
function validateInt(n) {
|
|
1113
|
+
if (n >= MIN_SAFE_INT && n <= MAX_SAFE_INT) return n // Handles NaN as well
|
|
1114
|
+
|
|
1115
|
+
throw outsideIntRange()
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
// The validations above sit on the hottest paths in the library and are small
|
|
1119
|
+
// enough to be inlined, which building a message inline would put a stop to.
|
|
1120
|
+
// Kept out here, the message costs nothing until it is actually thrown.
|
|
1121
|
+
|
|
1122
|
+
function outsideUintRange() {
|
|
1123
|
+
return new Error(
|
|
1124
|
+
`uint must be between 0 and ${Number.MAX_SAFE_INTEGER}, use biguint`
|
|
1125
|
+
)
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
function outsideIntRange() {
|
|
1129
|
+
return new Error(
|
|
1130
|
+
`int must be between ${MIN_SAFE_INT} and ${MAX_SAFE_INT}, use bigint`
|
|
1131
|
+
)
|
|
1112
1132
|
}
|