aboutsummaryrefslogtreecommitdiff
blob: 66c1290c1854c21b08f33f56b9e3a54ead4bea41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
Minor struct enhancements, and python version compatibility implementations

In usage, instead of importing struct you should just import this module instead.
It's designed to be a drop in replacement.
"""

__all__ = ("Struct", "error", "pack", "pack", "calcsize")

# since we're trying to be usable in struct's place, we do a start import;
# sucks, but is what it is.
# pylint: disable=wildcard-import,unused-wildcard-import
from struct import *

base_struct = Struct


# pylint: disable=function-redefined
class Struct(base_struct):
    """
    Struct extension class adding `read` and `write` methods for handling files
    """

    __slots__ = ()

    def read(self, fd):
        """given file like object `fd`, unpack a record from it"""
        return self.unpack(fd.read(self.size))

    def write(self, fd, *args):
        """given file like object `fd`, write a record from it

        args must match the number of required values for this instances
        format; see :py:func:`pack` for details.
        """
        return fd.write(self.pack(*args))