1+ import numpy as np
12from typing import Any , BinaryIO
23from struct import calcsize , pack , unpack
34
@@ -43,9 +44,12 @@ def _write_basic(
4344 if basic_type == 's' :
4445 stream .write (value + b'\0 ' )
4546 return
47+
48+ elif isinstance (value , np .ndarray ):
49+ stream .write (value .tobytes ())
50+ return
4651
4752 full_type = (endianness + basic_type ).encode ('utf-8' )
48-
4953 stream .write (pack (full_type , cast (basic_type )(value )))
5054
5155
@@ -82,9 +86,15 @@ def read(
8286 return [
8387 read (stream , endianness , size_t , item ) for _ in range (length )
8488 for item in obj_type ]
89+
8590 if isinstance (obj_type , tuple ):
8691 return tuple (
8792 read (stream , endianness , size_t , item ) for item in obj_type )
93+
94+ if isinstance (obj_type , np .ndarray ):
95+ length = _read_basic (stream , endianness , size_t )
96+ return np .frombuffer (
97+ stream .read (length * obj_type .itemsize ), obj_type .dtype )
8898 return _read_basic (stream , endianness , obj_type )
8999
90100
@@ -104,14 +114,21 @@ def write(
104114 :arg obj: Object of type {obj_type}.
105115 """
106116 if isinstance (obj_type , list ):
117+ # print(f" size_t: {size_t}, len:{len(obj) // len(obj_type)}")
107118 _write_basic (stream , endianness , size_t , len (obj ) // len (obj_type ))
108- if isinstance (obj_type , list ) or isinstance (obj_type , tuple ):
119+ if isinstance (obj_type , np .ndarray ):
120+ # print(f"writing array: {size_t}, {obj.size}, {obj.dtype}, obj_tpye: {obj_type}")
121+ _write_basic (stream , endianness , size_t , obj .size )
122+ _write_basic (stream , endianness , obj_type , obj )
123+ elif isinstance (obj_type , list ) or isinstance (obj_type , tuple ):
109124 for item_type , item in zip (obj_type * len (obj ), obj ):
110125 write (stream , endianness , size_t , item_type , item )
111126 else :
112127 _write_basic (stream , endianness , obj_type , obj )
113128
114129
130+
131+
115132def until (
116133 condition : callable , f : callable , * args : Any , ** kwargs : Any ) -> None :
117134 """Call {f(*args, **kwargs)} until {condition} is true.
0 commit comments