Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix float type (Single/Double) deserialization. #164

Merged
merged 2 commits into from
May 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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