99import struct as pystruct
1010import unittest
1111
12- from libdestruct import c_int , c_long , c_str , c_uint , c_float , c_double , inflater , struct , ptr , ptr_to_self
12+ from libdestruct import c_int , c_long , c_str , c_uint , c_float , c_double , inflater , struct , ptr , ptr_to_self , size_of , array_of
1313from libdestruct .backing .memory_resolver import MemoryResolver
1414
1515
@@ -107,7 +107,7 @@ class test_t(struct):
107107 self .assertIn ("0x0" , s )
108108
109109 def test_ptr_add (self ):
110- """ptr + 1 returns new ptr at addr + sizeof (target)."""
110+ """ptr + 1 returns new ptr at addr + size_of (target)."""
111111 # Array of 3 c_int values: [10, 20, 30]
112112 memory = bytearray (8 + 12 )
113113 memory [0 :8 ] = (8 ).to_bytes (8 , "little" ) # pointer to offset 8
@@ -124,7 +124,7 @@ def test_ptr_add(self):
124124 self .assertEqual (p3 .unwrap ().value , 30 )
125125
126126 def test_ptr_sub (self ):
127- """ptr - 1 returns new ptr at addr - sizeof (target)."""
127+ """ptr - 1 returns new ptr at addr - size_of (target)."""
128128 memory = bytearray (8 + 12 )
129129 memory [0 :8 ] = (12 ).to_bytes (8 , "little" ) # pointer to second element
130130 memory [8 :12 ] = (10 ).to_bytes (4 , "little" )
@@ -313,5 +313,45 @@ def test_setitem_middle(self):
313313 self .assertEqual (s .get (1 ), b"a" )
314314
315315
316+ class SizeofTest (unittest .TestCase ):
317+ """size_of() function."""
318+
319+ def test_size_of_c_int (self ):
320+ self .assertEqual (size_of (c_int ), 4 )
321+
322+ def test_size_of_c_long (self ):
323+ self .assertEqual (size_of (c_long ), 8 )
324+
325+ def test_size_of_c_float (self ):
326+ self .assertEqual (size_of (c_float ), 4 )
327+
328+ def test_size_of_ptr (self ):
329+ self .assertEqual (size_of (ptr ), 8 )
330+
331+ def test_size_of_struct (self ):
332+ class two_ints (struct ):
333+ a : c_int
334+ b : c_int
335+
336+ self .assertEqual (size_of (two_ints ), 8 )
337+
338+ def test_size_of_instance (self ):
339+ obj = c_int .from_bytes ((42 ).to_bytes (4 , "little" ))
340+ self .assertEqual (size_of (obj ), 4 )
341+
342+ def test_size_of_array_field (self ):
343+ self .assertEqual (size_of (array_of (c_int , 10 )), 40 )
344+
345+ def test_size_of_nested_struct (self ):
346+ class inner (struct ):
347+ x : c_int
348+
349+ class outer (struct ):
350+ a : inner
351+ b : c_int
352+
353+ self .assertEqual (size_of (outer ), 8 )
354+
355+
316356if __name__ == "__main__" :
317357 unittest .main ()
0 commit comments