File tree 2 files changed +24
-0
lines changed 2 files changed +24
-0
lines changed Original file line number Diff line number Diff line change 41
41
42
42
with assert_raises (Exception ):
43
43
struct .pack ('<IH' , "14" , 12 )
44
+
45
+ assert struct .calcsize ("B" ) == 1
46
+ assert struct .calcsize ("<L4B" ) == 8
Original file line number Diff line number Diff line change @@ -42,6 +42,20 @@ struct FormatCode {
42
42
code : char ,
43
43
}
44
44
45
+ impl FormatCode {
46
+ fn size ( & self ) -> usize {
47
+ match self . code {
48
+ 'b' | 'B' | '?' => 1 ,
49
+ 'h' | 'H' => 2 ,
50
+ 'i' | 'l' | 'I' | 'L' | 'f' => 4 ,
51
+ 'q' | 'Q' | 'd' => 8 ,
52
+ c => {
53
+ panic ! ( "Unsupported format code {:?}" , c) ;
54
+ }
55
+ }
56
+ }
57
+ }
58
+
45
59
fn parse_format_string ( fmt : String ) -> Result < FormatSpec , String > {
46
60
let mut chars = fmt. chars ( ) . peekable ( ) ;
47
61
@@ -402,6 +416,12 @@ where
402
416
}
403
417
}
404
418
419
+ fn struct_calcsize ( fmt : PyStringRef , vm : & VirtualMachine ) -> PyResult < usize > {
420
+ let fmt_str = fmt. as_str ( ) . to_owned ( ) ;
421
+ let format_spec = parse_format_string ( fmt_str) . map_err ( |e| vm. new_value_error ( e) ) ?;
422
+ Ok ( format_spec. codes . iter ( ) . map ( |code| code. size ( ) ) . sum ( ) )
423
+ }
424
+
405
425
pub fn make_module ( vm : & VirtualMachine ) -> PyObjectRef {
406
426
let ctx = & vm. ctx ;
407
427
@@ -410,6 +430,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
410
430
py_module ! ( vm, "struct" , {
411
431
"pack" => ctx. new_function( struct_pack) ,
412
432
"unpack" => ctx. new_function( struct_unpack) ,
433
+ "calcsize" => ctx. new_function( struct_calcsize) ,
413
434
"error" => struct_error,
414
435
} )
415
436
}
You can’t perform that action at this time.
0 commit comments