blob: 5c464ba7d67760257a8a76aab94bfb7c950b7066 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
Alexander Steffen55f33242017-06-30 09:22:17 +02002 * This file is part of the MicroPython project, http://micropython.org/
Damien George04b91472014-05-03 23:27:38 +01003 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul 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/unicode.h"
32#include "py/objstr.h"
33#include "py/objlist.h"
Damien George51dfcb42015-01-01 20:27:54 +000034#include "py/runtime.h"
pohmeliee3a29de2016-01-29 12:09:10 +030035#include "py/stackctrl.h"
Damiend99b0522013-12-21 18:17:45 +000036
Damien George90ab1912017-02-03 13:04:56 +110037STATIC 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 +020038
Damien Georgeae8d8672016-01-09 23:14:54 +000039STATIC 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 +030040STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030041
xyb8cfc9f02014-01-05 18:47:51 +080042/******************************************************************************/
43/* str */
44
Damien Georgec0d95002017-02-16 16:26:48 +110045void 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 +020046 // this escapes characters, but it will be very slow to print (calling print many times)
47 bool has_single_quote = false;
48 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100049 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020050 if (*s == '\'') {
51 has_single_quote = true;
52 } else if (*s == '"') {
53 has_double_quote = true;
54 }
55 }
56 int quote_char = '\'';
57 if (has_single_quote && !has_double_quote) {
58 quote_char = '"';
59 }
Damien George7f9d1d62015-04-09 23:56:15 +010060 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020061 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
62 if (*s == quote_char) {
Damien George7f9d1d62015-04-09 23:56:15 +010063 mp_printf(print, "\\%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020064 } else if (*s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010065 mp_print_str(print, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030066 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
67 // In strings, anything which is not ascii control character
68 // is printed as is, this includes characters in range 0x80-0xff
69 // (which can be non-Latin letters, etc.)
Damien George7f9d1d62015-04-09 23:56:15 +010070 mp_printf(print, "%c", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020071 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010072 mp_print_str(print, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010073 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010074 mp_print_str(print, "\\r");
Andrew Scheller12968fb2014-04-08 02:42:50 +010075 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +010076 mp_print_str(print, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020077 } else {
Damien George7f9d1d62015-04-09 23:56:15 +010078 mp_printf(print, "\\x%02x", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020079 }
80 }
Damien George7f9d1d62015-04-09 23:56:15 +010081 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020082}
83
Damien George612045f2014-09-17 22:56:34 +010084#if MICROPY_PY_UJSON
Damien George999cedb2015-11-27 17:01:44 +000085void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
Damien Georgecde0ca22014-09-25 17:35:56 +010086 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
87 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George7f9d1d62015-04-09 23:56:15 +010088 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +010089 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010090 if (*s == '"' || *s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010091 mp_printf(print, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010092 } else if (*s >= 32) {
93 // this will handle normal and utf-8 encoded chars
Damien George7f9d1d62015-04-09 23:56:15 +010094 mp_printf(print, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010095 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010096 mp_print_str(print, "\\n");
Damien George612045f2014-09-17 22:56:34 +010097 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010098 mp_print_str(print, "\\r");
Damien George612045f2014-09-17 22:56:34 +010099 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +0100100 mp_print_str(print, "\\t");
Damien George612045f2014-09-17 22:56:34 +0100101 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100102 // this will handle control chars
Damien George7f9d1d62015-04-09 23:56:15 +0100103 mp_printf(print, "\\u%04x", *s);
Damien George612045f2014-09-17 22:56:34 +0100104 }
105 }
Damien George7f9d1d62015-04-09 23:56:15 +0100106 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +0100107}
108#endif
109
Damien George7f9d1d62015-04-09 23:56:15 +0100110STATIC 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 +0000111 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100112 #if MICROPY_PY_UJSON
113 if (kind == PRINT_JSON) {
Damien George7f9d1d62015-04-09 23:56:15 +0100114 mp_str_print_json(print, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100115 return;
116 }
117 #endif
Damien Georgee2aa1172015-09-03 23:03:57 +0100118 #if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgecde0ca22014-09-25 17:35:56 +0100119 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Damien Georgee2aa1172015-09-03 23:03:57 +0100120 #else
121 bool is_bytes = true;
122 #endif
Paul Sokolovskyef63ab52015-12-20 16:44:36 +0200123 if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
Damien George7f9d1d62015-04-09 23:56:15 +0100124 mp_printf(print, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200125 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200126 if (is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100127 mp_print_str(print, "b");
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200128 }
Damien George7f9d1d62015-04-09 23:56:15 +0100129 mp_str_print_quoted(print, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200130 }
Damiend99b0522013-12-21 18:17:45 +0000131}
132
Damien George5b3f0b72016-01-03 15:55:55 +0000133mp_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 +0300134#if MICROPY_CPYTHON_COMPAT
135 if (n_kw != 0) {
136 mp_arg_error_unimpl_kw();
137 }
138#endif
139
Damien George1e9a92f2014-11-06 17:36:16 +0000140 mp_arg_check_num(n_args, n_kw, 0, 3, false);
141
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200142 switch (n_args) {
143 case 0:
144 return MP_OBJ_NEW_QSTR(MP_QSTR_);
145
Damien George1e9a92f2014-11-06 17:36:16 +0000146 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000147 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100148 mp_print_t print;
149 vstr_init_print(&vstr, 16, &print);
150 mp_obj_print_helper(&print, args[0], PRINT_STR);
Damien George5b3f0b72016-01-03 15:55:55 +0000151 return mp_obj_new_str_from_vstr(type, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200152 }
153
Damien George1e9a92f2014-11-06 17:36:16 +0000154 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200155 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200156 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
157 GET_STR_DATA_LEN(args[0], str_data, str_len);
158 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000159 if (str_hash == 0) {
160 str_hash = qstr_compute_hash(str_data, str_len);
161 }
tll68c28172017-06-24 08:38:32 +0800162 #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
163 if (!utf8_check(str_data, str_len)) {
164 mp_raise_msg(&mp_type_UnicodeError, NULL);
165 }
166 #endif
Damien George5b3f0b72016-01-03 15:55:55 +0000167 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 +0200168 o->data = str_data;
169 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000170 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200171 } else {
172 mp_buffer_info_t bufinfo;
173 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
tll68c28172017-06-24 08:38:32 +0800174 #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
175 if (!utf8_check(bufinfo.buf, bufinfo.len)) {
176 mp_raise_msg(&mp_type_UnicodeError, NULL);
177 }
178 #endif
Damien George46017592017-11-16 13:17:51 +1100179 return mp_obj_new_str(bufinfo.buf, bufinfo.len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200180 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200181 }
182}
183
Damien George5b3f0b72016-01-03 15:55:55 +0000184STATIC 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 +0000185 (void)type_in;
186
Damien George3a2171e2015-09-04 16:53:46 +0100187 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300188 if (n_kw != 0) {
189 mp_arg_error_unimpl_kw();
190 }
Damien George3a2171e2015-09-04 16:53:46 +0100191 #else
192 (void)n_kw;
193 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300194
Damien George42cec5c2015-09-04 16:51:55 +0100195 if (n_args == 0) {
196 return mp_const_empty_bytes;
197 }
198
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200199 if (MP_OBJ_IS_STR(args[0])) {
200 if (n_args < 2 || n_args > 3) {
201 goto wrong_args;
202 }
203 GET_STR_DATA_LEN(args[0], str_data, str_len);
204 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000205 if (str_hash == 0) {
206 str_hash = qstr_compute_hash(str_data, str_len);
207 }
Damien George999cedb2015-11-27 17:01:44 +0000208 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 +0200209 o->data = str_data;
210 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000211 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200212 }
213
214 if (n_args > 1) {
215 goto wrong_args;
216 }
217
218 if (MP_OBJ_IS_SMALL_INT(args[0])) {
219 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000220 vstr_t vstr;
221 vstr_init_len(&vstr, len);
222 memset(vstr.buf, 0, len);
223 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200224 }
225
Damien George32ef3a32014-12-04 15:46:14 +0000226 // check if argument has the buffer protocol
227 mp_buffer_info_t bufinfo;
228 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
229 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
230 }
231
Damien George0b9ee862015-01-21 19:14:25 +0000232 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200233 // Try to create array of exact len if initializer len is known
234 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
235 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000236 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200237 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000238 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000239 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200240 }
241
Damien Georgeae8d8672016-01-09 23:14:54 +0000242 mp_obj_iter_buf_t iter_buf;
243 mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200244 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100245 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100246 mp_int_t val = mp_obj_get_int(item);
Paul Sokolovsky9a973972017-04-02 21:20:07 +0300247 #if MICROPY_FULL_CHECKS
Damien Georgeede0f3a2015-04-23 15:28:18 +0100248 if (val < 0 || val > 255) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300249 mp_raise_ValueError("bytes value out of range");
Damien Georgeede0f3a2015-04-23 15:28:18 +0100250 }
251 #endif
252 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200253 }
254
Damien George0b9ee862015-01-21 19:14:25 +0000255 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200256
257wrong_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300258 mp_raise_TypeError("wrong number of arguments");
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200259}
260
Damien George55baff42014-01-21 21:40:13 +0000261// like strstr but with specified length and allows \0 bytes
262// TODO replace with something more efficient/standard
Damien Georgec0d95002017-02-16 16:26:48 +1100263const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
Damien George55baff42014-01-21 21:40:13 +0000264 if (hlen >= nlen) {
Damien Georgec0d95002017-02-16 16:26:48 +1100265 size_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700266 if (direction > 0) {
267 str_index = 0;
268 str_index_end = hlen - nlen;
269 } else {
270 str_index = hlen - nlen;
271 str_index_end = 0;
272 }
273 for (;;) {
274 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
275 //found
276 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000277 }
xbe17a5a832014-03-23 23:31:58 -0700278 if (str_index == str_index_end) {
279 //not found
280 break;
Damien George55baff42014-01-21 21:40:13 +0000281 }
xbe17a5a832014-03-23 23:31:58 -0700282 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000283 }
284 }
285 return NULL;
286}
287
Damien Georgea75b02e2014-08-27 09:20:30 +0100288// Note: this function is used to check if an object is a str or bytes, which
289// works because both those types use it as their binary_op method. Revisit
290// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien George58321dd2017-08-29 13:04:01 +1000291mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000292 // check for modulo
293 if (op == MP_BINARY_OP_MODULO) {
Damien George7317e342017-02-03 12:13:44 +1100294 mp_obj_t *args = &rhs_in;
Damien George6213ad72017-03-25 19:35:08 +1100295 size_t n_args = 1;
Damien Georgea65c03c2014-11-05 16:30:34 +0000296 mp_obj_t dict = MP_OBJ_NULL;
297 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
298 // TODO: Support tuple subclasses?
299 mp_obj_tuple_get(rhs_in, &n_args, &args);
300 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000301 dict = rhs_in;
Damien Georgea65c03c2014-11-05 16:30:34 +0000302 }
303 return str_modulo_format(lhs_in, n_args, args, dict);
304 }
305
306 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300307 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000308 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
309
310 // check for multiply
311 if (op == MP_BINARY_OP_MULTIPLY) {
312 mp_int_t n;
313 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
314 return MP_OBJ_NULL; // op not supported
315 }
316 if (n <= 0) {
317 if (lhs_type == &mp_type_str) {
318 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
319 } else {
320 return mp_const_empty_bytes;
321 }
322 }
Damien George05005f62015-01-21 22:48:37 +0000323 vstr_t vstr;
324 vstr_init_len(&vstr, lhs_len * n);
325 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
326 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000327 }
328
329 // From now on all operations allow:
330 // - str with str
331 // - bytes with bytes
332 // - bytes with bytearray
333 // - bytes with array.array
334 // To do this efficiently we use the buffer protocol to extract the raw
335 // data for the rhs, but only if the lhs is a bytes object.
336 //
337 // NOTE: CPython does not allow comparison between bytes ard array.array
338 // (even if the array is of type 'b'), even though it allows addition of
339 // such types. We are not compatible with this (we do allow comparison
340 // of bytes with anything that has the buffer protocol). It would be
341 // easy to "fix" this with a bit of extra logic below, but it costs code
342 // size and execution time so we don't.
343
344 const byte *rhs_data;
Damien Georgec0d95002017-02-16 16:26:48 +1100345 size_t rhs_len;
Damien Georgea65c03c2014-11-05 16:30:34 +0000346 if (lhs_type == mp_obj_get_type(rhs_in)) {
347 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
348 rhs_data = rhs_data_;
349 rhs_len = rhs_len_;
350 } else if (lhs_type == &mp_type_bytes) {
351 mp_buffer_info_t bufinfo;
352 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000353 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000354 }
355 rhs_data = bufinfo.buf;
356 rhs_len = bufinfo.len;
357 } else {
Damien George3d25d9c2017-08-09 21:25:48 +1000358 // LHS is str and RHS has an incompatible type
359 // (except if operation is EQUAL, but that's handled by mp_obj_equal)
360 bad_implicit_conversion(rhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000361 }
362
Damiend99b0522013-12-21 18:17:45 +0000363 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100364 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000365 case MP_BINARY_OP_INPLACE_ADD: {
Damien Georged279bcf2017-03-16 14:30:04 +1100366 if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
Paul Sokolovskye2e66322017-01-27 00:40:47 +0300367 return rhs_in;
368 }
369 if (rhs_len == 0) {
370 return lhs_in;
371 }
372
Damien George05005f62015-01-21 22:48:37 +0000373 vstr_t vstr;
374 vstr_init_len(&vstr, lhs_len + rhs_len);
375 memcpy(vstr.buf, lhs_data, lhs_len);
376 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
377 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200378 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200379
Damien Georgea65c03c2014-11-05 16:30:34 +0000380 case MP_BINARY_OP_IN:
381 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300382 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300383
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300384 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
385 case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
Damien Georged17926d2014-03-30 13:35:08 +0100386 case MP_BINARY_OP_LESS:
387 case MP_BINARY_OP_LESS_EQUAL:
388 case MP_BINARY_OP_MORE:
389 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300390 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000391
Damien George58321dd2017-08-29 13:04:01 +1000392 default:
393 return MP_OBJ_NULL; // op not supported
394 }
Damiend99b0522013-12-21 18:17:45 +0000395}
396
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300397#if !MICROPY_PY_BUILTINS_STR_UNICODE
398// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000399const 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 +0300400 mp_obj_t index, bool is_slice) {
Damien Georgec88cfe12017-03-23 16:17:40 +1100401 size_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300402 return self_data + index_val;
403}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300404#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300405
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300406// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
407STATIC 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 +0300408 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100409 GET_STR_DATA_LEN(self_in, self_data, self_len);
410 if (value == MP_OBJ_SENTINEL) {
411 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100412#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100413 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300414 mp_bound_slice_t slice;
415 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000416 mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100417 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100418 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100419 }
420#endif
Damien Georgec88cfe12017-03-23 16:17:40 +1100421 size_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100422 // If we have unicode enabled the type will always be bytes, so take the short cut.
423 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300424 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100425 } else {
Damien George46017592017-11-16 13:17:51 +1100426 return mp_obj_new_str_via_qstr((char*)&self_data[index_val], 1);
Damien George729f7b42014-04-17 22:10:53 +0100427 }
428 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100429 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100430 }
431}
432
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200433STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300434 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300435 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000436
Damien Georgefe8fb912014-01-02 16:36:09 +0000437 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000438 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000439
440 // process args
Damien George6213ad72017-03-25 19:35:08 +1100441 size_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000442 mp_obj_t *seq_items;
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100443
444 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list) && !MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
445 // arg is not a list nor a tuple, try to convert it to a list
446 // TODO: Try to optimize?
447 arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
Damiend99b0522013-12-21 18:17:45 +0000448 }
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100449 mp_obj_get_array(arg, &seq_len, &seq_items);
Damien Georgefe8fb912014-01-02 16:36:09 +0000450
451 // count required length
Damien Georgec0d95002017-02-16 16:26:48 +1100452 size_t required_len = 0;
453 for (size_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300454 if (mp_obj_get_type(seq_items[i]) != self_type) {
Damien George21967992016-08-14 16:51:54 +1000455 mp_raise_TypeError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300456 "join expects a list of str/bytes objects consistent with self object");
Damiend99b0522013-12-21 18:17:45 +0000457 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000458 if (i > 0) {
459 required_len += sep_len;
460 }
Damien George5fa93b62014-01-22 14:35:10 +0000461 GET_STR_LEN(seq_items[i], l);
462 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000463 }
464
465 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000466 vstr_t vstr;
467 vstr_init_len(&vstr, required_len);
468 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +1100469 for (size_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000470 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000471 memcpy(data, sep_str, sep_len);
472 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000473 }
Damien George5fa93b62014-01-22 14:35:10 +0000474 GET_STR_DATA_LEN(seq_items[i], s, l);
475 memcpy(data, s, l);
476 data += l;
Damiend99b0522013-12-21 18:17:45 +0000477 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000478
479 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000480 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000481}
Damien George65417c52017-07-02 23:35:42 +1000482MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Damiend99b0522013-12-21 18:17:45 +0000483
Damien Georgecc80c4d2016-05-13 12:21:32 +0100484mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300485 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100486 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200487 mp_obj_t sep = mp_const_none;
488 if (n_args > 1) {
489 sep = args[1];
490 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100491 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200492 }
493 }
Damien Georgedeed0872014-04-06 11:11:15 +0100494
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200495 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000496 GET_STR_DATA_LEN(args[0], s, len);
497 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200498
Damien Georgedeed0872014-04-06 11:11:15 +0100499 if (sep == mp_const_none) {
500 // sep not given, so separate on whitespace
501
502 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300503 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100504 while (s < top && splits != 0) {
505 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300506 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100507 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100508 if (s >= top) {
509 break;
510 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300511 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100512 if (splits > 0) {
513 splits--;
514 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200515 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200516
Damien Georgedeed0872014-04-06 11:11:15 +0100517 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100518 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100519 }
520
521 } else {
522 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300523 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000524 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300525 }
Damien Georgedeed0872014-04-06 11:11:15 +0100526
Damien George6b341072017-03-25 19:48:18 +1100527 size_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100528 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
529
530 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300531 mp_raise_ValueError("empty separator");
Damien Georgedeed0872014-04-06 11:11:15 +0100532 }
533
534 for (;;) {
535 const byte *start = s;
536 for (;;) {
537 if (splits == 0 || s + sep_len > top) {
538 s = top;
539 break;
540 } else if (memcmp(s, sep_str, sep_len) == 0) {
541 break;
542 }
543 s++;
544 }
Damien Georgecc80c4d2016-05-13 12:21:32 +0100545 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100546 if (s >= top) {
547 break;
548 }
549 s += sep_len;
550 if (splits > 0) {
551 splits--;
552 }
553 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200554 }
555
556 return res;
557}
Damien George65417c52017-07-02 23:35:42 +1000558MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200559
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300560#if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien George4b72b3a2016-01-03 14:21:40 +0000561STATIC 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 +0100562 enum { ARG_keepends };
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300563 static const mp_arg_t allowed_args[] = {
564 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
565 };
566
567 // parse args
Damien Georgecc80c4d2016-05-13 12:21:32 +0100568 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
569 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300570
Damien Georgecc80c4d2016-05-13 12:21:32 +0100571 const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
572 mp_obj_t res = mp_obj_new_list(0, NULL);
573
574 GET_STR_DATA_LEN(pos_args[0], s, len);
575 const byte *top = s + len;
576
577 while (s < top) {
578 const byte *start = s;
579 size_t match = 0;
580 while (s < top) {
581 if (*s == '\n') {
582 match = 1;
583 break;
584 } else if (*s == '\r') {
585 if (s[1] == '\n') {
586 match = 2;
587 } else {
588 match = 1;
589 }
590 break;
591 }
592 s++;
593 }
594 size_t sub_len = s - start;
595 if (args[ARG_keepends].u_bool) {
596 sub_len += match;
597 }
598 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
599 s += match;
600 }
601
602 return res;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300603}
Damien George65417c52017-07-02 23:35:42 +1000604MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300605#endif
606
Damien George4b72b3a2016-01-03 14:21:40 +0000607STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300608 if (n_args < 3) {
609 // If we don't have split limit, it doesn't matter from which side
610 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200611 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300612 }
613 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
614 mp_obj_t sep = args[1];
615 GET_STR_DATA_LEN(args[0], s, len);
616
Damien George40f3c022014-07-03 13:25:24 +0100617 mp_int_t splits = mp_obj_get_int(args[2]);
Damien George9f85c4f2017-06-02 13:07:22 +1000618 if (splits < 0) {
619 // Negative limit means no limit, so delegate to split().
620 return mp_obj_str_split(n_args, args);
621 }
622
Damien George40f3c022014-07-03 13:25:24 +0100623 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300624 // Preallocate list to the max expected # of elements, as we
625 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000626 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100627 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300628
629 if (sep == mp_const_none) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000630 mp_raise_NotImplementedError("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300631 } else {
Damien George6b341072017-03-25 19:48:18 +1100632 size_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300633 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
634
635 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300636 mp_raise_ValueError("empty separator");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300637 }
638
639 const byte *beg = s;
640 const byte *last = s + len;
641 for (;;) {
642 s = last - sep_len;
643 for (;;) {
644 if (splits == 0 || s < beg) {
645 break;
646 } else if (memcmp(s, sep_str, sep_len) == 0) {
647 break;
648 }
649 s--;
650 }
651 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100652 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300653 break;
654 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100655 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 +0300656 last = s;
657 if (splits > 0) {
658 splits--;
659 }
660 }
661 if (idx != 0) {
662 // We split less parts than split limit, now go cleanup surplus
Damien Georgec0d95002017-02-16 16:26:48 +1100663 size_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100664 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300665 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
666 res->len = used;
667 }
668 }
669
Damien George999cedb2015-11-27 17:01:44 +0000670 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300671}
Damien George65417c52017-07-02 23:35:42 +1000672MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300673
Damien Georgec0d95002017-02-16 16:26:48 +1100674STATIC 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 +0300675 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300676 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +0000677
678 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000679 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000680 bad_implicit_conversion(args[1]);
681 }
John R. Lentone8204912014-01-12 21:53:52 +0000682
Damien George5fa93b62014-01-22 14:35:10 +0000683 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
684 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000685
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300686 const byte *start = haystack;
687 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000688 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300689 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000690 }
691 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300692 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000693 }
694
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300695 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000696 if (p == NULL) {
697 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700698 if (is_index) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300699 mp_raise_ValueError("substring not found");
xbe3d9a39e2014-04-08 11:42:19 -0700700 } else {
701 return MP_OBJ_NEW_SMALL_INT(-1);
702 }
Damien George23005372014-01-13 19:39:01 +0000703 } else {
704 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300705 #if MICROPY_PY_BUILTINS_STR_UNICODE
706 if (self_type == &mp_type_str) {
707 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
708 }
709 #endif
xbe17a5a832014-03-23 23:31:58 -0700710 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000711 }
John R. Lentone8204912014-01-12 21:53:52 +0000712}
713
Damien George4b72b3a2016-01-03 14:21:40 +0000714STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700715 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700716}
Damien George65417c52017-07-02 23:35:42 +1000717MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -0700718
Damien George4b72b3a2016-01-03 14:21:40 +0000719STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700720 return str_finder(n_args, args, -1, false);
721}
Damien George65417c52017-07-02 23:35:42 +1000722MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -0700723
Damien George4b72b3a2016-01-03 14:21:40 +0000724STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700725 return str_finder(n_args, args, 1, true);
726}
Damien George65417c52017-07-02 23:35:42 +1000727MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
xbe3d9a39e2014-04-08 11:42:19 -0700728
Damien George4b72b3a2016-01-03 14:21:40 +0000729STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700730 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700731}
Damien George65417c52017-07-02 23:35:42 +1000732MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
xbe17a5a832014-03-23 23:31:58 -0700733
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200734// TODO: (Much) more variety in args
Damien George4b72b3a2016-01-03 14:21:40 +0000735STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300736 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300737 GET_STR_DATA_LEN(args[0], str, str_len);
Paul Sokolovsky37379a22017-08-29 00:06:21 +0300738 size_t prefix_len;
739 const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300740 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300741 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300742 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300743 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300744 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200745 return mp_const_false;
746 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300747 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200748}
Damien George65417c52017-07-02 23:35:42 +1000749MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200750
Damien George4b72b3a2016-01-03 14:21:40 +0000751STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300752 GET_STR_DATA_LEN(args[0], str, str_len);
Paul Sokolovsky37379a22017-08-29 00:06:21 +0300753 size_t suffix_len;
754 const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100755 if (n_args > 2) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000756 mp_raise_NotImplementedError("start/end indices");
Damien George55b11e62015-09-04 16:49:56 +0100757 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300758
759 if (suffix_len > str_len) {
760 return mp_const_false;
761 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300762 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300763}
Damien George65417c52017-07-02 23:35:42 +1000764MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300765
Paul Sokolovsky88107842014-04-26 06:20:08 +0300766enum { LSTRIP, RSTRIP, STRIP };
767
Damien George90ab1912017-02-03 13:04:56 +1100768STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300769 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300770 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000771
772 const byte *chars_to_del;
773 uint chars_to_del_len;
774 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800775
776 if (n_args == 1) {
777 chars_to_del = whitespace;
Paul Sokolovskyfc9a6dd2017-09-19 21:19:23 +0300778 chars_to_del_len = sizeof(whitespace) - 1;
xbe7b0f39f2014-01-08 14:23:45 -0800779 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300780 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000781 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300782 }
Damien George5fa93b62014-01-22 14:35:10 +0000783 GET_STR_DATA_LEN(args[1], s, l);
784 chars_to_del = s;
785 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800786 }
787
Damien George5fa93b62014-01-22 14:35:10 +0000788 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800789
Damien Georgec0d95002017-02-16 16:26:48 +1100790 size_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800791 bool first_good_char_pos_set = false;
Damien Georgec0d95002017-02-16 16:26:48 +1100792 size_t last_good_char_pos = 0;
793 size_t i = 0;
794 int delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300795 if (type == RSTRIP) {
796 i = orig_str_len - 1;
797 delta = -1;
798 }
Damien Georgec0d95002017-02-16 16:26:48 +1100799 for (size_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700800 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800801 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300802 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800803 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300804 if (type == LSTRIP) {
805 last_good_char_pos = orig_str_len - 1;
806 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300807 } else if (type == RSTRIP) {
808 first_good_char_pos = 0;
809 last_good_char_pos = i;
810 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300811 }
xbe7b0f39f2014-01-08 14:23:45 -0800812 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300813 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800814 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300815 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800816 }
817
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300818 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000819 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000820 if (self_type == &mp_type_str) {
821 return MP_OBJ_NEW_QSTR(MP_QSTR_);
822 } else {
823 return mp_const_empty_bytes;
824 }
xbe7b0f39f2014-01-08 14:23:45 -0800825 }
826
827 assert(last_good_char_pos >= first_good_char_pos);
Ville Skyttäca16c382017-05-29 10:08:14 +0300828 //+1 to accommodate the last character
Damien Georgec0d95002017-02-16 16:26:48 +1100829 size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300830 if (stripped_len == orig_str_len) {
831 // If nothing was stripped, don't bother to dup original string
832 // TODO: watch out for this case when we'll get to bytearray.strip()
833 assert(first_good_char_pos == 0);
834 return args[0];
835 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100836 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800837}
838
Damien George4b72b3a2016-01-03 14:21:40 +0000839STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300840 return str_uni_strip(STRIP, n_args, args);
841}
Damien George65417c52017-07-02 23:35:42 +1000842MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300843
Damien George4b72b3a2016-01-03 14:21:40 +0000844STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300845 return str_uni_strip(LSTRIP, n_args, args);
846}
Damien George65417c52017-07-02 23:35:42 +1000847MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300848
Damien George4b72b3a2016-01-03 14:21:40 +0000849STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300850 return str_uni_strip(RSTRIP, n_args, args);
851}
Damien George65417c52017-07-02 23:35:42 +1000852MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300853
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300854#if MICROPY_PY_BUILTINS_STR_CENTER
855STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
856 GET_STR_DATA_LEN(str_in, str, str_len);
Paul Sokolovsky9dde6062016-05-22 02:22:14 +0300857 mp_uint_t width = mp_obj_get_int(width_in);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300858 if (str_len >= width) {
859 return str_in;
860 }
861
862 vstr_t vstr;
863 vstr_init_len(&vstr, width);
864 memset(vstr.buf, ' ', width);
865 int left = (width - str_len) / 2;
866 memcpy(vstr.buf + left, str, str_len);
867 return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
868}
Damien George65417c52017-07-02 23:35:42 +1000869MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300870#endif
871
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872// Takes an int arg, but only parses unsigned numbers, and only changes
873// *num if at least one digit was parsed.
Damien George87e07ea2016-02-02 15:51:57 +0000874STATIC const char *str_to_int(const char *str, const char *top, int *num) {
875 if (str < top && '0' <= *str && *str <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700876 *num = 0;
877 do {
Damien George87e07ea2016-02-02 15:51:57 +0000878 *num = *num * 10 + (*str - '0');
879 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700880 }
Damien George87e07ea2016-02-02 15:51:57 +0000881 while (str < top && '0' <= *str && *str <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700882 }
Damien George87e07ea2016-02-02 15:51:57 +0000883 return str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700884}
885
Damien George2801e6f2015-04-04 15:53:11 +0100886STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700887 return ch && strchr("<>=^", ch) != NULL;
888}
889
Damien George2801e6f2015-04-04 15:53:11 +0100890STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700891 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
892}
893
Damien George2801e6f2015-04-04 15:53:11 +0100894STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700895 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
896}
897
Damien George2801e6f2015-04-04 15:53:11 +0100898STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700899 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100900#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100901 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902#endif
903 ;
904}
905
Damien George2801e6f2015-04-04 15:53:11 +0100906STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100907#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100908 if (mp_obj_is_float(arg)) {
909 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700910 }
911#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700912 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700913}
914
Damien George897129a2016-09-27 15:45:42 +1000915#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
Damien George1e9a92f2014-11-06 17:36:16 +0000916STATIC NORETURN void terse_str_format_value_error(void) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300917 mp_raise_ValueError("bad format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000918}
Damien George897129a2016-09-27 15:45:42 +1000919#else
920// define to nothing to improve coverage
921#define terse_str_format_value_error()
922#endif
Damien George1e9a92f2014-11-06 17:36:16 +0000923
Damien George90ab1912017-02-03 13:04:56 +1100924STATIC 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 +0000925 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100926 mp_print_t print;
927 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700928
pohmeliee3a29de2016-01-29 12:09:10 +0300929 for (; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700930 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000931 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700932 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100933 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700934 continue;
935 }
Damien George1e9a92f2014-11-06 17:36:16 +0000936 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
937 terse_str_format_value_error();
938 } else {
Damien George21967992016-08-14 16:51:54 +1000939 mp_raise_ValueError("single '}' encountered in format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000940 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700941 }
942 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100943 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700944 continue;
945 }
946
947 str++;
948 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100949 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700950 continue;
951 }
952
953 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
954
Damien George87e07ea2016-02-02 15:51:57 +0000955 const char *field_name = NULL;
956 const char *field_name_top = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700957 char conversion = '\0';
pohmeliee3a29de2016-01-29 12:09:10 +0300958 const char *format_spec = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700959
960 if (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000961 field_name = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700962 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000963 ++str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700964 }
Damien George87e07ea2016-02-02 15:51:57 +0000965 field_name_top = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700966 }
967
968 // conversion ::= "r" | "s"
969
970 if (str < top && *str == '!') {
971 str++;
972 if (str < top && (*str == 'r' || *str == 's')) {
973 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200974 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000975 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
976 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100977 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300978 mp_raise_ValueError("bad conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100979 } else {
980 if (str >= top) {
Damien George21967992016-08-14 16:51:54 +1000981 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300982 "end of format while looking for conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100983 } else {
984 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
985 "unknown conversion specifier %c", *str));
986 }
Damien George1e9a92f2014-11-06 17:36:16 +0000987 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700988 }
989 }
990
991 if (str < top && *str == ':') {
992 str++;
993 // {:} is the same as {}, which is the same as {!s}
994 // This makes a difference when passing in a True or False
995 // '{}'.format(True) returns 'True'
996 // '{:d}'.format(True) returns '1'
997 // So we treat {:} as {} and this later gets treated to be {!s}
998 if (*str != '}') {
pohmeliee3a29de2016-01-29 12:09:10 +0300999 format_spec = str;
1000 for (int nest = 1; str < top;) {
1001 if (*str == '{') {
1002 ++nest;
1003 } else if (*str == '}') {
1004 if (--nest == 0) {
1005 break;
1006 }
1007 }
1008 ++str;
Damiend99b0522013-12-21 18:17:45 +00001009 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001010 }
1011 }
1012 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001013 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1014 terse_str_format_value_error();
1015 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001016 mp_raise_ValueError("unmatched '{' in format");
Damien George1e9a92f2014-11-06 17:36:16 +00001017 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001018 }
1019 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +00001020 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1021 terse_str_format_value_error();
1022 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001023 mp_raise_ValueError("expected ':' after format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001024 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001025 }
1026
1027 mp_obj_t arg = mp_const_none;
1028
1029 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +01001030 int index = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001031 if (MP_LIKELY(unichar_isdigit(*field_name))) {
pohmeliee3a29de2016-01-29 12:09:10 +03001032 if (*arg_i > 0) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001033 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1034 terse_str_format_value_error();
1035 } else {
Damien George21967992016-08-14 16:51:54 +10001036 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001037 "can't switch from automatic field numbering to manual field specification");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001038 }
1039 }
Damien George87e07ea2016-02-02 15:51:57 +00001040 field_name = str_to_int(field_name, field_name_top, &index);
Damien George963a5a32015-01-16 17:47:07 +00001041 if ((uint)index >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001042 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001043 }
1044 arg = args[index + 1];
pohmeliee3a29de2016-01-29 12:09:10 +03001045 *arg_i = -1;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001046 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001047 const char *lookup;
1048 for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
Damien George46017592017-11-16 13:17:51 +11001049 mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr?
Damien George87e07ea2016-02-02 15:51:57 +00001050 field_name = lookup;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001051 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
1052 if (key_elem == NULL) {
1053 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
1054 }
1055 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001056 }
Damien George87e07ea2016-02-02 15:51:57 +00001057 if (field_name < field_name_top) {
Javier Candeira35a1fea2017-08-09 14:40:45 +10001058 mp_raise_NotImplementedError("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001059 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001060 } else {
pohmeliee3a29de2016-01-29 12:09:10 +03001061 if (*arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +00001062 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1063 terse_str_format_value_error();
1064 } else {
Damien George21967992016-08-14 16:51:54 +10001065 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001066 "can't switch from manual field specification to automatic field numbering");
Damien George1e9a92f2014-11-06 17:36:16 +00001067 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001068 }
pohmeliee3a29de2016-01-29 12:09:10 +03001069 if ((uint)*arg_i >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001070 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001071 }
pohmeliee3a29de2016-01-29 12:09:10 +03001072 arg = args[(*arg_i) + 1];
1073 (*arg_i)++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001074 }
1075 if (!format_spec && !conversion) {
1076 conversion = 's';
1077 }
1078 if (conversion) {
1079 mp_print_kind_t print_kind;
1080 if (conversion == 's') {
1081 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001082 } else {
Damien George000730e2015-08-30 12:43:21 +01001083 assert(conversion == 'r');
1084 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001085 }
Damien George0b9ee862015-01-21 19:14:25 +00001086 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001087 mp_print_t arg_print;
1088 vstr_init_print(&arg_vstr, 16, &arg_print);
1089 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001090 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 }
1092
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001093 char fill = '\0';
1094 char align = '\0';
1095 int width = -1;
1096 int precision = -1;
1097 char type = '\0';
1098 int flags = 0;
1099
1100 if (format_spec) {
1101 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1102 //
1103 // [[fill]align][sign][#][0][width][,][.precision][type]
1104 // fill ::= <any character>
1105 // align ::= "<" | ">" | "=" | "^"
1106 // sign ::= "+" | "-" | " "
1107 // width ::= integer
1108 // precision ::= integer
1109 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1110
pohmeliee3a29de2016-01-29 12:09:10 +03001111 // recursively call the formatter to format any nested specifiers
1112 MP_STACK_CHECK();
1113 vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001114 const char *s = vstr_null_terminated_str(&format_spec_vstr);
Damien George87e07ea2016-02-02 15:51:57 +00001115 const char *stop = s + format_spec_vstr.len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001116 if (isalignment(*s)) {
1117 align = *s++;
1118 } else if (*s && isalignment(s[1])) {
1119 fill = *s++;
1120 align = *s++;
1121 }
1122 if (*s == '+' || *s == '-' || *s == ' ') {
1123 if (*s == '+') {
1124 flags |= PF_FLAG_SHOW_SIGN;
1125 } else if (*s == ' ') {
1126 flags |= PF_FLAG_SPACE_SIGN;
1127 }
Damien George9d2c72a2017-07-04 02:13:27 +10001128 s++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001129 }
1130 if (*s == '#') {
1131 flags |= PF_FLAG_SHOW_PREFIX;
1132 s++;
1133 }
1134 if (*s == '0') {
1135 if (!align) {
1136 align = '=';
1137 }
1138 if (!fill) {
1139 fill = '0';
1140 }
1141 }
Damien George87e07ea2016-02-02 15:51:57 +00001142 s = str_to_int(s, stop, &width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001143 if (*s == ',') {
1144 flags |= PF_FLAG_SHOW_COMMA;
1145 s++;
1146 }
1147 if (*s == '.') {
1148 s++;
Damien George87e07ea2016-02-02 15:51:57 +00001149 s = str_to_int(s, stop, &precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 }
1151 if (istype(*s)) {
1152 type = *s++;
1153 }
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001154 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001155 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1156 terse_str_format_value_error();
1157 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001158 mp_raise_ValueError("invalid format specifier");
Damien George7ef75f92015-08-26 15:42:25 +01001159 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001160 }
pohmeliee3a29de2016-01-29 12:09:10 +03001161 vstr_clear(&format_spec_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001162 }
1163 if (!align) {
1164 if (arg_looks_numeric(arg)) {
1165 align = '>';
1166 } else {
1167 align = '<';
1168 }
1169 }
1170 if (!fill) {
1171 fill = ' ';
1172 }
1173
Damien George9d2c72a2017-07-04 02:13:27 +10001174 if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001175 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001176 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1177 terse_str_format_value_error();
1178 } else {
Damien George21967992016-08-14 16:51:54 +10001179 mp_raise_ValueError("sign not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001180 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001181 }
1182 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001183 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1184 terse_str_format_value_error();
1185 } else {
Damien George21967992016-08-14 16:51:54 +10001186 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001187 "sign not allowed with integer format specifier 'c'");
Damien George1e9a92f2014-11-06 17:36:16 +00001188 }
Damiend99b0522013-12-21 18:17:45 +00001189 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001190 }
1191
1192 switch (align) {
1193 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1194 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1195 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1196 }
1197
1198 if (arg_looks_integer(arg)) {
1199 switch (type) {
1200 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001201 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001202 continue;
1203
1204 case 'c':
1205 {
1206 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001207 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001208 continue;
1209 }
1210
1211 case '\0': // No explicit format type implies 'd'
1212 case 'n': // I don't think we support locales in uPy so use 'd'
1213 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001214 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001215 continue;
1216
1217 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001218 if (flags & PF_FLAG_SHOW_PREFIX) {
1219 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1220 }
1221
Damien George7f9d1d62015-04-09 23:56:15 +01001222 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001223 continue;
1224
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001225 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001226 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001227 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001228 continue;
1229
1230 case 'e':
1231 case 'E':
1232 case 'f':
1233 case 'F':
1234 case 'g':
1235 case 'G':
1236 case '%':
1237 // The floating point formatters all work with anything that
1238 // looks like an integer
1239 break;
1240
1241 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001242 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1243 terse_str_format_value_error();
1244 } else {
1245 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1246 "unknown format code '%c' for object of type '%s'",
1247 type, mp_obj_get_type_str(arg)));
1248 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001249 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001250 }
Damien George70f33cd2014-04-02 17:06:05 +01001251
Dave Hylands22fe4d72014-04-02 12:07:31 -07001252 // NOTE: no else here. We need the e, f, g etc formats for integer
1253 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001254 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001255 if (!type) {
1256
1257 // Even though the docs say that an unspecified type is the same
1258 // as 'g', there is one subtle difference, when the exponent
1259 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001260 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001261 // '{:10.1}'.format(0.0) ==> '0e+00'
1262 // '{:10.1g}'.format(0.0) ==> '0'
1263 //
1264 // TODO: Figure out how to deal with this.
1265 //
1266 // A proper solution would involve adding a special flag
1267 // or something to format_float, and create a format_double
1268 // to deal with doubles. In order to fix this when using
1269 // sprintf, we'd need to use the e format and tweak the
1270 // returned result to strip trailing zeros like the g format
1271 // does.
1272 //
1273 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1274 // but with 1.e2 you get 1e+02 and 1.00e+02
1275 //
1276 // Stripping the trailing 0's (like g) does would make the
1277 // e format give us the right format.
1278 //
1279 // CPython sources say:
1280 // Omitted type specifier. Behaves in the same way as repr(x)
1281 // and str(x) if no precision is given, else like 'g', but with
1282 // at least one digit after the decimal point. */
1283
1284 type = 'g';
1285 }
1286 if (type == 'n') {
1287 type = 'g';
1288 }
1289
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001290 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001291#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001292 case 'e':
1293 case 'E':
1294 case 'f':
1295 case 'F':
1296 case 'g':
1297 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001298 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001299 break;
1300
1301 case '%':
1302 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001303 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1304 #define F100 100.0F
1305 #else
1306 #define F100 100.0
1307 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001308 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001309 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001310 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001311#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001312
1313 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001314 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1315 terse_str_format_value_error();
1316 } else {
1317 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1318 "unknown format code '%c' for object of type 'float'",
1319 type, mp_obj_get_type_str(arg)));
1320 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001321 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001322 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001323 // arg doesn't look like a number
1324
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001325 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001326 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1327 terse_str_format_value_error();
1328 } else {
Damien George21967992016-08-14 16:51:54 +10001329 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001330 "'=' alignment not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001331 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001332 }
Damien George70f33cd2014-04-02 17:06:05 +01001333
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001334 switch (type) {
Damien Georged4df8f42016-01-04 13:13:39 +00001335 case '\0': // no explicit format type implies 's'
Damien Georged182b982014-08-30 14:19:41 +01001336 case 's': {
Damien George6b341072017-03-25 19:48:18 +11001337 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001338 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001339 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001340 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001341 }
Damien George6b341072017-03-25 19:48:18 +11001342 if (slen > (size_t)precision) {
Damien George50912e72015-01-20 11:55:10 +00001343 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001344 }
Damien George7f9d1d62015-04-09 23:56:15 +01001345 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001346 break;
1347 }
1348
1349 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001350 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1351 terse_str_format_value_error();
1352 } else {
1353 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1354 "unknown format code '%c' for object of type 'str'",
1355 type, mp_obj_get_type_str(arg)));
1356 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001357 }
Damiend99b0522013-12-21 18:17:45 +00001358 }
1359 }
1360
pohmeliee3a29de2016-01-29 12:09:10 +03001361 return vstr;
1362}
1363
1364mp_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 +03001365 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
pohmeliee3a29de2016-01-29 12:09:10 +03001366
1367 GET_STR_DATA_LEN(args[0], str, len);
1368 int arg_i = 0;
1369 vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs);
Damien George0b9ee862015-01-21 19:14:25 +00001370 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001371}
Damien George65417c52017-07-02 23:35:42 +10001372MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Damiend99b0522013-12-21 18:17:45 +00001373
Damien George90ab1912017-02-03 13:04:56 +11001374STATIC 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 +03001375 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001376
1377 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001378 const byte *start_str = str;
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001379 bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
Damien George90ab1912017-02-03 13:04:56 +11001380 size_t arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001381 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001382 mp_print_t print;
1383 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001384
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001385 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001386 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001387 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001388 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001389 continue;
1390 }
1391 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001392 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001393 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001394 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001395 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001396 continue;
1397 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001398
1399 // Dictionary value lookup
1400 if (*str == '(') {
Damien George7317e342017-02-03 12:13:44 +11001401 if (dict == MP_OBJ_NULL) {
1402 mp_raise_TypeError("format requires a dict");
1403 }
1404 arg_i = 1; // we used up the single dict argument
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001405 const byte *key = ++str;
1406 while (*str != ')') {
1407 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001408 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1409 terse_str_format_value_error();
1410 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001411 mp_raise_ValueError("incomplete format key");
Damien George1e9a92f2014-11-06 17:36:16 +00001412 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001413 }
1414 ++str;
1415 }
Damien George46017592017-11-16 13:17:51 +11001416 mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001417 arg = mp_obj_dict_get(dict, k_obj);
1418 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001419 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001420
Dave Hylands6756a372014-04-02 11:42:39 -07001421 int flags = 0;
1422 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001423 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001424 while (str < top) {
1425 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1426 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1427 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001428 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001429 else if (*str == '0') {
1430 flags |= PF_FLAG_PAD_AFTER_SIGN;
1431 fill = '0';
1432 } else break;
1433 str++;
1434 }
1435 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001436 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001437 if (str < top) {
1438 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001439 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001440 goto not_enough_args;
1441 }
Dave Hylands6756a372014-04-02 11:42:39 -07001442 width = mp_obj_get_int(args[arg_i++]);
1443 str++;
1444 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001445 str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001446 }
1447 }
1448 int prec = -1;
1449 if (str < top && *str == '.') {
1450 if (++str < top) {
1451 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001452 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001453 goto not_enough_args;
1454 }
Dave Hylands6756a372014-04-02 11:42:39 -07001455 prec = mp_obj_get_int(args[arg_i++]);
1456 str++;
1457 } else {
1458 prec = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001459 str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001460 }
1461 }
1462 }
1463
1464 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001465incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001466 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1467 terse_str_format_value_error();
1468 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001469 mp_raise_ValueError("incomplete format");
Damien George1e9a92f2014-11-06 17:36:16 +00001470 }
Dave Hylands6756a372014-04-02 11:42:39 -07001471 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001472
1473 // Tuple value lookup
1474 if (arg == MP_OBJ_NULL) {
Damien George90ab1912017-02-03 13:04:56 +11001475 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001476not_enough_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001477 mp_raise_TypeError("not enough arguments for format string");
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001478 }
1479 arg = args[arg_i++];
1480 }
Dave Hylands6756a372014-04-02 11:42:39 -07001481 switch (*str) {
1482 case 'c':
1483 if (MP_OBJ_IS_STR(arg)) {
Damien George6b341072017-03-25 19:48:18 +11001484 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001485 const char *s = mp_obj_str_get_data(arg, &slen);
1486 if (slen != 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001487 mp_raise_TypeError("%%c requires int or char");
Dave Hylands6756a372014-04-02 11:42:39 -07001488 }
Damien George7f9d1d62015-04-09 23:56:15 +01001489 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001490 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001491 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001492 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001493 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001494 mp_raise_TypeError("integer required");
Dave Hylands6756a372014-04-02 11:42:39 -07001495 }
Damien George11de8392014-06-05 18:57:38 +01001496 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001497
1498 case 'd':
1499 case 'i':
1500 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001501 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001502 break;
1503
Damien Georgefb510b32014-06-01 13:32:54 +01001504#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001505 case 'e':
1506 case 'E':
1507 case 'f':
1508 case 'F':
1509 case 'g':
1510 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001511 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001512 break;
1513#endif
1514
1515 case 'o':
1516 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001517 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001518 }
Damien George7f9d1d62015-04-09 23:56:15 +01001519 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001520 break;
1521
1522 case 'r':
1523 case 's':
1524 {
Damien George0b9ee862015-01-21 19:14:25 +00001525 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001526 mp_print_t arg_print;
1527 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001528 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1529 if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1530 // If we have something like b"%s" % b"1", bytes arg should be
1531 // printed undecorated.
1532 print_kind = PRINT_RAW;
1533 }
1534 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001535 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001536 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001537 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001538 }
Damien George50912e72015-01-20 11:55:10 +00001539 if (vlen > (uint)prec) {
1540 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001541 }
Damien George7f9d1d62015-04-09 23:56:15 +01001542 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001543 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001544 break;
1545 }
Dave Hylands6756a372014-04-02 11:42:39 -07001546
Dave Hylands6756a372014-04-02 11:42:39 -07001547 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001548 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001549 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001550 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001551
Dave Hylands6756a372014-04-02 11:42:39 -07001552 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001553 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1554 terse_str_format_value_error();
1555 } else {
1556 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1557 "unsupported format character '%c' (0x%x) at index %d",
1558 *str, *str, str - start_str));
1559 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001560 }
1561 }
1562
Damien George90ab1912017-02-03 13:04:56 +11001563 if (arg_i != n_args) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001564 mp_raise_TypeError("not all arguments converted during string formatting");
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001565 }
1566
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001567 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001568}
1569
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001570// The implementation is optimized, returning the original string if there's
1571// nothing to replace.
Damien George4b72b3a2016-01-03 14:21:40 +00001572STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001573 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001574
Damien George40f3c022014-07-03 13:25:24 +01001575 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001576 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001577 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001578 if (max_rep == 0) {
1579 return args[0];
1580 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001581 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001582 }
xbe480c15a2014-01-30 22:17:30 -08001583 }
Damien George94f68302014-01-31 23:45:12 +00001584
xbe729be9b2014-04-07 14:46:39 -07001585 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001586
Damien Georgeff715422014-04-07 00:39:13 +01001587 // check argument types
1588
Damien Georgec55a4d82014-12-24 20:28:30 +00001589 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1590
1591 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001592 bad_implicit_conversion(args[1]);
1593 }
1594
Damien Georgec55a4d82014-12-24 20:28:30 +00001595 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001596 bad_implicit_conversion(args[2]);
1597 }
1598
1599 // extract string data
1600
xbe480c15a2014-01-30 22:17:30 -08001601 GET_STR_DATA_LEN(args[0], str, str_len);
1602 GET_STR_DATA_LEN(args[1], old, old_len);
1603 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001604
1605 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001606 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001607 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001608 }
1609
Damien George94f68302014-01-31 23:45:12 +00001610 // data for the replaced string
1611 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001612 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001613
Damien George94f68302014-01-31 23:45:12 +00001614 // do 2 passes over the string:
1615 // first pass computes the required length of the replaced string
1616 // second pass does the replacements
1617 for (;;) {
Damien Georgec0d95002017-02-16 16:26:48 +11001618 size_t replaced_str_index = 0;
1619 size_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001620 const byte *old_occurrence;
1621 const byte *offset_ptr = str;
Damien Georgec0d95002017-02-16 16:26:48 +11001622 size_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001623 if (old_len == 0) {
1624 // if old_str is empty, copy new_str to start of replaced string
1625 // copy the replacement string
1626 if (data != NULL) {
1627 memcpy(data, new, new_len);
1628 }
1629 replaced_str_index += new_len;
1630 num_replacements_done++;
1631 }
Damien Georgec0d95002017-02-16 16:26:48 +11001632 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 +01001633 if (old_len == 0) {
1634 old_occurrence += 1;
1635 }
Damien George94f68302014-01-31 23:45:12 +00001636 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1637 if (data != NULL) {
1638 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1639 }
1640 replaced_str_index += old_occurrence - offset_ptr;
1641 // copy the replacement string
1642 if (data != NULL) {
1643 memcpy(data + replaced_str_index, new, new_len);
1644 }
1645 replaced_str_index += new_len;
1646 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001647 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001648 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001649 }
1650
1651 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1652 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001653 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001654 }
Damien Georgeff715422014-04-07 00:39:13 +01001655 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001656
1657 if (data == NULL) {
1658 // first pass
1659 if (num_replacements_done == 0) {
1660 // no substr found, return original string
1661 return args[0];
1662 } else {
1663 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001664 vstr_init_len(&vstr, replaced_str_index);
1665 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001666 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001667 }
1668 } else {
1669 // second pass, we are done
1670 break;
1671 }
xbe480c15a2014-01-30 22:17:30 -08001672 }
Damien George94f68302014-01-31 23:45:12 +00001673
Damien George05005f62015-01-21 22:48:37 +00001674 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001675}
Damien George65417c52017-07-02 23:35:42 +10001676MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe480c15a2014-01-30 22:17:30 -08001677
Damien George4b72b3a2016-01-03 14:21:40 +00001678STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001679 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001680 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +00001681
1682 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001683 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001684 bad_implicit_conversion(args[1]);
1685 }
xbe9e1e8cd2014-03-12 22:57:16 -07001686
1687 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1688 GET_STR_DATA_LEN(args[1], needle, needle_len);
1689
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001690 const byte *start = haystack;
1691 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001692 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001693 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001694 }
1695 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001696 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001697 }
1698
Damien George536dde22014-03-13 22:07:55 +00001699 // if needle_len is zero then we count each gap between characters as an occurrence
1700 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001701 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001702 }
1703
Damien George536dde22014-03-13 22:07:55 +00001704 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001705 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001706 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1707 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001708 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001709 haystack_ptr += needle_len;
1710 } else {
1711 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001712 }
xbe9e1e8cd2014-03-12 22:57:16 -07001713 }
1714
1715 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1716}
Damien George65417c52017-07-02 23:35:42 +10001717MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe9e1e8cd2014-03-12 22:57:16 -07001718
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001719#if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgec0d95002017-02-16 16:26:48 +11001720STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001721 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001722 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1723 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001724 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001725 }
Damien Georgeb035db32014-03-21 20:39:40 +00001726
xbe613a8e32014-03-18 00:06:29 -07001727 GET_STR_DATA_LEN(self_in, str, str_len);
1728 GET_STR_DATA_LEN(arg, sep, sep_len);
1729
1730 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001731 mp_raise_ValueError("empty separator");
xbe613a8e32014-03-18 00:06:29 -07001732 }
Damien Georgeb035db32014-03-21 20:39:40 +00001733
Damien Georgec55a4d82014-12-24 20:28:30 +00001734 mp_obj_t result[3];
1735 if (self_type == &mp_type_str) {
1736 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1737 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1738 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1739 } else {
1740 result[0] = mp_const_empty_bytes;
1741 result[1] = mp_const_empty_bytes;
1742 result[2] = mp_const_empty_bytes;
1743 }
Damien Georgeb035db32014-03-21 20:39:40 +00001744
1745 if (direction > 0) {
1746 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001747 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001748 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001749 }
xbe613a8e32014-03-18 00:06:29 -07001750
xbe17a5a832014-03-23 23:31:58 -07001751 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1752 if (position_ptr != NULL) {
Damien Georgec0d95002017-02-16 16:26:48 +11001753 size_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001754 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001755 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001756 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 -07001757 }
Damien Georgeb035db32014-03-21 20:39:40 +00001758
xbe0a6894c2014-03-21 01:12:26 -07001759 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001760}
1761
Damien Georgeb035db32014-03-21 20:39:40 +00001762STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1763 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001764}
Damien George65417c52017-07-02 23:35:42 +10001765MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001766
Damien Georgeb035db32014-03-21 20:39:40 +00001767STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1768 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001769}
Damien George65417c52017-07-02 23:35:42 +10001770MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001771#endif
xbe4504ea82014-03-19 00:46:14 -07001772
Paul Sokolovsky69135212014-05-10 19:47:41 +03001773// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001774STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001775 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001776 vstr_t vstr;
1777 vstr_init_len(&vstr, self_len);
1778 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +11001779 for (size_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001780 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001781 }
Damien George05005f62015-01-21 22:48:37 +00001782 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001783}
1784
1785STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001786 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001787}
Damien George65417c52017-07-02 23:35:42 +10001788MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001789
1790STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001791 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001792}
Damien George65417c52017-07-02 23:35:42 +10001793MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001794
Damien Georgefcc9cf62014-06-01 18:22:09 +01001795STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001796 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001797
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001798 if (self_len == 0) {
1799 return mp_const_false; // default to False for empty str
1800 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001801
Damien Georgefcc9cf62014-06-01 18:22:09 +01001802 if (f != unichar_isupper && f != unichar_islower) {
Damien Georgec0d95002017-02-16 16:26:48 +11001803 for (size_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001804 if (!f(*self_data++)) {
1805 return mp_const_false;
1806 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001807 }
1808 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001809 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001810
Damien Georgec0d95002017-02-16 16:26:48 +11001811 for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001812 if (unichar_isalpha(*self_data++)) {
1813 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001814 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1815 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001816 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001817 }
1818 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001819
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001820 if (!contains_alpha) {
1821 return mp_const_false;
1822 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001823 }
1824
1825 return mp_const_true;
1826}
1827
1828STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001829 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001830}
Damien George65417c52017-07-02 23:35:42 +10001831MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001832
1833STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001834 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001835}
Damien George65417c52017-07-02 23:35:42 +10001836MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001837
1838STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001839 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001840}
Damien George65417c52017-07-02 23:35:42 +10001841MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001842
1843STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001844 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001845}
Damien George65417c52017-07-02 23:35:42 +10001846MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001847
1848STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001849 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001850}
Damien George65417c52017-07-02 23:35:42 +10001851MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001852
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001853#if MICROPY_CPYTHON_COMPAT
Ville Skyttäca16c382017-05-29 10:08:14 +03001854// These methods are superfluous in the presence of str() and bytes()
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001855// constructors.
1856// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001857STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001858 mp_obj_t new_args[2];
1859 if (n_args == 1) {
1860 new_args[0] = args[0];
1861 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1862 args = new_args;
1863 n_args++;
1864 }
Damien George5b3f0b72016-01-03 15:55:55 +00001865 return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001866}
Damien George65417c52017-07-02 23:35:42 +10001867MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001868
1869// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001870STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001871 mp_obj_t new_args[2];
1872 if (n_args == 1) {
1873 new_args[0] = args[0];
1874 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1875 args = new_args;
1876 n_args++;
1877 }
Damien George5b3f0b72016-01-03 15:55:55 +00001878 return bytes_make_new(NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001879}
Damien George65417c52017-07-02 23:35:42 +10001880MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001881#endif
1882
Damien George4d917232014-08-30 14:28:06 +01001883mp_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 +01001884 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001885 GET_STR_DATA_LEN(self_in, str_data, str_len);
1886 bufinfo->buf = (void*)str_data;
1887 bufinfo->len = str_len;
Damien George12dd8df2016-05-07 21:18:17 +01001888 bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
Damien George2da98302014-03-09 19:58:18 +00001889 return 0;
1890 } else {
1891 // can't write to a string
1892 bufinfo->buf = NULL;
1893 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001894 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001895 return 1;
1896 }
1897}
1898
Damien Georgecbf76742015-11-27 13:38:15 +00001899STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001900#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001901 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001902 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1903 // If we have separate unicode type, then here we have methods only
1904 // for bytes type, and it should not have encode() methods. Otherwise,
1905 // we have non-compliant-but-practical bytestring type, which shares
1906 // method table with bytes, so they both have encode() and decode()
1907 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001908 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001909 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001910#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001911 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1912 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1913 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1914 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1915 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1916 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001917 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001918 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001919 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001920 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1921 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1922 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1923 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1924 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1925 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1926 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1927 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1928 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001929 #if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgecbf76742015-11-27 13:38:15 +00001930 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1931 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001932 #endif
Paul Sokolovsky15633882016-08-07 15:24:57 +03001933 #if MICROPY_PY_BUILTINS_STR_CENTER
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +03001934 { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
Paul Sokolovsky15633882016-08-07 15:24:57 +03001935 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001936 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1937 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1938 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1939 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1940 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1941 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1942 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001943};
Damien George97209d32014-01-07 15:58:30 +00001944
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001945STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001946
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001947#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgeae8d8672016-01-09 23:14:54 +00001948STATIC 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 +01001949
Damien George3e1a5c12014-03-29 13:43:38 +00001950const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001951 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001952 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001953 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001954 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001955 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001956 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001957 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001958 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001959 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001960};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001961#endif
Damiend99b0522013-12-21 18:17:45 +00001962
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001963// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001964const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001965 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001966 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001967 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001968 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001969 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001970 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001971 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001972 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001973 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001974};
1975
Damien Georgedfa563c2017-10-04 17:59:22 +11001976// The zero-length bytes object, with data that includes a null-terminating byte
1977const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte*)""};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001978
Damien George77089be2015-01-21 23:08:36 +00001979// Create a str/bytes object using the given data. New memory is allocated and
1980// the data is copied across.
Damien George999cedb2015-11-27 17:01:44 +00001981mp_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 +02001982 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001983 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001984 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001985 if (data) {
1986 o->hash = qstr_compute_hash(data, len);
1987 byte *p = m_new(byte, len + 1);
1988 o->data = p;
1989 memcpy(p, data, len * sizeof(byte));
1990 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1991 }
Damien George999cedb2015-11-27 17:01:44 +00001992 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001993}
1994
Damien George46017592017-11-16 13:17:51 +11001995// Create a str using a qstr to store the data; may use existing or new qstr.
1996mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len) {
1997 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
1998}
1999
Damien George77089be2015-01-21 23:08:36 +00002000// Create a str/bytes object from the given vstr. The vstr buffer is resized to
2001// the exact length required and then reused for the str/bytes object. The vstr
2002// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00002003mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
2004 // if not a bytes object, look if a qstr with this data already exists
2005 if (type == &mp_type_str) {
2006 qstr q = qstr_find_strn(vstr->buf, vstr->len);
2007 if (q != MP_QSTR_NULL) {
2008 vstr_clear(vstr);
2009 vstr->alloc = 0;
2010 return MP_OBJ_NEW_QSTR(q);
2011 }
2012 }
2013
2014 // make a new str/bytes object
2015 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
2016 o->base.type = type;
2017 o->len = vstr->len;
2018 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07002019 if (vstr->len + 1 == vstr->alloc) {
2020 o->data = (byte*)vstr->buf;
2021 } else {
2022 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
2023 }
Damien George0d3cb672015-01-28 23:43:01 +00002024 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00002025 vstr->buf = NULL;
2026 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00002027 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00002028}
2029
Damien George46017592017-11-16 13:17:51 +11002030mp_obj_t mp_obj_new_str(const char* data, size_t len) {
2031 qstr q = qstr_find_strn(data, len);
2032 if (q != MP_QSTR_NULL) {
2033 // qstr with this data already exists
2034 return MP_OBJ_NEW_QSTR(q);
Damien George5fa93b62014-01-22 14:35:10 +00002035 } else {
Damien George46017592017-11-16 13:17:51 +11002036 // no existing qstr, don't make one
2037 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002038 }
Damien George5fa93b62014-01-22 14:35:10 +00002039}
2040
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002041mp_obj_t mp_obj_str_intern(mp_obj_t str) {
2042 GET_STR_DATA_LEN(str, data, len);
Damien George46017592017-11-16 13:17:51 +11002043 return mp_obj_new_str_via_qstr((const char*)data, len);
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002044}
2045
Damien Georgec0d95002017-02-16 16:26:48 +11002046mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01002047 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002048}
2049
Damien George5fa93b62014-01-22 14:35:10 +00002050bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
2051 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
2052 return s1 == s2;
2053 } else {
2054 GET_STR_HASH(s1, h1);
2055 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03002056 // If any of hashes is 0, it means it's not valid
2057 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00002058 return false;
2059 }
2060 GET_STR_DATA_LEN(s1, d1, l1);
2061 GET_STR_DATA_LEN(s2, d2, l2);
2062 if (l1 != l2) {
2063 return false;
2064 }
Damien George1e708fe2014-01-23 18:27:51 +00002065 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002066 }
Damien George5fa93b62014-01-22 14:35:10 +00002067}
2068
Damien Georgedeed0872014-04-06 11:11:15 +01002069STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002070 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03002071 mp_raise_TypeError("can't convert to str implicitly");
Damien George1e9a92f2014-11-06 17:36:16 +00002072 } else {
stijnbf29fe22017-03-15 12:17:38 +01002073 const qstr src_name = mp_obj_get_type(self_in)->name;
Damien George1e9a92f2014-11-06 17:36:16 +00002074 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
stijnbf29fe22017-03-15 12:17:38 +01002075 "can't convert '%q' object to %q implicitly",
2076 src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str));
Damien George1e9a92f2014-11-06 17:36:16 +00002077 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002078}
2079
Damien Georgeb829b5c2014-01-25 13:51:19 +00002080// use this if you will anyway convert the string to a qstr
2081// will be more efficient for the case where it's already a qstr
2082qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2083 if (MP_OBJ_IS_QSTR(self_in)) {
2084 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002085 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002086 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002087 return qstr_from_strn((char*)self->data, self->len);
2088 } else {
2089 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002090 }
2091}
2092
2093// only use this function if you need the str data to be zero terminated
2094// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2095const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002096 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002097 GET_STR_DATA_LEN(self_in, s, l);
2098 (void)l; // len unused
2099 return (const char*)s;
2100 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002101 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002102 }
2103}
2104
Damien George6b341072017-03-25 19:48:18 +11002105const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002106 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002107 GET_STR_DATA_LEN(self_in, s, l);
2108 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002109 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002110 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002111 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002112 }
Damiend99b0522013-12-21 18:17:45 +00002113}
xyb8cfc9f02014-01-05 18:47:51 +08002114
Damien George04353cc2015-10-18 23:09:04 +01002115#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
Damien Georgec3f64d92015-11-27 12:23:18 +00002116const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien George04353cc2015-10-18 23:09:04 +01002117 if (MP_OBJ_IS_QSTR(self_in)) {
2118 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2119 } else {
2120 *len = ((mp_obj_str_t*)self_in)->len;
2121 return ((mp_obj_str_t*)self_in)->data;
2122 }
2123}
2124#endif
2125
xyb8cfc9f02014-01-05 18:47:51 +08002126/******************************************************************************/
2127/* str iterator */
2128
Damien George44e7cbf2015-05-17 16:44:24 +01002129typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002130 mp_obj_base_t base;
Damien George8212d972016-01-03 16:27:55 +00002131 mp_fun_1_t iternext;
Damien George5fa93b62014-01-22 14:35:10 +00002132 mp_obj_t str;
Damien Georgec0d95002017-02-16 16:26:48 +11002133 size_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002134} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002135
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002136#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002137STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George326e8862017-06-08 00:40:38 +10002138 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002139 GET_STR_DATA_LEN(self->str, str, len);
2140 if (self->cur < len) {
Damien George46017592017-11-16 13:17:51 +11002141 mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)str + self->cur, 1);
xyb8cfc9f02014-01-05 18:47:51 +08002142 self->cur += 1;
2143 return o_out;
2144 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002145 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002146 }
2147}
2148
Damien Georgeae8d8672016-01-09 23:14:54 +00002149STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2150 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2151 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002152 o->base.type = &mp_type_polymorph_iter;
2153 o->iternext = str_it_iternext;
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002154 o->str = str;
2155 o->cur = 0;
Damien George326e8862017-06-08 00:40:38 +10002156 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002157}
2158#endif
2159
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002160STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002161 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002162 GET_STR_DATA_LEN(self->str, str, len);
2163 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002164 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002165 self->cur += 1;
2166 return o_out;
2167 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002168 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002169 }
2170}
2171
Damien Georgeae8d8672016-01-09 23:14:54 +00002172mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2173 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2174 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002175 o->base.type = &mp_type_polymorph_iter;
2176 o->iternext = bytes_it_iternext;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002177 o->str = str;
2178 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002179 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002180}