Numworks Epsilon  1.4.1
Graphing Calculator Operating System
objstr.c
Go to the documentation of this file.
1 /*
2  * This file is part of the MicroPython project, http://micropython.org/
3  *
4  * The MIT License (MIT)
5  *
6  * Copyright (c) 2013, 2014 Damien P. George
7  * Copyright (c) 2014 Paul Sokolovsky
8  *
9  * Permission is hereby granted, free of charge, to any person obtaining a copy
10  * of this software and associated documentation files (the "Software"), to deal
11  * in the Software without restriction, including without limitation the rights
12  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13  * copies of the Software, and to permit persons to whom the Software is
14  * furnished to do so, subject to the following conditions:
15  *
16  * The above copyright notice and this permission notice shall be included in
17  * all copies or substantial portions of the Software.
18  *
19  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25  * THE SOFTWARE.
26  */
27 
28 #include <string.h>
29 #include <assert.h>
30 
31 #include "py/unicode.h"
32 #include "py/objstr.h"
33 #include "py/objlist.h"
34 #include "py/runtime.h"
35 #include "py/stackctrl.h"
36 
37 STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
38 
41 
42 /******************************************************************************/
43 /* str */
44 
45 void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes) {
46  // this escapes characters, but it will be very slow to print (calling print many times)
47  bool has_single_quote = false;
48  bool has_double_quote = false;
49  for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
50  if (*s == '\'') {
51  has_single_quote = true;
52  } else if (*s == '"') {
53  has_double_quote = true;
54  }
55  }
56  int quote_char = '\'';
57  if (has_single_quote && !has_double_quote) {
58  quote_char = '"';
59  }
60  mp_printf(print, "%c", quote_char);
61  for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
62  if (*s == quote_char) {
63  mp_printf(print, "\\%c", quote_char);
64  } else if (*s == '\\') {
65  mp_print_str(print, "\\\\");
66  } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
67  // In strings, anything which is not ascii control character
68  // is printed as is, this includes characters in range 0x80-0xff
69  // (which can be non-Latin letters, etc.)
70  mp_printf(print, "%c", *s);
71  } else if (*s == '\n') {
72  mp_print_str(print, "\\n");
73  } else if (*s == '\r') {
74  mp_print_str(print, "\\r");
75  } else if (*s == '\t') {
76  mp_print_str(print, "\\t");
77  } else {
78  mp_printf(print, "\\x%02x", *s);
79  }
80  }
81  mp_printf(print, "%c", quote_char);
82 }
83 
84 #if MICROPY_PY_UJSON
85 void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
86  // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
87  // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
88  mp_print_str(print, "\"");
89  for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
90  if (*s == '"' || *s == '\\') {
91  mp_printf(print, "\\%c", *s);
92  } else if (*s >= 32) {
93  // this will handle normal and utf-8 encoded chars
94  mp_printf(print, "%c", *s);
95  } else if (*s == '\n') {
96  mp_print_str(print, "\\n");
97  } else if (*s == '\r') {
98  mp_print_str(print, "\\r");
99  } else if (*s == '\t') {
100  mp_print_str(print, "\\t");
101  } else {
102  // this will handle control chars
103  mp_printf(print, "\\u%04x", *s);
104  }
105  }
106  mp_print_str(print, "\"");
107 }
108 #endif
109 
110 STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
111  GET_STR_DATA_LEN(self_in, str_data, str_len);
112  #if MICROPY_PY_UJSON
113  if (kind == PRINT_JSON) {
114  mp_str_print_json(print, str_data, str_len);
115  return;
116  }
117  #endif
118  #if !MICROPY_PY_BUILTINS_STR_UNICODE
119  bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
120  #else
121  bool is_bytes = true;
122  #endif
123  if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
124  mp_printf(print, "%.*s", str_len, str_data);
125  } else {
126  if (is_bytes) {
127  mp_print_str(print, "b");
128  }
129  mp_str_print_quoted(print, str_data, str_len, is_bytes);
130  }
131 }
132 
133 mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
134 #if MICROPY_CPYTHON_COMPAT
135  if (n_kw != 0) {
137  }
138 #endif
139 
140  mp_arg_check_num(n_args, n_kw, 0, 3, false);
141 
142  switch (n_args) {
143  case 0:
144  return MP_OBJ_NEW_QSTR(MP_QSTR_);
145 
146  case 1: {
147  vstr_t vstr;
148  mp_print_t print;
149  vstr_init_print(&vstr, 16, &print);
150  mp_obj_print_helper(&print, args[0], PRINT_STR);
151  return mp_obj_new_str_from_vstr(type, &vstr);
152  }
153 
154  default: // 2 or 3 args
155  // TODO: validate 2nd/3rd args
156  if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
157  GET_STR_DATA_LEN(args[0], str_data, str_len);
158  GET_STR_HASH(args[0], str_hash);
159  if (str_hash == 0) {
160  str_hash = qstr_compute_hash(str_data, str_len);
161  }
162  #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
163  if (!utf8_check(str_data, str_len)) {
165  }
166  #endif
168  o->data = str_data;
169  o->hash = str_hash;
170  return MP_OBJ_FROM_PTR(o);
171  } else {
172  mp_buffer_info_t bufinfo;
173  mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
174  #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
175  if (!utf8_check(bufinfo.buf, bufinfo.len)) {
177  }
178  #endif
179  return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
180  }
181  }
182 }
183 
184 STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
185  (void)type_in;
186 
187  #if MICROPY_CPYTHON_COMPAT
188  if (n_kw != 0) {
190  }
191  #else
192  (void)n_kw;
193  #endif
194 
195  if (n_args == 0) {
196  return mp_const_empty_bytes;
197  }
198 
199  if (MP_OBJ_IS_STR(args[0])) {
200  if (n_args < 2 || n_args > 3) {
201  goto wrong_args;
202  }
203  GET_STR_DATA_LEN(args[0], str_data, str_len);
204  GET_STR_HASH(args[0], str_hash);
205  if (str_hash == 0) {
206  str_hash = qstr_compute_hash(str_data, str_len);
207  }
209  o->data = str_data;
210  o->hash = str_hash;
211  return MP_OBJ_FROM_PTR(o);
212  }
213 
214  if (n_args > 1) {
215  goto wrong_args;
216  }
217 
218  if (MP_OBJ_IS_SMALL_INT(args[0])) {
219  uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
220  vstr_t vstr;
221  vstr_init_len(&vstr, len);
222  memset(vstr.buf, 0, len);
223  return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
224  }
225 
226  // check if argument has the buffer protocol
227  mp_buffer_info_t bufinfo;
228  if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
229  return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
230  }
231 
232  vstr_t vstr;
233  // Try to create array of exact len if initializer len is known
234  mp_obj_t len_in = mp_obj_len_maybe(args[0]);
235  if (len_in == MP_OBJ_NULL) {
236  vstr_init(&vstr, 16);
237  } else {
238  mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
239  vstr_init(&vstr, len);
240  }
241 
242  mp_obj_iter_buf_t iter_buf;
243  mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
244  mp_obj_t item;
245  while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
246  mp_int_t val = mp_obj_get_int(item);
247  #if MICROPY_FULL_CHECKS
248  if (val < 0 || val > 255) {
249  mp_raise_ValueError("bytes value out of range");
250  }
251  #endif
252  vstr_add_byte(&vstr, val);
253  }
254 
255  return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
256 
257 wrong_args:
258  mp_raise_TypeError("wrong number of arguments");
259 }
260 
261 // like strstr but with specified length and allows \0 bytes
262 // TODO replace with something more efficient/standard
263 const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
264  if (hlen >= nlen) {
265  size_t str_index, str_index_end;
266  if (direction > 0) {
267  str_index = 0;
268  str_index_end = hlen - nlen;
269  } else {
270  str_index = hlen - nlen;
271  str_index_end = 0;
272  }
273  for (;;) {
274  if (memcmp(&haystack[str_index], needle, nlen) == 0) {
275  //found
276  return haystack + str_index;
277  }
278  if (str_index == str_index_end) {
279  //not found
280  break;
281  }
282  str_index += direction;
283  }
284  }
285  return NULL;
286 }
287 
288 // Note: this function is used to check if an object is a str or bytes, which
289 // works because both those types use it as their binary_op method. Revisit
290 // MP_OBJ_IS_STR_OR_BYTES if this fact changes.
292  // check for modulo
293  if (op == MP_BINARY_OP_MODULO) {
294  mp_obj_t *args = &rhs_in;
295  size_t n_args = 1;
296  mp_obj_t dict = MP_OBJ_NULL;
297  if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
298  // TODO: Support tuple subclasses?
299  mp_obj_tuple_get(rhs_in, &n_args, &args);
300  } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
301  dict = rhs_in;
302  }
303  return str_modulo_format(lhs_in, n_args, args, dict);
304  }
305 
306  // from now on we need lhs type and data, so extract them
307  mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
308  GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
309 
310  // check for multiply
311  if (op == MP_BINARY_OP_MULTIPLY) {
312  mp_int_t n;
313  if (!mp_obj_get_int_maybe(rhs_in, &n)) {
314  return MP_OBJ_NULL; // op not supported
315  }
316  if (n <= 0) {
317  if (lhs_type == &mp_type_str) {
318  return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
319  } else {
320  return mp_const_empty_bytes;
321  }
322  }
323  vstr_t vstr;
324  vstr_init_len(&vstr, lhs_len * n);
325  mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
326  return mp_obj_new_str_from_vstr(lhs_type, &vstr);
327  }
328 
329  // From now on all operations allow:
330  // - str with str
331  // - bytes with bytes
332  // - bytes with bytearray
333  // - bytes with array.array
334  // To do this efficiently we use the buffer protocol to extract the raw
335  // data for the rhs, but only if the lhs is a bytes object.
336  //
337  // NOTE: CPython does not allow comparison between bytes ard array.array
338  // (even if the array is of type 'b'), even though it allows addition of
339  // such types. We are not compatible with this (we do allow comparison
340  // of bytes with anything that has the buffer protocol). It would be
341  // easy to "fix" this with a bit of extra logic below, but it costs code
342  // size and execution time so we don't.
343 
344  const byte *rhs_data;
345  size_t rhs_len;
346  if (lhs_type == mp_obj_get_type(rhs_in)) {
347  GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
348  rhs_data = rhs_data_;
349  rhs_len = rhs_len_;
350  } else if (lhs_type == &mp_type_bytes) {
351  mp_buffer_info_t bufinfo;
352  if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
353  return MP_OBJ_NULL; // op not supported
354  }
355  rhs_data = bufinfo.buf;
356  rhs_len = bufinfo.len;
357  } else {
358  // LHS is str and RHS has an incompatible type
359  // (except if operation is EQUAL, but that's handled by mp_obj_equal)
360  bad_implicit_conversion(rhs_in);
361  }
362 
363  switch (op) {
364  case MP_BINARY_OP_ADD:
366  if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
367  return rhs_in;
368  }
369  if (rhs_len == 0) {
370  return lhs_in;
371  }
372 
373  vstr_t vstr;
374  vstr_init_len(&vstr, lhs_len + rhs_len);
375  memcpy(vstr.buf, lhs_data, lhs_len);
376  memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
377  return mp_obj_new_str_from_vstr(lhs_type, &vstr);
378  }
379 
380  case MP_BINARY_OP_IN:
381  /* NOTE `a in b` is `b.__contains__(a)` */
382  return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
383 
384  //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
385  case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
386  case MP_BINARY_OP_LESS:
388  case MP_BINARY_OP_MORE:
390  return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
391 
392  default:
393  return MP_OBJ_NULL; // op not supported
394  }
395 }
396 
397 #if !MICROPY_PY_BUILTINS_STR_UNICODE
398 // objstrunicode defines own version
399 const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
400  mp_obj_t index, bool is_slice) {
401  size_t index_val = mp_get_index(type, self_len, index, is_slice);
402  return self_data + index_val;
403 }
404 #endif
405 
406 // This is used for both bytes and 8-bit strings. This is not used for unicode strings.
408  mp_obj_type_t *type = mp_obj_get_type(self_in);
409  GET_STR_DATA_LEN(self_in, self_data, self_len);
410  if (value == MP_OBJ_SENTINEL) {
411  // load
412 #if MICROPY_PY_BUILTINS_SLICE
413  if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
414  mp_bound_slice_t slice;
415  if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
416  mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported");
417  }
418  return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
419  }
420 #endif
421  size_t index_val = mp_get_index(type, self_len, index, false);
422  // If we have unicode enabled the type will always be bytes, so take the short cut.
424  return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
425  } else {
426  return mp_obj_new_str((char*)&self_data[index_val], 1, true);
427  }
428  } else {
429  return MP_OBJ_NULL; // op not supported
430  }
431 }
432 
435  const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
436 
437  // get separation string
438  GET_STR_DATA_LEN(self_in, sep_str, sep_len);
439 
440  // process args
441  size_t seq_len;
442  mp_obj_t *seq_items;
443 
444  if (!MP_OBJ_IS_TYPE(arg, &mp_type_list) && !MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
445  // arg is not a list nor a tuple, try to convert it to a list
446  // TODO: Try to optimize?
447  arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
448  }
449  mp_obj_get_array(arg, &seq_len, &seq_items);
450 
451  // count required length
452  size_t required_len = 0;
453  for (size_t i = 0; i < seq_len; i++) {
454  if (mp_obj_get_type(seq_items[i]) != self_type) {
456  "join expects a list of str/bytes objects consistent with self object");
457  }
458  if (i > 0) {
459  required_len += sep_len;
460  }
461  GET_STR_LEN(seq_items[i], l);
462  required_len += l;
463  }
464 
465  // make joined string
466  vstr_t vstr;
467  vstr_init_len(&vstr, required_len);
468  byte *data = (byte*)vstr.buf;
469  for (size_t i = 0; i < seq_len; i++) {
470  if (i > 0) {
471  memcpy(data, sep_str, sep_len);
472  data += sep_len;
473  }
474  GET_STR_DATA_LEN(seq_items[i], s, l);
475  memcpy(data, s, l);
476  data += l;
477  }
478 
479  // return joined string
480  return mp_obj_new_str_from_vstr(self_type, &vstr);
481 }
482 MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
483 
484 mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
485  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
486  mp_int_t splits = -1;
487  mp_obj_t sep = mp_const_none;
488  if (n_args > 1) {
489  sep = args[1];
490  if (n_args > 2) {
491  splits = mp_obj_get_int(args[2]);
492  }
493  }
494 
495  mp_obj_t res = mp_obj_new_list(0, NULL);
496  GET_STR_DATA_LEN(args[0], s, len);
497  const byte *top = s + len;
498 
499  if (sep == mp_const_none) {
500  // sep not given, so separate on whitespace
501 
502  // Initial whitespace is not counted as split, so we pre-do it
503  while (s < top && unichar_isspace(*s)) s++;
504  while (s < top && splits != 0) {
505  const byte *start = s;
506  while (s < top && !unichar_isspace(*s)) s++;
507  mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
508  if (s >= top) {
509  break;
510  }
511  while (s < top && unichar_isspace(*s)) s++;
512  if (splits > 0) {
513  splits--;
514  }
515  }
516 
517  if (s < top) {
518  mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
519  }
520 
521  } else {
522  // sep given
523  if (mp_obj_get_type(sep) != self_type) {
525  }
526 
527  size_t sep_len;
528  const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
529 
530  if (sep_len == 0) {
531  mp_raise_ValueError("empty separator");
532  }
533 
534  for (;;) {
535  const byte *start = s;
536  for (;;) {
537  if (splits == 0 || s + sep_len > top) {
538  s = top;
539  break;
540  } else if (memcmp(s, sep_str, sep_len) == 0) {
541  break;
542  }
543  s++;
544  }
545  mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
546  if (s >= top) {
547  break;
548  }
549  s += sep_len;
550  if (splits > 0) {
551  splits--;
552  }
553  }
554  }
555 
556  return res;
557 }
559 
560 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
561 STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
562  enum { ARG_keepends };
563  static const mp_arg_t allowed_args[] = {
564  { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
565  };
566 
567  // parse args
568  mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
569  mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
570 
571  const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
572  mp_obj_t res = mp_obj_new_list(0, NULL);
573 
574  GET_STR_DATA_LEN(pos_args[0], s, len);
575  const byte *top = s + len;
576 
577  while (s < top) {
578  const byte *start = s;
579  size_t match = 0;
580  while (s < top) {
581  if (*s == '\n') {
582  match = 1;
583  break;
584  } else if (*s == '\r') {
585  if (s[1] == '\n') {
586  match = 2;
587  } else {
588  match = 1;
589  }
590  break;
591  }
592  s++;
593  }
594  size_t sub_len = s - start;
595  if (args[ARG_keepends].u_bool) {
596  sub_len += match;
597  }
598  mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
599  s += match;
600  }
601 
602  return res;
603 }
604 MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
605 #endif
606 
607 STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
608  if (n_args < 3) {
609  // If we don't have split limit, it doesn't matter from which side
610  // we split.
611  return mp_obj_str_split(n_args, args);
612  }
613  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
614  mp_obj_t sep = args[1];
615  GET_STR_DATA_LEN(args[0], s, len);
616 
617  mp_int_t splits = mp_obj_get_int(args[2]);
618  if (splits < 0) {
619  // Negative limit means no limit, so delegate to split().
620  return mp_obj_str_split(n_args, args);
621  }
622 
623  mp_int_t org_splits = splits;
624  // Preallocate list to the max expected # of elements, as we
625  // will fill it from the end.
626  mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
627  mp_int_t idx = splits;
628 
629  if (sep == mp_const_none) {
630  mp_raise_NotImplementedError("rsplit(None,n)");
631  } else {
632  size_t sep_len;
633  const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
634 
635  if (sep_len == 0) {
636  mp_raise_ValueError("empty separator");
637  }
638 
639  const byte *beg = s;
640  const byte *last = s + len;
641  for (;;) {
642  s = last - sep_len;
643  for (;;) {
644  if (splits == 0 || s < beg) {
645  break;
646  } else if (memcmp(s, sep_str, sep_len) == 0) {
647  break;
648  }
649  s--;
650  }
651  if (s < beg || splits == 0) {
652  res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
653  break;
654  }
655  res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
656  last = s;
657  if (splits > 0) {
658  splits--;
659  }
660  }
661  if (idx != 0) {
662  // We split less parts than split limit, now go cleanup surplus
663  size_t used = org_splits + 1 - idx;
664  memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
665  mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
666  res->len = used;
667  }
668  }
669 
670  return MP_OBJ_FROM_PTR(res);
671 }
672 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
673 
674 STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) {
675  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
677 
678  // check argument type
679  if (mp_obj_get_type(args[1]) != self_type) {
681  }
682 
683  GET_STR_DATA_LEN(args[0], haystack, haystack_len);
684  GET_STR_DATA_LEN(args[1], needle, needle_len);
685 
686  const byte *start = haystack;
687  const byte *end = haystack + haystack_len;
688  if (n_args >= 3 && args[2] != mp_const_none) {
689  start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
690  }
691  if (n_args >= 4 && args[3] != mp_const_none) {
692  end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
693  }
694 
695  const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
696  if (p == NULL) {
697  // not found
698  if (is_index) {
699  mp_raise_ValueError("substring not found");
700  } else {
701  return MP_OBJ_NEW_SMALL_INT(-1);
702  }
703  } else {
704  // found
705  #if MICROPY_PY_BUILTINS_STR_UNICODE
706  if (self_type == &mp_type_str) {
707  return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
708  }
709  #endif
710  return MP_OBJ_NEW_SMALL_INT(p - haystack);
711  }
712 }
713 
714 STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
715  return str_finder(n_args, args, 1, false);
716 }
717 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
718 
719 STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
720  return str_finder(n_args, args, -1, false);
721 }
722 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
723 
724 STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
725  return str_finder(n_args, args, 1, true);
726 }
727 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
728 
729 STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
730  return str_finder(n_args, args, -1, true);
731 }
732 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
733 
734 // TODO: (Much) more variety in args
735 STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
736  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
737  GET_STR_DATA_LEN(args[0], str, str_len);
738  size_t prefix_len;
739  const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
740  const byte *start = str;
741  if (n_args > 2) {
742  start = str_index_to_ptr(self_type, str, str_len, args[2], true);
743  }
744  if (prefix_len + (start - str) > str_len) {
745  return mp_const_false;
746  }
747  return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
748 }
749 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
750 
751 STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
752  GET_STR_DATA_LEN(args[0], str, str_len);
753  size_t suffix_len;
754  const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
755  if (n_args > 2) {
756  mp_raise_NotImplementedError("start/end indices");
757  }
758 
759  if (suffix_len > str_len) {
760  return mp_const_false;
761  }
762  return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
763 }
764 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
765 
766 enum { LSTRIP, RSTRIP, STRIP };
767 
768 STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
770  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
771 
772  const byte *chars_to_del;
773  uint chars_to_del_len;
774  static const byte whitespace[] = " \t\n\r\v\f";
775 
776  if (n_args == 1) {
777  chars_to_del = whitespace;
778  chars_to_del_len = sizeof(whitespace) - 1;
779  } else {
780  if (mp_obj_get_type(args[1]) != self_type) {
782  }
783  GET_STR_DATA_LEN(args[1], s, l);
784  chars_to_del = s;
785  chars_to_del_len = l;
786  }
787 
788  GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
789 
790  size_t first_good_char_pos = 0;
791  bool first_good_char_pos_set = false;
792  size_t last_good_char_pos = 0;
793  size_t i = 0;
794  int delta = 1;
795  if (type == RSTRIP) {
796  i = orig_str_len - 1;
797  delta = -1;
798  }
799  for (size_t len = orig_str_len; len > 0; len--) {
800  if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
801  if (!first_good_char_pos_set) {
802  first_good_char_pos_set = true;
803  first_good_char_pos = i;
804  if (type == LSTRIP) {
805  last_good_char_pos = orig_str_len - 1;
806  break;
807  } else if (type == RSTRIP) {
808  first_good_char_pos = 0;
809  last_good_char_pos = i;
810  break;
811  }
812  }
813  last_good_char_pos = i;
814  }
815  i += delta;
816  }
817 
818  if (!first_good_char_pos_set) {
819  // string is all whitespace, return ''
820  if (self_type == &mp_type_str) {
821  return MP_OBJ_NEW_QSTR(MP_QSTR_);
822  } else {
823  return mp_const_empty_bytes;
824  }
825  }
826 
827  assert(last_good_char_pos >= first_good_char_pos);
828  //+1 to accommodate the last character
829  size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
830  if (stripped_len == orig_str_len) {
831  // If nothing was stripped, don't bother to dup original string
832  // TODO: watch out for this case when we'll get to bytearray.strip()
833  assert(first_good_char_pos == 0);
834  return args[0];
835  }
836  return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
837 }
838 
839 STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
840  return str_uni_strip(STRIP, n_args, args);
841 }
842 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
843 
844 STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
845  return str_uni_strip(LSTRIP, n_args, args);
846 }
847 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
848 
849 STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
850  return str_uni_strip(RSTRIP, n_args, args);
851 }
852 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
853 
854 #if MICROPY_PY_BUILTINS_STR_CENTER
855 STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
856  GET_STR_DATA_LEN(str_in, str, str_len);
857  mp_uint_t width = mp_obj_get_int(width_in);
858  if (str_len >= width) {
859  return str_in;
860  }
861 
862  vstr_t vstr;
863  vstr_init_len(&vstr, width);
864  memset(vstr.buf, ' ', width);
865  int left = (width - str_len) / 2;
866  memcpy(vstr.buf + left, str, str_len);
867  return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
868 }
869 MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
870 #endif
871 
872 // Takes an int arg, but only parses unsigned numbers, and only changes
873 // *num if at least one digit was parsed.
874 STATIC const char *str_to_int(const char *str, const char *top, int *num) {
875  if (str < top && '0' <= *str && *str <= '9') {
876  *num = 0;
877  do {
878  *num = *num * 10 + (*str - '0');
879  str++;
880  }
881  while (str < top && '0' <= *str && *str <= '9');
882  }
883  return str;
884 }
885 
886 STATIC bool isalignment(char ch) {
887  return ch && strchr("<>=^", ch) != NULL;
888 }
889 
890 STATIC bool istype(char ch) {
891  return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
892 }
893 
895  return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
896 }
897 
899  return arg_looks_integer(arg)
900 #if MICROPY_PY_BUILTINS_FLOAT
901  || mp_obj_is_float(arg)
902 #endif
903  ;
904 }
905 
907 #if MICROPY_PY_BUILTINS_FLOAT
908  if (mp_obj_is_float(arg)) {
909  return mp_obj_new_int_from_float(mp_obj_float_get(arg));
910  }
911 #endif
912  return arg;
913 }
914 
915 #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
917  mp_raise_ValueError("bad format string");
918 }
919 #else
920 // define to nothing to improve coverage
921 #define terse_str_format_value_error()
922 #endif
923 
924 STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
925  vstr_t vstr;
926  mp_print_t print;
927  vstr_init_print(&vstr, 16, &print);
928 
929  for (; str < top; str++) {
930  if (*str == '}') {
931  str++;
932  if (str < top && *str == '}') {
933  vstr_add_byte(&vstr, '}');
934  continue;
935  }
938  } else {
939  mp_raise_ValueError("single '}' encountered in format string");
940  }
941  }
942  if (*str != '{') {
943  vstr_add_byte(&vstr, *str);
944  continue;
945  }
946 
947  str++;
948  if (str < top && *str == '{') {
949  vstr_add_byte(&vstr, '{');
950  continue;
951  }
952 
953  // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
954 
955  const char *field_name = NULL;
956  const char *field_name_top = NULL;
957  char conversion = '\0';
958  const char *format_spec = NULL;
959 
960  if (str < top && *str != '}' && *str != '!' && *str != ':') {
961  field_name = (const char *)str;
962  while (str < top && *str != '}' && *str != '!' && *str != ':') {
963  ++str;
964  }
965  field_name_top = (const char *)str;
966  }
967 
968  // conversion ::= "r" | "s"
969 
970  if (str < top && *str == '!') {
971  str++;
972  if (str < top && (*str == 'r' || *str == 's')) {
973  conversion = *str++;
974  } else {
978  mp_raise_ValueError("bad conversion specifier");
979  } else {
980  if (str >= top) {
982  "end of format while looking for conversion specifier");
983  } else {
985  "unknown conversion specifier %c", *str));
986  }
987  }
988  }
989  }
990 
991  if (str < top && *str == ':') {
992  str++;
993  // {:} is the same as {}, which is the same as {!s}
994  // This makes a difference when passing in a True or False
995  // '{}'.format(True) returns 'True'
996  // '{:d}'.format(True) returns '1'
997  // So we treat {:} as {} and this later gets treated to be {!s}
998  if (*str != '}') {
999  format_spec = str;
1000  for (int nest = 1; str < top;) {
1001  if (*str == '{') {
1002  ++nest;
1003  } else if (*str == '}') {
1004  if (--nest == 0) {
1005  break;
1006  }
1007  }
1008  ++str;
1009  }
1010  }
1011  }
1012  if (str >= top) {
1015  } else {
1016  mp_raise_ValueError("unmatched '{' in format");
1017  }
1018  }
1019  if (*str != '}') {
1022  } else {
1023  mp_raise_ValueError("expected ':' after format specifier");
1024  }
1025  }
1026 
1027  mp_obj_t arg = mp_const_none;
1028 
1029  if (field_name) {
1030  int index = 0;
1031  if (MP_LIKELY(unichar_isdigit(*field_name))) {
1032  if (*arg_i > 0) {
1035  } else {
1037  "can't switch from automatic field numbering to manual field specification");
1038  }
1039  }
1040  field_name = str_to_int(field_name, field_name_top, &index);
1041  if ((uint)index >= n_args - 1) {
1042  mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
1043  }
1044  arg = args[index + 1];
1045  *arg_i = -1;
1046  } else {
1047  const char *lookup;
1048  for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
1049  mp_obj_t field_q = mp_obj_new_str(field_name, lookup - field_name, true/*?*/);
1050  field_name = lookup;
1051  mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
1052  if (key_elem == NULL) {
1054  }
1055  arg = key_elem->value;
1056  }
1057  if (field_name < field_name_top) {
1058  mp_raise_NotImplementedError("attributes not supported yet");
1059  }
1060  } else {
1061  if (*arg_i < 0) {
1064  } else {
1066  "can't switch from manual field specification to automatic field numbering");
1067  }
1068  }
1069  if ((uint)*arg_i >= n_args - 1) {
1070  mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
1071  }
1072  arg = args[(*arg_i) + 1];
1073  (*arg_i)++;
1074  }
1075  if (!format_spec && !conversion) {
1076  conversion = 's';
1077  }
1078  if (conversion) {
1079  mp_print_kind_t print_kind;
1080  if (conversion == 's') {
1081  print_kind = PRINT_STR;
1082  } else {
1083  assert(conversion == 'r');
1084  print_kind = PRINT_REPR;
1085  }
1086  vstr_t arg_vstr;
1087  mp_print_t arg_print;
1088  vstr_init_print(&arg_vstr, 16, &arg_print);
1089  mp_obj_print_helper(&arg_print, arg, print_kind);
1090  arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
1091  }
1092 
1093  char fill = '\0';
1094  char align = '\0';
1095  int width = -1;
1096  int precision = -1;
1097  char type = '\0';
1098  int flags = 0;
1099 
1100  if (format_spec) {
1101  // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1102  //
1103  // [[fill]align][sign][#][0][width][,][.precision][type]
1104  // fill ::= <any character>
1105  // align ::= "<" | ">" | "=" | "^"
1106  // sign ::= "+" | "-" | " "
1107  // width ::= integer
1108  // precision ::= integer
1109  // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1110 
1111  // recursively call the formatter to format any nested specifiers
1112  MP_STACK_CHECK();
1113  vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
1114  const char *s = vstr_null_terminated_str(&format_spec_vstr);
1115  const char *stop = s + format_spec_vstr.len;
1116  if (isalignment(*s)) {
1117  align = *s++;
1118  } else if (*s && isalignment(s[1])) {
1119  fill = *s++;
1120  align = *s++;
1121  }
1122  if (*s == '+' || *s == '-' || *s == ' ') {
1123  if (*s == '+') {
1124  flags |= PF_FLAG_SHOW_SIGN;
1125  } else if (*s == ' ') {
1126  flags |= PF_FLAG_SPACE_SIGN;
1127  }
1128  s++;
1129  }
1130  if (*s == '#') {
1131  flags |= PF_FLAG_SHOW_PREFIX;
1132  s++;
1133  }
1134  if (*s == '0') {
1135  if (!align) {
1136  align = '=';
1137  }
1138  if (!fill) {
1139  fill = '0';
1140  }
1141  }
1142  s = str_to_int(s, stop, &width);
1143  if (*s == ',') {
1144  flags |= PF_FLAG_SHOW_COMMA;
1145  s++;
1146  }
1147  if (*s == '.') {
1148  s++;
1149  s = str_to_int(s, stop, &precision);
1150  }
1151  if (istype(*s)) {
1152  type = *s++;
1153  }
1154  if (*s) {
1157  } else {
1158  mp_raise_ValueError("invalid format specifier");
1159  }
1160  }
1161  vstr_clear(&format_spec_vstr);
1162  }
1163  if (!align) {
1164  if (arg_looks_numeric(arg)) {
1165  align = '>';
1166  } else {
1167  align = '<';
1168  }
1169  }
1170  if (!fill) {
1171  fill = ' ';
1172  }
1173 
1174  if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
1175  if (type == 's') {
1178  } else {
1179  mp_raise_ValueError("sign not allowed in string format specifier");
1180  }
1181  }
1182  if (type == 'c') {
1185  } else {
1187  "sign not allowed with integer format specifier 'c'");
1188  }
1189  }
1190  }
1191 
1192  switch (align) {
1193  case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1194  case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1195  case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1196  }
1197 
1198  if (arg_looks_integer(arg)) {
1199  switch (type) {
1200  case 'b':
1201  mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
1202  continue;
1203 
1204  case 'c':
1205  {
1206  char ch = mp_obj_get_int(arg);
1207  mp_print_strn(&print, &ch, 1, flags, fill, width);
1208  continue;
1209  }
1210 
1211  case '\0': // No explicit format type implies 'd'
1212  case 'n': // I don't think we support locales in uPy so use 'd'
1213  case 'd':
1214  mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
1215  continue;
1216 
1217  case 'o':
1218  if (flags & PF_FLAG_SHOW_PREFIX) {
1219  flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1220  }
1221 
1222  mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
1223  continue;
1224 
1225  case 'X':
1226  case 'x':
1227  mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
1228  continue;
1229 
1230  case 'e':
1231  case 'E':
1232  case 'f':
1233  case 'F':
1234  case 'g':
1235  case 'G':
1236  case '%':
1237  // The floating point formatters all work with anything that
1238  // looks like an integer
1239  break;
1240 
1241  default:
1244  } else {
1246  "unknown format code '%c' for object of type '%s'",
1247  type, mp_obj_get_type_str(arg)));
1248  }
1249  }
1250  }
1251 
1252  // NOTE: no else here. We need the e, f, g etc formats for integer
1253  // arguments (from above if) to take this if.
1254  if (arg_looks_numeric(arg)) {
1255  if (!type) {
1256 
1257  // Even though the docs say that an unspecified type is the same
1258  // as 'g', there is one subtle difference, when the exponent
1259  // is one less than the precision.
1260  //
1261  // '{:10.1}'.format(0.0) ==> '0e+00'
1262  // '{:10.1g}'.format(0.0) ==> '0'
1263  //
1264  // TODO: Figure out how to deal with this.
1265  //
1266  // A proper solution would involve adding a special flag
1267  // or something to format_float, and create a format_double
1268  // to deal with doubles. In order to fix this when using
1269  // sprintf, we'd need to use the e format and tweak the
1270  // returned result to strip trailing zeros like the g format
1271  // does.
1272  //
1273  // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1274  // but with 1.e2 you get 1e+02 and 1.00e+02
1275  //
1276  // Stripping the trailing 0's (like g) does would make the
1277  // e format give us the right format.
1278  //
1279  // CPython sources say:
1280  // Omitted type specifier. Behaves in the same way as repr(x)
1281  // and str(x) if no precision is given, else like 'g', but with
1282  // at least one digit after the decimal point. */
1283 
1284  type = 'g';
1285  }
1286  if (type == 'n') {
1287  type = 'g';
1288  }
1289 
1290  switch (type) {
1291 #if MICROPY_PY_BUILTINS_FLOAT
1292  case 'e':
1293  case 'E':
1294  case 'f':
1295  case 'F':
1296  case 'g':
1297  case 'G':
1298  mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
1299  break;
1300 
1301  case '%':
1302  flags |= PF_FLAG_ADD_PERCENT;
1303  #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1304  #define F100 100.0F
1305  #else
1306  #define F100 100.0
1307  #endif
1308  mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
1309  #undef F100
1310  break;
1311 #endif
1312 
1313  default:
1316  } else {
1318  "unknown format code '%c' for object of type 'float'",
1319  type, mp_obj_get_type_str(arg)));
1320  }
1321  }
1322  } else {
1323  // arg doesn't look like a number
1324 
1325  if (align == '=') {
1328  } else {
1330  "'=' alignment not allowed in string format specifier");
1331  }
1332  }
1333 
1334  switch (type) {
1335  case '\0': // no explicit format type implies 's'
1336  case 's': {
1337  size_t slen;
1338  const char *s = mp_obj_str_get_data(arg, &slen);
1339  if (precision < 0) {
1340  precision = slen;
1341  }
1342  if (slen > (size_t)precision) {
1343  slen = precision;
1344  }
1345  mp_print_strn(&print, s, slen, flags, fill, width);
1346  break;
1347  }
1348 
1349  default:
1352  } else {
1354  "unknown format code '%c' for object of type 'str'",
1355  type, mp_obj_get_type_str(arg)));
1356  }
1357  }
1358  }
1359  }
1360 
1361  return vstr;
1362 }
1363 
1364 mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
1366 
1367  GET_STR_DATA_LEN(args[0], str, len);
1368  int arg_i = 0;
1369  vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs);
1370  return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
1371 }
1372 MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
1373 
1374 STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) {
1376 
1377  GET_STR_DATA_LEN(pattern, str, len);
1378  const byte *start_str = str;
1379  bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
1380  size_t arg_i = 0;
1381  vstr_t vstr;
1382  mp_print_t print;
1383  vstr_init_print(&vstr, 16, &print);
1384 
1385  for (const byte *top = str + len; str < top; str++) {
1386  mp_obj_t arg = MP_OBJ_NULL;
1387  if (*str != '%') {
1388  vstr_add_byte(&vstr, *str);
1389  continue;
1390  }
1391  if (++str >= top) {
1392  goto incomplete_format;
1393  }
1394  if (*str == '%') {
1395  vstr_add_byte(&vstr, '%');
1396  continue;
1397  }
1398 
1399  // Dictionary value lookup
1400  if (*str == '(') {
1401  if (dict == MP_OBJ_NULL) {
1402  mp_raise_TypeError("format requires a dict");
1403  }
1404  arg_i = 1; // we used up the single dict argument
1405  const byte *key = ++str;
1406  while (*str != ')') {
1407  if (str >= top) {
1410  } else {
1411  mp_raise_ValueError("incomplete format key");
1412  }
1413  }
1414  ++str;
1415  }
1416  mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1417  arg = mp_obj_dict_get(dict, k_obj);
1418  str++;
1419  }
1420 
1421  int flags = 0;
1422  char fill = ' ';
1423  int alt = 0;
1424  while (str < top) {
1425  if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1426  else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1427  else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1428  else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
1429  else if (*str == '0') {
1430  flags |= PF_FLAG_PAD_AFTER_SIGN;
1431  fill = '0';
1432  } else break;
1433  str++;
1434  }
1435  // parse width, if it exists
1436  int width = 0;
1437  if (str < top) {
1438  if (*str == '*') {
1439  if (arg_i >= n_args) {
1440  goto not_enough_args;
1441  }
1442  width = mp_obj_get_int(args[arg_i++]);
1443  str++;
1444  } else {
1445  str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
1446  }
1447  }
1448  int prec = -1;
1449  if (str < top && *str == '.') {
1450  if (++str < top) {
1451  if (*str == '*') {
1452  if (arg_i >= n_args) {
1453  goto not_enough_args;
1454  }
1455  prec = mp_obj_get_int(args[arg_i++]);
1456  str++;
1457  } else {
1458  prec = 0;
1459  str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
1460  }
1461  }
1462  }
1463 
1464  if (str >= top) {
1465 incomplete_format:
1468  } else {
1469  mp_raise_ValueError("incomplete format");
1470  }
1471  }
1472 
1473  // Tuple value lookup
1474  if (arg == MP_OBJ_NULL) {
1475  if (arg_i >= n_args) {
1476 not_enough_args:
1477  mp_raise_TypeError("not enough arguments for format string");
1478  }
1479  arg = args[arg_i++];
1480  }
1481  switch (*str) {
1482  case 'c':
1483  if (MP_OBJ_IS_STR(arg)) {
1484  size_t slen;
1485  const char *s = mp_obj_str_get_data(arg, &slen);
1486  if (slen != 1) {
1487  mp_raise_TypeError("%%c requires int or char");
1488  }
1489  mp_print_strn(&print, s, 1, flags, ' ', width);
1490  } else if (arg_looks_integer(arg)) {
1491  char ch = mp_obj_get_int(arg);
1492  mp_print_strn(&print, &ch, 1, flags, ' ', width);
1493  } else {
1494  mp_raise_TypeError("integer required");
1495  }
1496  break;
1497 
1498  case 'd':
1499  case 'i':
1500  case 'u':
1501  mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
1502  break;
1503 
1504 #if MICROPY_PY_BUILTINS_FLOAT
1505  case 'e':
1506  case 'E':
1507  case 'f':
1508  case 'F':
1509  case 'g':
1510  case 'G':
1511  mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1512  break;
1513 #endif
1514 
1515  case 'o':
1516  if (alt) {
1518  }
1519  mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
1520  break;
1521 
1522  case 'r':
1523  case 's':
1524  {
1525  vstr_t arg_vstr;
1526  mp_print_t arg_print;
1527  vstr_init_print(&arg_vstr, 16, &arg_print);
1528  mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1529  if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1530  // If we have something like b"%s" % b"1", bytes arg should be
1531  // printed undecorated.
1532  print_kind = PRINT_RAW;
1533  }
1534  mp_obj_print_helper(&arg_print, arg, print_kind);
1535  uint vlen = arg_vstr.len;
1536  if (prec < 0) {
1537  prec = vlen;
1538  }
1539  if (vlen > (uint)prec) {
1540  vlen = prec;
1541  }
1542  mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
1543  vstr_clear(&arg_vstr);
1544  break;
1545  }
1546 
1547  case 'X':
1548  case 'x':
1549  mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
1550  break;
1551 
1552  default:
1555  } else {
1557  "unsupported format character '%c' (0x%x) at index %d",
1558  *str, *str, str - start_str));
1559  }
1560  }
1561  }
1562 
1563  if (arg_i != n_args) {
1564  mp_raise_TypeError("not all arguments converted during string formatting");
1565  }
1566 
1567  return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
1568 }
1569 
1570 // The implementation is optimized, returning the original string if there's
1571 // nothing to replace.
1572 STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
1574 
1575  mp_int_t max_rep = -1;
1576  if (n_args == 4) {
1577  max_rep = mp_obj_get_int(args[3]);
1578  if (max_rep == 0) {
1579  return args[0];
1580  } else if (max_rep < 0) {
1581  max_rep = -1;
1582  }
1583  }
1584 
1585  // if max_rep is still -1 by this point we will need to do all possible replacements
1586 
1587  // check argument types
1588 
1589  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1590 
1591  if (mp_obj_get_type(args[1]) != self_type) {
1593  }
1594 
1595  if (mp_obj_get_type(args[2]) != self_type) {
1597  }
1598 
1599  // extract string data
1600 
1601  GET_STR_DATA_LEN(args[0], str, str_len);
1602  GET_STR_DATA_LEN(args[1], old, old_len);
1603  GET_STR_DATA_LEN(args[2], new, new_len);
1604 
1605  // old won't exist in str if it's longer, so nothing to replace
1606  if (old_len > str_len) {
1607  return args[0];
1608  }
1609 
1610  // data for the replaced string
1611  byte *data = NULL;
1612  vstr_t vstr;
1613 
1614  // do 2 passes over the string:
1615  // first pass computes the required length of the replaced string
1616  // second pass does the replacements
1617  for (;;) {
1618  size_t replaced_str_index = 0;
1619  size_t num_replacements_done = 0;
1620  const byte *old_occurrence;
1621  const byte *offset_ptr = str;
1622  size_t str_len_remain = str_len;
1623  if (old_len == 0) {
1624  // if old_str is empty, copy new_str to start of replaced string
1625  // copy the replacement string
1626  if (data != NULL) {
1627  memcpy(data, new, new_len);
1628  }
1629  replaced_str_index += new_len;
1630  num_replacements_done++;
1631  }
1632  while (num_replacements_done != (size_t)max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1633  if (old_len == 0) {
1634  old_occurrence += 1;
1635  }
1636  // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1637  if (data != NULL) {
1638  memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1639  }
1640  replaced_str_index += old_occurrence - offset_ptr;
1641  // copy the replacement string
1642  if (data != NULL) {
1643  memcpy(data + replaced_str_index, new, new_len);
1644  }
1645  replaced_str_index += new_len;
1646  offset_ptr = old_occurrence + old_len;
1647  str_len_remain = str + str_len - offset_ptr;
1648  num_replacements_done++;
1649  }
1650 
1651  // copy from just after end of last occurrence of to-be-replaced string to end of old string
1652  if (data != NULL) {
1653  memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
1654  }
1655  replaced_str_index += str_len_remain;
1656 
1657  if (data == NULL) {
1658  // first pass
1659  if (num_replacements_done == 0) {
1660  // no substr found, return original string
1661  return args[0];
1662  } else {
1663  // substr found, allocate new string
1664  vstr_init_len(&vstr, replaced_str_index);
1665  data = (byte*)vstr.buf;
1666  assert(data != NULL);
1667  }
1668  } else {
1669  // second pass, we are done
1670  break;
1671  }
1672  }
1673 
1674  return mp_obj_new_str_from_vstr(self_type, &vstr);
1675 }
1676 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1677 
1678 STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
1679  const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1681 
1682  // check argument type
1683  if (mp_obj_get_type(args[1]) != self_type) {
1685  }
1686 
1687  GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1688  GET_STR_DATA_LEN(args[1], needle, needle_len);
1689 
1690  const byte *start = haystack;
1691  const byte *end = haystack + haystack_len;
1692  if (n_args >= 3 && args[2] != mp_const_none) {
1693  start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
1694  }
1695  if (n_args >= 4 && args[3] != mp_const_none) {
1696  end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
1697  }
1698 
1699  // if needle_len is zero then we count each gap between characters as an occurrence
1700  if (needle_len == 0) {
1701  return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
1702  }
1703 
1704  // count the occurrences
1705  mp_int_t num_occurrences = 0;
1706  for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1707  if (memcmp(haystack_ptr, needle, needle_len) == 0) {
1708  num_occurrences++;
1709  haystack_ptr += needle_len;
1710  } else {
1711  haystack_ptr = utf8_next_char(haystack_ptr);
1712  }
1713  }
1714 
1715  return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1716 }
1717 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1718 
1719 #if MICROPY_PY_BUILTINS_STR_PARTITION
1720 STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
1722  mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1723  if (self_type != mp_obj_get_type(arg)) {
1725  }
1726 
1727  GET_STR_DATA_LEN(self_in, str, str_len);
1728  GET_STR_DATA_LEN(arg, sep, sep_len);
1729 
1730  if (sep_len == 0) {
1731  mp_raise_ValueError("empty separator");
1732  }
1733 
1734  mp_obj_t result[3];
1735  if (self_type == &mp_type_str) {
1736  result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1737  result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1738  result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1739  } else {
1740  result[0] = mp_const_empty_bytes;
1741  result[1] = mp_const_empty_bytes;
1742  result[2] = mp_const_empty_bytes;
1743  }
1744 
1745  if (direction > 0) {
1746  result[0] = self_in;
1747  } else {
1748  result[2] = self_in;
1749  }
1750 
1751  const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1752  if (position_ptr != NULL) {
1753  size_t position = position_ptr - str;
1754  result[0] = mp_obj_new_str_of_type(self_type, str, position);
1755  result[1] = arg;
1756  result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
1757  }
1758 
1759  return mp_obj_new_tuple(3, result);
1760 }
1761 
1762 STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1763  return str_partitioner(self_in, arg, 1);
1764 }
1765 MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1766 
1767 STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1768  return str_partitioner(self_in, arg, -1);
1769 }
1770 MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1771 #endif
1772 
1773 // Supposedly not too critical operations, so optimize for code size
1775  GET_STR_DATA_LEN(self_in, self_data, self_len);
1776  vstr_t vstr;
1777  vstr_init_len(&vstr, self_len);
1778  byte *data = (byte*)vstr.buf;
1779  for (size_t i = 0; i < self_len; i++) {
1780  *data++ = op(*self_data++);
1781  }
1782  return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
1783 }
1784 
1786  return str_caseconv(unichar_tolower, self_in);
1787 }
1788 MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1789 
1791  return str_caseconv(unichar_toupper, self_in);
1792 }
1793 MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1794 
1796  GET_STR_DATA_LEN(self_in, self_data, self_len);
1797 
1798  if (self_len == 0) {
1799  return mp_const_false; // default to False for empty str
1800  }
1801 
1802  if (f != unichar_isupper && f != unichar_islower) {
1803  for (size_t i = 0; i < self_len; i++) {
1804  if (!f(*self_data++)) {
1805  return mp_const_false;
1806  }
1807  }
1808  } else {
1809  bool contains_alpha = false;
1810 
1811  for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
1812  if (unichar_isalpha(*self_data++)) {
1813  contains_alpha = true;
1814  if (!f(*(self_data - 1))) { // -1 because we already incremented above
1815  return mp_const_false;
1816  }
1817  }
1818  }
1819 
1820  if (!contains_alpha) {
1821  return mp_const_false;
1822  }
1823  }
1824 
1825  return mp_const_true;
1826 }
1827 
1829  return str_uni_istype(unichar_isspace, self_in);
1830 }
1831 MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1832 
1834  return str_uni_istype(unichar_isalpha, self_in);
1835 }
1836 MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1837 
1839  return str_uni_istype(unichar_isdigit, self_in);
1840 }
1841 MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1842 
1844  return str_uni_istype(unichar_isupper, self_in);
1845 }
1846 MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1847 
1849  return str_uni_istype(unichar_islower, self_in);
1850 }
1851 MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
1852 
1853 #if MICROPY_CPYTHON_COMPAT
1854 // These methods are superfluous in the presence of str() and bytes()
1855 // constructors.
1856 // TODO: should accept kwargs too
1857 STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
1858  mp_obj_t new_args[2];
1859  if (n_args == 1) {
1860  new_args[0] = args[0];
1861  new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1862  args = new_args;
1863  n_args++;
1864  }
1865  return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
1866 }
1867 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1868 
1869 // TODO: should accept kwargs too
1870 STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
1871  mp_obj_t new_args[2];
1872  if (n_args == 1) {
1873  new_args[0] = args[0];
1874  new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1875  args = new_args;
1876  n_args++;
1877  }
1878  return bytes_make_new(NULL, n_args, 0, args);
1879 }
1880 MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1881 #endif
1882 
1884  if (flags == MP_BUFFER_READ) {
1885  GET_STR_DATA_LEN(self_in, str_data, str_len);
1886  bufinfo->buf = (void*)str_data;
1887  bufinfo->len = str_len;
1888  bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
1889  return 0;
1890  } else {
1891  // can't write to a string
1892  bufinfo->buf = NULL;
1893  bufinfo->len = 0;
1894  bufinfo->typecode = -1;
1895  return 1;
1896  }
1897 }
1898 
1900 #if MICROPY_CPYTHON_COMPAT
1901  { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
1902  #if !MICROPY_PY_BUILTINS_STR_UNICODE
1903  // If we have separate unicode type, then here we have methods only
1904  // for bytes type, and it should not have encode() methods. Otherwise,
1905  // we have non-compliant-but-practical bytestring type, which shares
1906  // method table with bytes, so they both have encode() and decode()
1907  // methods (which should do type checking at runtime).
1908  { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
1909  #endif
1910 #endif
1911  { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1912  { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1913  { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1914  { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1915  { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1916  { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
1917  #if MICROPY_PY_BUILTINS_STR_SPLITLINES
1918  { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
1919  #endif
1920  { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1921  { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1922  { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1923  { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1924  { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1925  { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1926  { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1927  { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1928  { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
1929  #if MICROPY_PY_BUILTINS_STR_PARTITION
1930  { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1931  { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
1932  #endif
1933  #if MICROPY_PY_BUILTINS_STR_CENTER
1934  { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
1935  #endif
1936  { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1937  { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1938  { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1939  { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1940  { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1941  { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1942  { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
1943 };
1944 
1946 
1947 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1949 
1951  { &mp_type_type },
1952  .name = MP_QSTR_str,
1953  .print = str_print,
1954  .make_new = mp_obj_str_make_new,
1955  .binary_op = mp_obj_str_binary_op,
1956  .subscr = bytes_subscr,
1957  .getiter = mp_obj_new_str_iterator,
1958  .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
1959  .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
1960 };
1961 #endif
1962 
1963 // Reuses most of methods from str
1965  { &mp_type_type },
1966  .name = MP_QSTR_bytes,
1967  .print = str_print,
1968  .make_new = bytes_make_new,
1969  .binary_op = mp_obj_str_binary_op,
1970  .subscr = bytes_subscr,
1971  .getiter = mp_obj_new_bytes_iterator,
1972  .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
1973  .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
1974 };
1975 
1976 // The zero-length bytes object, with data that includes a null-terminating byte
1978 
1979 // Create a str/bytes object using the given data. New memory is allocated and
1980 // the data is copied across.
1981 mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
1983  o->base.type = type;
1984  o->len = len;
1985  if (data) {
1986  o->hash = qstr_compute_hash(data, len);
1987  byte *p = m_new(byte, len + 1);
1988  o->data = p;
1989  memcpy(p, data, len * sizeof(byte));
1990  p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1991  }
1992  return MP_OBJ_FROM_PTR(o);
1993 }
1994 
1995 // Create a str/bytes object from the given vstr. The vstr buffer is resized to
1996 // the exact length required and then reused for the str/bytes object. The vstr
1997 // is cleared and can safely be passed to vstr_free if it was heap allocated.
1999  // if not a bytes object, look if a qstr with this data already exists
2000  if (type == &mp_type_str) {
2001  qstr q = qstr_find_strn(vstr->buf, vstr->len);
2002  if (q != MP_QSTR_NULL) {
2003  vstr_clear(vstr);
2004  vstr->alloc = 0;
2005  return MP_OBJ_NEW_QSTR(q);
2006  }
2007  }
2008 
2009  // make a new str/bytes object
2011  o->base.type = type;
2012  o->len = vstr->len;
2013  o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
2014  if (vstr->len + 1 == vstr->alloc) {
2015  o->data = (byte*)vstr->buf;
2016  } else {
2017  o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
2018  }
2019  ((byte*)o->data)[o->len] = '\0'; // add null byte
2020  vstr->buf = NULL;
2021  vstr->alloc = 0;
2022  return MP_OBJ_FROM_PTR(o);
2023 }
2024 
2025 mp_obj_t mp_obj_new_str(const char* data, size_t len, bool make_qstr_if_not_already) {
2026  if (make_qstr_if_not_already) {
2027  // use existing, or make a new qstr
2028  return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
2029  } else {
2030  qstr q = qstr_find_strn(data, len);
2031  if (q != MP_QSTR_NULL) {
2032  // qstr with this data already exists
2033  return MP_OBJ_NEW_QSTR(q);
2034  } else {
2035  // no existing qstr, don't make one
2036  return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
2037  }
2038  }
2039 }
2040 
2042  GET_STR_DATA_LEN(str, data, len);
2043  return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
2044 }
2045 
2046 mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
2047  return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
2048 }
2049 
2051  if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
2052  return s1 == s2;
2053  } else {
2054  GET_STR_HASH(s1, h1);
2055  GET_STR_HASH(s2, h2);
2056  // If any of hashes is 0, it means it's not valid
2057  if (h1 != 0 && h2 != 0 && h1 != h2) {
2058  return false;
2059  }
2060  GET_STR_DATA_LEN(s1, d1, l1);
2061  GET_STR_DATA_LEN(s2, d2, l2);
2062  if (l1 != l2) {
2063  return false;
2064  }
2065  return memcmp(d1, d2, l1) == 0;
2066  }
2067 }
2068 
2071  mp_raise_TypeError("can't convert to str implicitly");
2072  } else {
2073  const qstr src_name = mp_obj_get_type(self_in)->name;
2075  "can't convert '%q' object to %q implicitly",
2076  src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str));
2077  }
2078 }
2079 
2080 // use this if you will anyway convert the string to a qstr
2081 // will be more efficient for the case where it's already a qstr
2083  if (MP_OBJ_IS_QSTR(self_in)) {
2084  return MP_OBJ_QSTR_VALUE(self_in);
2085  } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
2086  mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
2087  return qstr_from_strn((char*)self->data, self->len);
2088  } else {
2089  bad_implicit_conversion(self_in);
2090  }
2091 }
2092 
2093 // only use this function if you need the str data to be zero terminated
2094 // at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2095 const char *mp_obj_str_get_str(mp_obj_t self_in) {
2096  if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
2097  GET_STR_DATA_LEN(self_in, s, l);
2098  (void)l; // len unused
2099  return (const char*)s;
2100  } else {
2101  bad_implicit_conversion(self_in);
2102  }
2103 }
2104 
2105 const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
2106  if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
2107  GET_STR_DATA_LEN(self_in, s, l);
2108  *len = l;
2109  return (const char*)s;
2110  } else {
2111  bad_implicit_conversion(self_in);
2112  }
2113 }
2114 
2115 #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
2116 const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
2117  if (MP_OBJ_IS_QSTR(self_in)) {
2118  return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2119  } else {
2120  *len = ((mp_obj_str_t*)self_in)->len;
2121  return ((mp_obj_str_t*)self_in)->data;
2122  }
2123 }
2124 #endif
2125 
2126 /******************************************************************************/
2127 /* str iterator */
2128 
2129 typedef struct _mp_obj_str8_it_t {
2133  size_t cur;
2135 
2136 #if !MICROPY_PY_BUILTINS_STR_UNICODE
2138  mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
2139  GET_STR_DATA_LEN(self->str, str, len);
2140  if (self->cur < len) {
2141  mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
2142  self->cur += 1;
2143  return o_out;
2144  } else {
2145  return MP_OBJ_STOP_ITERATION;
2146  }
2147 }
2148 
2150  assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2151  mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
2152  o->base.type = &mp_type_polymorph_iter;
2154  o->str = str;
2155  o->cur = 0;
2156  return MP_OBJ_FROM_PTR(o);
2157 }
2158 #endif
2159 
2161  mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
2162  GET_STR_DATA_LEN(self->str, str, len);
2163  if (self->cur < len) {
2164  mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
2165  self->cur += 1;
2166  return o_out;
2167  } else {
2168  return MP_OBJ_STOP_ITERATION;
2169  }
2170 }
2171 
2173  assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2174  mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
2175  o->base.type = &mp_type_polymorph_iter;
2177  o->str = str;
2178  o->cur = 0;
2179  return MP_OBJ_FROM_PTR(o);
2180 }
STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:849
bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2)
Definition: objstr.c:2050
struct _mp_obj_str8_it_t mp_obj_str8_it_t
intptr_t mp_int_t
Definition: mpconfigport.h:73
qstr qstr_from_strn(const char *str, size_t len)
Definition: qstr.c:187
mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in)
Definition: objstr.c:291
uintptr_t mp_uint_t
Definition: mpconfigport.h:74
#define mp_seq_clear(start, len, alloc_len, item_sz)
Definition: obj.h:856
#define PF_FLAG_SHOW_COMMA
Definition: mpprint.h:36
NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, const char *msg)
Definition: runtime.c:1448
Definition: misc.h:142
#define MP_BUFFER_READ
Definition: obj.h:454
void * memset(void *b, int c, size_t len)
Definition: memset.c:3
mp_obj_t mp_obj_new_str(const char *data, size_t len, bool make_qstr_if_not_already)
Definition: objstr.c:2025
mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items)
Definition: objtuple.c:235
STATIC mp_obj_t str_lower(mp_obj_t self_in)
Definition: objstr.c:1785
mp_uint_t stop
Definition: obj.h:840
STATIC mp_obj_t str_upper(mp_obj_t self_in)
Definition: objstr.c:1790
#define assert(e)
Definition: assert.h:9
#define MICROPY_ERROR_REPORTING_TERSE
Definition: mpconfig.h:521
#define mp_const_none
Definition: obj.h:614
STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:735
NORETURN void mp_raise_NotImplementedError(const char *msg)
Definition: runtime.c:1468
STATIC mp_obj_t str_isspace(mp_obj_t self_in)
Definition: objstr.c:1828
const char * mp_obj_str_get_data(mp_obj_t self_in, size_t *len)
Definition: objstr.c:2105
bool unichar_isalpha(unichar c)
Definition: unicode.c:132
def data
Definition: i18n.py:176
NORETURN void mp_arg_error_unimpl_kw(void)
mp_make_new_fun_t make_new
Definition: obj.h:484
const mp_obj_type_t mp_type_TypeError
mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:484
STATIC mp_obj_t str_it_iternext(mp_obj_t self_in)
Definition: objstr.c:2137
STATIC bool istype(char ch)
Definition: objstr.c:890
STATIC mp_obj_t str_isdigit(mp_obj_t self_in)
Definition: objstr.c:1838
size_t len
Definition: objlist.h:34
#define MP_OBJ_IS_TYPE(o, t)
Definition: obj.h:254
size_t len
Definition: objstr.h:35
mp_obj_t mp_obj_new_exception_msg_varg(const mp_obj_type_t *exc_type, const char *fmt,...)
Definition: objexcept.c:380
void vstr_init_len(vstr_t *vstr, size_t len)
Definition: vstr.c:52
char * buf
Definition: misc.h:145
MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format)
#define MP_OBJ_QSTR_VALUE(o)
Definition: obj.h:91
bool mp_get_buffer(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flags)
Definition: obj.c:512
mp_obj_t mp_obj_new_bytes(const byte *data, size_t len)
Definition: objstr.c:2046
STATIC mp_obj_t str_uni_istype(bool(*f)(unichar), mp_obj_t self_in)
Definition: objstr.c:1795
bool mp_seq_cmp_bytes(mp_uint_t op, const byte *data1, size_t len1, const byte *data2, size_t len2)
Definition: sequence.c:150
STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value)
Definition: objstr.c:407
STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:1572
#define MP_OBJ_SENTINEL
Definition: obj.h:75
mp_obj_type_t * mp_obj_get_type(mp_const_obj_t o_in)
Definition: obj.c:40
void vstr_init(vstr_t *vstr, size_t alloc)
Definition: vstr.c:40
int mp_print_str(const mp_print_t *print, const char *str)
Definition: mpprint.c:53
#define MP_ROM_QSTR(q)
Definition: obj.h:241
mp_obj_t mp_obj_str_intern(mp_obj_t str)
Definition: objstr.c:2041
#define MP_OBJ_FROM_PTR(p)
Definition: obj.h:233
const byte * str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len, mp_obj_t index, bool is_slice)
Definition: objstr.c:399
void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n_allowed, const mp_arg_t *allowed, mp_arg_val_t *out_vals)
Definition: argcheck.c:74
#define MP_OBJ_NEW_QSTR(qst)
Definition: obj.h:92
void mp_arg_check_num(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw)
Definition: argcheck.c:32
mp_fun_1_t iternext
Definition: objstr.c:2131
unichar unichar_tolower(unichar c)
Definition: unicode.c:162
const byte * mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len)
Definition: objstr.c:2116
STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:729
#define MP_ROM_PTR(p)
Definition: obj.h:242
#define mp_const_true
Definition: obj.h:616
void vstr_add_byte(vstr_t *vstr, byte v)
Definition: vstr.c:141
STATIC bool arg_looks_integer(mp_obj_t arg)
Definition: objstr.c:894
STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:714
#define MP_ARRAY_SIZE(a)
Definition: misc.h:106
mp_obj_t mp_obj_new_list(size_t n, mp_obj_t *items)
Definition: objlist.c:470
size_t len
Definition: obj.h:447
const mp_obj_type_t mp_type_str
Definition: objstr.c:1950
#define mp_const_empty_bytes
Definition: obj.h:617
STATIC mp_obj_t str_islower(mp_obj_t self_in)
Definition: objstr.c:1848
const byte * utf8_next_char(const byte *s)
Definition: unicode.c:89
size_t len
Definition: misc.h:144
STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in)
Definition: objstr.c:2160
STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg)
Definition: objstr.c:433
mp_int_t mp_obj_get_int(mp_const_obj_t arg)
Definition: obj.c:225
STATIC bool arg_looks_numeric(mp_obj_t arg)
Definition: objstr.c:898
bool unichar_isdigit(unichar c)
Definition: unicode.c:142
mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr)
Definition: objstr.c:1998
#define STATIC
Definition: mpconfig.h:1178
qstr qstr_find_strn(const char *str, size_t str_len)
Definition: qstr.c:166
#define MP_OBJ_SMALL_INT_VALUE(o)
Definition: obj.h:86
bool utf8_check(const byte *p, size_t len)
Definition: unicode.c:186
mp_obj_base_t base
Definition: objstr.c:2130
mp_obj_t(* mp_fun_1_t)(mp_obj_t)
Definition: obj.h:404
STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf)
Definition: objstr.c:2172
#define mp_obj_is_float(o)
Definition: obj.h:745
STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:719
mp_map_elem_t * mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind)
Definition: map.c:138
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split)
mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg)
Definition: objlist.c:234
void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items)
Definition: obj.c:346
size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool is_slice)
Definition: obj.c:376
#define MP_LIKELY(x)
Definition: mpconfig.h:1288
mp_uint_t utf8_ptr_to_index(const byte *s, const byte *ptr)
Definition: unicode.c:101
mp_obj_t mp_obj_len_maybe(mp_obj_t o_in)
Definition: obj.c:448
mp_print_kind_t
Definition: obj.h:412
#define MP_OBJ_NEW_SMALL_INT(small_int)
Definition: obj.h:87
#define MICROPY_ERROR_REPORTING
Definition: mpconfigport.h:32
STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:1678
STATIC mp_obj_t str_isupper(mp_obj_t self_in)
Definition: objstr.c:1843
STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict)
Definition: objstr.c:1374
const mp_obj_type_t mp_type_polymorph_iter
Definition: objpolyiter.c:48
bool unichar_isspace(unichar c)
Definition: unicode.c:128
STATIC mp_obj_t str_isalpha(mp_obj_t self_in)
Definition: objstr.c:1833
#define MICROPY_ERROR_REPORTING_NORMAL
Definition: mpconfig.h:523
STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index)
Definition: objstr.c:674
STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:607
MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower)
#define NULL
Definition: stddef.h:4
#define MP_OBJ_NULL
Definition: obj.h:73
mp_obj_t mp_obj_new_exception_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg)
Definition: objexcept.c:334
#define mp_check_self(pred)
Definition: runtime.h:161
mp_obj_base_t base
Definition: objstr.h:32
char * strchr(const char *s, int c)
Definition: strchr.c:3
mp_obj_t * items
Definition: objlist.h:35
#define PF_FLAG_SHOW_SIGN
Definition: mpprint.h:32
size_t alloc
Definition: objlist.h:33
const byte * data
Definition: objstr.h:36
mp_obj_t str
Definition: objstr.c:2132
void * memmove(void *dst, const void *src, size_t n)
Definition: memmove.c:3
bool unichar_islower(unichar c)
Definition: unicode.c:158
STATIC mp_obj_t str_caseconv(unichar(*op)(unichar), mp_obj_t self_in)
Definition: objstr.c:1774
STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
Definition: objstr.c:924
void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind)
Definition: obj.c:59
size_t qstr
Definition: qstr.h:48
#define GET_STR_LEN(str_obj_in, str_len)
Definition: objstr.h:48
STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:844
mp_binary_op_t
Definition: runtime0.h:67
Definition: objstr.c:766
mp_obj_t value
Definition: obj.h:343
void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items)
Definition: objtuple.c:250
const mp_obj_type_t mp_type_ValueError
void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes)
Definition: objstr.c:45
const byte * find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction)
Definition: objstr.c:263
void mp_seq_multiply(const void *items, size_t item_sz, size_t len, size_t times, void *dest)
Definition: sequence.c:38
args
Definition: i18n.py:175
qstr mp_obj_str_get_qstr(mp_obj_t self_in)
Definition: objstr.c:2082
#define NORETURN
Definition: mpconfig.h:1268
#define MP_OBJ_IS_INT(o)
Definition: obj.h:255
STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
Definition: objstr.c:110
mp_uint_t hash
Definition: objstr.h:33
STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table)
Definition: obj.h:417
mp_obj_t mp_obj_dict_get(mp_obj_t self_in, mp_obj_t index)
Definition: objdict.c:164
Definition: obj.h:356
unsigned char byte
Definition: misc.h:37
mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags)
Definition: objstr.c:1883
const mp_obj_type_t mp_type_UnicodeError
bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value)
Definition: obj.c:258
const mp_obj_type_t mp_type_type
Definition: objtype.c:969
const mp_obj_type_t mp_type_bool
Definition: obj.h:543
#define PF_FLAG_LEFT_ADJUST
Definition: mpprint.h:31
const byte * qstr_data(qstr q, size_t *len)
Definition: qstr.c:283
void start()
Definition: rt0.cpp:31
#define m_renew(type, ptr, old_num, new_num)
Definition: misc.h:75
STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in)
Definition: objstr.c:2069
const mp_obj_type_t mp_type_IndexError
NORETURN void mp_raise_ValueError(const char *msg)
Definition: runtime.c:1456
STATIC mp_obj_t arg_as_int(mp_obj_t arg)
Definition: objstr.c:906
void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len)
#define PF_FLAG_SPACE_SIGN
Definition: mpprint.h:33
const char * mp_obj_str_get_str(mp_obj_t self_in)
Definition: objstr.c:2095
void mp_get_buffer_raise(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flags)
Definition: obj.c:524
mp_uint_t qstr_compute_hash(const byte *data, size_t len)
Definition: qstr.c:84
Definition: objstr.c:766
char * vstr_null_terminated_str(vstr_t *vstr)
Definition: vstr.c:132
const mp_obj_type_t mp_type_slice
#define MP_OBJ_TO_PTR(o)
Definition: obj.h:228
STATIC const char * str_to_int(const char *str, const char *top, int *num)
Definition: objstr.c:874
Definition: obj.h:413
mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
Definition: objstr.c:133
const mp_obj_type_t mp_type_tuple
Definition: objtuple.c:220
const mp_obj_type_t mp_type_dict
Definition: objdict.c:552
STATIC const mp_rom_map_elem_t str8_locals_dict_table[]
Definition: objstr.c:1899
Definition: objstr.c:766
mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf)
Definition: runtime.c:1120
#define nlr_raise(val)
Definition: nlr.h:89
mp_uint_t start
Definition: obj.h:839
mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len)
Definition: objstr.c:1981
const char * mp_obj_get_type_str(mp_const_obj_t o_in)
Definition: obj.c:55
LIBA_BEGIN_DECLS int memcmp(const void *s1, const void *s2, size_t n)
Definition: memcmp.c:3
STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:751
#define MP_STACK_CHECK()
Definition: stackctrl.h:44
unichar unichar_toupper(unichar c)
Definition: unicode.c:169
STATIC NORETURN void terse_str_format_value_error(void)
Definition: objstr.c:916
#define PF_FLAG_ADD_PERCENT
Definition: mpprint.h:39
int mp_print_strn(const mp_print_t *print, const char *str, size_t len, int flags, char fill, int width)
Definition: mpprint.c:61
int typecode
Definition: obj.h:448
qstr name
Definition: obj.h:478
#define MP_OBJ_STOP_ITERATION
Definition: obj.h:74
#define PF_FLAG_SHOW_OCTAL_LETTER
Definition: mpprint.h:40
uint64_t mp_obj_t
Definition: obj.h:39
#define PF_FLAG_CENTER_ADJUST
Definition: mpprint.h:38
mp_obj_t mp_iternext(mp_obj_t o_in)
Definition: runtime.c:1186
#define PF_FLAG_PAD_AFTER_SIGN
Definition: mpprint.h:37
int mp_printf(const mp_print_t *print, const char *fmt,...)
Definition: mpprint.c:380
#define PF_FLAG_SHOW_PREFIX
Definition: mpprint.h:35
const mp_obj_type_t mp_type_bytes
Definition: objstr.c:1964
#define MP_OBJ_IS_STR(o)
Definition: obj.h:256
STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:724
int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char, int flags, char fill, int width, int prec)
Definition: mpprint.c:204
NORETURN void mp_raise_TypeError(const char *msg)
Definition: runtime.c:1460
#define MP_OBJ_IS_STR_OR_BYTES(o)
Definition: obj.h:257
STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf)
Definition: objstr.c:2149
#define m_new_obj(type)
Definition: misc.h:60
mp_uint_t unichar_charlen(const char *str, mp_uint_t len)
Definition: unicode.c:113
#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len)
Definition: objstr.h:55
MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join)
const mp_obj_type_t mp_type_list
Definition: objlist.c:444
uint unichar
Definition: misc.h:119
#define MICROPY_PY_BUILTINS_STR_UNICODE
Definition: mpconfig.h:698
void vstr_init_print(vstr_t *vstr, size_t alloc, struct _mp_print_t *print)
Definition: vstr.c:64
void vstr_clear(vstr_t *vstr)
Definition: vstr.c:70
const mp_obj_type_t mp_type_KeyError
STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args)
Definition: objstr.c:768
#define GET_STR_HASH(str_obj_in, str_hash)
Definition: objstr.h:43
size_t alloc
Definition: misc.h:143
void * memcpy(void *dst, const void *src, size_t n)
Definition: memcpy.c:3
void * buf
Definition: obj.h:446
STATIC bool isalignment(char ch)
Definition: objstr.c:886
bool unichar_isupper(unichar c)
Definition: unicode.c:154
mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
Definition: objstr.c:1364
#define m_new(type, num)
Definition: misc.h:57
STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args)
Definition: objstr.c:839
const mp_obj_str_t mp_const_empty_bytes_obj
Definition: objstr.c:1977
#define mp_const_false
Definition: obj.h:615
STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args)
Definition: objstr.c:184
unsigned int uint
Definition: misc.h:38