blob: ed850baa7b3a909c7dc34ec59836612249b4fea0 [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 Georgeecc88e92014-08-30 00:35:11 +010039STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_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 George7f9d1d62015-04-09 23:56:15 +010047void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, mp_uint_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 George5b3f0b72016-01-03 15:55:55 +0000161 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 +0200162 o->data = str_data;
163 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000164 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200165 } else {
166 mp_buffer_info_t bufinfo;
167 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
168 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200169 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200170 }
171}
172
Damien George5b3f0b72016-01-03 15:55:55 +0000173STATIC 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 +0000174 (void)type_in;
175
Damien George3a2171e2015-09-04 16:53:46 +0100176 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300177 if (n_kw != 0) {
178 mp_arg_error_unimpl_kw();
179 }
Damien George3a2171e2015-09-04 16:53:46 +0100180 #else
181 (void)n_kw;
182 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300183
Damien George42cec5c2015-09-04 16:51:55 +0100184 if (n_args == 0) {
185 return mp_const_empty_bytes;
186 }
187
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200188 if (MP_OBJ_IS_STR(args[0])) {
189 if (n_args < 2 || n_args > 3) {
190 goto wrong_args;
191 }
192 GET_STR_DATA_LEN(args[0], str_data, str_len);
193 GET_STR_HASH(args[0], str_hash);
Damien George999cedb2015-11-27 17:01:44 +0000194 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 +0200195 o->data = str_data;
196 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000197 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200198 }
199
200 if (n_args > 1) {
201 goto wrong_args;
202 }
203
204 if (MP_OBJ_IS_SMALL_INT(args[0])) {
205 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000206 vstr_t vstr;
207 vstr_init_len(&vstr, len);
208 memset(vstr.buf, 0, len);
209 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200210 }
211
Damien George32ef3a32014-12-04 15:46:14 +0000212 // check if argument has the buffer protocol
213 mp_buffer_info_t bufinfo;
214 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
215 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
216 }
217
Damien George0b9ee862015-01-21 19:14:25 +0000218 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200219 // Try to create array of exact len if initializer len is known
220 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
221 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000222 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200223 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000224 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000225 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200226 }
227
Damien Georged17926d2014-03-30 13:35:08 +0100228 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200229 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100230 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100231 mp_int_t val = mp_obj_get_int(item);
232 #if MICROPY_CPYTHON_COMPAT
233 if (val < 0 || val > 255) {
234 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bytes value out of range"));
235 }
236 #endif
237 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200238 }
239
Damien George0b9ee862015-01-21 19:14:25 +0000240 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200241
242wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000243 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200244}
245
Damien George55baff42014-01-21 21:40:13 +0000246// like strstr but with specified length and allows \0 bytes
247// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100248STATIC const byte *find_subbytes(const byte *haystack, mp_uint_t hlen, const byte *needle, mp_uint_t nlen, mp_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000249 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100250 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700251 if (direction > 0) {
252 str_index = 0;
253 str_index_end = hlen - nlen;
254 } else {
255 str_index = hlen - nlen;
256 str_index_end = 0;
257 }
258 for (;;) {
259 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
260 //found
261 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000262 }
xbe17a5a832014-03-23 23:31:58 -0700263 if (str_index == str_index_end) {
264 //not found
265 break;
Damien George55baff42014-01-21 21:40:13 +0000266 }
xbe17a5a832014-03-23 23:31:58 -0700267 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000268 }
269 }
270 return NULL;
271}
272
Damien Georgea75b02e2014-08-27 09:20:30 +0100273// Note: this function is used to check if an object is a str or bytes, which
274// works because both those types use it as their binary_op method. Revisit
275// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100276mp_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 +0000277 // check for modulo
278 if (op == MP_BINARY_OP_MODULO) {
279 mp_obj_t *args;
280 mp_uint_t n_args;
281 mp_obj_t dict = MP_OBJ_NULL;
282 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
283 // TODO: Support tuple subclasses?
284 mp_obj_tuple_get(rhs_in, &n_args, &args);
285 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
286 args = NULL;
287 n_args = 0;
288 dict = rhs_in;
289 } else {
290 args = &rhs_in;
291 n_args = 1;
292 }
293 return str_modulo_format(lhs_in, n_args, args, dict);
294 }
295
296 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300297 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000298 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
299
300 // check for multiply
301 if (op == MP_BINARY_OP_MULTIPLY) {
302 mp_int_t n;
303 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
304 return MP_OBJ_NULL; // op not supported
305 }
306 if (n <= 0) {
307 if (lhs_type == &mp_type_str) {
308 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
309 } else {
310 return mp_const_empty_bytes;
311 }
312 }
Damien George05005f62015-01-21 22:48:37 +0000313 vstr_t vstr;
314 vstr_init_len(&vstr, lhs_len * n);
315 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
316 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000317 }
318
319 // From now on all operations allow:
320 // - str with str
321 // - bytes with bytes
322 // - bytes with bytearray
323 // - bytes with array.array
324 // To do this efficiently we use the buffer protocol to extract the raw
325 // data for the rhs, but only if the lhs is a bytes object.
326 //
327 // NOTE: CPython does not allow comparison between bytes ard array.array
328 // (even if the array is of type 'b'), even though it allows addition of
329 // such types. We are not compatible with this (we do allow comparison
330 // of bytes with anything that has the buffer protocol). It would be
331 // easy to "fix" this with a bit of extra logic below, but it costs code
332 // size and execution time so we don't.
333
334 const byte *rhs_data;
335 mp_uint_t rhs_len;
336 if (lhs_type == mp_obj_get_type(rhs_in)) {
337 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
338 rhs_data = rhs_data_;
339 rhs_len = rhs_len_;
340 } else if (lhs_type == &mp_type_bytes) {
341 mp_buffer_info_t bufinfo;
342 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000343 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000344 }
345 rhs_data = bufinfo.buf;
346 rhs_len = bufinfo.len;
347 } else {
348 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000349 return MP_OBJ_NULL; // op not supported
350 }
351
Damiend99b0522013-12-21 18:17:45 +0000352 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100353 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000354 case MP_BINARY_OP_INPLACE_ADD: {
Damien George05005f62015-01-21 22:48:37 +0000355 vstr_t vstr;
356 vstr_init_len(&vstr, lhs_len + rhs_len);
357 memcpy(vstr.buf, lhs_data, lhs_len);
358 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
359 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200360 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200361
Damien Georgea65c03c2014-11-05 16:30:34 +0000362 case MP_BINARY_OP_IN:
363 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300364 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300365
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300366 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
367 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 +0100368 case MP_BINARY_OP_LESS:
369 case MP_BINARY_OP_LESS_EQUAL:
370 case MP_BINARY_OP_MORE:
371 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300372 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000373 }
374
Damien George6ac5dce2014-05-21 19:42:43 +0100375 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000376}
377
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300378#if !MICROPY_PY_BUILTINS_STR_UNICODE
379// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000380const 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 +0300381 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100382 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300383 return self_data + index_val;
384}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300385#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300386
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300387// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
388STATIC 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 +0300389 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100390 GET_STR_DATA_LEN(self_in, self_data, self_len);
391 if (value == MP_OBJ_SENTINEL) {
392 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100393#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100394 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300395 mp_bound_slice_t slice;
396 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Damien George821b7f22015-09-03 23:14:06 +0100397 mp_not_implemented("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100398 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100399 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100400 }
401#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300402 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100403 // If we have unicode enabled the type will always be bytes, so take the short cut.
404 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300405 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100406 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300407 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100408 }
409 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100410 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100411 }
412}
413
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200414STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700415 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300416 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000417
Damien Georgefe8fb912014-01-02 16:36:09 +0000418 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000419 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000420
421 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100422 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000423 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000424 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000425 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000426 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100427 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
428 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300429 // TODO: Try to optimize?
Damien George5b3f0b72016-01-03 15:55:55 +0000430 arg = mp_type_list.make_new(&mp_type_list, 1, 0, &arg);
Damien Georgea157e4c2014-04-09 19:17:53 +0100431 }
432 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000433 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000434
435 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100436 mp_uint_t required_len = 0;
437 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300438 if (mp_obj_get_type(seq_items[i]) != self_type) {
439 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
440 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000441 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000442 if (i > 0) {
443 required_len += sep_len;
444 }
Damien George5fa93b62014-01-22 14:35:10 +0000445 GET_STR_LEN(seq_items[i], l);
446 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000447 }
448
449 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000450 vstr_t vstr;
451 vstr_init_len(&vstr, required_len);
452 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +0100453 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000454 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000455 memcpy(data, sep_str, sep_len);
456 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000457 }
Damien George5fa93b62014-01-22 14:35:10 +0000458 GET_STR_DATA_LEN(seq_items[i], s, l);
459 memcpy(data, s, l);
460 data += l;
Damiend99b0522013-12-21 18:17:45 +0000461 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000462
463 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000464 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000465}
466
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300467enum {SPLIT = 0, KEEP = 1, SPLITLINES = 2};
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200468
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300469STATIC inline mp_obj_t str_split_internal(mp_uint_t n_args, const mp_obj_t *args, int type) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300470 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100471 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200472 mp_obj_t sep = mp_const_none;
473 if (n_args > 1) {
474 sep = args[1];
475 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100476 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200477 }
478 }
Damien Georgedeed0872014-04-06 11:11:15 +0100479
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200480 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000481 GET_STR_DATA_LEN(args[0], s, len);
482 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200483
Damien Georgedeed0872014-04-06 11:11:15 +0100484 if (sep == mp_const_none) {
485 // sep not given, so separate on whitespace
486
487 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300488 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100489 while (s < top && splits != 0) {
490 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300491 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100492 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100493 if (s >= top) {
494 break;
495 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300496 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100497 if (splits > 0) {
498 splits--;
499 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200500 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200501
Damien Georgedeed0872014-04-06 11:11:15 +0100502 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100503 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100504 }
505
506 } else {
507 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300508 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000509 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300510 }
Damien Georgedeed0872014-04-06 11:11:15 +0100511
Damien Georged182b982014-08-30 14:19:41 +0100512 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100513 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
514
515 if (sep_len == 0) {
516 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
517 }
518
519 for (;;) {
520 const byte *start = s;
521 for (;;) {
522 if (splits == 0 || s + sep_len > top) {
523 s = top;
524 break;
525 } else if (memcmp(s, sep_str, sep_len) == 0) {
526 break;
527 }
528 s++;
529 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300530 mp_uint_t sub_len = s - start;
Paul Sokolovsky7f59b4b2015-04-04 01:55:40 +0300531 if (MP_LIKELY(!(sub_len == 0 && s == top && (type && SPLITLINES)))) {
532 if (start + sub_len != top && (type & KEEP)) {
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300533 sub_len++;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300534 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300535 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300536 }
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
Damien George4b72b3a2016-01-03 14:21:40 +0000550mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300551 return str_split_internal(n_args, args, SPLIT);
552}
553
554#if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien George4b72b3a2016-01-03 14:21:40 +0000555STATIC mp_obj_t str_splitlines(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300556 static const mp_arg_t allowed_args[] = {
557 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
558 };
559
560 // parse args
Damien George22d85ec2016-01-13 15:47:56 +0000561 struct {
562 mp_arg_val_t keepends;
563 } args;
564 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args,
565 MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300566
567 mp_obj_t new_args[2] = {pos_args[0], MP_OBJ_NEW_QSTR(MP_QSTR__backslash_n)};
Damien George22d85ec2016-01-13 15:47:56 +0000568 return str_split_internal(2, new_args, SPLITLINES | (args.keepends.u_bool ? KEEP : 0));
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300569}
570#endif
571
Damien George4b72b3a2016-01-03 14:21:40 +0000572STATIC mp_obj_t str_rsplit(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300573 if (n_args < 3) {
574 // If we don't have split limit, it doesn't matter from which side
575 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200576 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300577 }
578 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
579 mp_obj_t sep = args[1];
580 GET_STR_DATA_LEN(args[0], s, len);
581
Damien George40f3c022014-07-03 13:25:24 +0100582 mp_int_t splits = mp_obj_get_int(args[2]);
583 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300584 // Preallocate list to the max expected # of elements, as we
585 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000586 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100587 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300588
589 if (sep == mp_const_none) {
Damien George22602cc2015-09-01 15:35:31 +0100590 mp_not_implemented("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300591 } else {
Damien Georged182b982014-08-30 14:19:41 +0100592 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300593 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
594
595 if (sep_len == 0) {
596 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
597 }
598
599 const byte *beg = s;
600 const byte *last = s + len;
601 for (;;) {
602 s = last - sep_len;
603 for (;;) {
604 if (splits == 0 || s < beg) {
605 break;
606 } else if (memcmp(s, sep_str, sep_len) == 0) {
607 break;
608 }
609 s--;
610 }
611 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100612 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300613 break;
614 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100615 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 +0300616 last = s;
617 if (splits > 0) {
618 splits--;
619 }
620 }
621 if (idx != 0) {
622 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100623 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100624 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300625 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
626 res->len = used;
627 }
628 }
629
Damien George999cedb2015-11-27 17:01:44 +0000630 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300631}
632
Damien Georgeecc88e92014-08-30 00:35:11 +0100633STATIC mp_obj_t str_finder(mp_uint_t n_args, const mp_obj_t *args, mp_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300634 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000635 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000636 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
637
638 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000639 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000640 bad_implicit_conversion(args[1]);
641 }
John R. Lentone8204912014-01-12 21:53:52 +0000642
Damien George5fa93b62014-01-22 14:35:10 +0000643 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
644 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000645
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300646 const byte *start = haystack;
647 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000648 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300649 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000650 }
651 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300652 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000653 }
654
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300655 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000656 if (p == NULL) {
657 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700658 if (is_index) {
659 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
660 } else {
661 return MP_OBJ_NEW_SMALL_INT(-1);
662 }
Damien George23005372014-01-13 19:39:01 +0000663 } else {
664 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300665 #if MICROPY_PY_BUILTINS_STR_UNICODE
666 if (self_type == &mp_type_str) {
667 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
668 }
669 #endif
xbe17a5a832014-03-23 23:31:58 -0700670 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000671 }
John R. Lentone8204912014-01-12 21:53:52 +0000672}
673
Damien George4b72b3a2016-01-03 14:21:40 +0000674STATIC mp_obj_t str_find(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700675 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700676}
677
Damien George4b72b3a2016-01-03 14:21:40 +0000678STATIC mp_obj_t str_rfind(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700679 return str_finder(n_args, args, -1, false);
680}
681
Damien George4b72b3a2016-01-03 14:21:40 +0000682STATIC mp_obj_t str_index(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700683 return str_finder(n_args, args, 1, true);
684}
685
Damien George4b72b3a2016-01-03 14:21:40 +0000686STATIC mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700687 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700688}
689
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200690// TODO: (Much) more variety in args
Damien George4b72b3a2016-01-03 14:21:40 +0000691STATIC mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300692 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300693 GET_STR_DATA_LEN(args[0], str, str_len);
694 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300695 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300696 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300697 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300698 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300699 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200700 return mp_const_false;
701 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300702 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200703}
704
Damien George4b72b3a2016-01-03 14:21:40 +0000705STATIC mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300706 GET_STR_DATA_LEN(args[0], str, str_len);
707 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100708 if (n_args > 2) {
709 mp_not_implemented("start/end indices");
710 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300711
712 if (suffix_len > str_len) {
713 return mp_const_false;
714 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300715 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300716}
717
Paul Sokolovsky88107842014-04-26 06:20:08 +0300718enum { LSTRIP, RSTRIP, STRIP };
719
Damien Georgeecc88e92014-08-30 00:35:11 +0100720STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800721 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700722 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300723 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000724
725 const byte *chars_to_del;
726 uint chars_to_del_len;
727 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800728
729 if (n_args == 1) {
730 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000731 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800732 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300733 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000734 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300735 }
Damien George5fa93b62014-01-22 14:35:10 +0000736 GET_STR_DATA_LEN(args[1], s, l);
737 chars_to_del = s;
738 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800739 }
740
Damien George5fa93b62014-01-22 14:35:10 +0000741 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800742
Damien George40f3c022014-07-03 13:25:24 +0100743 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800744 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100745 mp_uint_t last_good_char_pos = 0;
746 mp_uint_t i = 0;
747 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300748 if (type == RSTRIP) {
749 i = orig_str_len - 1;
750 delta = -1;
751 }
Damien George40f3c022014-07-03 13:25:24 +0100752 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700753 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800754 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300755 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800756 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300757 if (type == LSTRIP) {
758 last_good_char_pos = orig_str_len - 1;
759 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300760 } else if (type == RSTRIP) {
761 first_good_char_pos = 0;
762 last_good_char_pos = i;
763 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300764 }
xbe7b0f39f2014-01-08 14:23:45 -0800765 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300766 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800767 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300768 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800769 }
770
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300771 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000772 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000773 if (self_type == &mp_type_str) {
774 return MP_OBJ_NEW_QSTR(MP_QSTR_);
775 } else {
776 return mp_const_empty_bytes;
777 }
xbe7b0f39f2014-01-08 14:23:45 -0800778 }
779
780 assert(last_good_char_pos >= first_good_char_pos);
781 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100782 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300783 if (stripped_len == orig_str_len) {
784 // If nothing was stripped, don't bother to dup original string
785 // TODO: watch out for this case when we'll get to bytearray.strip()
786 assert(first_good_char_pos == 0);
787 return args[0];
788 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100789 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800790}
791
Damien George4b72b3a2016-01-03 14:21:40 +0000792STATIC mp_obj_t str_strip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300793 return str_uni_strip(STRIP, n_args, args);
794}
795
Damien George4b72b3a2016-01-03 14:21:40 +0000796STATIC mp_obj_t str_lstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300797 return str_uni_strip(LSTRIP, n_args, args);
798}
799
Damien George4b72b3a2016-01-03 14:21:40 +0000800STATIC mp_obj_t str_rstrip(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300801 return str_uni_strip(RSTRIP, n_args, args);
802}
803
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700804// Takes an int arg, but only parses unsigned numbers, and only changes
805// *num if at least one digit was parsed.
Damien George87e07ea2016-02-02 15:51:57 +0000806STATIC const char *str_to_int(const char *str, const char *top, int *num) {
807 if (str < top && '0' <= *str && *str <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700808 *num = 0;
809 do {
Damien George87e07ea2016-02-02 15:51:57 +0000810 *num = *num * 10 + (*str - '0');
811 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700812 }
Damien George87e07ea2016-02-02 15:51:57 +0000813 while (str < top && '0' <= *str && *str <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700814 }
Damien George87e07ea2016-02-02 15:51:57 +0000815 return str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700816}
817
Damien George2801e6f2015-04-04 15:53:11 +0100818STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700819 return ch && strchr("<>=^", ch) != NULL;
820}
821
Damien George2801e6f2015-04-04 15:53:11 +0100822STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700823 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
824}
825
Damien George2801e6f2015-04-04 15:53:11 +0100826STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700827 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
828}
829
Damien George2801e6f2015-04-04 15:53:11 +0100830STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700831 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100832#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100833 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700834#endif
835 ;
836}
837
Damien George2801e6f2015-04-04 15:53:11 +0100838STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100839#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100840 if (mp_obj_is_float(arg)) {
841 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700842 }
843#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700844 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700845}
846
Damien George1e9a92f2014-11-06 17:36:16 +0000847STATIC NORETURN void terse_str_format_value_error(void) {
848 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
849}
850
pohmeliee3a29de2016-01-29 12:09:10 +0300851vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Damien George0b9ee862015-01-21 19:14:25 +0000852 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100853 mp_print_t print;
854 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700855
pohmeliee3a29de2016-01-29 12:09:10 +0300856 for (; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000858 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700859 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100860 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700861 continue;
862 }
Damien George1e9a92f2014-11-06 17:36:16 +0000863 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
864 terse_str_format_value_error();
865 } else {
866 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
867 "single '}' encountered in format string"));
868 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700869 }
870 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100871 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872 continue;
873 }
874
875 str++;
876 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100877 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700878 continue;
879 }
880
881 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
882
Damien George87e07ea2016-02-02 15:51:57 +0000883 const char *field_name = NULL;
884 const char *field_name_top = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700885 char conversion = '\0';
pohmeliee3a29de2016-01-29 12:09:10 +0300886 const char *format_spec = NULL;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700887
888 if (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000889 field_name = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700890 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George87e07ea2016-02-02 15:51:57 +0000891 ++str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700892 }
Damien George87e07ea2016-02-02 15:51:57 +0000893 field_name_top = (const char *)str;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700894 }
895
896 // conversion ::= "r" | "s"
897
898 if (str < top && *str == '!') {
899 str++;
900 if (str < top && (*str == 'r' || *str == 's')) {
901 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200902 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000903 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
904 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100905 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000906 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
Damien George000730e2015-08-30 12:43:21 +0100907 "bad conversion specifier"));
908 } else {
909 if (str >= top) {
910 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
911 "end of format while looking for conversion specifier"));
912 } else {
913 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
914 "unknown conversion specifier %c", *str));
915 }
Damien George1e9a92f2014-11-06 17:36:16 +0000916 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700917 }
918 }
919
920 if (str < top && *str == ':') {
921 str++;
922 // {:} is the same as {}, which is the same as {!s}
923 // This makes a difference when passing in a True or False
924 // '{}'.format(True) returns 'True'
925 // '{:d}'.format(True) returns '1'
926 // So we treat {:} as {} and this later gets treated to be {!s}
927 if (*str != '}') {
pohmeliee3a29de2016-01-29 12:09:10 +0300928 format_spec = str;
929 for (int nest = 1; str < top;) {
930 if (*str == '{') {
931 ++nest;
932 } else if (*str == '}') {
933 if (--nest == 0) {
934 break;
935 }
936 }
937 ++str;
Damiend99b0522013-12-21 18:17:45 +0000938 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700939 }
940 }
941 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000942 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
943 terse_str_format_value_error();
944 } else {
945 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
946 "unmatched '{' in format"));
947 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700948 }
949 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000950 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
951 terse_str_format_value_error();
952 } else {
953 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
954 "expected ':' after format specifier"));
955 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700956 }
957
958 mp_obj_t arg = mp_const_none;
959
960 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100961 int index = 0;
Damien George87e07ea2016-02-02 15:51:57 +0000962 if (MP_LIKELY(unichar_isdigit(*field_name))) {
pohmeliee3a29de2016-01-29 12:09:10 +0300963 if (*arg_i > 0) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200964 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
965 terse_str_format_value_error();
966 } else {
967 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
968 "can't switch from automatic field numbering to manual field specification"));
969 }
970 }
Damien George87e07ea2016-02-02 15:51:57 +0000971 field_name = str_to_int(field_name, field_name_top, &index);
Damien George963a5a32015-01-16 17:47:07 +0000972 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200973 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
974 }
975 arg = args[index + 1];
pohmeliee3a29de2016-01-29 12:09:10 +0300976 *arg_i = -1;
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200977 } else {
Damien George87e07ea2016-02-02 15:51:57 +0000978 const char *lookup;
979 for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++);
980 mp_obj_t field_q = mp_obj_new_str(field_name, lookup - field_name, true/*?*/);
981 field_name = lookup;
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200982 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
983 if (key_elem == NULL) {
984 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
985 }
986 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700987 }
Damien George87e07ea2016-02-02 15:51:57 +0000988 if (field_name < field_name_top) {
Damien George821b7f22015-09-03 23:14:06 +0100989 mp_not_implemented("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700990 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700991 } else {
pohmeliee3a29de2016-01-29 12:09:10 +0300992 if (*arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000993 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
994 terse_str_format_value_error();
995 } else {
996 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
997 "can't switch from manual field specification to automatic field numbering"));
998 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700999 }
pohmeliee3a29de2016-01-29 12:09:10 +03001000 if ((uint)*arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001001 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001002 }
pohmeliee3a29de2016-01-29 12:09:10 +03001003 arg = args[(*arg_i) + 1];
1004 (*arg_i)++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001005 }
1006 if (!format_spec && !conversion) {
1007 conversion = 's';
1008 }
1009 if (conversion) {
1010 mp_print_kind_t print_kind;
1011 if (conversion == 's') {
1012 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001013 } else {
Damien George000730e2015-08-30 12:43:21 +01001014 assert(conversion == 'r');
1015 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001016 }
Damien George0b9ee862015-01-21 19:14:25 +00001017 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001018 mp_print_t arg_print;
1019 vstr_init_print(&arg_vstr, 16, &arg_print);
1020 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001021 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001022 }
1023
1024 char sign = '\0';
1025 char fill = '\0';
1026 char align = '\0';
1027 int width = -1;
1028 int precision = -1;
1029 char type = '\0';
1030 int flags = 0;
1031
1032 if (format_spec) {
1033 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1034 //
1035 // [[fill]align][sign][#][0][width][,][.precision][type]
1036 // fill ::= <any character>
1037 // align ::= "<" | ">" | "=" | "^"
1038 // sign ::= "+" | "-" | " "
1039 // width ::= integer
1040 // precision ::= integer
1041 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1042
pohmeliee3a29de2016-01-29 12:09:10 +03001043 // recursively call the formatter to format any nested specifiers
1044 MP_STACK_CHECK();
1045 vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs);
1046 const char *s = vstr_null_terminated_str(&format_spec_vstr);
Damien George87e07ea2016-02-02 15:51:57 +00001047 const char *stop = s + format_spec_vstr.len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001048 if (isalignment(*s)) {
1049 align = *s++;
1050 } else if (*s && isalignment(s[1])) {
1051 fill = *s++;
1052 align = *s++;
1053 }
1054 if (*s == '+' || *s == '-' || *s == ' ') {
1055 if (*s == '+') {
1056 flags |= PF_FLAG_SHOW_SIGN;
1057 } else if (*s == ' ') {
1058 flags |= PF_FLAG_SPACE_SIGN;
1059 }
1060 sign = *s++;
1061 }
1062 if (*s == '#') {
1063 flags |= PF_FLAG_SHOW_PREFIX;
1064 s++;
1065 }
1066 if (*s == '0') {
1067 if (!align) {
1068 align = '=';
1069 }
1070 if (!fill) {
1071 fill = '0';
1072 }
1073 }
Damien George87e07ea2016-02-02 15:51:57 +00001074 s = str_to_int(s, stop, &width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001075 if (*s == ',') {
1076 flags |= PF_FLAG_SHOW_COMMA;
1077 s++;
1078 }
1079 if (*s == '.') {
1080 s++;
Damien George87e07ea2016-02-02 15:51:57 +00001081 s = str_to_int(s, stop, &precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001082 }
1083 if (istype(*s)) {
1084 type = *s++;
1085 }
1086 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001087 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1088 terse_str_format_value_error();
1089 } else {
1090 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1091 "invalid format specifier"));
1092 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001093 }
pohmeliee3a29de2016-01-29 12:09:10 +03001094 vstr_clear(&format_spec_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001095 }
1096 if (!align) {
1097 if (arg_looks_numeric(arg)) {
1098 align = '>';
1099 } else {
1100 align = '<';
1101 }
1102 }
1103 if (!fill) {
1104 fill = ' ';
1105 }
1106
1107 if (sign) {
1108 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001109 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1110 terse_str_format_value_error();
1111 } else {
1112 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1113 "sign not allowed in string format specifier"));
1114 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001115 }
1116 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001117 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1118 terse_str_format_value_error();
1119 } else {
1120 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1121 "sign not allowed with integer format specifier 'c'"));
1122 }
Damiend99b0522013-12-21 18:17:45 +00001123 }
1124 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001125 sign = '-';
1126 }
1127
1128 switch (align) {
1129 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1130 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1131 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1132 }
1133
1134 if (arg_looks_integer(arg)) {
1135 switch (type) {
1136 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001137 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001138 continue;
1139
1140 case 'c':
1141 {
1142 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001143 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001144 continue;
1145 }
1146
1147 case '\0': // No explicit format type implies 'd'
1148 case 'n': // I don't think we support locales in uPy so use 'd'
1149 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001150 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001151 continue;
1152
1153 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001154 if (flags & PF_FLAG_SHOW_PREFIX) {
1155 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1156 }
1157
Damien George7f9d1d62015-04-09 23:56:15 +01001158 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001159 continue;
1160
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001161 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001162 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001163 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001164 continue;
1165
1166 case 'e':
1167 case 'E':
1168 case 'f':
1169 case 'F':
1170 case 'g':
1171 case 'G':
1172 case '%':
1173 // The floating point formatters all work with anything that
1174 // looks like an integer
1175 break;
1176
1177 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001178 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1179 terse_str_format_value_error();
1180 } else {
1181 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1182 "unknown format code '%c' for object of type '%s'",
1183 type, mp_obj_get_type_str(arg)));
1184 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001185 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001186 }
Damien George70f33cd2014-04-02 17:06:05 +01001187
Dave Hylands22fe4d72014-04-02 12:07:31 -07001188 // NOTE: no else here. We need the e, f, g etc formats for integer
1189 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001190 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001191 if (!type) {
1192
1193 // Even though the docs say that an unspecified type is the same
1194 // as 'g', there is one subtle difference, when the exponent
1195 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001196 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001197 // '{:10.1}'.format(0.0) ==> '0e+00'
1198 // '{:10.1g}'.format(0.0) ==> '0'
1199 //
1200 // TODO: Figure out how to deal with this.
1201 //
1202 // A proper solution would involve adding a special flag
1203 // or something to format_float, and create a format_double
1204 // to deal with doubles. In order to fix this when using
1205 // sprintf, we'd need to use the e format and tweak the
1206 // returned result to strip trailing zeros like the g format
1207 // does.
1208 //
1209 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1210 // but with 1.e2 you get 1e+02 and 1.00e+02
1211 //
1212 // Stripping the trailing 0's (like g) does would make the
1213 // e format give us the right format.
1214 //
1215 // CPython sources say:
1216 // Omitted type specifier. Behaves in the same way as repr(x)
1217 // and str(x) if no precision is given, else like 'g', but with
1218 // at least one digit after the decimal point. */
1219
1220 type = 'g';
1221 }
1222 if (type == 'n') {
1223 type = 'g';
1224 }
1225
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001226 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001227#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001228 case 'e':
1229 case 'E':
1230 case 'f':
1231 case 'F':
1232 case 'g':
1233 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001234 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001235 break;
1236
1237 case '%':
1238 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001239 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1240 #define F100 100.0F
1241 #else
1242 #define F100 100.0
1243 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001244 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001245 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001246 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001247#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001248
1249 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001250 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1251 terse_str_format_value_error();
1252 } else {
1253 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1254 "unknown format code '%c' for object of type 'float'",
1255 type, mp_obj_get_type_str(arg)));
1256 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001257 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001258 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001259 // arg doesn't look like a number
1260
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001261 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001262 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1263 terse_str_format_value_error();
1264 } else {
1265 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1266 "'=' alignment not allowed in string format specifier"));
1267 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001268 }
Damien George70f33cd2014-04-02 17:06:05 +01001269
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001270 switch (type) {
Damien Georged4df8f42016-01-04 13:13:39 +00001271 case '\0': // no explicit format type implies 's'
Damien Georged182b982014-08-30 14:19:41 +01001272 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001273 mp_uint_t slen;
1274 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001275 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001276 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001277 }
Damien George50912e72015-01-20 11:55:10 +00001278 if (slen > (mp_uint_t)precision) {
1279 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001280 }
Damien George7f9d1d62015-04-09 23:56:15 +01001281 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001282 break;
1283 }
1284
1285 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001286 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1287 terse_str_format_value_error();
1288 } else {
1289 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1290 "unknown format code '%c' for object of type 'str'",
1291 type, mp_obj_get_type_str(arg)));
1292 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001293 }
Damiend99b0522013-12-21 18:17:45 +00001294 }
1295 }
1296
pohmeliee3a29de2016-01-29 12:09:10 +03001297 return vstr;
1298}
1299
1300mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
1301 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1302
1303 GET_STR_DATA_LEN(args[0], str, len);
1304 int arg_i = 0;
1305 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 +00001306 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001307}
1308
Damien Georgeecc88e92014-08-30 00:35:11 +01001309STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001310 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001311
1312 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001313 const byte *start_str = str;
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001314 bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001315 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001316 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001317 mp_print_t print;
1318 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001319
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001320 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001321 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001322 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001323 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001324 continue;
1325 }
1326 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001327 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001328 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001329 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001330 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001331 continue;
1332 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001333
1334 // Dictionary value lookup
1335 if (*str == '(') {
1336 const byte *key = ++str;
1337 while (*str != ')') {
1338 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001339 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1340 terse_str_format_value_error();
1341 } else {
1342 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1343 "incomplete format key"));
1344 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001345 }
1346 ++str;
1347 }
1348 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1349 arg = mp_obj_dict_get(dict, k_obj);
1350 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001351 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001352
Dave Hylands6756a372014-04-02 11:42:39 -07001353 int flags = 0;
1354 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001355 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001356 while (str < top) {
1357 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1358 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1359 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001360 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001361 else if (*str == '0') {
1362 flags |= PF_FLAG_PAD_AFTER_SIGN;
1363 fill = '0';
1364 } else break;
1365 str++;
1366 }
1367 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001368 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001369 if (str < top) {
1370 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001371 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001372 goto not_enough_args;
1373 }
Dave Hylands6756a372014-04-02 11:42:39 -07001374 width = mp_obj_get_int(args[arg_i++]);
1375 str++;
1376 } else {
Damien George87e07ea2016-02-02 15:51:57 +00001377 str = (const byte*)str_to_int((const char*)str, (const char*)top, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001378 }
1379 }
1380 int prec = -1;
1381 if (str < top && *str == '.') {
1382 if (++str < top) {
1383 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001384 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001385 goto not_enough_args;
1386 }
Dave Hylands6756a372014-04-02 11:42:39 -07001387 prec = mp_obj_get_int(args[arg_i++]);
1388 str++;
1389 } else {
1390 prec = 0;
Damien George87e07ea2016-02-02 15:51:57 +00001391 str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001392 }
1393 }
1394 }
1395
1396 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001397incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001398 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1399 terse_str_format_value_error();
1400 } else {
1401 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1402 "incomplete format"));
1403 }
Dave Hylands6756a372014-04-02 11:42:39 -07001404 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001405
1406 // Tuple value lookup
1407 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001408 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001409not_enough_args:
1410 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1411 }
1412 arg = args[arg_i++];
1413 }
Dave Hylands6756a372014-04-02 11:42:39 -07001414 switch (*str) {
1415 case 'c':
1416 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001417 mp_uint_t slen;
1418 const char *s = mp_obj_str_get_data(arg, &slen);
1419 if (slen != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001420 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1421 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001422 }
Damien George7f9d1d62015-04-09 23:56:15 +01001423 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001424 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001425 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001426 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001427 } else {
1428 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1429 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001430 }
Damien George11de8392014-06-05 18:57:38 +01001431 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001432
1433 case 'd':
1434 case 'i':
1435 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001436 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001437 break;
1438
Damien Georgefb510b32014-06-01 13:32:54 +01001439#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001440 case 'e':
1441 case 'E':
1442 case 'f':
1443 case 'F':
1444 case 'g':
1445 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001446 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001447 break;
1448#endif
1449
1450 case 'o':
1451 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001452 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001453 }
Damien George7f9d1d62015-04-09 23:56:15 +01001454 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001455 break;
1456
1457 case 'r':
1458 case 's':
1459 {
Damien George0b9ee862015-01-21 19:14:25 +00001460 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001461 mp_print_t arg_print;
1462 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001463 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1464 if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1465 // If we have something like b"%s" % b"1", bytes arg should be
1466 // printed undecorated.
1467 print_kind = PRINT_RAW;
1468 }
1469 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001470 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001471 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001472 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001473 }
Damien George50912e72015-01-20 11:55:10 +00001474 if (vlen > (uint)prec) {
1475 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001476 }
Damien George7f9d1d62015-04-09 23:56:15 +01001477 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001478 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001479 break;
1480 }
Dave Hylands6756a372014-04-02 11:42:39 -07001481
Dave Hylands6756a372014-04-02 11:42:39 -07001482 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001483 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001484 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001485 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001486
Dave Hylands6756a372014-04-02 11:42:39 -07001487 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001488 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1489 terse_str_format_value_error();
1490 } else {
1491 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1492 "unsupported format character '%c' (0x%x) at index %d",
1493 *str, *str, str - start_str));
1494 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001495 }
1496 }
1497
Damien George963a5a32015-01-16 17:47:07 +00001498 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001499 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001500 }
1501
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001502 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001503}
1504
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001505// The implementation is optimized, returning the original string if there's
1506// nothing to replace.
Damien George4b72b3a2016-01-03 14:21:40 +00001507STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001508 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001509
Damien George40f3c022014-07-03 13:25:24 +01001510 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001511 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001512 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001513 if (max_rep == 0) {
1514 return args[0];
1515 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001516 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001517 }
xbe480c15a2014-01-30 22:17:30 -08001518 }
Damien George94f68302014-01-31 23:45:12 +00001519
xbe729be9b2014-04-07 14:46:39 -07001520 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001521
Damien Georgeff715422014-04-07 00:39:13 +01001522 // check argument types
1523
Damien Georgec55a4d82014-12-24 20:28:30 +00001524 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1525
1526 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001527 bad_implicit_conversion(args[1]);
1528 }
1529
Damien Georgec55a4d82014-12-24 20:28:30 +00001530 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001531 bad_implicit_conversion(args[2]);
1532 }
1533
1534 // extract string data
1535
xbe480c15a2014-01-30 22:17:30 -08001536 GET_STR_DATA_LEN(args[0], str, str_len);
1537 GET_STR_DATA_LEN(args[1], old, old_len);
1538 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001539
1540 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001541 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001542 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001543 }
1544
Damien George94f68302014-01-31 23:45:12 +00001545 // data for the replaced string
1546 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001547 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001548
Damien George94f68302014-01-31 23:45:12 +00001549 // do 2 passes over the string:
1550 // first pass computes the required length of the replaced string
1551 // second pass does the replacements
1552 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001553 mp_uint_t replaced_str_index = 0;
1554 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001555 const byte *old_occurrence;
1556 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001557 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001558 if (old_len == 0) {
1559 // if old_str is empty, copy new_str to start of replaced string
1560 // copy the replacement string
1561 if (data != NULL) {
1562 memcpy(data, new, new_len);
1563 }
1564 replaced_str_index += new_len;
1565 num_replacements_done++;
1566 }
Damien George963a5a32015-01-16 17:47:07 +00001567 while (num_replacements_done != (mp_uint_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 +01001568 if (old_len == 0) {
1569 old_occurrence += 1;
1570 }
Damien George94f68302014-01-31 23:45:12 +00001571 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1572 if (data != NULL) {
1573 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1574 }
1575 replaced_str_index += old_occurrence - offset_ptr;
1576 // copy the replacement string
1577 if (data != NULL) {
1578 memcpy(data + replaced_str_index, new, new_len);
1579 }
1580 replaced_str_index += new_len;
1581 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001582 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001583 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001584 }
1585
1586 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1587 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001588 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001589 }
Damien Georgeff715422014-04-07 00:39:13 +01001590 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001591
1592 if (data == NULL) {
1593 // first pass
1594 if (num_replacements_done == 0) {
1595 // no substr found, return original string
1596 return args[0];
1597 } else {
1598 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001599 vstr_init_len(&vstr, replaced_str_index);
1600 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001601 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001602 }
1603 } else {
1604 // second pass, we are done
1605 break;
1606 }
xbe480c15a2014-01-30 22:17:30 -08001607 }
Damien George94f68302014-01-31 23:45:12 +00001608
Damien George05005f62015-01-21 22:48:37 +00001609 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001610}
1611
Damien George4b72b3a2016-01-03 14:21:40 +00001612STATIC mp_obj_t str_count(size_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001613 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001614 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001615 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1616
1617 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001618 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001619 bad_implicit_conversion(args[1]);
1620 }
xbe9e1e8cd2014-03-12 22:57:16 -07001621
1622 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1623 GET_STR_DATA_LEN(args[1], needle, needle_len);
1624
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001625 const byte *start = haystack;
1626 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001627 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001628 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001629 }
1630 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001631 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001632 }
1633
Damien George536dde22014-03-13 22:07:55 +00001634 // if needle_len is zero then we count each gap between characters as an occurrence
1635 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001636 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001637 }
1638
Damien George536dde22014-03-13 22:07:55 +00001639 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001640 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001641 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1642 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001643 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001644 haystack_ptr += needle_len;
1645 } else {
1646 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001647 }
xbe9e1e8cd2014-03-12 22:57:16 -07001648 }
1649
1650 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1651}
1652
Damien George40f3c022014-07-03 13:25:24 +01001653STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001654 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001655 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1656 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001657 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001658 }
Damien Georgeb035db32014-03-21 20:39:40 +00001659
xbe613a8e32014-03-18 00:06:29 -07001660 GET_STR_DATA_LEN(self_in, str, str_len);
1661 GET_STR_DATA_LEN(arg, sep, sep_len);
1662
1663 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001664 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001665 }
Damien Georgeb035db32014-03-21 20:39:40 +00001666
Damien Georgec55a4d82014-12-24 20:28:30 +00001667 mp_obj_t result[3];
1668 if (self_type == &mp_type_str) {
1669 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1670 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1671 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1672 } else {
1673 result[0] = mp_const_empty_bytes;
1674 result[1] = mp_const_empty_bytes;
1675 result[2] = mp_const_empty_bytes;
1676 }
Damien Georgeb035db32014-03-21 20:39:40 +00001677
1678 if (direction > 0) {
1679 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001680 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001681 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001682 }
xbe613a8e32014-03-18 00:06:29 -07001683
xbe17a5a832014-03-23 23:31:58 -07001684 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1685 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001686 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001687 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001688 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001689 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 -07001690 }
Damien Georgeb035db32014-03-21 20:39:40 +00001691
xbe0a6894c2014-03-21 01:12:26 -07001692 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001693}
1694
Damien Georgeb035db32014-03-21 20:39:40 +00001695STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1696 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001697}
xbe4504ea82014-03-19 00:46:14 -07001698
Damien Georgeb035db32014-03-21 20:39:40 +00001699STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1700 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001701}
1702
Paul Sokolovsky69135212014-05-10 19:47:41 +03001703// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001704STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001705 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001706 vstr_t vstr;
1707 vstr_init_len(&vstr, self_len);
1708 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +01001709 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001710 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001711 }
Damien George05005f62015-01-21 22:48:37 +00001712 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001713}
1714
1715STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001716 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001717}
1718
1719STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001720 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001721}
1722
Damien Georgefcc9cf62014-06-01 18:22:09 +01001723STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001724 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001725
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001726 if (self_len == 0) {
1727 return mp_const_false; // default to False for empty str
1728 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001729
Damien Georgefcc9cf62014-06-01 18:22:09 +01001730 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001731 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001732 if (!f(*self_data++)) {
1733 return mp_const_false;
1734 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001735 }
1736 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001737 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001738
Damien George39dc1452014-10-03 19:52:22 +01001739 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001740 if (unichar_isalpha(*self_data++)) {
1741 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001742 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1743 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001744 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001745 }
1746 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001747
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001748 if (!contains_alpha) {
1749 return mp_const_false;
1750 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001751 }
1752
1753 return mp_const_true;
1754}
1755
1756STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001757 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001758}
1759
1760STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001761 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001762}
1763
1764STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001765 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001766}
1767
1768STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001769 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001770}
1771
1772STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001773 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001774}
1775
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001776#if MICROPY_CPYTHON_COMPAT
1777// These methods are superfluous in the presense of str() and bytes()
1778// constructors.
1779// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001780STATIC mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001781 mp_obj_t new_args[2];
1782 if (n_args == 1) {
1783 new_args[0] = args[0];
1784 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1785 args = new_args;
1786 n_args++;
1787 }
Damien George5b3f0b72016-01-03 15:55:55 +00001788 return mp_obj_str_make_new(&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001789}
1790
1791// TODO: should accept kwargs too
Damien George4b72b3a2016-01-03 14:21:40 +00001792STATIC mp_obj_t str_encode(size_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001793 mp_obj_t new_args[2];
1794 if (n_args == 1) {
1795 new_args[0] = args[0];
1796 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1797 args = new_args;
1798 n_args++;
1799 }
Damien George5b3f0b72016-01-03 15:55:55 +00001800 return bytes_make_new(NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001801}
1802#endif
1803
Damien George4d917232014-08-30 14:28:06 +01001804mp_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 +01001805 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001806 GET_STR_DATA_LEN(self_in, str_data, str_len);
1807 bufinfo->buf = (void*)str_data;
1808 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001809 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001810 return 0;
1811 } else {
1812 // can't write to a string
1813 bufinfo->buf = NULL;
1814 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001815 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001816 return 1;
1817 }
1818}
1819
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001820#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001821MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1822MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001823#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001824MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1825MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1826MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1827MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1828MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Paul Sokolovsky87051712015-03-23 22:15:12 +02001829MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001830#if MICROPY_PY_BUILTINS_STR_SPLITLINES
1831MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
1832#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001833MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1834MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1835MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1836MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1837MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1838MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001839MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001840MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1841MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1842MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1843MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1844MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1845MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1846MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1847MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1848MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1849MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1850MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001851
Damien Georgecbf76742015-11-27 13:38:15 +00001852STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001853#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001854 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001855 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1856 // If we have separate unicode type, then here we have methods only
1857 // for bytes type, and it should not have encode() methods. Otherwise,
1858 // we have non-compliant-but-practical bytestring type, which shares
1859 // method table with bytes, so they both have encode() and decode()
1860 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001861 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001862 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001863#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001864 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1865 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1866 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1867 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1868 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1869 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001870 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001871 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001872 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001873 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1874 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1875 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1876 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1877 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1878 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1879 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1880 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1881 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
1882 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1883 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
1884 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1885 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1886 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1887 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1888 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1889 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1890 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001891};
Damien George97209d32014-01-07 15:58:30 +00001892
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001893STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001894
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001895#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George44e7cbf2015-05-17 16:44:24 +01001896STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
1897
Damien George3e1a5c12014-03-29 13:43:38 +00001898const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001899 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001900 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001901 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001902 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001903 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001904 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001905 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001906 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001907 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001908};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001909#endif
Damiend99b0522013-12-21 18:17:45 +00001910
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001911// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001912const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001913 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001914 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001915 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001916 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001917 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001918 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001919 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001920 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001921 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001922};
1923
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001924// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001925const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001926
Damien George77089be2015-01-21 23:08:36 +00001927// Create a str/bytes object using the given data. New memory is allocated and
1928// the data is copied across.
Damien George999cedb2015-11-27 17:01:44 +00001929mp_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 +02001930 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001931 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001932 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001933 if (data) {
1934 o->hash = qstr_compute_hash(data, len);
1935 byte *p = m_new(byte, len + 1);
1936 o->data = p;
1937 memcpy(p, data, len * sizeof(byte));
1938 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1939 }
Damien George999cedb2015-11-27 17:01:44 +00001940 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001941}
1942
Damien George77089be2015-01-21 23:08:36 +00001943// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1944// the exact length required and then reused for the str/bytes object. The vstr
1945// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001946mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1947 // if not a bytes object, look if a qstr with this data already exists
1948 if (type == &mp_type_str) {
1949 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1950 if (q != MP_QSTR_NULL) {
1951 vstr_clear(vstr);
1952 vstr->alloc = 0;
1953 return MP_OBJ_NEW_QSTR(q);
1954 }
1955 }
1956
1957 // make a new str/bytes object
1958 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1959 o->base.type = type;
1960 o->len = vstr->len;
1961 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07001962 if (vstr->len + 1 == vstr->alloc) {
1963 o->data = (byte*)vstr->buf;
1964 } else {
1965 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
1966 }
Damien George0d3cb672015-01-28 23:43:01 +00001967 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00001968 vstr->buf = NULL;
1969 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00001970 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00001971}
1972
Damien Georged182b982014-08-30 14:19:41 +01001973mp_obj_t mp_obj_new_str(const char* data, mp_uint_t len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001974 if (make_qstr_if_not_already) {
1975 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001976 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001977 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001978 qstr q = qstr_find_strn(data, len);
1979 if (q != MP_QSTR_NULL) {
1980 // qstr with this data already exists
1981 return MP_OBJ_NEW_QSTR(q);
1982 } else {
1983 // no existing qstr, don't make one
1984 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1985 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001986 }
Damien George5fa93b62014-01-22 14:35:10 +00001987}
1988
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001989mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1990 GET_STR_DATA_LEN(str, data, len);
1991 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1992}
1993
Damien Georged182b982014-08-30 14:19:41 +01001994mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001995 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001996}
1997
Damien George5fa93b62014-01-22 14:35:10 +00001998bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1999 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
2000 return s1 == s2;
2001 } else {
2002 GET_STR_HASH(s1, h1);
2003 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03002004 // If any of hashes is 0, it means it's not valid
2005 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00002006 return false;
2007 }
2008 GET_STR_DATA_LEN(s1, d1, l1);
2009 GET_STR_DATA_LEN(s2, d2, l2);
2010 if (l1 != l2) {
2011 return false;
2012 }
Damien George1e708fe2014-01-23 18:27:51 +00002013 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02002014 }
Damien George5fa93b62014-01-22 14:35:10 +00002015}
2016
Damien Georgedeed0872014-04-06 11:11:15 +01002017STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002018 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
2019 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
2020 "can't convert to str implicitly"));
2021 } else {
2022 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
2023 "can't convert '%s' object to str implicitly",
2024 mp_obj_get_type_str(self_in)));
2025 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002026}
2027
Damien Georgeb829b5c2014-01-25 13:51:19 +00002028// use this if you will anyway convert the string to a qstr
2029// will be more efficient for the case where it's already a qstr
2030qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2031 if (MP_OBJ_IS_QSTR(self_in)) {
2032 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002033 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002034 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002035 return qstr_from_strn((char*)self->data, self->len);
2036 } else {
2037 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002038 }
2039}
2040
2041// only use this function if you need the str data to be zero terminated
2042// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2043const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002044 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002045 GET_STR_DATA_LEN(self_in, s, l);
2046 (void)l; // len unused
2047 return (const char*)s;
2048 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002049 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002050 }
2051}
2052
Damien Georged182b982014-08-30 14:19:41 +01002053const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002054 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002055 GET_STR_DATA_LEN(self_in, s, l);
2056 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002057 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002058 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002059 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002060 }
Damiend99b0522013-12-21 18:17:45 +00002061}
xyb8cfc9f02014-01-05 18:47:51 +08002062
Damien George04353cc2015-10-18 23:09:04 +01002063#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
Damien Georgec3f64d92015-11-27 12:23:18 +00002064const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien George04353cc2015-10-18 23:09:04 +01002065 if (MP_OBJ_IS_QSTR(self_in)) {
2066 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2067 } else {
2068 *len = ((mp_obj_str_t*)self_in)->len;
2069 return ((mp_obj_str_t*)self_in)->data;
2070 }
2071}
2072#endif
2073
xyb8cfc9f02014-01-05 18:47:51 +08002074/******************************************************************************/
2075/* str iterator */
2076
Damien George44e7cbf2015-05-17 16:44:24 +01002077typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002078 mp_obj_base_t base;
Damien George8212d972016-01-03 16:27:55 +00002079 mp_fun_1_t iternext;
Damien George5fa93b62014-01-22 14:35:10 +00002080 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002081 mp_uint_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002082} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002083
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002084#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002085STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002086 mp_obj_str8_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002087 GET_STR_DATA_LEN(self->str, str, len);
2088 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002089 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002090 self->cur += 1;
2091 return o_out;
2092 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002093 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002094 }
2095}
2096
Damien George44e7cbf2015-05-17 16:44:24 +01002097STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2098 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George8212d972016-01-03 16:27:55 +00002099 o->base.type = &mp_type_polymorph_iter;
2100 o->iternext = str_it_iternext;
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002101 o->str = str;
2102 o->cur = 0;
2103 return o;
2104}
2105#endif
2106
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002107STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002108 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002109 GET_STR_DATA_LEN(self->str, str, len);
2110 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002111 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002112 self->cur += 1;
2113 return o_out;
2114 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002115 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002116 }
2117}
2118
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002119mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
Damien George44e7cbf2015-05-17 16:44:24 +01002120 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George8212d972016-01-03 16:27:55 +00002121 o->base.type = &mp_type_polymorph_iter;
2122 o->iternext = bytes_it_iternext;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002123 o->str = str;
2124 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002125 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002126}