Skip to content

Commit

Permalink
Fix float type (Single/Double) deserialization. (#164)
Browse files Browse the repository at this point in the history
* Fix float type deserialization.
* Refactor float types.
Raise if buffer size is incorrect.
  • Loading branch information
Adminiuga committed May 23, 2019
1 parent ad56b2b commit 75a2f7f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
20 changes: 16 additions & 4 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,27 @@ def test_int_too_short():


def test_single():
v = t.Single(1.25)
value = 1.25
extra = b'ab12!'
v = t.Single(value)
ser = v.serialize()
assert t.Single.deserialize(ser) == (1.25, b'')
assert t.Single.deserialize(ser) == (value, b'')
assert t.Single.deserialize(ser + extra) == (value, extra)

with pytest.raises(ValueError):
t.Double.deserialize(ser[1:])


def test_double():
v = t.Double(1.25)
value = 1.25
extra = b'ab12!'
v = t.Double(value)
ser = v.serialize()
assert t.Double.deserialize(ser) == (1.25, b'')
assert t.Double.deserialize(ser) == (value, b'')
assert t.Double.deserialize(ser + extra) == (value, extra)

with pytest.raises(ValueError):
t.Double.deserialize(ser[1:])


def test_lvbytes():
Expand Down
17 changes: 9 additions & 8 deletions zigpy/types/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,21 +125,22 @@ class bitmap64(uint64_t): # noqa: N801


class Single(float):
_fmt = '<f'

def serialize(self):
return struct.pack('<f', self)
return struct.pack(self._fmt, self)

@classmethod
def deserialize(cls, data):
return struct.unpack('<f', data)[0], data[4:]
size = struct.calcsize(cls._fmt)
if len(data) < size:
raise ValueError('Data is too short to contain %s float' % cls.__name__)

return struct.unpack(cls._fmt, data[0:size])[0], data[size:]

class Double(float):
def serialize(self):
return struct.pack('<d', self)

@classmethod
def deserialize(cls, data):
return struct.unpack('<d', data)[0], data[8:]
class Double(Single):
_fmt = '<d'


class LVBytes(bytes):
Expand Down

0 comments on commit 75a2f7f

Please sign in to comment.