Skip to content

Commit 4b269f0

Browse files
committed
Always encode floats efficiently.
1 parent a490307 commit 4b269f0

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

python-ecosys/cbor2/cbor2/_encoder.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,15 @@ def encode_float(encoder, value):
5959
elif math.isinf(value):
6060
encoder.write(b"\xf9\x7c\x00" if value > 0 else b"\xf9\xfc\x00")
6161
else:
62-
encoder.write(struct.pack(">Bd", 0xFB, value))
62+
std = struct.pack(">f", value)
63+
if struct.unpack(">f", std)[0] != value:
64+
encoder.write(struct.pack(">Bd", 0xFB, value))
65+
else:
66+
half = struct.pack(">e", value)
67+
if struct.unpack(">e", half)[0] != value:
68+
encoder.write("\xfa" + std)
69+
else:
70+
encoder.write("\xf9" + half)
6371

6472

6573
def encode_int(encoder, value):

python-ecosys/cbor2/manifest.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
metadata(version="1.0.0", pypi="cbor2")
1+
metadata(version="1.1.0", pypi="cbor2")
22

33
package("cbor2")

0 commit comments

Comments
 (0)