blob: 30153813dab646cc16aa9ff2affdb10f05c11574 [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 George8d956c22017-11-16 14:02:28 +1100167
168 // Check if a qstr with this data already exists
169 qstr q = qstr_find_strn((const char*)str_data, str_len);
170 if (q != MP_QSTR_NULL) {
171 return MP_OBJ_NEW_QSTR(q);
172 }
173
Damien George1f1d5192017-11-16 13:53:04 +1100174 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len));
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200175 o->data = str_data;
176 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000177 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200178 } else {
179 mp_buffer_info_t bufinfo;
180 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
tll68c28172017-06-24 08:38:32 +0800181 #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK
182 if (!utf8_check(bufinfo.buf, bufinfo.len)) {
183 mp_raise_msg(&mp_type_UnicodeError, NULL);
184 }
185 #endif
Damien George46017592017-11-16 13:17:51 +1100186 return mp_obj_new_str(bufinfo.buf, bufinfo.len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200187 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200188 }
189}
190
Damien George5b3f0b72016-01-03 15:55:55 +0000191STATIC 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 +0000192 (void)type_in;
193
Damien George3a2171e2015-09-04 16:53:46 +0100194 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300195 if (n_kw != 0) {
196 mp_arg_error_unimpl_kw();
197 }
Damien George3a2171e2015-09-04 16:53:46 +0100198 #else
199 (void)n_kw;
200 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300201
Damien George42cec5c2015-09-04 16:51:55 +0100202 if (n_args == 0) {
203 return mp_const_empty_bytes;
204 }
205
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200206 if (MP_OBJ_IS_STR(args[0])) {
207 if (n_args < 2 || n_args > 3) {
208 goto wrong_args;
209 }
210 GET_STR_DATA_LEN(args[0], str_data, str_len);
211 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000212 if (str_hash == 0) {
213 str_hash = qstr_compute_hash(str_data, str_len);
214 }
Damien George1f1d5192017-11-16 13:53:04 +1100215 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(&mp_type_bytes, NULL, str_len));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 o->data = str_data;
217 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000218 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200219 }
220
221 if (n_args > 1) {
222 goto wrong_args;
223 }
224
225 if (MP_OBJ_IS_SMALL_INT(args[0])) {
226 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000227 vstr_t vstr;
228 vstr_init_len(&vstr, len);
229 memset(vstr.buf, 0, len);
230 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200231 }
232
Damien George32ef3a32014-12-04 15:46:14 +0000233 // check if argument has the buffer protocol
234 mp_buffer_info_t bufinfo;
235 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
Damien George1f1d5192017-11-16 13:53:04 +1100236 return mp_obj_new_bytes(bufinfo.buf, bufinfo.len);
Damien George32ef3a32014-12-04 15:46:14 +0000237 }
238
Damien George0b9ee862015-01-21 19:14:25 +0000239 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200240 // Try to create array of exact len if initializer len is known
241 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
242 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000243 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200244 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000245 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000246 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200247 }
248
Damien Georgeae8d8672016-01-09 23:14:54 +0000249 mp_obj_iter_buf_t iter_buf;
250 mp_obj_t iterable = mp_getiter(args[0], &iter_buf);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200251 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100252 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100253 mp_int_t val = mp_obj_get_int(item);
Paul Sokolovsky9a973972017-04-02 21:20:07 +0300254 #if MICROPY_FULL_CHECKS
Damien Georgeede0f3a2015-04-23 15:28:18 +0100255 if (val < 0 || val > 255) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300256 mp_raise_ValueError("bytes value out of range");
Damien Georgeede0f3a2015-04-23 15:28:18 +0100257 }
258 #endif
259 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200260 }
261
Damien George0b9ee862015-01-21 19:14:25 +0000262 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200263
264wrong_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300265 mp_raise_TypeError("wrong number of arguments");
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200266}
267
Damien George55baff42014-01-21 21:40:13 +0000268// like strstr but with specified length and allows \0 bytes
269// TODO replace with something more efficient/standard
Damien Georgec0d95002017-02-16 16:26:48 +1100270const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
Damien George55baff42014-01-21 21:40:13 +0000271 if (hlen >= nlen) {
Damien Georgec0d95002017-02-16 16:26:48 +1100272 size_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700273 if (direction > 0) {
274 str_index = 0;
275 str_index_end = hlen - nlen;
276 } else {
277 str_index = hlen - nlen;
278 str_index_end = 0;
279 }
280 for (;;) {
281 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
282 //found
283 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000284 }
xbe17a5a832014-03-23 23:31:58 -0700285 if (str_index == str_index_end) {
286 //not found
287 break;
Damien George55baff42014-01-21 21:40:13 +0000288 }
xbe17a5a832014-03-23 23:31:58 -0700289 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000290 }
291 }
292 return NULL;
293}
294
Damien Georgea75b02e2014-08-27 09:20:30 +0100295// Note: this function is used to check if an object is a str or bytes, which
296// works because both those types use it as their binary_op method. Revisit
297// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien George58321dd2017-08-29 13:04:01 +1000298mp_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 +0000299 // check for modulo
300 if (op == MP_BINARY_OP_MODULO) {
Damien George7317e342017-02-03 12:13:44 +1100301 mp_obj_t *args = &rhs_in;
Damien George6213ad72017-03-25 19:35:08 +1100302 size_t n_args = 1;
Damien Georgea65c03c2014-11-05 16:30:34 +0000303 mp_obj_t dict = MP_OBJ_NULL;
304 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
305 // TODO: Support tuple subclasses?
306 mp_obj_tuple_get(rhs_in, &n_args, &args);
307 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000308 dict = rhs_in;
Damien Georgea65c03c2014-11-05 16:30:34 +0000309 }
310 return str_modulo_format(lhs_in, n_args, args, dict);
311 }
312
313 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300314 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000315 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
316
317 // check for multiply
318 if (op == MP_BINARY_OP_MULTIPLY) {
319 mp_int_t n;
320 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
321 return MP_OBJ_NULL; // op not supported
322 }
323 if (n <= 0) {
324 if (lhs_type == &mp_type_str) {
325 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
326 } else {
327 return mp_const_empty_bytes;
328 }
329 }
Damien George05005f62015-01-21 22:48:37 +0000330 vstr_t vstr;
331 vstr_init_len(&vstr, lhs_len * n);
332 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
333 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000334 }
335
336 // From now on all operations allow:
337 // - str with str
338 // - bytes with bytes
339 // - bytes with bytearray
340 // - bytes with array.array
341 // To do this efficiently we use the buffer protocol to extract the raw
342 // data for the rhs, but only if the lhs is a bytes object.
343 //
344 // NOTE: CPython does not allow comparison between bytes ard array.array
345 // (even if the array is of type 'b'), even though it allows addition of
346 // such types. We are not compatible with this (we do allow comparison
347 // of bytes with anything that has the buffer protocol). It would be
348 // easy to "fix" this with a bit of extra logic below, but it costs code
349 // size and execution time so we don't.
350
351 const byte *rhs_data;
Damien Georgec0d95002017-02-16 16:26:48 +1100352 size_t rhs_len;
Damien Georgea65c03c2014-11-05 16:30:34 +0000353 if (lhs_type == mp_obj_get_type(rhs_in)) {
354 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
355 rhs_data = rhs_data_;
356 rhs_len = rhs_len_;
357 } else if (lhs_type == &mp_type_bytes) {
358 mp_buffer_info_t bufinfo;
359 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000360 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000361 }
362 rhs_data = bufinfo.buf;
363 rhs_len = bufinfo.len;
364 } else {
Damien George3d25d9c2017-08-09 21:25:48 +1000365 // LHS is str and RHS has an incompatible type
366 // (except if operation is EQUAL, but that's handled by mp_obj_equal)
367 bad_implicit_conversion(rhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000368 }
369
Damiend99b0522013-12-21 18:17:45 +0000370 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100371 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000372 case MP_BINARY_OP_INPLACE_ADD: {
Damien Georged279bcf2017-03-16 14:30:04 +1100373 if (lhs_len == 0 && mp_obj_get_type(rhs_in) == lhs_type) {
Paul Sokolovskye2e66322017-01-27 00:40:47 +0300374 return rhs_in;
375 }
376 if (rhs_len == 0) {
377 return lhs_in;
378 }
379
Damien George05005f62015-01-21 22:48:37 +0000380 vstr_t vstr;
381 vstr_init_len(&vstr, lhs_len + rhs_len);
382 memcpy(vstr.buf, lhs_data, lhs_len);
383 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
384 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200385 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200386
Damien George5e34a112017-11-24 13:04:24 +1100387 case MP_BINARY_OP_CONTAINS:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300388 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300389
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300390 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
391 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 +0100392 case MP_BINARY_OP_LESS:
393 case MP_BINARY_OP_LESS_EQUAL:
394 case MP_BINARY_OP_MORE:
395 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300396 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000397
Damien George58321dd2017-08-29 13:04:01 +1000398 default:
399 return MP_OBJ_NULL; // op not supported
400 }
Damiend99b0522013-12-21 18:17:45 +0000401}
402
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300403#if !MICROPY_PY_BUILTINS_STR_UNICODE
404// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000405const 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 +0300406 mp_obj_t index, bool is_slice) {
Damien Georgec88cfe12017-03-23 16:17:40 +1100407 size_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300408 return self_data + index_val;
409}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300410#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300411
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300412// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
413STATIC 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 +0300414 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100415 GET_STR_DATA_LEN(self_in, self_data, self_len);
416 if (value == MP_OBJ_SENTINEL) {
417 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100418#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100419 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300420 mp_bound_slice_t slice;
421 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000422 mp_raise_NotImplementedError("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100423 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100424 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100425 }
426#endif
Damien Georgec88cfe12017-03-23 16:17:40 +1100427 size_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100428 // If we have unicode enabled the type will always be bytes, so take the short cut.
429 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300430 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100431 } else {
Damien George46017592017-11-16 13:17:51 +1100432 return mp_obj_new_str_via_qstr((char*)&self_data[index_val], 1);
Damien George729f7b42014-04-17 22:10:53 +0100433 }
434 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100435 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100436 }
437}
438
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200439STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300440 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300441 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000442
Damien Georgefe8fb912014-01-02 16:36:09 +0000443 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000444 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000445
446 // process args
Damien George6213ad72017-03-25 19:35:08 +1100447 size_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000448 mp_obj_t *seq_items;
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100449
450 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list) && !MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
451 // arg is not a list nor a tuple, try to convert it to a list
452 // TODO: Try to optimize?
453 arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
Damiend99b0522013-12-21 18:17:45 +0000454 }
Krzysztof Blazewicz7e480e82017-03-04 12:29:20 +0100455 mp_obj_get_array(arg, &seq_len, &seq_items);
Damien Georgefe8fb912014-01-02 16:36:09 +0000456
457 // count required length
Damien Georgec0d95002017-02-16 16:26:48 +1100458 size_t required_len = 0;
459 for (size_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300460 if (mp_obj_get_type(seq_items[i]) != self_type) {
Damien George21967992016-08-14 16:51:54 +1000461 mp_raise_TypeError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300462 "join expects a list of str/bytes objects consistent with self object");
Damiend99b0522013-12-21 18:17:45 +0000463 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000464 if (i > 0) {
465 required_len += sep_len;
466 }
Damien George5fa93b62014-01-22 14:35:10 +0000467 GET_STR_LEN(seq_items[i], l);
468 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000469 }
470
471 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000472 vstr_t vstr;
473 vstr_init_len(&vstr, required_len);
474 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +1100475 for (size_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000476 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000477 memcpy(data, sep_str, sep_len);
478 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000479 }
Damien George5fa93b62014-01-22 14:35:10 +0000480 GET_STR_DATA_LEN(seq_items[i], s, l);
481 memcpy(data, s, l);
482 data += l;
Damiend99b0522013-12-21 18:17:45 +0000483 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000484
485 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000486 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000487}
Damien George65417c52017-07-02 23:35:42 +1000488MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Damiend99b0522013-12-21 18:17:45 +0000489
Damien Georgecc80c4d2016-05-13 12:21:32 +0100490mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300491 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100492 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200493 mp_obj_t sep = mp_const_none;
494 if (n_args > 1) {
495 sep = args[1];
496 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100497 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200498 }
499 }
Damien Georgedeed0872014-04-06 11:11:15 +0100500
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200501 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000502 GET_STR_DATA_LEN(args[0], s, len);
503 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200504
Damien Georgedeed0872014-04-06 11:11:15 +0100505 if (sep == mp_const_none) {
506 // sep not given, so separate on whitespace
507
508 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300509 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100510 while (s < top && splits != 0) {
511 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300512 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100513 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100514 if (s >= top) {
515 break;
516 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300517 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100518 if (splits > 0) {
519 splits--;
520 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200521 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200522
Damien Georgedeed0872014-04-06 11:11:15 +0100523 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100524 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100525 }
526
527 } else {
528 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300529 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000530 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300531 }
Damien Georgedeed0872014-04-06 11:11:15 +0100532
Damien George6b341072017-03-25 19:48:18 +1100533 size_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100534 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
535
536 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300537 mp_raise_ValueError("empty separator");
Damien Georgedeed0872014-04-06 11:11:15 +0100538 }
539
540 for (;;) {
541 const byte *start = s;
542 for (;;) {
543 if (splits == 0 || s + sep_len > top) {
544 s = top;
545 break;
546 } else if (memcmp(s, sep_str, sep_len) == 0) {
547 break;
548 }
549 s++;
550 }
Damien Georgecc80c4d2016-05-13 12:21:32 +0100551 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100552 if (s >= top) {
553 break;
554 }
555 s += sep_len;
556 if (splits > 0) {
557 splits--;
558 }
559 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200560 }
561
562 return res;
563}
Damien George65417c52017-07-02 23:35:42 +1000564MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200565
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300566#if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien George4b72b3a2016-01-03 14:21:40 +0000567STATIC 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 +0100568 enum { ARG_keepends };
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300569 static const mp_arg_t allowed_args[] = {
570 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
571 };
572
573 // parse args
Damien Georgecc80c4d2016-05-13 12:21:32 +0100574 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
575 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 +0300576
Damien Georgecc80c4d2016-05-13 12:21:32 +0100577 const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
578 mp_obj_t res = mp_obj_new_list(0, NULL);
579
580 GET_STR_DATA_LEN(pos_args[0], s, len);
581 const byte *top = s + len;
582
583 while (s < top) {
584 const byte *start = s;
585 size_t match = 0;
586 while (s < top) {
587 if (*s == '\n') {
588 match = 1;
589 break;
590 } else if (*s == '\r') {
591 if (s[1] == '\n') {
592 match = 2;
593 } else {
594 match = 1;
595 }
596 break;
597 }
598 s++;
599 }
600 size_t sub_len = s - start;
601 if (args[ARG_keepends].u_bool) {
602 sub_len += match;
603 }
604 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
605 s += match;
606 }
607
608 return res;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300609}
Damien George65417c52017-07-02 23:35:42 +1000610MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300611#endif
612
Damien George4b72b3a2016-01-03 14:21:40 +0000613STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300614 if (n_args < 3) {
615 // If we don't have split limit, it doesn't matter from which side
616 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200617 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300618 }
619 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
620 mp_obj_t sep = args[1];
621 GET_STR_DATA_LEN(args[0], s, len);
622
Damien George40f3c022014-07-03 13:25:24 +0100623 mp_int_t splits = mp_obj_get_int(args[2]);
Damien George9f85c4f2017-06-02 13:07:22 +1000624 if (splits < 0) {
625 // Negative limit means no limit, so delegate to split().
626 return mp_obj_str_split(n_args, args);
627 }
628
Damien George40f3c022014-07-03 13:25:24 +0100629 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300630 // Preallocate list to the max expected # of elements, as we
631 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000632 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100633 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300634
635 if (sep == mp_const_none) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000636 mp_raise_NotImplementedError("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300637 } else {
Damien George6b341072017-03-25 19:48:18 +1100638 size_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300639 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
640
641 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300642 mp_raise_ValueError("empty separator");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300643 }
644
645 const byte *beg = s;
646 const byte *last = s + len;
647 for (;;) {
648 s = last - sep_len;
649 for (;;) {
650 if (splits == 0 || s < beg) {
651 break;
652 } else if (memcmp(s, sep_str, sep_len) == 0) {
653 break;
654 }
655 s--;
656 }
657 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100658 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300659 break;
660 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100661 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 +0300662 last = s;
663 if (splits > 0) {
664 splits--;
665 }
666 }
667 if (idx != 0) {
668 // We split less parts than split limit, now go cleanup surplus
Damien Georgec0d95002017-02-16 16:26:48 +1100669 size_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100670 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300671 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
672 res->len = used;
673 }
674 }
675
Damien George999cedb2015-11-27 17:01:44 +0000676 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300677}
Damien George65417c52017-07-02 23:35:42 +1000678MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300679
Damien Georgec0d95002017-02-16 16:26:48 +1100680STATIC 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 +0300681 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300682 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +0000683
684 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000685 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000686 bad_implicit_conversion(args[1]);
687 }
John R. Lentone8204912014-01-12 21:53:52 +0000688
Damien George5fa93b62014-01-22 14:35:10 +0000689 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
690 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000691
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300692 const byte *start = haystack;
693 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000694 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300695 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000696 }
697 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300698 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000699 }
700
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300701 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000702 if (p == NULL) {
703 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700704 if (is_index) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300705 mp_raise_ValueError("substring not found");
xbe3d9a39e2014-04-08 11:42:19 -0700706 } else {
707 return MP_OBJ_NEW_SMALL_INT(-1);
708 }
Damien George23005372014-01-13 19:39:01 +0000709 } else {
710 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300711 #if MICROPY_PY_BUILTINS_STR_UNICODE
712 if (self_type == &mp_type_str) {
713 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
714 }
715 #endif
xbe17a5a832014-03-23 23:31:58 -0700716 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000717 }
John R. Lentone8204912014-01-12 21:53:52 +0000718}
719
Damien George4b72b3a2016-01-03 14:21:40 +0000720STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700721 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700722}
Damien George65417c52017-07-02 23:35:42 +1000723MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -0700724
Damien George4b72b3a2016-01-03 14:21:40 +0000725STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700726 return str_finder(n_args, args, -1, false);
727}
Damien George65417c52017-07-02 23:35:42 +1000728MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -0700729
Damien George4b72b3a2016-01-03 14:21:40 +0000730STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700731 return str_finder(n_args, args, 1, true);
732}
Damien George65417c52017-07-02 23:35:42 +1000733MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
xbe3d9a39e2014-04-08 11:42:19 -0700734
Damien George4b72b3a2016-01-03 14:21:40 +0000735STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700736 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700737}
Damien George65417c52017-07-02 23:35:42 +1000738MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
xbe17a5a832014-03-23 23:31:58 -0700739
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200740// TODO: (Much) more variety in args
Damien George4b72b3a2016-01-03 14:21:40 +0000741STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300742 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300743 GET_STR_DATA_LEN(args[0], str, str_len);
Paul Sokolovsky37379a22017-08-29 00:06:21 +0300744 size_t prefix_len;
745 const char *prefix = mp_obj_str_get_data(args[1], &prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300746 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300747 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300748 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300749 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300750 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200751 return mp_const_false;
752 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300753 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200754}
Damien George65417c52017-07-02 23:35:42 +1000755MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200756
Damien George4b72b3a2016-01-03 14:21:40 +0000757STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300758 GET_STR_DATA_LEN(args[0], str, str_len);
Paul Sokolovsky37379a22017-08-29 00:06:21 +0300759 size_t suffix_len;
760 const char *suffix = mp_obj_str_get_data(args[1], &suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100761 if (n_args > 2) {
Javier Candeira35a1fea2017-08-09 14:40:45 +1000762 mp_raise_NotImplementedError("start/end indices");
Damien George55b11e62015-09-04 16:49:56 +0100763 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300764
765 if (suffix_len > str_len) {
766 return mp_const_false;
767 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300768 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300769}
Damien George65417c52017-07-02 23:35:42 +1000770MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300771
Paul Sokolovsky88107842014-04-26 06:20:08 +0300772enum { LSTRIP, RSTRIP, STRIP };
773
Damien George90ab1912017-02-03 13:04:56 +1100774STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300775 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300776 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000777
778 const byte *chars_to_del;
779 uint chars_to_del_len;
780 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800781
782 if (n_args == 1) {
783 chars_to_del = whitespace;
Paul Sokolovskyfc9a6dd2017-09-19 21:19:23 +0300784 chars_to_del_len = sizeof(whitespace) - 1;
xbe7b0f39f2014-01-08 14:23:45 -0800785 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300786 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000787 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300788 }
Damien George5fa93b62014-01-22 14:35:10 +0000789 GET_STR_DATA_LEN(args[1], s, l);
790 chars_to_del = s;
791 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800792 }
793
Damien George5fa93b62014-01-22 14:35:10 +0000794 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800795
Damien Georgec0d95002017-02-16 16:26:48 +1100796 size_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800797 bool first_good_char_pos_set = false;
Damien Georgec0d95002017-02-16 16:26:48 +1100798 size_t last_good_char_pos = 0;
799 size_t i = 0;
800 int delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300801 if (type == RSTRIP) {
802 i = orig_str_len - 1;
803 delta = -1;
804 }
Damien Georgec0d95002017-02-16 16:26:48 +1100805 for (size_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700806 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800807 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300808 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800809 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300810 if (type == LSTRIP) {
811 last_good_char_pos = orig_str_len - 1;
812 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300813 } else if (type == RSTRIP) {
814 first_good_char_pos = 0;
815 last_good_char_pos = i;
816 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300817 }
xbe7b0f39f2014-01-08 14:23:45 -0800818 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300819 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800820 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300821 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800822 }
823
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300824 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000825 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000826 if (self_type == &mp_type_str) {
827 return MP_OBJ_NEW_QSTR(MP_QSTR_);
828 } else {
829 return mp_const_empty_bytes;
830 }
xbe7b0f39f2014-01-08 14:23:45 -0800831 }
832
833 assert(last_good_char_pos >= first_good_char_pos);
Ville Skyttäca16c382017-05-29 10:08:14 +0300834 //+1 to accommodate the last character
Damien Georgec0d95002017-02-16 16:26:48 +1100835 size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300836 if (stripped_len == orig_str_len) {
837 // If nothing was stripped, don't bother to dup original string
838 // TODO: watch out for this case when we'll get to bytearray.strip()
839 assert(first_good_char_pos == 0);
840 return args[0];
841 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100842 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800843}
844
Damien George4b72b3a2016-01-03 14:21:40 +0000845STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300846 return str_uni_strip(STRIP, n_args, args);
847}
Damien George65417c52017-07-02 23:35:42 +1000848MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300849
Damien George4b72b3a2016-01-03 14:21:40 +0000850STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300851 return str_uni_strip(LSTRIP, n_args, args);
852}
Damien George65417c52017-07-02 23:35:42 +1000853MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300854
Damien George4b72b3a2016-01-03 14:21:40 +0000855STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300856 return str_uni_strip(RSTRIP, n_args, args);
857}
Damien George65417c52017-07-02 23:35:42 +1000858MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovsky88107842014-04-26 06:20:08 +0300859
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300860#if MICROPY_PY_BUILTINS_STR_CENTER
861STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
862 GET_STR_DATA_LEN(str_in, str, str_len);
Paul Sokolovsky9dde6062016-05-22 02:22:14 +0300863 mp_uint_t width = mp_obj_get_int(width_in);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300864 if (str_len >= width) {
865 return str_in;
866 }
867
868 vstr_t vstr;
869 vstr_init_len(&vstr, width);
870 memset(vstr.buf, ' ', width);
871 int left = (width - str_len) / 2;
872 memcpy(vstr.buf + left, str, str_len);
873 return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
874}
Damien George65417c52017-07-02 23:35:42 +1000875MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300876#endif
877
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700878// Takes an int arg, but only parses unsigned numbers, and only changes
879// *num if at least one digit was parsed.
Damien George87e07ea2016-02-02 15:51:57 +0000880STATIC const char *str_to_int(const char *str, const char *top, int *num) {
881 if (str < top && '0' <= *str && *str <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700882 *num = 0;
883 do {
Damien George87e07ea2016-02-02 15:51:57 +0000884 *num = *num * 10 + (*str - '0');
885 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700886 }
Damien George87e07ea2016-02-02 15:51:57 +0000887 while (str < top && '0' <= *str && *str <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700888 }
Damien George87e07ea2016-02-02 15:51:57 +0000889 return str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700890}
891
Damien George2801e6f2015-04-04 15:53:11 +0100892STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700893 return ch && strchr("<>=^", ch) != NULL;
894}
895
Damien George2801e6f2015-04-04 15:53:11 +0100896STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700897 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
898}
899
Damien George2801e6f2015-04-04 15:53:11 +0100900STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700901 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
902}
903
Damien George2801e6f2015-04-04 15:53:11 +0100904STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100906#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100907 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700908#endif
909 ;
910}
911
Damien George2801e6f2015-04-04 15:53:11 +0100912STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100913#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100914 if (mp_obj_is_float(arg)) {
915 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700916 }
917#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700918 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700919}
920
Damien George897129a2016-09-27 15:45:42 +1000921#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
Damien George1e9a92f2014-11-06 17:36:16 +0000922STATIC NORETURN void terse_str_format_value_error(void) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300923 mp_raise_ValueError("bad format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000924}
Damien George897129a2016-09-27 15:45:42 +1000925#else
926// define to nothing to improve coverage
927#define terse_str_format_value_error()
928#endif
Damien George1e9a92f2014-11-06 17:36:16 +0000929
Damien George90ab1912017-02-03 13:04:56 +1100930STATIC 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 +0000931 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100932 mp_print_t print;
933 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700934
pohmeliee3a29de2016-01-29 12:09:10 +0300935 for (; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700936 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000937 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700938 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100939 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700940 continue;
941 }
Damien George1e9a92f2014-11-06 17:36:16 +0000942 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
943 terse_str_format_value_error();
944 } else {
Damien George21967992016-08-14 16:51:54 +1000945 mp_raise_ValueError("single '}' encountered in format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000946 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700947 }
948 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100949 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700950 continue;
951 }
952
953 str++;
954 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100955 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700956 continue;
957 }
958
959 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
960
Damien George87e07ea2016-02-02 15:51:57 +0000961 const char *field_name = NULL;
962 const char *field_name_top = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700963 char conversion = '\0';
pohmeliee3a29de2016-01-29 12:09:10 +0300964 const char *format_spec = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700965
966 if (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000967 field_name = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700968 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000969 ++str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700970 }
Damien George87e07ea2016-02-02 15:51:57 +0000971 field_name_top = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700972 }
973
974 // conversion ::= "r" | "s"
975
976 if (str < top && *str == '!') {
977 str++;
978 if (str < top && (*str == 'r' || *str == 's')) {
979 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200980 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000981 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
982 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100983 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300984 mp_raise_ValueError("bad conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100985 } else {
986 if (str >= top) {
Damien George21967992016-08-14 16:51:54 +1000987 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300988 "end of format while looking for conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100989 } else {
990 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
991 "unknown conversion specifier %c", *str));
992 }
Damien George1e9a92f2014-11-06 17:36:16 +0000993 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700994 }
995 }
996
997 if (str < top && *str == ':') {
998 str++;
999 // {:} is the same as {}, which is the same as {!s}
1000 // This makes a difference when passing in a True or False
1001 // '{}'.format(True) returns 'True'
1002 // '{:d}'.format(True) returns '1'
1003 // So we treat {:} as {} and this later gets treated to be {!s}
1004 if (*str != '}') {
pohmeliee3a29de2016-01-29 12:09:10 +03001005 format_spec = str;
1006 for (int nest = 1; str < top;) {
1007 if (*str == '{') {
1008 ++nest;
1009 } else if (*str == '}') {
1010 if (--nest == 0) {
1011 break;
1012 }
1013 }
1014 ++str;
Damiend99b0522013-12-21 18:17:45 +00001015 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001016 }
1017 }
1018 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001019 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1020 terse_str_format_value_error();
1021 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001022 mp_raise_ValueError("unmatched '{' in format");
Damien George1e9a92f2014-11-06 17:36:16 +00001023 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001024 }
1025 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +00001026 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1027 terse_str_format_value_error();
1028 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001029 mp_raise_ValueError("expected ':' after format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001030 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001031 }
1032
1033 mp_obj_t arg = mp_const_none;
1034
1035 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +01001036 int index = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001037 if (MP_LIKELY(unichar_isdigit(*field_name))) {
pohmeliee3a29de2016-01-29 12:09:10 +03001038 if (*arg_i > 0) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001039 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1040 terse_str_format_value_error();
1041 } else {
Damien George21967992016-08-14 16:51:54 +10001042 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001043 "can't switch from automatic field numbering to manual field specification");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001044 }
1045 }
Damien George87e07ea2016-02-02 15:51:57 +00001046 field_name = str_to_int(field_name, field_name_top, &index);
Damien George963a5a32015-01-16 17:47:07 +00001047 if ((uint)index >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001048 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001049 }
1050 arg = args[index + 1];
pohmeliee3a29de2016-01-29 12:09:10 +03001051 *arg_i = -1;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001052 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001053 const char *lookup;
1054 for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
Damien George46017592017-11-16 13:17:51 +11001055 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 +00001056 field_name = lookup;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001057 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
1058 if (key_elem == NULL) {
1059 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
1060 }
1061 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001062 }
Damien George87e07ea2016-02-02 15:51:57 +00001063 if (field_name < field_name_top) {
Javier Candeira35a1fea2017-08-09 14:40:45 +10001064 mp_raise_NotImplementedError("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001065 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001066 } else {
pohmeliee3a29de2016-01-29 12:09:10 +03001067 if (*arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +00001068 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1069 terse_str_format_value_error();
1070 } else {
Damien George21967992016-08-14 16:51:54 +10001071 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001072 "can't switch from manual field specification to automatic field numbering");
Damien George1e9a92f2014-11-06 17:36:16 +00001073 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001074 }
pohmeliee3a29de2016-01-29 12:09:10 +03001075 if ((uint)*arg_i >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001076 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001077 }
pohmeliee3a29de2016-01-29 12:09:10 +03001078 arg = args[(*arg_i) + 1];
1079 (*arg_i)++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001080 }
1081 if (!format_spec && !conversion) {
1082 conversion = 's';
1083 }
1084 if (conversion) {
1085 mp_print_kind_t print_kind;
1086 if (conversion == 's') {
1087 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001088 } else {
Damien George000730e2015-08-30 12:43:21 +01001089 assert(conversion == 'r');
1090 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 }
Damien George0b9ee862015-01-21 19:14:25 +00001092 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001093 mp_print_t arg_print;
1094 vstr_init_print(&arg_vstr, 16, &arg_print);
1095 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001096 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001097 }
1098
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001099 char fill = '\0';
1100 char align = '\0';
1101 int width = -1;
1102 int precision = -1;
1103 char type = '\0';
1104 int flags = 0;
1105
1106 if (format_spec) {
1107 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1108 //
1109 // [[fill]align][sign][#][0][width][,][.precision][type]
1110 // fill ::= <any character>
1111 // align ::= "<" | ">" | "=" | "^"
1112 // sign ::= "+" | "-" | " "
1113 // width ::= integer
1114 // precision ::= integer
1115 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1116
pohmeliee3a29de2016-01-29 12:09:10 +03001117 // recursively call the formatter to format any nested specifiers
1118 MP_STACK_CHECK();
1119 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 +03001120 const char *s = vstr_null_terminated_str(&format_spec_vstr);
Damien George87e07ea2016-02-02 15:51:57 +00001121 const char *stop = s + format_spec_vstr.len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001122 if (isalignment(*s)) {
1123 align = *s++;
1124 } else if (*s && isalignment(s[1])) {
1125 fill = *s++;
1126 align = *s++;
1127 }
1128 if (*s == '+' || *s == '-' || *s == ' ') {
1129 if (*s == '+') {
1130 flags |= PF_FLAG_SHOW_SIGN;
1131 } else if (*s == ' ') {
1132 flags |= PF_FLAG_SPACE_SIGN;
1133 }
Damien George9d2c72a2017-07-04 02:13:27 +10001134 s++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001135 }
1136 if (*s == '#') {
1137 flags |= PF_FLAG_SHOW_PREFIX;
1138 s++;
1139 }
1140 if (*s == '0') {
1141 if (!align) {
1142 align = '=';
1143 }
1144 if (!fill) {
1145 fill = '0';
1146 }
1147 }
Damien George87e07ea2016-02-02 15:51:57 +00001148 s = str_to_int(s, stop, &width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001149 if (*s == ',') {
1150 flags |= PF_FLAG_SHOW_COMMA;
1151 s++;
1152 }
1153 if (*s == '.') {
1154 s++;
Damien George87e07ea2016-02-02 15:51:57 +00001155 s = str_to_int(s, stop, &precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001156 }
1157 if (istype(*s)) {
1158 type = *s++;
1159 }
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001160 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001161 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1162 terse_str_format_value_error();
1163 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001164 mp_raise_ValueError("invalid format specifier");
Damien George7ef75f92015-08-26 15:42:25 +01001165 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001166 }
pohmeliee3a29de2016-01-29 12:09:10 +03001167 vstr_clear(&format_spec_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001168 }
1169 if (!align) {
1170 if (arg_looks_numeric(arg)) {
1171 align = '>';
1172 } else {
1173 align = '<';
1174 }
1175 }
1176 if (!fill) {
1177 fill = ' ';
1178 }
1179
Damien George9d2c72a2017-07-04 02:13:27 +10001180 if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001181 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001182 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1183 terse_str_format_value_error();
1184 } else {
Damien George21967992016-08-14 16:51:54 +10001185 mp_raise_ValueError("sign not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001186 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001187 }
1188 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001189 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1190 terse_str_format_value_error();
1191 } else {
Damien George21967992016-08-14 16:51:54 +10001192 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001193 "sign not allowed with integer format specifier 'c'");
Damien George1e9a92f2014-11-06 17:36:16 +00001194 }
Damiend99b0522013-12-21 18:17:45 +00001195 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001196 }
1197
1198 switch (align) {
1199 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1200 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1201 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1202 }
1203
1204 if (arg_looks_integer(arg)) {
1205 switch (type) {
1206 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001207 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001208 continue;
1209
1210 case 'c':
1211 {
1212 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001213 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001214 continue;
1215 }
1216
1217 case '\0': // No explicit format type implies 'd'
1218 case 'n': // I don't think we support locales in uPy so use 'd'
1219 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001220 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001221 continue;
1222
1223 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001224 if (flags & PF_FLAG_SHOW_PREFIX) {
1225 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1226 }
1227
Damien George7f9d1d62015-04-09 23:56:15 +01001228 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001229 continue;
1230
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001231 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001232 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001233 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001234 continue;
1235
1236 case 'e':
1237 case 'E':
1238 case 'f':
1239 case 'F':
1240 case 'g':
1241 case 'G':
1242 case '%':
1243 // The floating point formatters all work with anything that
1244 // looks like an integer
1245 break;
1246
1247 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001248 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1249 terse_str_format_value_error();
1250 } else {
1251 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1252 "unknown format code '%c' for object of type '%s'",
1253 type, mp_obj_get_type_str(arg)));
1254 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001255 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001256 }
Damien George70f33cd2014-04-02 17:06:05 +01001257
Dave Hylands22fe4d72014-04-02 12:07:31 -07001258 // NOTE: no else here. We need the e, f, g etc formats for integer
1259 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001260 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001261 if (!type) {
1262
1263 // Even though the docs say that an unspecified type is the same
1264 // as 'g', there is one subtle difference, when the exponent
1265 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001266 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001267 // '{:10.1}'.format(0.0) ==> '0e+00'
1268 // '{:10.1g}'.format(0.0) ==> '0'
1269 //
1270 // TODO: Figure out how to deal with this.
1271 //
1272 // A proper solution would involve adding a special flag
1273 // or something to format_float, and create a format_double
1274 // to deal with doubles. In order to fix this when using
1275 // sprintf, we'd need to use the e format and tweak the
1276 // returned result to strip trailing zeros like the g format
1277 // does.
1278 //
1279 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1280 // but with 1.e2 you get 1e+02 and 1.00e+02
1281 //
1282 // Stripping the trailing 0's (like g) does would make the
1283 // e format give us the right format.
1284 //
1285 // CPython sources say:
1286 // Omitted type specifier. Behaves in the same way as repr(x)
1287 // and str(x) if no precision is given, else like 'g', but with
1288 // at least one digit after the decimal point. */
1289
1290 type = 'g';
1291 }
1292 if (type == 'n') {
1293 type = 'g';
1294 }
1295
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001296 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001297#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001298 case 'e':
1299 case 'E':
1300 case 'f':
1301 case 'F':
1302 case 'g':
1303 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001304 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001305 break;
1306
1307 case '%':
1308 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001309 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1310 #define F100 100.0F
1311 #else
1312 #define F100 100.0
1313 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001314 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001315 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001316 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001317#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001318
1319 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001320 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1321 terse_str_format_value_error();
1322 } else {
1323 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1324 "unknown format code '%c' for object of type 'float'",
1325 type, mp_obj_get_type_str(arg)));
1326 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001327 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001328 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001329 // arg doesn't look like a number
1330
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001331 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001332 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1333 terse_str_format_value_error();
1334 } else {
Damien George21967992016-08-14 16:51:54 +10001335 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001336 "'=' alignment not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001337 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001338 }
Damien George70f33cd2014-04-02 17:06:05 +01001339
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001340 switch (type) {
Damien Georged4df8f42016-01-04 13:13:39 +00001341 case '\0': // no explicit format type implies 's'
Damien Georged182b982014-08-30 14:19:41 +01001342 case 's': {
Damien George6b341072017-03-25 19:48:18 +11001343 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001344 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001345 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001346 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001347 }
Damien George6b341072017-03-25 19:48:18 +11001348 if (slen > (size_t)precision) {
Damien George50912e72015-01-20 11:55:10 +00001349 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001350 }
Damien George7f9d1d62015-04-09 23:56:15 +01001351 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001352 break;
1353 }
1354
1355 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001356 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1357 terse_str_format_value_error();
1358 } else {
1359 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1360 "unknown format code '%c' for object of type 'str'",
1361 type, mp_obj_get_type_str(arg)));
1362 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001363 }
Damiend99b0522013-12-21 18:17:45 +00001364 }
1365 }
1366
pohmeliee3a29de2016-01-29 12:09:10 +03001367 return vstr;
1368}
1369
1370mp_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 +03001371 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
pohmeliee3a29de2016-01-29 12:09:10 +03001372
1373 GET_STR_DATA_LEN(args[0], str, len);
1374 int arg_i = 0;
1375 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 +00001376 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001377}
Damien George65417c52017-07-02 23:35:42 +10001378MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Damiend99b0522013-12-21 18:17:45 +00001379
Damien George90ab1912017-02-03 13:04:56 +11001380STATIC 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 +03001381 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001382
1383 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001384 const byte *start_str = str;
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001385 bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
Damien George90ab1912017-02-03 13:04:56 +11001386 size_t arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001387 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001388 mp_print_t print;
1389 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001390
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001391 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001392 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001393 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001394 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001395 continue;
1396 }
1397 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001398 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001399 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001400 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001401 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001402 continue;
1403 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001404
1405 // Dictionary value lookup
1406 if (*str == '(') {
Damien George7317e342017-02-03 12:13:44 +11001407 if (dict == MP_OBJ_NULL) {
1408 mp_raise_TypeError("format requires a dict");
1409 }
1410 arg_i = 1; // we used up the single dict argument
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001411 const byte *key = ++str;
1412 while (*str != ')') {
1413 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001414 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1415 terse_str_format_value_error();
1416 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001417 mp_raise_ValueError("incomplete format key");
Damien George1e9a92f2014-11-06 17:36:16 +00001418 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001419 }
1420 ++str;
1421 }
Damien George46017592017-11-16 13:17:51 +11001422 mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001423 arg = mp_obj_dict_get(dict, k_obj);
1424 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001425 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001426
Dave Hylands6756a372014-04-02 11:42:39 -07001427 int flags = 0;
1428 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001429 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001430 while (str < top) {
1431 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1432 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1433 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001434 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001435 else if (*str == '0') {
1436 flags |= PF_FLAG_PAD_AFTER_SIGN;
1437 fill = '0';
1438 } else break;
1439 str++;
1440 }
1441 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001442 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001443 if (str < top) {
1444 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001445 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001446 goto not_enough_args;
1447 }
Dave Hylands6756a372014-04-02 11:42:39 -07001448 width = mp_obj_get_int(args[arg_i++]);
1449 str++;
1450 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001451 str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001452 }
1453 }
1454 int prec = -1;
1455 if (str < top && *str == '.') {
1456 if (++str < top) {
1457 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001458 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001459 goto not_enough_args;
1460 }
Dave Hylands6756a372014-04-02 11:42:39 -07001461 prec = mp_obj_get_int(args[arg_i++]);
1462 str++;
1463 } else {
1464 prec = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001465 str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001466 }
1467 }
1468 }
1469
1470 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001471incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001472 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1473 terse_str_format_value_error();
1474 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001475 mp_raise_ValueError("incomplete format");
Damien George1e9a92f2014-11-06 17:36:16 +00001476 }
Dave Hylands6756a372014-04-02 11:42:39 -07001477 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001478
1479 // Tuple value lookup
1480 if (arg == MP_OBJ_NULL) {
Damien George90ab1912017-02-03 13:04:56 +11001481 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001482not_enough_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001483 mp_raise_TypeError("not enough arguments for format string");
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001484 }
1485 arg = args[arg_i++];
1486 }
Dave Hylands6756a372014-04-02 11:42:39 -07001487 switch (*str) {
1488 case 'c':
1489 if (MP_OBJ_IS_STR(arg)) {
Damien George6b341072017-03-25 19:48:18 +11001490 size_t slen;
Damien George50912e72015-01-20 11:55:10 +00001491 const char *s = mp_obj_str_get_data(arg, &slen);
1492 if (slen != 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001493 mp_raise_TypeError("%%c requires int or char");
Dave Hylands6756a372014-04-02 11:42:39 -07001494 }
Damien George7f9d1d62015-04-09 23:56:15 +01001495 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001496 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001497 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001498 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001499 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001500 mp_raise_TypeError("integer required");
Dave Hylands6756a372014-04-02 11:42:39 -07001501 }
Damien George11de8392014-06-05 18:57:38 +01001502 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001503
1504 case 'd':
1505 case 'i':
1506 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001507 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001508 break;
1509
Damien Georgefb510b32014-06-01 13:32:54 +01001510#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001511 case 'e':
1512 case 'E':
1513 case 'f':
1514 case 'F':
1515 case 'g':
1516 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001517 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001518 break;
1519#endif
1520
1521 case 'o':
1522 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001523 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001524 }
Damien George7f9d1d62015-04-09 23:56:15 +01001525 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001526 break;
1527
1528 case 'r':
1529 case 's':
1530 {
Damien George0b9ee862015-01-21 19:14:25 +00001531 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001532 mp_print_t arg_print;
1533 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001534 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1535 if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1536 // If we have something like b"%s" % b"1", bytes arg should be
1537 // printed undecorated.
1538 print_kind = PRINT_RAW;
1539 }
1540 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001541 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001542 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001543 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001544 }
Damien George50912e72015-01-20 11:55:10 +00001545 if (vlen > (uint)prec) {
1546 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001547 }
Damien George7f9d1d62015-04-09 23:56:15 +01001548 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001549 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001550 break;
1551 }
Dave Hylands6756a372014-04-02 11:42:39 -07001552
Dave Hylands6756a372014-04-02 11:42:39 -07001553 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001554 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001555 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001556 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001557
Dave Hylands6756a372014-04-02 11:42:39 -07001558 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001559 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1560 terse_str_format_value_error();
1561 } else {
1562 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1563 "unsupported format character '%c' (0x%x) at index %d",
1564 *str, *str, str - start_str));
1565 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001566 }
1567 }
1568
Damien George90ab1912017-02-03 13:04:56 +11001569 if (arg_i != n_args) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001570 mp_raise_TypeError("not all arguments converted during string formatting");
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001571 }
1572
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001573 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001574}
1575
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001576// The implementation is optimized, returning the original string if there's
1577// nothing to replace.
Damien George4b72b3a2016-01-03 14:21:40 +00001578STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001579 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001580
Damien George40f3c022014-07-03 13:25:24 +01001581 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001582 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001583 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001584 if (max_rep == 0) {
1585 return args[0];
1586 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001587 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001588 }
xbe480c15a2014-01-30 22:17:30 -08001589 }
Damien George94f68302014-01-31 23:45:12 +00001590
xbe729be9b2014-04-07 14:46:39 -07001591 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001592
Damien Georgeff715422014-04-07 00:39:13 +01001593 // check argument types
1594
Damien Georgec55a4d82014-12-24 20:28:30 +00001595 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1596
1597 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001598 bad_implicit_conversion(args[1]);
1599 }
1600
Damien Georgec55a4d82014-12-24 20:28:30 +00001601 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001602 bad_implicit_conversion(args[2]);
1603 }
1604
1605 // extract string data
1606
xbe480c15a2014-01-30 22:17:30 -08001607 GET_STR_DATA_LEN(args[0], str, str_len);
1608 GET_STR_DATA_LEN(args[1], old, old_len);
1609 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001610
1611 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001612 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001613 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001614 }
1615
Damien George94f68302014-01-31 23:45:12 +00001616 // data for the replaced string
1617 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001618 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001619
Damien George94f68302014-01-31 23:45:12 +00001620 // do 2 passes over the string:
1621 // first pass computes the required length of the replaced string
1622 // second pass does the replacements
1623 for (;;) {
Damien Georgec0d95002017-02-16 16:26:48 +11001624 size_t replaced_str_index = 0;
1625 size_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001626 const byte *old_occurrence;
1627 const byte *offset_ptr = str;
Damien Georgec0d95002017-02-16 16:26:48 +11001628 size_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001629 if (old_len == 0) {
1630 // if old_str is empty, copy new_str to start of replaced string
1631 // copy the replacement string
1632 if (data != NULL) {
1633 memcpy(data, new, new_len);
1634 }
1635 replaced_str_index += new_len;
1636 num_replacements_done++;
1637 }
Damien Georgec0d95002017-02-16 16:26:48 +11001638 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 +01001639 if (old_len == 0) {
1640 old_occurrence += 1;
1641 }
Damien George94f68302014-01-31 23:45:12 +00001642 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1643 if (data != NULL) {
1644 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1645 }
1646 replaced_str_index += old_occurrence - offset_ptr;
1647 // copy the replacement string
1648 if (data != NULL) {
1649 memcpy(data + replaced_str_index, new, new_len);
1650 }
1651 replaced_str_index += new_len;
1652 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001653 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001654 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001655 }
1656
1657 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1658 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001659 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001660 }
Damien Georgeff715422014-04-07 00:39:13 +01001661 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001662
1663 if (data == NULL) {
1664 // first pass
1665 if (num_replacements_done == 0) {
1666 // no substr found, return original string
1667 return args[0];
1668 } else {
1669 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001670 vstr_init_len(&vstr, replaced_str_index);
1671 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001672 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001673 }
1674 } else {
1675 // second pass, we are done
1676 break;
1677 }
xbe480c15a2014-01-30 22:17:30 -08001678 }
Damien George94f68302014-01-31 23:45:12 +00001679
Damien George05005f62015-01-21 22:48:37 +00001680 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001681}
Damien George65417c52017-07-02 23:35:42 +10001682MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe480c15a2014-01-30 22:17:30 -08001683
Damien George4b72b3a2016-01-03 14:21:40 +00001684STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001685 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001686 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +00001687
1688 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001689 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001690 bad_implicit_conversion(args[1]);
1691 }
xbe9e1e8cd2014-03-12 22:57:16 -07001692
1693 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1694 GET_STR_DATA_LEN(args[1], needle, needle_len);
1695
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001696 const byte *start = haystack;
1697 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001698 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001699 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001700 }
1701 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001702 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001703 }
1704
Damien George536dde22014-03-13 22:07:55 +00001705 // if needle_len is zero then we count each gap between characters as an occurrence
1706 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001707 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001708 }
1709
Damien George536dde22014-03-13 22:07:55 +00001710 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001711 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001712 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1713 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001714 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001715 haystack_ptr += needle_len;
1716 } else {
1717 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001718 }
xbe9e1e8cd2014-03-12 22:57:16 -07001719 }
1720
1721 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1722}
Damien George65417c52017-07-02 23:35:42 +10001723MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe9e1e8cd2014-03-12 22:57:16 -07001724
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001725#if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgec0d95002017-02-16 16:26:48 +11001726STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001727 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001728 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1729 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001730 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001731 }
Damien Georgeb035db32014-03-21 20:39:40 +00001732
xbe613a8e32014-03-18 00:06:29 -07001733 GET_STR_DATA_LEN(self_in, str, str_len);
1734 GET_STR_DATA_LEN(arg, sep, sep_len);
1735
1736 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001737 mp_raise_ValueError("empty separator");
xbe613a8e32014-03-18 00:06:29 -07001738 }
Damien Georgeb035db32014-03-21 20:39:40 +00001739
Damien Georgec55a4d82014-12-24 20:28:30 +00001740 mp_obj_t result[3];
1741 if (self_type == &mp_type_str) {
1742 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1743 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1744 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1745 } else {
1746 result[0] = mp_const_empty_bytes;
1747 result[1] = mp_const_empty_bytes;
1748 result[2] = mp_const_empty_bytes;
1749 }
Damien Georgeb035db32014-03-21 20:39:40 +00001750
1751 if (direction > 0) {
1752 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001753 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001754 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001755 }
xbe613a8e32014-03-18 00:06:29 -07001756
xbe17a5a832014-03-23 23:31:58 -07001757 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1758 if (position_ptr != NULL) {
Damien Georgec0d95002017-02-16 16:26:48 +11001759 size_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001760 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001761 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001762 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 -07001763 }
Damien Georgeb035db32014-03-21 20:39:40 +00001764
xbe0a6894c2014-03-21 01:12:26 -07001765 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001766}
1767
Damien Georgeb035db32014-03-21 20:39:40 +00001768STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1769 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001770}
Damien George65417c52017-07-02 23:35:42 +10001771MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001772
Damien Georgeb035db32014-03-21 20:39:40 +00001773STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1774 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001775}
Damien George65417c52017-07-02 23:35:42 +10001776MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001777#endif
xbe4504ea82014-03-19 00:46:14 -07001778
Paul Sokolovsky69135212014-05-10 19:47:41 +03001779// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001780STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001781 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001782 vstr_t vstr;
1783 vstr_init_len(&vstr, self_len);
1784 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +11001785 for (size_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001786 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001787 }
Damien George05005f62015-01-21 22:48:37 +00001788 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001789}
1790
1791STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001792 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001793}
Damien George65417c52017-07-02 23:35:42 +10001794MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001795
1796STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001797 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001798}
Damien George65417c52017-07-02 23:35:42 +10001799MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001800
Damien Georgefcc9cf62014-06-01 18:22:09 +01001801STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001802 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001803
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001804 if (self_len == 0) {
1805 return mp_const_false; // default to False for empty str
1806 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001807
Damien Georgefcc9cf62014-06-01 18:22:09 +01001808 if (f != unichar_isupper && f != unichar_islower) {
Damien Georgec0d95002017-02-16 16:26:48 +11001809 for (size_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001810 if (!f(*self_data++)) {
1811 return mp_const_false;
1812 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001813 }
1814 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001815 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001816
Damien Georgec0d95002017-02-16 16:26:48 +11001817 for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001818 if (unichar_isalpha(*self_data++)) {
1819 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001820 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1821 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001822 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001823 }
1824 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001825
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001826 if (!contains_alpha) {
1827 return mp_const_false;
1828 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001829 }
1830
1831 return mp_const_true;
1832}
1833
1834STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001835 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001836}
Damien George65417c52017-07-02 23:35:42 +10001837MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001838
1839STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001840 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001841}
Damien George65417c52017-07-02 23:35:42 +10001842MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001843
1844STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001845 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001846}
Damien George65417c52017-07-02 23:35:42 +10001847MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001848
1849STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001850 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001851}
Damien George65417c52017-07-02 23:35:42 +10001852MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001853
1854STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001855 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001856}
Damien George65417c52017-07-02 23:35:42 +10001857MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001858
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001859#if MICROPY_CPYTHON_COMPAT
Ville Skyttäca16c382017-05-29 10:08:14 +03001860// These methods are superfluous in the presence of str() and bytes()
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001861// constructors.
1862// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001863STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001864 mp_obj_t new_args[2];
1865 if (n_args == 1) {
1866 new_args[0] = args[0];
1867 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1868 args = new_args;
1869 n_args++;
1870 }
Damien George5b3f0b72016-01-03 15:55:55 +00001871 return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001872}
Damien George65417c52017-07-02 23:35:42 +10001873MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001874
1875// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001876STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001877 mp_obj_t new_args[2];
1878 if (n_args == 1) {
1879 new_args[0] = args[0];
1880 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1881 args = new_args;
1882 n_args++;
1883 }
Damien George5b3f0b72016-01-03 15:55:55 +00001884 return bytes_make_new(NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001885}
Damien George65417c52017-07-02 23:35:42 +10001886MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001887#endif
1888
Damien George4d917232014-08-30 14:28:06 +01001889mp_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 +01001890 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001891 GET_STR_DATA_LEN(self_in, str_data, str_len);
1892 bufinfo->buf = (void*)str_data;
1893 bufinfo->len = str_len;
Damien George12dd8df2016-05-07 21:18:17 +01001894 bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
Damien George2da98302014-03-09 19:58:18 +00001895 return 0;
1896 } else {
1897 // can't write to a string
1898 bufinfo->buf = NULL;
1899 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001900 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001901 return 1;
1902 }
1903}
1904
Damien Georgecbf76742015-11-27 13:38:15 +00001905STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001906#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001907 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001908 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1909 // If we have separate unicode type, then here we have methods only
1910 // for bytes type, and it should not have encode() methods. Otherwise,
1911 // we have non-compliant-but-practical bytestring type, which shares
1912 // method table with bytes, so they both have encode() and decode()
1913 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001914 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001915 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001916#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001917 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1918 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1919 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1920 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1921 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1922 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001923 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001924 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001925 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001926 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1927 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1928 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1929 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1930 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1931 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1932 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1933 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1934 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001935 #if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgecbf76742015-11-27 13:38:15 +00001936 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1937 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001938 #endif
Paul Sokolovsky15633882016-08-07 15:24:57 +03001939 #if MICROPY_PY_BUILTINS_STR_CENTER
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +03001940 { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
Paul Sokolovsky15633882016-08-07 15:24:57 +03001941 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001942 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1943 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1944 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1945 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1946 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1947 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1948 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001949};
Damien George97209d32014-01-07 15:58:30 +00001950
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001951STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001952
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001953#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgeae8d8672016-01-09 23:14:54 +00001954STATIC 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 +01001955
Damien George3e1a5c12014-03-29 13:43:38 +00001956const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001957 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001958 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001959 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001960 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001961 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001962 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001963 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001964 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001965 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001966};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001967#endif
Damiend99b0522013-12-21 18:17:45 +00001968
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001969// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001970const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001971 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001972 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001973 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001974 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001975 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001976 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001977 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001978 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001979 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001980};
1981
Damien Georgedfa563c2017-10-04 17:59:22 +11001982// The zero-length bytes object, with data that includes a null-terminating byte
1983const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte*)""};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001984
Damien George77089be2015-01-21 23:08:36 +00001985// Create a str/bytes object using the given data. New memory is allocated and
Damien George1f1d5192017-11-16 13:53:04 +11001986// the data is copied across. This function should only be used if the type is bytes,
1987// or if the type is str and the string data is known to be not interned.
1988mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001989 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001990 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001991 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001992 if (data) {
1993 o->hash = qstr_compute_hash(data, len);
1994 byte *p = m_new(byte, len + 1);
1995 o->data = p;
1996 memcpy(p, data, len * sizeof(byte));
1997 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1998 }
Damien George999cedb2015-11-27 17:01:44 +00001999 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002000}
2001
Damien George1f1d5192017-11-16 13:53:04 +11002002// Create a str/bytes object using the given data. If the type is str and the string
2003// data is already interned, then a qstr object is returned. Otherwise new memory is
2004// allocated for the object and the data is copied across.
2005mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
2006 if (type == &mp_type_str) {
2007 return mp_obj_new_str((const char*)data, len);
2008 } else {
2009 return mp_obj_new_bytes(data, len);
2010 }
2011}
2012
Damien George46017592017-11-16 13:17:51 +11002013// Create a str using a qstr to store the data; may use existing or new qstr.
2014mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len) {
2015 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
2016}
2017
Damien George77089be2015-01-21 23:08:36 +00002018// Create a str/bytes object from the given vstr. The vstr buffer is resized to
2019// the exact length required and then reused for the str/bytes object. The vstr
2020// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00002021mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
2022 // if not a bytes object, look if a qstr with this data already exists
2023 if (type == &mp_type_str) {
2024 qstr q = qstr_find_strn(vstr->buf, vstr->len);
2025 if (q != MP_QSTR_NULL) {
2026 vstr_clear(vstr);
2027 vstr->alloc = 0;
2028 return MP_OBJ_NEW_QSTR(q);
2029 }
2030 }
2031
2032 // make a new str/bytes object
2033 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
2034 o->base.type = type;
2035 o->len = vstr->len;
2036 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07002037 if (vstr->len + 1 == vstr->alloc) {
2038 o->data = (byte*)vstr->buf;
2039 } else {
2040 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
2041 }
Damien George0d3cb672015-01-28 23:43:01 +00002042 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00002043 vstr->buf = NULL;
2044 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00002045 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00002046}
2047
Damien George46017592017-11-16 13:17:51 +11002048mp_obj_t mp_obj_new_str(const char* data, size_t len) {
2049 qstr q = qstr_find_strn(data, len);
2050 if (q != MP_QSTR_NULL) {
2051 // qstr with this data already exists
2052 return MP_OBJ_NEW_QSTR(q);
Damien George5fa93b62014-01-22 14:35:10 +00002053 } else {
Damien George46017592017-11-16 13:17:51 +11002054 // no existing qstr, don't make one
Damien George1f1d5192017-11-16 13:53:04 +11002055 return mp_obj_new_str_copy(&mp_type_str, (const byte*)data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002056 }
Damien George5fa93b62014-01-22 14:35:10 +00002057}
2058
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002059mp_obj_t mp_obj_str_intern(mp_obj_t str) {
2060 GET_STR_DATA_LEN(str, data, len);
Damien George46017592017-11-16 13:17:51 +11002061 return mp_obj_new_str_via_qstr((const char*)data, len);
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002062}
2063
Damien Georgec0d95002017-02-16 16:26:48 +11002064mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
Damien George1f1d5192017-11-16 13:53:04 +11002065 return mp_obj_new_str_copy(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002066}
2067
Damien George5fa93b62014-01-22 14:35:10 +00002068bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
2069 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
2070 return s1 == s2;
2071 } else {
2072 GET_STR_HASH(s1, h1);
2073 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03002074 // If any of hashes is 0, it means it's not valid
2075 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00002076 return false;
2077 }
2078 GET_STR_DATA_LEN(s1, d1, l1);
2079 GET_STR_DATA_LEN(s2, d2, l2);
2080 if (l1 != l2) {
2081 return false;
2082 }
Damien George1e708fe2014-01-23 18:27:51 +00002083 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002084 }
Damien George5fa93b62014-01-22 14:35:10 +00002085}
2086
Damien George3990a522017-11-29 15:43:40 +11002087STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002088 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03002089 mp_raise_TypeError("can't convert to str implicitly");
Damien George1e9a92f2014-11-06 17:36:16 +00002090 } else {
stijnbf29fe22017-03-15 12:17:38 +01002091 const qstr src_name = mp_obj_get_type(self_in)->name;
Damien George1e9a92f2014-11-06 17:36:16 +00002092 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
stijnbf29fe22017-03-15 12:17:38 +01002093 "can't convert '%q' object to %q implicitly",
2094 src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str));
Damien George1e9a92f2014-11-06 17:36:16 +00002095 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002096}
2097
Damien Georgeb829b5c2014-01-25 13:51:19 +00002098// use this if you will anyway convert the string to a qstr
2099// will be more efficient for the case where it's already a qstr
2100qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2101 if (MP_OBJ_IS_QSTR(self_in)) {
2102 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002103 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002104 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002105 return qstr_from_strn((char*)self->data, self->len);
2106 } else {
2107 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002108 }
2109}
2110
2111// only use this function if you need the str data to be zero terminated
2112// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2113const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002114 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002115 GET_STR_DATA_LEN(self_in, s, l);
2116 (void)l; // len unused
2117 return (const char*)s;
2118 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002119 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002120 }
2121}
2122
Damien George6b341072017-03-25 19:48:18 +11002123const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002124 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002125 GET_STR_DATA_LEN(self_in, s, l);
2126 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002127 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002128 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002129 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002130 }
Damiend99b0522013-12-21 18:17:45 +00002131}
xyb8cfc9f02014-01-05 18:47:51 +08002132
Damien George04353cc2015-10-18 23:09:04 +01002133#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
Damien Georgec3f64d92015-11-27 12:23:18 +00002134const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien George04353cc2015-10-18 23:09:04 +01002135 if (MP_OBJ_IS_QSTR(self_in)) {
2136 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2137 } else {
2138 *len = ((mp_obj_str_t*)self_in)->len;
2139 return ((mp_obj_str_t*)self_in)->data;
2140 }
2141}
2142#endif
2143
xyb8cfc9f02014-01-05 18:47:51 +08002144/******************************************************************************/
2145/* str iterator */
2146
Damien George44e7cbf2015-05-17 16:44:24 +01002147typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002148 mp_obj_base_t base;
Damien George8212d972016-01-03 16:27:55 +00002149 mp_fun_1_t iternext;
Damien George5fa93b62014-01-22 14:35:10 +00002150 mp_obj_t str;
Damien Georgec0d95002017-02-16 16:26:48 +11002151 size_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002152} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002153
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002154#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002155STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George326e8862017-06-08 00:40:38 +10002156 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002157 GET_STR_DATA_LEN(self->str, str, len);
2158 if (self->cur < len) {
Damien George46017592017-11-16 13:17:51 +11002159 mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)str + self->cur, 1);
xyb8cfc9f02014-01-05 18:47:51 +08002160 self->cur += 1;
2161 return o_out;
2162 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002163 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002164 }
2165}
2166
Damien Georgeae8d8672016-01-09 23:14:54 +00002167STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2168 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2169 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002170 o->base.type = &mp_type_polymorph_iter;
2171 o->iternext = str_it_iternext;
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002172 o->str = str;
2173 o->cur = 0;
Damien George326e8862017-06-08 00:40:38 +10002174 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002175}
2176#endif
2177
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002178STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002179 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002180 GET_STR_DATA_LEN(self->str, str, len);
2181 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002182 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002183 self->cur += 1;
2184 return o_out;
2185 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002186 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002187 }
2188}
2189
Damien Georgeae8d8672016-01-09 23:14:54 +00002190mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) {
2191 assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t));
2192 mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf;
Damien George8212d972016-01-03 16:27:55 +00002193 o->base.type = &mp_type_polymorph_iter;
2194 o->iternext = bytes_it_iternext;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002195 o->str = str;
2196 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002197 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002198}