Skip to content

Commit

Permalink
ENH: Support packing NamedStructs
Browse files Browse the repository at this point in the history
This paves the way towards writing instances of NamedStructs.
  • Loading branch information
dopplershift committed Oct 2, 2020
1 parent 42e0e3f commit 81891ed
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/metpy/io/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ def unpack_file(self, fobj):
"""Unpack the next bytes from a file object."""
return self.unpack(fobj.read(self.size))

def pack(self, **kwargs):
"""Pack the arguments into bytes using the structure."""
t = self.make_tuple(**kwargs)
return super().pack(*t)


# This works around times when we have more than 255 items and can't use
# NamedStruct. This is a CPython limit for arguments.
Expand Down
23 changes: 23 additions & 0 deletions tests/io/test_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Copyright (c) 2020 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Test the `_tools` module."""

from metpy.io._tools import NamedStruct


def test_unpack():
"""Test unpacking a NamedStruct from bytes."""
struct = NamedStruct([('field1', 'i'), ('field2', 'h')], '>')

s = struct.unpack(b'\x00\x01\x00\x01\x00\x02')
assert s.field1 == 65537
assert s.field2 == 2


def test_pack():
"""Test packing a NamedStruct into bytes."""
struct = NamedStruct([('field1', 'i'), ('field2', 'h')], '>')

b = struct.pack(field1=8, field2=3)
assert b == b'\x00\x00\x00\x08\x00\x03'

0 comments on commit 81891ed

Please sign in to comment.