blob: f25ec1737839e1620936315766223240abfb491f [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
Damien George6f5eb842014-11-27 16:55:47 +0000133#if !MICROPY_PY_BUILTINS_STR_UNICODE || MICROPY_CPYTHON_COMPAT
Damien Georgeecc88e92014-08-30 00:35:11 +0100134STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300135#if MICROPY_CPYTHON_COMPAT
136 if (n_kw != 0) {
137 mp_arg_error_unimpl_kw();
138 }
139#endif
140
Damien George1e9a92f2014-11-06 17:36:16 +0000141 mp_arg_check_num(n_args, n_kw, 0, 3, false);
142
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200143 switch (n_args) {
144 case 0:
145 return MP_OBJ_NEW_QSTR(MP_QSTR_);
146
Damien George1e9a92f2014-11-06 17:36:16 +0000147 case 1: {
Damien George0b9ee862015-01-21 19:14:25 +0000148 vstr_t vstr;
149 vstr_init(&vstr, 16);
150 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, &vstr, args[0], PRINT_STR);
151 return mp_obj_new_str_from_vstr(type_in, &vstr);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200152 }
153
Damien George1e9a92f2014-11-06 17:36:16 +0000154 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200155 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200156 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
157 GET_STR_DATA_LEN(args[0], str_data, str_len);
158 GET_STR_HASH(args[0], str_hash);
Damien George0b9ee862015-01-21 19:14:25 +0000159 mp_obj_str_t *o = mp_obj_new_str_of_type(type_in, NULL, str_len);
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200160 o->data = str_data;
161 o->hash = str_hash;
162 return o;
163 } else {
164 mp_buffer_info_t bufinfo;
165 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
166 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200167 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200168 }
169}
Damien George6f5eb842014-11-27 16:55:47 +0000170#endif
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200171
Damien Georgeecc88e92014-08-30 00:35:11 +0100172STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Damien Georgeff8dd3f2015-01-20 12:47:20 +0000173 (void)type_in;
174
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200175 if (n_args == 0) {
176 return mp_const_empty_bytes;
177 }
178
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300179#if MICROPY_CPYTHON_COMPAT
180 if (n_kw != 0) {
181 mp_arg_error_unimpl_kw();
182 }
183#endif
184
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200185 if (MP_OBJ_IS_STR(args[0])) {
186 if (n_args < 2 || n_args > 3) {
187 goto wrong_args;
188 }
189 GET_STR_DATA_LEN(args[0], str_data, str_len);
190 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100191 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200192 o->data = str_data;
193 o->hash = str_hash;
194 return o;
195 }
196
197 if (n_args > 1) {
198 goto wrong_args;
199 }
200
201 if (MP_OBJ_IS_SMALL_INT(args[0])) {
202 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
Damien George05005f62015-01-21 22:48:37 +0000203 vstr_t vstr;
204 vstr_init_len(&vstr, len);
205 memset(vstr.buf, 0, len);
206 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200207 }
208
Damien George32ef3a32014-12-04 15:46:14 +0000209 // check if argument has the buffer protocol
210 mp_buffer_info_t bufinfo;
211 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
212 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
213 }
214
Damien George0b9ee862015-01-21 19:14:25 +0000215 vstr_t vstr;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 // Try to create array of exact len if initializer len is known
217 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
218 if (len_in == MP_OBJ_NULL) {
Damien George0b9ee862015-01-21 19:14:25 +0000219 vstr_init(&vstr, 16);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200220 } else {
Damien George0b9ee862015-01-21 19:14:25 +0000221 mp_int_t len = MP_OBJ_SMALL_INT_VALUE(len_in);
222 vstr_init(&vstr, len + 1);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200223 }
224
Damien Georged17926d2014-03-30 13:35:08 +0100225 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200226 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100227 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Damien George0b9ee862015-01-21 19:14:25 +0000228 vstr_add_char(&vstr, MP_OBJ_SMALL_INT_VALUE(item));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200229 }
230
Damien George0b9ee862015-01-21 19:14:25 +0000231 return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200232
233wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000234 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200235}
236
Damien George55baff42014-01-21 21:40:13 +0000237// like strstr but with specified length and allows \0 bytes
238// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100239STATIC 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 +0000240 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100241 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700242 if (direction > 0) {
243 str_index = 0;
244 str_index_end = hlen - nlen;
245 } else {
246 str_index = hlen - nlen;
247 str_index_end = 0;
248 }
249 for (;;) {
250 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
251 //found
252 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000253 }
xbe17a5a832014-03-23 23:31:58 -0700254 if (str_index == str_index_end) {
255 //not found
256 break;
Damien George55baff42014-01-21 21:40:13 +0000257 }
xbe17a5a832014-03-23 23:31:58 -0700258 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000259 }
260 }
261 return NULL;
262}
263
Damien Georgea75b02e2014-08-27 09:20:30 +0100264// Note: this function is used to check if an object is a str or bytes, which
265// works because both those types use it as their binary_op method. Revisit
266// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100267mp_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 +0000268 // check for modulo
269 if (op == MP_BINARY_OP_MODULO) {
270 mp_obj_t *args;
271 mp_uint_t n_args;
272 mp_obj_t dict = MP_OBJ_NULL;
273 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
274 // TODO: Support tuple subclasses?
275 mp_obj_tuple_get(rhs_in, &n_args, &args);
276 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
277 args = NULL;
278 n_args = 0;
279 dict = rhs_in;
280 } else {
281 args = &rhs_in;
282 n_args = 1;
283 }
284 return str_modulo_format(lhs_in, n_args, args, dict);
285 }
286
287 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300288 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000289 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
290
291 // check for multiply
292 if (op == MP_BINARY_OP_MULTIPLY) {
293 mp_int_t n;
294 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
295 return MP_OBJ_NULL; // op not supported
296 }
297 if (n <= 0) {
298 if (lhs_type == &mp_type_str) {
299 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
300 } else {
301 return mp_const_empty_bytes;
302 }
303 }
Damien George05005f62015-01-21 22:48:37 +0000304 vstr_t vstr;
305 vstr_init_len(&vstr, lhs_len * n);
306 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, vstr.buf);
307 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Damien Georgea65c03c2014-11-05 16:30:34 +0000308 }
309
310 // From now on all operations allow:
311 // - str with str
312 // - bytes with bytes
313 // - bytes with bytearray
314 // - bytes with array.array
315 // To do this efficiently we use the buffer protocol to extract the raw
316 // data for the rhs, but only if the lhs is a bytes object.
317 //
318 // NOTE: CPython does not allow comparison between bytes ard array.array
319 // (even if the array is of type 'b'), even though it allows addition of
320 // such types. We are not compatible with this (we do allow comparison
321 // of bytes with anything that has the buffer protocol). It would be
322 // easy to "fix" this with a bit of extra logic below, but it costs code
323 // size and execution time so we don't.
324
325 const byte *rhs_data;
326 mp_uint_t rhs_len;
327 if (lhs_type == mp_obj_get_type(rhs_in)) {
328 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
329 rhs_data = rhs_data_;
330 rhs_len = rhs_len_;
331 } else if (lhs_type == &mp_type_bytes) {
332 mp_buffer_info_t bufinfo;
333 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000334 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000335 }
336 rhs_data = bufinfo.buf;
337 rhs_len = bufinfo.len;
338 } else {
339 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000340 return MP_OBJ_NULL; // op not supported
341 }
342
Damiend99b0522013-12-21 18:17:45 +0000343 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100344 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000345 case MP_BINARY_OP_INPLACE_ADD: {
Damien George05005f62015-01-21 22:48:37 +0000346 vstr_t vstr;
347 vstr_init_len(&vstr, lhs_len + rhs_len);
348 memcpy(vstr.buf, lhs_data, lhs_len);
349 memcpy(vstr.buf + lhs_len, rhs_data, rhs_len);
350 return mp_obj_new_str_from_vstr(lhs_type, &vstr);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200351 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200352
Damien Georgea65c03c2014-11-05 16:30:34 +0000353 case MP_BINARY_OP_IN:
354 /* NOTE `a in b` is `b.__contains__(a)` */
355 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300356
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300357 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
358 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 +0100359 case MP_BINARY_OP_LESS:
360 case MP_BINARY_OP_LESS_EQUAL:
361 case MP_BINARY_OP_MORE:
362 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000363 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000364 }
365
Damien George6ac5dce2014-05-21 19:42:43 +0100366 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000367}
368
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300369#if !MICROPY_PY_BUILTINS_STR_UNICODE
370// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100371const 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 +0300372 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100373 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300374 return self_data + index_val;
375}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300376#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300377
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300378// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
379STATIC 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 +0300380 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100381 GET_STR_DATA_LEN(self_in, self_data, self_len);
382 if (value == MP_OBJ_SENTINEL) {
383 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100384#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100385 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300386 mp_bound_slice_t slice;
387 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300388 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100389 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100390 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100391 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100392 }
393#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300394 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100395 // If we have unicode enabled the type will always be bytes, so take the short cut.
396 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300397 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100398 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300399 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100400 }
401 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100402 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100403 }
404}
405
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200406STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700407 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300408 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000409
Damien Georgefe8fb912014-01-02 16:36:09 +0000410 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000411 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000412
413 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100414 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000415 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000416 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000417 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000418 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100419 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
420 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300421 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100422 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
423 }
424 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000425 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000426
427 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100428 mp_uint_t required_len = 0;
429 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300430 if (mp_obj_get_type(seq_items[i]) != self_type) {
431 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
432 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000433 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000434 if (i > 0) {
435 required_len += sep_len;
436 }
Damien George5fa93b62014-01-22 14:35:10 +0000437 GET_STR_LEN(seq_items[i], l);
438 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000439 }
440
441 // make joined string
Damien George05005f62015-01-21 22:48:37 +0000442 vstr_t vstr;
443 vstr_init_len(&vstr, required_len);
444 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +0100445 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000446 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000447 memcpy(data, sep_str, sep_len);
448 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000449 }
Damien George5fa93b62014-01-22 14:35:10 +0000450 GET_STR_DATA_LEN(seq_items[i], s, l);
451 memcpy(data, s, l);
452 data += l;
Damiend99b0522013-12-21 18:17:45 +0000453 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000454
455 // return joined string
Damien George05005f62015-01-21 22:48:37 +0000456 return mp_obj_new_str_from_vstr(self_type, &vstr);
Damiend99b0522013-12-21 18:17:45 +0000457}
458
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200459#define is_ws(c) ((c) == ' ' || (c) == '\t')
460
Damien Georgeecc88e92014-08-30 00:35:11 +0100461STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300462 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100463 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200464 mp_obj_t sep = mp_const_none;
465 if (n_args > 1) {
466 sep = args[1];
467 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100468 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200469 }
470 }
Damien Georgedeed0872014-04-06 11:11:15 +0100471
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200472 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000473 GET_STR_DATA_LEN(args[0], s, len);
474 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200475
Damien Georgedeed0872014-04-06 11:11:15 +0100476 if (sep == mp_const_none) {
477 // sep not given, so separate on whitespace
478
479 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000480 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100481 while (s < top && splits != 0) {
482 const byte *start = s;
483 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100484 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100485 if (s >= top) {
486 break;
487 }
488 while (s < top && is_ws(*s)) s++;
489 if (splits > 0) {
490 splits--;
491 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200492 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200493
Damien Georgedeed0872014-04-06 11:11:15 +0100494 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100495 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100496 }
497
498 } else {
499 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300500 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000501 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300502 }
Damien Georgedeed0872014-04-06 11:11:15 +0100503
Damien Georged182b982014-08-30 14:19:41 +0100504 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100505 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
506
507 if (sep_len == 0) {
508 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
509 }
510
511 for (;;) {
512 const byte *start = s;
513 for (;;) {
514 if (splits == 0 || s + sep_len > top) {
515 s = top;
516 break;
517 } else if (memcmp(s, sep_str, sep_len) == 0) {
518 break;
519 }
520 s++;
521 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100522 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100523 if (s >= top) {
524 break;
525 }
526 s += sep_len;
527 if (splits > 0) {
528 splits--;
529 }
530 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200531 }
532
533 return res;
534}
535
Damien Georgeecc88e92014-08-30 00:35:11 +0100536STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300537 if (n_args < 3) {
538 // If we don't have split limit, it doesn't matter from which side
539 // we split.
540 return str_split(n_args, args);
541 }
542 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
543 mp_obj_t sep = args[1];
544 GET_STR_DATA_LEN(args[0], s, len);
545
Damien George40f3c022014-07-03 13:25:24 +0100546 mp_int_t splits = mp_obj_get_int(args[2]);
547 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300548 // Preallocate list to the max expected # of elements, as we
549 // will fill it from the end.
550 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100551 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300552
553 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000554 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300555 } else {
Damien Georged182b982014-08-30 14:19:41 +0100556 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300557 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
558
559 if (sep_len == 0) {
560 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
561 }
562
563 const byte *beg = s;
564 const byte *last = s + len;
565 for (;;) {
566 s = last - sep_len;
567 for (;;) {
568 if (splits == 0 || s < beg) {
569 break;
570 } else if (memcmp(s, sep_str, sep_len) == 0) {
571 break;
572 }
573 s--;
574 }
575 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100576 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300577 break;
578 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100579 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 +0300580 last = s;
581 if (splits > 0) {
582 splits--;
583 }
584 }
585 if (idx != 0) {
586 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100587 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100588 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300589 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
590 res->len = used;
591 }
592 }
593
594 return res;
595}
596
Damien Georgeecc88e92014-08-30 00:35:11 +0100597STATIC 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 +0300598 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000599 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000600 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
601
602 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000603 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000604 bad_implicit_conversion(args[1]);
605 }
John R. Lentone8204912014-01-12 21:53:52 +0000606
Damien George5fa93b62014-01-22 14:35:10 +0000607 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
608 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000609
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300610 const byte *start = haystack;
611 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000612 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300613 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000614 }
615 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300616 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000617 }
618
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300619 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000620 if (p == NULL) {
621 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700622 if (is_index) {
623 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
624 } else {
625 return MP_OBJ_NEW_SMALL_INT(-1);
626 }
Damien George23005372014-01-13 19:39:01 +0000627 } else {
628 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300629 #if MICROPY_PY_BUILTINS_STR_UNICODE
630 if (self_type == &mp_type_str) {
631 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
632 }
633 #endif
xbe17a5a832014-03-23 23:31:58 -0700634 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000635 }
John R. Lentone8204912014-01-12 21:53:52 +0000636}
637
Damien Georgeecc88e92014-08-30 00:35:11 +0100638STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700639 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700640}
641
Damien Georgeecc88e92014-08-30 00:35:11 +0100642STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700643 return str_finder(n_args, args, -1, false);
644}
645
Damien Georgeecc88e92014-08-30 00:35:11 +0100646STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700647 return str_finder(n_args, args, 1, true);
648}
649
Damien Georgeecc88e92014-08-30 00:35:11 +0100650STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700651 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700652}
653
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200654// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100655STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300656 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300657 GET_STR_DATA_LEN(args[0], str, str_len);
658 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300659 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300660 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300661 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300662 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300663 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200664 return mp_const_false;
665 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300666 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200667}
668
Damien Georgeecc88e92014-08-30 00:35:11 +0100669STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300670 GET_STR_DATA_LEN(args[0], str, str_len);
671 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
672 assert(n_args == 2);
673
674 if (suffix_len > str_len) {
675 return mp_const_false;
676 }
677 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
678}
679
Paul Sokolovsky88107842014-04-26 06:20:08 +0300680enum { LSTRIP, RSTRIP, STRIP };
681
Damien Georgeecc88e92014-08-30 00:35:11 +0100682STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800683 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700684 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300685 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000686
687 const byte *chars_to_del;
688 uint chars_to_del_len;
689 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800690
691 if (n_args == 1) {
692 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000693 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800694 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300695 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000696 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300697 }
Damien George5fa93b62014-01-22 14:35:10 +0000698 GET_STR_DATA_LEN(args[1], s, l);
699 chars_to_del = s;
700 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800701 }
702
Damien George5fa93b62014-01-22 14:35:10 +0000703 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800704
Damien George40f3c022014-07-03 13:25:24 +0100705 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800706 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100707 mp_uint_t last_good_char_pos = 0;
708 mp_uint_t i = 0;
709 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300710 if (type == RSTRIP) {
711 i = orig_str_len - 1;
712 delta = -1;
713 }
Damien George40f3c022014-07-03 13:25:24 +0100714 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700715 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800716 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300717 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800718 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300719 if (type == LSTRIP) {
720 last_good_char_pos = orig_str_len - 1;
721 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300722 } else if (type == RSTRIP) {
723 first_good_char_pos = 0;
724 last_good_char_pos = i;
725 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300726 }
xbe7b0f39f2014-01-08 14:23:45 -0800727 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300728 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800729 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300730 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800731 }
732
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300733 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000734 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000735 if (self_type == &mp_type_str) {
736 return MP_OBJ_NEW_QSTR(MP_QSTR_);
737 } else {
738 return mp_const_empty_bytes;
739 }
xbe7b0f39f2014-01-08 14:23:45 -0800740 }
741
742 assert(last_good_char_pos >= first_good_char_pos);
743 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100744 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300745 if (stripped_len == orig_str_len) {
746 // If nothing was stripped, don't bother to dup original string
747 // TODO: watch out for this case when we'll get to bytearray.strip()
748 assert(first_good_char_pos == 0);
749 return args[0];
750 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100751 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800752}
753
Damien Georgeecc88e92014-08-30 00:35:11 +0100754STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300755 return str_uni_strip(STRIP, n_args, args);
756}
757
Damien Georgeecc88e92014-08-30 00:35:11 +0100758STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300759 return str_uni_strip(LSTRIP, n_args, args);
760}
761
Damien Georgeecc88e92014-08-30 00:35:11 +0100762STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300763 return str_uni_strip(RSTRIP, n_args, args);
764}
765
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700766// Takes an int arg, but only parses unsigned numbers, and only changes
767// *num if at least one digit was parsed.
768static int str_to_int(const char *str, int *num) {
769 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000770 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700771 *num = 0;
772 do {
773 *num = *num * 10 + (*s - '0');
774 s++;
775 }
Damien George81836c22014-12-21 21:07:03 +0000776 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700777 }
778 return s - str;
779}
780
781static bool isalignment(char ch) {
782 return ch && strchr("<>=^", ch) != NULL;
783}
784
785static bool istype(char ch) {
786 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
787}
788
789static bool arg_looks_integer(mp_obj_t arg) {
790 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
791}
792
793static bool arg_looks_numeric(mp_obj_t arg) {
794 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100795#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700796 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
797#endif
798 ;
799}
800
Dave Hylandsc4029e52014-04-07 11:19:51 -0700801static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100802#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700803 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Paul Sokolovsky2c756652014-12-31 02:20:57 +0200804 return mp_obj_new_int_from_float(mp_obj_get_float(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700805 }
806#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700807 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700808}
809
Damien George1e9a92f2014-11-06 17:36:16 +0000810STATIC NORETURN void terse_str_format_value_error(void) {
811 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
812}
813
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200814mp_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 +0000815 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000816
Damien George5fa93b62014-01-22 14:35:10 +0000817 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700818 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +0000819 vstr_t vstr;
820 vstr_init(&vstr, 16);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700821 pfenv_t pfenv_vstr;
Damien George0b9ee862015-01-21 19:14:25 +0000822 pfenv_vstr.data = &vstr;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700823 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
824
Damien George5fa93b62014-01-22 14:35:10 +0000825 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700826 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000827 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700828 if (str < top && *str == '}') {
Damien George0b9ee862015-01-21 19:14:25 +0000829 vstr_add_char(&vstr, '}');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700830 continue;
831 }
Damien George1e9a92f2014-11-06 17:36:16 +0000832 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
833 terse_str_format_value_error();
834 } else {
835 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
836 "single '}' encountered in format string"));
837 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700838 }
839 if (*str != '{') {
Damien George0b9ee862015-01-21 19:14:25 +0000840 vstr_add_char(&vstr, *str);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700841 continue;
842 }
843
844 str++;
845 if (str < top && *str == '{') {
Damien George0b9ee862015-01-21 19:14:25 +0000846 vstr_add_char(&vstr, '{');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700847 continue;
848 }
849
850 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
851
852 vstr_t *field_name = NULL;
853 char conversion = '\0';
854 vstr_t *format_spec = NULL;
855
856 if (str < top && *str != '}' && *str != '!' && *str != ':') {
857 field_name = vstr_new();
858 while (str < top && *str != '}' && *str != '!' && *str != ':') {
859 vstr_add_char(field_name, *str++);
860 }
861 vstr_add_char(field_name, '\0');
862 }
863
864 // conversion ::= "r" | "s"
865
866 if (str < top && *str == '!') {
867 str++;
868 if (str < top && (*str == 'r' || *str == 's')) {
869 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200870 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000871 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
872 terse_str_format_value_error();
873 } else {
874 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
875 "end of format while looking for conversion specifier"));
876 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700877 }
878 }
879
880 if (str < top && *str == ':') {
881 str++;
882 // {:} is the same as {}, which is the same as {!s}
883 // This makes a difference when passing in a True or False
884 // '{}'.format(True) returns 'True'
885 // '{:d}'.format(True) returns '1'
886 // So we treat {:} as {} and this later gets treated to be {!s}
887 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100888 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700889 while (str < top && *str != '}') {
890 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000891 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700892 vstr_add_char(format_spec, '\0');
893 }
894 }
895 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000896 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
897 terse_str_format_value_error();
898 } else {
899 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
900 "unmatched '{' in format"));
901 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902 }
903 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000904 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
905 terse_str_format_value_error();
906 } else {
907 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
908 "expected ':' after format specifier"));
909 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700910 }
911
912 mp_obj_t arg = mp_const_none;
913
914 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100915 int index = 0;
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200916 const char *field = vstr_str(field_name);
917 const char *lookup = NULL;
918 if (MP_LIKELY(unichar_isdigit(*field))) {
919 if (arg_i > 0) {
920 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
921 terse_str_format_value_error();
922 } else {
923 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
924 "can't switch from automatic field numbering to manual field specification"));
925 }
926 }
Paul Sokolovskyff8e35b2015-01-04 13:23:44 +0200927 lookup = str_to_int(field, &index) + field;
Damien George963a5a32015-01-16 17:47:07 +0000928 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200929 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
930 }
931 arg = args[index + 1];
932 arg_i = -1;
933 } else {
934 for (lookup = field; *lookup && *lookup != '.' && *lookup != '['; lookup++);
935 mp_obj_t field_q = mp_obj_new_str(field, lookup - field, true/*?*/);
936 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
937 if (key_elem == NULL) {
938 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
939 }
940 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700941 }
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200942 if (*lookup) {
943 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700944 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700945 vstr_free(field_name);
946 field_name = NULL;
947 } else {
948 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000949 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
950 terse_str_format_value_error();
951 } else {
952 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
953 "can't switch from manual field specification to automatic field numbering"));
954 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700955 }
Damien George963a5a32015-01-16 17:47:07 +0000956 if ((uint)arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100957 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700958 }
959 arg = args[arg_i + 1];
960 arg_i++;
961 }
962 if (!format_spec && !conversion) {
963 conversion = 's';
964 }
965 if (conversion) {
966 mp_print_kind_t print_kind;
967 if (conversion == 's') {
968 print_kind = PRINT_STR;
969 } else if (conversion == 'r') {
970 print_kind = PRINT_REPR;
971 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000972 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
973 terse_str_format_value_error();
974 } else {
975 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
976 "unknown conversion specifier %c", conversion));
977 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700978 }
Damien George0b9ee862015-01-21 19:14:25 +0000979 vstr_t arg_vstr;
980 vstr_init(&arg_vstr, 16);
981 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, &arg_vstr, arg, print_kind);
982 arg = mp_obj_new_str_from_vstr(&mp_type_str, &arg_vstr);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700983 }
984
985 char sign = '\0';
986 char fill = '\0';
987 char align = '\0';
988 int width = -1;
989 int precision = -1;
990 char type = '\0';
991 int flags = 0;
992
993 if (format_spec) {
994 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
995 //
996 // [[fill]align][sign][#][0][width][,][.precision][type]
997 // fill ::= <any character>
998 // align ::= "<" | ">" | "=" | "^"
999 // sign ::= "+" | "-" | " "
1000 // width ::= integer
1001 // precision ::= integer
1002 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1003
1004 const char *s = vstr_str(format_spec);
1005 if (isalignment(*s)) {
1006 align = *s++;
1007 } else if (*s && isalignment(s[1])) {
1008 fill = *s++;
1009 align = *s++;
1010 }
1011 if (*s == '+' || *s == '-' || *s == ' ') {
1012 if (*s == '+') {
1013 flags |= PF_FLAG_SHOW_SIGN;
1014 } else if (*s == ' ') {
1015 flags |= PF_FLAG_SPACE_SIGN;
1016 }
1017 sign = *s++;
1018 }
1019 if (*s == '#') {
1020 flags |= PF_FLAG_SHOW_PREFIX;
1021 s++;
1022 }
1023 if (*s == '0') {
1024 if (!align) {
1025 align = '=';
1026 }
1027 if (!fill) {
1028 fill = '0';
1029 }
1030 }
1031 s += str_to_int(s, &width);
1032 if (*s == ',') {
1033 flags |= PF_FLAG_SHOW_COMMA;
1034 s++;
1035 }
1036 if (*s == '.') {
1037 s++;
1038 s += str_to_int(s, &precision);
1039 }
1040 if (istype(*s)) {
1041 type = *s++;
1042 }
1043 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001044 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001045 }
1046 vstr_free(format_spec);
1047 format_spec = NULL;
1048 }
1049 if (!align) {
1050 if (arg_looks_numeric(arg)) {
1051 align = '>';
1052 } else {
1053 align = '<';
1054 }
1055 }
1056 if (!fill) {
1057 fill = ' ';
1058 }
1059
1060 if (sign) {
1061 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001062 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1063 terse_str_format_value_error();
1064 } else {
1065 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1066 "sign not allowed in string format specifier"));
1067 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001068 }
1069 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001070 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1071 terse_str_format_value_error();
1072 } else {
1073 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1074 "sign not allowed with integer format specifier 'c'"));
1075 }
Damiend99b0522013-12-21 18:17:45 +00001076 }
1077 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001078 sign = '-';
1079 }
1080
1081 switch (align) {
1082 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1083 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1084 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1085 }
1086
1087 if (arg_looks_integer(arg)) {
1088 switch (type) {
1089 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001090 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 continue;
1092
1093 case 'c':
1094 {
1095 char ch = mp_obj_get_int(arg);
1096 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1097 continue;
1098 }
1099
1100 case '\0': // No explicit format type implies 'd'
1101 case 'n': // I don't think we support locales in uPy so use 'd'
1102 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001103 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001104 continue;
1105
1106 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001107 if (flags & PF_FLAG_SHOW_PREFIX) {
1108 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1109 }
1110
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001111 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001112 continue;
1113
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001114 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001115 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001116 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001117 continue;
1118
1119 case 'e':
1120 case 'E':
1121 case 'f':
1122 case 'F':
1123 case 'g':
1124 case 'G':
1125 case '%':
1126 // The floating point formatters all work with anything that
1127 // looks like an integer
1128 break;
1129
1130 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001131 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1132 terse_str_format_value_error();
1133 } else {
1134 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1135 "unknown format code '%c' for object of type '%s'",
1136 type, mp_obj_get_type_str(arg)));
1137 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001138 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001139 }
Damien George70f33cd2014-04-02 17:06:05 +01001140
Dave Hylands22fe4d72014-04-02 12:07:31 -07001141 // NOTE: no else here. We need the e, f, g etc formats for integer
1142 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001143 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001144 if (!type) {
1145
1146 // Even though the docs say that an unspecified type is the same
1147 // as 'g', there is one subtle difference, when the exponent
1148 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001149 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 // '{:10.1}'.format(0.0) ==> '0e+00'
1151 // '{:10.1g}'.format(0.0) ==> '0'
1152 //
1153 // TODO: Figure out how to deal with this.
1154 //
1155 // A proper solution would involve adding a special flag
1156 // or something to format_float, and create a format_double
1157 // to deal with doubles. In order to fix this when using
1158 // sprintf, we'd need to use the e format and tweak the
1159 // returned result to strip trailing zeros like the g format
1160 // does.
1161 //
1162 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1163 // but with 1.e2 you get 1e+02 and 1.00e+02
1164 //
1165 // Stripping the trailing 0's (like g) does would make the
1166 // e format give us the right format.
1167 //
1168 // CPython sources say:
1169 // Omitted type specifier. Behaves in the same way as repr(x)
1170 // and str(x) if no precision is given, else like 'g', but with
1171 // at least one digit after the decimal point. */
1172
1173 type = 'g';
1174 }
1175 if (type == 'n') {
1176 type = 'g';
1177 }
1178
1179 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1180 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001181#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001182 case 'e':
1183 case 'E':
1184 case 'f':
1185 case 'F':
1186 case 'g':
1187 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001188 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001189 break;
1190
1191 case '%':
1192 flags |= PF_FLAG_ADD_PERCENT;
Damien George0178aa92015-01-12 21:56:35 +00001193 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1194 #define F100 100.0F
1195 #else
1196 #define F100 100.0
1197 #endif
1198 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
1199 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001200 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001201#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001202
1203 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001204 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1205 terse_str_format_value_error();
1206 } else {
1207 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1208 "unknown format code '%c' for object of type 'float'",
1209 type, mp_obj_get_type_str(arg)));
1210 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001211 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001212 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001213 // arg doesn't look like a number
1214
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001215 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001216 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1217 terse_str_format_value_error();
1218 } else {
1219 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1220 "'=' alignment not allowed in string format specifier"));
1221 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001222 }
Damien George70f33cd2014-04-02 17:06:05 +01001223
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001224 switch (type) {
1225 case '\0':
Damien George0b9ee862015-01-21 19:14:25 +00001226 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, &vstr, arg, PRINT_STR);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001227 break;
1228
Damien Georged182b982014-08-30 14:19:41 +01001229 case 's': {
Damien George50912e72015-01-20 11:55:10 +00001230 mp_uint_t slen;
1231 const char *s = mp_obj_str_get_data(arg, &slen);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001232 if (precision < 0) {
Damien George50912e72015-01-20 11:55:10 +00001233 precision = slen;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001234 }
Damien George50912e72015-01-20 11:55:10 +00001235 if (slen > (mp_uint_t)precision) {
1236 slen = precision;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001237 }
Damien George50912e72015-01-20 11:55:10 +00001238 pfenv_print_strn(&pfenv_vstr, s, slen, flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001239 break;
1240 }
1241
1242 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001243 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1244 terse_str_format_value_error();
1245 } else {
1246 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1247 "unknown format code '%c' for object of type 'str'",
1248 type, mp_obj_get_type_str(arg)));
1249 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001250 }
Damiend99b0522013-12-21 18:17:45 +00001251 }
1252 }
1253
Damien George0b9ee862015-01-21 19:14:25 +00001254 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Damiend99b0522013-12-21 18:17:45 +00001255}
1256
Damien Georgeecc88e92014-08-30 00:35:11 +01001257STATIC 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 +00001258 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001259
1260 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001261 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001262 int arg_i = 0;
Damien George0b9ee862015-01-21 19:14:25 +00001263 vstr_t vstr;
1264 vstr_init(&vstr, 16);
Dave Hylands6756a372014-04-02 11:42:39 -07001265 pfenv_t pfenv_vstr;
Damien George0b9ee862015-01-21 19:14:25 +00001266 pfenv_vstr.data = &vstr;
Dave Hylands6756a372014-04-02 11:42:39 -07001267 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1268
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001269 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001270 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001271 if (*str != '%') {
Damien George0b9ee862015-01-21 19:14:25 +00001272 vstr_add_char(&vstr, *str);
Dave Hylands6756a372014-04-02 11:42:39 -07001273 continue;
1274 }
1275 if (++str >= top) {
1276 break;
1277 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001278 if (*str == '%') {
Damien George0b9ee862015-01-21 19:14:25 +00001279 vstr_add_char(&vstr, '%');
Dave Hylands6756a372014-04-02 11:42:39 -07001280 continue;
1281 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001282
1283 // Dictionary value lookup
1284 if (*str == '(') {
1285 const byte *key = ++str;
1286 while (*str != ')') {
1287 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001288 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1289 terse_str_format_value_error();
1290 } else {
1291 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1292 "incomplete format key"));
1293 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001294 }
1295 ++str;
1296 }
1297 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1298 arg = mp_obj_dict_get(dict, k_obj);
1299 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001300 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001301
Dave Hylands6756a372014-04-02 11:42:39 -07001302 int flags = 0;
1303 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001304 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001305 while (str < top) {
1306 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1307 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1308 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001309 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001310 else if (*str == '0') {
1311 flags |= PF_FLAG_PAD_AFTER_SIGN;
1312 fill = '0';
1313 } else break;
1314 str++;
1315 }
1316 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001317 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001318 if (str < top) {
1319 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001320 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001321 goto not_enough_args;
1322 }
Dave Hylands6756a372014-04-02 11:42:39 -07001323 width = mp_obj_get_int(args[arg_i++]);
1324 str++;
1325 } else {
Damien George81836c22014-12-21 21:07:03 +00001326 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001327 }
1328 }
1329 int prec = -1;
1330 if (str < top && *str == '.') {
1331 if (++str < top) {
1332 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001333 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001334 goto not_enough_args;
1335 }
Dave Hylands6756a372014-04-02 11:42:39 -07001336 prec = mp_obj_get_int(args[arg_i++]);
1337 str++;
1338 } else {
1339 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001340 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001341 }
1342 }
1343 }
1344
1345 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001346 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1347 terse_str_format_value_error();
1348 } else {
1349 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1350 "incomplete format"));
1351 }
Dave Hylands6756a372014-04-02 11:42:39 -07001352 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001353
1354 // Tuple value lookup
1355 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001356 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001357not_enough_args:
1358 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1359 }
1360 arg = args[arg_i++];
1361 }
Dave Hylands6756a372014-04-02 11:42:39 -07001362 switch (*str) {
1363 case 'c':
1364 if (MP_OBJ_IS_STR(arg)) {
Damien George50912e72015-01-20 11:55:10 +00001365 mp_uint_t slen;
1366 const char *s = mp_obj_str_get_data(arg, &slen);
1367 if (slen != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001368 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1369 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001370 }
1371 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001372 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001373 char ch = mp_obj_get_int(arg);
1374 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001375 } else {
1376 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1377 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001378 }
Damien George11de8392014-06-05 18:57:38 +01001379 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001380
1381 case 'd':
1382 case 'i':
1383 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001384 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001385 break;
1386
Damien Georgefb510b32014-06-01 13:32:54 +01001387#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001388 case 'e':
1389 case 'E':
1390 case 'f':
1391 case 'F':
1392 case 'g':
1393 case 'G':
1394 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1395 break;
1396#endif
1397
1398 case 'o':
1399 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001400 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001401 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001402 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001403 break;
1404
1405 case 'r':
1406 case 's':
1407 {
Damien George0b9ee862015-01-21 19:14:25 +00001408 vstr_t arg_vstr;
1409 vstr_init(&arg_vstr, 16);
Dave Hylands6756a372014-04-02 11:42:39 -07001410 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
Damien George0b9ee862015-01-21 19:14:25 +00001411 &arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1412 uint vlen = arg_vstr.len;
Dave Hylands6756a372014-04-02 11:42:39 -07001413 if (prec < 0) {
Damien George50912e72015-01-20 11:55:10 +00001414 prec = vlen;
Dave Hylands6756a372014-04-02 11:42:39 -07001415 }
Damien George50912e72015-01-20 11:55:10 +00001416 if (vlen > (uint)prec) {
1417 vlen = prec;
Dave Hylands6756a372014-04-02 11:42:39 -07001418 }
Damien George0b9ee862015-01-21 19:14:25 +00001419 pfenv_print_strn(&pfenv_vstr, arg_vstr.buf, vlen, flags, ' ', width);
1420 vstr_clear(&arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001421 break;
1422 }
Dave Hylands6756a372014-04-02 11:42:39 -07001423
Dave Hylands6756a372014-04-02 11:42:39 -07001424 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001425 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001426 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001427 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001428
Dave Hylands6756a372014-04-02 11:42:39 -07001429 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001430 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1431 terse_str_format_value_error();
1432 } else {
1433 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1434 "unsupported format character '%c' (0x%x) at index %d",
1435 *str, *str, str - start_str));
1436 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001437 }
1438 }
1439
Damien George963a5a32015-01-16 17:47:07 +00001440 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001441 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001442 }
1443
Damien George0b9ee862015-01-21 19:14:25 +00001444 return mp_obj_new_str_from_vstr(&mp_type_str, &vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001445}
1446
Damien Georgeecc88e92014-08-30 00:35:11 +01001447STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001448 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001449
Damien George40f3c022014-07-03 13:25:24 +01001450 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001451 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001452 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001453 if (max_rep == 0) {
1454 return args[0];
1455 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001456 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001457 }
xbe480c15a2014-01-30 22:17:30 -08001458 }
Damien George94f68302014-01-31 23:45:12 +00001459
xbe729be9b2014-04-07 14:46:39 -07001460 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001461
Damien Georgeff715422014-04-07 00:39:13 +01001462 // check argument types
1463
Damien Georgec55a4d82014-12-24 20:28:30 +00001464 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1465
1466 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001467 bad_implicit_conversion(args[1]);
1468 }
1469
Damien Georgec55a4d82014-12-24 20:28:30 +00001470 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001471 bad_implicit_conversion(args[2]);
1472 }
1473
1474 // extract string data
1475
xbe480c15a2014-01-30 22:17:30 -08001476 GET_STR_DATA_LEN(args[0], str, str_len);
1477 GET_STR_DATA_LEN(args[1], old, old_len);
1478 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001479
1480 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001481 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001482 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001483 }
1484
Damien George94f68302014-01-31 23:45:12 +00001485 // data for the replaced string
1486 byte *data = NULL;
Damien George05005f62015-01-21 22:48:37 +00001487 vstr_t vstr;
xbe480c15a2014-01-30 22:17:30 -08001488
Damien George94f68302014-01-31 23:45:12 +00001489 // do 2 passes over the string:
1490 // first pass computes the required length of the replaced string
1491 // second pass does the replacements
1492 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001493 mp_uint_t replaced_str_index = 0;
1494 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001495 const byte *old_occurrence;
1496 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001497 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001498 if (old_len == 0) {
1499 // if old_str is empty, copy new_str to start of replaced string
1500 // copy the replacement string
1501 if (data != NULL) {
1502 memcpy(data, new, new_len);
1503 }
1504 replaced_str_index += new_len;
1505 num_replacements_done++;
1506 }
Damien George963a5a32015-01-16 17:47:07 +00001507 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 +01001508 if (old_len == 0) {
1509 old_occurrence += 1;
1510 }
Damien George94f68302014-01-31 23:45:12 +00001511 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1512 if (data != NULL) {
1513 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1514 }
1515 replaced_str_index += old_occurrence - offset_ptr;
1516 // copy the replacement string
1517 if (data != NULL) {
1518 memcpy(data + replaced_str_index, new, new_len);
1519 }
1520 replaced_str_index += new_len;
1521 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001522 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001523 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001524 }
1525
1526 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1527 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001528 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001529 }
Damien Georgeff715422014-04-07 00:39:13 +01001530 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001531
1532 if (data == NULL) {
1533 // first pass
1534 if (num_replacements_done == 0) {
1535 // no substr found, return original string
1536 return args[0];
1537 } else {
1538 // substr found, allocate new string
Damien George05005f62015-01-21 22:48:37 +00001539 vstr_init_len(&vstr, replaced_str_index);
1540 data = (byte*)vstr.buf;
Damien Georgeff715422014-04-07 00:39:13 +01001541 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001542 }
1543 } else {
1544 // second pass, we are done
1545 break;
1546 }
xbe480c15a2014-01-30 22:17:30 -08001547 }
Damien George94f68302014-01-31 23:45:12 +00001548
Damien George05005f62015-01-21 22:48:37 +00001549 return mp_obj_new_str_from_vstr(self_type, &vstr);
xbe480c15a2014-01-30 22:17:30 -08001550}
1551
Damien Georgeecc88e92014-08-30 00:35:11 +01001552STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001553 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001554 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001555 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1556
1557 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001558 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001559 bad_implicit_conversion(args[1]);
1560 }
xbe9e1e8cd2014-03-12 22:57:16 -07001561
1562 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1563 GET_STR_DATA_LEN(args[1], needle, needle_len);
1564
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001565 const byte *start = haystack;
1566 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001567 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001568 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001569 }
1570 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001571 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001572 }
1573
Damien George536dde22014-03-13 22:07:55 +00001574 // if needle_len is zero then we count each gap between characters as an occurrence
1575 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001576 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001577 }
1578
Damien George536dde22014-03-13 22:07:55 +00001579 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001580 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001581 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1582 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001583 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001584 haystack_ptr += needle_len;
1585 } else {
1586 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001587 }
xbe9e1e8cd2014-03-12 22:57:16 -07001588 }
1589
1590 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1591}
1592
Damien George40f3c022014-07-03 13:25:24 +01001593STATIC 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 +00001594 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001595 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1596 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001597 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001598 }
Damien Georgeb035db32014-03-21 20:39:40 +00001599
xbe613a8e32014-03-18 00:06:29 -07001600 GET_STR_DATA_LEN(self_in, str, str_len);
1601 GET_STR_DATA_LEN(arg, sep, sep_len);
1602
1603 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001604 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001605 }
Damien Georgeb035db32014-03-21 20:39:40 +00001606
Damien Georgec55a4d82014-12-24 20:28:30 +00001607 mp_obj_t result[3];
1608 if (self_type == &mp_type_str) {
1609 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1610 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1611 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1612 } else {
1613 result[0] = mp_const_empty_bytes;
1614 result[1] = mp_const_empty_bytes;
1615 result[2] = mp_const_empty_bytes;
1616 }
Damien Georgeb035db32014-03-21 20:39:40 +00001617
1618 if (direction > 0) {
1619 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001620 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001621 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001622 }
xbe613a8e32014-03-18 00:06:29 -07001623
xbe17a5a832014-03-23 23:31:58 -07001624 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1625 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001626 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001627 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001628 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001629 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 -07001630 }
Damien Georgeb035db32014-03-21 20:39:40 +00001631
xbe0a6894c2014-03-21 01:12:26 -07001632 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001633}
1634
Damien Georgeb035db32014-03-21 20:39:40 +00001635STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1636 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001637}
xbe4504ea82014-03-19 00:46:14 -07001638
Damien Georgeb035db32014-03-21 20:39:40 +00001639STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1640 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001641}
1642
Paul Sokolovsky69135212014-05-10 19:47:41 +03001643// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001644STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001645 GET_STR_DATA_LEN(self_in, self_data, self_len);
Damien George05005f62015-01-21 22:48:37 +00001646 vstr_t vstr;
1647 vstr_init_len(&vstr, self_len);
1648 byte *data = (byte*)vstr.buf;
Damien George39dc1452014-10-03 19:52:22 +01001649 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001650 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001651 }
Damien George05005f62015-01-21 22:48:37 +00001652 return mp_obj_new_str_from_vstr(mp_obj_get_type(self_in), &vstr);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001653}
1654
1655STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001656 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001657}
1658
1659STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001660 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001661}
1662
Damien Georgefcc9cf62014-06-01 18:22:09 +01001663STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001664 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001665
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001666 if (self_len == 0) {
1667 return mp_const_false; // default to False for empty str
1668 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001669
Damien Georgefcc9cf62014-06-01 18:22:09 +01001670 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001671 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001672 if (!f(*self_data++)) {
1673 return mp_const_false;
1674 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001675 }
1676 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001677 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001678
Damien George39dc1452014-10-03 19:52:22 +01001679 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001680 if (unichar_isalpha(*self_data++)) {
1681 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001682 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1683 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001684 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001685 }
1686 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001687
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001688 if (!contains_alpha) {
1689 return mp_const_false;
1690 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001691 }
1692
1693 return mp_const_true;
1694}
1695
1696STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001697 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001698}
1699
1700STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001701 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001702}
1703
1704STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001705 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001706}
1707
1708STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001709 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001710}
1711
1712STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001713 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001714}
1715
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001716#if MICROPY_CPYTHON_COMPAT
1717// These methods are superfluous in the presense of str() and bytes()
1718// constructors.
1719// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001720STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001721 mp_obj_t new_args[2];
1722 if (n_args == 1) {
1723 new_args[0] = args[0];
1724 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1725 args = new_args;
1726 n_args++;
1727 }
Damien George0b9ee862015-01-21 19:14:25 +00001728 return str_make_new((mp_obj_t)&mp_type_str, n_args, 0, args);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001729}
1730
1731// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001732STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001733 mp_obj_t new_args[2];
1734 if (n_args == 1) {
1735 new_args[0] = args[0];
1736 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1737 args = new_args;
1738 n_args++;
1739 }
1740 return bytes_make_new(NULL, n_args, 0, args);
1741}
1742#endif
1743
Damien George4d917232014-08-30 14:28:06 +01001744mp_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 +01001745 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001746 GET_STR_DATA_LEN(self_in, str_data, str_len);
1747 bufinfo->buf = (void*)str_data;
1748 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001749 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001750 return 0;
1751 } else {
1752 // can't write to a string
1753 bufinfo->buf = NULL;
1754 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001755 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001756 return 1;
1757 }
1758}
1759
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001760#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001761MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1762MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001763#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001764MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1765MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1766MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1767MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1768MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1769MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1770MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1771MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1772MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1773MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1774MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1775MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001776MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001777MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1778MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1779MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1780MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1781MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1782MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1783MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1784MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1785MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1786MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1787MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001788
Damien George9b196cd2014-03-26 21:47:19 +00001789STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001790#if MICROPY_CPYTHON_COMPAT
1791 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001792 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1793 // If we have separate unicode type, then here we have methods only
1794 // for bytes type, and it should not have encode() methods. Otherwise,
1795 // we have non-compliant-but-practical bytestring type, which shares
1796 // method table with bytes, so they both have encode() and decode()
1797 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001798 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001799 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001800#endif
Damien George9b196cd2014-03-26 21:47:19 +00001801 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1802 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001803 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1804 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001805 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1806 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001807 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001808 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001809 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001810 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001811 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1812 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001813 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1814 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1815 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1816 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1817 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001818 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1819 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001820 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1821 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1822 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1823 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1824 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001825};
Damien George97209d32014-01-07 15:58:30 +00001826
Damien George9b196cd2014-03-26 21:47:19 +00001827STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1828
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001829#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001830const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001831 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001832 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001833 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001834 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001835 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001836 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001837 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001838 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001839 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001840};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001841#endif
Damiend99b0522013-12-21 18:17:45 +00001842
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001843// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001844const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001845 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001846 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001847 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001848 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001849 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001850 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001851 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001852 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001853 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001854};
1855
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001856// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001857const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001858
Damien George4abff752014-08-30 14:59:21 +01001859mp_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 +02001860 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001861 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001862 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001863 if (data) {
1864 o->hash = qstr_compute_hash(data, len);
1865 byte *p = m_new(byte, len + 1);
1866 o->data = p;
1867 memcpy(p, data, len * sizeof(byte));
1868 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1869 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001870 return o;
1871}
1872
Damien George0b9ee862015-01-21 19:14:25 +00001873mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) {
1874 // if not a bytes object, look if a qstr with this data already exists
1875 if (type == &mp_type_str) {
1876 qstr q = qstr_find_strn(vstr->buf, vstr->len);
1877 if (q != MP_QSTR_NULL) {
1878 vstr_clear(vstr);
1879 vstr->alloc = 0;
1880 return MP_OBJ_NEW_QSTR(q);
1881 }
1882 }
1883
1884 // make a new str/bytes object
1885 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
1886 o->base.type = type;
1887 o->len = vstr->len;
1888 o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len);
1889 o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1);
1890 vstr->buf = NULL;
1891 vstr->alloc = 0;
1892 return o;
1893}
1894
Damien Georged182b982014-08-30 14:19:41 +01001895mp_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 +01001896 if (make_qstr_if_not_already) {
1897 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001898 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001899 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001900 qstr q = qstr_find_strn(data, len);
1901 if (q != MP_QSTR_NULL) {
1902 // qstr with this data already exists
1903 return MP_OBJ_NEW_QSTR(q);
1904 } else {
1905 // no existing qstr, don't make one
1906 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1907 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001908 }
Damien George5fa93b62014-01-22 14:35:10 +00001909}
1910
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001911mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1912 GET_STR_DATA_LEN(str, data, len);
1913 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1914}
1915
Damien Georged182b982014-08-30 14:19:41 +01001916mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001917 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001918}
1919
Damien George5fa93b62014-01-22 14:35:10 +00001920bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1921 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1922 return s1 == s2;
1923 } else {
1924 GET_STR_HASH(s1, h1);
1925 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001926 // If any of hashes is 0, it means it's not valid
1927 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001928 return false;
1929 }
1930 GET_STR_DATA_LEN(s1, d1, l1);
1931 GET_STR_DATA_LEN(s2, d2, l2);
1932 if (l1 != l2) {
1933 return false;
1934 }
Damien George1e708fe2014-01-23 18:27:51 +00001935 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001936 }
Damien George5fa93b62014-01-22 14:35:10 +00001937}
1938
Damien Georgedeed0872014-04-06 11:11:15 +01001939STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001940 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1941 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1942 "can't convert to str implicitly"));
1943 } else {
1944 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1945 "can't convert '%s' object to str implicitly",
1946 mp_obj_get_type_str(self_in)));
1947 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001948}
1949
Damien Georged182b982014-08-30 14:19:41 +01001950mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001951 // TODO: This has too big overhead for hash accessor
Damien Georgebe8e99c2014-11-05 16:45:54 +00001952 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001953 GET_STR_HASH(self_in, h);
1954 return h;
1955 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001956 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001957 }
1958}
1959
Damien Georged182b982014-08-30 14:19:41 +01001960mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001961 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001962 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001963 GET_STR_LEN(self_in, l);
1964 return l;
1965 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001966 bad_implicit_conversion(self_in);
1967 }
1968}
1969
1970// use this if you will anyway convert the string to a qstr
1971// will be more efficient for the case where it's already a qstr
1972qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1973 if (MP_OBJ_IS_QSTR(self_in)) {
1974 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001975 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001976 mp_obj_str_t *self = self_in;
1977 return qstr_from_strn((char*)self->data, self->len);
1978 } else {
1979 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001980 }
1981}
1982
1983// only use this function if you need the str data to be zero terminated
1984// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1985const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02001986 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001987 GET_STR_DATA_LEN(self_in, s, l);
1988 (void)l; // len unused
1989 return (const char*)s;
1990 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001991 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001992 }
1993}
1994
Damien Georged182b982014-08-30 14:19:41 +01001995const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001996 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001997 GET_STR_DATA_LEN(self_in, s, l);
1998 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001999 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002000 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002001 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002002 }
Damiend99b0522013-12-21 18:17:45 +00002003}
xyb8cfc9f02014-01-05 18:47:51 +08002004
2005/******************************************************************************/
2006/* str iterator */
2007
2008typedef struct _mp_obj_str_it_t {
2009 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002010 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002011 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08002012} mp_obj_str_it_t;
2013
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002014#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002015STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08002016 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002017 GET_STR_DATA_LEN(self->str, str, len);
2018 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002019 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002020 self->cur += 1;
2021 return o_out;
2022 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002023 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002024 }
2025}
2026
Damien George3e1a5c12014-03-29 13:43:38 +00002027STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002028 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002029 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002030 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002031 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002032};
2033
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002034mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2035 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
2036 o->base.type = &mp_type_str_it;
2037 o->str = str;
2038 o->cur = 0;
2039 return o;
2040}
2041#endif
2042
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002043STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002044 mp_obj_str_it_t *self = self_in;
2045 GET_STR_DATA_LEN(self->str, str, len);
2046 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002047 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002048 self->cur += 1;
2049 return o_out;
2050 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002051 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002052 }
2053}
2054
Damien George3e1a5c12014-03-29 13:43:38 +00002055STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002056 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002057 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002058 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002059 .iternext = bytes_it_iternext,
2060};
2061
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002062mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
2063 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002064 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002065 o->str = str;
2066 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002067 return o;
2068}