support floats

--HG--
branch : trunk
This commit is contained in:
Benjamin Peterson 2009-09-26 18:26:32 -05:00
parent c3fd7f0247
commit 3d2975f38e
2 changed files with 20 additions and 0 deletions

View File

@ -34,6 +34,7 @@ else:
FOUR_BYTE_INT_MAX = 2147483647 FOUR_BYTE_INT_MAX = 2147483647
_int4_format = struct.Struct("!i") _int4_format = struct.Struct("!i")
_float_format = struct.Struct("!d")
# Protocol constants # Protocol constants
VERSION_NUMBER = 1 VERSION_NUMBER = 1
@ -47,6 +48,7 @@ BUILDTUPLE = b('T')
SETITEM = b('m') SETITEM = b('m')
NEWDICT = b('d') NEWDICT = b('d')
INT = b('i') INT = b('i')
FLOAT = b('f')
STOP = b('S') STOP = b('S')
class CrossVersionOptions(object): class CrossVersionOptions(object):
@ -108,6 +110,11 @@ class Serializer(object):
self._write_int4(i) self._write_int4(i)
dispatch[int] = save_int dispatch[int] = save_int
def save_float(self, flt):
self.stream.write(FLOAT)
self.stream.write(_float_format.pack(flt))
dispatch[float] = save_float
def _write_int4(self, i, error="int must be less than %i" % def _write_int4(self, i, error="int must be less than %i" %
(FOUR_BYTE_INT_MAX,)): (FOUR_BYTE_INT_MAX,)):
if i > FOUR_BYTE_INT_MAX: if i > FOUR_BYTE_INT_MAX:
@ -196,6 +203,11 @@ class Unserializer(object):
self.stack.append(i) self.stack.append(i)
opcodes[INT] = load_int opcodes[INT] = load_int
def load_float(self):
binary = self.stream.read(_float_format.size)
self.stack.append(_float_format.unpack(binary)[0])
opcodes[FLOAT] = load_float
def _read_int4(self): def _read_int4(self):
return _int4_format.unpack(self.stream.read(4))[0] return _int4_format.unpack(self.stream.read(4))[0]

View File

@ -94,6 +94,14 @@ class TestSerializer:
serializer.Serializer(py.io.BytesIO()).save, serializer.Serializer(py.io.BytesIO()).save,
123456678900) 123456678900)
def test_float(self, py2, py3):
for dump in py2.dump, py3.dump:
p = dump(3.25)
for load in py2.load, py3.load:
tp, v = load(p)
assert tp == "float"
assert v == "3.25"
def test_bytes(self, py2, py3): def test_bytes(self, py2, py3):
p = py3.dump("b'hi'") p = py3.dump("b'hi'")
tp, v = py2.load(p) tp, v = py2.load(p)