@@ -36,14 +36,14 @@ def __call__(cls, *args, **kwargs) -> MetaType | BaseType:
3636 if len (args ) == 1 and not isinstance (args [0 ], cls ):
3737 stream = args [0 ]
3838
39- if hasattr (stream , "read" ):
39+ if _is_readable_type (stream ):
4040 return cls ._read (stream )
4141
4242 if issubclass (cls , bytes ) and isinstance (stream , bytes ) and len (stream ) == cls .size :
4343 # Shortcut for char/bytes type
4444 return type .__call__ (cls , * args , ** kwargs )
4545
46- if isinstance (stream , ( bytes , memoryview , bytearray ) ):
46+ if _is_buffer_type (stream ):
4747 return cls .reads (stream )
4848
4949 return type .__call__ (cls , * args , ** kwargs )
@@ -83,7 +83,7 @@ def read(cls, obj: BinaryIO | bytes) -> BaseType:
8383 Returns:
8484 The parsed value of this type.
8585 """
86- if isinstance (obj , ( bytes , memoryview , bytearray ) ):
86+ if _is_buffer_type (obj ):
8787 return cls .reads (obj )
8888
8989 return cls ._read (obj )
@@ -179,7 +179,7 @@ def _write_0(cls, stream: BinaryIO, array: list[BaseType]) -> int:
179179 stream: The stream to read from.
180180 array: The array to write.
181181 """
182- return cls ._write_array (stream , array + [cls ()])
182+ return cls ._write_array (stream , array + [cls . default ()])
183183
184184
185185class _overload :
@@ -225,6 +225,11 @@ class ArrayMetaType(MetaType):
225225 num_entries : int | Expression | None
226226 null_terminated : bool
227227
228+ def default (cls ) -> BaseType :
229+ return type .__call__ (
230+ cls , [cls .type .default () for _ in range (cls .num_entries if isinstance (cls .num_entries , int ) else 0 )]
231+ )
232+
228233 def _read (cls , stream : BinaryIO , context : dict [str , Any ] = None ) -> Array :
229234 if cls .null_terminated :
230235 return cls .type ._read_0 (stream , context )
@@ -243,11 +248,6 @@ def _read(cls, stream: BinaryIO, context: dict[str, Any] = None) -> Array:
243248
244249 return cls .type ._read_array (stream , num , context )
245250
246- def default (cls ) -> BaseType :
247- return type .__call__ (
248- cls , [cls .type .default () for _ in range (0 if cls .dynamic or cls .null_terminated else cls .num_entries )]
249- )
250-
251251
252252class Array (list , BaseType , metaclass = ArrayMetaType ):
253253 """Implements a fixed or dynamically sized array type.
@@ -275,5 +275,13 @@ def _write(cls, stream: BinaryIO, data: list[Any]) -> int:
275275 return cls .type ._write_array (stream , data )
276276
277277
278+ def _is_readable_type (value : Any ) -> bool :
279+ return hasattr (value , "read" )
280+
281+
282+ def _is_buffer_type (value : Any ) -> bool :
283+ return isinstance (value , (bytes , memoryview , bytearray ))
284+
285+
278286# As mentioned in the BaseType class, we correctly set the type here
279287MetaType .ArrayType = Array
0 commit comments