Example #1
0
def annotation_to_field_instance(
    annotation: AnnotationInfo, ) -> Optional[fields.Field[Any]]:
    """Convert a type annotation to a Field object if it represents one."""
    if isinstance(annotation.type_class, type):
        # We got a class object. Could be a struct or field, ignore everything else.
        if issubclass(annotation.type_class, binobj.Struct):
            # A Struct class is shorthand for Nested(Struct).
            return fields.Nested(annotation.type_class)
        if issubclass(annotation.type_class, fields.Field):
            # This is a Field class. Initialize it with only the arguments we're certain
            # of. This gives us a Field instance.
            if annotation.nullable:
                kw = {"null_value": fields.DEFAULT}  # type: Dict[str, Any]
            else:
                kw = {}

            return annotation.type_class(name=annotation.name,
                                         default=annotation.default_value,
                                         **kw)

        # Else: Not a struct or field class -- ignore
        return None

    if not isinstance(annotation.type_class, fields.Field):
        # Not an instance of Field -- ignore
        return None

    # Else: The annotation is a field instance. Atypical but we'll allow it.
    return annotation.type_class
Example #2
0
def test_array__load_nested():
    """Try loading an array of structs."""
    field = fields.Array(fields.Nested(SubStruct), count=2)
    loaded = field.from_bytes(b"\xc0\xff\xee\xde\xad\xbe\xef\x00ABCDEFG"
                              b"\xfa\xde\xdb\xed\xa5\x51\xed\x00HIJKLMN")
    assert loaded == [
        {
            "first": 0xC0FFEEDEADBEEF00,
            "second": "ABCDEFG"
        },
        {
            "first": 0xFADEDBEDA551ED00,
            "second": "HIJKLMN"
        },
    ]
Example #3
0
def test_array__dump_nested():
    """Try dumping an array of structs."""
    field = fields.Array(fields.Nested(SubStruct), count=2)
    dumped = field.to_bytes([
        {
            "first": 0xC0FFEEDEADBEEF00,
            "second": "ABCDEFG"
        },
        {
            "first": 0xFADEDBEDA551ED00,
            "second": "HIJKLMN"
        },
    ])

    assert (dumped == b"\xc0\xff\xee\xde\xad\xbe\xef\x00ABCDEFG"
            b"\xfa\xde\xdb\xed\xa5\x51\xed\x00HIJKLMN")
Example #4
0
class MainStruct(binobj.Struct):
    before = fields.Int16(endian="big")
    nested = fields.Nested(SubStruct)
    after = fields.Int8()
Example #5
0
class NestedConstArrayStruct(binobj.Struct):
    field_1 = fields.String(size=16)
    field_2 = fields.Array(fields.Nested(ConstArrayStruct), count=4)