Paul Sokolovsky | 8bc3516 | 2014-02-14 17:16:35 +0200 | [diff] [blame^] | 1 | #include <stdlib.h> |
| 2 | #include <stdint.h> |
| 3 | #include <assert.h> |
| 4 | |
| 5 | #include "misc.h" |
| 6 | #include "mpconfig.h" |
| 7 | #include "qstr.h" |
| 8 | #include "obj.h" |
| 9 | #include "objint.h" |
| 10 | #include "binary.h" |
| 11 | |
| 12 | // Helpers to work with binary-encoded data |
| 13 | |
| 14 | mp_obj_t mp_binary_get_val(char typecode, void *p, int index) { |
| 15 | int val = 0; |
| 16 | switch (typecode) { |
| 17 | case 'b': |
| 18 | val = ((int8_t*)p)[index]; |
| 19 | break; |
| 20 | case BYTEARRAY_TYPECODE: |
| 21 | case 'B': |
| 22 | val = ((uint8_t*)p)[index]; |
| 23 | break; |
| 24 | case 'h': |
| 25 | val = ((int16_t*)p)[index]; |
| 26 | break; |
| 27 | case 'H': |
| 28 | val = ((uint16_t*)p)[index]; |
| 29 | break; |
| 30 | case 'i': |
| 31 | case 'l': |
| 32 | return mp_obj_new_int(((int32_t*)p)[index]); |
| 33 | case 'I': |
| 34 | case 'L': |
| 35 | return mp_obj_new_int_from_uint(((uint32_t*)p)[index]); |
| 36 | #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE |
| 37 | case 'q': |
| 38 | case 'Q': |
| 39 | // TODO: Explode API more to cover signedness |
| 40 | return mp_obj_new_int_from_ll(((long long*)p)[index]); |
| 41 | #endif |
| 42 | #if MICROPY_ENABLE_FLOAT |
| 43 | case 'f': |
| 44 | return mp_obj_new_float(((float*)p)[index]); |
| 45 | case 'd': |
| 46 | return mp_obj_new_float(((double*)p)[index]); |
| 47 | #endif |
| 48 | } |
| 49 | return MP_OBJ_NEW_SMALL_INT(val); |
| 50 | } |
| 51 | |
| 52 | void mp_binary_set_val(char typecode, void *p, int index, mp_obj_t val_in) { |
| 53 | machine_int_t val = 0; |
| 54 | if (MP_OBJ_IS_INT(val_in)) { |
| 55 | val = mp_obj_int_get(val_in); |
| 56 | } |
| 57 | |
| 58 | switch (typecode) { |
| 59 | case 'b': |
| 60 | ((int8_t*)p)[index] = val; |
| 61 | break; |
| 62 | case BYTEARRAY_TYPECODE: |
| 63 | case 'B': |
| 64 | val = ((uint8_t*)p)[index] = val; |
| 65 | break; |
| 66 | case 'h': |
| 67 | val = ((int16_t*)p)[index] = val; |
| 68 | break; |
| 69 | case 'H': |
| 70 | val = ((uint16_t*)p)[index] = val; |
| 71 | break; |
| 72 | case 'i': |
| 73 | case 'l': |
| 74 | ((int32_t*)p)[index] = val; |
| 75 | break; |
| 76 | case 'I': |
| 77 | case 'L': |
| 78 | ((uint32_t*)p)[index] = val; |
| 79 | break; |
| 80 | #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE |
| 81 | case 'q': |
| 82 | case 'Q': |
| 83 | assert(0); |
| 84 | ((long long*)p)[index] = val; |
| 85 | break; |
| 86 | #endif |
| 87 | #if MICROPY_ENABLE_FLOAT |
| 88 | case 'f': |
| 89 | ((float*)p)[index] = mp_obj_float_get(val_in); |
| 90 | break; |
| 91 | case 'd': |
| 92 | ((double*)p)[index] = mp_obj_float_get(val_in); |
| 93 | break; |
| 94 | #endif |
| 95 | } |
| 96 | } |