blob: 262b89ddd8eddb8acedeb94d78b24813a04e977e [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
Damiend99b0522013-12-21 18:17:45 +000028#include <string.h>
29#include <assert.h>
30
Damien George51dfcb42015-01-01 20:27:54 +000031#include "py/nlr.h"
32#include "py/unicode.h"
33#include "py/objstr.h"
34#include "py/objlist.h"
35#include "py/runtime0.h"
36#include "py/runtime.h"
pohmeliee3a29de2016-01-29 12:09:10 +030037#include "py/stackctrl.h"
Damiend99b0522013-12-21 18:17:45 +000038
Damien George90ab1912017-02-03 13:04:56 +110039STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020040
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020041STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030042STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030043
xyb8cfc9f02014-01-05 18:47:51 +080044/******************************************************************************/
45/* str */
46
Damien Georgec0d95002017-02-16 16:26:48 +110047void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020048 // this escapes characters, but it will be very slow to print (calling print many times)
49 bool has_single_quote = false;
50 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100051 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020052 if (*s == '\'') {
53 has_single_quote = true;
54 } else if (*s == '"') {
55 has_double_quote = true;
56 }
57 }
58 int quote_char = '\'';
59 if (has_single_quote && !has_double_quote) {
60 quote_char = '"';
61 }
Damien George7f9d1d62015-04-09 23:56:15 +010062 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020063 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
64 if (*s == quote_char) {
Damien George7f9d1d62015-04-09 23:56:15 +010065 mp_printf(print, "\\%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020066 } else if (*s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010067 mp_print_str(print, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030068 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
69 // In strings, anything which is not ascii control character
70 // is printed as is, this includes characters in range 0x80-0xff
71 // (which can be non-Latin letters, etc.)
Damien George7f9d1d62015-04-09 23:56:15 +010072 mp_printf(print, "%c", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020073 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010074 mp_print_str(print, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010075 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010076 mp_print_str(print, "\\r");
Andrew Scheller12968fb2014-04-08 02:42:50 +010077 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +010078 mp_print_str(print, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020079 } else {
Damien George7f9d1d62015-04-09 23:56:15 +010080 mp_printf(print, "\\x%02x", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020081 }
82 }
Damien George7f9d1d62015-04-09 23:56:15 +010083 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020084}
85
Damien George612045f2014-09-17 22:56:34 +010086#if MICROPY_PY_UJSON
Damien George999cedb2015-11-27 17:01:44 +000087void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
Damien Georgecde0ca22014-09-25 17:35:56 +010088 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
89 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George7f9d1d62015-04-09 23:56:15 +010090 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +010091 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010092 if (*s == '"' || *s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010093 mp_printf(print, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010094 } else if (*s >= 32) {
95 // this will handle normal and utf-8 encoded chars
Damien George7f9d1d62015-04-09 23:56:15 +010096 mp_printf(print, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010097 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010098 mp_print_str(print, "\\n");
Damien George612045f2014-09-17 22:56:34 +010099 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +0100100 mp_print_str(print, "\\r");
Damien George612045f2014-09-17 22:56:34 +0100101 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +0100102 mp_print_str(print, "\\t");
Damien George612045f2014-09-17 22:56:34 +0100103 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100104 // this will handle control chars
Damien George7f9d1d62015-04-09 23:56:15 +0100105 mp_printf(print, "\\u%04x", *s);
Damien George612045f2014-09-17 22:56:34 +0100106 }
107 }
Damien George7f9d1d62015-04-09 23:56:15 +0100108 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +0100109}
110#endif
111
Damien George7f9d1d62015-04-09 23:56:15 +0100112STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +0000113 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100114 #if MICROPY_PY_UJSON
115 if (kind == PRINT_JSON) {
Damien George7f9d1d62015-04-09 23:56:15 +0100116 mp_str_print_json(print, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100117 return;
118 }
119 #endif
Damien Georgee2aa1172015-09-03 23:03:57 +0100120 #if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgecde0ca22014-09-25 17:35:56 +0100121 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Damien Georgee2aa1172015-09-03 23:03:57 +0100122 #else
123 bool is_bytes = true;
124 #endif
Paul Sokolovskyef63ab52015-12-20 16:44:36 +0200125 if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
Damien George7f9d1d62015-04-09 23:56:15 +0100126 mp_printf(print, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200127 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200128 if (is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100129 mp_print_str(print, "b");
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200130 }
Damien George7f9d1d62015-04-09 23:56:15 +0100131 mp_str_print_quoted(print, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200132 }
Damiend99b0522013-12-21 18:17:45 +0000133}
134
Damien George5b3f0b72016-01-03 15:55:55 +0000135mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300136#if MICROPY_CPYTHON_COMPAT
137 if (n_kw != 0) {
138 mp_arg_error_unimpl_kw();
139 }
140#endif
141
Damien George1e9a92f2014-11-06 17:36:16 +0000142 mp_arg_check_num(n_args, n_kw, 0, 3, false);
143
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200144 switch (n_args) {
145 case 0:
146 return MP_OBJ_NEW_QSTR(MP_QSTR_);
147
Damien George1e9a92f2014-11-06 17:36:16 +0000148 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000149 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100150 mp_print_t print;
151 vstr_init_print(&vstr, 16, &print);
152 mp_obj_print_helper(&print, args[0], PRINT_STR);
Damien George5b3f0b72016-01-03 15:55:55 +0000153 return mp_obj_new_str_from_vstr(type, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200154 }
155
Damien George1e9a92f2014-11-06 17:36:16 +0000156 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200157 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200158 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
159 GET_STR_DATA_LEN(args[0], str_data, str_len);
160 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000161 if (str_hash == 0) {
162 str_hash = qstr_compute_hash(str_data, str_len);
163 }
Damien George5b3f0b72016-01-03 15:55:55 +0000164 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(type, NULL, str_len));
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200165 o->data = str_data;
166 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000167 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200168 } else {
169 mp_buffer_info_t bufinfo;
170 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
171 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200172 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200173 }
174}
175
Damien George5b3f0b72016-01-03 15:55:55 +0000176STATIC mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +0000177 (void)type_in;
178
Damien George3a2171e2015-09-04 16:53:46 +0100179 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300180 if (n_kw != 0) {
181 mp_arg_error_unimpl_kw();
182 }
Damien George3a2171e2015-09-04 16:53:46 +0100183 #else
184 (void)n_kw;
185 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300186
Damien George42cec5c2015-09-04 16:51:55 +0100187 if (n_args == 0) {
188 return mp_const_empty_bytes;
189 }
190
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200191 if (MP_OBJ_IS_STR(args[0])) {
192 if (n_args < 2 || n_args > 3) {
193 goto wrong_args;
194 }
195 GET_STR_DATA_LEN(args[0], str_data, str_len);
196 GET_STR_HASH(args[0], str_hash);
Damien George5f3bda42016-09-02 14:42:53 +1000197 if (str_hash == 0) {
198 str_hash = qstr_compute_hash(str_data, str_len);
199 }
Damien George999cedb2015-11-27 17:01:44 +0000200 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200201 o->data = str_data;
202 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000203 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200204 }
205
206 if (n_args > 1) {
207 goto wrong_args;
208 }
209
210 if (MP_OBJ_IS_SMALL_INT(args[0])) {
211 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000212 vstr_t vstr;
213 vstr_init_len(&vstr, len);
214 memset(vstr.buf, 0, len);
215 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 }
217
Damien George32ef3a32014-12-04 15:46:14 +0000218 // check if argument has the buffer protocol
219 mp_buffer_info_t bufinfo;
220 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
221 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
222 }
223
Damien George0b9ee862015-01-21 19:14:25 +0000224 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200225 // Try to create array of exact len if initializer len is known
226 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
227 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000228 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200229 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000230 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000231 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200232 }
233
Damien Georged17926d2014-03-30 13:35:08 +0100234 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200235 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100236 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100237 mp_int_t val = mp_obj_get_int(item);
238 #if MICROPY_CPYTHON_COMPAT
239 if (val < 0 || val > 255) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300240 mp_raise_ValueError("bytes value out of range");
Damien Georgeede0f3a2015-04-23 15:28:18 +0100241 }
242 #endif
243 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200244 }
245
Damien George0b9ee862015-01-21 19:14:25 +0000246 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200247
248wrong_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300249 mp_raise_TypeError("wrong number of arguments");
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200250}
251
Damien George55baff42014-01-21 21:40:13 +0000252// like strstr but with specified length and allows \0 bytes
253// TODO replace with something more efficient/standard
Damien Georgec0d95002017-02-16 16:26:48 +1100254const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction) {
Damien George55baff42014-01-21 21:40:13 +0000255 if (hlen >= nlen) {
Damien Georgec0d95002017-02-16 16:26:48 +1100256 size_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700257 if (direction > 0) {
258 str_index = 0;
259 str_index_end = hlen - nlen;
260 } else {
261 str_index = hlen - nlen;
262 str_index_end = 0;
263 }
264 for (;;) {
265 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
266 //found
267 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000268 }
xbe17a5a832014-03-23 23:31:58 -0700269 if (str_index == str_index_end) {
270 //not found
271 break;
Damien George55baff42014-01-21 21:40:13 +0000272 }
xbe17a5a832014-03-23 23:31:58 -0700273 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000274 }
275 }
276 return NULL;
277}
278
Damien Georgea75b02e2014-08-27 09:20:30 +0100279// Note: this function is used to check if an object is a str or bytes, which
280// works because both those types use it as their binary_op method. Revisit
281// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100282mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000283 // check for modulo
284 if (op == MP_BINARY_OP_MODULO) {
Damien George7317e342017-02-03 12:13:44 +1100285 mp_obj_t *args = &rhs_in;
286 mp_uint_t n_args = 1;
Damien Georgea65c03c2014-11-05 16:30:34 +0000287 mp_obj_t dict = MP_OBJ_NULL;
288 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
289 // TODO: Support tuple subclasses?
290 mp_obj_tuple_get(rhs_in, &n_args, &args);
291 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000292 dict = rhs_in;
Damien Georgea65c03c2014-11-05 16:30:34 +0000293 }
294 return str_modulo_format(lhs_in, n_args, args, dict);
295 }
296
297 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300298 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000299 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
300
301 // check for multiply
302 if (op == MP_BINARY_OP_MULTIPLY) {
303 mp_int_t n;
304 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
305 return MP_OBJ_NULL; // op not supported
306 }
307 if (n <= 0) {
308 if (lhs_type == &mp_type_str) {
309 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
310 } else {
311 return mp_const_empty_bytes;
312 }
313 }
Damien George05005f62015-01-21 22:48:37 +0000314 vstr_t vstr;
315 vstr_init_len(&vstr, lhs_len * n);
316 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
317 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000318 }
319
320 // From now on all operations allow:
321 // - str with str
322 // - bytes with bytes
323 // - bytes with bytearray
324 // - bytes with array.array
325 // To do this efficiently we use the buffer protocol to extract the raw
326 // data for the rhs, but only if the lhs is a bytes object.
327 //
328 // NOTE: CPython does not allow comparison between bytes ard array.array
329 // (even if the array is of type 'b'), even though it allows addition of
330 // such types. We are not compatible with this (we do allow comparison
331 // of bytes with anything that has the buffer protocol). It would be
332 // easy to "fix" this with a bit of extra logic below, but it costs code
333 // size and execution time so we don't.
334
335 const byte *rhs_data;
Damien Georgec0d95002017-02-16 16:26:48 +1100336 size_t rhs_len;
Damien Georgea65c03c2014-11-05 16:30:34 +0000337 if (lhs_type == mp_obj_get_type(rhs_in)) {
338 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
339 rhs_data = rhs_data_;
340 rhs_len = rhs_len_;
341 } else if (lhs_type == &mp_type_bytes) {
342 mp_buffer_info_t bufinfo;
343 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000344 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000345 }
346 rhs_data = bufinfo.buf;
347 rhs_len = bufinfo.len;
348 } else {
349 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000350 return MP_OBJ_NULL; // op not supported
351 }
352
Damiend99b0522013-12-21 18:17:45 +0000353 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100354 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000355 case MP_BINARY_OP_INPLACE_ADD: {
Paul Sokolovskye2e66322017-01-27 00:40:47 +0300356 if (lhs_len == 0) {
357 return rhs_in;
358 }
359 if (rhs_len == 0) {
360 return lhs_in;
361 }
362
Damien George05005f62015-01-21 22:48:37 +0000363 vstr_t vstr;
364 vstr_init_len(&vstr, lhs_len + rhs_len);
365 memcpy(vstr.buf, lhs_data, lhs_len);
366 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
367 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200368 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200369
Damien Georgea65c03c2014-11-05 16:30:34 +0000370 case MP_BINARY_OP_IN:
371 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300372 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300373
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300374 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
375 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 +0100376 case MP_BINARY_OP_LESS:
377 case MP_BINARY_OP_LESS_EQUAL:
378 case MP_BINARY_OP_MORE:
379 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300380 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000381 }
382
Damien George6ac5dce2014-05-21 19:42:43 +0100383 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000384}
385
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300386#if !MICROPY_PY_BUILTINS_STR_UNICODE
387// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000388const 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 +0300389 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100390 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300391 return self_data + index_val;
392}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300393#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300394
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300395// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
396STATIC 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 +0300397 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100398 GET_STR_DATA_LEN(self_in, self_data, self_len);
399 if (value == MP_OBJ_SENTINEL) {
400 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100401#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100402 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300403 mp_bound_slice_t slice;
404 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Damien George821b7f22015-09-03 23:14:06 +0100405 mp_not_implemented("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100406 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100407 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100408 }
409#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300410 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100411 // If we have unicode enabled the type will always be bytes, so take the short cut.
412 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300413 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100414 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300415 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100416 }
417 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100418 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100419 }
420}
421
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200422STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300423 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300424 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000425
Damien Georgefe8fb912014-01-02 16:36:09 +0000426 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000427 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000428
429 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100430 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000431 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000432 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000433 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000434 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100435 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
436 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300437 // TODO: Try to optimize?
Damien George5b3f0b72016-01-03 15:55:55 +0000438 arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
Damien Georgea157e4c2014-04-09 19:17:53 +0100439 }
440 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000441 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000442
443 // count required length
Damien Georgec0d95002017-02-16 16:26:48 +1100444 size_t required_len = 0;
445 for (size_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300446 if (mp_obj_get_type(seq_items[i]) != self_type) {
Damien George21967992016-08-14 16:51:54 +1000447 mp_raise_TypeError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300448 "join expects a list of str/bytes objects consistent with self object");
Damiend99b0522013-12-21 18:17:45 +0000449 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000450 if (i > 0) {
451 required_len += sep_len;
452 }
Damien George5fa93b62014-01-22 14:35:10 +0000453 GET_STR_LEN(seq_items[i], l);
454 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000455 }
456
457 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000458 vstr_t vstr;
459 vstr_init_len(&vstr, required_len);
460 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +1100461 for (size_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000462 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000463 memcpy(data, sep_str, sep_len);
464 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000465 }
Damien George5fa93b62014-01-22 14:35:10 +0000466 GET_STR_DATA_LEN(seq_items[i], s, l);
467 memcpy(data, s, l);
468 data += l;
Damiend99b0522013-12-21 18:17:45 +0000469 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000470
471 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000472 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000473}
474
Damien Georgecc80c4d2016-05-13 12:21:32 +0100475mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300476 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100477 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200478 mp_obj_t sep = mp_const_none;
479 if (n_args > 1) {
480 sep = args[1];
481 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100482 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200483 }
484 }
Damien Georgedeed0872014-04-06 11:11:15 +0100485
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200486 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000487 GET_STR_DATA_LEN(args[0], s, len);
488 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200489
Damien Georgedeed0872014-04-06 11:11:15 +0100490 if (sep == mp_const_none) {
491 // sep not given, so separate on whitespace
492
493 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300494 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100495 while (s < top && splits != 0) {
496 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300497 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100498 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100499 if (s >= top) {
500 break;
501 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300502 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100503 if (splits > 0) {
504 splits--;
505 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200506 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200507
Damien Georgedeed0872014-04-06 11:11:15 +0100508 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100509 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100510 }
511
512 } else {
513 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300514 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000515 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300516 }
Damien Georgedeed0872014-04-06 11:11:15 +0100517
Damien Georged182b982014-08-30 14:19:41 +0100518 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100519 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
520
521 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300522 mp_raise_ValueError("empty separator");
Damien Georgedeed0872014-04-06 11:11:15 +0100523 }
524
525 for (;;) {
526 const byte *start = s;
527 for (;;) {
528 if (splits == 0 || s + sep_len > top) {
529 s = top;
530 break;
531 } else if (memcmp(s, sep_str, sep_len) == 0) {
532 break;
533 }
534 s++;
535 }
Damien Georgecc80c4d2016-05-13 12:21:32 +0100536 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100537 if (s >= top) {
538 break;
539 }
540 s += sep_len;
541 if (splits > 0) {
542 splits--;
543 }
544 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200545 }
546
547 return res;
548}
549
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300550#if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien George4b72b3a2016-01-03 14:21:40 +0000551STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Damien Georgecc80c4d2016-05-13 12:21:32 +0100552 enum { ARG_keepends };
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300553 static const mp_arg_t allowed_args[] = {
554 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
555 };
556
557 // parse args
Damien Georgecc80c4d2016-05-13 12:21:32 +0100558 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
559 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300560
Damien Georgecc80c4d2016-05-13 12:21:32 +0100561 const mp_obj_type_t *self_type = mp_obj_get_type(pos_args[0]);
562 mp_obj_t res = mp_obj_new_list(0, NULL);
563
564 GET_STR_DATA_LEN(pos_args[0], s, len);
565 const byte *top = s + len;
566
567 while (s < top) {
568 const byte *start = s;
569 size_t match = 0;
570 while (s < top) {
571 if (*s == '\n') {
572 match = 1;
573 break;
574 } else if (*s == '\r') {
575 if (s[1] == '\n') {
576 match = 2;
577 } else {
578 match = 1;
579 }
580 break;
581 }
582 s++;
583 }
584 size_t sub_len = s - start;
585 if (args[ARG_keepends].u_bool) {
586 sub_len += match;
587 }
588 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
589 s += match;
590 }
591
592 return res;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300593}
594#endif
595
Damien George4b72b3a2016-01-03 14:21:40 +0000596STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300597 if (n_args < 3) {
598 // If we don't have split limit, it doesn't matter from which side
599 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200600 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300601 }
602 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
603 mp_obj_t sep = args[1];
604 GET_STR_DATA_LEN(args[0], s, len);
605
Damien George40f3c022014-07-03 13:25:24 +0100606 mp_int_t splits = mp_obj_get_int(args[2]);
607 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300608 // Preallocate list to the max expected # of elements, as we
609 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000610 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100611 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300612
613 if (sep == mp_const_none) {
Damien George22602cc2015-09-01 15:35:31 +0100614 mp_not_implemented("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300615 } else {
Damien Georged182b982014-08-30 14:19:41 +0100616 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300617 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
618
619 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300620 mp_raise_ValueError("empty separator");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300621 }
622
623 const byte *beg = s;
624 const byte *last = s + len;
625 for (;;) {
626 s = last - sep_len;
627 for (;;) {
628 if (splits == 0 || s < beg) {
629 break;
630 } else if (memcmp(s, sep_str, sep_len) == 0) {
631 break;
632 }
633 s--;
634 }
635 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100636 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300637 break;
638 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100639 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 +0300640 last = s;
641 if (splits > 0) {
642 splits--;
643 }
644 }
645 if (idx != 0) {
646 // We split less parts than split limit, now go cleanup surplus
Damien Georgec0d95002017-02-16 16:26:48 +1100647 size_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100648 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300649 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
650 res->len = used;
651 }
652 }
653
Damien George999cedb2015-11-27 17:01:44 +0000654 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300655}
656
Damien Georgec0d95002017-02-16 16:26:48 +1100657STATIC 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 +0300658 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300659 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +0000660
661 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000662 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000663 bad_implicit_conversion(args[1]);
664 }
John R. Lentone8204912014-01-12 21:53:52 +0000665
Damien George5fa93b62014-01-22 14:35:10 +0000666 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
667 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000668
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300669 const byte *start = haystack;
670 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000671 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300672 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000673 }
674 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300675 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000676 }
677
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300678 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000679 if (p == NULL) {
680 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700681 if (is_index) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300682 mp_raise_ValueError("substring not found");
xbe3d9a39e2014-04-08 11:42:19 -0700683 } else {
684 return MP_OBJ_NEW_SMALL_INT(-1);
685 }
Damien George23005372014-01-13 19:39:01 +0000686 } else {
687 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300688 #if MICROPY_PY_BUILTINS_STR_UNICODE
689 if (self_type == &mp_type_str) {
690 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
691 }
692 #endif
xbe17a5a832014-03-23 23:31:58 -0700693 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000694 }
John R. Lentone8204912014-01-12 21:53:52 +0000695}
696
Damien George4b72b3a2016-01-03 14:21:40 +0000697STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700698 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700699}
700
Damien George4b72b3a2016-01-03 14:21:40 +0000701STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700702 return str_finder(n_args, args, -1, false);
703}
704
Damien George4b72b3a2016-01-03 14:21:40 +0000705STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700706 return str_finder(n_args, args, 1, true);
707}
708
Damien George4b72b3a2016-01-03 14:21:40 +0000709STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700710 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700711}
712
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200713// TODO: (Much) more variety in args
Damien George4b72b3a2016-01-03 14:21:40 +0000714STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300715 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300716 GET_STR_DATA_LEN(args[0], str, str_len);
717 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300718 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300719 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300720 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300721 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300722 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200723 return mp_const_false;
724 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300725 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200726}
727
Damien George4b72b3a2016-01-03 14:21:40 +0000728STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300729 GET_STR_DATA_LEN(args[0], str, str_len);
730 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100731 if (n_args > 2) {
732 mp_not_implemented("start/end indices");
733 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300734
735 if (suffix_len > str_len) {
736 return mp_const_false;
737 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300738 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300739}
740
Paul Sokolovsky88107842014-04-26 06:20:08 +0300741enum { LSTRIP, RSTRIP, STRIP };
742
Damien George90ab1912017-02-03 13:04:56 +1100743STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +0300744 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300745 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000746
747 const byte *chars_to_del;
748 uint chars_to_del_len;
749 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800750
751 if (n_args == 1) {
752 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000753 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800754 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300755 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000756 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300757 }
Damien George5fa93b62014-01-22 14:35:10 +0000758 GET_STR_DATA_LEN(args[1], s, l);
759 chars_to_del = s;
760 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800761 }
762
Damien George5fa93b62014-01-22 14:35:10 +0000763 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800764
Damien Georgec0d95002017-02-16 16:26:48 +1100765 size_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800766 bool first_good_char_pos_set = false;
Damien Georgec0d95002017-02-16 16:26:48 +1100767 size_t last_good_char_pos = 0;
768 size_t i = 0;
769 int delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300770 if (type == RSTRIP) {
771 i = orig_str_len - 1;
772 delta = -1;
773 }
Damien Georgec0d95002017-02-16 16:26:48 +1100774 for (size_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700775 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800776 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300777 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800778 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300779 if (type == LSTRIP) {
780 last_good_char_pos = orig_str_len - 1;
781 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300782 } else if (type == RSTRIP) {
783 first_good_char_pos = 0;
784 last_good_char_pos = i;
785 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300786 }
xbe7b0f39f2014-01-08 14:23:45 -0800787 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300788 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800789 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300790 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800791 }
792
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300793 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000794 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000795 if (self_type == &mp_type_str) {
796 return MP_OBJ_NEW_QSTR(MP_QSTR_);
797 } else {
798 return mp_const_empty_bytes;
799 }
xbe7b0f39f2014-01-08 14:23:45 -0800800 }
801
802 assert(last_good_char_pos >= first_good_char_pos);
803 //+1 to accomodate the last character
Damien Georgec0d95002017-02-16 16:26:48 +1100804 size_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300805 if (stripped_len == orig_str_len) {
806 // If nothing was stripped, don't bother to dup original string
807 // TODO: watch out for this case when we'll get to bytearray.strip()
808 assert(first_good_char_pos == 0);
809 return args[0];
810 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100811 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800812}
813
Damien George4b72b3a2016-01-03 14:21:40 +0000814STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300815 return str_uni_strip(STRIP, n_args, args);
816}
817
Damien George4b72b3a2016-01-03 14:21:40 +0000818STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300819 return str_uni_strip(LSTRIP, n_args, args);
820}
821
Damien George4b72b3a2016-01-03 14:21:40 +0000822STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300823 return str_uni_strip(RSTRIP, n_args, args);
824}
825
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300826#if MICROPY_PY_BUILTINS_STR_CENTER
827STATIC mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) {
828 GET_STR_DATA_LEN(str_in, str, str_len);
Paul Sokolovsky9dde6062016-05-22 02:22:14 +0300829 mp_uint_t width = mp_obj_get_int(width_in);
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +0300830 if (str_len >= width) {
831 return str_in;
832 }
833
834 vstr_t vstr;
835 vstr_init_len(&vstr, width);
836 memset(vstr.buf, ' ', width);
837 int left = (width - str_len) / 2;
838 memcpy(vstr.buf + left, str, str_len);
839 return mp_obj_new_str_from_vstr(mp_obj_get_type(str_in), &vstr);
840}
841#endif
842
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700843// Takes an int arg, but only parses unsigned numbers, and only changes
844// *num if at least one digit was parsed.
Damien George87e07ea2016-02-02 15:51:57 +0000845STATIC const char *str_to_int(const char *str, const char *top, int *num) {
846 if (str < top && '0' <= *str && *str <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700847 *num = 0;
848 do {
Damien George87e07ea2016-02-02 15:51:57 +0000849 *num = *num * 10 + (*str - '0');
850 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700851 }
Damien George87e07ea2016-02-02 15:51:57 +0000852 while (str < top && '0' <= *str && *str <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700853 }
Damien George87e07ea2016-02-02 15:51:57 +0000854 return str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700855}
856
Damien George2801e6f2015-04-04 15:53:11 +0100857STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700858 return ch && strchr("<>=^", ch) != NULL;
859}
860
Damien George2801e6f2015-04-04 15:53:11 +0100861STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700862 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
863}
864
Damien George2801e6f2015-04-04 15:53:11 +0100865STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700866 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
867}
868
Damien George2801e6f2015-04-04 15:53:11 +0100869STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700870 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100871#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100872 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700873#endif
874 ;
875}
876
Damien George2801e6f2015-04-04 15:53:11 +0100877STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100878#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100879 if (mp_obj_is_float(arg)) {
880 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700881 }
882#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700883 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700884}
885
Damien George897129a2016-09-27 15:45:42 +1000886#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE
Damien George1e9a92f2014-11-06 17:36:16 +0000887STATIC NORETURN void terse_str_format_value_error(void) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300888 mp_raise_ValueError("bad format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000889}
Damien George897129a2016-09-27 15:45:42 +1000890#else
891// define to nothing to improve coverage
892#define terse_str_format_value_error()
893#endif
Damien George1e9a92f2014-11-06 17:36:16 +0000894
Damien George90ab1912017-02-03 13:04:56 +1100895STATIC 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 +0000896 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100897 mp_print_t print;
898 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700899
pohmeliee3a29de2016-01-29 12:09:10 +0300900 for (; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700901 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000902 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700903 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100904 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 continue;
906 }
Damien George1e9a92f2014-11-06 17:36:16 +0000907 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
908 terse_str_format_value_error();
909 } else {
Damien George21967992016-08-14 16:51:54 +1000910 mp_raise_ValueError("single '}' encountered in format string");
Damien George1e9a92f2014-11-06 17:36:16 +0000911 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700912 }
913 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100914 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700915 continue;
916 }
917
918 str++;
919 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100920 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700921 continue;
922 }
923
924 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
925
Damien George87e07ea2016-02-02 15:51:57 +0000926 const char *field_name = NULL;
927 const char *field_name_top = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700928 char conversion = '\0';
pohmeliee3a29de2016-01-29 12:09:10 +0300929 const char *format_spec = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700930
931 if (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000932 field_name = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700933 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000934 ++str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700935 }
Damien George87e07ea2016-02-02 15:51:57 +0000936 field_name_top = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700937 }
938
939 // conversion ::= "r" | "s"
940
941 if (str < top && *str == '!') {
942 str++;
943 if (str < top && (*str == 'r' || *str == 's')) {
944 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200945 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000946 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
947 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100948 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300949 mp_raise_ValueError("bad conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100950 } else {
951 if (str >= top) {
Damien George21967992016-08-14 16:51:54 +1000952 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300953 "end of format while looking for conversion specifier");
Damien George000730e2015-08-30 12:43:21 +0100954 } else {
955 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
956 "unknown conversion specifier %c", *str));
957 }
Damien George1e9a92f2014-11-06 17:36:16 +0000958 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700959 }
960 }
961
962 if (str < top && *str == ':') {
963 str++;
964 // {:} is the same as {}, which is the same as {!s}
965 // This makes a difference when passing in a True or False
966 // '{}'.format(True) returns 'True'
967 // '{:d}'.format(True) returns '1'
968 // So we treat {:} as {} and this later gets treated to be {!s}
969 if (*str != '}') {
pohmeliee3a29de2016-01-29 12:09:10 +0300970 format_spec = str;
971 for (int nest = 1; str < top;) {
972 if (*str == '{') {
973 ++nest;
974 } else if (*str == '}') {
975 if (--nest == 0) {
976 break;
977 }
978 }
979 ++str;
Damiend99b0522013-12-21 18:17:45 +0000980 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700981 }
982 }
983 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000984 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
985 terse_str_format_value_error();
986 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300987 mp_raise_ValueError("unmatched '{' in format");
Damien George1e9a92f2014-11-06 17:36:16 +0000988 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700989 }
990 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000991 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
992 terse_str_format_value_error();
993 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +0300994 mp_raise_ValueError("expected ':' after format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +0000995 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700996 }
997
998 mp_obj_t arg = mp_const_none;
999
1000 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +01001001 int index = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001002 if (MP_LIKELY(unichar_isdigit(*field_name))) {
pohmeliee3a29de2016-01-29 12:09:10 +03001003 if (*arg_i > 0) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001004 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1005 terse_str_format_value_error();
1006 } else {
Damien George21967992016-08-14 16:51:54 +10001007 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001008 "can't switch from automatic field numbering to manual field specification");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001009 }
1010 }
Damien George87e07ea2016-02-02 15:51:57 +00001011 field_name = str_to_int(field_name, field_name_top, &index);
Damien George963a5a32015-01-16 17:47:07 +00001012 if ((uint)index >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001013 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001014 }
1015 arg = args[index + 1];
pohmeliee3a29de2016-01-29 12:09:10 +03001016 *arg_i = -1;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001017 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001018 const char *lookup;
1019 for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
1020 mp_obj_t field_q = mp_obj_new_str(field_name, lookup - field_name, true/*?*/);
1021 field_name = lookup;
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001022 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
1023 if (key_elem == NULL) {
1024 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
1025 }
1026 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001027 }
Damien George87e07ea2016-02-02 15:51:57 +00001028 if (field_name < field_name_top) {
Damien George821b7f22015-09-03 23:14:06 +01001029 mp_not_implemented("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001030 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001031 } else {
pohmeliee3a29de2016-01-29 12:09:10 +03001032 if (*arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +00001033 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1034 terse_str_format_value_error();
1035 } else {
Damien George21967992016-08-14 16:51:54 +10001036 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001037 "can't switch from manual field specification to automatic field numbering");
Damien George1e9a92f2014-11-06 17:36:16 +00001038 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001039 }
pohmeliee3a29de2016-01-29 12:09:10 +03001040 if ((uint)*arg_i >= n_args - 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001041 mp_raise_msg(&mp_type_IndexError, "tuple index out of range");
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001042 }
pohmeliee3a29de2016-01-29 12:09:10 +03001043 arg = args[(*arg_i) + 1];
1044 (*arg_i)++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001045 }
1046 if (!format_spec && !conversion) {
1047 conversion = 's';
1048 }
1049 if (conversion) {
1050 mp_print_kind_t print_kind;
1051 if (conversion == 's') {
1052 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001053 } else {
Damien George000730e2015-08-30 12:43:21 +01001054 assert(conversion == 'r');
1055 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001056 }
Damien George0b9ee862015-01-21 19:14:25 +00001057 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001058 mp_print_t arg_print;
1059 vstr_init_print(&arg_vstr, 16, &arg_print);
1060 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001061 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001062 }
1063
1064 char sign = '\0';
1065 char fill = '\0';
1066 char align = '\0';
1067 int width = -1;
1068 int precision = -1;
1069 char type = '\0';
1070 int flags = 0;
1071
1072 if (format_spec) {
1073 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1074 //
1075 // [[fill]align][sign][#][0][width][,][.precision][type]
1076 // fill ::= <any character>
1077 // align ::= "<" | ">" | "=" | "^"
1078 // sign ::= "+" | "-" | " "
1079 // width ::= integer
1080 // precision ::= integer
1081 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1082
pohmeliee3a29de2016-01-29 12:09:10 +03001083 // recursively call the formatter to format any nested specifiers
1084 MP_STACK_CHECK();
1085 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 +03001086 const char *s = vstr_null_terminated_str(&format_spec_vstr);
Damien George87e07ea2016-02-02 15:51:57 +00001087 const char *stop = s + format_spec_vstr.len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001088 if (isalignment(*s)) {
1089 align = *s++;
1090 } else if (*s && isalignment(s[1])) {
1091 fill = *s++;
1092 align = *s++;
1093 }
1094 if (*s == '+' || *s == '-' || *s == ' ') {
1095 if (*s == '+') {
1096 flags |= PF_FLAG_SHOW_SIGN;
1097 } else if (*s == ' ') {
1098 flags |= PF_FLAG_SPACE_SIGN;
1099 }
1100 sign = *s++;
1101 }
1102 if (*s == '#') {
1103 flags |= PF_FLAG_SHOW_PREFIX;
1104 s++;
1105 }
1106 if (*s == '0') {
1107 if (!align) {
1108 align = '=';
1109 }
1110 if (!fill) {
1111 fill = '0';
1112 }
1113 }
Damien George87e07ea2016-02-02 15:51:57 +00001114 s = str_to_int(s, stop, &width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001115 if (*s == ',') {
1116 flags |= PF_FLAG_SHOW_COMMA;
1117 s++;
1118 }
1119 if (*s == '.') {
1120 s++;
Damien George87e07ea2016-02-02 15:51:57 +00001121 s = str_to_int(s, stop, &precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001122 }
1123 if (istype(*s)) {
1124 type = *s++;
1125 }
Paul Sokolovsky40f00962016-05-09 23:42:42 +03001126 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001127 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1128 terse_str_format_value_error();
1129 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001130 mp_raise_ValueError("invalid format specifier");
Damien George7ef75f92015-08-26 15:42:25 +01001131 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001132 }
pohmeliee3a29de2016-01-29 12:09:10 +03001133 vstr_clear(&format_spec_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001134 }
1135 if (!align) {
1136 if (arg_looks_numeric(arg)) {
1137 align = '>';
1138 } else {
1139 align = '<';
1140 }
1141 }
1142 if (!fill) {
1143 fill = ' ';
1144 }
1145
1146 if (sign) {
1147 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001148 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1149 terse_str_format_value_error();
1150 } else {
Damien George21967992016-08-14 16:51:54 +10001151 mp_raise_ValueError("sign not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001152 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001153 }
1154 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001155 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1156 terse_str_format_value_error();
1157 } else {
Damien George21967992016-08-14 16:51:54 +10001158 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001159 "sign not allowed with integer format specifier 'c'");
Damien George1e9a92f2014-11-06 17:36:16 +00001160 }
Damiend99b0522013-12-21 18:17:45 +00001161 }
1162 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001163 sign = '-';
1164 }
1165
1166 switch (align) {
1167 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1168 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1169 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1170 }
1171
1172 if (arg_looks_integer(arg)) {
1173 switch (type) {
1174 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001175 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001176 continue;
1177
1178 case 'c':
1179 {
1180 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001181 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001182 continue;
1183 }
1184
1185 case '\0': // No explicit format type implies 'd'
1186 case 'n': // I don't think we support locales in uPy so use 'd'
1187 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001188 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001189 continue;
1190
1191 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001192 if (flags & PF_FLAG_SHOW_PREFIX) {
1193 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1194 }
1195
Damien George7f9d1d62015-04-09 23:56:15 +01001196 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001197 continue;
1198
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001199 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001200 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001201 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001202 continue;
1203
1204 case 'e':
1205 case 'E':
1206 case 'f':
1207 case 'F':
1208 case 'g':
1209 case 'G':
1210 case '%':
1211 // The floating point formatters all work with anything that
1212 // looks like an integer
1213 break;
1214
1215 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001216 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1217 terse_str_format_value_error();
1218 } else {
1219 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1220 "unknown format code '%c' for object of type '%s'",
1221 type, mp_obj_get_type_str(arg)));
1222 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001223 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001224 }
Damien George70f33cd2014-04-02 17:06:05 +01001225
Dave Hylands22fe4d72014-04-02 12:07:31 -07001226 // NOTE: no else here. We need the e, f, g etc formats for integer
1227 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001228 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001229 if (!type) {
1230
1231 // Even though the docs say that an unspecified type is the same
1232 // as 'g', there is one subtle difference, when the exponent
1233 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001234 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001235 // '{:10.1}'.format(0.0) ==> '0e+00'
1236 // '{:10.1g}'.format(0.0) ==> '0'
1237 //
1238 // TODO: Figure out how to deal with this.
1239 //
1240 // A proper solution would involve adding a special flag
1241 // or something to format_float, and create a format_double
1242 // to deal with doubles. In order to fix this when using
1243 // sprintf, we'd need to use the e format and tweak the
1244 // returned result to strip trailing zeros like the g format
1245 // does.
1246 //
1247 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1248 // but with 1.e2 you get 1e+02 and 1.00e+02
1249 //
1250 // Stripping the trailing 0's (like g) does would make the
1251 // e format give us the right format.
1252 //
1253 // CPython sources say:
1254 // Omitted type specifier. Behaves in the same way as repr(x)
1255 // and str(x) if no precision is given, else like 'g', but with
1256 // at least one digit after the decimal point. */
1257
1258 type = 'g';
1259 }
1260 if (type == 'n') {
1261 type = 'g';
1262 }
1263
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001264 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001265#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001266 case 'e':
1267 case 'E':
1268 case 'f':
1269 case 'F':
1270 case 'g':
1271 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001272 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001273 break;
1274
1275 case '%':
1276 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001277 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1278 #define F100 100.0F
1279 #else
1280 #define F100 100.0
1281 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001282 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001283 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001284 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001285#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001286
1287 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001288 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1289 terse_str_format_value_error();
1290 } else {
1291 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1292 "unknown format code '%c' for object of type 'float'",
1293 type, mp_obj_get_type_str(arg)));
1294 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001295 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001296 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001297 // arg doesn't look like a number
1298
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001299 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001300 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1301 terse_str_format_value_error();
1302 } else {
Damien George21967992016-08-14 16:51:54 +10001303 mp_raise_ValueError(
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001304 "'=' alignment not allowed in string format specifier");
Damien George1e9a92f2014-11-06 17:36:16 +00001305 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001306 }
Damien George70f33cd2014-04-02 17:06:05 +01001307
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001308 switch (type) {
Damien Georged4df8f42016-01-04 13:13:39 +00001309 case '\0': // no explicit format type implies 's'
Damien Georged182b982014-08-30 14:19:41 +01001310 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001311 mp_uint_t slen;
1312 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001313 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001314 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001315 }
Damien George50912e72015-01-20 11:55:10 +00001316 if (slen > (mp_uint_t)precision) {
1317 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001318 }
Damien George7f9d1d62015-04-09 23:56:15 +01001319 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001320 break;
1321 }
1322
1323 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001324 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1325 terse_str_format_value_error();
1326 } else {
1327 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1328 "unknown format code '%c' for object of type 'str'",
1329 type, mp_obj_get_type_str(arg)));
1330 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001331 }
Damiend99b0522013-12-21 18:17:45 +00001332 }
1333 }
1334
pohmeliee3a29de2016-01-29 12:09:10 +03001335 return vstr;
1336}
1337
1338mp_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 +03001339 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
pohmeliee3a29de2016-01-29 12:09:10 +03001340
1341 GET_STR_DATA_LEN(args[0], str, len);
1342 int arg_i = 0;
1343 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 +00001344 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001345}
1346
Damien George90ab1912017-02-03 13:04:56 +11001347STATIC 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 +03001348 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001349
1350 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001351 const byte *start_str = str;
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001352 bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
Damien George90ab1912017-02-03 13:04:56 +11001353 size_t arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001354 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001355 mp_print_t print;
1356 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001357
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001358 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001359 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001360 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001361 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001362 continue;
1363 }
1364 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001365 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001366 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001367 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001368 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001369 continue;
1370 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001371
1372 // Dictionary value lookup
1373 if (*str == '(') {
Damien George7317e342017-02-03 12:13:44 +11001374 if (dict == MP_OBJ_NULL) {
1375 mp_raise_TypeError("format requires a dict");
1376 }
1377 arg_i = 1; // we used up the single dict argument
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001378 const byte *key = ++str;
1379 while (*str != ')') {
1380 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001381 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1382 terse_str_format_value_error();
1383 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001384 mp_raise_ValueError("incomplete format key");
Damien George1e9a92f2014-11-06 17:36:16 +00001385 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001386 }
1387 ++str;
1388 }
1389 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1390 arg = mp_obj_dict_get(dict, k_obj);
1391 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001392 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001393
Dave Hylands6756a372014-04-02 11:42:39 -07001394 int flags = 0;
1395 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001396 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001397 while (str < top) {
1398 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1399 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1400 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001401 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001402 else if (*str == '0') {
1403 flags |= PF_FLAG_PAD_AFTER_SIGN;
1404 fill = '0';
1405 } else break;
1406 str++;
1407 }
1408 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001409 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001410 if (str < top) {
1411 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001412 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001413 goto not_enough_args;
1414 }
Dave Hylands6756a372014-04-02 11:42:39 -07001415 width = mp_obj_get_int(args[arg_i++]);
1416 str++;
1417 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001418 str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001419 }
1420 }
1421 int prec = -1;
1422 if (str < top && *str == '.') {
1423 if (++str < top) {
1424 if (*str == '*') {
Damien George90ab1912017-02-03 13:04:56 +11001425 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001426 goto not_enough_args;
1427 }
Dave Hylands6756a372014-04-02 11:42:39 -07001428 prec = mp_obj_get_int(args[arg_i++]);
1429 str++;
1430 } else {
1431 prec = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001432 str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001433 }
1434 }
1435 }
1436
1437 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001438incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001439 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1440 terse_str_format_value_error();
1441 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001442 mp_raise_ValueError("incomplete format");
Damien George1e9a92f2014-11-06 17:36:16 +00001443 }
Dave Hylands6756a372014-04-02 11:42:39 -07001444 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001445
1446 // Tuple value lookup
1447 if (arg == MP_OBJ_NULL) {
Damien George90ab1912017-02-03 13:04:56 +11001448 if (arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001449not_enough_args:
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001450 mp_raise_TypeError("not enough arguments for format string");
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001451 }
1452 arg = args[arg_i++];
1453 }
Dave Hylands6756a372014-04-02 11:42:39 -07001454 switch (*str) {
1455 case 'c':
1456 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001457 mp_uint_t slen;
1458 const char *s = mp_obj_str_get_data(arg, &slen);
1459 if (slen != 1) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001460 mp_raise_TypeError("%%c requires int or char");
Dave Hylands6756a372014-04-02 11:42:39 -07001461 }
Damien George7f9d1d62015-04-09 23:56:15 +01001462 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001463 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001464 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001465 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001466 } else {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001467 mp_raise_TypeError("integer required");
Dave Hylands6756a372014-04-02 11:42:39 -07001468 }
Damien George11de8392014-06-05 18:57:38 +01001469 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001470
1471 case 'd':
1472 case 'i':
1473 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001474 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001475 break;
1476
Damien Georgefb510b32014-06-01 13:32:54 +01001477#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001478 case 'e':
1479 case 'E':
1480 case 'f':
1481 case 'F':
1482 case 'g':
1483 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001484 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001485 break;
1486#endif
1487
1488 case 'o':
1489 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001490 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001491 }
Damien George7f9d1d62015-04-09 23:56:15 +01001492 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001493 break;
1494
1495 case 'r':
1496 case 's':
1497 {
Damien George0b9ee862015-01-21 19:14:25 +00001498 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001499 mp_print_t arg_print;
1500 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001501 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1502 if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1503 // If we have something like b"%s" % b"1", bytes arg should be
1504 // printed undecorated.
1505 print_kind = PRINT_RAW;
1506 }
1507 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001508 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001509 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001510 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001511 }
Damien George50912e72015-01-20 11:55:10 +00001512 if (vlen > (uint)prec) {
1513 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001514 }
Damien George7f9d1d62015-04-09 23:56:15 +01001515 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001516 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001517 break;
1518 }
Dave Hylands6756a372014-04-02 11:42:39 -07001519
Dave Hylands6756a372014-04-02 11:42:39 -07001520 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001521 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001522 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001523 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001524
Dave Hylands6756a372014-04-02 11:42:39 -07001525 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001526 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1527 terse_str_format_value_error();
1528 } else {
1529 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1530 "unsupported format character '%c' (0x%x) at index %d",
1531 *str, *str, str - start_str));
1532 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001533 }
1534 }
1535
Damien George90ab1912017-02-03 13:04:56 +11001536 if (arg_i != n_args) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001537 mp_raise_TypeError("not all arguments converted during string formatting");
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001538 }
1539
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001540 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001541}
1542
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001543// The implementation is optimized, returning the original string if there's
1544// nothing to replace.
Damien George4b72b3a2016-01-03 14:21:40 +00001545STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001546 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001547
Damien George40f3c022014-07-03 13:25:24 +01001548 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001549 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001550 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001551 if (max_rep == 0) {
1552 return args[0];
1553 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001554 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001555 }
xbe480c15a2014-01-30 22:17:30 -08001556 }
Damien George94f68302014-01-31 23:45:12 +00001557
xbe729be9b2014-04-07 14:46:39 -07001558 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001559
Damien Georgeff715422014-04-07 00:39:13 +01001560 // check argument types
1561
Damien Georgec55a4d82014-12-24 20:28:30 +00001562 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1563
1564 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001565 bad_implicit_conversion(args[1]);
1566 }
1567
Damien Georgec55a4d82014-12-24 20:28:30 +00001568 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001569 bad_implicit_conversion(args[2]);
1570 }
1571
1572 // extract string data
1573
xbe480c15a2014-01-30 22:17:30 -08001574 GET_STR_DATA_LEN(args[0], str, str_len);
1575 GET_STR_DATA_LEN(args[1], old, old_len);
1576 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001577
1578 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001579 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001580 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001581 }
1582
Damien George94f68302014-01-31 23:45:12 +00001583 // data for the replaced string
1584 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001585 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001586
Damien George94f68302014-01-31 23:45:12 +00001587 // do 2 passes over the string:
1588 // first pass computes the required length of the replaced string
1589 // second pass does the replacements
1590 for (;;) {
Damien Georgec0d95002017-02-16 16:26:48 +11001591 size_t replaced_str_index = 0;
1592 size_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001593 const byte *old_occurrence;
1594 const byte *offset_ptr = str;
Damien Georgec0d95002017-02-16 16:26:48 +11001595 size_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001596 if (old_len == 0) {
1597 // if old_str is empty, copy new_str to start of replaced string
1598 // copy the replacement string
1599 if (data != NULL) {
1600 memcpy(data, new, new_len);
1601 }
1602 replaced_str_index += new_len;
1603 num_replacements_done++;
1604 }
Damien Georgec0d95002017-02-16 16:26:48 +11001605 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 +01001606 if (old_len == 0) {
1607 old_occurrence += 1;
1608 }
Damien George94f68302014-01-31 23:45:12 +00001609 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1610 if (data != NULL) {
1611 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1612 }
1613 replaced_str_index += old_occurrence - offset_ptr;
1614 // copy the replacement string
1615 if (data != NULL) {
1616 memcpy(data + replaced_str_index, new, new_len);
1617 }
1618 replaced_str_index += new_len;
1619 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001620 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001621 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001622 }
1623
1624 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1625 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001626 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001627 }
Damien Georgeff715422014-04-07 00:39:13 +01001628 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001629
1630 if (data == NULL) {
1631 // first pass
1632 if (num_replacements_done == 0) {
1633 // no substr found, return original string
1634 return args[0];
1635 } else {
1636 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001637 vstr_init_len(&vstr, replaced_str_index);
1638 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001639 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001640 }
1641 } else {
1642 // second pass, we are done
1643 break;
1644 }
xbe480c15a2014-01-30 22:17:30 -08001645 }
Damien George94f68302014-01-31 23:45:12 +00001646
Damien George05005f62015-01-21 22:48:37 +00001647 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001648}
1649
Damien George4b72b3a2016-01-03 14:21:40 +00001650STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001651 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001652 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damien Georgebe8e99c2014-11-05 16:45:54 +00001653
1654 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001655 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001656 bad_implicit_conversion(args[1]);
1657 }
xbe9e1e8cd2014-03-12 22:57:16 -07001658
1659 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1660 GET_STR_DATA_LEN(args[1], needle, needle_len);
1661
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001662 const byte *start = haystack;
1663 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001664 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001665 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001666 }
1667 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001668 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001669 }
1670
Damien George536dde22014-03-13 22:07:55 +00001671 // if needle_len is zero then we count each gap between characters as an occurrence
1672 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001673 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001674 }
1675
Damien George536dde22014-03-13 22:07:55 +00001676 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001677 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001678 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1679 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001680 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001681 haystack_ptr += needle_len;
1682 } else {
1683 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001684 }
xbe9e1e8cd2014-03-12 22:57:16 -07001685 }
1686
1687 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1688}
1689
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001690#if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgec0d95002017-02-16 16:26:48 +11001691STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) {
Paul Sokolovskyc4a80042016-08-12 22:06:47 +03001692 mp_check_self(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001693 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1694 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001695 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001696 }
Damien Georgeb035db32014-03-21 20:39:40 +00001697
xbe613a8e32014-03-18 00:06:29 -07001698 GET_STR_DATA_LEN(self_in, str, str_len);
1699 GET_STR_DATA_LEN(arg, sep, sep_len);
1700
1701 if (sep_len == 0) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03001702 mp_raise_ValueError("empty separator");
xbe613a8e32014-03-18 00:06:29 -07001703 }
Damien Georgeb035db32014-03-21 20:39:40 +00001704
Damien Georgec55a4d82014-12-24 20:28:30 +00001705 mp_obj_t result[3];
1706 if (self_type == &mp_type_str) {
1707 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1708 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1709 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1710 } else {
1711 result[0] = mp_const_empty_bytes;
1712 result[1] = mp_const_empty_bytes;
1713 result[2] = mp_const_empty_bytes;
1714 }
Damien Georgeb035db32014-03-21 20:39:40 +00001715
1716 if (direction > 0) {
1717 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001718 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001719 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001720 }
xbe613a8e32014-03-18 00:06:29 -07001721
xbe17a5a832014-03-23 23:31:58 -07001722 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1723 if (position_ptr != NULL) {
Damien Georgec0d95002017-02-16 16:26:48 +11001724 size_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001725 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001726 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001727 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 -07001728 }
Damien Georgeb035db32014-03-21 20:39:40 +00001729
xbe0a6894c2014-03-21 01:12:26 -07001730 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001731}
1732
Damien Georgeb035db32014-03-21 20:39:40 +00001733STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1734 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001735}
xbe4504ea82014-03-19 00:46:14 -07001736
Damien Georgeb035db32014-03-21 20:39:40 +00001737STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1738 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001739}
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001740#endif
xbe4504ea82014-03-19 00:46:14 -07001741
Paul Sokolovsky69135212014-05-10 19:47:41 +03001742// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001743STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001744 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001745 vstr_t vstr;
1746 vstr_init_len(&vstr, self_len);
1747 byte *data = (byte*)vstr.buf;
Damien Georgec0d95002017-02-16 16:26:48 +11001748 for (size_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001749 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001750 }
Damien George05005f62015-01-21 22:48:37 +00001751 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001752}
1753
1754STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001755 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001756}
1757
1758STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001759 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001760}
1761
Damien Georgefcc9cf62014-06-01 18:22:09 +01001762STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001763 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001764
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001765 if (self_len == 0) {
1766 return mp_const_false; // default to False for empty str
1767 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001768
Damien Georgefcc9cf62014-06-01 18:22:09 +01001769 if (f != unichar_isupper && f != unichar_islower) {
Damien Georgec0d95002017-02-16 16:26:48 +11001770 for (size_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001771 if (!f(*self_data++)) {
1772 return mp_const_false;
1773 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001774 }
1775 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001776 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001777
Damien Georgec0d95002017-02-16 16:26:48 +11001778 for (size_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001779 if (unichar_isalpha(*self_data++)) {
1780 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001781 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1782 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001783 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001784 }
1785 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001786
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001787 if (!contains_alpha) {
1788 return mp_const_false;
1789 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001790 }
1791
1792 return mp_const_true;
1793}
1794
1795STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001796 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001797}
1798
1799STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001800 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001801}
1802
1803STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001804 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001805}
1806
1807STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001808 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001809}
1810
1811STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001812 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001813}
1814
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001815#if MICROPY_CPYTHON_COMPAT
1816// These methods are superfluous in the presense of str() and bytes()
1817// constructors.
1818// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001819STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001820 mp_obj_t new_args[2];
1821 if (n_args == 1) {
1822 new_args[0] = args[0];
1823 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1824 args = new_args;
1825 n_args++;
1826 }
Damien George5b3f0b72016-01-03 15:55:55 +00001827 return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001828}
1829
1830// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001831STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001832 mp_obj_t new_args[2];
1833 if (n_args == 1) {
1834 new_args[0] = args[0];
1835 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1836 args = new_args;
1837 n_args++;
1838 }
Damien George5b3f0b72016-01-03 15:55:55 +00001839 return bytes_make_new(NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001840}
1841#endif
1842
Damien George4d917232014-08-30 14:28:06 +01001843mp_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 +01001844 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001845 GET_STR_DATA_LEN(self_in, str_data, str_len);
1846 bufinfo->buf = (void*)str_data;
1847 bufinfo->len = str_len;
Damien George12dd8df2016-05-07 21:18:17 +01001848 bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access
Damien George2da98302014-03-09 19:58:18 +00001849 return 0;
1850 } else {
1851 // can't write to a string
1852 bufinfo->buf = NULL;
1853 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001854 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001855 return 1;
1856 }
1857}
1858
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001859#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001860MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1861MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001862#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001863MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1864MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1865MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1866MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1867MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Paul Sokolovsky87051712015-03-23 22:15:12 +02001868MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001869#if MICROPY_PY_BUILTINS_STR_SPLITLINES
1870MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
1871#endif
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +03001872#if MICROPY_PY_BUILTINS_STR_CENTER
1873MP_DEFINE_CONST_FUN_OBJ_2(str_center_obj, str_center);
1874#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001875MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1876MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1877MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1878MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1879MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1880MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001881MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001882MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1883MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001884#if MICROPY_PY_BUILTINS_STR_PARTITION
Paul Sokolovsky97319122014-06-13 22:01:26 +03001885MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1886MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001887#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001888MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1889MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1890MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1891MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1892MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1893MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1894MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001895
Damien Georgecbf76742015-11-27 13:38:15 +00001896STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001897#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001898 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001899 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1900 // If we have separate unicode type, then here we have methods only
1901 // for bytes type, and it should not have encode() methods. Otherwise,
1902 // we have non-compliant-but-practical bytestring type, which shares
1903 // method table with bytes, so they both have encode() and decode()
1904 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001905 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001906 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001907#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001908 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1909 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1910 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1911 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1912 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1913 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001914 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001915 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001916 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001917 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1918 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1919 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1920 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1921 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1922 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1923 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1924 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1925 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001926 #if MICROPY_PY_BUILTINS_STR_PARTITION
Damien Georgecbf76742015-11-27 13:38:15 +00001927 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1928 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
Paul Sokolovsky56eb25f2016-08-07 06:46:55 +03001929 #endif
Paul Sokolovsky15633882016-08-07 15:24:57 +03001930 #if MICROPY_PY_BUILTINS_STR_CENTER
Paul Sokolovsky1b5abfc2016-05-22 00:13:44 +03001931 { MP_ROM_QSTR(MP_QSTR_center), MP_ROM_PTR(&str_center_obj) },
Paul Sokolovsky15633882016-08-07 15:24:57 +03001932 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001933 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1934 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1935 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1936 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1937 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1938 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1939 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001940};
Damien George97209d32014-01-07 15:58:30 +00001941
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001942STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001943
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001944#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George44e7cbf2015-05-17 16:44:24 +01001945STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
1946
Damien George3e1a5c12014-03-29 13:43:38 +00001947const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001948 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001949 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001950 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001951 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001952 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001953 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001954 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001955 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001956 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001957};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001958#endif
Damiend99b0522013-12-21 18:17:45 +00001959
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001960// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001961const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001962 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001963 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001964 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001965 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001966 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001967 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001968 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001969 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001970 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001971};
1972
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001973// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001974const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001975
Damien George77089be2015-01-21 23:08:36 +00001976// Create a str/bytes object using the given data. New memory is allocated and
1977// the data is copied across.
Damien George999cedb2015-11-27 17:01:44 +00001978mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001979 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001980 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001981 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001982 if (data) {
1983 o->hash = qstr_compute_hash(data, len);
1984 byte *p = m_new(byte, len + 1);
1985 o->data = p;
1986 memcpy(p, data, len * sizeof(byte));
1987 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1988 }
Damien George999cedb2015-11-27 17:01:44 +00001989 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001990}
1991
Damien George77089be2015-01-21 23:08:36 +00001992// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1993// the exact length required and then reused for the str/bytes object. The vstr
1994// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001995mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1996 // if not a bytes object, look if a qstr with this data already exists
1997 if (type == &mp_type_str) {
1998 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1999 if (q != MP_QSTR_NULL) {
2000 vstr_clear(vstr);
2001 vstr->alloc = 0;
2002 return MP_OBJ_NEW_QSTR(q);
2003 }
2004 }
2005
2006 // make a new str/bytes object
2007 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
2008 o->base.type = type;
2009 o->len = vstr->len;
2010 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07002011 if (vstr->len + 1 == vstr->alloc) {
2012 o->data = (byte*)vstr->buf;
2013 } else {
2014 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
2015 }
Damien George0d3cb672015-01-28 23:43:01 +00002016 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00002017 vstr->buf = NULL;
2018 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00002019 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00002020}
2021
Damien Georgec0d95002017-02-16 16:26:48 +11002022mp_obj_t mp_obj_new_str(const char* data, size_t len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01002023 if (make_qstr_if_not_already) {
2024 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01002025 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00002026 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01002027 qstr q = qstr_find_strn(data, len);
2028 if (q != MP_QSTR_NULL) {
2029 // qstr with this data already exists
2030 return MP_OBJ_NEW_QSTR(q);
2031 } else {
2032 // no existing qstr, don't make one
2033 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
2034 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002035 }
Damien George5fa93b62014-01-22 14:35:10 +00002036}
2037
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03002038mp_obj_t mp_obj_str_intern(mp_obj_t str) {
2039 GET_STR_DATA_LEN(str, data, len);
2040 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
2041}
2042
Damien Georgec0d95002017-02-16 16:26:48 +11002043mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01002044 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002045}
2046
Damien George5fa93b62014-01-22 14:35:10 +00002047bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
2048 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
2049 return s1 == s2;
2050 } else {
2051 GET_STR_HASH(s1, h1);
2052 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03002053 // If any of hashes is 0, it means it's not valid
2054 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00002055 return false;
2056 }
2057 GET_STR_DATA_LEN(s1, d1, l1);
2058 GET_STR_DATA_LEN(s2, d2, l2);
2059 if (l1 != l2) {
2060 return false;
2061 }
Damien George1e708fe2014-01-23 18:27:51 +00002062 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002063 }
Damien George5fa93b62014-01-22 14:35:10 +00002064}
2065
Damien Georgedeed0872014-04-06 11:11:15 +01002066STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002067 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
Paul Sokolovsky9e1b61d2016-08-12 21:26:12 +03002068 mp_raise_TypeError("can't convert to str implicitly");
Damien George1e9a92f2014-11-06 17:36:16 +00002069 } else {
2070 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
2071 "can't convert '%s' object to str implicitly",
2072 mp_obj_get_type_str(self_in)));
2073 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002074}
2075
Damien Georgeb829b5c2014-01-25 13:51:19 +00002076// use this if you will anyway convert the string to a qstr
2077// will be more efficient for the case where it's already a qstr
2078qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2079 if (MP_OBJ_IS_QSTR(self_in)) {
2080 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002081 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002082 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002083 return qstr_from_strn((char*)self->data, self->len);
2084 } else {
2085 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002086 }
2087}
2088
2089// only use this function if you need the str data to be zero terminated
2090// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2091const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002092 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002093 GET_STR_DATA_LEN(self_in, s, l);
2094 (void)l; // len unused
2095 return (const char*)s;
2096 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002097 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002098 }
2099}
2100
Damien Georged182b982014-08-30 14:19:41 +01002101const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002102 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002103 GET_STR_DATA_LEN(self_in, s, l);
2104 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002105 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002106 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002107 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002108 }
Damiend99b0522013-12-21 18:17:45 +00002109}
xyb8cfc9f02014-01-05 18:47:51 +08002110
Damien George04353cc2015-10-18 23:09:04 +01002111#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
Damien Georgec3f64d92015-11-27 12:23:18 +00002112const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien George04353cc2015-10-18 23:09:04 +01002113 if (MP_OBJ_IS_QSTR(self_in)) {
2114 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2115 } else {
2116 *len = ((mp_obj_str_t*)self_in)->len;
2117 return ((mp_obj_str_t*)self_in)->data;
2118 }
2119}
2120#endif
2121
xyb8cfc9f02014-01-05 18:47:51 +08002122/******************************************************************************/
2123/* str iterator */
2124
Damien George44e7cbf2015-05-17 16:44:24 +01002125typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002126 mp_obj_base_t base;
Damien George8212d972016-01-03 16:27:55 +00002127 mp_fun_1_t iternext;
Damien George5fa93b62014-01-22 14:35:10 +00002128 mp_obj_t str;
Damien Georgec0d95002017-02-16 16:26:48 +11002129 size_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002130} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002131
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002132#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002133STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002134 mp_obj_str8_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002135 GET_STR_DATA_LEN(self->str, str, len);
2136 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002137 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002138 self->cur += 1;
2139 return o_out;
2140 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002141 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002142 }
2143}
2144
Damien George44e7cbf2015-05-17 16:44:24 +01002145STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2146 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George8212d972016-01-03 16:27:55 +00002147 o->base.type = &mp_type_polymorph_iter;
2148 o->iternext = str_it_iternext;
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002149 o->str = str;
2150 o->cur = 0;
2151 return o;
2152}
2153#endif
2154
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002155STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002156 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002157 GET_STR_DATA_LEN(self->str, str, len);
2158 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002159 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002160 self->cur += 1;
2161 return o_out;
2162 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002163 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002164 }
2165}
2166
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002167mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
Damien George44e7cbf2015-05-17 16:44:24 +01002168 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George8212d972016-01-03 16:27:55 +00002169 o->base.type = &mp_type_polymorph_iter;
2170 o->iternext = bytes_it_iternext;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002171 o->str = str;
2172 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002173 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002174}