blob: cea10770c8d43d2e9a3da706ab57c9468839c193 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 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/nlr.h"
32#include "py/unicode.h"
33#include "py/objstr.h"
34#include "py/objlist.h"
35#include "py/runtime0.h"
36#include "py/runtime.h"
pohmeliee3a29de2016-01-29 12:09:10 +030037#include "py/stackctrl.h"
Damiend99b0522013-12-21 18:17:45 +000038
Damien George90ab1912017-02-03 13:04:56 +110039STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
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 Georgecde0ca22014-09-25 17:35:56 +0100121 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
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200158 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
159 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 }
Damien George5b3f0b72016-01-03 15:55:55 +0000164 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(type, NULL, str_len));
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200165 o->data = str_data;
166 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000167 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200168 } else {
169 mp_buffer_info_t bufinfo;
170 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
171 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200172 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200173 }
174}
175
Damien George5b3f0b72016-01-03 15:55:55 +0000176STATIC 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 +0000177 (void)type_in;
178
Damien George3a2171e2015-09-04 16:53:46 +0100179 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300180 if (n_kw != 0) {
181 mp_arg_error_unimpl_kw();
182 }
Damien George3a2171e2015-09-04 16:53:46 +0100183 #else
184 (void)n_kw;
185 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300186
Damien George42cec5c2015-09-04 16:51:55 +0100187 if (n_args == 0) {
188 return mp_const_empty_bytes;
189 }
190
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200191 if (MP_OBJ_IS_STR(args[0])) {
192 if (n_args < 2 || n_args > 3) {
193 goto wrong_args;
194 }
195 GET_STR_DATA_LEN(args[0], str_data, str_len);
196 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000197 if (str_hash == 0) {
198 str_hash = qstr_compute_hash(str_data, str_len);
199 }
Damien George999cedb2015-11-27 17:01:44 +0000200 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200201 o->data = str_data;
202 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000203 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200204 }
205
206 if (n_args > 1) {
207 goto wrong_args;
208 }
209
210 if (MP_OBJ_IS_SMALL_INT(args[0])) {
211 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000212 vstr_t vstr;
213 vstr_init_len(&vstr, len);
214 memset(vstr.buf, 0, len);
215 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 }
217
Damien George32ef3a32014-12-04 15:46:14 +0000218 // check if argument has the buffer protocol
219 mp_buffer_info_t bufinfo;
220 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
221 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
222 }
223
Damien George0b9ee862015-01-21 19:14:25 +0000224 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200225 // Try to create array of exact len if initializer len is known
226 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
227 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000228 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200229 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000230 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000231 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200232 }
233
Damien Georgeae8d8672016-01-09 23:14:54 +0000234 mp_obj_iter_buf_t iter_buf;
235 mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200236 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100237 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100238 mp_int_t val = mp_obj_get_int(item);
Paul Sokolovsky9a973972017-04-02 21:20:07 +0300239 #if MICROPY_FULL_CHECKS
Damien Georgeede0f3a2015-04-23 15:28:18 +0100240 if (val < 0 || val > 255) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300241 mp_raise_ValueError("bytes value out of range");
Damien Georgeede0f3a2015-04-23 15:28:18 +0100242 }
243 #endif
244 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200245 }
246
Damien George0b9ee862015-01-21 19:14:25 +0000247 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200248
249wrong_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300250 mp_raise_TypeError("wrong number of arguments");
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200251}
252
Damien George55baff42014-01-21 21:40:13 +0000253// like strstr but with specified length and allows \0 bytes
254// TODO replace with something more efficient/standard
Damien Georgec0d95002017-02-16 16:26:48 +1100255const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
Damien George55baff42014-01-21 21:40:13 +0000256 if (hlen >= nlen) {
Damien Georgec0d95002017-02-16 16:26:48 +1100257 size_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700258 if (direction > 0) {
259 str_index = 0;
260 str_index_end = hlen - nlen;
261 } else {
262 str_index = hlen - nlen;
263 str_index_end = 0;
264 }
265 for (;;) {
266 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
267 //found
268 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000269 }
xbe17a5a832014-03-23 23:31:58 -0700270 if (str_index == str_index_end) {
271 //not found
272 break;
Damien George55baff42014-01-21 21:40:13 +0000273 }
xbe17a5a832014-03-23 23:31:58 -0700274 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000275 }
276 }
277 return NULL;
278}
279
Damien Georgea75b02e2014-08-27 09:20:30 +0100280// Note: this function is used to check if an object is a str or bytes, which
281// works because both those types use it as their binary_op method. Revisit
282// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100283mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000284 // check for modulo
285 if (op == MP_BINARY_OP_MODULO) {
Damien George7317e342017-02-03 12:13:44 +1100286 mp_obj_t *args = &rhs_in;
Damien George6213ad72017-03-25 19:35:08 +1100287 size_t n_args = 1;
Damien Georgea65c03c2014-11-05 16:30:34 +0000288 mp_obj_t dict = MP_OBJ_NULL;
289 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
290 // TODO: Support tuple subclasses?
291 mp_obj_tuple_get(rhs_in, &n_args, &args);
292 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000293 dict = rhs_in;
Damien Georgea65c03c2014-11-05 16:30:34 +0000294 }
295 return str_modulo_format(lhs_in, n_args, args, dict);
296 }
297
298 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300299 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000300 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
301
302 // check for multiply
303 if (op == MP_BINARY_OP_MULTIPLY) {
304 mp_int_t n;
305 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
306 return MP_OBJ_NULL; // op not supported
307 }
308 if (n <= 0) {
309 if (lhs_type == &mp_type_str) {
310 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
311 } else {
312 return mp_const_empty_bytes;
313 }
314 }
Damien George05005f62015-01-21 22:48:37 +0000315 vstr_t vstr;
316 vstr_init_len(&vstr, lhs_len * n);
317 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
318 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000319 }
320
321 // From now on all operations allow:
322 // - str with str
323 // - bytes with bytes
324 // - bytes with bytearray
325 // - bytes with array.array
326 // To do this efficiently we use the buffer protocol to extract the raw
327 // data for the rhs, but only if the lhs is a bytes object.
328 //
329 // NOTE: CPython does not allow comparison between bytes ard array.array
330 // (even if the array is of type 'b'), even though it allows addition of
331 // such types. We are not compatible with this (we do allow comparison
332 // of bytes with anything that has the buffer protocol). It would be
333 // easy to "fix" this with a bit of extra logic below, but it costs code
334 // size and execution time so we don't.
335
336 const byte *rhs_data;
Damien Georgec0d95002017-02-16 16:26:48 +1100337 size_t rhs_len;
Damien Georgea65c03c2014-11-05 16:30:34 +0000338 if (lhs_type == mp_obj_get_type(rhs_in)) {
339 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
340 rhs_data = rhs_data_;
341 rhs_len = rhs_len_;
342 } else if (lhs_type == &mp_type_bytes) {
343 mp_buffer_info_t bufinfo;
344 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000345 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000346 }
347 rhs_data = bufinfo.buf;
348 rhs_len = bufinfo.len;
349 } else {
350 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000351 return MP_OBJ_NULL; // op not supported
352 }
353
Damiend99b0522013-12-21 18:17:45 +0000354 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100355 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000356 case MP_BINARY_OP_INPLACE_ADD: {
Damien Georged279bcf2017-03-16 14:30:04 +1100357 if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
Paul Sokolovskye2e66322017-01-27 00:40:47 +0300358 return rhs_in;
359 }
360 if (rhs_len == 0) {
361 return lhs_in;
362 }
363
Damien George05005f62015-01-21 22:48:37 +0000364 vstr_t vstr;
365 vstr_init_len(&vstr, lhs_len + rhs_len);
366 memcpy(vstr.buf, lhs_data, lhs_len);
367 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
368 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200369 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200370
Damien Georgea65c03c2014-11-05 16:30:34 +0000371 case MP_BINARY_OP_IN:
372 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300373 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300374
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300375 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
376 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 +0100377 case MP_BINARY_OP_LESS:
378 case MP_BINARY_OP_LESS_EQUAL:
379 case MP_BINARY_OP_MORE:
380 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300381 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000382 }
383
Damien George6ac5dce2014-05-21 19:42:43 +0100384 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000385}
386
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300387#if !MICROPY_PY_BUILTINS_STR_UNICODE
388// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000389const 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 +0300390 mp_obj_t index, bool is_slice) {
Damien Georgec88cfe12017-03-23 16:17:40 +1100391 size_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300392 return self_data + index_val;
393}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300394#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300395
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300396// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
397STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300398 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100399 GET_STR_DATA_LEN(self_in, self_data, self_len);
400 if (value == MP_OBJ_SENTINEL) {
401 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100402#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100403 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300404 mp_bound_slice_t slice;
405 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Damien George821b7f22015-09-03 23:14:06 +0100406 mp_not_implemented("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100407 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100408 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100409 }
410#endif
Damien Georgec88cfe12017-03-23 16:17:40 +1100411 size_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100412 // If we have unicode enabled the type will always be bytes, so take the short cut.
413 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300414 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100415 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300416 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100417 }
418 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100419 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100420 }
421}
422
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200423STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300424 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300425 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000426
Damien Georgefe8fb912014-01-02 16:36:09 +0000427 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000428 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000429
430 // process args
Damien George6213ad72017-03-25 19:35:08 +1100431 size_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000432 mp_obj_t *seq_items;
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100433
434 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list) && !MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
435 // arg is not a list nor a tuple, try to convert it to a list
436 // TODO: Try to optimize?
437 arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
Damiend99b0522013-12-21 18:17:45 +0000438 }
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100439 mp_obj_get_array(arg, &seq_len, &seq_items);
Damien Georgefe8fb912014-01-02 16:36:09 +0000440
441 // count required length
Damien Georgec0d95002017-02-16 16:26:48 +1100442 size_t required_len = 0;
443 for (size_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300444 if (mp_obj_get_type(seq_items[i]) != self_type) {
Damien George21967992016-08-14 16:51:54 +1000445 mp_raise_TypeError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300446 "join expects a list of str/bytes objects consistent with self object");
Damiend99b0522013-12-21 18:17:45 +0000447 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000448 if (i > 0) {
449 required_len += sep_len;
450 }
Damien George5fa93b62014-01-22 14:35:10 +0000451 GET_STR_LEN(seq_items[i], l);
452 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000453 }
454
455 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000456 vstr_t vstr;
457 vstr_init_len(&vstr, required_len);
458 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +1100459 for (size_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000460 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000461 memcpy(data, sep_str, sep_len);
462 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000463 }
Damien George5fa93b62014-01-22 14:35:10 +0000464 GET_STR_DATA_LEN(seq_items[i], s, l);
465 memcpy(data, s, l);
466 data += l;
Damiend99b0522013-12-21 18:17:45 +0000467 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000468
469 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000470 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000471}
Damien George65417c52017-07-02 23:35:42 +1000472MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Damiend99b0522013-12-21 18:17:45 +0000473
Damien Georgecc80c4d2016-05-13 12:21:32 +0100474mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300475 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100476 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200477 mp_obj_t sep = mp_const_none;
478 if (n_args > 1) {
479 sep = args[1];
480 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100481 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200482 }
483 }
Damien Georgedeed0872014-04-06 11:11:15 +0100484
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200485 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000486 GET_STR_DATA_LEN(args[0], s, len);
487 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200488
Damien Georgedeed0872014-04-06 11:11:15 +0100489 if (sep == mp_const_none) {
490 // sep not given, so separate on whitespace
491
492 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300493 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100494 while (s < top && splits != 0) {
495 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300496 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100497 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100498 if (s >= top) {
499 break;
500 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300501 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100502 if (splits > 0) {
503 splits--;
504 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200505 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200506
Damien Georgedeed0872014-04-06 11:11:15 +0100507 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100508 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100509 }
510
511 } else {
512 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300513 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000514 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300515 }
Damien Georgedeed0872014-04-06 11:11:15 +0100516
Damien George6b341072017-03-25 19:48:18 +1100517 size_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100518 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
519
520 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300521 mp_raise_ValueError("empty separator");
Damien Georgedeed0872014-04-06 11:11:15 +0100522 }
523
524 for (;;) {
525 const byte *start = s;
526 for (;;) {
527 if (splits == 0 || s + sep_len > top) {
528 s = top;
529 break;
530 } else if (memcmp(s, sep_str, sep_len) == 0) {
531 break;
532 }
533 s++;
534 }
Damien Georgecc80c4d2016-05-13 12:21:32 +0100535 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100536 if (s >= top) {
537 break;
538 }
539 s += sep_len;
540 if (splits > 0) {
541 splits--;
542 }
543 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200544 }
545
546 return res;
547}
Damien George65417c52017-07-02 23:35:42 +1000548MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200549
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300550#if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien George4b72b3a2016-01-03 14:21:40 +0000551STATIC 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 +0100552 enum { ARG_keepends };
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300553 static const mp_arg_t allowed_args[] = {
554 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
555 };
556
557 // parse args
Damien Georgecc80c4d2016-05-13 12:21:32 +0100558 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
559 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 +0300560
Damien Georgecc80c4d2016-05-13 12:21:32 +0100561 const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
562 mp_obj_t res = mp_obj_new_list(0, NULL);
563
564 GET_STR_DATA_LEN(pos_args[0], s, len);
565 const byte *top = s + len;
566
567 while (s < top) {
568 const byte *start = s;
569 size_t match = 0;
570 while (s < top) {
571 if (*s == '\n') {
572 match = 1;
573 break;
574 } else if (*s == '\r') {
575 if (s[1] == '\n') {
576 match = 2;
577 } else {
578 match = 1;
579 }
580 break;
581 }
582 s++;
583 }
584 size_t sub_len = s - start;
585 if (args[ARG_keepends].u_bool) {
586 sub_len += match;
587 }
588 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
589 s += match;
590 }
591
592 return res;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300593}
Damien George65417c52017-07-02 23:35:42 +1000594MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300595#endif
596
Damien George4b72b3a2016-01-03 14:21:40 +0000597STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300598 if (n_args < 3) {
599 // If we don't have split limit, it doesn't matter from which side
600 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200601 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300602 }
603 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
604 mp_obj_t sep = args[1];
605 GET_STR_DATA_LEN(args[0], s, len);
606
Damien George40f3c022014-07-03 13:25:24 +0100607 mp_int_t splits = mp_obj_get_int(args[2]);
Damien George9f85c4f2017-06-02 13:07:22 +1000608 if (splits < 0) {
609 // Negative limit means no limit, so delegate to split().
610 return mp_obj_str_split(n_args, args);
611 }
612
Damien George40f3c022014-07-03 13:25:24 +0100613 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300614 // Preallocate list to the max expected # of elements, as we
615 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000616 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100617 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300618
619 if (sep == mp_const_none) {
Damien George22602cc2015-09-01 15:35:31 +0100620 mp_not_implemented("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300621 } else {
Damien George6b341072017-03-25 19:48:18 +1100622 size_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300623 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
624
625 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300626 mp_raise_ValueError("empty separator");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300627 }
628
629 const byte *beg = s;
630 const byte *last = s + len;
631 for (;;) {
632 s = last - sep_len;
633 for (;;) {
634 if (splits == 0 || s < beg) {
635 break;
636 } else if (memcmp(s, sep_str, sep_len) == 0) {
637 break;
638 }
639 s--;
640 }
641 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100642 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300643 break;
644 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100645 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 +0300646 last = s;
647 if (splits > 0) {
648 splits--;
649 }
650 }
651 if (idx != 0) {
652 // We split less parts than split limit, now go cleanup surplus
Damien Georgec0d95002017-02-16 16:26:48 +1100653 size_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100654 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300655 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
656 res->len = used;
657 }
658 }
659
Damien George999cedb2015-11-27 17:01:44 +0000660 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300661}
Damien George65417c52017-07-02 23:35:42 +1000662MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300663
Damien Georgec0d95002017-02-16 16:26:48 +1100664STATIC 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 +0300665 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300666 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +0000667
668 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000669 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000670 bad_implicit_conversion(args[1]);
671 }
John R. Lentone8204912014-01-12 21:53:52 +0000672
Damien George5fa93b62014-01-22 14:35:10 +0000673 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
674 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000675
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300676 const byte *start = haystack;
677 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000678 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300679 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000680 }
681 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300682 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000683 }
684
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300685 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000686 if (p == NULL) {
687 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700688 if (is_index) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300689 mp_raise_ValueError("substring not found");
xbe3d9a39e2014-04-08 11:42:19 -0700690 } else {
691 return MP_OBJ_NEW_SMALL_INT(-1);
692 }
Damien George23005372014-01-13 19:39:01 +0000693 } else {
694 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300695 #if MICROPY_PY_BUILTINS_STR_UNICODE
696 if (self_type == &mp_type_str) {
697 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
698 }
699 #endif
xbe17a5a832014-03-23 23:31:58 -0700700 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000701 }
John R. Lentone8204912014-01-12 21:53:52 +0000702}
703
Damien George4b72b3a2016-01-03 14:21:40 +0000704STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700705 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700706}
Damien George65417c52017-07-02 23:35:42 +1000707MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -0700708
Damien George4b72b3a2016-01-03 14:21:40 +0000709STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700710 return str_finder(n_args, args, -1, false);
711}
Damien George65417c52017-07-02 23:35:42 +1000712MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -0700713
Damien George4b72b3a2016-01-03 14:21:40 +0000714STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700715 return str_finder(n_args, args, 1, true);
716}
Damien George65417c52017-07-02 23:35:42 +1000717MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
xbe3d9a39e2014-04-08 11:42:19 -0700718
Damien George4b72b3a2016-01-03 14:21:40 +0000719STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700720 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700721}
Damien George65417c52017-07-02 23:35:42 +1000722MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
xbe17a5a832014-03-23 23:31:58 -0700723
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200724// TODO: (Much) more variety in args
Damien George4b72b3a2016-01-03 14:21:40 +0000725STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300726 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300727 GET_STR_DATA_LEN(args[0], str, str_len);
728 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300729 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300730 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300731 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300732 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300733 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200734 return mp_const_false;
735 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300736 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200737}
Damien George65417c52017-07-02 23:35:42 +1000738MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200739
Damien George4b72b3a2016-01-03 14:21:40 +0000740STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300741 GET_STR_DATA_LEN(args[0], str, str_len);
742 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100743 if (n_args > 2) {
744 mp_not_implemented("start/end indices");
745 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300746
747 if (suffix_len > str_len) {
748 return mp_const_false;
749 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300750 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300751}
Damien George65417c52017-07-02 23:35:42 +1000752MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300753
Paul Sokolovsky88107842014-04-26 06:20:08 +0300754enum { LSTRIP, RSTRIP, STRIP };
755
Damien George90ab1912017-02-03 13:04:56 +1100756STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300757 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300758 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000759
760 const byte *chars_to_del;
761 uint chars_to_del_len;
762 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800763
764 if (n_args == 1) {
765 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000766 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800767 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300768 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000769 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300770 }
Damien George5fa93b62014-01-22 14:35:10 +0000771 GET_STR_DATA_LEN(args[1], s, l);
772 chars_to_del = s;
773 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800774 }
775
Damien George5fa93b62014-01-22 14:35:10 +0000776 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800777
Damien Georgec0d95002017-02-16 16:26:48 +1100778 size_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800779 bool first_good_char_pos_set = false;
Damien Georgec0d95002017-02-16 16:26:48 +1100780 size_t last_good_char_pos = 0;
781 size_t i = 0;
782 int delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300783 if (type == RSTRIP) {
784 i = orig_str_len - 1;
785 delta = -1;
786 }
Damien Georgec0d95002017-02-16 16:26:48 +1100787 for (size_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700788 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800789 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300790 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800791 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300792 if (type == LSTRIP) {
793 last_good_char_pos = orig_str_len - 1;
794 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300795 } else if (type == RSTRIP) {
796 first_good_char_pos = 0;
797 last_good_char_pos = i;
798 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300799 }
xbe7b0f39f2014-01-08 14:23:45 -0800800 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300801 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800802 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300803 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800804 }
805
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300806 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000807 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000808 if (self_type == &mp_type_str) {
809 return MP_OBJ_NEW_QSTR(MP_QSTR_);
810 } else {
811 return mp_const_empty_bytes;
812 }
xbe7b0f39f2014-01-08 14:23:45 -0800813 }
814
815 assert(last_good_char_pos >= first_good_char_pos);
Ville Skyttäca16c382017-05-29 10:08:14 +0300816 //+1 to accommodate the last character
Damien Georgec0d95002017-02-16 16:26:48 +1100817 size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300818 if (stripped_len == orig_str_len) {
819 // If nothing was stripped, don't bother to dup original string
820 // TODO: watch out for this case when we'll get to bytearray.strip()
821 assert(first_good_char_pos == 0);
822 return args[0];
823 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100824 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800825}
826
Damien George4b72b3a2016-01-03 14:21:40 +0000827STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300828 return str_uni_strip(STRIP, n_args, args);
829}
Damien George65417c52017-07-02 23:35:42 +1000830MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300831
Damien George4b72b3a2016-01-03 14:21:40 +0000832STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300833 return str_uni_strip(LSTRIP, n_args, args);
834}
Damien George65417c52017-07-02 23:35:42 +1000835MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300836
Damien George4b72b3a2016-01-03 14:21:40 +0000837STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300838 return str_uni_strip(RSTRIP, n_args, args);
839}
Damien George65417c52017-07-02 23:35:42 +1000840MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300841
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300842#if MICROPY_PY_BUILTINS_STR_CENTER
843STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
844 GET_STR_DATA_LEN(str_in, str, str_len);
Paul Sokolovsky9dde6062016-05-22 02:22:14 +0300845 mp_uint_t width = mp_obj_get_int(width_in);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300846 if (str_len >= width) {
847 return str_in;
848 }
849
850 vstr_t vstr;
851 vstr_init_len(&vstr, width);
852 memset(vstr.buf, ' ', width);
853 int left = (width - str_len) / 2;
854 memcpy(vstr.buf + left, str, str_len);
855 return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
856}
Damien George65417c52017-07-02 23:35:42 +1000857MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300858#endif
859
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860// Takes an int arg, but only parses unsigned numbers, and only changes
861// *num if at least one digit was parsed.
Damien George87e07ea2016-02-02 15:51:57 +0000862STATIC const char *str_to_int(const char *str, const char *top, int *num) {
863 if (str < top && '0' <= *str && *str <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700864 *num = 0;
865 do {
Damien George87e07ea2016-02-02 15:51:57 +0000866 *num = *num * 10 + (*str - '0');
867 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700868 }
Damien George87e07ea2016-02-02 15:51:57 +0000869 while (str < top && '0' <= *str && *str <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700870 }
Damien George87e07ea2016-02-02 15:51:57 +0000871 return str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872}
873
Damien George2801e6f2015-04-04 15:53:11 +0100874STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700875 return ch && strchr("<>=^", ch) != NULL;
876}
877
Damien George2801e6f2015-04-04 15:53:11 +0100878STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700879 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
880}
881
Damien George2801e6f2015-04-04 15:53:11 +0100882STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700883 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
884}
885
Damien George2801e6f2015-04-04 15:53:11 +0100886STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700887 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100888#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100889 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700890#endif
891 ;
892}
893
Damien George2801e6f2015-04-04 15:53:11 +0100894STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100895#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100896 if (mp_obj_is_float(arg)) {
897 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700898 }
899#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700900 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700901}
902
Damien George897129a2016-09-27 15:45:42 +1000903#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
Damien George1e9a92f2014-11-06 17:36:16 +0000904STATIC NORETURN void terse_str_format_value_error(void) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300905 mp_raise_ValueError("bad format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000906}
Damien George897129a2016-09-27 15:45:42 +1000907#else
908// define to nothing to improve coverage
909#define terse_str_format_value_error()
910#endif
Damien George1e9a92f2014-11-06 17:36:16 +0000911
Damien George90ab1912017-02-03 13:04:56 +1100912STATIC 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 +0000913 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100914 mp_print_t print;
915 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700916
pohmeliee3a29de2016-01-29 12:09:10 +0300917 for (; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700918 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000919 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700920 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100921 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700922 continue;
923 }
Damien George1e9a92f2014-11-06 17:36:16 +0000924 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
925 terse_str_format_value_error();
926 } else {
Damien George21967992016-08-14 16:51:54 +1000927 mp_raise_ValueError("single '}' encountered in format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000928 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700929 }
930 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100931 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700932 continue;
933 }
934
935 str++;
936 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100937 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700938 continue;
939 }
940
941 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
942
Damien George87e07ea2016-02-02 15:51:57 +0000943 const char *field_name = NULL;
944 const char *field_name_top = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700945 char conversion = '\0';
pohmeliee3a29de2016-01-29 12:09:10 +0300946 const char *format_spec = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700947
948 if (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000949 field_name = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700950 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000951 ++str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700952 }
Damien George87e07ea2016-02-02 15:51:57 +0000953 field_name_top = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700954 }
955
956 // conversion ::= "r" | "s"
957
958 if (str < top && *str == '!') {
959 str++;
960 if (str < top && (*str == 'r' || *str == 's')) {
961 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200962 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000963 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
964 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100965 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300966 mp_raise_ValueError("bad conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100967 } else {
968 if (str >= top) {
Damien George21967992016-08-14 16:51:54 +1000969 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300970 "end of format while looking for conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100971 } else {
972 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
973 "unknown conversion specifier %c", *str));
974 }
Damien George1e9a92f2014-11-06 17:36:16 +0000975 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700976 }
977 }
978
979 if (str < top && *str == ':') {
980 str++;
981 // {:} is the same as {}, which is the same as {!s}
982 // This makes a difference when passing in a True or False
983 // '{}'.format(True) returns 'True'
984 // '{:d}'.format(True) returns '1'
985 // So we treat {:} as {} and this later gets treated to be {!s}
986 if (*str != '}') {
pohmeliee3a29de2016-01-29 12:09:10 +0300987 format_spec = str;
988 for (int nest = 1; str < top;) {
989 if (*str == '{') {
990 ++nest;
991 } else if (*str == '}') {
992 if (--nest == 0) {
993 break;
994 }
995 }
996 ++str;
Damiend99b0522013-12-21 18:17:45 +0000997 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700998 }
999 }
1000 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001001 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1002 terse_str_format_value_error();
1003 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001004 mp_raise_ValueError("unmatched '{' in format");
Damien George1e9a92f2014-11-06 17:36:16 +00001005 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001006 }
1007 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +00001008 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1009 terse_str_format_value_error();
1010 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001011 mp_raise_ValueError("expected ':' after format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001012 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001013 }
1014
1015 mp_obj_t arg = mp_const_none;
1016
1017 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +01001018 int index = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001019 if (MP_LIKELY(unichar_isdigit(*field_name))) {
pohmeliee3a29de2016-01-29 12:09:10 +03001020 if (*arg_i > 0) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001021 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1022 terse_str_format_value_error();
1023 } else {
Damien George21967992016-08-14 16:51:54 +10001024 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001025 "can't switch from automatic field numbering to manual field specification");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001026 }
1027 }
Damien George87e07ea2016-02-02 15:51:57 +00001028 field_name = str_to_int(field_name, field_name_top, &index);
Damien George963a5a32015-01-16 17:47:07 +00001029 if ((uint)index >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001030 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001031 }
1032 arg = args[index + 1];
pohmeliee3a29de2016-01-29 12:09:10 +03001033 *arg_i = -1;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001034 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001035 const char *lookup;
1036 for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
1037 mp_obj_t field_q = mp_obj_new_str(field_name, lookup - field_name, true/*?*/);
1038 field_name = lookup;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001039 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
1040 if (key_elem == NULL) {
1041 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
1042 }
1043 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001044 }
Damien George87e07ea2016-02-02 15:51:57 +00001045 if (field_name < field_name_top) {
Damien George821b7f22015-09-03 23:14:06 +01001046 mp_not_implemented("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001047 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001048 } else {
pohmeliee3a29de2016-01-29 12:09:10 +03001049 if (*arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +00001050 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1051 terse_str_format_value_error();
1052 } else {
Damien George21967992016-08-14 16:51:54 +10001053 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001054 "can't switch from manual field specification to automatic field numbering");
Damien George1e9a92f2014-11-06 17:36:16 +00001055 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001056 }
pohmeliee3a29de2016-01-29 12:09:10 +03001057 if ((uint)*arg_i >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001058 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001059 }
pohmeliee3a29de2016-01-29 12:09:10 +03001060 arg = args[(*arg_i) + 1];
1061 (*arg_i)++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001062 }
1063 if (!format_spec && !conversion) {
1064 conversion = 's';
1065 }
1066 if (conversion) {
1067 mp_print_kind_t print_kind;
1068 if (conversion == 's') {
1069 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001070 } else {
Damien George000730e2015-08-30 12:43:21 +01001071 assert(conversion == 'r');
1072 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001073 }
Damien George0b9ee862015-01-21 19:14:25 +00001074 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001075 mp_print_t arg_print;
1076 vstr_init_print(&arg_vstr, 16, &arg_print);
1077 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001078 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001079 }
1080
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001081 char fill = '\0';
1082 char align = '\0';
1083 int width = -1;
1084 int precision = -1;
1085 char type = '\0';
1086 int flags = 0;
1087
1088 if (format_spec) {
1089 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1090 //
1091 // [[fill]align][sign][#][0][width][,][.precision][type]
1092 // fill ::= <any character>
1093 // align ::= "<" | ">" | "=" | "^"
1094 // sign ::= "+" | "-" | " "
1095 // width ::= integer
1096 // precision ::= integer
1097 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1098
pohmeliee3a29de2016-01-29 12:09:10 +03001099 // recursively call the formatter to format any nested specifiers
1100 MP_STACK_CHECK();
1101 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 +03001102 const char *s = vstr_null_terminated_str(&format_spec_vstr);
Damien George87e07ea2016-02-02 15:51:57 +00001103 const char *stop = s + format_spec_vstr.len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001104 if (isalignment(*s)) {
1105 align = *s++;
1106 } else if (*s && isalignment(s[1])) {
1107 fill = *s++;
1108 align = *s++;
1109 }
1110 if (*s == '+' || *s == '-' || *s == ' ') {
1111 if (*s == '+') {
1112 flags |= PF_FLAG_SHOW_SIGN;
1113 } else if (*s == ' ') {
1114 flags |= PF_FLAG_SPACE_SIGN;
1115 }
Damien George9d2c72a2017-07-04 02:13:27 +10001116 s++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001117 }
1118 if (*s == '#') {
1119 flags |= PF_FLAG_SHOW_PREFIX;
1120 s++;
1121 }
1122 if (*s == '0') {
1123 if (!align) {
1124 align = '=';
1125 }
1126 if (!fill) {
1127 fill = '0';
1128 }
1129 }
Damien George87e07ea2016-02-02 15:51:57 +00001130 s = str_to_int(s, stop, &width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001131 if (*s == ',') {
1132 flags |= PF_FLAG_SHOW_COMMA;
1133 s++;
1134 }
1135 if (*s == '.') {
1136 s++;
Damien George87e07ea2016-02-02 15:51:57 +00001137 s = str_to_int(s, stop, &precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001138 }
1139 if (istype(*s)) {
1140 type = *s++;
1141 }
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001142 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001143 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1144 terse_str_format_value_error();
1145 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001146 mp_raise_ValueError("invalid format specifier");
Damien George7ef75f92015-08-26 15:42:25 +01001147 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001148 }
pohmeliee3a29de2016-01-29 12:09:10 +03001149 vstr_clear(&format_spec_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 }
1151 if (!align) {
1152 if (arg_looks_numeric(arg)) {
1153 align = '>';
1154 } else {
1155 align = '<';
1156 }
1157 }
1158 if (!fill) {
1159 fill = ' ';
1160 }
1161
Damien George9d2c72a2017-07-04 02:13:27 +10001162 if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001163 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001164 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1165 terse_str_format_value_error();
1166 } else {
Damien George21967992016-08-14 16:51:54 +10001167 mp_raise_ValueError("sign not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001168 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001169 }
1170 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001171 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1172 terse_str_format_value_error();
1173 } else {
Damien George21967992016-08-14 16:51:54 +10001174 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001175 "sign not allowed with integer format specifier 'c'");
Damien George1e9a92f2014-11-06 17:36:16 +00001176 }
Damiend99b0522013-12-21 18:17:45 +00001177 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001178 }
1179
1180 switch (align) {
1181 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1182 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1183 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1184 }
1185
1186 if (arg_looks_integer(arg)) {
1187 switch (type) {
1188 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001189 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001190 continue;
1191
1192 case 'c':
1193 {
1194 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001195 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001196 continue;
1197 }
1198
1199 case '\0': // No explicit format type implies 'd'
1200 case 'n': // I don't think we support locales in uPy so use 'd'
1201 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001202 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001203 continue;
1204
1205 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001206 if (flags & PF_FLAG_SHOW_PREFIX) {
1207 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1208 }
1209
Damien George7f9d1d62015-04-09 23:56:15 +01001210 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001211 continue;
1212
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001213 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001214 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001215 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001216 continue;
1217
1218 case 'e':
1219 case 'E':
1220 case 'f':
1221 case 'F':
1222 case 'g':
1223 case 'G':
1224 case '%':
1225 // The floating point formatters all work with anything that
1226 // looks like an integer
1227 break;
1228
1229 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001230 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1231 terse_str_format_value_error();
1232 } else {
1233 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1234 "unknown format code '%c' for object of type '%s'",
1235 type, mp_obj_get_type_str(arg)));
1236 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001237 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001238 }
Damien George70f33cd2014-04-02 17:06:05 +01001239
Dave Hylands22fe4d72014-04-02 12:07:31 -07001240 // NOTE: no else here. We need the e, f, g etc formats for integer
1241 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001242 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001243 if (!type) {
1244
1245 // Even though the docs say that an unspecified type is the same
1246 // as 'g', there is one subtle difference, when the exponent
1247 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001248 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001249 // '{:10.1}'.format(0.0) ==> '0e+00'
1250 // '{:10.1g}'.format(0.0) ==> '0'
1251 //
1252 // TODO: Figure out how to deal with this.
1253 //
1254 // A proper solution would involve adding a special flag
1255 // or something to format_float, and create a format_double
1256 // to deal with doubles. In order to fix this when using
1257 // sprintf, we'd need to use the e format and tweak the
1258 // returned result to strip trailing zeros like the g format
1259 // does.
1260 //
1261 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1262 // but with 1.e2 you get 1e+02 and 1.00e+02
1263 //
1264 // Stripping the trailing 0's (like g) does would make the
1265 // e format give us the right format.
1266 //
1267 // CPython sources say:
1268 // Omitted type specifier. Behaves in the same way as repr(x)
1269 // and str(x) if no precision is given, else like 'g', but with
1270 // at least one digit after the decimal point. */
1271
1272 type = 'g';
1273 }
1274 if (type == 'n') {
1275 type = 'g';
1276 }
1277
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001278 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001279#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001280 case 'e':
1281 case 'E':
1282 case 'f':
1283 case 'F':
1284 case 'g':
1285 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001286 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001287 break;
1288
1289 case '%':
1290 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001291 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1292 #define F100 100.0F
1293 #else
1294 #define F100 100.0
1295 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001296 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001297 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001298 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001299#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001300
1301 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001302 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1303 terse_str_format_value_error();
1304 } else {
1305 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1306 "unknown format code '%c' for object of type 'float'",
1307 type, mp_obj_get_type_str(arg)));
1308 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001309 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001310 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001311 // arg doesn't look like a number
1312
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001313 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001314 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1315 terse_str_format_value_error();
1316 } else {
Damien George21967992016-08-14 16:51:54 +10001317 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001318 "'=' alignment not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001319 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001320 }
Damien George70f33cd2014-04-02 17:06:05 +01001321
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001322 switch (type) {
Damien Georged4df8f42016-01-04 13:13:39 +00001323 case '\0': // no explicit format type implies 's'
Damien Georged182b982014-08-30 14:19:41 +01001324 case 's': {
Damien George6b341072017-03-25 19:48:18 +11001325 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001326 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001327 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001328 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001329 }
Damien George6b341072017-03-25 19:48:18 +11001330 if (slen > (size_t)precision) {
Damien George50912e72015-01-20 11:55:10 +00001331 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001332 }
Damien George7f9d1d62015-04-09 23:56:15 +01001333 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001334 break;
1335 }
1336
1337 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001338 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1339 terse_str_format_value_error();
1340 } else {
1341 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1342 "unknown format code '%c' for object of type 'str'",
1343 type, mp_obj_get_type_str(arg)));
1344 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001345 }
Damiend99b0522013-12-21 18:17:45 +00001346 }
1347 }
1348
pohmeliee3a29de2016-01-29 12:09:10 +03001349 return vstr;
1350}
1351
1352mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001353 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
pohmeliee3a29de2016-01-29 12:09:10 +03001354
1355 GET_STR_DATA_LEN(args[0], str, len);
1356 int arg_i = 0;
1357 vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs);
Damien George0b9ee862015-01-21 19:14:25 +00001358 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001359}
Damien George65417c52017-07-02 23:35:42 +10001360MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Damiend99b0522013-12-21 18:17:45 +00001361
Damien George90ab1912017-02-03 13:04:56 +11001362STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001363 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001364
1365 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001366 const byte *start_str = str;
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001367 bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
Damien George90ab1912017-02-03 13:04:56 +11001368 size_t arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001369 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001370 mp_print_t print;
1371 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001372
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001373 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001374 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001375 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001376 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001377 continue;
1378 }
1379 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001380 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001381 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001382 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001383 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001384 continue;
1385 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001386
1387 // Dictionary value lookup
1388 if (*str == '(') {
Damien George7317e342017-02-03 12:13:44 +11001389 if (dict == MP_OBJ_NULL) {
1390 mp_raise_TypeError("format requires a dict");
1391 }
1392 arg_i = 1; // we used up the single dict argument
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001393 const byte *key = ++str;
1394 while (*str != ')') {
1395 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001396 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1397 terse_str_format_value_error();
1398 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001399 mp_raise_ValueError("incomplete format key");
Damien George1e9a92f2014-11-06 17:36:16 +00001400 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001401 }
1402 ++str;
1403 }
1404 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1405 arg = mp_obj_dict_get(dict, k_obj);
1406 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001407 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001408
Dave Hylands6756a372014-04-02 11:42:39 -07001409 int flags = 0;
1410 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001411 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001412 while (str < top) {
1413 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1414 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1415 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001416 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001417 else if (*str == '0') {
1418 flags |= PF_FLAG_PAD_AFTER_SIGN;
1419 fill = '0';
1420 } else break;
1421 str++;
1422 }
1423 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001424 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001425 if (str < top) {
1426 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001427 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001428 goto not_enough_args;
1429 }
Dave Hylands6756a372014-04-02 11:42:39 -07001430 width = mp_obj_get_int(args[arg_i++]);
1431 str++;
1432 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001433 str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001434 }
1435 }
1436 int prec = -1;
1437 if (str < top && *str == '.') {
1438 if (++str < top) {
1439 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001440 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001441 goto not_enough_args;
1442 }
Dave Hylands6756a372014-04-02 11:42:39 -07001443 prec = mp_obj_get_int(args[arg_i++]);
1444 str++;
1445 } else {
1446 prec = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001447 str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001448 }
1449 }
1450 }
1451
1452 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001453incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001454 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1455 terse_str_format_value_error();
1456 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001457 mp_raise_ValueError("incomplete format");
Damien George1e9a92f2014-11-06 17:36:16 +00001458 }
Dave Hylands6756a372014-04-02 11:42:39 -07001459 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001460
1461 // Tuple value lookup
1462 if (arg == MP_OBJ_NULL) {
Damien George90ab1912017-02-03 13:04:56 +11001463 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001464not_enough_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001465 mp_raise_TypeError("not enough arguments for format string");
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001466 }
1467 arg = args[arg_i++];
1468 }
Dave Hylands6756a372014-04-02 11:42:39 -07001469 switch (*str) {
1470 case 'c':
1471 if (MP_OBJ_IS_STR(arg)) {
Damien George6b341072017-03-25 19:48:18 +11001472 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001473 const char *s = mp_obj_str_get_data(arg, &slen);
1474 if (slen != 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001475 mp_raise_TypeError("%%c requires int or char");
Dave Hylands6756a372014-04-02 11:42:39 -07001476 }
Damien George7f9d1d62015-04-09 23:56:15 +01001477 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001478 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001479 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001480 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001481 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001482 mp_raise_TypeError("integer required");
Dave Hylands6756a372014-04-02 11:42:39 -07001483 }
Damien George11de8392014-06-05 18:57:38 +01001484 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001485
1486 case 'd':
1487 case 'i':
1488 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001489 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001490 break;
1491
Damien Georgefb510b32014-06-01 13:32:54 +01001492#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001493 case 'e':
1494 case 'E':
1495 case 'f':
1496 case 'F':
1497 case 'g':
1498 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001499 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001500 break;
1501#endif
1502
1503 case 'o':
1504 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001505 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001506 }
Damien George7f9d1d62015-04-09 23:56:15 +01001507 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001508 break;
1509
1510 case 'r':
1511 case 's':
1512 {
Damien George0b9ee862015-01-21 19:14:25 +00001513 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001514 mp_print_t arg_print;
1515 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001516 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1517 if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1518 // If we have something like b"%s" % b"1", bytes arg should be
1519 // printed undecorated.
1520 print_kind = PRINT_RAW;
1521 }
1522 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001523 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001524 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001525 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001526 }
Damien George50912e72015-01-20 11:55:10 +00001527 if (vlen > (uint)prec) {
1528 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001529 }
Damien George7f9d1d62015-04-09 23:56:15 +01001530 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001531 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001532 break;
1533 }
Dave Hylands6756a372014-04-02 11:42:39 -07001534
Dave Hylands6756a372014-04-02 11:42:39 -07001535 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001536 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001537 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001538 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001539
Dave Hylands6756a372014-04-02 11:42:39 -07001540 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001541 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1542 terse_str_format_value_error();
1543 } else {
1544 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1545 "unsupported format character '%c' (0x%x) at index %d",
1546 *str, *str, str - start_str));
1547 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001548 }
1549 }
1550
Damien George90ab1912017-02-03 13:04:56 +11001551 if (arg_i != n_args) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001552 mp_raise_TypeError("not all arguments converted during string formatting");
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001553 }
1554
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001555 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001556}
1557
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001558// The implementation is optimized, returning the original string if there's
1559// nothing to replace.
Damien George4b72b3a2016-01-03 14:21:40 +00001560STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001561 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001562
Damien George40f3c022014-07-03 13:25:24 +01001563 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001564 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001565 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001566 if (max_rep == 0) {
1567 return args[0];
1568 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001569 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001570 }
xbe480c15a2014-01-30 22:17:30 -08001571 }
Damien George94f68302014-01-31 23:45:12 +00001572
xbe729be9b2014-04-07 14:46:39 -07001573 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001574
Damien Georgeff715422014-04-07 00:39:13 +01001575 // check argument types
1576
Damien Georgec55a4d82014-12-24 20:28:30 +00001577 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1578
1579 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001580 bad_implicit_conversion(args[1]);
1581 }
1582
Damien Georgec55a4d82014-12-24 20:28:30 +00001583 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001584 bad_implicit_conversion(args[2]);
1585 }
1586
1587 // extract string data
1588
xbe480c15a2014-01-30 22:17:30 -08001589 GET_STR_DATA_LEN(args[0], str, str_len);
1590 GET_STR_DATA_LEN(args[1], old, old_len);
1591 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001592
1593 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001594 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001595 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001596 }
1597
Damien George94f68302014-01-31 23:45:12 +00001598 // data for the replaced string
1599 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001600 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001601
Damien George94f68302014-01-31 23:45:12 +00001602 // do 2 passes over the string:
1603 // first pass computes the required length of the replaced string
1604 // second pass does the replacements
1605 for (;;) {
Damien Georgec0d95002017-02-16 16:26:48 +11001606 size_t replaced_str_index = 0;
1607 size_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001608 const byte *old_occurrence;
1609 const byte *offset_ptr = str;
Damien Georgec0d95002017-02-16 16:26:48 +11001610 size_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001611 if (old_len == 0) {
1612 // if old_str is empty, copy new_str to start of replaced string
1613 // copy the replacement string
1614 if (data != NULL) {
1615 memcpy(data, new, new_len);
1616 }
1617 replaced_str_index += new_len;
1618 num_replacements_done++;
1619 }
Damien Georgec0d95002017-02-16 16:26:48 +11001620 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 +01001621 if (old_len == 0) {
1622 old_occurrence += 1;
1623 }
Damien George94f68302014-01-31 23:45:12 +00001624 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1625 if (data != NULL) {
1626 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1627 }
1628 replaced_str_index += old_occurrence - offset_ptr;
1629 // copy the replacement string
1630 if (data != NULL) {
1631 memcpy(data + replaced_str_index, new, new_len);
1632 }
1633 replaced_str_index += new_len;
1634 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001635 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001636 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001637 }
1638
1639 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1640 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001641 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001642 }
Damien Georgeff715422014-04-07 00:39:13 +01001643 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001644
1645 if (data == NULL) {
1646 // first pass
1647 if (num_replacements_done == 0) {
1648 // no substr found, return original string
1649 return args[0];
1650 } else {
1651 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001652 vstr_init_len(&vstr, replaced_str_index);
1653 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001654 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001655 }
1656 } else {
1657 // second pass, we are done
1658 break;
1659 }
xbe480c15a2014-01-30 22:17:30 -08001660 }
Damien George94f68302014-01-31 23:45:12 +00001661
Damien George05005f62015-01-21 22:48:37 +00001662 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001663}
Damien George65417c52017-07-02 23:35:42 +10001664MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe480c15a2014-01-30 22:17:30 -08001665
Damien George4b72b3a2016-01-03 14:21:40 +00001666STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001667 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001668 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +00001669
1670 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001671 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001672 bad_implicit_conversion(args[1]);
1673 }
xbe9e1e8cd2014-03-12 22:57:16 -07001674
1675 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1676 GET_STR_DATA_LEN(args[1], needle, needle_len);
1677
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001678 const byte *start = haystack;
1679 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001680 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001681 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001682 }
1683 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001684 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001685 }
1686
Damien George536dde22014-03-13 22:07:55 +00001687 // if needle_len is zero then we count each gap between characters as an occurrence
1688 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001689 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001690 }
1691
Damien George536dde22014-03-13 22:07:55 +00001692 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001693 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001694 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1695 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001696 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001697 haystack_ptr += needle_len;
1698 } else {
1699 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001700 }
xbe9e1e8cd2014-03-12 22:57:16 -07001701 }
1702
1703 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1704}
Damien George65417c52017-07-02 23:35:42 +10001705MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe9e1e8cd2014-03-12 22:57:16 -07001706
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001707#if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgec0d95002017-02-16 16:26:48 +11001708STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001709 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001710 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1711 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001712 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001713 }
Damien Georgeb035db32014-03-21 20:39:40 +00001714
xbe613a8e32014-03-18 00:06:29 -07001715 GET_STR_DATA_LEN(self_in, str, str_len);
1716 GET_STR_DATA_LEN(arg, sep, sep_len);
1717
1718 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001719 mp_raise_ValueError("empty separator");
xbe613a8e32014-03-18 00:06:29 -07001720 }
Damien Georgeb035db32014-03-21 20:39:40 +00001721
Damien Georgec55a4d82014-12-24 20:28:30 +00001722 mp_obj_t result[3];
1723 if (self_type == &mp_type_str) {
1724 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1725 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1726 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1727 } else {
1728 result[0] = mp_const_empty_bytes;
1729 result[1] = mp_const_empty_bytes;
1730 result[2] = mp_const_empty_bytes;
1731 }
Damien Georgeb035db32014-03-21 20:39:40 +00001732
1733 if (direction > 0) {
1734 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001735 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001736 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001737 }
xbe613a8e32014-03-18 00:06:29 -07001738
xbe17a5a832014-03-23 23:31:58 -07001739 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1740 if (position_ptr != NULL) {
Damien Georgec0d95002017-02-16 16:26:48 +11001741 size_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001742 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001743 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001744 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 -07001745 }
Damien Georgeb035db32014-03-21 20:39:40 +00001746
xbe0a6894c2014-03-21 01:12:26 -07001747 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001748}
1749
Damien Georgeb035db32014-03-21 20:39:40 +00001750STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1751 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001752}
Damien George65417c52017-07-02 23:35:42 +10001753MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001754
Damien Georgeb035db32014-03-21 20:39:40 +00001755STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1756 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001757}
Damien George65417c52017-07-02 23:35:42 +10001758MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001759#endif
xbe4504ea82014-03-19 00:46:14 -07001760
Paul Sokolovsky69135212014-05-10 19:47:41 +03001761// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001762STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001763 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001764 vstr_t vstr;
1765 vstr_init_len(&vstr, self_len);
1766 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +11001767 for (size_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001768 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001769 }
Damien George05005f62015-01-21 22:48:37 +00001770 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001771}
1772
1773STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001774 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001775}
Damien George65417c52017-07-02 23:35:42 +10001776MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001777
1778STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001779 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001780}
Damien George65417c52017-07-02 23:35:42 +10001781MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001782
Damien Georgefcc9cf62014-06-01 18:22:09 +01001783STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001784 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001785
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001786 if (self_len == 0) {
1787 return mp_const_false; // default to False for empty str
1788 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001789
Damien Georgefcc9cf62014-06-01 18:22:09 +01001790 if (f != unichar_isupper && f != unichar_islower) {
Damien Georgec0d95002017-02-16 16:26:48 +11001791 for (size_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001792 if (!f(*self_data++)) {
1793 return mp_const_false;
1794 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001795 }
1796 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001797 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001798
Damien Georgec0d95002017-02-16 16:26:48 +11001799 for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001800 if (unichar_isalpha(*self_data++)) {
1801 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001802 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1803 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001804 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001805 }
1806 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001807
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001808 if (!contains_alpha) {
1809 return mp_const_false;
1810 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001811 }
1812
1813 return mp_const_true;
1814}
1815
1816STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001817 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001818}
Damien George65417c52017-07-02 23:35:42 +10001819MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001820
1821STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001822 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001823}
Damien George65417c52017-07-02 23:35:42 +10001824MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001825
1826STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001827 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001828}
Damien George65417c52017-07-02 23:35:42 +10001829MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001830
1831STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001832 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001833}
Damien George65417c52017-07-02 23:35:42 +10001834MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001835
1836STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001837 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001838}
Damien George65417c52017-07-02 23:35:42 +10001839MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001840
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001841#if MICROPY_CPYTHON_COMPAT
Ville Skyttäca16c382017-05-29 10:08:14 +03001842// These methods are superfluous in the presence of str() and bytes()
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001843// constructors.
1844// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001845STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001846 mp_obj_t new_args[2];
1847 if (n_args == 1) {
1848 new_args[0] = args[0];
1849 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1850 args = new_args;
1851 n_args++;
1852 }
Damien George5b3f0b72016-01-03 15:55:55 +00001853 return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001854}
Damien George65417c52017-07-02 23:35:42 +10001855MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001856
1857// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001858STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001859 mp_obj_t new_args[2];
1860 if (n_args == 1) {
1861 new_args[0] = args[0];
1862 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1863 args = new_args;
1864 n_args++;
1865 }
Damien George5b3f0b72016-01-03 15:55:55 +00001866 return bytes_make_new(NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001867}
Damien George65417c52017-07-02 23:35:42 +10001868MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001869#endif
1870
Damien George4d917232014-08-30 14:28:06 +01001871mp_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 +01001872 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001873 GET_STR_DATA_LEN(self_in, str_data, str_len);
1874 bufinfo->buf = (void*)str_data;
1875 bufinfo->len = str_len;
Damien George12dd8df2016-05-07 21:18:17 +01001876 bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
Damien George2da98302014-03-09 19:58:18 +00001877 return 0;
1878 } else {
1879 // can't write to a string
1880 bufinfo->buf = NULL;
1881 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001882 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001883 return 1;
1884 }
1885}
1886
Damien Georgecbf76742015-11-27 13:38:15 +00001887STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001888#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001889 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001890 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1891 // If we have separate unicode type, then here we have methods only
1892 // for bytes type, and it should not have encode() methods. Otherwise,
1893 // we have non-compliant-but-practical bytestring type, which shares
1894 // method table with bytes, so they both have encode() and decode()
1895 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001896 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001897 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001898#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001899 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1900 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1901 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1902 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1903 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1904 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001905 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001906 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001907 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001908 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1909 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1910 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1911 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1912 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1913 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1914 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1915 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1916 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001917 #if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgecbf76742015-11-27 13:38:15 +00001918 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1919 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001920 #endif
Paul Sokolovsky15633882016-08-07 15:24:57 +03001921 #if MICROPY_PY_BUILTINS_STR_CENTER
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +03001922 { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
Paul Sokolovsky15633882016-08-07 15:24:57 +03001923 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001924 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1925 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1926 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1927 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1928 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1929 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1930 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001931};
Damien George97209d32014-01-07 15:58:30 +00001932
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001933STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001934
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001935#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgeae8d8672016-01-09 23:14:54 +00001936STATIC 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 +01001937
Damien George3e1a5c12014-03-29 13:43:38 +00001938const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001939 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001940 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001941 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001942 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001943 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001944 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001945 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001946 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001947 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001948};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001949#endif
Damiend99b0522013-12-21 18:17:45 +00001950
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001951// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001952const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001953 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001954 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001955 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001956 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001957 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001958 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001959 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001960 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001961 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001962};
1963
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001964// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001965const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001966
Damien George77089be2015-01-21 23:08:36 +00001967// Create a str/bytes object using the given data. New memory is allocated and
1968// the data is copied across.
Damien George999cedb2015-11-27 17:01:44 +00001969mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001970 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001971 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001972 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001973 if (data) {
1974 o->hash = qstr_compute_hash(data, len);
1975 byte *p = m_new(byte, len + 1);
1976 o->data = p;
1977 memcpy(p, data, len * sizeof(byte));
1978 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1979 }
Damien George999cedb2015-11-27 17:01:44 +00001980 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001981}
1982
Damien George77089be2015-01-21 23:08:36 +00001983// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1984// the exact length required and then reused for the str/bytes object. The vstr
1985// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001986mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1987 // if not a bytes object, look if a qstr with this data already exists
1988 if (type == &mp_type_str) {
1989 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1990 if (q != MP_QSTR_NULL) {
1991 vstr_clear(vstr);
1992 vstr->alloc = 0;
1993 return MP_OBJ_NEW_QSTR(q);
1994 }
1995 }
1996
1997 // make a new str/bytes object
1998 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1999 o->base.type = type;
2000 o->len = vstr->len;
2001 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07002002 if (vstr->len + 1 == vstr->alloc) {
2003 o->data = (byte*)vstr->buf;
2004 } else {
2005 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
2006 }
Damien George0d3cb672015-01-28 23:43:01 +00002007 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00002008 vstr->buf = NULL;
2009 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00002010 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00002011}
2012
Damien Georgec0d95002017-02-16 16:26:48 +11002013mp_obj_t mp_obj_new_str(const char* data, size_t len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01002014 if (make_qstr_if_not_already) {
2015 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01002016 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00002017 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01002018 qstr q = qstr_find_strn(data, len);
2019 if (q != MP_QSTR_NULL) {
2020 // qstr with this data already exists
2021 return MP_OBJ_NEW_QSTR(q);
2022 } else {
2023 // no existing qstr, don't make one
2024 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
2025 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002026 }
Damien George5fa93b62014-01-22 14:35:10 +00002027}
2028
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002029mp_obj_t mp_obj_str_intern(mp_obj_t str) {
2030 GET_STR_DATA_LEN(str, data, len);
2031 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
2032}
2033
Damien Georgec0d95002017-02-16 16:26:48 +11002034mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01002035 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002036}
2037
Damien George5fa93b62014-01-22 14:35:10 +00002038bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
2039 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
2040 return s1 == s2;
2041 } else {
2042 GET_STR_HASH(s1, h1);
2043 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03002044 // If any of hashes is 0, it means it's not valid
2045 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00002046 return false;
2047 }
2048 GET_STR_DATA_LEN(s1, d1, l1);
2049 GET_STR_DATA_LEN(s2, d2, l2);
2050 if (l1 != l2) {
2051 return false;
2052 }
Damien George1e708fe2014-01-23 18:27:51 +00002053 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002054 }
Damien George5fa93b62014-01-22 14:35:10 +00002055}
2056
Damien Georgedeed0872014-04-06 11:11:15 +01002057STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002058 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03002059 mp_raise_TypeError("can't convert to str implicitly");
Damien George1e9a92f2014-11-06 17:36:16 +00002060 } else {
stijnbf29fe22017-03-15 12:17:38 +01002061 const qstr src_name = mp_obj_get_type(self_in)->name;
Damien George1e9a92f2014-11-06 17:36:16 +00002062 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
stijnbf29fe22017-03-15 12:17:38 +01002063 "can't convert '%q' object to %q implicitly",
2064 src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str));
Damien George1e9a92f2014-11-06 17:36:16 +00002065 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002066}
2067
Damien Georgeb829b5c2014-01-25 13:51:19 +00002068// use this if you will anyway convert the string to a qstr
2069// will be more efficient for the case where it's already a qstr
2070qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2071 if (MP_OBJ_IS_QSTR(self_in)) {
2072 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002073 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002074 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002075 return qstr_from_strn((char*)self->data, self->len);
2076 } else {
2077 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002078 }
2079}
2080
2081// only use this function if you need the str data to be zero terminated
2082// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2083const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002084 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002085 GET_STR_DATA_LEN(self_in, s, l);
2086 (void)l; // len unused
2087 return (const char*)s;
2088 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002089 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002090 }
2091}
2092
Damien George6b341072017-03-25 19:48:18 +11002093const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002094 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002095 GET_STR_DATA_LEN(self_in, s, l);
2096 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002097 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002098 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002099 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002100 }
Damiend99b0522013-12-21 18:17:45 +00002101}
xyb8cfc9f02014-01-05 18:47:51 +08002102
Damien George04353cc2015-10-18 23:09:04 +01002103#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
Damien Georgec3f64d92015-11-27 12:23:18 +00002104const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien George04353cc2015-10-18 23:09:04 +01002105 if (MP_OBJ_IS_QSTR(self_in)) {
2106 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2107 } else {
2108 *len = ((mp_obj_str_t*)self_in)->len;
2109 return ((mp_obj_str_t*)self_in)->data;
2110 }
2111}
2112#endif
2113
xyb8cfc9f02014-01-05 18:47:51 +08002114/******************************************************************************/
2115/* str iterator */
2116
Damien George44e7cbf2015-05-17 16:44:24 +01002117typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002118 mp_obj_base_t base;
Damien George8212d972016-01-03 16:27:55 +00002119 mp_fun_1_t iternext;
Damien George5fa93b62014-01-22 14:35:10 +00002120 mp_obj_t str;
Damien Georgec0d95002017-02-16 16:26:48 +11002121 size_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002122} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002123
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002124#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002125STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George326e8862017-06-08 00:40:38 +10002126 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002127 GET_STR_DATA_LEN(self->str, str, len);
2128 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002129 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002130 self->cur += 1;
2131 return o_out;
2132 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002133 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002134 }
2135}
2136
Damien Georgeae8d8672016-01-09 23:14:54 +00002137STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2138 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2139 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002140 o->base.type = &mp_type_polymorph_iter;
2141 o->iternext = str_it_iternext;
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002142 o->str = str;
2143 o->cur = 0;
Damien George326e8862017-06-08 00:40:38 +10002144 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002145}
2146#endif
2147
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002148STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002149 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002150 GET_STR_DATA_LEN(self->str, str, len);
2151 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002152 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002153 self->cur += 1;
2154 return o_out;
2155 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002156 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002157 }
2158}
2159
Damien Georgeae8d8672016-01-09 23:14:54 +00002160mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2161 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2162 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002163 o->base.type = &mp_type_polymorph_iter;
2164 o->iternext = bytes_it_iternext;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002165 o->str = str;
2166 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002167 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002168}