blob: 43de047a724907d0011a7a83588b5a829fcab745 [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"
37#include "py/pfenv.h"
Damiend99b0522013-12-21 18:17:45 +000038
Damien Georgeecc88e92014-08-30 00:35:11 +010039STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020040
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030041mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020042STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030043STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030044
xyb8cfc9f02014-01-05 18:47:51 +080045/******************************************************************************/
46/* str */
47
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030048void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
Damien Georged182b982014-08-30 14:19:41 +010049 const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020050 // this escapes characters, but it will be very slow to print (calling print many times)
51 bool has_single_quote = false;
52 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100053 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020054 if (*s == '\'') {
55 has_single_quote = true;
56 } else if (*s == '"') {
57 has_double_quote = true;
58 }
59 }
60 int quote_char = '\'';
61 if (has_single_quote && !has_double_quote) {
62 quote_char = '"';
63 }
64 print(env, "%c", quote_char);
65 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
66 if (*s == quote_char) {
67 print(env, "\\%c", quote_char);
68 } else if (*s == '\\') {
69 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030070 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
71 // In strings, anything which is not ascii control character
72 // is printed as is, this includes characters in range 0x80-0xff
73 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020074 print(env, "%c", *s);
75 } else if (*s == '\n') {
76 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010077 } else if (*s == '\r') {
78 print(env, "\\r");
79 } else if (*s == '\t') {
80 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020081 } else {
82 print(env, "\\x%02x", *s);
83 }
84 }
85 print(env, "%c", quote_char);
86}
87
Damien George612045f2014-09-17 22:56:34 +010088#if MICROPY_PY_UJSON
Damien Georgecde0ca22014-09-25 17:35:56 +010089void mp_str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) {
90 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
91 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George612045f2014-09-17 22:56:34 +010092 print(env, "\"");
93 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010094 if (*s == '"' || *s == '\\') {
Damien George612045f2014-09-17 22:56:34 +010095 print(env, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010096 } else if (*s >= 32) {
97 // this will handle normal and utf-8 encoded chars
Damien George612045f2014-09-17 22:56:34 +010098 print(env, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010099 } else if (*s == '\n') {
100 print(env, "\\n");
101 } else if (*s == '\r') {
102 print(env, "\\r");
103 } else if (*s == '\t') {
104 print(env, "\\t");
105 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100106 // this will handle control chars
Damien George612045f2014-09-17 22:56:34 +0100107 print(env, "\\u%04x", *s);
108 }
109 }
110 print(env, "\"");
111}
112#endif
113
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200114STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +0000115 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100116 #if MICROPY_PY_UJSON
117 if (kind == PRINT_JSON) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100118 mp_str_print_json(print, env, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100119 return;
120 }
121 #endif
Damien Georgecde0ca22014-09-25 17:35:56 +0100122 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200123 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000124 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200125 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200126 if (is_bytes) {
127 print(env, "b");
128 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300129 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200130 }
Damiend99b0522013-12-21 18:17:45 +0000131}
132
Paul Sokolovsky344e15b2015-01-23 02:15:56 +0200133mp_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 +0300134#if MICROPY_CPYTHON_COMPAT
135 if (n_kw != 0) {
136 mp_arg_error_unimpl_kw();
137 }
138#endif
139
Damien George1e9a92f2014-11-06 17:36:16 +0000140 mp_arg_check_num(n_args, n_kw, 0, 3, false);
141
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200142 switch (n_args) {
143 case 0:
144 return MP_OBJ_NEW_QSTR(MP_QSTR_);
145
Damien George1e9a92f2014-11-06 17:36:16 +0000146 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000147 vstr_t vstr;
148 vstr_init(&vstr, 16);
149 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, &vstr, args[0], PRINT_STR);
150 return mp_obj_new_str_from_vstr(type_in, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200151 }
152
Damien George1e9a92f2014-11-06 17:36:16 +0000153 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200154 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200155 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
156 GET_STR_DATA_LEN(args[0], str_data, str_len);
157 GET_STR_HASH(args[0], str_hash);
Damien George0b9ee862015-01-21 19:14:25 +0000158 mp_obj_str_t *o = mp_obj_new_str_of_type(type_in, NULL, str_len);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200159 o->data = str_data;
160 o->hash = str_hash;
161 return o;
162 } else {
163 mp_buffer_info_t bufinfo;
164 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
165 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200166 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200167 }
168}
169
Damien Georgeecc88e92014-08-30 00:35:11 +0100170STATIC 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 +0000171 (void)type_in;
172
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200173 if (n_args == 0) {
174 return mp_const_empty_bytes;
175 }
176
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300177#if MICROPY_CPYTHON_COMPAT
178 if (n_kw != 0) {
179 mp_arg_error_unimpl_kw();
180 }
181#endif
182
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200183 if (MP_OBJ_IS_STR(args[0])) {
184 if (n_args < 2 || n_args > 3) {
185 goto wrong_args;
186 }
187 GET_STR_DATA_LEN(args[0], str_data, str_len);
188 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100189 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200190 o->data = str_data;
191 o->hash = str_hash;
192 return o;
193 }
194
195 if (n_args > 1) {
196 goto wrong_args;
197 }
198
199 if (MP_OBJ_IS_SMALL_INT(args[0])) {
200 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000201 vstr_t vstr;
202 vstr_init_len(&vstr, len);
203 memset(vstr.buf, 0, len);
204 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200205 }
206
Damien George32ef3a32014-12-04 15:46:14 +0000207 // check if argument has the buffer protocol
208 mp_buffer_info_t bufinfo;
209 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
210 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
211 }
212
Damien George0b9ee862015-01-21 19:14:25 +0000213 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200214 // Try to create array of exact len if initializer len is known
215 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
216 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000217 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200218 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000219 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George0d3cb672015-01-28 23:43:01 +0000220 vstr_init(&vstr, len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200221 }
222
Damien Georged17926d2014-03-30 13:35:08 +0100223 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200224 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100225 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovskybbd92512015-01-28 22:29:07 +0200226 vstr_add_byte(&vstr, MP_OBJ_SMALL_INT_VALUE(item));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200227 }
228
Damien George0b9ee862015-01-21 19:14:25 +0000229 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200230
231wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000232 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200233}
234
Damien George55baff42014-01-21 21:40:13 +0000235// like strstr but with specified length and allows \0 bytes
236// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100237STATIC 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 +0000238 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100239 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700240 if (direction > 0) {
241 str_index = 0;
242 str_index_end = hlen - nlen;
243 } else {
244 str_index = hlen - nlen;
245 str_index_end = 0;
246 }
247 for (;;) {
248 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
249 //found
250 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000251 }
xbe17a5a832014-03-23 23:31:58 -0700252 if (str_index == str_index_end) {
253 //not found
254 break;
Damien George55baff42014-01-21 21:40:13 +0000255 }
xbe17a5a832014-03-23 23:31:58 -0700256 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000257 }
258 }
259 return NULL;
260}
261
Damien Georgea75b02e2014-08-27 09:20:30 +0100262// Note: this function is used to check if an object is a str or bytes, which
263// works because both those types use it as their binary_op method. Revisit
264// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100265mp_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 +0000266 // check for modulo
267 if (op == MP_BINARY_OP_MODULO) {
268 mp_obj_t *args;
269 mp_uint_t n_args;
270 mp_obj_t dict = MP_OBJ_NULL;
271 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
272 // TODO: Support tuple subclasses?
273 mp_obj_tuple_get(rhs_in, &n_args, &args);
274 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
275 args = NULL;
276 n_args = 0;
277 dict = rhs_in;
278 } else {
279 args = &rhs_in;
280 n_args = 1;
281 }
282 return str_modulo_format(lhs_in, n_args, args, dict);
283 }
284
285 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300286 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000287 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
288
289 // check for multiply
290 if (op == MP_BINARY_OP_MULTIPLY) {
291 mp_int_t n;
292 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
293 return MP_OBJ_NULL; // op not supported
294 }
295 if (n <= 0) {
296 if (lhs_type == &mp_type_str) {
297 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
298 } else {
299 return mp_const_empty_bytes;
300 }
301 }
Damien George05005f62015-01-21 22:48:37 +0000302 vstr_t vstr;
303 vstr_init_len(&vstr, lhs_len * n);
304 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
305 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000306 }
307
308 // From now on all operations allow:
309 // - str with str
310 // - bytes with bytes
311 // - bytes with bytearray
312 // - bytes with array.array
313 // To do this efficiently we use the buffer protocol to extract the raw
314 // data for the rhs, but only if the lhs is a bytes object.
315 //
316 // NOTE: CPython does not allow comparison between bytes ard array.array
317 // (even if the array is of type 'b'), even though it allows addition of
318 // such types. We are not compatible with this (we do allow comparison
319 // of bytes with anything that has the buffer protocol). It would be
320 // easy to "fix" this with a bit of extra logic below, but it costs code
321 // size and execution time so we don't.
322
323 const byte *rhs_data;
324 mp_uint_t rhs_len;
325 if (lhs_type == mp_obj_get_type(rhs_in)) {
326 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
327 rhs_data = rhs_data_;
328 rhs_len = rhs_len_;
329 } else if (lhs_type == &mp_type_bytes) {
330 mp_buffer_info_t bufinfo;
331 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000332 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000333 }
334 rhs_data = bufinfo.buf;
335 rhs_len = bufinfo.len;
336 } else {
337 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000338 return MP_OBJ_NULL; // op not supported
339 }
340
Damiend99b0522013-12-21 18:17:45 +0000341 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100342 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000343 case MP_BINARY_OP_INPLACE_ADD: {
Damien George05005f62015-01-21 22:48:37 +0000344 vstr_t vstr;
345 vstr_init_len(&vstr, lhs_len + rhs_len);
346 memcpy(vstr.buf, lhs_data, lhs_len);
347 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
348 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200349 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200350
Damien Georgea65c03c2014-11-05 16:30:34 +0000351 case MP_BINARY_OP_IN:
352 /* NOTE `a in b` is `b.__contains__(a)` */
353 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300354
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300355 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
356 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 +0100357 case MP_BINARY_OP_LESS:
358 case MP_BINARY_OP_LESS_EQUAL:
359 case MP_BINARY_OP_MORE:
360 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000361 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000362 }
363
Damien George6ac5dce2014-05-21 19:42:43 +0100364 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000365}
366
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300367#if !MICROPY_PY_BUILTINS_STR_UNICODE
368// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100369const 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 +0300370 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100371 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300372 return self_data + index_val;
373}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300374#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300375
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300376// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
377STATIC 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 +0300378 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100379 GET_STR_DATA_LEN(self_in, self_data, self_len);
380 if (value == MP_OBJ_SENTINEL) {
381 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100382#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100383 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300384 mp_bound_slice_t slice;
385 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300386 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100387 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100388 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100389 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100390 }
391#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300392 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100393 // If we have unicode enabled the type will always be bytes, so take the short cut.
394 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300395 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100396 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300397 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100398 }
399 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100400 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100401 }
402}
403
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200404STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700405 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300406 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000407
Damien Georgefe8fb912014-01-02 16:36:09 +0000408 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000409 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000410
411 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100412 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000413 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000414 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000415 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000416 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100417 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
418 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300419 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100420 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
421 }
422 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000423 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000424
425 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100426 mp_uint_t required_len = 0;
427 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300428 if (mp_obj_get_type(seq_items[i]) != self_type) {
429 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
430 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000431 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000432 if (i > 0) {
433 required_len += sep_len;
434 }
Damien George5fa93b62014-01-22 14:35:10 +0000435 GET_STR_LEN(seq_items[i], l);
436 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000437 }
438
439 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000440 vstr_t vstr;
441 vstr_init_len(&vstr, required_len);
442 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +0100443 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000444 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000445 memcpy(data, sep_str, sep_len);
446 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000447 }
Damien George5fa93b62014-01-22 14:35:10 +0000448 GET_STR_DATA_LEN(seq_items[i], s, l);
449 memcpy(data, s, l);
450 data += l;
Damiend99b0522013-12-21 18:17:45 +0000451 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000452
453 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000454 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000455}
456
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200457#define is_ws(c) ((c) == ' ' || (c) == '\t')
458
Damien Georgeecc88e92014-08-30 00:35:11 +0100459STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300460 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100461 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200462 mp_obj_t sep = mp_const_none;
463 if (n_args > 1) {
464 sep = args[1];
465 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100466 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200467 }
468 }
Damien Georgedeed0872014-04-06 11:11:15 +0100469
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200470 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000471 GET_STR_DATA_LEN(args[0], s, len);
472 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200473
Damien Georgedeed0872014-04-06 11:11:15 +0100474 if (sep == mp_const_none) {
475 // sep not given, so separate on whitespace
476
477 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000478 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100479 while (s < top && splits != 0) {
480 const byte *start = s;
481 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100482 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100483 if (s >= top) {
484 break;
485 }
486 while (s < top && is_ws(*s)) s++;
487 if (splits > 0) {
488 splits--;
489 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200490 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200491
Damien Georgedeed0872014-04-06 11:11:15 +0100492 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100493 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100494 }
495
496 } else {
497 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300498 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000499 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300500 }
Damien Georgedeed0872014-04-06 11:11:15 +0100501
Damien Georged182b982014-08-30 14:19:41 +0100502 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100503 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
504
505 if (sep_len == 0) {
506 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
507 }
508
509 for (;;) {
510 const byte *start = s;
511 for (;;) {
512 if (splits == 0 || s + sep_len > top) {
513 s = top;
514 break;
515 } else if (memcmp(s, sep_str, sep_len) == 0) {
516 break;
517 }
518 s++;
519 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100520 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100521 if (s >= top) {
522 break;
523 }
524 s += sep_len;
525 if (splits > 0) {
526 splits--;
527 }
528 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200529 }
530
531 return res;
532}
533
Damien Georgeecc88e92014-08-30 00:35:11 +0100534STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300535 if (n_args < 3) {
536 // If we don't have split limit, it doesn't matter from which side
537 // we split.
538 return str_split(n_args, args);
539 }
540 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
541 mp_obj_t sep = args[1];
542 GET_STR_DATA_LEN(args[0], s, len);
543
Damien George40f3c022014-07-03 13:25:24 +0100544 mp_int_t splits = mp_obj_get_int(args[2]);
545 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300546 // Preallocate list to the max expected # of elements, as we
547 // will fill it from the end.
548 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100549 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300550
551 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000552 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300553 } else {
Damien Georged182b982014-08-30 14:19:41 +0100554 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300555 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
556
557 if (sep_len == 0) {
558 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
559 }
560
561 const byte *beg = s;
562 const byte *last = s + len;
563 for (;;) {
564 s = last - sep_len;
565 for (;;) {
566 if (splits == 0 || s < beg) {
567 break;
568 } else if (memcmp(s, sep_str, sep_len) == 0) {
569 break;
570 }
571 s--;
572 }
573 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100574 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300575 break;
576 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100577 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 +0300578 last = s;
579 if (splits > 0) {
580 splits--;
581 }
582 }
583 if (idx != 0) {
584 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100585 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100586 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300587 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
588 res->len = used;
589 }
590 }
591
592 return res;
593}
594
Damien Georgeecc88e92014-08-30 00:35:11 +0100595STATIC 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 +0300596 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000597 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000598 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
599
600 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000601 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000602 bad_implicit_conversion(args[1]);
603 }
John R. Lentone8204912014-01-12 21:53:52 +0000604
Damien George5fa93b62014-01-22 14:35:10 +0000605 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
606 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000607
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300608 const byte *start = haystack;
609 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000610 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300611 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000612 }
613 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300614 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000615 }
616
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300617 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000618 if (p == NULL) {
619 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700620 if (is_index) {
621 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
622 } else {
623 return MP_OBJ_NEW_SMALL_INT(-1);
624 }
Damien George23005372014-01-13 19:39:01 +0000625 } else {
626 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300627 #if MICROPY_PY_BUILTINS_STR_UNICODE
628 if (self_type == &mp_type_str) {
629 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
630 }
631 #endif
xbe17a5a832014-03-23 23:31:58 -0700632 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000633 }
John R. Lentone8204912014-01-12 21:53:52 +0000634}
635
Damien Georgeecc88e92014-08-30 00:35:11 +0100636STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700637 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700638}
639
Damien Georgeecc88e92014-08-30 00:35:11 +0100640STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700641 return str_finder(n_args, args, -1, false);
642}
643
Damien Georgeecc88e92014-08-30 00:35:11 +0100644STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700645 return str_finder(n_args, args, 1, true);
646}
647
Damien Georgeecc88e92014-08-30 00:35:11 +0100648STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700649 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700650}
651
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200652// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100653STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300654 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300655 GET_STR_DATA_LEN(args[0], str, str_len);
656 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300657 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300658 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300659 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300660 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300661 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200662 return mp_const_false;
663 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300664 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200665}
666
Damien Georgeecc88e92014-08-30 00:35:11 +0100667STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300668 GET_STR_DATA_LEN(args[0], str, str_len);
669 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
670 assert(n_args == 2);
671
672 if (suffix_len > str_len) {
673 return mp_const_false;
674 }
675 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
676}
677
Paul Sokolovsky88107842014-04-26 06:20:08 +0300678enum { LSTRIP, RSTRIP, STRIP };
679
Damien Georgeecc88e92014-08-30 00:35:11 +0100680STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800681 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700682 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300683 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000684
685 const byte *chars_to_del;
686 uint chars_to_del_len;
687 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800688
689 if (n_args == 1) {
690 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000691 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800692 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300693 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000694 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300695 }
Damien George5fa93b62014-01-22 14:35:10 +0000696 GET_STR_DATA_LEN(args[1], s, l);
697 chars_to_del = s;
698 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800699 }
700
Damien George5fa93b62014-01-22 14:35:10 +0000701 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800702
Damien George40f3c022014-07-03 13:25:24 +0100703 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800704 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100705 mp_uint_t last_good_char_pos = 0;
706 mp_uint_t i = 0;
707 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300708 if (type == RSTRIP) {
709 i = orig_str_len - 1;
710 delta = -1;
711 }
Damien George40f3c022014-07-03 13:25:24 +0100712 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700713 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800714 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300715 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800716 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300717 if (type == LSTRIP) {
718 last_good_char_pos = orig_str_len - 1;
719 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300720 } else if (type == RSTRIP) {
721 first_good_char_pos = 0;
722 last_good_char_pos = i;
723 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300724 }
xbe7b0f39f2014-01-08 14:23:45 -0800725 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300726 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800727 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300728 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800729 }
730
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300731 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000732 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000733 if (self_type == &mp_type_str) {
734 return MP_OBJ_NEW_QSTR(MP_QSTR_);
735 } else {
736 return mp_const_empty_bytes;
737 }
xbe7b0f39f2014-01-08 14:23:45 -0800738 }
739
740 assert(last_good_char_pos >= first_good_char_pos);
741 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100742 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300743 if (stripped_len == orig_str_len) {
744 // If nothing was stripped, don't bother to dup original string
745 // TODO: watch out for this case when we'll get to bytearray.strip()
746 assert(first_good_char_pos == 0);
747 return args[0];
748 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100749 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800750}
751
Damien Georgeecc88e92014-08-30 00:35:11 +0100752STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300753 return str_uni_strip(STRIP, n_args, args);
754}
755
Damien Georgeecc88e92014-08-30 00:35:11 +0100756STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300757 return str_uni_strip(LSTRIP, n_args, args);
758}
759
Damien Georgeecc88e92014-08-30 00:35:11 +0100760STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300761 return str_uni_strip(RSTRIP, n_args, args);
762}
763
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700764// Takes an int arg, but only parses unsigned numbers, and only changes
765// *num if at least one digit was parsed.
766static int str_to_int(const char *str, int *num) {
767 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000768 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700769 *num = 0;
770 do {
771 *num = *num * 10 + (*s - '0');
772 s++;
773 }
Damien George81836c22014-12-21 21:07:03 +0000774 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700775 }
776 return s - str;
777}
778
779static bool isalignment(char ch) {
780 return ch && strchr("<>=^", ch) != NULL;
781}
782
783static bool istype(char ch) {
784 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
785}
786
787static bool arg_looks_integer(mp_obj_t arg) {
788 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
789}
790
791static bool arg_looks_numeric(mp_obj_t arg) {
792 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100793#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700794 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
795#endif
796 ;
797}
798
Dave Hylandsc4029e52014-04-07 11:19:51 -0700799static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100800#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700801 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Paul Sokolovsky2c756652014-12-31 02:20:57 +0200802 return mp_obj_new_int_from_float(mp_obj_get_float(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700803 }
804#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700805 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700806}
807
Damien George1e9a92f2014-11-06 17:36:16 +0000808STATIC NORETURN void terse_str_format_value_error(void) {
809 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
810}
811
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200812mp_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 +0000813 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000814
Damien George5fa93b62014-01-22 14:35:10 +0000815 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700816 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +0000817 vstr_t vstr;
818 vstr_init(&vstr, 16);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700819 pfenv_t pfenv_vstr;
Damien George0b9ee862015-01-21 19:14:25 +0000820 pfenv_vstr.data = &vstr;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700821 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
822
Damien George5fa93b62014-01-22 14:35:10 +0000823 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700824 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000825 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700826 if (str < top && *str == '}') {
Damien George0b9ee862015-01-21 19:14:25 +0000827 vstr_add_char(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700828 continue;
829 }
Damien George1e9a92f2014-11-06 17:36:16 +0000830 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
831 terse_str_format_value_error();
832 } else {
833 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
834 "single '}' encountered in format string"));
835 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700836 }
837 if (*str != '{') {
Damien George0b9ee862015-01-21 19:14:25 +0000838 vstr_add_char(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700839 continue;
840 }
841
842 str++;
843 if (str < top && *str == '{') {
Damien George0b9ee862015-01-21 19:14:25 +0000844 vstr_add_char(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700845 continue;
846 }
847
848 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
849
850 vstr_t *field_name = NULL;
851 char conversion = '\0';
852 vstr_t *format_spec = NULL;
853
854 if (str < top && *str != '}' && *str != '!' && *str != ':') {
855 field_name = vstr_new();
856 while (str < top && *str != '}' && *str != '!' && *str != ':') {
857 vstr_add_char(field_name, *str++);
858 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700859 }
860
861 // conversion ::= "r" | "s"
862
863 if (str < top && *str == '!') {
864 str++;
865 if (str < top && (*str == 'r' || *str == 's')) {
866 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200867 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000868 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
869 terse_str_format_value_error();
870 } else {
871 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
872 "end of format while looking for conversion specifier"));
873 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700874 }
875 }
876
877 if (str < top && *str == ':') {
878 str++;
879 // {:} is the same as {}, which is the same as {!s}
880 // This makes a difference when passing in a True or False
881 // '{}'.format(True) returns 'True'
882 // '{:d}'.format(True) returns '1'
883 // So we treat {:} as {} and this later gets treated to be {!s}
884 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100885 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700886 while (str < top && *str != '}') {
887 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000888 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700889 }
890 }
891 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000892 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
893 terse_str_format_value_error();
894 } else {
895 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
896 "unmatched '{' in format"));
897 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700898 }
899 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000900 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
901 terse_str_format_value_error();
902 } else {
903 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
904 "expected ':' after format specifier"));
905 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700906 }
907
908 mp_obj_t arg = mp_const_none;
909
910 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100911 int index = 0;
Damien George827b0f72015-01-29 13:57:23 +0000912 const char *field = vstr_null_terminated_str(field_name);
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200913 const char *lookup = NULL;
914 if (MP_LIKELY(unichar_isdigit(*field))) {
915 if (arg_i > 0) {
916 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
917 terse_str_format_value_error();
918 } else {
919 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
920 "can't switch from automatic field numbering to manual field specification"));
921 }
922 }
Paul Sokolovskyff8e35b2015-01-04 13:23:44 +0200923 lookup = str_to_int(field, &index) + field;
Damien George963a5a32015-01-16 17:47:07 +0000924 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200925 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
926 }
927 arg = args[index + 1];
928 arg_i = -1;
929 } else {
930 for (lookup = field; *lookup && *lookup != '.' && *lookup != '['; lookup++);
931 mp_obj_t field_q = mp_obj_new_str(field, lookup - field, true/*?*/);
932 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
933 if (key_elem == NULL) {
934 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
935 }
936 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700937 }
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200938 if (*lookup) {
939 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700940 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700941 vstr_free(field_name);
942 field_name = NULL;
943 } else {
944 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000945 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
946 terse_str_format_value_error();
947 } else {
948 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
949 "can't switch from manual field specification to automatic field numbering"));
950 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700951 }
Damien George963a5a32015-01-16 17:47:07 +0000952 if ((uint)arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100953 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700954 }
955 arg = args[arg_i + 1];
956 arg_i++;
957 }
958 if (!format_spec && !conversion) {
959 conversion = 's';
960 }
961 if (conversion) {
962 mp_print_kind_t print_kind;
963 if (conversion == 's') {
964 print_kind = PRINT_STR;
965 } else if (conversion == 'r') {
966 print_kind = PRINT_REPR;
967 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000968 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
969 terse_str_format_value_error();
970 } else {
971 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
972 "unknown conversion specifier %c", conversion));
973 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700974 }
Damien George0b9ee862015-01-21 19:14:25 +0000975 vstr_t arg_vstr;
976 vstr_init(&arg_vstr, 16);
977 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, &arg_vstr, arg, print_kind);
978 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700979 }
980
981 char sign = '\0';
982 char fill = '\0';
983 char align = '\0';
984 int width = -1;
985 int precision = -1;
986 char type = '\0';
987 int flags = 0;
988
989 if (format_spec) {
990 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
991 //
992 // [[fill]align][sign][#][0][width][,][.precision][type]
993 // fill ::= <any character>
994 // align ::= "<" | ">" | "=" | "^"
995 // sign ::= "+" | "-" | " "
996 // width ::= integer
997 // precision ::= integer
998 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
999
Damien George827b0f72015-01-29 13:57:23 +00001000 const char *s = vstr_null_terminated_str(format_spec);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001001 if (isalignment(*s)) {
1002 align = *s++;
1003 } else if (*s && isalignment(s[1])) {
1004 fill = *s++;
1005 align = *s++;
1006 }
1007 if (*s == '+' || *s == '-' || *s == ' ') {
1008 if (*s == '+') {
1009 flags |= PF_FLAG_SHOW_SIGN;
1010 } else if (*s == ' ') {
1011 flags |= PF_FLAG_SPACE_SIGN;
1012 }
1013 sign = *s++;
1014 }
1015 if (*s == '#') {
1016 flags |= PF_FLAG_SHOW_PREFIX;
1017 s++;
1018 }
1019 if (*s == '0') {
1020 if (!align) {
1021 align = '=';
1022 }
1023 if (!fill) {
1024 fill = '0';
1025 }
1026 }
1027 s += str_to_int(s, &width);
1028 if (*s == ',') {
1029 flags |= PF_FLAG_SHOW_COMMA;
1030 s++;
1031 }
1032 if (*s == '.') {
1033 s++;
1034 s += str_to_int(s, &precision);
1035 }
1036 if (istype(*s)) {
1037 type = *s++;
1038 }
1039 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001040 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001041 }
1042 vstr_free(format_spec);
1043 format_spec = NULL;
1044 }
1045 if (!align) {
1046 if (arg_looks_numeric(arg)) {
1047 align = '>';
1048 } else {
1049 align = '<';
1050 }
1051 }
1052 if (!fill) {
1053 fill = ' ';
1054 }
1055
1056 if (sign) {
1057 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001058 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1059 terse_str_format_value_error();
1060 } else {
1061 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1062 "sign not allowed in string format specifier"));
1063 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001064 }
1065 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001066 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1067 terse_str_format_value_error();
1068 } else {
1069 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1070 "sign not allowed with integer format specifier 'c'"));
1071 }
Damiend99b0522013-12-21 18:17:45 +00001072 }
1073 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001074 sign = '-';
1075 }
1076
1077 switch (align) {
1078 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1079 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1080 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1081 }
1082
1083 if (arg_looks_integer(arg)) {
1084 switch (type) {
1085 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001086 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001087 continue;
1088
1089 case 'c':
1090 {
1091 char ch = mp_obj_get_int(arg);
1092 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1093 continue;
1094 }
1095
1096 case '\0': // No explicit format type implies 'd'
1097 case 'n': // I don't think we support locales in uPy so use 'd'
1098 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001099 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001100 continue;
1101
1102 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001103 if (flags & PF_FLAG_SHOW_PREFIX) {
1104 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1105 }
1106
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001107 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001108 continue;
1109
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001110 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001111 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001112 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001113 continue;
1114
1115 case 'e':
1116 case 'E':
1117 case 'f':
1118 case 'F':
1119 case 'g':
1120 case 'G':
1121 case '%':
1122 // The floating point formatters all work with anything that
1123 // looks like an integer
1124 break;
1125
1126 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001127 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1128 terse_str_format_value_error();
1129 } else {
1130 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1131 "unknown format code '%c' for object of type '%s'",
1132 type, mp_obj_get_type_str(arg)));
1133 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001134 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001135 }
Damien George70f33cd2014-04-02 17:06:05 +01001136
Dave Hylands22fe4d72014-04-02 12:07:31 -07001137 // NOTE: no else here. We need the e, f, g etc formats for integer
1138 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001139 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001140 if (!type) {
1141
1142 // Even though the docs say that an unspecified type is the same
1143 // as 'g', there is one subtle difference, when the exponent
1144 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001145 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001146 // '{:10.1}'.format(0.0) ==> '0e+00'
1147 // '{:10.1g}'.format(0.0) ==> '0'
1148 //
1149 // TODO: Figure out how to deal with this.
1150 //
1151 // A proper solution would involve adding a special flag
1152 // or something to format_float, and create a format_double
1153 // to deal with doubles. In order to fix this when using
1154 // sprintf, we'd need to use the e format and tweak the
1155 // returned result to strip trailing zeros like the g format
1156 // does.
1157 //
1158 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1159 // but with 1.e2 you get 1e+02 and 1.00e+02
1160 //
1161 // Stripping the trailing 0's (like g) does would make the
1162 // e format give us the right format.
1163 //
1164 // CPython sources say:
1165 // Omitted type specifier. Behaves in the same way as repr(x)
1166 // and str(x) if no precision is given, else like 'g', but with
1167 // at least one digit after the decimal point. */
1168
1169 type = 'g';
1170 }
1171 if (type == 'n') {
1172 type = 'g';
1173 }
1174
1175 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1176 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001177#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001178 case 'e':
1179 case 'E':
1180 case 'f':
1181 case 'F':
1182 case 'g':
1183 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001184 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001185 break;
1186
1187 case '%':
1188 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001189 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1190 #define F100 100.0F
1191 #else
1192 #define F100 100.0
1193 #endif
1194 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
1195 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001196 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001197#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001198
1199 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001200 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1201 terse_str_format_value_error();
1202 } else {
1203 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1204 "unknown format code '%c' for object of type 'float'",
1205 type, mp_obj_get_type_str(arg)));
1206 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001207 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001208 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001209 // arg doesn't look like a number
1210
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001211 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001212 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1213 terse_str_format_value_error();
1214 } else {
1215 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1216 "'=' alignment not allowed in string format specifier"));
1217 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001218 }
Damien George70f33cd2014-04-02 17:06:05 +01001219
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001220 switch (type) {
1221 case '\0':
Damien George0b9ee862015-01-21 19:14:25 +00001222 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, &vstr, arg, PRINT_STR);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001223 break;
1224
Damien Georged182b982014-08-30 14:19:41 +01001225 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001226 mp_uint_t slen;
1227 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001228 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001229 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001230 }
Damien George50912e72015-01-20 11:55:10 +00001231 if (slen > (mp_uint_t)precision) {
1232 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001233 }
Damien George50912e72015-01-20 11:55:10 +00001234 pfenv_print_strn(&pfenv_vstr, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001235 break;
1236 }
1237
1238 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001239 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1240 terse_str_format_value_error();
1241 } else {
1242 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1243 "unknown format code '%c' for object of type 'str'",
1244 type, mp_obj_get_type_str(arg)));
1245 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001246 }
Damiend99b0522013-12-21 18:17:45 +00001247 }
1248 }
1249
Damien George0b9ee862015-01-21 19:14:25 +00001250 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001251}
1252
Damien Georgeecc88e92014-08-30 00:35:11 +01001253STATIC 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 +00001254 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001255
1256 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001257 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001258 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001259 vstr_t vstr;
1260 vstr_init(&vstr, 16);
Dave Hylands6756a372014-04-02 11:42:39 -07001261 pfenv_t pfenv_vstr;
Damien George0b9ee862015-01-21 19:14:25 +00001262 pfenv_vstr.data = &vstr;
Dave Hylands6756a372014-04-02 11:42:39 -07001263 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1264
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001265 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001266 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001267 if (*str != '%') {
Damien George0b9ee862015-01-21 19:14:25 +00001268 vstr_add_char(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001269 continue;
1270 }
1271 if (++str >= top) {
1272 break;
1273 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001274 if (*str == '%') {
Damien George0b9ee862015-01-21 19:14:25 +00001275 vstr_add_char(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001276 continue;
1277 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001278
1279 // Dictionary value lookup
1280 if (*str == '(') {
1281 const byte *key = ++str;
1282 while (*str != ')') {
1283 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001284 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1285 terse_str_format_value_error();
1286 } else {
1287 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1288 "incomplete format key"));
1289 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001290 }
1291 ++str;
1292 }
1293 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1294 arg = mp_obj_dict_get(dict, k_obj);
1295 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001296 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001297
Dave Hylands6756a372014-04-02 11:42:39 -07001298 int flags = 0;
1299 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001300 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001301 while (str < top) {
1302 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1303 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1304 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001305 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001306 else if (*str == '0') {
1307 flags |= PF_FLAG_PAD_AFTER_SIGN;
1308 fill = '0';
1309 } else break;
1310 str++;
1311 }
1312 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001313 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001314 if (str < top) {
1315 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001316 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001317 goto not_enough_args;
1318 }
Dave Hylands6756a372014-04-02 11:42:39 -07001319 width = mp_obj_get_int(args[arg_i++]);
1320 str++;
1321 } else {
Damien George81836c22014-12-21 21:07:03 +00001322 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001323 }
1324 }
1325 int prec = -1;
1326 if (str < top && *str == '.') {
1327 if (++str < top) {
1328 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001329 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001330 goto not_enough_args;
1331 }
Dave Hylands6756a372014-04-02 11:42:39 -07001332 prec = mp_obj_get_int(args[arg_i++]);
1333 str++;
1334 } else {
1335 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001336 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001337 }
1338 }
1339 }
1340
1341 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001342 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1343 terse_str_format_value_error();
1344 } else {
1345 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1346 "incomplete format"));
1347 }
Dave Hylands6756a372014-04-02 11:42:39 -07001348 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001349
1350 // Tuple value lookup
1351 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001352 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001353not_enough_args:
1354 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1355 }
1356 arg = args[arg_i++];
1357 }
Dave Hylands6756a372014-04-02 11:42:39 -07001358 switch (*str) {
1359 case 'c':
1360 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001361 mp_uint_t slen;
1362 const char *s = mp_obj_str_get_data(arg, &slen);
1363 if (slen != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001364 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1365 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001366 }
1367 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001368 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001369 char ch = mp_obj_get_int(arg);
1370 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001371 } else {
1372 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1373 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001374 }
Damien George11de8392014-06-05 18:57:38 +01001375 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001376
1377 case 'd':
1378 case 'i':
1379 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001380 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001381 break;
1382
Damien Georgefb510b32014-06-01 13:32:54 +01001383#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001384 case 'e':
1385 case 'E':
1386 case 'f':
1387 case 'F':
1388 case 'g':
1389 case 'G':
1390 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1391 break;
1392#endif
1393
1394 case 'o':
1395 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001396 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001397 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001398 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001399 break;
1400
1401 case 'r':
1402 case 's':
1403 {
Damien George0b9ee862015-01-21 19:14:25 +00001404 vstr_t arg_vstr;
1405 vstr_init(&arg_vstr, 16);
Dave Hylands6756a372014-04-02 11:42:39 -07001406 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
Damien George0b9ee862015-01-21 19:14:25 +00001407 &arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1408 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001409 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001410 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001411 }
Damien George50912e72015-01-20 11:55:10 +00001412 if (vlen > (uint)prec) {
1413 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001414 }
Damien George0b9ee862015-01-21 19:14:25 +00001415 pfenv_print_strn(&pfenv_vstr, arg_vstr.buf, vlen, flags, ' ', width);
1416 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001417 break;
1418 }
Dave Hylands6756a372014-04-02 11:42:39 -07001419
Dave Hylands6756a372014-04-02 11:42:39 -07001420 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001421 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001422 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001423 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001424
Dave Hylands6756a372014-04-02 11:42:39 -07001425 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001426 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1427 terse_str_format_value_error();
1428 } else {
1429 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1430 "unsupported format character '%c' (0x%x) at index %d",
1431 *str, *str, str - start_str));
1432 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001433 }
1434 }
1435
Damien George963a5a32015-01-16 17:47:07 +00001436 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001437 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001438 }
1439
Damien George0b9ee862015-01-21 19:14:25 +00001440 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001441}
1442
Damien Georgeecc88e92014-08-30 00:35:11 +01001443STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001444 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001445
Damien George40f3c022014-07-03 13:25:24 +01001446 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001447 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001448 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001449 if (max_rep == 0) {
1450 return args[0];
1451 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001452 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001453 }
xbe480c15a2014-01-30 22:17:30 -08001454 }
Damien George94f68302014-01-31 23:45:12 +00001455
xbe729be9b2014-04-07 14:46:39 -07001456 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001457
Damien Georgeff715422014-04-07 00:39:13 +01001458 // check argument types
1459
Damien Georgec55a4d82014-12-24 20:28:30 +00001460 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1461
1462 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001463 bad_implicit_conversion(args[1]);
1464 }
1465
Damien Georgec55a4d82014-12-24 20:28:30 +00001466 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001467 bad_implicit_conversion(args[2]);
1468 }
1469
1470 // extract string data
1471
xbe480c15a2014-01-30 22:17:30 -08001472 GET_STR_DATA_LEN(args[0], str, str_len);
1473 GET_STR_DATA_LEN(args[1], old, old_len);
1474 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001475
1476 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001477 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001478 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001479 }
1480
Damien George94f68302014-01-31 23:45:12 +00001481 // data for the replaced string
1482 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001483 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001484
Damien George94f68302014-01-31 23:45:12 +00001485 // do 2 passes over the string:
1486 // first pass computes the required length of the replaced string
1487 // second pass does the replacements
1488 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001489 mp_uint_t replaced_str_index = 0;
1490 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001491 const byte *old_occurrence;
1492 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001493 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001494 if (old_len == 0) {
1495 // if old_str is empty, copy new_str to start of replaced string
1496 // copy the replacement string
1497 if (data != NULL) {
1498 memcpy(data, new, new_len);
1499 }
1500 replaced_str_index += new_len;
1501 num_replacements_done++;
1502 }
Damien George963a5a32015-01-16 17:47:07 +00001503 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 +01001504 if (old_len == 0) {
1505 old_occurrence += 1;
1506 }
Damien George94f68302014-01-31 23:45:12 +00001507 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1508 if (data != NULL) {
1509 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1510 }
1511 replaced_str_index += old_occurrence - offset_ptr;
1512 // copy the replacement string
1513 if (data != NULL) {
1514 memcpy(data + replaced_str_index, new, new_len);
1515 }
1516 replaced_str_index += new_len;
1517 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001518 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001519 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001520 }
1521
1522 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1523 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001524 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001525 }
Damien Georgeff715422014-04-07 00:39:13 +01001526 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001527
1528 if (data == NULL) {
1529 // first pass
1530 if (num_replacements_done == 0) {
1531 // no substr found, return original string
1532 return args[0];
1533 } else {
1534 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001535 vstr_init_len(&vstr, replaced_str_index);
1536 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001537 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001538 }
1539 } else {
1540 // second pass, we are done
1541 break;
1542 }
xbe480c15a2014-01-30 22:17:30 -08001543 }
Damien George94f68302014-01-31 23:45:12 +00001544
Damien George05005f62015-01-21 22:48:37 +00001545 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001546}
1547
Damien Georgeecc88e92014-08-30 00:35:11 +01001548STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001549 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001550 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001551 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1552
1553 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001554 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001555 bad_implicit_conversion(args[1]);
1556 }
xbe9e1e8cd2014-03-12 22:57:16 -07001557
1558 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1559 GET_STR_DATA_LEN(args[1], needle, needle_len);
1560
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001561 const byte *start = haystack;
1562 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001563 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001564 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001565 }
1566 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001567 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001568 }
1569
Damien George536dde22014-03-13 22:07:55 +00001570 // if needle_len is zero then we count each gap between characters as an occurrence
1571 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001572 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001573 }
1574
Damien George536dde22014-03-13 22:07:55 +00001575 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001576 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001577 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1578 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001579 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001580 haystack_ptr += needle_len;
1581 } else {
1582 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001583 }
xbe9e1e8cd2014-03-12 22:57:16 -07001584 }
1585
1586 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1587}
1588
Damien George40f3c022014-07-03 13:25:24 +01001589STATIC 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 +00001590 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001591 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1592 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001593 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001594 }
Damien Georgeb035db32014-03-21 20:39:40 +00001595
xbe613a8e32014-03-18 00:06:29 -07001596 GET_STR_DATA_LEN(self_in, str, str_len);
1597 GET_STR_DATA_LEN(arg, sep, sep_len);
1598
1599 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001600 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001601 }
Damien Georgeb035db32014-03-21 20:39:40 +00001602
Damien Georgec55a4d82014-12-24 20:28:30 +00001603 mp_obj_t result[3];
1604 if (self_type == &mp_type_str) {
1605 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1606 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1607 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1608 } else {
1609 result[0] = mp_const_empty_bytes;
1610 result[1] = mp_const_empty_bytes;
1611 result[2] = mp_const_empty_bytes;
1612 }
Damien Georgeb035db32014-03-21 20:39:40 +00001613
1614 if (direction > 0) {
1615 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001616 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001617 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001618 }
xbe613a8e32014-03-18 00:06:29 -07001619
xbe17a5a832014-03-23 23:31:58 -07001620 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1621 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001622 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001623 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001624 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001625 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 -07001626 }
Damien Georgeb035db32014-03-21 20:39:40 +00001627
xbe0a6894c2014-03-21 01:12:26 -07001628 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001629}
1630
Damien Georgeb035db32014-03-21 20:39:40 +00001631STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1632 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001633}
xbe4504ea82014-03-19 00:46:14 -07001634
Damien Georgeb035db32014-03-21 20:39:40 +00001635STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1636 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001637}
1638
Paul Sokolovsky69135212014-05-10 19:47:41 +03001639// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001640STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001641 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001642 vstr_t vstr;
1643 vstr_init_len(&vstr, self_len);
1644 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +01001645 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001646 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001647 }
Damien George05005f62015-01-21 22:48:37 +00001648 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001649}
1650
1651STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001652 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001653}
1654
1655STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001656 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001657}
1658
Damien Georgefcc9cf62014-06-01 18:22:09 +01001659STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001660 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001661
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001662 if (self_len == 0) {
1663 return mp_const_false; // default to False for empty str
1664 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001665
Damien Georgefcc9cf62014-06-01 18:22:09 +01001666 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001667 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001668 if (!f(*self_data++)) {
1669 return mp_const_false;
1670 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001671 }
1672 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001673 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001674
Damien George39dc1452014-10-03 19:52:22 +01001675 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001676 if (unichar_isalpha(*self_data++)) {
1677 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001678 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1679 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001680 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001681 }
1682 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001683
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001684 if (!contains_alpha) {
1685 return mp_const_false;
1686 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001687 }
1688
1689 return mp_const_true;
1690}
1691
1692STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001693 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001694}
1695
1696STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001697 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001698}
1699
1700STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001701 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001702}
1703
1704STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001705 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001706}
1707
1708STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001709 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001710}
1711
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001712#if MICROPY_CPYTHON_COMPAT
1713// These methods are superfluous in the presense of str() and bytes()
1714// constructors.
1715// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001716STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001717 mp_obj_t new_args[2];
1718 if (n_args == 1) {
1719 new_args[0] = args[0];
1720 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1721 args = new_args;
1722 n_args++;
1723 }
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001724 return mp_obj_str_make_new((mp_obj_t)&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001725}
1726
1727// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001728STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001729 mp_obj_t new_args[2];
1730 if (n_args == 1) {
1731 new_args[0] = args[0];
1732 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1733 args = new_args;
1734 n_args++;
1735 }
1736 return bytes_make_new(NULL, n_args, 0, args);
1737}
1738#endif
1739
Damien George4d917232014-08-30 14:28:06 +01001740mp_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 +01001741 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001742 GET_STR_DATA_LEN(self_in, str_data, str_len);
1743 bufinfo->buf = (void*)str_data;
1744 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001745 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001746 return 0;
1747 } else {
1748 // can't write to a string
1749 bufinfo->buf = NULL;
1750 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001751 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001752 return 1;
1753 }
1754}
1755
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001756#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001757MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1758MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001759#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001760MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1761MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1762MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1763MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1764MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1765MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1766MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1767MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1768MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1769MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1770MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1771MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001772MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001773MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1774MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1775MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1776MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1777MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1778MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1779MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1780MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1781MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1782MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1783MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001784
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001785STATIC const mp_map_elem_t str8_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001786#if MICROPY_CPYTHON_COMPAT
1787 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001788 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1789 // If we have separate unicode type, then here we have methods only
1790 // for bytes type, and it should not have encode() methods. Otherwise,
1791 // we have non-compliant-but-practical bytestring type, which shares
1792 // method table with bytes, so they both have encode() and decode()
1793 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001794 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001795 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001796#endif
Damien George9b196cd2014-03-26 21:47:19 +00001797 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1798 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001799 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1800 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001801 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1802 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001803 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001804 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001805 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001806 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001807 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1808 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001809 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1810 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1811 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1812 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1813 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001814 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1815 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001816 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1817 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1818 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1819 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1820 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001821};
Damien George97209d32014-01-07 15:58:30 +00001822
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001823STATIC MP_DEFINE_CONST_DICT(str8_locals_dict, str8_locals_dict_table);
Damien George9b196cd2014-03-26 21:47:19 +00001824
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001825#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001826const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001827 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001828 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001829 .print = str_print,
Paul Sokolovsky344e15b2015-01-23 02:15:56 +02001830 .make_new = mp_obj_str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001831 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001832 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001833 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001834 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001835 .locals_dict = (mp_obj_t)&str8_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001836};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001837#endif
Damiend99b0522013-12-21 18:17:45 +00001838
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001839// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001840const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001841 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001842 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001843 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001844 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001845 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001846 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001847 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001848 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Paul Sokolovsky6113eb22015-01-23 02:05:58 +02001849 .locals_dict = (mp_obj_t)&str8_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001850};
1851
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001852// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001853const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001854
Damien George77089be2015-01-21 23:08:36 +00001855// Create a str/bytes object using the given data. New memory is allocated and
1856// the data is copied across.
Damien George4abff752014-08-30 14:59:21 +01001857mp_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 +02001858 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001859 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001860 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001861 if (data) {
1862 o->hash = qstr_compute_hash(data, len);
1863 byte *p = m_new(byte, len + 1);
1864 o->data = p;
1865 memcpy(p, data, len * sizeof(byte));
1866 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1867 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001868 return o;
1869}
1870
Damien George77089be2015-01-21 23:08:36 +00001871// Create a str/bytes object from the given vstr. The vstr buffer is resized to
1872// the exact length required and then reused for the str/bytes object. The vstr
1873// is cleared and can safely be passed to vstr_free if it was heap allocated.
Damien George0b9ee862015-01-21 19:14:25 +00001874mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1875 // if not a bytes object, look if a qstr with this data already exists
1876 if (type == &mp_type_str) {
1877 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1878 if (q != MP_QSTR_NULL) {
1879 vstr_clear(vstr);
1880 vstr->alloc = 0;
1881 return MP_OBJ_NEW_QSTR(q);
1882 }
1883 }
1884
1885 // make a new str/bytes object
1886 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1887 o->base.type = type;
1888 o->len = vstr->len;
1889 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
1890 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
Damien George0d3cb672015-01-28 23:43:01 +00001891 ((byte*)o->data)[o->len] = '\0'; // add null byte
Damien George0b9ee862015-01-21 19:14:25 +00001892 vstr->buf = NULL;
1893 vstr->alloc = 0;
1894 return o;
1895}
1896
Damien Georged182b982014-08-30 14:19:41 +01001897mp_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 +01001898 if (make_qstr_if_not_already) {
1899 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001900 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001901 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001902 qstr q = qstr_find_strn(data, len);
1903 if (q != MP_QSTR_NULL) {
1904 // qstr with this data already exists
1905 return MP_OBJ_NEW_QSTR(q);
1906 } else {
1907 // no existing qstr, don't make one
1908 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1909 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001910 }
Damien George5fa93b62014-01-22 14:35:10 +00001911}
1912
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001913mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1914 GET_STR_DATA_LEN(str, data, len);
1915 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1916}
1917
Damien Georged182b982014-08-30 14:19:41 +01001918mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001919 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001920}
1921
Damien George5fa93b62014-01-22 14:35:10 +00001922bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1923 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1924 return s1 == s2;
1925 } else {
1926 GET_STR_HASH(s1, h1);
1927 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001928 // If any of hashes is 0, it means it's not valid
1929 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001930 return false;
1931 }
1932 GET_STR_DATA_LEN(s1, d1, l1);
1933 GET_STR_DATA_LEN(s2, d2, l2);
1934 if (l1 != l2) {
1935 return false;
1936 }
Damien George1e708fe2014-01-23 18:27:51 +00001937 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001938 }
Damien George5fa93b62014-01-22 14:35:10 +00001939}
1940
Damien Georgedeed0872014-04-06 11:11:15 +01001941STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001942 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1943 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1944 "can't convert to str implicitly"));
1945 } else {
1946 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1947 "can't convert '%s' object to str implicitly",
1948 mp_obj_get_type_str(self_in)));
1949 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001950}
1951
Damien Georged182b982014-08-30 14:19:41 +01001952mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001953 // TODO: This has too big overhead for hash accessor
Damien Georgebe8e99c2014-11-05 16:45:54 +00001954 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001955 GET_STR_HASH(self_in, h);
1956 return h;
1957 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001958 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001959 }
1960}
1961
Damien Georged182b982014-08-30 14:19:41 +01001962mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001963 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001964 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001965 GET_STR_LEN(self_in, l);
1966 return l;
1967 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001968 bad_implicit_conversion(self_in);
1969 }
1970}
1971
1972// use this if you will anyway convert the string to a qstr
1973// will be more efficient for the case where it's already a qstr
1974qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1975 if (MP_OBJ_IS_QSTR(self_in)) {
1976 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001977 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001978 mp_obj_str_t *self = self_in;
1979 return qstr_from_strn((char*)self->data, self->len);
1980 } else {
1981 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001982 }
1983}
1984
1985// only use this function if you need the str data to be zero terminated
1986// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1987const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02001988 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001989 GET_STR_DATA_LEN(self_in, s, l);
1990 (void)l; // len unused
1991 return (const char*)s;
1992 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001993 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001994 }
1995}
1996
Damien Georged182b982014-08-30 14:19:41 +01001997const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001998 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001999 GET_STR_DATA_LEN(self_in, s, l);
2000 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002001 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002002 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002003 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002004 }
Damiend99b0522013-12-21 18:17:45 +00002005}
xyb8cfc9f02014-01-05 18:47:51 +08002006
2007/******************************************************************************/
2008/* str iterator */
2009
2010typedef struct _mp_obj_str_it_t {
2011 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002012 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002013 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08002014} mp_obj_str_it_t;
2015
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002016#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002017STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08002018 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002019 GET_STR_DATA_LEN(self->str, str, len);
2020 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002021 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002022 self->cur += 1;
2023 return o_out;
2024 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002025 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002026 }
2027}
2028
Damien George3e1a5c12014-03-29 13:43:38 +00002029STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002030 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002031 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002032 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002033 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002034};
2035
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002036mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2037 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
2038 o->base.type = &mp_type_str_it;
2039 o->str = str;
2040 o->cur = 0;
2041 return o;
2042}
2043#endif
2044
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002045STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002046 mp_obj_str_it_t *self = self_in;
2047 GET_STR_DATA_LEN(self->str, str, len);
2048 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002049 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002050 self->cur += 1;
2051 return o_out;
2052 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002053 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002054 }
2055}
2056
Damien George3e1a5c12014-03-29 13:43:38 +00002057STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002058 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002059 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002060 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002061 .iternext = bytes_it_iternext,
2062};
2063
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002064mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
2065 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002066 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002067 o->str = str;
2068 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002069 return o;
2070}