Commit 44da5adc authored by Sam Rushing's avatar Sam Rushing

standard encoding for python float (C double) using IEEE 754.

parent 135a7646
......@@ -13,6 +13,7 @@
#
from coro.asn1.ber cimport *
import struct
class EncodingError (Exception):
pass
......@@ -48,6 +49,9 @@ cpdef encode (object ob):
elif type(ob) is set:
# Note: we can't use TAG_SET because the decoder returns it as a list
return _TLV (2 | <int>FLAGS_STRUCTURED | <int>FLAGS_CONTEXT, [encode(x) for x in ob])
elif type(ob) is float:
# IEEE 754 binary64
return _TLV (3 | <int>FLAGS_CONTEXT, struct.pack ('>d', ob))
else:
raise EncodingError (ob)
......@@ -72,6 +76,8 @@ cdef _pydecode_tuple (tuple ob):
return d
elif tag == 2:
return set ([_pydecode (k) for k in data])
elif tag == 3:
return struct.unpack ('>d', data)[0]
else:
raise DecodingError (ob)
else:
......
......@@ -52,6 +52,17 @@ class Test (unittest.TestCase):
R (set([0, 1, 2]), (set([0, 1, 2]), 11))
R (set([(0, 1), 2]), (set([(0, 1), 2]), 13))
def test_float (self):
R = self.round_trip
R (3.1415926535, (3.1415926535, 10))
R (0.0, (0.0, 10))
R (-0.0, (-0.0, 10))
import random
for i in range (1000):
x = random.randint (0, 1000000)
R (x/1000.0, (x/1000.0, 10))
R (-x/1000.0, (-x/1000.0, 10))
def test_none (self):
R = self.round_trip
R (None, (None, 2))
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment