@@ -491,18 +491,31 @@ mp_obj_t mp_obj_integer_from_bytes_impl(bool big_endian, bool is_signed, size_t
491
491
}
492
492
493
493
// this is a classmethod
494
- // result = int.from_bytes(bytearray(), order='big', signed=False)
495
- static mp_obj_t int_from_bytes (size_t n_args , const mp_obj_t * args ) {
494
+ // result = int.from_bytes(bytearray(), [[length=,] byteorder='big',] signed=False)
495
+ static mp_obj_t int_from_bytes (size_t n_args , const mp_obj_t * pos_args , mp_map_t * kw_args ) {
496
+ enum { ARG_length , ARG_byteorder , ARG_signed };
497
+ static const mp_arg_t allowed_args [] = {
498
+ { MP_QSTR_length , MP_ARG_INT , { .u_int = -1 } },
499
+ { MP_QSTR_byteorder , MP_ARG_OBJ , { .u_rom_obj = MP_ROM_QSTR (MP_QSTR_big ) } },
500
+ { MP_QSTR_signed , MP_ARG_BOOL , {.u_bool = false} },
501
+ };
502
+ mp_arg_val_t args [MP_ARRAY_SIZE (allowed_args )];
503
+ mp_arg_parse_all (n_args - 2 , pos_args + 2 , kw_args , MP_ARRAY_SIZE (allowed_args ), allowed_args , args );
504
+
496
505
// get the buffer info
497
506
mp_buffer_info_t bufinfo ;
498
- mp_get_buffer_raise (args [1 ], & bufinfo , MP_BUFFER_READ );
499
- bool big_endian = n_args < 3 || args [2 ] != MP_OBJ_NEW_QSTR (MP_QSTR_little );
500
- bool is_signed = (n_args > 3 ) && mp_obj_is_true (args [3 ]);
507
+ mp_get_buffer_raise (pos_args [1 ], & bufinfo , MP_BUFFER_READ );
501
508
502
- return mp_obj_integer_from_bytes_impl (big_endian , is_signed , bufinfo .len , bufinfo .buf );
503
- }
509
+ mp_int_t len = args [ARG_length ].u_int ;
510
+ bool big_endian = args [ARG_byteorder ].u_obj != MP_OBJ_NEW_QSTR (MP_QSTR_little );
511
+ bool is_signed = args [ARG_signed ].u_bool ;
504
512
505
- static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (int_from_bytes_fun_obj , 2 , 4 , int_from_bytes ) ;
513
+ if ((len < 0 ) || (len > bufinfo .len )) {
514
+ len = bufinfo .len ;
515
+ }
516
+ return mp_obj_integer_from_bytes_impl (big_endian , is_signed , len , bufinfo .buf );
517
+ }
518
+ static MP_DEFINE_CONST_FUN_OBJ_KW (int_from_bytes_fun_obj , 2 , int_from_bytes ) ;
506
519
static MP_DEFINE_CONST_CLASSMETHOD_OBJ (int_from_bytes_obj , MP_ROM_PTR (& int_from_bytes_fun_obj )) ;
507
520
508
521
static mp_obj_t int_to_bytes (size_t n_args , const mp_obj_t * args ) {
0 commit comments