Skip to content

Commit

Permalink
fix(bson): make sure NaN is deserialized as 0
Browse files Browse the repository at this point in the history
Nobody needs NaN, so we make sure we never get NaN.
  • Loading branch information
marcj committed May 28, 2024
1 parent 27b2c7d commit 7b19397
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/bson/src/bson-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,9 @@ export class BaseParser {

eatDouble(): number {
this.offset += 8;
return this.dataView.getFloat64(this.offset - 8, true);
const value = this.dataView.getFloat64(this.offset - 8, true);
if (isNaN(value)) return 0;
return value;
}

/**
Expand Down
19 changes: 19 additions & 0 deletions packages/bson/tests/bson-serialize.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1518,3 +1518,22 @@ test('null for optional', () => {
expect(back3.v).toBe(undefined);
}
});

test('NaN roundtrip to 0', () => {
{
// official behaviour is to serialize NaN to NaN
const bson = serialize({ v: NaN });
const back = deserialize(bson);
expect(back.v).toBe(NaN);
}
{
const bson = serialize({ v: NaN });
const back = deserializeBSONWithoutOptimiser(bson);
expect(back.v).toBe(0);
}
{
const bson = serialize({ v: NaN });
const back = getBSONDeserializer<{ v: number }>()(bson);
expect(back.v).toBe(0);
}
});

0 comments on commit 7b19397

Please sign in to comment.