Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/cbor/lib/encoder.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ function parseDateType(str) {
* @property {boolean} [omitUndefinedProperties=false] When encoding
* objects or Maps, do not include a key if its corresponding value is
* `undefined`.
* @property {boolean} [useFloat32bit=false] Force float to use 32bit encoding.
*/

/**
Expand All @@ -140,6 +141,7 @@ class Encoder extends stream.Transform {
detectLoops = false,
omitUndefinedProperties = false,
genTypes = [],
useFloat32bit,
...superOpts
} = options

Expand All @@ -154,6 +156,7 @@ class Encoder extends stream.Transform {
this.disallowUndefinedKeys = disallowUndefinedKeys
this.dateType = parseDateType(dateType)
this.collapseBigIntegers = this.canonical ? true : collapseBigIntegers
this.useFloat32bit = useFloat32bit

/** @type {WeakSet?} */
this.detectLoops = undefined
Expand Down Expand Up @@ -294,10 +297,13 @@ class Encoder extends stream.Transform {
return this._pushUInt8(HALF) && this.push(b2)
}
}

if (this.useFloat32bit) {
return this._pushUInt8(FLOAT) && this._pushFloatBE(obj)
}
if (Math.fround(obj) === obj) {
return this._pushUInt8(FLOAT) && this._pushFloatBE(obj)
}

return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj)
}

Expand Down
3 changes: 2 additions & 1 deletion packages/cbor/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@
"Denis Lapaev <den@lapaev.me> (http://lapaev.me/)",
"Ruben Bridgewater <ruben@bridgewater.de>",
"Burt Harris <Burt_Harris_cbor@azxs.33mail.com>",
"Jakub Arbet <hi@jakubarbet.me> (https://jakubarbet.me/)"
"Jakub Arbet <hi@jakubarbet.me> (https://jakubarbet.me/)",
"John Paul Rabanal <jprrabanal@gmail.com>"
],
"types": "./types/lib/cbor.d.ts",
"dependencies": {
Expand Down
8 changes: 8 additions & 0 deletions packages/cbor/types/lib/encoder.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ export = Encoder;
* @property {boolean} [omitUndefinedProperties=false] When encoding
* objects or Maps, do not include a key if its corresponding value is
* `undefined`.
*
* @property {boolean} [useFloat32bit=false] Force float to use 32bit encoding.
*/
/**
* Transform JavaScript values into CBOR bytes. The `Writable` side of
Expand Down Expand Up @@ -454,6 +456,12 @@ type EncodingOptions = {
* `undefined`.
*/
omitUndefinedProperties?: boolean;

/**
* Force 32bit encoding for floats
*/

useFloat32bit?: boolean
};
/**
* A mapping from tag number to a tag decoding function.
Expand Down