blob: 454d1cbcc5445d353baeaacbcd7184221eb96315 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
Alexander Steffen55f33242017-06-30 09:22:17 +02002 * This file is part of the MicroPython project, http://micropython.org/
Damien George04b91472014-05-03 23:27:38 +01003 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovsky8fea8332019-01-31 11:55:21 +03007 * Copyright (c) 2014-2018 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
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
Damiend99b0522013-12-21 18:17:45 +000028#include <string.h>
29#include <assert.h>
30
Damien George51dfcb42015-01-01 20:27:54 +000031#include "py/unicode.h"
32#include "py/objstr.h"
33#include "py/objlist.h"
Damien George51dfcb42015-01-01 20:27:54 +000034#include "py/runtime.h"
pohmeliee3a29de2016-01-29 12:09:10 +030035#include "py/stackctrl.h"
Damiend99b0522013-12-21 18:17:45 +000036
Paul Sokolovsky2da5d412018-08-15 15:17:41 +030037#if MICROPY_PY_BUILTINS_STR_OP_MODULO
Damien George90ab1912017-02-03 13:04:56 +110038STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky2da5d412018-08-15 15:17:41 +030039#endif
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020040
Damien Georgeae8d8672016-01-09 23:14:54 +000041STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
Paul Sokolovskye9085912014-04-30 05:35:18 +030042STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030043
xyb8cfc9f02014-01-05 18:47:51 +080044/******************************************************************************/
45/* str */
46
Damien Georgec0d95002017-02-16 16:26:48 +110047void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020048 // this escapes characters, but it will be very slow to print (calling print many times)
49 bool has_single_quote = false;
50 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100051 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020052 if (*s == '\'') {
53 has_single_quote = true;
54 } else if (*s == '"') {
55 has_double_quote = true;
56 }
57 }
58 int quote_char = '\'';
59 if (has_single_quote && !has_double_quote) {
60 quote_char = '"';
61 }
Damien George7f9d1d62015-04-09 23:56:15 +010062 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020063 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
64 if (*s == quote_char) {
Damien George7f9d1d62015-04-09 23:56:15 +010065 mp_printf(print, "\\%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020066 } else if (*s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010067 mp_print_str(print, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030068 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
69 // In strings, anything which is not ascii control character
70 // is printed as is, this includes characters in range 0x80-0xff
71 // (which can be non-Latin letters, etc.)
Damien George7f9d1d62015-04-09 23:56:15 +010072 mp_printf(print, "%c", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020073 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010074 mp_print_str(print, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010075 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010076 mp_print_str(print, "\\r");
Andrew Scheller12968fb2014-04-08 02:42:50 +010077 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +010078 mp_print_str(print, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020079 } else {
Damien George7f9d1d62015-04-09 23:56:15 +010080 mp_printf(print, "\\x%02x", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020081 }
82 }
Damien George7f9d1d62015-04-09 23:56:15 +010083 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020084}
85
Damien George612045f2014-09-17 22:56:34 +010086#if MICROPY_PY_UJSON
Damien George999cedb2015-11-27 17:01:44 +000087void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
Damien Georgecde0ca22014-09-25 17:35:56 +010088 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
89 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George7f9d1d62015-04-09 23:56:15 +010090 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +010091 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010092 if (*s == '"' || *s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010093 mp_printf(print, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010094 } else if (*s >= 32) {
95 // this will handle normal and utf-8 encoded chars
Damien George7f9d1d62015-04-09 23:56:15 +010096 mp_printf(print, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010097 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010098 mp_print_str(print, "\\n");
Damien George612045f2014-09-17 22:56:34 +010099 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +0100100 mp_print_str(print, "\\r");
Damien George612045f2014-09-17 22:56:34 +0100101 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +0100102 mp_print_str(print, "\\t");
Damien George612045f2014-09-17 22:56:34 +0100103 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100104 // this will handle control chars
Damien George7f9d1d62015-04-09 23:56:15 +0100105 mp_printf(print, "\\u%04x", *s);
Damien George612045f2014-09-17 22:56:34 +0100106 }
107 }
Damien George7f9d1d62015-04-09 23:56:15 +0100108 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +0100109}
110#endif
111
Damien George7f9d1d62015-04-09 23:56:15 +0100112STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +0000113 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100114 #if MICROPY_PY_UJSON
115 if (kind == PRINT_JSON) {
Damien George7f9d1d62015-04-09 23:56:15 +0100116 mp_str_print_json(print, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100117 return;
118 }
119 #endif
Damien Georgee2aa1172015-09-03 23:03:57 +0100120 #if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgeeee1e882019-01-30 18:49:52 +1100121 bool is_bytes = mp_obj_is_type(self_in, &mp_type_bytes);
Damien Georgee2aa1172015-09-03 23:03:57 +0100122 #else
123 bool is_bytes = true;
124 #endif
Paul Sokolovskyef63ab52015-12-20 16:44:36 +0200125 if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
Damien George7f9d1d62015-04-09 23:56:15 +0100126 mp_printf(print, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200127 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200128 if (is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100129 mp_print_str(print, "b");
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200130 }
Damien George7f9d1d62015-04-09 23:56:15 +0100131 mp_str_print_quoted(print, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200132 }
Damiend99b0522013-12-21 18:17:45 +0000133}
134
Damien George5b3f0b72016-01-03 15:55:55 +0000135mp_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) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300136#if MICROPY_CPYTHON_COMPAT
137 if (n_kw != 0) {
138 mp_arg_error_unimpl_kw();
139 }
140#endif
141
Damien George1e9a92f2014-11-06 17:36:16 +0000142 mp_arg_check_num(n_args, n_kw, 0, 3, false);
143
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200144 switch (n_args) {
145 case 0:
146 return MP_OBJ_NEW_QSTR(MP_QSTR_);
147
Damien George1e9a92f2014-11-06 17:36:16 +0000148 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000149 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100150 mp_print_t print;
151 vstr_init_print(&vstr, 16, &print);
152 mp_obj_print_helper(&print, args[0], PRINT_STR);
Damien George5b3f0b72016-01-03 15:55:55 +0000153 return mp_obj_new_str_from_vstr(type, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200154 }
155
Damien George1e9a92f2014-11-06 17:36:16 +0000156 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200157 // TODO: validate 2nd/3rd args
Damien Georgeeee1e882019-01-30 18:49:52 +1100158 if (mp_obj_is_type(args[0], &mp_type_bytes)) {
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200159 GET_STR_DATA_LEN(args[0], str_data, str_len);
160 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000161 if (str_hash == 0) {
162 str_hash = qstr_compute_hash(str_data, str_len);
163 }
tll68c28172017-06-24 08:38:32 +0800164 #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
165 if (!utf8_check(str_data, str_len)) {
166 mp_raise_msg(&mp_type_UnicodeError, NULL);
167 }
168 #endif
Damien George8d956c22017-11-16 14:02:28 +1100169
170 // Check if a qstr with this data already exists
171 qstr q = qstr_find_strn((const char*)str_data, str_len);
Josh Lloyd7d58a192019-09-25 17:53:30 +1200172 if (q != MP_QSTRnull) {
Damien George8d956c22017-11-16 14:02:28 +1100173 return MP_OBJ_NEW_QSTR(q);
174 }
175
Damien George1f1d5192017-11-16 13:53:04 +1100176 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len));
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200177 o->data = str_data;
178 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000179 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200180 } else {
181 mp_buffer_info_t bufinfo;
182 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
tll68c28172017-06-24 08:38:32 +0800183 #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
184 if (!utf8_check(bufinfo.buf, bufinfo.len)) {
185 mp_raise_msg(&mp_type_UnicodeError, NULL);
186 }
187 #endif
Damien George46017592017-11-16 13:17:51 +1100188 return mp_obj_new_str(bufinfo.buf, bufinfo.len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200189 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200190 }
191}
192
Damien George5b3f0b72016-01-03 15:55:55 +0000193STATIC 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) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +0000194 (void)type_in;
195
Damien George3a2171e2015-09-04 16:53:46 +0100196 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300197 if (n_kw != 0) {
198 mp_arg_error_unimpl_kw();
199 }
Damien George3a2171e2015-09-04 16:53:46 +0100200 #else
201 (void)n_kw;
202 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300203
Damien George42cec5c2015-09-04 16:51:55 +0100204 if (n_args == 0) {
205 return mp_const_empty_bytes;
206 }
207
Damien Georgeeee1e882019-01-30 18:49:52 +1100208 if (mp_obj_is_str(args[0])) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200209 if (n_args < 2 || n_args > 3) {
210 goto wrong_args;
211 }
212 GET_STR_DATA_LEN(args[0], str_data, str_len);
213 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000214 if (str_hash == 0) {
215 str_hash = qstr_compute_hash(str_data, str_len);
216 }
Damien George1f1d5192017-11-16 13:53:04 +1100217 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(&mp_type_bytes, NULL, str_len));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200218 o->data = str_data;
219 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000220 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200221 }
222
223 if (n_args > 1) {
224 goto wrong_args;
225 }
226
Damien Georgeeee1e882019-01-30 18:49:52 +1100227 if (mp_obj_is_small_int(args[0])) {
Damien George4e469082018-02-19 16:25:30 +1100228 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(args[0]);
229 if (len < 0) {
230 mp_raise_ValueError(NULL);
231 }
Damien George05005f62015-01-21 22:48:37 +0000232 vstr_t vstr;
233 vstr_init_len(&vstr, len);
234 memset(vstr.buf, 0, len);
235 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200236 }
237
Damien George32ef3a32014-12-04 15:46:14 +0000238 // check if argument has the buffer protocol
239 mp_buffer_info_t bufinfo;
240 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
Damien George1f1d5192017-11-16 13:53:04 +1100241 return mp_obj_new_bytes(bufinfo.buf, bufinfo.len);
Damien George32ef3a32014-12-04 15:46:14 +0000242 }
243
Damien George0b9ee862015-01-21 19:14:25 +0000244 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200245 // Try to create array of exact len if initializer len is known
246 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
247 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000248 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200249 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000250 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000251 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200252 }
253
Damien Georgeae8d8672016-01-09 23:14:54 +0000254 mp_obj_iter_buf_t iter_buf;
255 mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200256 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100257 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100258 mp_int_t val = mp_obj_get_int(item);
Paul Sokolovsky9a973972017-04-02 21:20:07 +0300259 #if MICROPY_FULL_CHECKS
Damien Georgeede0f3a2015-04-23 15:28:18 +0100260 if (val < 0 || val > 255) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300261 mp_raise_ValueError("bytes value out of range");
Damien Georgeede0f3a2015-04-23 15:28:18 +0100262 }
263 #endif
264 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200265 }
266
Damien George0b9ee862015-01-21 19:14:25 +0000267 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200268
269wrong_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300270 mp_raise_TypeError("wrong number of arguments");
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200271}
272
Damien George55baff42014-01-21 21:40:13 +0000273// like strstr but with specified length and allows \0 bytes
274// TODO replace with something more efficient/standard
Damien Georgec0d95002017-02-16 16:26:48 +1100275const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
Damien George55baff42014-01-21 21:40:13 +0000276 if (hlen >= nlen) {
Damien Georgec0d95002017-02-16 16:26:48 +1100277 size_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700278 if (direction > 0) {
279 str_index = 0;
280 str_index_end = hlen - nlen;
281 } else {
282 str_index = hlen - nlen;
283 str_index_end = 0;
284 }
285 for (;;) {
286 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
287 //found
288 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000289 }
xbe17a5a832014-03-23 23:31:58 -0700290 if (str_index == str_index_end) {
291 //not found
292 break;
Damien George55baff42014-01-21 21:40:13 +0000293 }
xbe17a5a832014-03-23 23:31:58 -0700294 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000295 }
296 }
297 return NULL;
298}
299
Damien Georgea75b02e2014-08-27 09:20:30 +0100300// Note: this function is used to check if an object is a str or bytes, which
301// works because both those types use it as their binary_op method. Revisit
Damien Georgeeee1e882019-01-30 18:49:52 +1100302// mp_obj_is_str_or_bytes if this fact changes.
Damien George58321dd2017-08-29 13:04:01 +1000303mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000304 // check for modulo
305 if (op == MP_BINARY_OP_MODULO) {
Paul Sokolovsky2da5d412018-08-15 15:17:41 +0300306 #if MICROPY_PY_BUILTINS_STR_OP_MODULO
Damien George7317e342017-02-03 12:13:44 +1100307 mp_obj_t *args = &rhs_in;
Damien George6213ad72017-03-25 19:35:08 +1100308 size_t n_args = 1;
Damien Georgea65c03c2014-11-05 16:30:34 +0000309 mp_obj_t dict = MP_OBJ_NULL;
Damien Georgeeee1e882019-01-30 18:49:52 +1100310 if (mp_obj_is_type(rhs_in, &mp_type_tuple)) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000311 // TODO: Support tuple subclasses?
312 mp_obj_tuple_get(rhs_in, &n_args, &args);
Damien Georgeeee1e882019-01-30 18:49:52 +1100313 } else if (mp_obj_is_type(rhs_in, &mp_type_dict)) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000314 dict = rhs_in;
Damien Georgea65c03c2014-11-05 16:30:34 +0000315 }
316 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky2da5d412018-08-15 15:17:41 +0300317 #else
318 return MP_OBJ_NULL;
319 #endif
Damien Georgea65c03c2014-11-05 16:30:34 +0000320 }
321
322 // from now on we need lhs type and data, so extract them
Damien Georgebfbd9442020-01-09 11:01:14 +1100323 const mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000324 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
325
326 // check for multiply
327 if (op == MP_BINARY_OP_MULTIPLY) {
328 mp_int_t n;
329 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
330 return MP_OBJ_NULL; // op not supported
331 }
332 if (n <= 0) {
333 if (lhs_type == &mp_type_str) {
334 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
335 } else {
336 return mp_const_empty_bytes;
337 }
338 }
Damien George05005f62015-01-21 22:48:37 +0000339 vstr_t vstr;
340 vstr_init_len(&vstr, lhs_len * n);
341 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
342 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000343 }
344
345 // From now on all operations allow:
346 // - str with str
347 // - bytes with bytes
348 // - bytes with bytearray
349 // - bytes with array.array
350 // To do this efficiently we use the buffer protocol to extract the raw
351 // data for the rhs, but only if the lhs is a bytes object.
352 //
353 // NOTE: CPython does not allow comparison between bytes ard array.array
354 // (even if the array is of type 'b'), even though it allows addition of
355 // such types. We are not compatible with this (we do allow comparison
356 // of bytes with anything that has the buffer protocol). It would be
357 // easy to "fix" this with a bit of extra logic below, but it costs code
358 // size and execution time so we don't.
359
360 const byte *rhs_data;
Damien Georgec0d95002017-02-16 16:26:48 +1100361 size_t rhs_len;
Damien Georgea65c03c2014-11-05 16:30:34 +0000362 if (lhs_type == mp_obj_get_type(rhs_in)) {
363 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
364 rhs_data = rhs_data_;
365 rhs_len = rhs_len_;
366 } else if (lhs_type == &mp_type_bytes) {
367 mp_buffer_info_t bufinfo;
368 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000369 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000370 }
371 rhs_data = bufinfo.buf;
372 rhs_len = bufinfo.len;
373 } else {
Damien George3d25d9c2017-08-09 21:25:48 +1000374 // LHS is str and RHS has an incompatible type
375 // (except if operation is EQUAL, but that's handled by mp_obj_equal)
376 bad_implicit_conversion(rhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000377 }
378
Damiend99b0522013-12-21 18:17:45 +0000379 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100380 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000381 case MP_BINARY_OP_INPLACE_ADD: {
Damien Georged279bcf2017-03-16 14:30:04 +1100382 if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
Paul Sokolovskye2e66322017-01-27 00:40:47 +0300383 return rhs_in;
384 }
385 if (rhs_len == 0) {
386 return lhs_in;
387 }
388
Damien George05005f62015-01-21 22:48:37 +0000389 vstr_t vstr;
390 vstr_init_len(&vstr, lhs_len + rhs_len);
391 memcpy(vstr.buf, lhs_data, lhs_len);
392 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
393 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200394 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200395
Damien George5e34a112017-11-24 13:04:24 +1100396 case MP_BINARY_OP_CONTAINS:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300397 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300398
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300399 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
400 case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
Damien Georged17926d2014-03-30 13:35:08 +0100401 case MP_BINARY_OP_LESS:
402 case MP_BINARY_OP_LESS_EQUAL:
403 case MP_BINARY_OP_MORE:
404 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300405 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000406
Damien George58321dd2017-08-29 13:04:01 +1000407 default:
408 return MP_OBJ_NULL; // op not supported
409 }
Damiend99b0522013-12-21 18:17:45 +0000410}
411
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300412#if !MICROPY_PY_BUILTINS_STR_UNICODE
413// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000414const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len,
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300415 mp_obj_t index, bool is_slice) {
Damien Georgec88cfe12017-03-23 16:17:40 +1100416 size_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300417 return self_data + index_val;
418}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300419#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300420
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300421// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
422STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Damien Georgebfbd9442020-01-09 11:01:14 +1100423 const mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100424 GET_STR_DATA_LEN(self_in, self_data, self_len);
425 if (value == MP_OBJ_SENTINEL) {
426 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100427#if MICROPY_PY_BUILTINS_SLICE
Damien Georgeeee1e882019-01-30 18:49:52 +1100428 if (mp_obj_is_type(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300429 mp_bound_slice_t slice;
430 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000431 mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100432 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100433 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100434 }
435#endif
Damien Georgec88cfe12017-03-23 16:17:40 +1100436 size_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100437 // If we have unicode enabled the type will always be bytes, so take the short cut.
438 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300439 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100440 } else {
Damien George46017592017-11-16 13:17:51 +1100441 return mp_obj_new_str_via_qstr((char*)&self_data[index_val], 1);
Damien George729f7b42014-04-17 22:10:53 +0100442 }
443 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100444 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100445 }
446}
447
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200448STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Damien Georgeeee1e882019-01-30 18:49:52 +1100449 mp_check_self(mp_obj_is_str_or_bytes(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300450 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000451
Damien Georgefe8fb912014-01-02 16:36:09 +0000452 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000453 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000454
455 // process args
Damien George6213ad72017-03-25 19:35:08 +1100456 size_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000457 mp_obj_t *seq_items;
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100458
Damien Georgeeee1e882019-01-30 18:49:52 +1100459 if (!mp_obj_is_type(arg, &mp_type_list) && !mp_obj_is_type(arg, &mp_type_tuple)) {
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100460 // arg is not a list nor a tuple, try to convert it to a list
461 // TODO: Try to optimize?
462 arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
Damiend99b0522013-12-21 18:17:45 +0000463 }
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100464 mp_obj_get_array(arg, &seq_len, &seq_items);
Damien Georgefe8fb912014-01-02 16:36:09 +0000465
466 // count required length
Damien Georgec0d95002017-02-16 16:26:48 +1100467 size_t required_len = 0;
468 for (size_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300469 if (mp_obj_get_type(seq_items[i]) != self_type) {
Damien George21967992016-08-14 16:51:54 +1000470 mp_raise_TypeError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300471 "join expects a list of str/bytes objects consistent with self object");
Damiend99b0522013-12-21 18:17:45 +0000472 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000473 if (i > 0) {
474 required_len += sep_len;
475 }
Damien George5fa93b62014-01-22 14:35:10 +0000476 GET_STR_LEN(seq_items[i], l);
477 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000478 }
479
480 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000481 vstr_t vstr;
482 vstr_init_len(&vstr, required_len);
483 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +1100484 for (size_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000485 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000486 memcpy(data, sep_str, sep_len);
487 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000488 }
Damien George5fa93b62014-01-22 14:35:10 +0000489 GET_STR_DATA_LEN(seq_items[i], s, l);
490 memcpy(data, s, l);
491 data += l;
Damiend99b0522013-12-21 18:17:45 +0000492 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000493
494 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000495 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000496}
Damien George65417c52017-07-02 23:35:42 +1000497MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Damiend99b0522013-12-21 18:17:45 +0000498
Damien Georgecc80c4d2016-05-13 12:21:32 +0100499mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300500 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100501 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200502 mp_obj_t sep = mp_const_none;
503 if (n_args > 1) {
504 sep = args[1];
505 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100506 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200507 }
508 }
Damien Georgedeed0872014-04-06 11:11:15 +0100509
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200510 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000511 GET_STR_DATA_LEN(args[0], s, len);
512 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200513
Damien Georgedeed0872014-04-06 11:11:15 +0100514 if (sep == mp_const_none) {
515 // sep not given, so separate on whitespace
516
517 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300518 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100519 while (s < top && splits != 0) {
520 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300521 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100522 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100523 if (s >= top) {
524 break;
525 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300526 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100527 if (splits > 0) {
528 splits--;
529 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200530 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200531
Damien Georgedeed0872014-04-06 11:11:15 +0100532 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100533 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100534 }
535
536 } else {
537 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300538 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000539 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300540 }
Damien Georgedeed0872014-04-06 11:11:15 +0100541
Damien George6b341072017-03-25 19:48:18 +1100542 size_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100543 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
544
545 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300546 mp_raise_ValueError("empty separator");
Damien Georgedeed0872014-04-06 11:11:15 +0100547 }
548
549 for (;;) {
550 const byte *start = s;
551 for (;;) {
552 if (splits == 0 || s + sep_len > top) {
553 s = top;
554 break;
555 } else if (memcmp(s, sep_str, sep_len) == 0) {
556 break;
557 }
558 s++;
559 }
Damien Georgecc80c4d2016-05-13 12:21:32 +0100560 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100561 if (s >= top) {
562 break;
563 }
564 s += sep_len;
565 if (splits > 0) {
566 splits--;
567 }
568 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200569 }
570
571 return res;
572}
Damien George65417c52017-07-02 23:35:42 +1000573MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200574
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300575#if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien George4b72b3a2016-01-03 14:21:40 +0000576STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Damien Georgecc80c4d2016-05-13 12:21:32 +0100577 enum { ARG_keepends };
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300578 static const mp_arg_t allowed_args[] = {
579 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
580 };
581
582 // parse args
Damien Georgecc80c4d2016-05-13 12:21:32 +0100583 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
584 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300585
Damien Georgecc80c4d2016-05-13 12:21:32 +0100586 const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
587 mp_obj_t res = mp_obj_new_list(0, NULL);
588
589 GET_STR_DATA_LEN(pos_args[0], s, len);
590 const byte *top = s + len;
591
592 while (s < top) {
593 const byte *start = s;
594 size_t match = 0;
595 while (s < top) {
596 if (*s == '\n') {
597 match = 1;
598 break;
599 } else if (*s == '\r') {
600 if (s[1] == '\n') {
601 match = 2;
602 } else {
603 match = 1;
604 }
605 break;
606 }
607 s++;
608 }
609 size_t sub_len = s - start;
610 if (args[ARG_keepends].u_bool) {
611 sub_len += match;
612 }
613 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
614 s += match;
615 }
616
617 return res;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300618}
Damien George65417c52017-07-02 23:35:42 +1000619MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300620#endif
621
Damien George4b72b3a2016-01-03 14:21:40 +0000622STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300623 if (n_args < 3) {
624 // If we don't have split limit, it doesn't matter from which side
625 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200626 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300627 }
628 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
629 mp_obj_t sep = args[1];
630 GET_STR_DATA_LEN(args[0], s, len);
631
Damien George40f3c022014-07-03 13:25:24 +0100632 mp_int_t splits = mp_obj_get_int(args[2]);
Damien George9f85c4f2017-06-02 13:07:22 +1000633 if (splits < 0) {
634 // Negative limit means no limit, so delegate to split().
635 return mp_obj_str_split(n_args, args);
636 }
637
Damien George40f3c022014-07-03 13:25:24 +0100638 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300639 // Preallocate list to the max expected # of elements, as we
640 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000641 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100642 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300643
644 if (sep == mp_const_none) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000645 mp_raise_NotImplementedError("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300646 } else {
Damien George6b341072017-03-25 19:48:18 +1100647 size_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300648 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
649
650 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300651 mp_raise_ValueError("empty separator");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300652 }
653
654 const byte *beg = s;
655 const byte *last = s + len;
656 for (;;) {
657 s = last - sep_len;
658 for (;;) {
659 if (splits == 0 || s < beg) {
660 break;
661 } else if (memcmp(s, sep_str, sep_len) == 0) {
662 break;
663 }
664 s--;
665 }
666 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100667 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300668 break;
669 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100670 res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300671 last = s;
Damien George87690492018-02-20 19:19:02 +1100672 splits--;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300673 }
674 if (idx != 0) {
675 // We split less parts than split limit, now go cleanup surplus
Damien Georgec0d95002017-02-16 16:26:48 +1100676 size_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100677 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300678 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
679 res->len = used;
680 }
681 }
682
Damien George999cedb2015-11-27 17:01:44 +0000683 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300684}
Damien George65417c52017-07-02 23:35:42 +1000685MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300686
Damien Georgec0d95002017-02-16 16:26:48 +1100687STATIC mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300688 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgeeee1e882019-01-30 18:49:52 +1100689 mp_check_self(mp_obj_is_str_or_bytes(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +0000690
691 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000692 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000693 bad_implicit_conversion(args[1]);
694 }
John R. Lentone8204912014-01-12 21:53:52 +0000695
Damien George5fa93b62014-01-22 14:35:10 +0000696 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
697 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000698
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300699 const byte *start = haystack;
700 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000701 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300702 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000703 }
704 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300705 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000706 }
707
Jeff Eplerd6cf5c62018-03-31 21:27:56 -0500708 if (end < start) {
709 goto out_error;
710 }
711
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300712 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000713 if (p == NULL) {
Jeff Eplerd6cf5c62018-03-31 21:27:56 -0500714 out_error:
Damien George23005372014-01-13 19:39:01 +0000715 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700716 if (is_index) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300717 mp_raise_ValueError("substring not found");
xbe3d9a39e2014-04-08 11:42:19 -0700718 } else {
719 return MP_OBJ_NEW_SMALL_INT(-1);
720 }
Damien George23005372014-01-13 19:39:01 +0000721 } else {
722 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300723 #if MICROPY_PY_BUILTINS_STR_UNICODE
724 if (self_type == &mp_type_str) {
725 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
726 }
727 #endif
xbe17a5a832014-03-23 23:31:58 -0700728 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000729 }
John R. Lentone8204912014-01-12 21:53:52 +0000730}
731
Damien George4b72b3a2016-01-03 14:21:40 +0000732STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700733 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700734}
Damien George65417c52017-07-02 23:35:42 +1000735MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -0700736
Damien George4b72b3a2016-01-03 14:21:40 +0000737STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700738 return str_finder(n_args, args, -1, false);
739}
Damien George65417c52017-07-02 23:35:42 +1000740MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -0700741
Damien George4b72b3a2016-01-03 14:21:40 +0000742STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700743 return str_finder(n_args, args, 1, true);
744}
Damien George65417c52017-07-02 23:35:42 +1000745MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
xbe3d9a39e2014-04-08 11:42:19 -0700746
Damien George4b72b3a2016-01-03 14:21:40 +0000747STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700748 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700749}
Damien George65417c52017-07-02 23:35:42 +1000750MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
xbe17a5a832014-03-23 23:31:58 -0700751
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200752// TODO: (Much) more variety in args
Damien George4b72b3a2016-01-03 14:21:40 +0000753STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300754 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300755 GET_STR_DATA_LEN(args[0], str, str_len);
Paul Sokolovsky37379a22017-08-29 00:06:21 +0300756 size_t prefix_len;
757 const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300758 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300759 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300760 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300761 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300762 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200763 return mp_const_false;
764 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300765 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200766}
Damien George65417c52017-07-02 23:35:42 +1000767MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200768
Damien George4b72b3a2016-01-03 14:21:40 +0000769STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300770 GET_STR_DATA_LEN(args[0], str, str_len);
Paul Sokolovsky37379a22017-08-29 00:06:21 +0300771 size_t suffix_len;
772 const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100773 if (n_args > 2) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000774 mp_raise_NotImplementedError("start/end indices");
Damien George55b11e62015-09-04 16:49:56 +0100775 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300776
777 if (suffix_len > str_len) {
778 return mp_const_false;
779 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300780 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300781}
Damien George65417c52017-07-02 23:35:42 +1000782MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300783
Paul Sokolovsky88107842014-04-26 06:20:08 +0300784enum { LSTRIP, RSTRIP, STRIP };
785
Damien George90ab1912017-02-03 13:04:56 +1100786STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
Damien Georgeeee1e882019-01-30 18:49:52 +1100787 mp_check_self(mp_obj_is_str_or_bytes(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300788 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000789
790 const byte *chars_to_del;
791 uint chars_to_del_len;
792 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800793
794 if (n_args == 1) {
795 chars_to_del = whitespace;
Paul Sokolovskyfc9a6dd2017-09-19 21:19:23 +0300796 chars_to_del_len = sizeof(whitespace) - 1;
xbe7b0f39f2014-01-08 14:23:45 -0800797 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300798 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000799 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300800 }
Damien George5fa93b62014-01-22 14:35:10 +0000801 GET_STR_DATA_LEN(args[1], s, l);
802 chars_to_del = s;
803 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800804 }
805
Damien George5fa93b62014-01-22 14:35:10 +0000806 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800807
Damien Georgec0d95002017-02-16 16:26:48 +1100808 size_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800809 bool first_good_char_pos_set = false;
Damien Georgec0d95002017-02-16 16:26:48 +1100810 size_t last_good_char_pos = 0;
811 size_t i = 0;
812 int delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300813 if (type == RSTRIP) {
814 i = orig_str_len - 1;
815 delta = -1;
816 }
Damien Georgec0d95002017-02-16 16:26:48 +1100817 for (size_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700818 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800819 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300820 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800821 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300822 if (type == LSTRIP) {
823 last_good_char_pos = orig_str_len - 1;
824 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300825 } else if (type == RSTRIP) {
826 first_good_char_pos = 0;
827 last_good_char_pos = i;
828 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300829 }
xbe7b0f39f2014-01-08 14:23:45 -0800830 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300831 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800832 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300833 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800834 }
835
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300836 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000837 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000838 if (self_type == &mp_type_str) {
839 return MP_OBJ_NEW_QSTR(MP_QSTR_);
840 } else {
841 return mp_const_empty_bytes;
842 }
xbe7b0f39f2014-01-08 14:23:45 -0800843 }
844
845 assert(last_good_char_pos >= first_good_char_pos);
Ville Skyttäca16c382017-05-29 10:08:14 +0300846 //+1 to accommodate the last character
Damien Georgec0d95002017-02-16 16:26:48 +1100847 size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300848 if (stripped_len == orig_str_len) {
849 // If nothing was stripped, don't bother to dup original string
850 // TODO: watch out for this case when we'll get to bytearray.strip()
851 assert(first_good_char_pos == 0);
852 return args[0];
853 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100854 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800855}
856
Damien George4b72b3a2016-01-03 14:21:40 +0000857STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300858 return str_uni_strip(STRIP, n_args, args);
859}
Damien George65417c52017-07-02 23:35:42 +1000860MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300861
Damien George4b72b3a2016-01-03 14:21:40 +0000862STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300863 return str_uni_strip(LSTRIP, n_args, args);
864}
Damien George65417c52017-07-02 23:35:42 +1000865MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300866
Damien George4b72b3a2016-01-03 14:21:40 +0000867STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300868 return str_uni_strip(RSTRIP, n_args, args);
869}
Damien George65417c52017-07-02 23:35:42 +1000870MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300871
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300872#if MICROPY_PY_BUILTINS_STR_CENTER
873STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
874 GET_STR_DATA_LEN(str_in, str, str_len);
Paul Sokolovsky9dde6062016-05-22 02:22:14 +0300875 mp_uint_t width = mp_obj_get_int(width_in);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300876 if (str_len >= width) {
877 return str_in;
878 }
879
880 vstr_t vstr;
881 vstr_init_len(&vstr, width);
882 memset(vstr.buf, ' ', width);
883 int left = (width - str_len) / 2;
884 memcpy(vstr.buf + left, str, str_len);
885 return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
886}
Damien George65417c52017-07-02 23:35:42 +1000887MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300888#endif
889
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700890// Takes an int arg, but only parses unsigned numbers, and only changes
891// *num if at least one digit was parsed.
Damien George87e07ea2016-02-02 15:51:57 +0000892STATIC const char *str_to_int(const char *str, const char *top, int *num) {
893 if (str < top && '0' <= *str && *str <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700894 *num = 0;
895 do {
Damien George87e07ea2016-02-02 15:51:57 +0000896 *num = *num * 10 + (*str - '0');
897 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700898 }
Damien George87e07ea2016-02-02 15:51:57 +0000899 while (str < top && '0' <= *str && *str <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700900 }
Damien George87e07ea2016-02-02 15:51:57 +0000901 return str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902}
903
Damien George2801e6f2015-04-04 15:53:11 +0100904STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 return ch && strchr("<>=^", ch) != NULL;
906}
907
Damien George2801e6f2015-04-04 15:53:11 +0100908STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700909 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
910}
911
Damien George2801e6f2015-04-04 15:53:11 +0100912STATIC bool arg_looks_integer(mp_obj_t arg) {
Damien Georgeeee1e882019-01-30 18:49:52 +1100913 return mp_obj_is_type(arg, &mp_type_bool) || mp_obj_is_int(arg);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700914}
915
Damien George2801e6f2015-04-04 15:53:11 +0100916STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700917 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100918#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100919 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700920#endif
921 ;
922}
923
Paul Sokolovsky2da5d412018-08-15 15:17:41 +0300924#if MICROPY_PY_BUILTINS_STR_OP_MODULO
Damien George2801e6f2015-04-04 15:53:11 +0100925STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100926#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100927 if (mp_obj_is_float(arg)) {
928 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700929 }
930#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700931 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700932}
Paul Sokolovsky2da5d412018-08-15 15:17:41 +0300933#endif
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700934
Damien George897129a2016-09-27 15:45:42 +1000935#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
Damien George1e9a92f2014-11-06 17:36:16 +0000936STATIC NORETURN void terse_str_format_value_error(void) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300937 mp_raise_ValueError("bad format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000938}
Damien George897129a2016-09-27 15:45:42 +1000939#else
940// define to nothing to improve coverage
941#define terse_str_format_value_error()
942#endif
Damien George1e9a92f2014-11-06 17:36:16 +0000943
Damien George90ab1912017-02-03 13:04:56 +1100944STATIC 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) {
Damien George0b9ee862015-01-21 19:14:25 +0000945 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100946 mp_print_t print;
947 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700948
pohmeliee3a29de2016-01-29 12:09:10 +0300949 for (; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700950 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000951 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700952 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100953 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700954 continue;
955 }
Damien George1e9a92f2014-11-06 17:36:16 +0000956 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
957 terse_str_format_value_error();
958 } else {
Damien George21967992016-08-14 16:51:54 +1000959 mp_raise_ValueError("single '}' encountered in format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000960 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700961 }
962 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100963 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700964 continue;
965 }
966
967 str++;
968 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100969 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700970 continue;
971 }
972
973 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
974
Damien George87e07ea2016-02-02 15:51:57 +0000975 const char *field_name = NULL;
976 const char *field_name_top = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700977 char conversion = '\0';
pohmeliee3a29de2016-01-29 12:09:10 +0300978 const char *format_spec = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700979
980 if (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000981 field_name = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700982 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000983 ++str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700984 }
Damien George87e07ea2016-02-02 15:51:57 +0000985 field_name_top = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700986 }
987
988 // conversion ::= "r" | "s"
989
990 if (str < top && *str == '!') {
991 str++;
992 if (str < top && (*str == 'r' || *str == 's')) {
993 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200994 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000995 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
996 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100997 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300998 mp_raise_ValueError("bad conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100999 } else {
1000 if (str >= top) {
Damien George21967992016-08-14 16:51:54 +10001001 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001002 "end of format while looking for conversion specifier");
Damien George000730e2015-08-30 12:43:21 +01001003 } else {
1004 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1005 "unknown conversion specifier %c", *str));
1006 }
Damien George1e9a92f2014-11-06 17:36:16 +00001007 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001008 }
1009 }
1010
1011 if (str < top && *str == ':') {
1012 str++;
1013 // {:} is the same as {}, which is the same as {!s}
1014 // This makes a difference when passing in a True or False
1015 // '{}'.format(True) returns 'True'
1016 // '{:d}'.format(True) returns '1'
1017 // So we treat {:} as {} and this later gets treated to be {!s}
1018 if (*str != '}') {
pohmeliee3a29de2016-01-29 12:09:10 +03001019 format_spec = str;
1020 for (int nest = 1; str < top;) {
1021 if (*str == '{') {
1022 ++nest;
1023 } else if (*str == '}') {
1024 if (--nest == 0) {
1025 break;
1026 }
1027 }
1028 ++str;
Damiend99b0522013-12-21 18:17:45 +00001029 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001030 }
1031 }
1032 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001033 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1034 terse_str_format_value_error();
1035 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001036 mp_raise_ValueError("unmatched '{' in format");
Damien George1e9a92f2014-11-06 17:36:16 +00001037 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001038 }
1039 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +00001040 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1041 terse_str_format_value_error();
1042 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001043 mp_raise_ValueError("expected ':' after format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001044 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001045 }
1046
1047 mp_obj_t arg = mp_const_none;
1048
1049 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +01001050 int index = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001051 if (MP_LIKELY(unichar_isdigit(*field_name))) {
pohmeliee3a29de2016-01-29 12:09:10 +03001052 if (*arg_i > 0) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001053 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1054 terse_str_format_value_error();
1055 } else {
Damien George21967992016-08-14 16:51:54 +10001056 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001057 "can't switch from automatic field numbering to manual field specification");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001058 }
1059 }
Damien George87e07ea2016-02-02 15:51:57 +00001060 field_name = str_to_int(field_name, field_name_top, &index);
Damien George963a5a32015-01-16 17:47:07 +00001061 if ((uint)index >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001062 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001063 }
1064 arg = args[index + 1];
pohmeliee3a29de2016-01-29 12:09:10 +03001065 *arg_i = -1;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001066 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001067 const char *lookup;
1068 for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
Damien George46017592017-11-16 13:17:51 +11001069 mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr?
Damien George87e07ea2016-02-02 15:51:57 +00001070 field_name = lookup;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001071 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
1072 if (key_elem == NULL) {
1073 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
1074 }
1075 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001076 }
Damien George87e07ea2016-02-02 15:51:57 +00001077 if (field_name < field_name_top) {
Javier Candeira35a1fea2017-08-09 14:40:45 +10001078 mp_raise_NotImplementedError("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001079 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001080 } else {
pohmeliee3a29de2016-01-29 12:09:10 +03001081 if (*arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +00001082 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1083 terse_str_format_value_error();
1084 } else {
Damien George21967992016-08-14 16:51:54 +10001085 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001086 "can't switch from manual field specification to automatic field numbering");
Damien George1e9a92f2014-11-06 17:36:16 +00001087 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001088 }
pohmeliee3a29de2016-01-29 12:09:10 +03001089 if ((uint)*arg_i >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001090 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 }
pohmeliee3a29de2016-01-29 12:09:10 +03001092 arg = args[(*arg_i) + 1];
1093 (*arg_i)++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001094 }
1095 if (!format_spec && !conversion) {
1096 conversion = 's';
1097 }
1098 if (conversion) {
1099 mp_print_kind_t print_kind;
1100 if (conversion == 's') {
1101 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001102 } else {
Damien George000730e2015-08-30 12:43:21 +01001103 assert(conversion == 'r');
1104 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001105 }
Damien George0b9ee862015-01-21 19:14:25 +00001106 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001107 mp_print_t arg_print;
1108 vstr_init_print(&arg_vstr, 16, &arg_print);
1109 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001110 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001111 }
1112
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001113 char fill = '\0';
1114 char align = '\0';
1115 int width = -1;
1116 int precision = -1;
1117 char type = '\0';
1118 int flags = 0;
1119
1120 if (format_spec) {
1121 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1122 //
1123 // [[fill]align][sign][#][0][width][,][.precision][type]
1124 // fill ::= <any character>
1125 // align ::= "<" | ">" | "=" | "^"
1126 // sign ::= "+" | "-" | " "
1127 // width ::= integer
1128 // precision ::= integer
1129 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1130
pohmeliee3a29de2016-01-29 12:09:10 +03001131 // recursively call the formatter to format any nested specifiers
1132 MP_STACK_CHECK();
1133 vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001134 const char *s = vstr_null_terminated_str(&format_spec_vstr);
Damien George87e07ea2016-02-02 15:51:57 +00001135 const char *stop = s + format_spec_vstr.len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001136 if (isalignment(*s)) {
1137 align = *s++;
1138 } else if (*s && isalignment(s[1])) {
1139 fill = *s++;
1140 align = *s++;
1141 }
1142 if (*s == '+' || *s == '-' || *s == ' ') {
1143 if (*s == '+') {
1144 flags |= PF_FLAG_SHOW_SIGN;
1145 } else if (*s == ' ') {
1146 flags |= PF_FLAG_SPACE_SIGN;
1147 }
Damien George9d2c72a2017-07-04 02:13:27 +10001148 s++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001149 }
1150 if (*s == '#') {
1151 flags |= PF_FLAG_SHOW_PREFIX;
1152 s++;
1153 }
1154 if (*s == '0') {
1155 if (!align) {
1156 align = '=';
1157 }
1158 if (!fill) {
1159 fill = '0';
1160 }
1161 }
Damien George87e07ea2016-02-02 15:51:57 +00001162 s = str_to_int(s, stop, &width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001163 if (*s == ',') {
1164 flags |= PF_FLAG_SHOW_COMMA;
1165 s++;
1166 }
1167 if (*s == '.') {
1168 s++;
Damien George87e07ea2016-02-02 15:51:57 +00001169 s = str_to_int(s, stop, &precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001170 }
1171 if (istype(*s)) {
1172 type = *s++;
1173 }
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001174 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001175 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1176 terse_str_format_value_error();
1177 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001178 mp_raise_ValueError("invalid format specifier");
Damien George7ef75f92015-08-26 15:42:25 +01001179 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001180 }
pohmeliee3a29de2016-01-29 12:09:10 +03001181 vstr_clear(&format_spec_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001182 }
1183 if (!align) {
1184 if (arg_looks_numeric(arg)) {
1185 align = '>';
1186 } else {
1187 align = '<';
1188 }
1189 }
1190 if (!fill) {
1191 fill = ' ';
1192 }
1193
Damien George9d2c72a2017-07-04 02:13:27 +10001194 if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001195 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001196 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1197 terse_str_format_value_error();
1198 } else {
Damien George21967992016-08-14 16:51:54 +10001199 mp_raise_ValueError("sign not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001200 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001201 }
1202 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001203 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1204 terse_str_format_value_error();
1205 } else {
Damien George21967992016-08-14 16:51:54 +10001206 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001207 "sign not allowed with integer format specifier 'c'");
Damien George1e9a92f2014-11-06 17:36:16 +00001208 }
Damiend99b0522013-12-21 18:17:45 +00001209 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001210 }
1211
1212 switch (align) {
1213 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1214 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1215 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1216 }
1217
1218 if (arg_looks_integer(arg)) {
1219 switch (type) {
1220 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001221 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001222 continue;
1223
1224 case 'c':
1225 {
1226 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001227 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001228 continue;
1229 }
1230
1231 case '\0': // No explicit format type implies 'd'
1232 case 'n': // I don't think we support locales in uPy so use 'd'
1233 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001234 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001235 continue;
1236
1237 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001238 if (flags & PF_FLAG_SHOW_PREFIX) {
1239 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1240 }
1241
Damien George7f9d1d62015-04-09 23:56:15 +01001242 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001243 continue;
1244
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001245 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001246 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001247 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001248 continue;
1249
1250 case 'e':
1251 case 'E':
1252 case 'f':
1253 case 'F':
1254 case 'g':
1255 case 'G':
1256 case '%':
1257 // The floating point formatters all work with anything that
1258 // looks like an integer
1259 break;
1260
1261 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001262 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1263 terse_str_format_value_error();
1264 } else {
1265 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1266 "unknown format code '%c' for object of type '%s'",
1267 type, mp_obj_get_type_str(arg)));
1268 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001269 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001270 }
Damien George70f33cd2014-04-02 17:06:05 +01001271
Dave Hylands22fe4d72014-04-02 12:07:31 -07001272 // NOTE: no else here. We need the e, f, g etc formats for integer
1273 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001274 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001275 if (!type) {
1276
1277 // Even though the docs say that an unspecified type is the same
1278 // as 'g', there is one subtle difference, when the exponent
1279 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001280 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001281 // '{:10.1}'.format(0.0) ==> '0e+00'
1282 // '{:10.1g}'.format(0.0) ==> '0'
1283 //
1284 // TODO: Figure out how to deal with this.
1285 //
1286 // A proper solution would involve adding a special flag
1287 // or something to format_float, and create a format_double
1288 // to deal with doubles. In order to fix this when using
1289 // sprintf, we'd need to use the e format and tweak the
1290 // returned result to strip trailing zeros like the g format
1291 // does.
1292 //
1293 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1294 // but with 1.e2 you get 1e+02 and 1.00e+02
1295 //
1296 // Stripping the trailing 0's (like g) does would make the
1297 // e format give us the right format.
1298 //
1299 // CPython sources say:
1300 // Omitted type specifier. Behaves in the same way as repr(x)
1301 // and str(x) if no precision is given, else like 'g', but with
1302 // at least one digit after the decimal point. */
1303
1304 type = 'g';
1305 }
1306 if (type == 'n') {
1307 type = 'g';
1308 }
1309
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001310 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001311#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001312 case 'e':
1313 case 'E':
1314 case 'f':
1315 case 'F':
1316 case 'g':
1317 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001318 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001319 break;
1320
1321 case '%':
1322 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001323 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1324 #define F100 100.0F
1325 #else
1326 #define F100 100.0
1327 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001328 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001329 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001330 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001331#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001332
1333 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001334 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1335 terse_str_format_value_error();
1336 } else {
1337 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien Georgeaec6fa92018-07-30 12:46:47 +10001338 "unknown format code '%c' for object of type '%s'",
Damien George1e9a92f2014-11-06 17:36:16 +00001339 type, mp_obj_get_type_str(arg)));
1340 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001341 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001342 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001343 // arg doesn't look like a number
1344
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001345 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001346 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1347 terse_str_format_value_error();
1348 } else {
Damien George21967992016-08-14 16:51:54 +10001349 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001350 "'=' alignment not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001351 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001352 }
Damien George70f33cd2014-04-02 17:06:05 +01001353
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001354 switch (type) {
Damien Georged4df8f42016-01-04 13:13:39 +00001355 case '\0': // no explicit format type implies 's'
Damien Georged182b982014-08-30 14:19:41 +01001356 case 's': {
Damien George6b341072017-03-25 19:48:18 +11001357 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001358 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001359 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001360 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001361 }
Damien George6b341072017-03-25 19:48:18 +11001362 if (slen > (size_t)precision) {
Damien George50912e72015-01-20 11:55:10 +00001363 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001364 }
Damien George7f9d1d62015-04-09 23:56:15 +01001365 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001366 break;
1367 }
1368
1369 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001370 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1371 terse_str_format_value_error();
1372 } else {
1373 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien Georgeaec6fa92018-07-30 12:46:47 +10001374 "unknown format code '%c' for object of type '%s'",
Damien George1e9a92f2014-11-06 17:36:16 +00001375 type, mp_obj_get_type_str(arg)));
1376 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001377 }
Damiend99b0522013-12-21 18:17:45 +00001378 }
1379 }
1380
pohmeliee3a29de2016-01-29 12:09:10 +03001381 return vstr;
1382}
1383
1384mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Damien Georgeeee1e882019-01-30 18:49:52 +11001385 mp_check_self(mp_obj_is_str_or_bytes(args[0]));
pohmeliee3a29de2016-01-29 12:09:10 +03001386
1387 GET_STR_DATA_LEN(args[0], str, len);
1388 int arg_i = 0;
1389 vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs);
Paul Sokolovskya135bca2018-09-21 16:44:04 -07001390 return mp_obj_new_str_from_vstr(mp_obj_get_type(args[0]), &vstr);
Damiend99b0522013-12-21 18:17:45 +00001391}
Damien George65417c52017-07-02 23:35:42 +10001392MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Damiend99b0522013-12-21 18:17:45 +00001393
Paul Sokolovsky2da5d412018-08-15 15:17:41 +03001394#if MICROPY_PY_BUILTINS_STR_OP_MODULO
Damien George90ab1912017-02-03 13:04:56 +11001395STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Damien Georgeeee1e882019-01-30 18:49:52 +11001396 mp_check_self(mp_obj_is_str_or_bytes(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001397
1398 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001399 const byte *start_str = str;
Damien Georgeeee1e882019-01-30 18:49:52 +11001400 bool is_bytes = mp_obj_is_type(pattern, &mp_type_bytes);
Damien George90ab1912017-02-03 13:04:56 +11001401 size_t arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001402 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001403 mp_print_t print;
1404 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001405
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001406 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001407 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001408 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001409 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001410 continue;
1411 }
1412 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001413 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001414 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001415 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001416 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001417 continue;
1418 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001419
1420 // Dictionary value lookup
1421 if (*str == '(') {
Damien George7317e342017-02-03 12:13:44 +11001422 if (dict == MP_OBJ_NULL) {
Damien Georgeb01f66c2018-06-20 21:02:11 +10001423 mp_raise_TypeError("format needs a dict");
Damien George7317e342017-02-03 12:13:44 +11001424 }
1425 arg_i = 1; // we used up the single dict argument
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001426 const byte *key = ++str;
1427 while (*str != ')') {
1428 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001429 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1430 terse_str_format_value_error();
1431 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001432 mp_raise_ValueError("incomplete format key");
Damien George1e9a92f2014-11-06 17:36:16 +00001433 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001434 }
1435 ++str;
1436 }
Damien George46017592017-11-16 13:17:51 +11001437 mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001438 arg = mp_obj_dict_get(dict, k_obj);
1439 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001440 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001441
Dave Hylands6756a372014-04-02 11:42:39 -07001442 int flags = 0;
1443 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001444 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001445 while (str < top) {
1446 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1447 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1448 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001449 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001450 else if (*str == '0') {
1451 flags |= PF_FLAG_PAD_AFTER_SIGN;
1452 fill = '0';
1453 } else break;
1454 str++;
1455 }
1456 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001457 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001458 if (str < top) {
1459 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001460 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001461 goto not_enough_args;
1462 }
Dave Hylands6756a372014-04-02 11:42:39 -07001463 width = mp_obj_get_int(args[arg_i++]);
1464 str++;
1465 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001466 str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001467 }
1468 }
1469 int prec = -1;
1470 if (str < top && *str == '.') {
1471 if (++str < top) {
1472 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001473 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001474 goto not_enough_args;
1475 }
Dave Hylands6756a372014-04-02 11:42:39 -07001476 prec = mp_obj_get_int(args[arg_i++]);
1477 str++;
1478 } else {
1479 prec = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001480 str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001481 }
1482 }
1483 }
1484
1485 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001486incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001487 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1488 terse_str_format_value_error();
1489 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001490 mp_raise_ValueError("incomplete format");
Damien George1e9a92f2014-11-06 17:36:16 +00001491 }
Dave Hylands6756a372014-04-02 11:42:39 -07001492 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001493
1494 // Tuple value lookup
1495 if (arg == MP_OBJ_NULL) {
Damien George90ab1912017-02-03 13:04:56 +11001496 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001497not_enough_args:
Damien Georgeb01f66c2018-06-20 21:02:11 +10001498 mp_raise_TypeError("format string needs more arguments");
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001499 }
1500 arg = args[arg_i++];
1501 }
Dave Hylands6756a372014-04-02 11:42:39 -07001502 switch (*str) {
1503 case 'c':
Damien Georgeeee1e882019-01-30 18:49:52 +11001504 if (mp_obj_is_str(arg)) {
Damien George6b341072017-03-25 19:48:18 +11001505 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001506 const char *s = mp_obj_str_get_data(arg, &slen);
1507 if (slen != 1) {
Damien Georgeb01f66c2018-06-20 21:02:11 +10001508 mp_raise_TypeError("%%c needs int or char");
Dave Hylands6756a372014-04-02 11:42:39 -07001509 }
Damien George7f9d1d62015-04-09 23:56:15 +01001510 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001511 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001512 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001513 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001514 } else {
Damien Georgeb01f66c2018-06-20 21:02:11 +10001515 mp_raise_TypeError("integer needed");
Dave Hylands6756a372014-04-02 11:42:39 -07001516 }
Damien George11de8392014-06-05 18:57:38 +01001517 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001518
1519 case 'd':
1520 case 'i':
1521 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001522 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001523 break;
1524
Damien Georgefb510b32014-06-01 13:32:54 +01001525#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001526 case 'e':
1527 case 'E':
1528 case 'f':
1529 case 'F':
1530 case 'g':
1531 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001532 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001533 break;
1534#endif
1535
1536 case 'o':
1537 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001538 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001539 }
Damien George7f9d1d62015-04-09 23:56:15 +01001540 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001541 break;
1542
1543 case 'r':
1544 case 's':
1545 {
Damien George0b9ee862015-01-21 19:14:25 +00001546 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001547 mp_print_t arg_print;
1548 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001549 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
Damien Georgeeee1e882019-01-30 18:49:52 +11001550 if (print_kind == PRINT_STR && is_bytes && mp_obj_is_type(arg, &mp_type_bytes)) {
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001551 // If we have something like b"%s" % b"1", bytes arg should be
1552 // printed undecorated.
1553 print_kind = PRINT_RAW;
1554 }
1555 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001556 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001557 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001558 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001559 }
Damien George50912e72015-01-20 11:55:10 +00001560 if (vlen > (uint)prec) {
1561 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001562 }
Damien George7f9d1d62015-04-09 23:56:15 +01001563 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001564 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001565 break;
1566 }
Dave Hylands6756a372014-04-02 11:42:39 -07001567
Dave Hylands6756a372014-04-02 11:42:39 -07001568 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001569 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001570 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001571 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001572
Dave Hylands6756a372014-04-02 11:42:39 -07001573 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001574 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1575 terse_str_format_value_error();
1576 } else {
1577 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1578 "unsupported format character '%c' (0x%x) at index %d",
1579 *str, *str, str - start_str));
1580 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001581 }
1582 }
1583
Damien George90ab1912017-02-03 13:04:56 +11001584 if (arg_i != n_args) {
Damien Georgeb01f66c2018-06-20 21:02:11 +10001585 mp_raise_TypeError("format string didn't convert all arguments");
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001586 }
1587
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001588 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001589}
Paul Sokolovsky2da5d412018-08-15 15:17:41 +03001590#endif
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001591
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001592// The implementation is optimized, returning the original string if there's
1593// nothing to replace.
Damien George4b72b3a2016-01-03 14:21:40 +00001594STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
Damien Georgeeee1e882019-01-30 18:49:52 +11001595 mp_check_self(mp_obj_is_str_or_bytes(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001596
Damien George40f3c022014-07-03 13:25:24 +01001597 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001598 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001599 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001600 if (max_rep == 0) {
1601 return args[0];
1602 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001603 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001604 }
xbe480c15a2014-01-30 22:17:30 -08001605 }
Damien George94f68302014-01-31 23:45:12 +00001606
xbe729be9b2014-04-07 14:46:39 -07001607 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001608
Damien Georgeff715422014-04-07 00:39:13 +01001609 // check argument types
1610
Damien Georgec55a4d82014-12-24 20:28:30 +00001611 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1612
1613 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001614 bad_implicit_conversion(args[1]);
1615 }
1616
Damien Georgec55a4d82014-12-24 20:28:30 +00001617 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001618 bad_implicit_conversion(args[2]);
1619 }
1620
1621 // extract string data
1622
xbe480c15a2014-01-30 22:17:30 -08001623 GET_STR_DATA_LEN(args[0], str, str_len);
1624 GET_STR_DATA_LEN(args[1], old, old_len);
1625 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001626
1627 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001628 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001629 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001630 }
1631
Damien George94f68302014-01-31 23:45:12 +00001632 // data for the replaced string
1633 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001634 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001635
Damien George94f68302014-01-31 23:45:12 +00001636 // do 2 passes over the string:
1637 // first pass computes the required length of the replaced string
1638 // second pass does the replacements
1639 for (;;) {
Damien Georgec0d95002017-02-16 16:26:48 +11001640 size_t replaced_str_index = 0;
1641 size_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001642 const byte *old_occurrence;
1643 const byte *offset_ptr = str;
Damien Georgec0d95002017-02-16 16:26:48 +11001644 size_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001645 if (old_len == 0) {
1646 // if old_str is empty, copy new_str to start of replaced string
1647 // copy the replacement string
1648 if (data != NULL) {
1649 memcpy(data, new, new_len);
1650 }
1651 replaced_str_index += new_len;
1652 num_replacements_done++;
1653 }
Damien Georgec0d95002017-02-16 16:26:48 +11001654 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) {
Damien Georgeff715422014-04-07 00:39:13 +01001655 if (old_len == 0) {
1656 old_occurrence += 1;
1657 }
Damien George94f68302014-01-31 23:45:12 +00001658 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1659 if (data != NULL) {
1660 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1661 }
1662 replaced_str_index += old_occurrence - offset_ptr;
1663 // copy the replacement string
1664 if (data != NULL) {
1665 memcpy(data + replaced_str_index, new, new_len);
1666 }
1667 replaced_str_index += new_len;
1668 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001669 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001670 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001671 }
1672
1673 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1674 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001675 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001676 }
Damien Georgeff715422014-04-07 00:39:13 +01001677 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001678
1679 if (data == NULL) {
1680 // first pass
1681 if (num_replacements_done == 0) {
1682 // no substr found, return original string
1683 return args[0];
1684 } else {
1685 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001686 vstr_init_len(&vstr, replaced_str_index);
1687 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001688 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001689 }
1690 } else {
1691 // second pass, we are done
1692 break;
1693 }
xbe480c15a2014-01-30 22:17:30 -08001694 }
Damien George94f68302014-01-31 23:45:12 +00001695
Damien George05005f62015-01-21 22:48:37 +00001696 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001697}
Damien George65417c52017-07-02 23:35:42 +10001698MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe480c15a2014-01-30 22:17:30 -08001699
Paul Sokolovsky5a91fce2018-08-05 23:56:19 +03001700#if MICROPY_PY_BUILTINS_STR_COUNT
Damien George4b72b3a2016-01-03 14:21:40 +00001701STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001702 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgeeee1e882019-01-30 18:49:52 +11001703 mp_check_self(mp_obj_is_str_or_bytes(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +00001704
1705 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001706 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001707 bad_implicit_conversion(args[1]);
1708 }
xbe9e1e8cd2014-03-12 22:57:16 -07001709
1710 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1711 GET_STR_DATA_LEN(args[1], needle, needle_len);
1712
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001713 const byte *start = haystack;
1714 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001715 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001716 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001717 }
1718 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001719 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001720 }
1721
Damien George536dde22014-03-13 22:07:55 +00001722 // if needle_len is zero then we count each gap between characters as an occurrence
1723 if (needle_len == 0) {
Damien George19aee942018-02-14 18:19:22 +11001724 return MP_OBJ_NEW_SMALL_INT(utf8_charlen(start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001725 }
1726
Damien George536dde22014-03-13 22:07:55 +00001727 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001728 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001729 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1730 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001731 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001732 haystack_ptr += needle_len;
1733 } else {
1734 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001735 }
xbe9e1e8cd2014-03-12 22:57:16 -07001736 }
1737
1738 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1739}
Damien George65417c52017-07-02 23:35:42 +10001740MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
Paul Sokolovsky5a91fce2018-08-05 23:56:19 +03001741#endif
xbe9e1e8cd2014-03-12 22:57:16 -07001742
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001743#if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgec0d95002017-02-16 16:26:48 +11001744STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
Damien Georgeeee1e882019-01-30 18:49:52 +11001745 mp_check_self(mp_obj_is_str_or_bytes(self_in));
Damien Georgebfbd9442020-01-09 11:01:14 +11001746 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001747 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001748 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001749 }
Damien Georgeb035db32014-03-21 20:39:40 +00001750
xbe613a8e32014-03-18 00:06:29 -07001751 GET_STR_DATA_LEN(self_in, str, str_len);
1752 GET_STR_DATA_LEN(arg, sep, sep_len);
1753
1754 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001755 mp_raise_ValueError("empty separator");
xbe613a8e32014-03-18 00:06:29 -07001756 }
Damien Georgeb035db32014-03-21 20:39:40 +00001757
Damien Georgec55a4d82014-12-24 20:28:30 +00001758 mp_obj_t result[3];
1759 if (self_type == &mp_type_str) {
1760 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1761 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1762 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1763 } else {
1764 result[0] = mp_const_empty_bytes;
1765 result[1] = mp_const_empty_bytes;
1766 result[2] = mp_const_empty_bytes;
1767 }
Damien Georgeb035db32014-03-21 20:39:40 +00001768
1769 if (direction > 0) {
1770 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001771 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001772 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001773 }
xbe613a8e32014-03-18 00:06:29 -07001774
xbe17a5a832014-03-23 23:31:58 -07001775 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1776 if (position_ptr != NULL) {
Damien Georgec0d95002017-02-16 16:26:48 +11001777 size_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001778 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001779 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001780 result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001781 }
Damien Georgeb035db32014-03-21 20:39:40 +00001782
xbe0a6894c2014-03-21 01:12:26 -07001783 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001784}
1785
Damien Georgeb035db32014-03-21 20:39:40 +00001786STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1787 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001788}
Damien George65417c52017-07-02 23:35:42 +10001789MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001790
Damien Georgeb035db32014-03-21 20:39:40 +00001791STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1792 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001793}
Damien George65417c52017-07-02 23:35:42 +10001794MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001795#endif
xbe4504ea82014-03-19 00:46:14 -07001796
Paul Sokolovsky69135212014-05-10 19:47:41 +03001797// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001798STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001799 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001800 vstr_t vstr;
1801 vstr_init_len(&vstr, self_len);
1802 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +11001803 for (size_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001804 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001805 }
Damien George05005f62015-01-21 22:48:37 +00001806 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001807}
1808
1809STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001810 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001811}
Damien George65417c52017-07-02 23:35:42 +10001812MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001813
1814STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001815 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001816}
Damien George65417c52017-07-02 23:35:42 +10001817MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001818
Damien Georgefcc9cf62014-06-01 18:22:09 +01001819STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001820 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001821
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001822 if (self_len == 0) {
1823 return mp_const_false; // default to False for empty str
1824 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001825
Damien Georgefcc9cf62014-06-01 18:22:09 +01001826 if (f != unichar_isupper && f != unichar_islower) {
Damien Georgec0d95002017-02-16 16:26:48 +11001827 for (size_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001828 if (!f(*self_data++)) {
1829 return mp_const_false;
1830 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001831 }
1832 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001833 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001834
Damien Georgec0d95002017-02-16 16:26:48 +11001835 for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001836 if (unichar_isalpha(*self_data++)) {
1837 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001838 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1839 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001840 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001841 }
1842 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001843
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001844 if (!contains_alpha) {
1845 return mp_const_false;
1846 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001847 }
1848
1849 return mp_const_true;
1850}
1851
1852STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001853 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001854}
Damien George65417c52017-07-02 23:35:42 +10001855MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001856
1857STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001858 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001859}
Damien George65417c52017-07-02 23:35:42 +10001860MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001861
1862STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001863 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001864}
Damien George65417c52017-07-02 23:35:42 +10001865MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001866
1867STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001868 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001869}
Damien George65417c52017-07-02 23:35:42 +10001870MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001871
1872STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001873 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001874}
Damien George65417c52017-07-02 23:35:42 +10001875MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001876
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001877#if MICROPY_CPYTHON_COMPAT
Ville Skyttäca16c382017-05-29 10:08:14 +03001878// These methods are superfluous in the presence of str() and bytes()
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001879// constructors.
1880// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001881STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001882 mp_obj_t new_args[2];
1883 if (n_args == 1) {
1884 new_args[0] = args[0];
1885 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1886 args = new_args;
1887 n_args++;
1888 }
Damien George5b3f0b72016-01-03 15:55:55 +00001889 return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001890}
Damien George65417c52017-07-02 23:35:42 +10001891MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001892
1893// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001894STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001895 mp_obj_t new_args[2];
1896 if (n_args == 1) {
1897 new_args[0] = args[0];
1898 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1899 args = new_args;
1900 n_args++;
1901 }
Damien George5b3f0b72016-01-03 15:55:55 +00001902 return bytes_make_new(NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001903}
Damien George65417c52017-07-02 23:35:42 +10001904MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001905#endif
1906
Damien George4d917232014-08-30 14:28:06 +01001907mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
Damien George57a4b4f2014-04-18 22:29:21 +01001908 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001909 GET_STR_DATA_LEN(self_in, str_data, str_len);
1910 bufinfo->buf = (void*)str_data;
1911 bufinfo->len = str_len;
Damien George12dd8df2016-05-07 21:18:17 +01001912 bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
Damien George2da98302014-03-09 19:58:18 +00001913 return 0;
1914 } else {
1915 // can't write to a string
Damien George2da98302014-03-09 19:58:18 +00001916 return 1;
1917 }
1918}
1919
Damien Georgecbf76742015-11-27 13:38:15 +00001920STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001921#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001922 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001923 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1924 // If we have separate unicode type, then here we have methods only
1925 // for bytes type, and it should not have encode() methods. Otherwise,
1926 // we have non-compliant-but-practical bytestring type, which shares
1927 // method table with bytes, so they both have encode() and decode()
1928 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001929 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001930 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001931#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001932 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1933 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1934 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1935 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1936 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1937 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001938 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001939 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001940 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001941 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1942 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1943 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1944 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1945 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1946 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1947 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1948 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
Paul Sokolovsky5a91fce2018-08-05 23:56:19 +03001949 #if MICROPY_PY_BUILTINS_STR_COUNT
Damien Georgecbf76742015-11-27 13:38:15 +00001950 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
Paul Sokolovsky5a91fce2018-08-05 23:56:19 +03001951 #endif
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001952 #if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgecbf76742015-11-27 13:38:15 +00001953 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1954 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001955 #endif
Paul Sokolovsky15633882016-08-07 15:24:57 +03001956 #if MICROPY_PY_BUILTINS_STR_CENTER
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +03001957 { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
Paul Sokolovsky15633882016-08-07 15:24:57 +03001958 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001959 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1960 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1961 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1962 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1963 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1964 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1965 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001966};
Damien George97209d32014-01-07 15:58:30 +00001967
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001968STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001969
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001970#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgeae8d8672016-01-09 23:14:54 +00001971STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf);
Damien George44e7cbf2015-05-17 16:44:24 +01001972
Damien George3e1a5c12014-03-29 13:43:38 +00001973const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001974 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001975 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001976 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001977 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001978 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001979 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001980 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001981 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001982 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001983};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001984#endif
Damiend99b0522013-12-21 18:17:45 +00001985
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001986// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001987const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001988 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001989 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001990 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001991 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001992 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001993 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001994 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001995 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001996 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001997};
1998
Damien Georgedfa563c2017-10-04 17:59:22 +11001999// The zero-length bytes object, with data that includes a null-terminating byte
2000const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte*)""};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02002001
Damien George77089be2015-01-21 23:08:36 +00002002// Create a str/bytes object using the given data. New memory is allocated and
Damien George1f1d5192017-11-16 13:53:04 +11002003// the data is copied across. This function should only be used if the type is bytes,
2004// or if the type is str and the string data is known to be not interned.
2005mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02002006 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002007 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002008 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02002009 if (data) {
2010 o->hash = qstr_compute_hash(data, len);
2011 byte *p = m_new(byte, len + 1);
2012 o->data = p;
2013 memcpy(p, data, len * sizeof(byte));
2014 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
2015 }
Damien George999cedb2015-11-27 17:01:44 +00002016 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002017}
2018
Damien George1f1d5192017-11-16 13:53:04 +11002019// Create a str/bytes object using the given data. If the type is str and the string
2020// data is already interned, then a qstr object is returned. Otherwise new memory is
2021// allocated for the object and the data is copied across.
2022mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
2023 if (type == &mp_type_str) {
2024 return mp_obj_new_str((const char*)data, len);
2025 } else {
2026 return mp_obj_new_bytes(data, len);
2027 }
2028}
2029
Damien George46017592017-11-16 13:17:51 +11002030// Create a str using a qstr to store the data; may use existing or new qstr.
2031mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len) {
2032 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
2033}
2034
Damien George77089be2015-01-21 23:08:36 +00002035// Create a str/bytes object from the given vstr. The vstr buffer is resized to
2036// the exact length required and then reused for the str/bytes object. The vstr
2037// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00002038mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
2039 // if not a bytes object, look if a qstr with this data already exists
2040 if (type == &mp_type_str) {
2041 qstr q = qstr_find_strn(vstr->buf, vstr->len);
Josh Lloyd7d58a192019-09-25 17:53:30 +12002042 if (q != MP_QSTRnull) {
Damien George0b9ee862015-01-21 19:14:25 +00002043 vstr_clear(vstr);
2044 vstr->alloc = 0;
2045 return MP_OBJ_NEW_QSTR(q);
2046 }
2047 }
2048
2049 // make a new str/bytes object
2050 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
2051 o->base.type = type;
2052 o->len = vstr->len;
2053 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07002054 if (vstr->len + 1 == vstr->alloc) {
2055 o->data = (byte*)vstr->buf;
2056 } else {
2057 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
2058 }
Damien George0d3cb672015-01-28 23:43:01 +00002059 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00002060 vstr->buf = NULL;
2061 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00002062 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00002063}
2064
Damien George46017592017-11-16 13:17:51 +11002065mp_obj_t mp_obj_new_str(const char* data, size_t len) {
2066 qstr q = qstr_find_strn(data, len);
Josh Lloyd7d58a192019-09-25 17:53:30 +12002067 if (q != MP_QSTRnull) {
Damien George46017592017-11-16 13:17:51 +11002068 // qstr with this data already exists
2069 return MP_OBJ_NEW_QSTR(q);
Damien George5fa93b62014-01-22 14:35:10 +00002070 } else {
Damien George46017592017-11-16 13:17:51 +11002071 // no existing qstr, don't make one
Damien George1f1d5192017-11-16 13:53:04 +11002072 return mp_obj_new_str_copy(&mp_type_str, (const byte*)data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002073 }
Damien George5fa93b62014-01-22 14:35:10 +00002074}
2075
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002076mp_obj_t mp_obj_str_intern(mp_obj_t str) {
2077 GET_STR_DATA_LEN(str, data, len);
Damien George46017592017-11-16 13:17:51 +11002078 return mp_obj_new_str_via_qstr((const char*)data, len);
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002079}
2080
Damien George32807882018-03-30 11:09:00 +11002081mp_obj_t mp_obj_str_intern_checked(mp_obj_t obj) {
2082 size_t len;
2083 const char *data = mp_obj_str_get_data(obj, &len);
2084 return mp_obj_new_str_via_qstr((const char*)data, len);
2085}
2086
Damien Georgec0d95002017-02-16 16:26:48 +11002087mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
Damien George1f1d5192017-11-16 13:53:04 +11002088 return mp_obj_new_str_copy(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002089}
2090
Damien George5fa93b62014-01-22 14:35:10 +00002091bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
Damien Georgeeee1e882019-01-30 18:49:52 +11002092 if (mp_obj_is_qstr(s1) && mp_obj_is_qstr(s2)) {
Damien George5fa93b62014-01-22 14:35:10 +00002093 return s1 == s2;
2094 } else {
2095 GET_STR_HASH(s1, h1);
2096 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03002097 // If any of hashes is 0, it means it's not valid
2098 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00002099 return false;
2100 }
2101 GET_STR_DATA_LEN(s1, d1, l1);
2102 GET_STR_DATA_LEN(s2, d2, l2);
2103 if (l1 != l2) {
2104 return false;
2105 }
Damien George1e708fe2014-01-23 18:27:51 +00002106 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002107 }
Damien George5fa93b62014-01-22 14:35:10 +00002108}
2109
Damien George3990a522017-11-29 15:43:40 +11002110STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002111 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03002112 mp_raise_TypeError("can't convert to str implicitly");
Damien George1e9a92f2014-11-06 17:36:16 +00002113 } else {
stijnbf29fe22017-03-15 12:17:38 +01002114 const qstr src_name = mp_obj_get_type(self_in)->name;
Damien George1e9a92f2014-11-06 17:36:16 +00002115 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
stijnbf29fe22017-03-15 12:17:38 +01002116 "can't convert '%q' object to %q implicitly",
2117 src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str));
Damien George1e9a92f2014-11-06 17:36:16 +00002118 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002119}
2120
Damien Georgeb829b5c2014-01-25 13:51:19 +00002121// use this if you will anyway convert the string to a qstr
2122// will be more efficient for the case where it's already a qstr
2123qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
Damien Georgeeee1e882019-01-30 18:49:52 +11002124 if (mp_obj_is_qstr(self_in)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002125 return MP_OBJ_QSTR_VALUE(self_in);
Damien Georgeeee1e882019-01-30 18:49:52 +11002126 } else if (mp_obj_is_type(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002127 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002128 return qstr_from_strn((char*)self->data, self->len);
2129 } else {
2130 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002131 }
2132}
2133
2134// only use this function if you need the str data to be zero terminated
2135// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2136const char *mp_obj_str_get_str(mp_obj_t self_in) {
Damien Georgeeee1e882019-01-30 18:49:52 +11002137 if (mp_obj_is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002138 GET_STR_DATA_LEN(self_in, s, l);
2139 (void)l; // len unused
2140 return (const char*)s;
2141 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002142 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002143 }
2144}
2145
Damien George6b341072017-03-25 19:48:18 +11002146const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
Damien Georgeeee1e882019-01-30 18:49:52 +11002147 if (mp_obj_is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002148 GET_STR_DATA_LEN(self_in, s, l);
2149 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002150 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002151 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002152 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002153 }
Damiend99b0522013-12-21 18:17:45 +00002154}
xyb8cfc9f02014-01-05 18:47:51 +08002155
Damien George4c0176d2019-12-27 23:15:52 +11002156#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D
Damien Georgec3f64d92015-11-27 12:23:18 +00002157const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien Georgeeee1e882019-01-30 18:49:52 +11002158 if (mp_obj_is_qstr(self_in)) {
Damien George04353cc2015-10-18 23:09:04 +01002159 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2160 } else {
Damien George4c0176d2019-12-27 23:15:52 +11002161 *len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(self_in))->len;
2162 return ((mp_obj_str_t*)MP_OBJ_TO_PTR(self_in))->data;
Damien George04353cc2015-10-18 23:09:04 +01002163 }
2164}
2165#endif
2166
xyb8cfc9f02014-01-05 18:47:51 +08002167/******************************************************************************/
2168/* str iterator */
2169
Damien George44e7cbf2015-05-17 16:44:24 +01002170typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002171 mp_obj_base_t base;
Damien George8212d972016-01-03 16:27:55 +00002172 mp_fun_1_t iternext;
Damien George5fa93b62014-01-22 14:35:10 +00002173 mp_obj_t str;
Damien Georgec0d95002017-02-16 16:26:48 +11002174 size_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002175} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002176
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002177#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002178STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George326e8862017-06-08 00:40:38 +10002179 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002180 GET_STR_DATA_LEN(self->str, str, len);
2181 if (self->cur < len) {
Damien George46017592017-11-16 13:17:51 +11002182 mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)str + self->cur, 1);
xyb8cfc9f02014-01-05 18:47:51 +08002183 self->cur += 1;
2184 return o_out;
2185 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002186 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002187 }
2188}
2189
Damien Georgeae8d8672016-01-09 23:14:54 +00002190STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2191 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2192 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002193 o->base.type = &mp_type_polymorph_iter;
2194 o->iternext = str_it_iternext;
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002195 o->str = str;
2196 o->cur = 0;
Damien George326e8862017-06-08 00:40:38 +10002197 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002198}
2199#endif
2200
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002201STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002202 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002203 GET_STR_DATA_LEN(self->str, str, len);
2204 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002205 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002206 self->cur += 1;
2207 return o_out;
2208 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002209 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002210 }
2211}
2212
Damien Georgeae8d8672016-01-09 23:14:54 +00002213mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2214 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2215 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002216 o->base.type = &mp_type_polymorph_iter;
2217 o->iternext = bytes_it_iternext;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002218 o->str = str;
2219 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002220 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002221}