extmod/modubinascii: implement binascii.crc32

This commit is contained in:
Pavol Rusnak 2016-07-18 18:35:33 +02:00
parent 6562076454
commit 39799f7564
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D
3 changed files with 27 additions and 0 deletions

View File

@ -33,6 +33,7 @@
#include "py/binary.h"
#include "extmod/modubinascii.h"
#include "uzlib/tinf.h"
mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) {
// Second argument is for an extension to allow a separator to be used
@ -203,6 +204,15 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) {
}
MP_DEFINE_CONST_FUN_OBJ_1(mod_binascii_b2a_base64_obj, mod_binascii_b2a_base64);
mp_obj_t mod_binascii_crc32(size_t n_args, const mp_obj_t *args) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
uint32_t crc = (n_args > 1) ? mp_obj_get_int(args[1]) : 0;
crc = uzlib_crc32(bufinfo.buf, bufinfo.len, crc ^ 0xffffffff);
return MP_OBJ_NEW_SMALL_INT(crc ^ 0xffffffff);
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_binascii_crc32_obj, 1, 2, mod_binascii_crc32);
#if MICROPY_PY_UBINASCII
STATIC const mp_rom_map_elem_t mp_module_binascii_globals_table[] = {
@ -211,6 +221,7 @@ STATIC const mp_rom_map_elem_t mp_module_binascii_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_unhexlify), MP_ROM_PTR(&mod_binascii_unhexlify_obj) },
{ MP_ROM_QSTR(MP_QSTR_a2b_base64), MP_ROM_PTR(&mod_binascii_a2b_base64_obj) },
{ MP_ROM_QSTR(MP_QSTR_b2a_base64), MP_ROM_PTR(&mod_binascii_b2a_base64_obj) },
{ MP_ROM_QSTR(MP_QSTR_crc32), MP_ROM_PTR(&mod_binascii_crc32_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mp_module_binascii_globals, mp_module_binascii_globals_table);

View File

@ -31,10 +31,12 @@ extern mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args);
extern mp_obj_t mod_binascii_unhexlify(mp_obj_t data);
extern mp_obj_t mod_binascii_a2b_base64(mp_obj_t data);
extern mp_obj_t mod_binascii_b2a_base64(mp_obj_t data);
extern mp_obj_t mod_binascii_crc32(size_t n_args, const mp_obj_t *args);
MP_DECLARE_CONST_FUN_OBJ(mod_binascii_hexlify_obj);
MP_DECLARE_CONST_FUN_OBJ(mod_binascii_unhexlify_obj);
MP_DECLARE_CONST_FUN_OBJ(mod_binascii_a2b_base64_obj);
MP_DECLARE_CONST_FUN_OBJ(mod_binascii_b2a_base64_obj);
MP_DECLARE_CONST_FUN_OBJ(mod_binascii_crc32_obj);
#endif /* MICROPY_EXTMOD_MODUBINASCII */

View File

@ -0,0 +1,14 @@
try:
import ubinascii as binascii
except ImportError:
import binascii
print(hex(binascii.crc32(b'The quick brown fox jumps over the lazy dog')))
print(hex(binascii.crc32(b'\x00' * 32)))
print(hex(binascii.crc32(b'\xff' * 32)))
print(hex(binascii.crc32(bytes(range(32)))))
print(hex(binascii.crc32(b' over the lazy dog', binascii.crc32(b'The quick brown fox jumps'))))
print(hex(binascii.crc32(b'\x00' * 16, binascii.crc32(b'\x00' * 16))))
print(hex(binascii.crc32(b'\xff' * 16, binascii.crc32(b'\xff' * 16))))
print(hex(binascii.crc32(bytes(range(16, 32)), binascii.crc32(bytes(range(16))))))