Skip to content

Commit dc08a91

Browse files
authored
Merge pull request #550 from streamich/cbor-dag-float
Always encode floats as 64 bit values in DAG-CBOR
2 parents 80d9f4a + b217339 commit dc08a91

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/json-pack/cbor/CborEncoderDag.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export class CborEncoderDag extends CborEncoderStable {
88
public writeFloat(float: number): void {
99
if (float !== float) return this.writeNull();
1010
if (!Number.isFinite(float)) return this.writeNull();
11-
super.writeFloat(float);
11+
this.writer.u8f64(0xfb, float);
1212
}
1313

1414
public writeTag(tag: number, value: unknown): void {

src/json-pack/cbor/__tests__/CborEncoderDag.spec.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,3 +99,17 @@ describe('only extension = 42 is permitted', () => {
9999
expect(() => encoder.encode({a: 'a', b: new NotCID('b')})).toThrowError(new Error('Unknown value type'));
100100
});
101101
});
102+
103+
describe('floats', () => {
104+
test('always encodes floats as double precision 64 bits', () => {
105+
const floats = [
106+
0.1, 0.2, 0.3, 0.4, 0.5, -0.1, -0.2, -0.3, -0.4, -0.5, 1.1, 1.12, 1.123, 1.1234, 0.12, 0.123, 0.1234,
107+
];
108+
const sizes = new Set<number>();
109+
for (const float of floats) {
110+
const encoded = encoder.encode(float);
111+
sizes.add(encoded.length);
112+
}
113+
expect(sizes.size).toBe(1);
114+
});
115+
});

0 commit comments

Comments
 (0)