blob: 7315f40020a03753b785e47394d9d2127243c582 [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"
Damiend99b0522013-12-21 18:17:45 +000037
Damien Georgeecc88e92014-08-30 00:35:11 +010038STATIC 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 +020039
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020040STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030041STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030042
xyb8cfc9f02014-01-05 18:47:51 +080043/******************************************************************************/
44/* str */
45
Damien George7f9d1d62015-04-09 23:56:15 +010046void 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 +020047 // this escapes characters, but it will be very slow to print (calling print many times)
48 bool has_single_quote = false;
49 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100050 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020051 if (*s == '\'') {
52 has_single_quote = true;
53 } else if (*s == '"') {
54 has_double_quote = true;
55 }
56 }
57 int quote_char = '\'';
58 if (has_single_quote && !has_double_quote) {
59 quote_char = '"';
60 }
Damien George7f9d1d62015-04-09 23:56:15 +010061 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020062 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
63 if (*s == quote_char) {
Damien George7f9d1d62015-04-09 23:56:15 +010064 mp_printf(print, "\\%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020065 } else if (*s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010066 mp_print_str(print, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030067 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
68 // In strings, anything which is not ascii control character
69 // is printed as is, this includes characters in range 0x80-0xff
70 // (which can be non-Latin letters, etc.)
Damien George7f9d1d62015-04-09 23:56:15 +010071 mp_printf(print, "%c", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020072 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010073 mp_print_str(print, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010074 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010075 mp_print_str(print, "\\r");
Andrew Scheller12968fb2014-04-08 02:42:50 +010076 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +010077 mp_print_str(print, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020078 } else {
Damien George7f9d1d62015-04-09 23:56:15 +010079 mp_printf(print, "\\x%02x", *s);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020080 }
81 }
Damien George7f9d1d62015-04-09 23:56:15 +010082 mp_printf(print, "%c", quote_char);
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020083}
84
Damien George612045f2014-09-17 22:56:34 +010085#if MICROPY_PY_UJSON
Damien George999cedb2015-11-27 17:01:44 +000086void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len) {
Damien Georgecde0ca22014-09-25 17:35:56 +010087 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
88 // 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 +010089 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +010090 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010091 if (*s == '"' || *s == '\\') {
Damien George7f9d1d62015-04-09 23:56:15 +010092 mp_printf(print, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010093 } else if (*s >= 32) {
94 // this will handle normal and utf-8 encoded chars
Damien George7f9d1d62015-04-09 23:56:15 +010095 mp_printf(print, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010096 } else if (*s == '\n') {
Damien George7f9d1d62015-04-09 23:56:15 +010097 mp_print_str(print, "\\n");
Damien George612045f2014-09-17 22:56:34 +010098 } else if (*s == '\r') {
Damien George7f9d1d62015-04-09 23:56:15 +010099 mp_print_str(print, "\\r");
Damien George612045f2014-09-17 22:56:34 +0100100 } else if (*s == '\t') {
Damien George7f9d1d62015-04-09 23:56:15 +0100101 mp_print_str(print, "\\t");
Damien George612045f2014-09-17 22:56:34 +0100102 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100103 // this will handle control chars
Damien George7f9d1d62015-04-09 23:56:15 +0100104 mp_printf(print, "\\u%04x", *s);
Damien George612045f2014-09-17 22:56:34 +0100105 }
106 }
Damien George7f9d1d62015-04-09 23:56:15 +0100107 mp_print_str(print, "\"");
Damien George612045f2014-09-17 22:56:34 +0100108}
109#endif
110
Damien George7f9d1d62015-04-09 23:56:15 +0100111STATIC 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 +0000112 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100113 #if MICROPY_PY_UJSON
114 if (kind == PRINT_JSON) {
Damien George7f9d1d62015-04-09 23:56:15 +0100115 mp_str_print_json(print, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100116 return;
117 }
118 #endif
Damien Georgee2aa1172015-09-03 23:03:57 +0100119 #if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien Georgecde0ca22014-09-25 17:35:56 +0100120 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Damien Georgee2aa1172015-09-03 23:03:57 +0100121 #else
122 bool is_bytes = true;
123 #endif
Paul Sokolovskyef63ab52015-12-20 16:44:36 +0200124 if (kind == PRINT_RAW || (!MICROPY_PY_BUILTINS_STR_UNICODE && kind == PRINT_STR && !is_bytes)) {
Damien George7f9d1d62015-04-09 23:56:15 +0100125 mp_printf(print, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200126 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200127 if (is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100128 mp_print_str(print, "b");
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200129 }
Damien George7f9d1d62015-04-09 23:56:15 +0100130 mp_str_print_quoted(print, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200131 }
Damiend99b0522013-12-21 18:17:45 +0000132}
133
Paul Sokolovsky344e15b2015-01-23 02:15:56 +0200134mp_obj_t mp_obj_str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300135#if MICROPY_CPYTHON_COMPAT
136 if (n_kw != 0) {
137 mp_arg_error_unimpl_kw();
138 }
139#endif
140
Damien George1e9a92f2014-11-06 17:36:16 +0000141 mp_arg_check_num(n_args, n_kw, 0, 3, false);
142
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200143 switch (n_args) {
144 case 0:
145 return MP_OBJ_NEW_QSTR(MP_QSTR_);
146
Damien George1e9a92f2014-11-06 17:36:16 +0000147 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000148 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100149 mp_print_t print;
150 vstr_init_print(&vstr, 16, &print);
151 mp_obj_print_helper(&print, args[0], PRINT_STR);
Damien George999cedb2015-11-27 17:01:44 +0000152 return mp_obj_new_str_from_vstr(MP_OBJ_TO_PTR(type_in), &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200153 }
154
Damien George1e9a92f2014-11-06 17:36:16 +0000155 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200156 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200157 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
158 GET_STR_DATA_LEN(args[0], str_data, str_len);
159 GET_STR_HASH(args[0], str_hash);
Damien George999cedb2015-11-27 17:01:44 +0000160 mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_of_type(MP_OBJ_TO_PTR(type_in), NULL, str_len));
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200161 o->data = str_data;
162 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000163 return MP_OBJ_FROM_PTR(o);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200164 } else {
165 mp_buffer_info_t bufinfo;
166 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
167 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200168 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200169 }
170}
171
Damien Georgeecc88e92014-08-30 00:35:11 +0100172STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +0000173 (void)type_in;
174
Damien George3a2171e2015-09-04 16:53:46 +0100175 #if MICROPY_CPYTHON_COMPAT
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300176 if (n_kw != 0) {
177 mp_arg_error_unimpl_kw();
178 }
Damien George3a2171e2015-09-04 16:53:46 +0100179 #else
180 (void)n_kw;
181 #endif
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300182
Damien George42cec5c2015-09-04 16:51:55 +0100183 if (n_args == 0) {
184 return mp_const_empty_bytes;
185 }
186
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200187 if (MP_OBJ_IS_STR(args[0])) {
188 if (n_args < 2 || n_args > 3) {
189 goto wrong_args;
190 }
191 GET_STR_DATA_LEN(args[0], str_data, str_len);
192 GET_STR_HASH(args[0], str_hash);
Damien George999cedb2015-11-27 17:01:44 +0000193 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 +0200194 o->data = str_data;
195 o->hash = str_hash;
Damien George999cedb2015-11-27 17:01:44 +0000196 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200197 }
198
199 if (n_args > 1) {
200 goto wrong_args;
201 }
202
203 if (MP_OBJ_IS_SMALL_INT(args[0])) {
204 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000205 vstr_t vstr;
206 vstr_init_len(&vstr, len);
207 memset(vstr.buf, 0, len);
208 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200209 }
210
Damien George32ef3a32014-12-04 15:46:14 +0000211 // check if argument has the buffer protocol
212 mp_buffer_info_t bufinfo;
213 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
214 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
215 }
216
Damien George0b9ee862015-01-21 19:14:25 +0000217 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200218 // Try to create array of exact len if initializer len is known
219 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
220 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000221 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200222 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000223 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000224 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200225 }
226
Damien Georged17926d2014-03-30 13:35:08 +0100227 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200228 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100229 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100230 mp_int_t val = mp_obj_get_int(item);
231 #if MICROPY_CPYTHON_COMPAT
232 if (val < 0 || val > 255) {
233 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bytes value out of range"));
234 }
235 #endif
236 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200237 }
238
Damien George0b9ee862015-01-21 19:14:25 +0000239 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200240
241wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000242 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200243}
244
Damien George55baff42014-01-21 21:40:13 +0000245// like strstr but with specified length and allows \0 bytes
246// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100247STATIC 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 +0000248 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100249 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700250 if (direction > 0) {
251 str_index = 0;
252 str_index_end = hlen - nlen;
253 } else {
254 str_index = hlen - nlen;
255 str_index_end = 0;
256 }
257 for (;;) {
258 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
259 //found
260 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000261 }
xbe17a5a832014-03-23 23:31:58 -0700262 if (str_index == str_index_end) {
263 //not found
264 break;
Damien George55baff42014-01-21 21:40:13 +0000265 }
xbe17a5a832014-03-23 23:31:58 -0700266 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000267 }
268 }
269 return NULL;
270}
271
Damien Georgea75b02e2014-08-27 09:20:30 +0100272// Note: this function is used to check if an object is a str or bytes, which
273// works because both those types use it as their binary_op method. Revisit
274// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100275mp_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 +0000276 // check for modulo
277 if (op == MP_BINARY_OP_MODULO) {
278 mp_obj_t *args;
279 mp_uint_t n_args;
280 mp_obj_t dict = MP_OBJ_NULL;
281 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
282 // TODO: Support tuple subclasses?
283 mp_obj_tuple_get(rhs_in, &n_args, &args);
284 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
285 args = NULL;
286 n_args = 0;
287 dict = rhs_in;
288 } else {
289 args = &rhs_in;
290 n_args = 1;
291 }
292 return str_modulo_format(lhs_in, n_args, args, dict);
293 }
294
295 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300296 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000297 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
298
299 // check for multiply
300 if (op == MP_BINARY_OP_MULTIPLY) {
301 mp_int_t n;
302 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
303 return MP_OBJ_NULL; // op not supported
304 }
305 if (n <= 0) {
306 if (lhs_type == &mp_type_str) {
307 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
308 } else {
309 return mp_const_empty_bytes;
310 }
311 }
Damien George05005f62015-01-21 22:48:37 +0000312 vstr_t vstr;
313 vstr_init_len(&vstr, lhs_len * n);
314 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
315 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000316 }
317
318 // From now on all operations allow:
319 // - str with str
320 // - bytes with bytes
321 // - bytes with bytearray
322 // - bytes with array.array
323 // To do this efficiently we use the buffer protocol to extract the raw
324 // data for the rhs, but only if the lhs is a bytes object.
325 //
326 // NOTE: CPython does not allow comparison between bytes ard array.array
327 // (even if the array is of type 'b'), even though it allows addition of
328 // such types. We are not compatible with this (we do allow comparison
329 // of bytes with anything that has the buffer protocol). It would be
330 // easy to "fix" this with a bit of extra logic below, but it costs code
331 // size and execution time so we don't.
332
333 const byte *rhs_data;
334 mp_uint_t rhs_len;
335 if (lhs_type == mp_obj_get_type(rhs_in)) {
336 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
337 rhs_data = rhs_data_;
338 rhs_len = rhs_len_;
339 } else if (lhs_type == &mp_type_bytes) {
340 mp_buffer_info_t bufinfo;
341 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000342 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000343 }
344 rhs_data = bufinfo.buf;
345 rhs_len = bufinfo.len;
346 } else {
347 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000348 return MP_OBJ_NULL; // op not supported
349 }
350
Damiend99b0522013-12-21 18:17:45 +0000351 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100352 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000353 case MP_BINARY_OP_INPLACE_ADD: {
Damien George05005f62015-01-21 22:48:37 +0000354 vstr_t vstr;
355 vstr_init_len(&vstr, lhs_len + rhs_len);
356 memcpy(vstr.buf, lhs_data, lhs_len);
357 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
358 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200359 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200360
Damien Georgea65c03c2014-11-05 16:30:34 +0000361 case MP_BINARY_OP_IN:
362 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300363 return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300364
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300365 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
366 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 +0100367 case MP_BINARY_OP_LESS:
368 case MP_BINARY_OP_LESS_EQUAL:
369 case MP_BINARY_OP_MORE:
370 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300371 return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000372 }
373
Damien George6ac5dce2014-05-21 19:42:43 +0100374 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000375}
376
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300377#if !MICROPY_PY_BUILTINS_STR_UNICODE
378// objstrunicode defines own version
Damien George999cedb2015-11-27 17:01:44 +0000379const 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 +0300380 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100381 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300382 return self_data + index_val;
383}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300384#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300385
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300386// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
387STATIC 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 +0300388 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100389 GET_STR_DATA_LEN(self_in, self_data, self_len);
390 if (value == MP_OBJ_SENTINEL) {
391 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100392#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100393 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300394 mp_bound_slice_t slice;
395 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Damien George821b7f22015-09-03 23:14:06 +0100396 mp_not_implemented("only slices with step=1 (aka None) are supported");
Damien George729f7b42014-04-17 22:10:53 +0100397 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100398 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100399 }
400#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300401 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100402 // If we have unicode enabled the type will always be bytes, so take the short cut.
403 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300404 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100405 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300406 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100407 }
408 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100409 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100410 }
411}
412
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200413STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700414 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300415 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000416
Damien Georgefe8fb912014-01-02 16:36:09 +0000417 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000418 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000419
420 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100421 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000422 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000423 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000424 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000425 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100426 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
427 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300428 // TODO: Try to optimize?
Damien George999cedb2015-11-27 17:01:44 +0000429 arg = mp_type_list.make_new(MP_OBJ_FROM_PTR(&mp_type_list), 1, 0, &arg);
Damien Georgea157e4c2014-04-09 19:17:53 +0100430 }
431 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000432 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000433
434 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100435 mp_uint_t required_len = 0;
436 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300437 if (mp_obj_get_type(seq_items[i]) != self_type) {
438 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
439 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000440 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000441 if (i > 0) {
442 required_len += sep_len;
443 }
Damien George5fa93b62014-01-22 14:35:10 +0000444 GET_STR_LEN(seq_items[i], l);
445 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000446 }
447
448 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000449 vstr_t vstr;
450 vstr_init_len(&vstr, required_len);
451 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +0100452 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000453 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000454 memcpy(data, sep_str, sep_len);
455 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000456 }
Damien George5fa93b62014-01-22 14:35:10 +0000457 GET_STR_DATA_LEN(seq_items[i], s, l);
458 memcpy(data, s, l);
459 data += l;
Damiend99b0522013-12-21 18:17:45 +0000460 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000461
462 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000463 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000464}
465
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300466enum {SPLIT = 0, KEEP = 1, SPLITLINES = 2};
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200467
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300468STATIC 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 +0300469 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100470 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200471 mp_obj_t sep = mp_const_none;
472 if (n_args > 1) {
473 sep = args[1];
474 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100475 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200476 }
477 }
Damien Georgedeed0872014-04-06 11:11:15 +0100478
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200479 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000480 GET_STR_DATA_LEN(args[0], s, len);
481 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200482
Damien Georgedeed0872014-04-06 11:11:15 +0100483 if (sep == mp_const_none) {
484 // sep not given, so separate on whitespace
485
486 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300487 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100488 while (s < top && splits != 0) {
489 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300490 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100491 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100492 if (s >= top) {
493 break;
494 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300495 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100496 if (splits > 0) {
497 splits--;
498 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200499 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200500
Damien Georgedeed0872014-04-06 11:11:15 +0100501 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100502 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100503 }
504
505 } else {
506 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300507 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000508 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300509 }
Damien Georgedeed0872014-04-06 11:11:15 +0100510
Damien Georged182b982014-08-30 14:19:41 +0100511 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100512 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
513
514 if (sep_len == 0) {
515 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
516 }
517
518 for (;;) {
519 const byte *start = s;
520 for (;;) {
521 if (splits == 0 || s + sep_len > top) {
522 s = top;
523 break;
524 } else if (memcmp(s, sep_str, sep_len) == 0) {
525 break;
526 }
527 s++;
528 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300529 mp_uint_t sub_len = s - start;
Paul Sokolovsky7f59b4b2015-04-04 01:55:40 +0300530 if (MP_LIKELY(!(sub_len == 0 && s == top && (type && SPLITLINES)))) {
531 if (start + sub_len != top && (type & KEEP)) {
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300532 sub_len++;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300533 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300534 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300535 }
Damien Georgedeed0872014-04-06 11:11:15 +0100536 if (s >= top) {
537 break;
538 }
539 s += sep_len;
540 if (splits > 0) {
541 splits--;
542 }
543 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200544 }
545
546 return res;
547}
548
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300549mp_obj_t mp_obj_str_split(mp_uint_t n_args, const mp_obj_t *args) {
550 return str_split_internal(n_args, args, SPLIT);
551}
552
553#if MICROPY_PY_BUILTINS_STR_SPLITLINES
554STATIC mp_obj_t str_splitlines(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
555 static const mp_arg_t allowed_args[] = {
556 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
557 };
558
559 // parse args
560 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
561 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
562
563 mp_obj_t new_args[2] = {pos_args[0], MP_OBJ_NEW_QSTR(MP_QSTR__backslash_n)};
564 return str_split_internal(2, new_args, SPLITLINES | (args[0].u_bool ? KEEP : 0));
565}
566#endif
567
Damien Georgeecc88e92014-08-30 00:35:11 +0100568STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300569 if (n_args < 3) {
570 // If we don't have split limit, it doesn't matter from which side
571 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200572 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300573 }
574 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
575 mp_obj_t sep = args[1];
576 GET_STR_DATA_LEN(args[0], s, len);
577
Damien George40f3c022014-07-03 13:25:24 +0100578 mp_int_t splits = mp_obj_get_int(args[2]);
579 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300580 // Preallocate list to the max expected # of elements, as we
581 // will fill it from the end.
Damien George999cedb2015-11-27 17:01:44 +0000582 mp_obj_list_t *res = MP_OBJ_TO_PTR(mp_obj_new_list(splits + 1, NULL));
Damien George39dc1452014-10-03 19:52:22 +0100583 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300584
585 if (sep == mp_const_none) {
Damien George22602cc2015-09-01 15:35:31 +0100586 mp_not_implemented("rsplit(None,n)");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300587 } else {
Damien Georged182b982014-08-30 14:19:41 +0100588 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300589 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
590
591 if (sep_len == 0) {
592 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
593 }
594
595 const byte *beg = s;
596 const byte *last = s + len;
597 for (;;) {
598 s = last - sep_len;
599 for (;;) {
600 if (splits == 0 || s < beg) {
601 break;
602 } else if (memcmp(s, sep_str, sep_len) == 0) {
603 break;
604 }
605 s--;
606 }
607 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100608 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300609 break;
610 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100611 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 +0300612 last = s;
613 if (splits > 0) {
614 splits--;
615 }
616 }
617 if (idx != 0) {
618 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100619 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100620 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300621 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
622 res->len = used;
623 }
624 }
625
Damien George999cedb2015-11-27 17:01:44 +0000626 return MP_OBJ_FROM_PTR(res);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300627}
628
Damien Georgeecc88e92014-08-30 00:35:11 +0100629STATIC 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 +0300630 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000631 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000632 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
633
634 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000635 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000636 bad_implicit_conversion(args[1]);
637 }
John R. Lentone8204912014-01-12 21:53:52 +0000638
Damien George5fa93b62014-01-22 14:35:10 +0000639 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
640 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000641
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300642 const byte *start = haystack;
643 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000644 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300645 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000646 }
647 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300648 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000649 }
650
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300651 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000652 if (p == NULL) {
653 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700654 if (is_index) {
655 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
656 } else {
657 return MP_OBJ_NEW_SMALL_INT(-1);
658 }
Damien George23005372014-01-13 19:39:01 +0000659 } else {
660 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300661 #if MICROPY_PY_BUILTINS_STR_UNICODE
662 if (self_type == &mp_type_str) {
663 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
664 }
665 #endif
xbe17a5a832014-03-23 23:31:58 -0700666 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000667 }
John R. Lentone8204912014-01-12 21:53:52 +0000668}
669
Damien Georgeecc88e92014-08-30 00:35:11 +0100670STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700671 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700672}
673
Damien Georgeecc88e92014-08-30 00:35:11 +0100674STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700675 return str_finder(n_args, args, -1, false);
676}
677
Damien Georgeecc88e92014-08-30 00:35:11 +0100678STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700679 return str_finder(n_args, args, 1, true);
680}
681
Damien Georgeecc88e92014-08-30 00:35:11 +0100682STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700683 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700684}
685
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200686// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100687STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300688 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300689 GET_STR_DATA_LEN(args[0], str, str_len);
690 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300691 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300692 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300693 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300694 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300695 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200696 return mp_const_false;
697 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300698 return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200699}
700
Damien Georgeecc88e92014-08-30 00:35:11 +0100701STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300702 GET_STR_DATA_LEN(args[0], str, str_len);
703 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
Damien George55b11e62015-09-04 16:49:56 +0100704 if (n_args > 2) {
705 mp_not_implemented("start/end indices");
706 }
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300707
708 if (suffix_len > str_len) {
709 return mp_const_false;
710 }
Paul Sokolovsky1b586f32015-10-11 12:09:43 +0300711 return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300712}
713
Paul Sokolovsky88107842014-04-26 06:20:08 +0300714enum { LSTRIP, RSTRIP, STRIP };
715
Damien Georgeecc88e92014-08-30 00:35:11 +0100716STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800717 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700718 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300719 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000720
721 const byte *chars_to_del;
722 uint chars_to_del_len;
723 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800724
725 if (n_args == 1) {
726 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000727 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800728 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300729 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000730 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300731 }
Damien George5fa93b62014-01-22 14:35:10 +0000732 GET_STR_DATA_LEN(args[1], s, l);
733 chars_to_del = s;
734 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800735 }
736
Damien George5fa93b62014-01-22 14:35:10 +0000737 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800738
Damien George40f3c022014-07-03 13:25:24 +0100739 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800740 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100741 mp_uint_t last_good_char_pos = 0;
742 mp_uint_t i = 0;
743 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300744 if (type == RSTRIP) {
745 i = orig_str_len - 1;
746 delta = -1;
747 }
Damien George40f3c022014-07-03 13:25:24 +0100748 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700749 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800750 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300751 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800752 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300753 if (type == LSTRIP) {
754 last_good_char_pos = orig_str_len - 1;
755 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300756 } else if (type == RSTRIP) {
757 first_good_char_pos = 0;
758 last_good_char_pos = i;
759 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300760 }
xbe7b0f39f2014-01-08 14:23:45 -0800761 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300762 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800763 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300764 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800765 }
766
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300767 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000768 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000769 if (self_type == &mp_type_str) {
770 return MP_OBJ_NEW_QSTR(MP_QSTR_);
771 } else {
772 return mp_const_empty_bytes;
773 }
xbe7b0f39f2014-01-08 14:23:45 -0800774 }
775
776 assert(last_good_char_pos >= first_good_char_pos);
777 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100778 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300779 if (stripped_len == orig_str_len) {
780 // If nothing was stripped, don't bother to dup original string
781 // TODO: watch out for this case when we'll get to bytearray.strip()
782 assert(first_good_char_pos == 0);
783 return args[0];
784 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100785 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800786}
787
Damien Georgeecc88e92014-08-30 00:35:11 +0100788STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300789 return str_uni_strip(STRIP, n_args, args);
790}
791
Damien Georgeecc88e92014-08-30 00:35:11 +0100792STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300793 return str_uni_strip(LSTRIP, n_args, args);
794}
795
Damien Georgeecc88e92014-08-30 00:35:11 +0100796STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300797 return str_uni_strip(RSTRIP, n_args, args);
798}
799
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700800// Takes an int arg, but only parses unsigned numbers, and only changes
801// *num if at least one digit was parsed.
Damien George2801e6f2015-04-04 15:53:11 +0100802STATIC int str_to_int(const char *str, int *num) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700803 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000804 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700805 *num = 0;
806 do {
807 *num = *num * 10 + (*s - '0');
808 s++;
809 }
Damien George81836c22014-12-21 21:07:03 +0000810 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700811 }
812 return s - str;
813}
814
Damien George2801e6f2015-04-04 15:53:11 +0100815STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700816 return ch && strchr("<>=^", ch) != NULL;
817}
818
Damien George2801e6f2015-04-04 15:53:11 +0100819STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700820 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
821}
822
Damien George2801e6f2015-04-04 15:53:11 +0100823STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700824 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
825}
826
Damien George2801e6f2015-04-04 15:53:11 +0100827STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700828 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100829#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100830 || mp_obj_is_float(arg)
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700831#endif
832 ;
833}
834
Damien George2801e6f2015-04-04 15:53:11 +0100835STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100836#if MICROPY_PY_BUILTINS_FLOAT
Damien Georgeaaef1852015-08-20 23:30:12 +0100837 if (mp_obj_is_float(arg)) {
838 return mp_obj_new_int_from_float(mp_obj_float_get(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700839 }
840#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700841 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700842}
843
Damien George1e9a92f2014-11-06 17:36:16 +0000844STATIC NORETURN void terse_str_format_value_error(void) {
845 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
846}
847
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200848mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000849 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000850
Damien George5fa93b62014-01-22 14:35:10 +0000851 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700852 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +0000853 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100854 mp_print_t print;
855 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700856
Damien George5fa93b62014-01-22 14:35:10 +0000857 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700858 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000859 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860 if (str < top && *str == '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100861 vstr_add_byte(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700862 continue;
863 }
Damien George1e9a92f2014-11-06 17:36:16 +0000864 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
865 terse_str_format_value_error();
866 } else {
867 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
868 "single '}' encountered in format string"));
869 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700870 }
871 if (*str != '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100872 vstr_add_byte(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700873 continue;
874 }
875
876 str++;
877 if (str < top && *str == '{') {
Damien George51b9a0d2015-08-26 15:29:49 +0100878 vstr_add_byte(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700879 continue;
880 }
881
882 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
883
884 vstr_t *field_name = NULL;
885 char conversion = '\0';
886 vstr_t *format_spec = NULL;
887
888 if (str < top && *str != '}' && *str != '!' && *str != ':') {
889 field_name = vstr_new();
890 while (str < top && *str != '}' && *str != '!' && *str != ':') {
Damien George51b9a0d2015-08-26 15:29:49 +0100891 vstr_add_byte(field_name, *str++);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700892 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700893 }
894
895 // conversion ::= "r" | "s"
896
897 if (str < top && *str == '!') {
898 str++;
899 if (str < top && (*str == 'r' || *str == 's')) {
900 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200901 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000902 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
903 terse_str_format_value_error();
Damien George000730e2015-08-30 12:43:21 +0100904 } else if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL) {
Damien George1e9a92f2014-11-06 17:36:16 +0000905 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
Damien George000730e2015-08-30 12:43:21 +0100906 "bad conversion specifier"));
907 } else {
908 if (str >= top) {
909 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
910 "end of format while looking for conversion specifier"));
911 } else {
912 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
913 "unknown conversion specifier %c", *str));
914 }
Damien George1e9a92f2014-11-06 17:36:16 +0000915 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700916 }
917 }
918
919 if (str < top && *str == ':') {
920 str++;
921 // {:} is the same as {}, which is the same as {!s}
922 // This makes a difference when passing in a True or False
923 // '{}'.format(True) returns 'True'
924 // '{:d}'.format(True) returns '1'
925 // So we treat {:} as {} and this later gets treated to be {!s}
926 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100927 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700928 while (str < top && *str != '}') {
Damien George51b9a0d2015-08-26 15:29:49 +0100929 vstr_add_byte(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000930 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700931 }
932 }
933 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000934 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
935 terse_str_format_value_error();
936 } else {
937 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
938 "unmatched '{' in format"));
939 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700940 }
941 if (*str != '}') {
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 "expected ':' after format specifier"));
947 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700948 }
949
950 mp_obj_t arg = mp_const_none;
951
952 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100953 int index = 0;
Damien George827b0f72015-01-29 13:57:23 +0000954 const char *field = vstr_null_terminated_str(field_name);
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200955 const char *lookup = NULL;
956 if (MP_LIKELY(unichar_isdigit(*field))) {
957 if (arg_i > 0) {
958 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
959 terse_str_format_value_error();
960 } else {
961 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
962 "can't switch from automatic field numbering to manual field specification"));
963 }
964 }
Paul Sokolovskyff8e35b2015-01-04 13:23:44 +0200965 lookup = str_to_int(field, &index) + field;
Damien George963a5a32015-01-16 17:47:07 +0000966 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200967 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
968 }
969 arg = args[index + 1];
970 arg_i = -1;
971 } else {
972 for (lookup = field; *lookup && *lookup != '.' && *lookup != '['; lookup++);
973 mp_obj_t field_q = mp_obj_new_str(field, lookup - field, true/*?*/);
974 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
975 if (key_elem == NULL) {
976 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
977 }
978 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700979 }
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200980 if (*lookup) {
Damien George821b7f22015-09-03 23:14:06 +0100981 mp_not_implemented("attributes not supported yet");
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700982 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700983 vstr_free(field_name);
984 field_name = NULL;
985 } else {
986 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000987 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
988 terse_str_format_value_error();
989 } else {
990 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
991 "can't switch from manual field specification to automatic field numbering"));
992 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700993 }
Damien George963a5a32015-01-16 17:47:07 +0000994 if ((uint)arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100995 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700996 }
997 arg = args[arg_i + 1];
998 arg_i++;
999 }
1000 if (!format_spec && !conversion) {
1001 conversion = 's';
1002 }
1003 if (conversion) {
1004 mp_print_kind_t print_kind;
1005 if (conversion == 's') {
1006 print_kind = PRINT_STR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001007 } else {
Damien George000730e2015-08-30 12:43:21 +01001008 assert(conversion == 'r');
1009 print_kind = PRINT_REPR;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001010 }
Damien George0b9ee862015-01-21 19:14:25 +00001011 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001012 mp_print_t arg_print;
1013 vstr_init_print(&arg_vstr, 16, &arg_print);
1014 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001015 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001016 }
1017
1018 char sign = '\0';
1019 char fill = '\0';
1020 char align = '\0';
1021 int width = -1;
1022 int precision = -1;
1023 char type = '\0';
1024 int flags = 0;
1025
1026 if (format_spec) {
1027 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1028 //
1029 // [[fill]align][sign][#][0][width][,][.precision][type]
1030 // fill ::= <any character>
1031 // align ::= "<" | ">" | "=" | "^"
1032 // sign ::= "+" | "-" | " "
1033 // width ::= integer
1034 // precision ::= integer
1035 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1036
Damien George827b0f72015-01-29 13:57:23 +00001037 const char *s = vstr_null_terminated_str(format_spec);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001038 if (isalignment(*s)) {
1039 align = *s++;
1040 } else if (*s && isalignment(s[1])) {
1041 fill = *s++;
1042 align = *s++;
1043 }
1044 if (*s == '+' || *s == '-' || *s == ' ') {
1045 if (*s == '+') {
1046 flags |= PF_FLAG_SHOW_SIGN;
1047 } else if (*s == ' ') {
1048 flags |= PF_FLAG_SPACE_SIGN;
1049 }
1050 sign = *s++;
1051 }
1052 if (*s == '#') {
1053 flags |= PF_FLAG_SHOW_PREFIX;
1054 s++;
1055 }
1056 if (*s == '0') {
1057 if (!align) {
1058 align = '=';
1059 }
1060 if (!fill) {
1061 fill = '0';
1062 }
1063 }
1064 s += str_to_int(s, &width);
1065 if (*s == ',') {
1066 flags |= PF_FLAG_SHOW_COMMA;
1067 s++;
1068 }
1069 if (*s == '.') {
1070 s++;
1071 s += str_to_int(s, &precision);
1072 }
1073 if (istype(*s)) {
1074 type = *s++;
1075 }
1076 if (*s) {
Damien George7ef75f92015-08-26 15:42:25 +01001077 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1078 terse_str_format_value_error();
1079 } else {
1080 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1081 "invalid format specifier"));
1082 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001083 }
1084 vstr_free(format_spec);
1085 format_spec = NULL;
1086 }
1087 if (!align) {
1088 if (arg_looks_numeric(arg)) {
1089 align = '>';
1090 } else {
1091 align = '<';
1092 }
1093 }
1094 if (!fill) {
1095 fill = ' ';
1096 }
1097
1098 if (sign) {
1099 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001100 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1101 terse_str_format_value_error();
1102 } else {
1103 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1104 "sign not allowed in string format specifier"));
1105 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001106 }
1107 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001108 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1109 terse_str_format_value_error();
1110 } else {
1111 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1112 "sign not allowed with integer format specifier 'c'"));
1113 }
Damiend99b0522013-12-21 18:17:45 +00001114 }
1115 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001116 sign = '-';
1117 }
1118
1119 switch (align) {
1120 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1121 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1122 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1123 }
1124
1125 if (arg_looks_integer(arg)) {
1126 switch (type) {
1127 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001128 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001129 continue;
1130
1131 case 'c':
1132 {
1133 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001134 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001135 continue;
1136 }
1137
1138 case '\0': // No explicit format type implies 'd'
1139 case 'n': // I don't think we support locales in uPy so use 'd'
1140 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001141 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001142 continue;
1143
1144 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001145 if (flags & PF_FLAG_SHOW_PREFIX) {
1146 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1147 }
1148
Damien George7f9d1d62015-04-09 23:56:15 +01001149 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 continue;
1151
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001152 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001153 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001154 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001155 continue;
1156
1157 case 'e':
1158 case 'E':
1159 case 'f':
1160 case 'F':
1161 case 'g':
1162 case 'G':
1163 case '%':
1164 // The floating point formatters all work with anything that
1165 // looks like an integer
1166 break;
1167
1168 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001169 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1170 terse_str_format_value_error();
1171 } else {
1172 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1173 "unknown format code '%c' for object of type '%s'",
1174 type, mp_obj_get_type_str(arg)));
1175 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001176 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001177 }
Damien George70f33cd2014-04-02 17:06:05 +01001178
Dave Hylands22fe4d72014-04-02 12:07:31 -07001179 // NOTE: no else here. We need the e, f, g etc formats for integer
1180 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001181 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001182 if (!type) {
1183
1184 // Even though the docs say that an unspecified type is the same
1185 // as 'g', there is one subtle difference, when the exponent
1186 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001187 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001188 // '{:10.1}'.format(0.0) ==> '0e+00'
1189 // '{:10.1g}'.format(0.0) ==> '0'
1190 //
1191 // TODO: Figure out how to deal with this.
1192 //
1193 // A proper solution would involve adding a special flag
1194 // or something to format_float, and create a format_double
1195 // to deal with doubles. In order to fix this when using
1196 // sprintf, we'd need to use the e format and tweak the
1197 // returned result to strip trailing zeros like the g format
1198 // does.
1199 //
1200 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1201 // but with 1.e2 you get 1e+02 and 1.00e+02
1202 //
1203 // Stripping the trailing 0's (like g) does would make the
1204 // e format give us the right format.
1205 //
1206 // CPython sources say:
1207 // Omitted type specifier. Behaves in the same way as repr(x)
1208 // and str(x) if no precision is given, else like 'g', but with
1209 // at least one digit after the decimal point. */
1210
1211 type = 'g';
1212 }
1213 if (type == 'n') {
1214 type = 'g';
1215 }
1216
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001217 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001218#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001219 case 'e':
1220 case 'E':
1221 case 'f':
1222 case 'F':
1223 case 'g':
1224 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001225 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001226 break;
1227
1228 case '%':
1229 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001230 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1231 #define F100 100.0F
1232 #else
1233 #define F100 100.0
1234 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001235 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001236 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001237 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001238#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001239
1240 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001241 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1242 terse_str_format_value_error();
1243 } else {
1244 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1245 "unknown format code '%c' for object of type 'float'",
1246 type, mp_obj_get_type_str(arg)));
1247 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001248 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001249 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001250 // arg doesn't look like a number
1251
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001252 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001253 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1254 terse_str_format_value_error();
1255 } else {
1256 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1257 "'=' alignment not allowed in string format specifier"));
1258 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001259 }
Damien George70f33cd2014-04-02 17:06:05 +01001260
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001261 switch (type) {
1262 case '\0':
Damien George7f9d1d62015-04-09 23:56:15 +01001263 mp_obj_print_helper(&print, arg, PRINT_STR);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001264 break;
1265
Damien Georged182b982014-08-30 14:19:41 +01001266 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001267 mp_uint_t slen;
1268 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001269 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001270 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001271 }
Damien George50912e72015-01-20 11:55:10 +00001272 if (slen > (mp_uint_t)precision) {
1273 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001274 }
Damien George7f9d1d62015-04-09 23:56:15 +01001275 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001276 break;
1277 }
1278
1279 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001280 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1281 terse_str_format_value_error();
1282 } else {
1283 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1284 "unknown format code '%c' for object of type 'str'",
1285 type, mp_obj_get_type_str(arg)));
1286 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001287 }
Damiend99b0522013-12-21 18:17:45 +00001288 }
1289 }
1290
Damien George0b9ee862015-01-21 19:14:25 +00001291 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001292}
1293
Damien Georgeecc88e92014-08-30 00:35:11 +01001294STATIC 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 +00001295 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001296
1297 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001298 const byte *start_str = str;
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001299 bool is_bytes = MP_OBJ_IS_TYPE(pattern, &mp_type_bytes);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001300 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001301 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001302 mp_print_t print;
1303 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001304
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001305 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001306 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001307 if (*str != '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001308 vstr_add_byte(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001309 continue;
1310 }
1311 if (++str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001312 goto incomplete_format;
Dave Hylands6756a372014-04-02 11:42:39 -07001313 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001314 if (*str == '%') {
Damien George51b9a0d2015-08-26 15:29:49 +01001315 vstr_add_byte(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001316 continue;
1317 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001318
1319 // Dictionary value lookup
1320 if (*str == '(') {
1321 const byte *key = ++str;
1322 while (*str != ')') {
1323 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001324 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1325 terse_str_format_value_error();
1326 } else {
1327 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1328 "incomplete format key"));
1329 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001330 }
1331 ++str;
1332 }
1333 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1334 arg = mp_obj_dict_get(dict, k_obj);
1335 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001336 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001337
Dave Hylands6756a372014-04-02 11:42:39 -07001338 int flags = 0;
1339 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001340 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001341 while (str < top) {
1342 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1343 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1344 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001345 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001346 else if (*str == '0') {
1347 flags |= PF_FLAG_PAD_AFTER_SIGN;
1348 fill = '0';
1349 } else break;
1350 str++;
1351 }
1352 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001353 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001354 if (str < top) {
1355 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001356 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001357 goto not_enough_args;
1358 }
Dave Hylands6756a372014-04-02 11:42:39 -07001359 width = mp_obj_get_int(args[arg_i++]);
1360 str++;
1361 } else {
Damien George81836c22014-12-21 21:07:03 +00001362 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001363 }
1364 }
1365 int prec = -1;
1366 if (str < top && *str == '.') {
1367 if (++str < top) {
1368 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001369 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001370 goto not_enough_args;
1371 }
Dave Hylands6756a372014-04-02 11:42:39 -07001372 prec = mp_obj_get_int(args[arg_i++]);
1373 str++;
1374 } else {
1375 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001376 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001377 }
1378 }
1379 }
1380
1381 if (str >= top) {
Damien Georgeb648e982015-08-26 15:45:06 +01001382incomplete_format:
Damien George1e9a92f2014-11-06 17:36:16 +00001383 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1384 terse_str_format_value_error();
1385 } else {
1386 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1387 "incomplete format"));
1388 }
Dave Hylands6756a372014-04-02 11:42:39 -07001389 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001390
1391 // Tuple value lookup
1392 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001393 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001394not_enough_args:
1395 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1396 }
1397 arg = args[arg_i++];
1398 }
Dave Hylands6756a372014-04-02 11:42:39 -07001399 switch (*str) {
1400 case 'c':
1401 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001402 mp_uint_t slen;
1403 const char *s = mp_obj_str_get_data(arg, &slen);
1404 if (slen != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001405 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1406 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001407 }
Damien George7f9d1d62015-04-09 23:56:15 +01001408 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001409 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001410 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001411 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001412 } else {
1413 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1414 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001415 }
Damien George11de8392014-06-05 18:57:38 +01001416 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001417
1418 case 'd':
1419 case 'i':
1420 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001421 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001422 break;
1423
Damien Georgefb510b32014-06-01 13:32:54 +01001424#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001425 case 'e':
1426 case 'E':
1427 case 'f':
1428 case 'F':
1429 case 'g':
1430 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001431 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001432 break;
1433#endif
1434
1435 case 'o':
1436 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001437 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001438 }
Damien George7f9d1d62015-04-09 23:56:15 +01001439 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001440 break;
1441
1442 case 'r':
1443 case 's':
1444 {
Damien George0b9ee862015-01-21 19:14:25 +00001445 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001446 mp_print_t arg_print;
1447 vstr_init_print(&arg_vstr, 16, &arg_print);
Paul Sokolovskyef63ab52015-12-20 16:44:36 +02001448 mp_print_kind_t print_kind = (*str == 'r' ? PRINT_REPR : PRINT_STR);
1449 if (print_kind == PRINT_STR && is_bytes && MP_OBJ_IS_TYPE(arg, &mp_type_bytes)) {
1450 // If we have something like b"%s" % b"1", bytes arg should be
1451 // printed undecorated.
1452 print_kind = PRINT_RAW;
1453 }
1454 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001455 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001456 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001457 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001458 }
Damien George50912e72015-01-20 11:55:10 +00001459 if (vlen > (uint)prec) {
1460 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001461 }
Damien George7f9d1d62015-04-09 23:56:15 +01001462 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001463 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001464 break;
1465 }
Dave Hylands6756a372014-04-02 11:42:39 -07001466
Dave Hylands6756a372014-04-02 11:42:39 -07001467 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001468 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001469 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001470 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001471
Dave Hylands6756a372014-04-02 11:42:39 -07001472 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001473 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1474 terse_str_format_value_error();
1475 } else {
1476 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1477 "unsupported format character '%c' (0x%x) at index %d",
1478 *str, *str, str - start_str));
1479 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001480 }
1481 }
1482
Damien George963a5a32015-01-16 17:47:07 +00001483 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001484 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001485 }
1486
Paul Sokolovskyd50f6492015-12-20 16:50:51 +02001487 return mp_obj_new_str_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001488}
1489
Paul Sokolovskyf44cc512015-06-26 17:33:21 +03001490// The implementation is optimized, returning the original string if there's
1491// nothing to replace.
Damien Georgeecc88e92014-08-30 00:35:11 +01001492STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001493 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001494
Damien George40f3c022014-07-03 13:25:24 +01001495 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001496 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001497 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001498 if (max_rep == 0) {
1499 return args[0];
1500 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001501 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001502 }
xbe480c15a2014-01-30 22:17:30 -08001503 }
Damien George94f68302014-01-31 23:45:12 +00001504
xbe729be9b2014-04-07 14:46:39 -07001505 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001506
Damien Georgeff715422014-04-07 00:39:13 +01001507 // check argument types
1508
Damien Georgec55a4d82014-12-24 20:28:30 +00001509 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1510
1511 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001512 bad_implicit_conversion(args[1]);
1513 }
1514
Damien Georgec55a4d82014-12-24 20:28:30 +00001515 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001516 bad_implicit_conversion(args[2]);
1517 }
1518
1519 // extract string data
1520
xbe480c15a2014-01-30 22:17:30 -08001521 GET_STR_DATA_LEN(args[0], str, str_len);
1522 GET_STR_DATA_LEN(args[1], old, old_len);
1523 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001524
1525 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001526 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001527 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001528 }
1529
Damien George94f68302014-01-31 23:45:12 +00001530 // data for the replaced string
1531 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001532 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001533
Damien George94f68302014-01-31 23:45:12 +00001534 // do 2 passes over the string:
1535 // first pass computes the required length of the replaced string
1536 // second pass does the replacements
1537 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001538 mp_uint_t replaced_str_index = 0;
1539 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001540 const byte *old_occurrence;
1541 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001542 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001543 if (old_len == 0) {
1544 // if old_str is empty, copy new_str to start of replaced string
1545 // copy the replacement string
1546 if (data != NULL) {
1547 memcpy(data, new, new_len);
1548 }
1549 replaced_str_index += new_len;
1550 num_replacements_done++;
1551 }
Damien George963a5a32015-01-16 17:47:07 +00001552 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 +01001553 if (old_len == 0) {
1554 old_occurrence += 1;
1555 }
Damien George94f68302014-01-31 23:45:12 +00001556 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1557 if (data != NULL) {
1558 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1559 }
1560 replaced_str_index += old_occurrence - offset_ptr;
1561 // copy the replacement string
1562 if (data != NULL) {
1563 memcpy(data + replaced_str_index, new, new_len);
1564 }
1565 replaced_str_index += new_len;
1566 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001567 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001568 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001569 }
1570
1571 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1572 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001573 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001574 }
Damien Georgeff715422014-04-07 00:39:13 +01001575 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001576
1577 if (data == NULL) {
1578 // first pass
1579 if (num_replacements_done == 0) {
1580 // no substr found, return original string
1581 return args[0];
1582 } else {
1583 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001584 vstr_init_len(&vstr, replaced_str_index);
1585 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001586 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001587 }
1588 } else {
1589 // second pass, we are done
1590 break;
1591 }
xbe480c15a2014-01-30 22:17:30 -08001592 }
Damien George94f68302014-01-31 23:45:12 +00001593
Damien George05005f62015-01-21 22:48:37 +00001594 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001595}
1596
Damien Georgeecc88e92014-08-30 00:35:11 +01001597STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001598 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001599 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001600 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1601
1602 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001603 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001604 bad_implicit_conversion(args[1]);
1605 }
xbe9e1e8cd2014-03-12 22:57:16 -07001606
1607 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1608 GET_STR_DATA_LEN(args[1], needle, needle_len);
1609
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001610 const byte *start = haystack;
1611 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001612 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001613 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001614 }
1615 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001616 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001617 }
1618
Damien George536dde22014-03-13 22:07:55 +00001619 // if needle_len is zero then we count each gap between characters as an occurrence
1620 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001621 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001622 }
1623
Damien George536dde22014-03-13 22:07:55 +00001624 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001625 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001626 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1627 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001628 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001629 haystack_ptr += needle_len;
1630 } else {
1631 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001632 }
xbe9e1e8cd2014-03-12 22:57:16 -07001633 }
1634
1635 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1636}
1637
Damien George40f3c022014-07-03 13:25:24 +01001638STATIC 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 +00001639 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001640 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1641 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001642 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001643 }
Damien Georgeb035db32014-03-21 20:39:40 +00001644
xbe613a8e32014-03-18 00:06:29 -07001645 GET_STR_DATA_LEN(self_in, str, str_len);
1646 GET_STR_DATA_LEN(arg, sep, sep_len);
1647
1648 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001649 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001650 }
Damien Georgeb035db32014-03-21 20:39:40 +00001651
Damien Georgec55a4d82014-12-24 20:28:30 +00001652 mp_obj_t result[3];
1653 if (self_type == &mp_type_str) {
1654 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1655 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1656 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1657 } else {
1658 result[0] = mp_const_empty_bytes;
1659 result[1] = mp_const_empty_bytes;
1660 result[2] = mp_const_empty_bytes;
1661 }
Damien Georgeb035db32014-03-21 20:39:40 +00001662
1663 if (direction > 0) {
1664 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001665 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001666 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001667 }
xbe613a8e32014-03-18 00:06:29 -07001668
xbe17a5a832014-03-23 23:31:58 -07001669 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1670 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001671 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001672 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001673 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001674 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 -07001675 }
Damien Georgeb035db32014-03-21 20:39:40 +00001676
xbe0a6894c2014-03-21 01:12:26 -07001677 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001678}
1679
Damien Georgeb035db32014-03-21 20:39:40 +00001680STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1681 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001682}
xbe4504ea82014-03-19 00:46:14 -07001683
Damien Georgeb035db32014-03-21 20:39:40 +00001684STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1685 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001686}
1687
Paul Sokolovsky69135212014-05-10 19:47:41 +03001688// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001689STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001690 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001691 vstr_t vstr;
1692 vstr_init_len(&vstr, self_len);
1693 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +01001694 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001695 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001696 }
Damien George05005f62015-01-21 22:48:37 +00001697 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001698}
1699
1700STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001701 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001702}
1703
1704STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001705 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001706}
1707
Damien Georgefcc9cf62014-06-01 18:22:09 +01001708STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001709 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001710
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001711 if (self_len == 0) {
1712 return mp_const_false; // default to False for empty str
1713 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001714
Damien Georgefcc9cf62014-06-01 18:22:09 +01001715 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001716 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001717 if (!f(*self_data++)) {
1718 return mp_const_false;
1719 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001720 }
1721 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001722 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001723
Damien George39dc1452014-10-03 19:52:22 +01001724 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001725 if (unichar_isalpha(*self_data++)) {
1726 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001727 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1728 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001729 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001730 }
1731 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001732
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001733 if (!contains_alpha) {
1734 return mp_const_false;
1735 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001736 }
1737
1738 return mp_const_true;
1739}
1740
1741STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001742 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001743}
1744
1745STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001746 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001747}
1748
1749STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001750 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001751}
1752
1753STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001754 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001755}
1756
1757STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001758 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001759}
1760
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001761#if MICROPY_CPYTHON_COMPAT
1762// These methods are superfluous in the presense of str() and bytes()
1763// constructors.
1764// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001765STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001766 mp_obj_t new_args[2];
1767 if (n_args == 1) {
1768 new_args[0] = args[0];
1769 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1770 args = new_args;
1771 n_args++;
1772 }
Damien George999cedb2015-11-27 17:01:44 +00001773 return mp_obj_str_make_new(MP_OBJ_FROM_PTR(&mp_type_str), n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001774}
1775
1776// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001777STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001778 mp_obj_t new_args[2];
1779 if (n_args == 1) {
1780 new_args[0] = args[0];
1781 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1782 args = new_args;
1783 n_args++;
1784 }
Damien George999cedb2015-11-27 17:01:44 +00001785 return bytes_make_new(MP_OBJ_NULL, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001786}
1787#endif
1788
Damien George4d917232014-08-30 14:28:06 +01001789mp_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 +01001790 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001791 GET_STR_DATA_LEN(self_in, str_data, str_len);
1792 bufinfo->buf = (void*)str_data;
1793 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001794 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001795 return 0;
1796 } else {
1797 // can't write to a string
1798 bufinfo->buf = NULL;
1799 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001800 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001801 return 1;
1802 }
1803}
1804
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001805#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001806MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1807MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001808#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001809MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1810MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1811MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1812MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1813MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Paul Sokolovsky87051712015-03-23 22:15:12 +02001814MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001815#if MICROPY_PY_BUILTINS_STR_SPLITLINES
1816MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
1817#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001818MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1819MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1820MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1821MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1822MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1823MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001824MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001825MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1826MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1827MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1828MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1829MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1830MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1831MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1832MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1833MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1834MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1835MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001836
Damien Georgecbf76742015-11-27 13:38:15 +00001837STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001838#if MICROPY_CPYTHON_COMPAT
Damien Georgecbf76742015-11-27 13:38:15 +00001839 { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001840 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1841 // If we have separate unicode type, then here we have methods only
1842 // for bytes type, and it should not have encode() methods. Otherwise,
1843 // we have non-compliant-but-practical bytestring type, which shares
1844 // method table with bytes, so they both have encode() and decode()
1845 // methods (which should do type checking at runtime).
Damien Georgecbf76742015-11-27 13:38:15 +00001846 { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001847 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001848#endif
Damien Georgecbf76742015-11-27 13:38:15 +00001849 { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) },
1850 { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) },
1851 { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) },
1852 { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&str_rindex_obj) },
1853 { MP_ROM_QSTR(MP_QSTR_join), MP_ROM_PTR(&str_join_obj) },
1854 { MP_ROM_QSTR(MP_QSTR_split), MP_ROM_PTR(&str_split_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001855 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
Damien Georgecbf76742015-11-27 13:38:15 +00001856 { MP_ROM_QSTR(MP_QSTR_splitlines), MP_ROM_PTR(&str_splitlines_obj) },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001857 #endif
Damien Georgecbf76742015-11-27 13:38:15 +00001858 { MP_ROM_QSTR(MP_QSTR_rsplit), MP_ROM_PTR(&str_rsplit_obj) },
1859 { MP_ROM_QSTR(MP_QSTR_startswith), MP_ROM_PTR(&str_startswith_obj) },
1860 { MP_ROM_QSTR(MP_QSTR_endswith), MP_ROM_PTR(&str_endswith_obj) },
1861 { MP_ROM_QSTR(MP_QSTR_strip), MP_ROM_PTR(&str_strip_obj) },
1862 { MP_ROM_QSTR(MP_QSTR_lstrip), MP_ROM_PTR(&str_lstrip_obj) },
1863 { MP_ROM_QSTR(MP_QSTR_rstrip), MP_ROM_PTR(&str_rstrip_obj) },
1864 { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&str_format_obj) },
1865 { MP_ROM_QSTR(MP_QSTR_replace), MP_ROM_PTR(&str_replace_obj) },
1866 { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&str_count_obj) },
1867 { MP_ROM_QSTR(MP_QSTR_partition), MP_ROM_PTR(&str_partition_obj) },
1868 { MP_ROM_QSTR(MP_QSTR_rpartition), MP_ROM_PTR(&str_rpartition_obj) },
1869 { MP_ROM_QSTR(MP_QSTR_lower), MP_ROM_PTR(&str_lower_obj) },
1870 { MP_ROM_QSTR(MP_QSTR_upper), MP_ROM_PTR(&str_upper_obj) },
1871 { MP_ROM_QSTR(MP_QSTR_isspace), MP_ROM_PTR(&str_isspace_obj) },
1872 { MP_ROM_QSTR(MP_QSTR_isalpha), MP_ROM_PTR(&str_isalpha_obj) },
1873 { MP_ROM_QSTR(MP_QSTR_isdigit), MP_ROM_PTR(&str_isdigit_obj) },
1874 { MP_ROM_QSTR(MP_QSTR_isupper), MP_ROM_PTR(&str_isupper_obj) },
1875 { MP_ROM_QSTR(MP_QSTR_islower), MP_ROM_PTR(&str_islower_obj) },
ian-v7a16fad2014-01-06 09:52:29 -08001876};
Damien George97209d32014-01-07 15:58:30 +00001877
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001878STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001879
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001880#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George44e7cbf2015-05-17 16:44:24 +01001881STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
1882
Damien George3e1a5c12014-03-29 13:43:38 +00001883const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001884 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001885 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001886 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001887 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001888 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001889 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001890 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001891 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001892 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001893};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001894#endif
Damiend99b0522013-12-21 18:17:45 +00001895
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001896// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001897const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001898 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001899 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001900 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001901 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001902 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001903 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001904 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001905 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George999cedb2015-11-27 17:01:44 +00001906 .locals_dict = (mp_obj_dict_t*)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001907};
1908
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001909// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001910const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001911
Damien George77089be2015-01-21 23:08:36 +00001912// Create a str/bytes object using the given data. New memory is allocated and
1913// the data is copied across.
Damien George999cedb2015-11-27 17:01:44 +00001914mp_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 +02001915 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001916 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001917 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001918 if (data) {
1919 o->hash = qstr_compute_hash(data, len);
1920 byte *p = m_new(byte, len + 1);
1921 o->data = p;
1922 memcpy(p, data, len * sizeof(byte));
1923 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1924 }
Damien George999cedb2015-11-27 17:01:44 +00001925 return MP_OBJ_FROM_PTR(o);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001926}
1927
Damien George77089be2015-01-21 23:08:36 +00001928// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1929// the exact length required and then reused for the str/bytes object. The vstr
1930// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001931mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1932 // if not a bytes object, look if a qstr with this data already exists
1933 if (type == &mp_type_str) {
1934 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1935 if (q != MP_QSTR_NULL) {
1936 vstr_clear(vstr);
1937 vstr->alloc = 0;
1938 return MP_OBJ_NEW_QSTR(q);
1939 }
1940 }
1941
1942 // make a new str/bytes object
1943 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1944 o->base.type = type;
1945 o->len = vstr->len;
1946 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
Dave Hylands9f76dcd2015-05-18 13:25:36 -07001947 if (vstr->len + 1 == vstr->alloc) {
1948 o->data = (byte*)vstr->buf;
1949 } else {
1950 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
1951 }
Damien George0d3cb672015-01-28 23:43:01 +00001952 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00001953 vstr->buf = NULL;
1954 vstr->alloc = 0;
Damien George999cedb2015-11-27 17:01:44 +00001955 return MP_OBJ_FROM_PTR(o);
Damien George0b9ee862015-01-21 19:14:25 +00001956}
1957
Damien Georged182b982014-08-30 14:19:41 +01001958mp_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 +01001959 if (make_qstr_if_not_already) {
1960 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001961 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001962 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001963 qstr q = qstr_find_strn(data, len);
1964 if (q != MP_QSTR_NULL) {
1965 // qstr with this data already exists
1966 return MP_OBJ_NEW_QSTR(q);
1967 } else {
1968 // no existing qstr, don't make one
1969 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1970 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001971 }
Damien George5fa93b62014-01-22 14:35:10 +00001972}
1973
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001974mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1975 GET_STR_DATA_LEN(str, data, len);
1976 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1977}
1978
Damien Georged182b982014-08-30 14:19:41 +01001979mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001980 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001981}
1982
Damien George5fa93b62014-01-22 14:35:10 +00001983bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1984 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1985 return s1 == s2;
1986 } else {
1987 GET_STR_HASH(s1, h1);
1988 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001989 // If any of hashes is 0, it means it's not valid
1990 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001991 return false;
1992 }
1993 GET_STR_DATA_LEN(s1, d1, l1);
1994 GET_STR_DATA_LEN(s2, d2, l2);
1995 if (l1 != l2) {
1996 return false;
1997 }
Damien George1e708fe2014-01-23 18:27:51 +00001998 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001999 }
Damien George5fa93b62014-01-22 14:35:10 +00002000}
2001
Damien Georgedeed0872014-04-06 11:11:15 +01002002STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00002003 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
2004 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
2005 "can't convert to str implicitly"));
2006 } else {
2007 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
2008 "can't convert '%s' object to str implicitly",
2009 mp_obj_get_type_str(self_in)));
2010 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00002011}
2012
Damien Georgeb829b5c2014-01-25 13:51:19 +00002013// use this if you will anyway convert the string to a qstr
2014// will be more efficient for the case where it's already a qstr
2015qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
2016 if (MP_OBJ_IS_QSTR(self_in)) {
2017 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002018 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien George999cedb2015-11-27 17:01:44 +00002019 mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in);
Damien Georgeb829b5c2014-01-25 13:51:19 +00002020 return qstr_from_strn((char*)self->data, self->len);
2021 } else {
2022 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002023 }
2024}
2025
2026// only use this function if you need the str data to be zero terminated
2027// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2028const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002029 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002030 GET_STR_DATA_LEN(self_in, s, l);
2031 (void)l; // len unused
2032 return (const char*)s;
2033 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002034 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002035 }
2036}
2037
Damien Georged182b982014-08-30 14:19:41 +01002038const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002039 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002040 GET_STR_DATA_LEN(self_in, s, l);
2041 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002042 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002043 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002044 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002045 }
Damiend99b0522013-12-21 18:17:45 +00002046}
xyb8cfc9f02014-01-05 18:47:51 +08002047
Damien George04353cc2015-10-18 23:09:04 +01002048#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C
Damien Georgec3f64d92015-11-27 12:23:18 +00002049const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) {
Damien George04353cc2015-10-18 23:09:04 +01002050 if (MP_OBJ_IS_QSTR(self_in)) {
2051 return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len);
2052 } else {
2053 *len = ((mp_obj_str_t*)self_in)->len;
2054 return ((mp_obj_str_t*)self_in)->data;
2055 }
2056}
2057#endif
2058
xyb8cfc9f02014-01-05 18:47:51 +08002059/******************************************************************************/
2060/* str iterator */
2061
Damien George44e7cbf2015-05-17 16:44:24 +01002062typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002063 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002064 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002065 mp_uint_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002066} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002067
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002068#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002069STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002070 mp_obj_str8_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002071 GET_STR_DATA_LEN(self->str, str, len);
2072 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002073 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002074 self->cur += 1;
2075 return o_out;
2076 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002077 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002078 }
2079}
2080
Damien George3e1a5c12014-03-29 13:43:38 +00002081STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002082 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002083 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002084 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002085 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002086};
2087
Damien George44e7cbf2015-05-17 16:44:24 +01002088STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2089 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002090 o->base.type = &mp_type_str_it;
2091 o->str = str;
2092 o->cur = 0;
2093 return o;
2094}
2095#endif
2096
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002097STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George999cedb2015-11-27 17:01:44 +00002098 mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002099 GET_STR_DATA_LEN(self->str, str, len);
2100 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002101 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002102 self->cur += 1;
2103 return o_out;
2104 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002105 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002106 }
2107}
2108
Damien George3e1a5c12014-03-29 13:43:38 +00002109STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002110 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002111 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002112 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002113 .iternext = bytes_it_iternext,
2114};
2115
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002116mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
Damien George44e7cbf2015-05-17 16:44:24 +01002117 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002118 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002119 o->str = str;
2120 o->cur = 0;
Damien George999cedb2015-11-27 17:01:44 +00002121 return MP_OBJ_FROM_PTR(o);
xyb8cfc9f02014-01-05 18:47:51 +08002122}