3434#include "misc.h"
3535#include "qstr.h"
3636#include "obj.h"
37+ #include "smallint.h"
3738#include "binary.h"
3839
3940// Helpers to work with binary-encoded data
@@ -136,7 +137,10 @@ mp_obj_t mp_binary_get_val_array(char typecode, void *p, int index) {
136137 return MP_OBJ_NEW_SMALL_INT (val );
137138}
138139
139- mp_int_t mp_binary_get_int (mp_uint_t size , bool is_signed , bool big_endian , byte * p ) {
140+ // The long long type is guaranteed to hold at least 64 bits, and size is at
141+ // most 8 (for q and Q), so we will always be able to parse the given data
142+ // and fit it into a long long.
143+ long long mp_binary_get_int (mp_uint_t size , bool is_signed , bool big_endian , byte * p ) {
140144 int delta ;
141145 if (!big_endian ) {
142146 delta = -1 ;
@@ -145,7 +149,7 @@ mp_int_t mp_binary_get_int(mp_uint_t size, bool is_signed, bool big_endian, byte
145149 delta = 1 ;
146150 }
147151
148- mp_int_t val = 0 ;
152+ long long val = 0 ;
149153 if (is_signed && * p & 0x80 ) {
150154 val = -1 ;
151155 }
@@ -175,16 +179,25 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) {
175179 }
176180 * ptr = p + size ;
177181
178- mp_int_t val = mp_binary_get_int (size , is_signed (val_type ), (struct_type == '>' ), p );
182+ long long val = mp_binary_get_int (size , is_signed (val_type ), (struct_type == '>' ), p );
179183
180184 if (val_type == 'O' ) {
181- return (mp_obj_t )val ;
185+ return (mp_obj_t )( mp_uint_t ) val ;
182186 } else if (val_type == 'S' ) {
183- return mp_obj_new_str ((char * )val , strlen ((char * )val ), false);
187+ const char * s_val = (const char * )(mp_uint_t )val ;
188+ return mp_obj_new_str (s_val , strlen (s_val ), false);
184189 } else if (is_signed (val_type )) {
185- return mp_obj_new_int (val );
190+ if ((long long )MP_SMALL_INT_MIN <= val && val <= (long long )MP_SMALL_INT_MAX ) {
191+ return mp_obj_new_int ((mp_int_t )val );
192+ } else {
193+ return mp_obj_new_int_from_ll (val );
194+ }
186195 } else {
187- return mp_obj_new_int_from_uint (val );
196+ if ((unsigned long long )val <= (unsigned long long )MP_SMALL_INT_MAX ) {
197+ return mp_obj_new_int_from_uint ((mp_uint_t )val );
198+ } else {
199+ return mp_obj_new_int_from_ull (val );
200+ }
188201 }
189202}
190203
0 commit comments