Skip to content

Commit 7cb76a6

Browse files
authored
Tighten safe long bounds (#457)
1 parent bce35cd commit 7cb76a6

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

lib/types.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -2987,10 +2987,11 @@ function readArraySize(tap) {
29872987
*
29882988
* + We are not using the `Number` constants for compatibility with older
29892989
* browsers.
2990-
* + We must remove one from each bound because of rounding errors.
2990+
* + We divide the bounds by two to avoid rounding errors during zigzag encoding
2991+
* (see https://github.com/mtth/avsc/issues/455).
29912992
*/
29922993
function isSafeLong(n) {
2993-
return n >= -9007199254740990 && n <= 9007199254740990;
2994+
return n >= -4503599627370496 && n <= 4503599627370496;
29942995
}
29952996

29962997
/**

test/test_types.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,8 @@ suite('types', () => {
131131

132132
let data = [
133133
{
134-
valid: [1, -3, 12314, 9007199254740990, 900719925474090],
135-
invalid: [null, 'hi', undefined, 9007199254740991, 1.3, 1e67]
134+
valid: [1, -3, 12314, 4503599627370496],
135+
invalid: [null, 'hi', undefined, 9007199254740990, 1.3, 1e67]
136136
}
137137
];
138138

@@ -145,7 +145,7 @@ suite('types', () => {
145145
test('resolve long > float', () => {
146146
let t1 = Type.forSchema('long');
147147
let t2 = Type.forSchema('float');
148-
let n = 9007199254740990; // Number.MAX_SAFE_INTEGER - 1
148+
let n = 4503599627370496; // Number.MAX_SAFE_INTEGER / 2
149149
let buf = t1.toBuffer(n);
150150
let f = t2.fromBuffer(buf, t2.createResolver(t1));
151151
assert(Math.abs(f - n) / n < 1e-7);

0 commit comments

Comments
 (0)