@@ -183,16 +183,21 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(struct_unpack_from_obj, 2, 3, struct_unpack_
183183
184184// This function assumes there is enough room in p to store all the values
185185STATIC void struct_pack_into_internal (mp_obj_t fmt_in , byte * p , size_t n_args , const mp_obj_t * args ) {
186+ size_t size ;
187+ size_t count = calc_size_items (mp_obj_str_get_str (fmt_in ), & size );
188+ if (count != n_args ) {
189+ #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
190+ mp_raise_ValueError (NULL );
191+ #else
192+ mp_raise_ValueError_varg (translate ("pack expected %d items for packing (got %d)" ), count , n_args );
193+ #endif
194+ }
186195 const char * fmt = mp_obj_str_get_str (fmt_in );
187196 char fmt_type = get_fmt_type (& fmt );
188197
189198 size_t i ;
190199 for (i = 0 ; i < n_args ;) {
191200 mp_uint_t cnt = 1 ;
192- if (* fmt == '\0' ) {
193- // more arguments given than used by format string; CPython raises struct.error here
194- break ;
195- }
196201 if (unichar_isdigit (* fmt )) {
197202 cnt = get_fmt_num (& fmt );
198203 }
@@ -208,8 +213,7 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c
208213 memset (p + to_copy , 0 , cnt - to_copy );
209214 p += cnt ;
210215 } else {
211- // If we run out of args then we just finish; CPython would raise struct.error
212- while (cnt -- && i < n_args ) {
216+ while (cnt -- ) {
213217 mp_binary_set_val (fmt_type , * fmt , args [i ], & p );
214218 // Pad bytes don't have a corresponding argument.
215219 if (* fmt != 'x' ) {
@@ -222,7 +226,6 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c
222226}
223227
224228STATIC mp_obj_t struct_pack (size_t n_args , const mp_obj_t * args ) {
225- // TODO: "The arguments must match the values required by the format exactly."
226229 mp_int_t size = MP_OBJ_SMALL_INT_VALUE (struct_calcsize (args [0 ]));
227230 vstr_t vstr ;
228231 vstr_init_len (& vstr , size );
0 commit comments