blob: 0246262a518a31544cf7f8bba1f0fb2fb57f5a7c [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 George7f9d1d62015-04-09 23:56:15 +010086void mp_str_print_json(const mp_print_t *print, const byte *str_data, mp_uint_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 Georgecde0ca22014-09-25 17:35:56 +0100119 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200120 if (kind == PRINT_STR && !is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100121 mp_printf(print, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200122 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200123 if (is_bytes) {
Damien George7f9d1d62015-04-09 23:56:15 +0100124 mp_print_str(print, "b");
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200125 }
Damien George7f9d1d62015-04-09 23:56:15 +0100126 mp_str_print_quoted(print, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200127 }
Damiend99b0522013-12-21 18:17:45 +0000128}
129
Paul Sokolovsky344e15b2015-01-23 02:15:56 +0200130mp_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 +0300131#if MICROPY_CPYTHON_COMPAT
132 if (n_kw != 0) {
133 mp_arg_error_unimpl_kw();
134 }
135#endif
136
Damien George1e9a92f2014-11-06 17:36:16 +0000137 mp_arg_check_num(n_args, n_kw, 0, 3, false);
138
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200139 switch (n_args) {
140 case 0:
141 return MP_OBJ_NEW_QSTR(MP_QSTR_);
142
Damien George1e9a92f2014-11-06 17:36:16 +0000143 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000144 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100145 mp_print_t print;
146 vstr_init_print(&vstr, 16, &print);
147 mp_obj_print_helper(&print, args[0], PRINT_STR);
Damien George0b9ee862015-01-21 19:14:25 +0000148 return mp_obj_new_str_from_vstr(type_in, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200149 }
150
Damien George1e9a92f2014-11-06 17:36:16 +0000151 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200152 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200153 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
154 GET_STR_DATA_LEN(args[0], str_data, str_len);
155 GET_STR_HASH(args[0], str_hash);
Damien George0b9ee862015-01-21 19:14:25 +0000156 mp_obj_str_t *o = mp_obj_new_str_of_type(type_in, NULL, str_len);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200157 o->data = str_data;
158 o->hash = str_hash;
159 return o;
160 } else {
161 mp_buffer_info_t bufinfo;
162 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
163 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200164 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200165 }
166}
167
Damien Georgeecc88e92014-08-30 00:35:11 +0100168STATIC 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 +0000169 (void)type_in;
170
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200171 if (n_args == 0) {
172 return mp_const_empty_bytes;
173 }
174
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300175#if MICROPY_CPYTHON_COMPAT
176 if (n_kw != 0) {
177 mp_arg_error_unimpl_kw();
178 }
179#endif
180
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200181 if (MP_OBJ_IS_STR(args[0])) {
182 if (n_args < 2 || n_args > 3) {
183 goto wrong_args;
184 }
185 GET_STR_DATA_LEN(args[0], str_data, str_len);
186 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100187 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200188 o->data = str_data;
189 o->hash = str_hash;
190 return o;
191 }
192
193 if (n_args > 1) {
194 goto wrong_args;
195 }
196
197 if (MP_OBJ_IS_SMALL_INT(args[0])) {
198 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000199 vstr_t vstr;
200 vstr_init_len(&vstr, len);
201 memset(vstr.buf, 0, len);
202 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200203 }
204
Damien George32ef3a32014-12-04 15:46:14 +0000205 // check if argument has the buffer protocol
206 mp_buffer_info_t bufinfo;
207 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
208 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
209 }
210
Damien George0b9ee862015-01-21 19:14:25 +0000211 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200212 // Try to create array of exact len if initializer len is known
213 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
214 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000215 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000217 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000218 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200219 }
220
Damien Georged17926d2014-03-30 13:35:08 +0100221 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200222 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100223 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien Georgeede0f3a2015-04-23 15:28:18 +0100224 mp_int_t val = mp_obj_get_int(item);
225 #if MICROPY_CPYTHON_COMPAT
226 if (val < 0 || val > 255) {
227 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bytes value out of range"));
228 }
229 #endif
230 vstr_add_byte(&vstr, val);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200231 }
232
Damien George0b9ee862015-01-21 19:14:25 +0000233 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200234
235wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000236 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200237}
238
Damien George55baff42014-01-21 21:40:13 +0000239// like strstr but with specified length and allows \0 bytes
240// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100241STATIC 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 +0000242 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100243 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700244 if (direction > 0) {
245 str_index = 0;
246 str_index_end = hlen - nlen;
247 } else {
248 str_index = hlen - nlen;
249 str_index_end = 0;
250 }
251 for (;;) {
252 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
253 //found
254 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000255 }
xbe17a5a832014-03-23 23:31:58 -0700256 if (str_index == str_index_end) {
257 //not found
258 break;
Damien George55baff42014-01-21 21:40:13 +0000259 }
xbe17a5a832014-03-23 23:31:58 -0700260 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000261 }
262 }
263 return NULL;
264}
265
Damien Georgea75b02e2014-08-27 09:20:30 +0100266// Note: this function is used to check if an object is a str or bytes, which
267// works because both those types use it as their binary_op method. Revisit
268// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100269mp_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 +0000270 // check for modulo
271 if (op == MP_BINARY_OP_MODULO) {
272 mp_obj_t *args;
273 mp_uint_t n_args;
274 mp_obj_t dict = MP_OBJ_NULL;
275 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
276 // TODO: Support tuple subclasses?
277 mp_obj_tuple_get(rhs_in, &n_args, &args);
278 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
279 args = NULL;
280 n_args = 0;
281 dict = rhs_in;
282 } else {
283 args = &rhs_in;
284 n_args = 1;
285 }
286 return str_modulo_format(lhs_in, n_args, args, dict);
287 }
288
289 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300290 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000291 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
292
293 // check for multiply
294 if (op == MP_BINARY_OP_MULTIPLY) {
295 mp_int_t n;
296 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
297 return MP_OBJ_NULL; // op not supported
298 }
299 if (n <= 0) {
300 if (lhs_type == &mp_type_str) {
301 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
302 } else {
303 return mp_const_empty_bytes;
304 }
305 }
Damien George05005f62015-01-21 22:48:37 +0000306 vstr_t vstr;
307 vstr_init_len(&vstr, lhs_len * n);
308 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
309 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000310 }
311
312 // From now on all operations allow:
313 // - str with str
314 // - bytes with bytes
315 // - bytes with bytearray
316 // - bytes with array.array
317 // To do this efficiently we use the buffer protocol to extract the raw
318 // data for the rhs, but only if the lhs is a bytes object.
319 //
320 // NOTE: CPython does not allow comparison between bytes ard array.array
321 // (even if the array is of type 'b'), even though it allows addition of
322 // such types. We are not compatible with this (we do allow comparison
323 // of bytes with anything that has the buffer protocol). It would be
324 // easy to "fix" this with a bit of extra logic below, but it costs code
325 // size and execution time so we don't.
326
327 const byte *rhs_data;
328 mp_uint_t rhs_len;
329 if (lhs_type == mp_obj_get_type(rhs_in)) {
330 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
331 rhs_data = rhs_data_;
332 rhs_len = rhs_len_;
333 } else if (lhs_type == &mp_type_bytes) {
334 mp_buffer_info_t bufinfo;
335 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000336 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000337 }
338 rhs_data = bufinfo.buf;
339 rhs_len = bufinfo.len;
340 } else {
341 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000342 return MP_OBJ_NULL; // op not supported
343 }
344
Damiend99b0522013-12-21 18:17:45 +0000345 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100346 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000347 case MP_BINARY_OP_INPLACE_ADD: {
Damien George05005f62015-01-21 22:48:37 +0000348 vstr_t vstr;
349 vstr_init_len(&vstr, lhs_len + rhs_len);
350 memcpy(vstr.buf, lhs_data, lhs_len);
351 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
352 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200353 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200354
Damien Georgea65c03c2014-11-05 16:30:34 +0000355 case MP_BINARY_OP_IN:
356 /* NOTE `a in b` is `b.__contains__(a)` */
357 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300358
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300359 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
360 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 +0100361 case MP_BINARY_OP_LESS:
362 case MP_BINARY_OP_LESS_EQUAL:
363 case MP_BINARY_OP_MORE:
364 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000365 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000366 }
367
Damien George6ac5dce2014-05-21 19:42:43 +0100368 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000369}
370
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300371#if !MICROPY_PY_BUILTINS_STR_UNICODE
372// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100373const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, mp_uint_t self_len,
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300374 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100375 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300376 return self_data + index_val;
377}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300378#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300379
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300380// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
381STATIC 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 +0300382 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100383 GET_STR_DATA_LEN(self_in, self_data, self_len);
384 if (value == MP_OBJ_SENTINEL) {
385 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100386#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100387 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300388 mp_bound_slice_t slice;
389 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300390 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100391 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100392 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100393 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100394 }
395#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300396 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100397 // If we have unicode enabled the type will always be bytes, so take the short cut.
398 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300399 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100400 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300401 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100402 }
403 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100404 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100405 }
406}
407
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200408STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700409 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300410 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000411
Damien Georgefe8fb912014-01-02 16:36:09 +0000412 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000413 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000414
415 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100416 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000417 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000418 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000419 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000420 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100421 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
422 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300423 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100424 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
425 }
426 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000427 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000428
429 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100430 mp_uint_t required_len = 0;
431 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300432 if (mp_obj_get_type(seq_items[i]) != self_type) {
433 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
434 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000435 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000436 if (i > 0) {
437 required_len += sep_len;
438 }
Damien George5fa93b62014-01-22 14:35:10 +0000439 GET_STR_LEN(seq_items[i], l);
440 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000441 }
442
443 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000444 vstr_t vstr;
445 vstr_init_len(&vstr, required_len);
446 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +0100447 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000448 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000449 memcpy(data, sep_str, sep_len);
450 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000451 }
Damien George5fa93b62014-01-22 14:35:10 +0000452 GET_STR_DATA_LEN(seq_items[i], s, l);
453 memcpy(data, s, l);
454 data += l;
Damiend99b0522013-12-21 18:17:45 +0000455 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000456
457 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000458 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000459}
460
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300461enum {SPLIT = 0, KEEP = 1, SPLITLINES = 2};
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200462
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300463STATIC 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 +0300464 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100465 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200466 mp_obj_t sep = mp_const_none;
467 if (n_args > 1) {
468 sep = args[1];
469 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100470 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200471 }
472 }
Damien Georgedeed0872014-04-06 11:11:15 +0100473
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200474 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000475 GET_STR_DATA_LEN(args[0], s, len);
476 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200477
Damien Georgedeed0872014-04-06 11:11:15 +0100478 if (sep == mp_const_none) {
479 // sep not given, so separate on whitespace
480
481 // Initial whitespace is not counted as split, so we pre-do it
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300482 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100483 while (s < top && splits != 0) {
484 const byte *start = s;
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300485 while (s < top && !unichar_isspace(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100486 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100487 if (s >= top) {
488 break;
489 }
Paul Sokolovsky8b7faa32015-04-12 00:17:16 +0300490 while (s < top && unichar_isspace(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100491 if (splits > 0) {
492 splits--;
493 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200494 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200495
Damien Georgedeed0872014-04-06 11:11:15 +0100496 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100497 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100498 }
499
500 } else {
501 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300502 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000503 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300504 }
Damien Georgedeed0872014-04-06 11:11:15 +0100505
Damien Georged182b982014-08-30 14:19:41 +0100506 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100507 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
508
509 if (sep_len == 0) {
510 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
511 }
512
513 for (;;) {
514 const byte *start = s;
515 for (;;) {
516 if (splits == 0 || s + sep_len > top) {
517 s = top;
518 break;
519 } else if (memcmp(s, sep_str, sep_len) == 0) {
520 break;
521 }
522 s++;
523 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300524 mp_uint_t sub_len = s - start;
Paul Sokolovsky7f59b4b2015-04-04 01:55:40 +0300525 if (MP_LIKELY(!(sub_len == 0 && s == top && (type && SPLITLINES)))) {
526 if (start + sub_len != top && (type & KEEP)) {
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300527 sub_len++;
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300528 }
Paul Sokolovskyacf6aec2015-04-04 01:23:18 +0300529 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, sub_len));
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300530 }
Damien Georgedeed0872014-04-06 11:11:15 +0100531 if (s >= top) {
532 break;
533 }
534 s += sep_len;
535 if (splits > 0) {
536 splits--;
537 }
538 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200539 }
540
541 return res;
542}
543
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +0300544mp_obj_t mp_obj_str_split(mp_uint_t n_args, const mp_obj_t *args) {
545 return str_split_internal(n_args, args, SPLIT);
546}
547
548#if MICROPY_PY_BUILTINS_STR_SPLITLINES
549STATIC mp_obj_t str_splitlines(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
550 static const mp_arg_t allowed_args[] = {
551 { MP_QSTR_keepends, MP_ARG_BOOL, {.u_bool = false} },
552 };
553
554 // parse args
555 mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
556 mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
557
558 mp_obj_t new_args[2] = {pos_args[0], MP_OBJ_NEW_QSTR(MP_QSTR__backslash_n)};
559 return str_split_internal(2, new_args, SPLITLINES | (args[0].u_bool ? KEEP : 0));
560}
561#endif
562
Damien Georgeecc88e92014-08-30 00:35:11 +0100563STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300564 if (n_args < 3) {
565 // If we don't have split limit, it doesn't matter from which side
566 // we split.
Paul Sokolovsky87051712015-03-23 22:15:12 +0200567 return mp_obj_str_split(n_args, args);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300568 }
569 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
570 mp_obj_t sep = args[1];
571 GET_STR_DATA_LEN(args[0], s, len);
572
Damien George40f3c022014-07-03 13:25:24 +0100573 mp_int_t splits = mp_obj_get_int(args[2]);
574 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300575 // Preallocate list to the max expected # of elements, as we
576 // will fill it from the end.
577 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100578 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300579
580 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000581 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300582 } else {
Damien Georged182b982014-08-30 14:19:41 +0100583 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300584 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
585
586 if (sep_len == 0) {
587 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
588 }
589
590 const byte *beg = s;
591 const byte *last = s + len;
592 for (;;) {
593 s = last - sep_len;
594 for (;;) {
595 if (splits == 0 || s < beg) {
596 break;
597 } else if (memcmp(s, sep_str, sep_len) == 0) {
598 break;
599 }
600 s--;
601 }
602 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100603 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300604 break;
605 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100606 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 +0300607 last = s;
608 if (splits > 0) {
609 splits--;
610 }
611 }
612 if (idx != 0) {
613 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100614 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100615 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300616 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
617 res->len = used;
618 }
619 }
620
621 return res;
622}
623
Damien Georgeecc88e92014-08-30 00:35:11 +0100624STATIC 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 +0300625 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000626 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000627 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
628
629 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000630 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000631 bad_implicit_conversion(args[1]);
632 }
John R. Lentone8204912014-01-12 21:53:52 +0000633
Damien George5fa93b62014-01-22 14:35:10 +0000634 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
635 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000636
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300637 const byte *start = haystack;
638 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000639 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300640 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000641 }
642 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300643 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000644 }
645
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300646 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000647 if (p == NULL) {
648 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700649 if (is_index) {
650 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
651 } else {
652 return MP_OBJ_NEW_SMALL_INT(-1);
653 }
Damien George23005372014-01-13 19:39:01 +0000654 } else {
655 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300656 #if MICROPY_PY_BUILTINS_STR_UNICODE
657 if (self_type == &mp_type_str) {
658 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
659 }
660 #endif
xbe17a5a832014-03-23 23:31:58 -0700661 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000662 }
John R. Lentone8204912014-01-12 21:53:52 +0000663}
664
Damien Georgeecc88e92014-08-30 00:35:11 +0100665STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700666 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700667}
668
Damien Georgeecc88e92014-08-30 00:35:11 +0100669STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700670 return str_finder(n_args, args, -1, false);
671}
672
Damien Georgeecc88e92014-08-30 00:35:11 +0100673STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700674 return str_finder(n_args, args, 1, true);
675}
676
Damien Georgeecc88e92014-08-30 00:35:11 +0100677STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700678 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700679}
680
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200681// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100682STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300683 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300684 GET_STR_DATA_LEN(args[0], str, str_len);
685 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300686 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300687 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300688 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300689 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300690 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200691 return mp_const_false;
692 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300693 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200694}
695
Damien Georgeecc88e92014-08-30 00:35:11 +0100696STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300697 GET_STR_DATA_LEN(args[0], str, str_len);
698 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
699 assert(n_args == 2);
700
701 if (suffix_len > str_len) {
702 return mp_const_false;
703 }
704 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
705}
706
Paul Sokolovsky88107842014-04-26 06:20:08 +0300707enum { LSTRIP, RSTRIP, STRIP };
708
Damien Georgeecc88e92014-08-30 00:35:11 +0100709STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800710 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700711 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300712 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000713
714 const byte *chars_to_del;
715 uint chars_to_del_len;
716 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800717
718 if (n_args == 1) {
719 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000720 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800721 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300722 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000723 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300724 }
Damien George5fa93b62014-01-22 14:35:10 +0000725 GET_STR_DATA_LEN(args[1], s, l);
726 chars_to_del = s;
727 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800728 }
729
Damien George5fa93b62014-01-22 14:35:10 +0000730 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800731
Damien George40f3c022014-07-03 13:25:24 +0100732 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800733 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100734 mp_uint_t last_good_char_pos = 0;
735 mp_uint_t i = 0;
736 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300737 if (type == RSTRIP) {
738 i = orig_str_len - 1;
739 delta = -1;
740 }
Damien George40f3c022014-07-03 13:25:24 +0100741 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700742 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800743 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300744 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800745 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300746 if (type == LSTRIP) {
747 last_good_char_pos = orig_str_len - 1;
748 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300749 } else if (type == RSTRIP) {
750 first_good_char_pos = 0;
751 last_good_char_pos = i;
752 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300753 }
xbe7b0f39f2014-01-08 14:23:45 -0800754 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300755 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800756 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300757 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800758 }
759
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300760 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000761 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000762 if (self_type == &mp_type_str) {
763 return MP_OBJ_NEW_QSTR(MP_QSTR_);
764 } else {
765 return mp_const_empty_bytes;
766 }
xbe7b0f39f2014-01-08 14:23:45 -0800767 }
768
769 assert(last_good_char_pos >= first_good_char_pos);
770 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100771 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300772 if (stripped_len == orig_str_len) {
773 // If nothing was stripped, don't bother to dup original string
774 // TODO: watch out for this case when we'll get to bytearray.strip()
775 assert(first_good_char_pos == 0);
776 return args[0];
777 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100778 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800779}
780
Damien Georgeecc88e92014-08-30 00:35:11 +0100781STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300782 return str_uni_strip(STRIP, n_args, args);
783}
784
Damien Georgeecc88e92014-08-30 00:35:11 +0100785STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300786 return str_uni_strip(LSTRIP, n_args, args);
787}
788
Damien Georgeecc88e92014-08-30 00:35:11 +0100789STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300790 return str_uni_strip(RSTRIP, n_args, args);
791}
792
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700793// Takes an int arg, but only parses unsigned numbers, and only changes
794// *num if at least one digit was parsed.
Damien George2801e6f2015-04-04 15:53:11 +0100795STATIC int str_to_int(const char *str, int *num) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700796 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000797 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700798 *num = 0;
799 do {
800 *num = *num * 10 + (*s - '0');
801 s++;
802 }
Damien George81836c22014-12-21 21:07:03 +0000803 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700804 }
805 return s - str;
806}
807
Damien George2801e6f2015-04-04 15:53:11 +0100808STATIC bool isalignment(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700809 return ch && strchr("<>=^", ch) != NULL;
810}
811
Damien George2801e6f2015-04-04 15:53:11 +0100812STATIC bool istype(char ch) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700813 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
814}
815
Damien George2801e6f2015-04-04 15:53:11 +0100816STATIC bool arg_looks_integer(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700817 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
818}
819
Damien George2801e6f2015-04-04 15:53:11 +0100820STATIC bool arg_looks_numeric(mp_obj_t arg) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700821 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100822#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700823 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
824#endif
825 ;
826}
827
Damien George2801e6f2015-04-04 15:53:11 +0100828STATIC mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100829#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700830 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Paul Sokolovsky2c756652014-12-31 02:20:57 +0200831 return mp_obj_new_int_from_float(mp_obj_get_float(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700832 }
833#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700834 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700835}
836
Damien George1e9a92f2014-11-06 17:36:16 +0000837STATIC NORETURN void terse_str_format_value_error(void) {
838 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
839}
840
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200841mp_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 +0000842 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000843
Damien George5fa93b62014-01-22 14:35:10 +0000844 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700845 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +0000846 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +0100847 mp_print_t print;
848 vstr_init_print(&vstr, 16, &print);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700849
Damien George5fa93b62014-01-22 14:35:10 +0000850 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700851 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000852 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700853 if (str < top && *str == '}') {
Damien George0b9ee862015-01-21 19:14:25 +0000854 vstr_add_char(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700855 continue;
856 }
Damien George1e9a92f2014-11-06 17:36:16 +0000857 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
858 terse_str_format_value_error();
859 } else {
860 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
861 "single '}' encountered in format string"));
862 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700863 }
864 if (*str != '{') {
Damien George0b9ee862015-01-21 19:14:25 +0000865 vstr_add_char(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700866 continue;
867 }
868
869 str++;
870 if (str < top && *str == '{') {
Damien George0b9ee862015-01-21 19:14:25 +0000871 vstr_add_char(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872 continue;
873 }
874
875 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
876
877 vstr_t *field_name = NULL;
878 char conversion = '\0';
879 vstr_t *format_spec = NULL;
880
881 if (str < top && *str != '}' && *str != '!' && *str != ':') {
882 field_name = vstr_new();
883 while (str < top && *str != '}' && *str != '!' && *str != ':') {
884 vstr_add_char(field_name, *str++);
885 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700886 }
887
888 // conversion ::= "r" | "s"
889
890 if (str < top && *str == '!') {
891 str++;
892 if (str < top && (*str == 'r' || *str == 's')) {
893 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200894 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000895 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
896 terse_str_format_value_error();
897 } else {
898 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
899 "end of format while looking for conversion specifier"));
900 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700901 }
902 }
903
904 if (str < top && *str == ':') {
905 str++;
906 // {:} is the same as {}, which is the same as {!s}
907 // This makes a difference when passing in a True or False
908 // '{}'.format(True) returns 'True'
909 // '{:d}'.format(True) returns '1'
910 // So we treat {:} as {} and this later gets treated to be {!s}
911 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100912 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700913 while (str < top && *str != '}') {
914 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000915 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700916 }
917 }
918 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000919 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
920 terse_str_format_value_error();
921 } else {
922 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
923 "unmatched '{' in format"));
924 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700925 }
926 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000927 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
928 terse_str_format_value_error();
929 } else {
930 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
931 "expected ':' after format specifier"));
932 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700933 }
934
935 mp_obj_t arg = mp_const_none;
936
937 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100938 int index = 0;
Damien George827b0f72015-01-29 13:57:23 +0000939 const char *field = vstr_null_terminated_str(field_name);
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200940 const char *lookup = NULL;
941 if (MP_LIKELY(unichar_isdigit(*field))) {
942 if (arg_i > 0) {
943 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
944 terse_str_format_value_error();
945 } else {
946 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
947 "can't switch from automatic field numbering to manual field specification"));
948 }
949 }
Paul Sokolovskyff8e35b2015-01-04 13:23:44 +0200950 lookup = str_to_int(field, &index) + field;
Damien George963a5a32015-01-16 17:47:07 +0000951 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200952 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
953 }
954 arg = args[index + 1];
955 arg_i = -1;
956 } else {
957 for (lookup = field; *lookup && *lookup != '.' && *lookup != '['; lookup++);
958 mp_obj_t field_q = mp_obj_new_str(field, lookup - field, true/*?*/);
959 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
960 if (key_elem == NULL) {
961 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
962 }
963 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700964 }
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200965 if (*lookup) {
966 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700967 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700968 vstr_free(field_name);
969 field_name = NULL;
970 } else {
971 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000972 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
973 terse_str_format_value_error();
974 } else {
975 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
976 "can't switch from manual field specification to automatic field numbering"));
977 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700978 }
Damien George963a5a32015-01-16 17:47:07 +0000979 if ((uint)arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100980 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700981 }
982 arg = args[arg_i + 1];
983 arg_i++;
984 }
985 if (!format_spec && !conversion) {
986 conversion = 's';
987 }
988 if (conversion) {
989 mp_print_kind_t print_kind;
990 if (conversion == 's') {
991 print_kind = PRINT_STR;
992 } else if (conversion == 'r') {
993 print_kind = PRINT_REPR;
994 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000995 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
996 terse_str_format_value_error();
997 } else {
998 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
999 "unknown conversion specifier %c", conversion));
1000 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001001 }
Damien George0b9ee862015-01-21 19:14:25 +00001002 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001003 mp_print_t arg_print;
1004 vstr_init_print(&arg_vstr, 16, &arg_print);
1005 mp_obj_print_helper(&arg_print, arg, print_kind);
Damien George0b9ee862015-01-21 19:14:25 +00001006 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001007 }
1008
1009 char sign = '\0';
1010 char fill = '\0';
1011 char align = '\0';
1012 int width = -1;
1013 int precision = -1;
1014 char type = '\0';
1015 int flags = 0;
1016
1017 if (format_spec) {
1018 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1019 //
1020 // [[fill]align][sign][#][0][width][,][.precision][type]
1021 // fill ::= <any character>
1022 // align ::= "<" | ">" | "=" | "^"
1023 // sign ::= "+" | "-" | " "
1024 // width ::= integer
1025 // precision ::= integer
1026 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1027
Damien George827b0f72015-01-29 13:57:23 +00001028 const char *s = vstr_null_terminated_str(format_spec);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001029 if (isalignment(*s)) {
1030 align = *s++;
1031 } else if (*s && isalignment(s[1])) {
1032 fill = *s++;
1033 align = *s++;
1034 }
1035 if (*s == '+' || *s == '-' || *s == ' ') {
1036 if (*s == '+') {
1037 flags |= PF_FLAG_SHOW_SIGN;
1038 } else if (*s == ' ') {
1039 flags |= PF_FLAG_SPACE_SIGN;
1040 }
1041 sign = *s++;
1042 }
1043 if (*s == '#') {
1044 flags |= PF_FLAG_SHOW_PREFIX;
1045 s++;
1046 }
1047 if (*s == '0') {
1048 if (!align) {
1049 align = '=';
1050 }
1051 if (!fill) {
1052 fill = '0';
1053 }
1054 }
1055 s += str_to_int(s, &width);
1056 if (*s == ',') {
1057 flags |= PF_FLAG_SHOW_COMMA;
1058 s++;
1059 }
1060 if (*s == '.') {
1061 s++;
1062 s += str_to_int(s, &precision);
1063 }
1064 if (istype(*s)) {
1065 type = *s++;
1066 }
1067 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001068 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001069 }
1070 vstr_free(format_spec);
1071 format_spec = NULL;
1072 }
1073 if (!align) {
1074 if (arg_looks_numeric(arg)) {
1075 align = '>';
1076 } else {
1077 align = '<';
1078 }
1079 }
1080 if (!fill) {
1081 fill = ' ';
1082 }
1083
1084 if (sign) {
1085 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001086 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1087 terse_str_format_value_error();
1088 } else {
1089 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1090 "sign not allowed in string format specifier"));
1091 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001092 }
1093 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001094 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1095 terse_str_format_value_error();
1096 } else {
1097 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1098 "sign not allowed with integer format specifier 'c'"));
1099 }
Damiend99b0522013-12-21 18:17:45 +00001100 }
1101 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001102 sign = '-';
1103 }
1104
1105 switch (align) {
1106 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1107 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1108 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1109 }
1110
1111 if (arg_looks_integer(arg)) {
1112 switch (type) {
1113 case 'b':
Damien George7f9d1d62015-04-09 23:56:15 +01001114 mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001115 continue;
1116
1117 case 'c':
1118 {
1119 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001120 mp_print_strn(&print, &ch, 1, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001121 continue;
1122 }
1123
1124 case '\0': // No explicit format type implies 'd'
1125 case 'n': // I don't think we support locales in uPy so use 'd'
1126 case 'd':
Damien George7f9d1d62015-04-09 23:56:15 +01001127 mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001128 continue;
1129
1130 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001131 if (flags & PF_FLAG_SHOW_PREFIX) {
1132 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1133 }
1134
Damien George7f9d1d62015-04-09 23:56:15 +01001135 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001136 continue;
1137
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001138 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001139 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001140 mp_print_mp_int(&print, arg, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001141 continue;
1142
1143 case 'e':
1144 case 'E':
1145 case 'f':
1146 case 'F':
1147 case 'g':
1148 case 'G':
1149 case '%':
1150 // The floating point formatters all work with anything that
1151 // looks like an integer
1152 break;
1153
1154 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001155 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1156 terse_str_format_value_error();
1157 } else {
1158 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1159 "unknown format code '%c' for object of type '%s'",
1160 type, mp_obj_get_type_str(arg)));
1161 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001162 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001163 }
Damien George70f33cd2014-04-02 17:06:05 +01001164
Dave Hylands22fe4d72014-04-02 12:07:31 -07001165 // NOTE: no else here. We need the e, f, g etc formats for integer
1166 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001167 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001168 if (!type) {
1169
1170 // Even though the docs say that an unspecified type is the same
1171 // as 'g', there is one subtle difference, when the exponent
1172 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001173 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001174 // '{:10.1}'.format(0.0) ==> '0e+00'
1175 // '{:10.1g}'.format(0.0) ==> '0'
1176 //
1177 // TODO: Figure out how to deal with this.
1178 //
1179 // A proper solution would involve adding a special flag
1180 // or something to format_float, and create a format_double
1181 // to deal with doubles. In order to fix this when using
1182 // sprintf, we'd need to use the e format and tweak the
1183 // returned result to strip trailing zeros like the g format
1184 // does.
1185 //
1186 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1187 // but with 1.e2 you get 1e+02 and 1.00e+02
1188 //
1189 // Stripping the trailing 0's (like g) does would make the
1190 // e format give us the right format.
1191 //
1192 // CPython sources say:
1193 // Omitted type specifier. Behaves in the same way as repr(x)
1194 // and str(x) if no precision is given, else like 'g', but with
1195 // at least one digit after the decimal point. */
1196
1197 type = 'g';
1198 }
1199 if (type == 'n') {
1200 type = 'g';
1201 }
1202
1203 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1204 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001205#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001206 case 'e':
1207 case 'E':
1208 case 'f':
1209 case 'F':
1210 case 'g':
1211 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001212 mp_print_float(&print, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001213 break;
1214
1215 case '%':
1216 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001217 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1218 #define F100 100.0F
1219 #else
1220 #define F100 100.0
1221 #endif
Damien George7f9d1d62015-04-09 23:56:15 +01001222 mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
Damien George0178aa92015-01-12 21:56:35 +00001223 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001224 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001225#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001226
1227 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001228 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1229 terse_str_format_value_error();
1230 } else {
1231 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1232 "unknown format code '%c' for object of type 'float'",
1233 type, mp_obj_get_type_str(arg)));
1234 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001235 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001236 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001237 // arg doesn't look like a number
1238
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001239 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001240 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1241 terse_str_format_value_error();
1242 } else {
1243 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1244 "'=' alignment not allowed in string format specifier"));
1245 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001246 }
Damien George70f33cd2014-04-02 17:06:05 +01001247
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001248 switch (type) {
1249 case '\0':
Damien George7f9d1d62015-04-09 23:56:15 +01001250 mp_obj_print_helper(&print, arg, PRINT_STR);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001251 break;
1252
Damien Georged182b982014-08-30 14:19:41 +01001253 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001254 mp_uint_t slen;
1255 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001256 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001257 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001258 }
Damien George50912e72015-01-20 11:55:10 +00001259 if (slen > (mp_uint_t)precision) {
1260 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001261 }
Damien George7f9d1d62015-04-09 23:56:15 +01001262 mp_print_strn(&print, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001263 break;
1264 }
1265
1266 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001267 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1268 terse_str_format_value_error();
1269 } else {
1270 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1271 "unknown format code '%c' for object of type 'str'",
1272 type, mp_obj_get_type_str(arg)));
1273 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001274 }
Damiend99b0522013-12-21 18:17:45 +00001275 }
1276 }
1277
Damien George0b9ee862015-01-21 19:14:25 +00001278 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001279}
1280
Damien Georgeecc88e92014-08-30 00:35:11 +01001281STATIC 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 +00001282 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001283
1284 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001285 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001286 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001287 vstr_t vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001288 mp_print_t print;
1289 vstr_init_print(&vstr, 16, &print);
Dave Hylands6756a372014-04-02 11:42:39 -07001290
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001291 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001292 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001293 if (*str != '%') {
Damien George0b9ee862015-01-21 19:14:25 +00001294 vstr_add_char(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001295 continue;
1296 }
1297 if (++str >= top) {
1298 break;
1299 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001300 if (*str == '%') {
Damien George0b9ee862015-01-21 19:14:25 +00001301 vstr_add_char(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001302 continue;
1303 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001304
1305 // Dictionary value lookup
1306 if (*str == '(') {
1307 const byte *key = ++str;
1308 while (*str != ')') {
1309 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001310 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1311 terse_str_format_value_error();
1312 } else {
1313 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1314 "incomplete format key"));
1315 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001316 }
1317 ++str;
1318 }
1319 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1320 arg = mp_obj_dict_get(dict, k_obj);
1321 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001322 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001323
Dave Hylands6756a372014-04-02 11:42:39 -07001324 int flags = 0;
1325 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001326 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001327 while (str < top) {
1328 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1329 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1330 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001331 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001332 else if (*str == '0') {
1333 flags |= PF_FLAG_PAD_AFTER_SIGN;
1334 fill = '0';
1335 } else break;
1336 str++;
1337 }
1338 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001339 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001340 if (str < top) {
1341 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001342 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001343 goto not_enough_args;
1344 }
Dave Hylands6756a372014-04-02 11:42:39 -07001345 width = mp_obj_get_int(args[arg_i++]);
1346 str++;
1347 } else {
Damien George81836c22014-12-21 21:07:03 +00001348 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001349 }
1350 }
1351 int prec = -1;
1352 if (str < top && *str == '.') {
1353 if (++str < top) {
1354 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001355 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001356 goto not_enough_args;
1357 }
Dave Hylands6756a372014-04-02 11:42:39 -07001358 prec = mp_obj_get_int(args[arg_i++]);
1359 str++;
1360 } else {
1361 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001362 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001363 }
1364 }
1365 }
1366
1367 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001368 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1369 terse_str_format_value_error();
1370 } else {
1371 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1372 "incomplete format"));
1373 }
Dave Hylands6756a372014-04-02 11:42:39 -07001374 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001375
1376 // Tuple value lookup
1377 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001378 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001379not_enough_args:
1380 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1381 }
1382 arg = args[arg_i++];
1383 }
Dave Hylands6756a372014-04-02 11:42:39 -07001384 switch (*str) {
1385 case 'c':
1386 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001387 mp_uint_t slen;
1388 const char *s = mp_obj_str_get_data(arg, &slen);
1389 if (slen != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001390 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1391 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001392 }
Damien George7f9d1d62015-04-09 23:56:15 +01001393 mp_print_strn(&print, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001394 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001395 char ch = mp_obj_get_int(arg);
Damien George7f9d1d62015-04-09 23:56:15 +01001396 mp_print_strn(&print, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001397 } else {
1398 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1399 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001400 }
Damien George11de8392014-06-05 18:57:38 +01001401 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001402
1403 case 'd':
1404 case 'i':
1405 case 'u':
Damien George7f9d1d62015-04-09 23:56:15 +01001406 mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001407 break;
1408
Damien Georgefb510b32014-06-01 13:32:54 +01001409#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001410 case 'e':
1411 case 'E':
1412 case 'f':
1413 case 'F':
1414 case 'g':
1415 case 'G':
Damien George7f9d1d62015-04-09 23:56:15 +01001416 mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001417 break;
1418#endif
1419
1420 case 'o':
1421 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001422 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001423 }
Damien George7f9d1d62015-04-09 23:56:15 +01001424 mp_print_mp_int(&print, arg, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001425 break;
1426
1427 case 'r':
1428 case 's':
1429 {
Damien George0b9ee862015-01-21 19:14:25 +00001430 vstr_t arg_vstr;
Damien George7f9d1d62015-04-09 23:56:15 +01001431 mp_print_t arg_print;
1432 vstr_init_print(&arg_vstr, 16, &arg_print);
1433 mp_obj_print_helper(&arg_print, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
Damien George0b9ee862015-01-21 19:14:25 +00001434 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001435 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001436 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001437 }
Damien George50912e72015-01-20 11:55:10 +00001438 if (vlen > (uint)prec) {
1439 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001440 }
Damien George7f9d1d62015-04-09 23:56:15 +01001441 mp_print_strn(&print, arg_vstr.buf, vlen, flags, ' ', width);
Damien George0b9ee862015-01-21 19:14:25 +00001442 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001443 break;
1444 }
Dave Hylands6756a372014-04-02 11:42:39 -07001445
Dave Hylands6756a372014-04-02 11:42:39 -07001446 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001447 case 'x':
Damien George7f9d1d62015-04-09 23:56:15 +01001448 mp_print_mp_int(&print, arg, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001449 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001450
Dave Hylands6756a372014-04-02 11:42:39 -07001451 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001452 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1453 terse_str_format_value_error();
1454 } else {
1455 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1456 "unsupported format character '%c' (0x%x) at index %d",
1457 *str, *str, str - start_str));
1458 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001459 }
1460 }
1461
Damien George963a5a32015-01-16 17:47:07 +00001462 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001463 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001464 }
1465
Damien George0b9ee862015-01-21 19:14:25 +00001466 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001467}
1468
Damien Georgeecc88e92014-08-30 00:35:11 +01001469STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001470 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001471
Damien George40f3c022014-07-03 13:25:24 +01001472 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001473 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001474 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001475 if (max_rep == 0) {
1476 return args[0];
1477 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001478 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001479 }
xbe480c15a2014-01-30 22:17:30 -08001480 }
Damien George94f68302014-01-31 23:45:12 +00001481
xbe729be9b2014-04-07 14:46:39 -07001482 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001483
Damien Georgeff715422014-04-07 00:39:13 +01001484 // check argument types
1485
Damien Georgec55a4d82014-12-24 20:28:30 +00001486 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1487
1488 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001489 bad_implicit_conversion(args[1]);
1490 }
1491
Damien Georgec55a4d82014-12-24 20:28:30 +00001492 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001493 bad_implicit_conversion(args[2]);
1494 }
1495
1496 // extract string data
1497
xbe480c15a2014-01-30 22:17:30 -08001498 GET_STR_DATA_LEN(args[0], str, str_len);
1499 GET_STR_DATA_LEN(args[1], old, old_len);
1500 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001501
1502 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001503 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001504 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001505 }
1506
Damien George94f68302014-01-31 23:45:12 +00001507 // data for the replaced string
1508 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001509 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001510
Damien George94f68302014-01-31 23:45:12 +00001511 // do 2 passes over the string:
1512 // first pass computes the required length of the replaced string
1513 // second pass does the replacements
1514 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001515 mp_uint_t replaced_str_index = 0;
1516 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001517 const byte *old_occurrence;
1518 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001519 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001520 if (old_len == 0) {
1521 // if old_str is empty, copy new_str to start of replaced string
1522 // copy the replacement string
1523 if (data != NULL) {
1524 memcpy(data, new, new_len);
1525 }
1526 replaced_str_index += new_len;
1527 num_replacements_done++;
1528 }
Damien George963a5a32015-01-16 17:47:07 +00001529 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 +01001530 if (old_len == 0) {
1531 old_occurrence += 1;
1532 }
Damien George94f68302014-01-31 23:45:12 +00001533 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1534 if (data != NULL) {
1535 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1536 }
1537 replaced_str_index += old_occurrence - offset_ptr;
1538 // copy the replacement string
1539 if (data != NULL) {
1540 memcpy(data + replaced_str_index, new, new_len);
1541 }
1542 replaced_str_index += new_len;
1543 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001544 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001545 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001546 }
1547
1548 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1549 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001550 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001551 }
Damien Georgeff715422014-04-07 00:39:13 +01001552 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001553
1554 if (data == NULL) {
1555 // first pass
1556 if (num_replacements_done == 0) {
1557 // no substr found, return original string
1558 return args[0];
1559 } else {
1560 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001561 vstr_init_len(&vstr, replaced_str_index);
1562 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001563 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001564 }
1565 } else {
1566 // second pass, we are done
1567 break;
1568 }
xbe480c15a2014-01-30 22:17:30 -08001569 }
Damien George94f68302014-01-31 23:45:12 +00001570
Damien George05005f62015-01-21 22:48:37 +00001571 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001572}
1573
Damien Georgeecc88e92014-08-30 00:35:11 +01001574STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001575 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001576 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001577 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1578
1579 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001580 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001581 bad_implicit_conversion(args[1]);
1582 }
xbe9e1e8cd2014-03-12 22:57:16 -07001583
1584 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1585 GET_STR_DATA_LEN(args[1], needle, needle_len);
1586
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001587 const byte *start = haystack;
1588 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001589 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001590 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001591 }
1592 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001593 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001594 }
1595
Damien George536dde22014-03-13 22:07:55 +00001596 // if needle_len is zero then we count each gap between characters as an occurrence
1597 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001598 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001599 }
1600
Damien George536dde22014-03-13 22:07:55 +00001601 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001602 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001603 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1604 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001605 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001606 haystack_ptr += needle_len;
1607 } else {
1608 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001609 }
xbe9e1e8cd2014-03-12 22:57:16 -07001610 }
1611
1612 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1613}
1614
Damien George40f3c022014-07-03 13:25:24 +01001615STATIC 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 +00001616 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001617 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1618 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001619 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001620 }
Damien Georgeb035db32014-03-21 20:39:40 +00001621
xbe613a8e32014-03-18 00:06:29 -07001622 GET_STR_DATA_LEN(self_in, str, str_len);
1623 GET_STR_DATA_LEN(arg, sep, sep_len);
1624
1625 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001626 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001627 }
Damien Georgeb035db32014-03-21 20:39:40 +00001628
Damien Georgec55a4d82014-12-24 20:28:30 +00001629 mp_obj_t result[3];
1630 if (self_type == &mp_type_str) {
1631 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1632 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1633 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1634 } else {
1635 result[0] = mp_const_empty_bytes;
1636 result[1] = mp_const_empty_bytes;
1637 result[2] = mp_const_empty_bytes;
1638 }
Damien Georgeb035db32014-03-21 20:39:40 +00001639
1640 if (direction > 0) {
1641 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001642 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001643 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001644 }
xbe613a8e32014-03-18 00:06:29 -07001645
xbe17a5a832014-03-23 23:31:58 -07001646 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1647 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001648 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001649 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001650 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001651 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 -07001652 }
Damien Georgeb035db32014-03-21 20:39:40 +00001653
xbe0a6894c2014-03-21 01:12:26 -07001654 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001655}
1656
Damien Georgeb035db32014-03-21 20:39:40 +00001657STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1658 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001659}
xbe4504ea82014-03-19 00:46:14 -07001660
Damien Georgeb035db32014-03-21 20:39:40 +00001661STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1662 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001663}
1664
Paul Sokolovsky69135212014-05-10 19:47:41 +03001665// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001666STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001667 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001668 vstr_t vstr;
1669 vstr_init_len(&vstr, self_len);
1670 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +01001671 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001672 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001673 }
Damien George05005f62015-01-21 22:48:37 +00001674 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001675}
1676
1677STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001678 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001679}
1680
1681STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001682 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001683}
1684
Damien Georgefcc9cf62014-06-01 18:22:09 +01001685STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001686 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001687
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001688 if (self_len == 0) {
1689 return mp_const_false; // default to False for empty str
1690 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001691
Damien Georgefcc9cf62014-06-01 18:22:09 +01001692 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001693 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001694 if (!f(*self_data++)) {
1695 return mp_const_false;
1696 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001697 }
1698 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001699 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001700
Damien George39dc1452014-10-03 19:52:22 +01001701 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001702 if (unichar_isalpha(*self_data++)) {
1703 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001704 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1705 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001706 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001707 }
1708 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001709
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001710 if (!contains_alpha) {
1711 return mp_const_false;
1712 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001713 }
1714
1715 return mp_const_true;
1716}
1717
1718STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001719 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001720}
1721
1722STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001723 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001724}
1725
1726STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001727 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001728}
1729
1730STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001731 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001732}
1733
1734STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001735 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001736}
1737
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001738#if MICROPY_CPYTHON_COMPAT
1739// These methods are superfluous in the presense of str() and bytes()
1740// constructors.
1741// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001742STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001743 mp_obj_t new_args[2];
1744 if (n_args == 1) {
1745 new_args[0] = args[0];
1746 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1747 args = new_args;
1748 n_args++;
1749 }
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001750 return mp_obj_str_make_new((mp_obj_t)&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001751}
1752
1753// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001754STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001755 mp_obj_t new_args[2];
1756 if (n_args == 1) {
1757 new_args[0] = args[0];
1758 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1759 args = new_args;
1760 n_args++;
1761 }
1762 return bytes_make_new(NULL, n_args, 0, args);
1763}
1764#endif
1765
Damien George4d917232014-08-30 14:28:06 +01001766mp_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 +01001767 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001768 GET_STR_DATA_LEN(self_in, str_data, str_len);
1769 bufinfo->buf = (void*)str_data;
1770 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001771 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001772 return 0;
1773 } else {
1774 // can't write to a string
1775 bufinfo->buf = NULL;
1776 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001777 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001778 return 1;
1779 }
1780}
1781
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001782#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001783MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1784MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001785#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001786MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1787MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1788MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1789MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1790MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
Paul Sokolovsky87051712015-03-23 22:15:12 +02001791MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, mp_obj_str_split);
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001792#if MICROPY_PY_BUILTINS_STR_SPLITLINES
1793MP_DEFINE_CONST_FUN_OBJ_KW(str_splitlines_obj, 1, str_splitlines);
1794#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001795MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1796MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1797MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1798MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1799MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1800MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001801MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001802MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1803MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1804MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1805MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1806MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1807MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1808MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1809MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1810MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1811MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1812MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001813
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001814STATIC const mp_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001815#if MICROPY_CPYTHON_COMPAT
1816 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001817 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1818 // If we have separate unicode type, then here we have methods only
1819 // for bytes type, and it should not have encode() methods. Otherwise,
1820 // we have non-compliant-but-practical bytestring type, which shares
1821 // method table with bytes, so they both have encode() and decode()
1822 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001823 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001824 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001825#endif
Damien George9b196cd2014-03-26 21:47:19 +00001826 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1827 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001828 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1829 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001830 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1831 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovskyac2f7a72015-04-04 00:09:23 +03001832 #if MICROPY_PY_BUILTINS_STR_SPLITLINES
1833 { MP_OBJ_NEW_QSTR(MP_QSTR_splitlines), (mp_obj_t)&str_splitlines_obj },
1834 #endif
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001835 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001836 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001837 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001838 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001839 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1840 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001841 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1842 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1843 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1844 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1845 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001846 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1847 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001848 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1849 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1850 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1851 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1852 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001853};
Damien George97209d32014-01-07 15:58:30 +00001854
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001855STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001856
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001857#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George44e7cbf2015-05-17 16:44:24 +01001858STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
1859
Damien George3e1a5c12014-03-29 13:43:38 +00001860const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001861 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001862 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001863 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001864 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001865 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001866 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001867 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001868 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001869 .locals_dict = (mp_obj_t)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001870};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001871#endif
Damiend99b0522013-12-21 18:17:45 +00001872
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001873// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001874const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001875 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001876 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001877 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001878 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001879 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001880 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001881 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001882 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001883 .locals_dict = (mp_obj_t)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001884};
1885
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001886// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001887const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001888
Damien George77089be2015-01-21 23:08:36 +00001889// Create a str/bytes object using the given data. New memory is allocated and
1890// the data is copied across.
Damien George4abff752014-08-30 14:59:21 +01001891mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, mp_uint_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001892 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001893 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001894 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001895 if (data) {
1896 o->hash = qstr_compute_hash(data, len);
1897 byte *p = m_new(byte, len + 1);
1898 o->data = p;
1899 memcpy(p, data, len * sizeof(byte));
1900 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1901 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001902 return o;
1903}
1904
Damien George77089be2015-01-21 23:08:36 +00001905// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1906// the exact length required and then reused for the str/bytes object. The vstr
1907// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001908mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1909 // if not a bytes object, look if a qstr with this data already exists
1910 if (type == &mp_type_str) {
1911 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1912 if (q != MP_QSTR_NULL) {
1913 vstr_clear(vstr);
1914 vstr->alloc = 0;
1915 return MP_OBJ_NEW_QSTR(q);
1916 }
1917 }
1918
1919 // make a new str/bytes object
1920 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1921 o->base.type = type;
1922 o->len = vstr->len;
1923 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
1924 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
Damien George0d3cb672015-01-28 23:43:01 +00001925 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00001926 vstr->buf = NULL;
1927 vstr->alloc = 0;
1928 return o;
1929}
1930
Damien Georged182b982014-08-30 14:19:41 +01001931mp_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 +01001932 if (make_qstr_if_not_already) {
1933 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001934 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001935 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001936 qstr q = qstr_find_strn(data, len);
1937 if (q != MP_QSTR_NULL) {
1938 // qstr with this data already exists
1939 return MP_OBJ_NEW_QSTR(q);
1940 } else {
1941 // no existing qstr, don't make one
1942 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1943 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001944 }
Damien George5fa93b62014-01-22 14:35:10 +00001945}
1946
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001947mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1948 GET_STR_DATA_LEN(str, data, len);
1949 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1950}
1951
Damien Georged182b982014-08-30 14:19:41 +01001952mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001953 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001954}
1955
Damien George5fa93b62014-01-22 14:35:10 +00001956bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1957 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1958 return s1 == s2;
1959 } else {
1960 GET_STR_HASH(s1, h1);
1961 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001962 // If any of hashes is 0, it means it's not valid
1963 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001964 return false;
1965 }
1966 GET_STR_DATA_LEN(s1, d1, l1);
1967 GET_STR_DATA_LEN(s2, d2, l2);
1968 if (l1 != l2) {
1969 return false;
1970 }
Damien George1e708fe2014-01-23 18:27:51 +00001971 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001972 }
Damien George5fa93b62014-01-22 14:35:10 +00001973}
1974
Damien Georgedeed0872014-04-06 11:11:15 +01001975STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001976 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1977 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1978 "can't convert to str implicitly"));
1979 } else {
1980 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1981 "can't convert '%s' object to str implicitly",
1982 mp_obj_get_type_str(self_in)));
1983 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001984}
1985
Damien Georged182b982014-08-30 14:19:41 +01001986mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001987 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001988 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001989 GET_STR_LEN(self_in, l);
1990 return l;
1991 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001992 bad_implicit_conversion(self_in);
1993 }
1994}
1995
1996// use this if you will anyway convert the string to a qstr
1997// will be more efficient for the case where it's already a qstr
1998qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1999 if (MP_OBJ_IS_QSTR(self_in)) {
2000 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00002001 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002002 mp_obj_str_t *self = self_in;
2003 return qstr_from_strn((char*)self->data, self->len);
2004 } else {
2005 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002006 }
2007}
2008
2009// only use this function if you need the str data to be zero terminated
2010// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2011const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002012 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002013 GET_STR_DATA_LEN(self_in, s, l);
2014 (void)l; // len unused
2015 return (const char*)s;
2016 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002017 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002018 }
2019}
2020
Damien Georged182b982014-08-30 14:19:41 +01002021const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002022 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002023 GET_STR_DATA_LEN(self_in, s, l);
2024 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002025 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002026 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002027 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002028 }
Damiend99b0522013-12-21 18:17:45 +00002029}
xyb8cfc9f02014-01-05 18:47:51 +08002030
2031/******************************************************************************/
2032/* str iterator */
2033
Damien George44e7cbf2015-05-17 16:44:24 +01002034typedef struct _mp_obj_str8_it_t {
xyb8cfc9f02014-01-05 18:47:51 +08002035 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002036 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002037 mp_uint_t cur;
Damien George44e7cbf2015-05-17 16:44:24 +01002038} mp_obj_str8_it_t;
xyb8cfc9f02014-01-05 18:47:51 +08002039
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002040#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002041STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002042 mp_obj_str8_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002043 GET_STR_DATA_LEN(self->str, str, len);
2044 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002045 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002046 self->cur += 1;
2047 return o_out;
2048 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002049 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002050 }
2051}
2052
Damien George3e1a5c12014-03-29 13:43:38 +00002053STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002054 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002055 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002056 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002057 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002058};
2059
Damien George44e7cbf2015-05-17 16:44:24 +01002060STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2061 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002062 o->base.type = &mp_type_str_it;
2063 o->str = str;
2064 o->cur = 0;
2065 return o;
2066}
2067#endif
2068
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002069STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Damien George44e7cbf2015-05-17 16:44:24 +01002070 mp_obj_str8_it_t *self = self_in;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002071 GET_STR_DATA_LEN(self->str, str, len);
2072 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002073 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002074 self->cur += 1;
2075 return o_out;
2076 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002077 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002078 }
2079}
2080
Damien George3e1a5c12014-03-29 13:43:38 +00002081STATIC const mp_obj_type_t mp_type_bytes_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 Sokolovsky91fb1c92014-01-24 22:50:40 +02002085 .iternext = bytes_it_iternext,
2086};
2087
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002088mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
Damien George44e7cbf2015-05-17 16:44:24 +01002089 mp_obj_str8_it_t *o = m_new_obj(mp_obj_str8_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002090 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002091 o->str = str;
2092 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002093 return o;
2094}