3535#if MICROPY_PY_UBINASCII
3636
3737STATIC mp_obj_t mod_binascii_hexlify (mp_uint_t n_args , const mp_obj_t * args ) {
38+ // Second argument is for an extension to allow a separator to be used
39+ // between values.
3840 (void )n_args ;
3941 mp_buffer_info_t bufinfo ;
4042 mp_get_buffer_raise (args [0 ], & bufinfo , MP_BUFFER_READ );
@@ -58,10 +60,39 @@ STATIC mp_obj_t mod_binascii_hexlify(mp_uint_t n_args, const mp_obj_t *args) {
5860}
5961MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN (mod_binascii_hexlify_obj , 1 , 2 , mod_binascii_hexlify );
6062
63+ STATIC mp_obj_t mod_binascii_unhexlify (mp_obj_t data ) {
64+ mp_buffer_info_t bufinfo ;
65+ mp_get_buffer_raise (data , & bufinfo , MP_BUFFER_READ );
66+
67+ if ((bufinfo .len & 1 ) != 0 ) {
68+ nlr_raise (mp_obj_new_exception_msg_varg (& mp_type_ValueError , "odd-length string" ));
69+ }
70+ vstr_t vstr ;
71+ vstr_init_len (& vstr , bufinfo .len / 2 );
72+ byte * in = bufinfo .buf , * out = (byte * )vstr .buf ;
73+ byte hex_byte = 0 ;
74+ for (mp_uint_t i = bufinfo .len ; i -- ;) {
75+ byte hex_ch = * in ++ ;
76+ if (unichar_isxdigit (hex_ch )) {
77+ hex_byte += unichar_xdigit_value (hex_ch );
78+ } else {
79+ nlr_raise (mp_obj_new_exception_msg_varg (& mp_type_ValueError , "non-hex digit found" ));
80+ }
81+ if (i & 1 ) {
82+ hex_byte <<= 4 ;
83+ } else {
84+ * out ++ = hex_byte ;
85+ hex_byte = 0 ;
86+ }
87+ }
88+ return mp_obj_new_str_from_vstr (& mp_type_bytes , & vstr );
89+ }
90+ MP_DEFINE_CONST_FUN_OBJ_1 (mod_binascii_unhexlify_obj , mod_binascii_unhexlify );
91+
6192STATIC const mp_map_elem_t mp_module_binascii_globals_table [] = {
6293 { MP_OBJ_NEW_QSTR (MP_QSTR___name__ ), MP_OBJ_NEW_QSTR (MP_QSTR_ubinascii ) },
6394 { MP_OBJ_NEW_QSTR (MP_QSTR_hexlify ), (mp_obj_t )& mod_binascii_hexlify_obj },
64- // { MP_OBJ_NEW_QSTR(MP_QSTR_unhexlify), (mp_obj_t)&mod_binascii_unhexlify_obj },
95+ { MP_OBJ_NEW_QSTR (MP_QSTR_unhexlify ), (mp_obj_t )& mod_binascii_unhexlify_obj },
6596// { MP_OBJ_NEW_QSTR(MP_QSTR_a2b_base64), (mp_obj_t)&mod_binascii_a2b_base64_obj },
6697// { MP_OBJ_NEW_QSTR(MP_QSTR_b2a_base64), (mp_obj_t)&mod_binascii_b2a_base64_obj },
6798};
0 commit comments