blob: 714a170d0ae39874db28274abfd3b305c38d102c [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
xbeefe34222014-03-16 00:14:26 -070028#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +000029#include <string.h>
30#include <assert.h>
31
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030032#include "mpconfig.h"
Damiend99b0522013-12-21 18:17:45 +000033#include "nlr.h"
34#include "misc.h"
Paul Sokolovsky5048df02014-06-14 03:15:00 +030035#include "unicode.h"
Damien George55baff42014-01-21 21:40:13 +000036#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000037#include "obj.h"
38#include "runtime0.h"
39#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070040#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030041#include "objstr.h"
Paul Sokolovsky2a273652014-05-13 08:07:08 +030042#include "objlist.h"
Damiend99b0522013-12-21 18:17:45 +000043
Paul Sokolovsky75ce9252014-06-05 20:02:15 +030044STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020045const mp_obj_t mp_const_empty_bytes;
46
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030047mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020048STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030049STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030050STATIC NORETURN void arg_type_mixup();
51
52STATIC bool is_str_or_bytes(mp_obj_t o) {
53 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
54}
xyb8cfc9f02014-01-05 18:47:51 +080055
56/******************************************************************************/
57/* str */
58
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030059void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
60 const byte *str_data, uint str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020061 // this escapes characters, but it will be very slow to print (calling print many times)
62 bool has_single_quote = false;
63 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100064 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020065 if (*s == '\'') {
66 has_single_quote = true;
67 } else if (*s == '"') {
68 has_double_quote = true;
69 }
70 }
71 int quote_char = '\'';
72 if (has_single_quote && !has_double_quote) {
73 quote_char = '"';
74 }
75 print(env, "%c", quote_char);
76 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
77 if (*s == quote_char) {
78 print(env, "\\%c", quote_char);
79 } else if (*s == '\\') {
80 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030081 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
82 // In strings, anything which is not ascii control character
83 // is printed as is, this includes characters in range 0x80-0xff
84 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020085 print(env, "%c", *s);
86 } else if (*s == '\n') {
87 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010088 } else if (*s == '\r') {
89 print(env, "\\r");
90 } else if (*s == '\t') {
91 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020092 } else {
93 print(env, "\\x%02x", *s);
94 }
95 }
96 print(env, "%c", quote_char);
97}
98
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020099STATIC 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 +0000100 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000101 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200102 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000103 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200104 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200105 if (is_bytes) {
106 print(env, "b");
107 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300108 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200109 }
Damiend99b0522013-12-21 18:17:45 +0000110}
111
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200112STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300113#if MICROPY_CPYTHON_COMPAT
114 if (n_kw != 0) {
115 mp_arg_error_unimpl_kw();
116 }
117#endif
118
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200119 switch (n_args) {
120 case 0:
121 return MP_OBJ_NEW_QSTR(MP_QSTR_);
122
123 case 1:
124 {
125 vstr_t *vstr = vstr_new();
126 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100127 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200128 vstr_free(vstr);
129 return s;
130 }
131
132 case 2:
133 case 3:
134 {
135 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000136 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100137 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200138 }
139 GET_STR_DATA_LEN(args[0], str_data, str_len);
140 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100141 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200142 o->data = str_data;
143 o->hash = str_hash;
144 return o;
145 }
146
147 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100148 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200149 }
150}
151
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200152STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
153 if (n_args == 0) {
154 return mp_const_empty_bytes;
155 }
156
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300157#if MICROPY_CPYTHON_COMPAT
158 if (n_kw != 0) {
159 mp_arg_error_unimpl_kw();
160 }
161#endif
162
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200163 if (MP_OBJ_IS_STR(args[0])) {
164 if (n_args < 2 || n_args > 3) {
165 goto wrong_args;
166 }
167 GET_STR_DATA_LEN(args[0], str_data, str_len);
168 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100169 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200170 o->data = str_data;
171 o->hash = str_hash;
172 return o;
173 }
174
175 if (n_args > 1) {
176 goto wrong_args;
177 }
178
179 if (MP_OBJ_IS_SMALL_INT(args[0])) {
180 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
181 byte *data;
182
Damien George3e1a5c12014-03-29 13:43:38 +0000183 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200184 memset(data, 0, len);
185 return mp_obj_str_builder_end(o);
186 }
187
188 int len;
189 byte *data;
190 vstr_t *vstr = NULL;
191 mp_obj_t o = NULL;
192 // Try to create array of exact len if initializer len is known
193 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
194 if (len_in == MP_OBJ_NULL) {
195 len = -1;
196 vstr = vstr_new();
197 } else {
198 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000199 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200200 }
201
Damien Georged17926d2014-03-30 13:35:08 +0100202 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200203 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100204 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200205 if (len == -1) {
206 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
207 } else {
208 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
209 }
210 }
211
212 if (len == -1) {
213 vstr_shrink(vstr);
214 // TODO: Optimize, borrow buffer from vstr
215 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000216 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200217 memcpy(data, vstr_str(vstr), len);
218 vstr_free(vstr);
219 }
220
221 return mp_obj_str_builder_end(o);
222
223wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100224 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200225}
226
Damien George55baff42014-01-21 21:40:13 +0000227// like strstr but with specified length and allows \0 bytes
228// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700229STATIC const byte *find_subbytes(const byte *haystack, machine_uint_t hlen, const byte *needle, machine_uint_t nlen, machine_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000230 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700231 machine_uint_t str_index, str_index_end;
232 if (direction > 0) {
233 str_index = 0;
234 str_index_end = hlen - nlen;
235 } else {
236 str_index = hlen - nlen;
237 str_index_end = 0;
238 }
239 for (;;) {
240 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
241 //found
242 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000243 }
xbe17a5a832014-03-23 23:31:58 -0700244 if (str_index == str_index_end) {
245 //not found
246 break;
Damien George55baff42014-01-21 21:40:13 +0000247 }
xbe17a5a832014-03-23 23:31:58 -0700248 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000249 }
250 }
251 return NULL;
252}
253
Paul Sokolovsky97319122014-06-13 22:01:26 +0300254mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000255 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300256 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
257 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000258 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100259 case MP_BINARY_OP_ADD:
260 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300261 if (lhs_type == rhs_type) {
262 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000263
264 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000265 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000266
267 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000268 byte *q_ptr;
269 byte *val = qstr_build_start(alloc_len, &q_ptr);
270 memcpy(val, lhs_data, lhs_len);
271 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000272 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
273 */
274
275 // code for non-qstr
276 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300277 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000278 memcpy(data, lhs_data, lhs_len);
279 memcpy(data + lhs_len, rhs_data, rhs_len);
280 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000281 }
282 break;
Damien George5fa93b62014-01-22 14:35:10 +0000283
Damien Georged17926d2014-03-30 13:35:08 +0100284 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000285 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300286 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000287 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700288 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000289 }
290 break;
Damien George5fa93b62014-01-22 14:35:10 +0000291
Damien Georged0a5bf32014-05-10 13:55:11 +0100292 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200293 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100294 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200295 }
296 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000297 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300298 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000299 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
300 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200301 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200302
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300303 case MP_BINARY_OP_MODULO: {
304 mp_obj_t *args;
305 uint n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300306 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300307 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
308 // TODO: Support tuple subclasses?
309 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300310 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
311 args = NULL;
312 n_args = 0;
313 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300314 } else {
315 args = &rhs_in;
316 n_args = 1;
317 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300318 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300319 }
320
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300321 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
322 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 +0100323 case MP_BINARY_OP_LESS:
324 case MP_BINARY_OP_LESS_EQUAL:
325 case MP_BINARY_OP_MORE:
326 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300327 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200328 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
329 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
330 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300331 if (lhs_type == &mp_type_bytes) {
332 mp_buffer_info_t bufinfo;
333 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
334 goto uncomparable;
335 }
336 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
337 }
338uncomparable:
339 if (op == MP_BINARY_OP_EQUAL) {
340 return mp_const_false;
341 }
Damiend99b0522013-12-21 18:17:45 +0000342 }
343
Damien George6ac5dce2014-05-21 19:42:43 +0100344 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000345}
346
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300347const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, uint self_len,
348 mp_obj_t index, bool is_slice) {
349 machine_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
350 return self_data + index_val;
351}
352
Damien George729f7b42014-04-17 22:10:53 +0100353STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300354 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100355 GET_STR_DATA_LEN(self_in, self_data, self_len);
356 if (value == MP_OBJ_SENTINEL) {
357 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100358#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100359 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300360 mp_bound_slice_t slice;
361 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300362 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100363 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100364 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100365 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100366 }
367#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300368 const byte *p = str_index_to_ptr(type, self_data, self_len, index, false);
Damien George729f7b42014-04-17 22:10:53 +0100369 if (type == &mp_type_bytes) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300370 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)*p);
Damien George729f7b42014-04-17 22:10:53 +0100371 } else {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300372 return mp_obj_new_str((char*)p, 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100373 }
374 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100375 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100376 }
377}
378
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200379STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300380 assert(is_str_or_bytes(self_in));
381 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000382
Damien Georgefe8fb912014-01-02 16:36:09 +0000383 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000384 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000385
386 // process args
Damiend99b0522013-12-21 18:17:45 +0000387 uint seq_len;
388 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000389 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000390 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000391 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100392 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
393 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300394 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100395 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
396 }
397 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000398 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000399
400 // count required length
401 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000402 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300403 if (mp_obj_get_type(seq_items[i]) != self_type) {
404 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
405 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000406 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000407 if (i > 0) {
408 required_len += sep_len;
409 }
Damien George5fa93b62014-01-22 14:35:10 +0000410 GET_STR_LEN(seq_items[i], l);
411 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000412 }
413
414 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000415 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300416 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000417 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000418 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000419 memcpy(data, sep_str, sep_len);
420 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000421 }
Damien George5fa93b62014-01-22 14:35:10 +0000422 GET_STR_DATA_LEN(seq_items[i], s, l);
423 memcpy(data, s, l);
424 data += l;
Damiend99b0522013-12-21 18:17:45 +0000425 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000426
427 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000428 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000429}
430
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200431#define is_ws(c) ((c) == ' ' || (c) == '\t')
432
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200433STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300434 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100435 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200436 mp_obj_t sep = mp_const_none;
437 if (n_args > 1) {
438 sep = args[1];
439 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100440 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200441 }
442 }
Damien Georgedeed0872014-04-06 11:11:15 +0100443
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200444 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000445 GET_STR_DATA_LEN(args[0], s, len);
446 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200447
Damien Georgedeed0872014-04-06 11:11:15 +0100448 if (sep == mp_const_none) {
449 // sep not given, so separate on whitespace
450
451 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000452 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100453 while (s < top && splits != 0) {
454 const byte *start = s;
455 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100456 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100457 if (s >= top) {
458 break;
459 }
460 while (s < top && is_ws(*s)) s++;
461 if (splits > 0) {
462 splits--;
463 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200464 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200465
Damien Georgedeed0872014-04-06 11:11:15 +0100466 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100467 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100468 }
469
470 } else {
471 // sep given
472
473 uint sep_len;
474 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
475
476 if (sep_len == 0) {
477 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
478 }
479
480 for (;;) {
481 const byte *start = s;
482 for (;;) {
483 if (splits == 0 || s + sep_len > top) {
484 s = top;
485 break;
486 } else if (memcmp(s, sep_str, sep_len) == 0) {
487 break;
488 }
489 s++;
490 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100491 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100492 if (s >= top) {
493 break;
494 }
495 s += sep_len;
496 if (splits > 0) {
497 splits--;
498 }
499 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200500 }
501
502 return res;
503}
504
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300505STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
506 if (n_args < 3) {
507 // If we don't have split limit, it doesn't matter from which side
508 // we split.
509 return str_split(n_args, args);
510 }
511 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
512 mp_obj_t sep = args[1];
513 GET_STR_DATA_LEN(args[0], s, len);
514
515 machine_int_t splits = mp_obj_get_int(args[2]);
516 machine_int_t org_splits = splits;
517 // Preallocate list to the max expected # of elements, as we
518 // will fill it from the end.
519 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
520 int idx = splits;
521
522 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000523 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300524 } else {
525 uint sep_len;
526 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
527
528 if (sep_len == 0) {
529 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
530 }
531
532 const byte *beg = s;
533 const byte *last = s + len;
534 for (;;) {
535 s = last - sep_len;
536 for (;;) {
537 if (splits == 0 || s < beg) {
538 break;
539 } else if (memcmp(s, sep_str, sep_len) == 0) {
540 break;
541 }
542 s--;
543 }
544 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100545 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300546 break;
547 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100548 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 +0300549 last = s;
550 if (splits > 0) {
551 splits--;
552 }
553 }
554 if (idx != 0) {
555 // We split less parts than split limit, now go cleanup surplus
556 int used = org_splits + 1 - idx;
557 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
558 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
559 res->len = used;
560 }
561 }
562
563 return res;
564}
565
566
xbe3d9a39e2014-04-08 11:42:19 -0700567STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, machine_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300568 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000569 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000570 assert(MP_OBJ_IS_STR(args[0]));
571 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000572
Damien George5fa93b62014-01-22 14:35:10 +0000573 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
574 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000575
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300576 const byte *start = haystack;
577 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000578 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300579 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000580 }
581 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300582 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000583 }
584
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300585 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000586 if (p == NULL) {
587 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700588 if (is_index) {
589 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
590 } else {
591 return MP_OBJ_NEW_SMALL_INT(-1);
592 }
Damien George23005372014-01-13 19:39:01 +0000593 } else {
594 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300595 #if MICROPY_PY_BUILTINS_STR_UNICODE
596 if (self_type == &mp_type_str) {
597 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
598 }
599 #endif
xbe17a5a832014-03-23 23:31:58 -0700600 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000601 }
John R. Lentone8204912014-01-12 21:53:52 +0000602}
603
xbe17a5a832014-03-23 23:31:58 -0700604STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700605 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700606}
607
608STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700609 return str_finder(n_args, args, -1, false);
610}
611
612STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
613 return str_finder(n_args, args, 1, true);
614}
615
616STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
617 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700618}
619
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200620// TODO: (Much) more variety in args
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300621STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300622 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300623 GET_STR_DATA_LEN(args[0], str, str_len);
624 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300625 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300626 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300627 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300628 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300629 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200630 return mp_const_false;
631 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300632 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200633}
634
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300635STATIC mp_obj_t str_endswith(uint n_args, const mp_obj_t *args) {
636 GET_STR_DATA_LEN(args[0], str, str_len);
637 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
638 assert(n_args == 2);
639
640 if (suffix_len > str_len) {
641 return mp_const_false;
642 }
643 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
644}
645
Paul Sokolovsky88107842014-04-26 06:20:08 +0300646enum { LSTRIP, RSTRIP, STRIP };
647
648STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800649 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300650 assert(is_str_or_bytes(args[0]));
651 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000652
653 const byte *chars_to_del;
654 uint chars_to_del_len;
655 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800656
657 if (n_args == 1) {
658 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000659 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800660 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300661 if (mp_obj_get_type(args[1]) != self_type) {
662 arg_type_mixup();
663 }
Damien George5fa93b62014-01-22 14:35:10 +0000664 GET_STR_DATA_LEN(args[1], s, l);
665 chars_to_del = s;
666 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800667 }
668
Damien George5fa93b62014-01-22 14:35:10 +0000669 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800670
xbec5538882014-03-16 17:58:35 -0700671 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800672 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700673 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300674 machine_uint_t i = 0;
675 machine_int_t delta = 1;
676 if (type == RSTRIP) {
677 i = orig_str_len - 1;
678 delta = -1;
679 }
680 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700681 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800682 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300683 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800684 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300685 if (type == LSTRIP) {
686 last_good_char_pos = orig_str_len - 1;
687 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300688 } else if (type == RSTRIP) {
689 first_good_char_pos = 0;
690 last_good_char_pos = i;
691 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300692 }
xbe7b0f39f2014-01-08 14:23:45 -0800693 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300694 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800695 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300696 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800697 }
698
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300699 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000700 // string is all whitespace, return ''
701 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800702 }
703
704 assert(last_good_char_pos >= first_good_char_pos);
705 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700706 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300707 if (stripped_len == orig_str_len) {
708 // If nothing was stripped, don't bother to dup original string
709 // TODO: watch out for this case when we'll get to bytearray.strip()
710 assert(first_good_char_pos == 0);
711 return args[0];
712 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100713 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800714}
715
Paul Sokolovsky88107842014-04-26 06:20:08 +0300716STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
717 return str_uni_strip(STRIP, n_args, args);
718}
719
720STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
721 return str_uni_strip(LSTRIP, n_args, args);
722}
723
724STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
725 return str_uni_strip(RSTRIP, n_args, args);
726}
727
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700728// Takes an int arg, but only parses unsigned numbers, and only changes
729// *num if at least one digit was parsed.
730static int str_to_int(const char *str, int *num) {
731 const char *s = str;
732 if (unichar_isdigit(*s)) {
733 *num = 0;
734 do {
735 *num = *num * 10 + (*s - '0');
736 s++;
737 }
738 while (unichar_isdigit(*s));
739 }
740 return s - str;
741}
742
743static bool isalignment(char ch) {
744 return ch && strchr("<>=^", ch) != NULL;
745}
746
747static bool istype(char ch) {
748 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
749}
750
751static bool arg_looks_integer(mp_obj_t arg) {
752 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
753}
754
755static bool arg_looks_numeric(mp_obj_t arg) {
756 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100757#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700758 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
759#endif
760 ;
761}
762
Dave Hylandsc4029e52014-04-07 11:19:51 -0700763static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100764#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700765 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700766
767 // TODO: Needs a way to construct an mpz integer from a float
768
769 mp_small_int_t num = mp_obj_get_float(arg);
770 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700771 }
772#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700773 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700774}
775
Damien George897fe0c2014-04-15 22:03:55 +0100776mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000777 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000778
Damien George5fa93b62014-01-22 14:35:10 +0000779 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700780 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000781 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700782 pfenv_t pfenv_vstr;
783 pfenv_vstr.data = vstr;
784 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
785
Damien George5fa93b62014-01-22 14:35:10 +0000786 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700787 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000788 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700789 if (str < top && *str == '}') {
790 vstr_add_char(vstr, '}');
791 continue;
792 }
Damien George11de8392014-06-05 18:57:38 +0100793 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700794 }
795 if (*str != '{') {
796 vstr_add_char(vstr, *str);
797 continue;
798 }
799
800 str++;
801 if (str < top && *str == '{') {
802 vstr_add_char(vstr, '{');
803 continue;
804 }
805
806 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
807
808 vstr_t *field_name = NULL;
809 char conversion = '\0';
810 vstr_t *format_spec = NULL;
811
812 if (str < top && *str != '}' && *str != '!' && *str != ':') {
813 field_name = vstr_new();
814 while (str < top && *str != '}' && *str != '!' && *str != ':') {
815 vstr_add_char(field_name, *str++);
816 }
817 vstr_add_char(field_name, '\0');
818 }
819
820 // conversion ::= "r" | "s"
821
822 if (str < top && *str == '!') {
823 str++;
824 if (str < top && (*str == 'r' || *str == 's')) {
825 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200826 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100827 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "end of format while looking for conversion specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700828 }
829 }
830
831 if (str < top && *str == ':') {
832 str++;
833 // {:} is the same as {}, which is the same as {!s}
834 // This makes a difference when passing in a True or False
835 // '{}'.format(True) returns 'True'
836 // '{:d}'.format(True) returns '1'
837 // So we treat {:} as {} and this later gets treated to be {!s}
838 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100839 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700840 while (str < top && *str != '}') {
841 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000842 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700843 vstr_add_char(format_spec, '\0');
844 }
845 }
846 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100847 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700848 }
849 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100850 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700851 }
852
853 mp_obj_t arg = mp_const_none;
854
855 if (field_name) {
856 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100857 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700858 }
Damien George3bb8bd82014-04-14 21:20:30 +0100859 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100861 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700862 }
863 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100864 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700865 }
866 arg = args[index + 1];
867 arg_i = -1;
868 vstr_free(field_name);
869 field_name = NULL;
870 } else {
871 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100872 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700873 }
874 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100875 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700876 }
877 arg = args[arg_i + 1];
878 arg_i++;
879 }
880 if (!format_spec && !conversion) {
881 conversion = 's';
882 }
883 if (conversion) {
884 mp_print_kind_t print_kind;
885 if (conversion == 's') {
886 print_kind = PRINT_STR;
887 } else if (conversion == 'r') {
888 print_kind = PRINT_REPR;
889 } else {
Damien George11de8392014-06-05 18:57:38 +0100890 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700891 }
892 vstr_t *arg_vstr = vstr_new();
893 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100894 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700895 vstr_free(arg_vstr);
896 }
897
898 char sign = '\0';
899 char fill = '\0';
900 char align = '\0';
901 int width = -1;
902 int precision = -1;
903 char type = '\0';
904 int flags = 0;
905
906 if (format_spec) {
907 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
908 //
909 // [[fill]align][sign][#][0][width][,][.precision][type]
910 // fill ::= <any character>
911 // align ::= "<" | ">" | "=" | "^"
912 // sign ::= "+" | "-" | " "
913 // width ::= integer
914 // precision ::= integer
915 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
916
917 const char *s = vstr_str(format_spec);
918 if (isalignment(*s)) {
919 align = *s++;
920 } else if (*s && isalignment(s[1])) {
921 fill = *s++;
922 align = *s++;
923 }
924 if (*s == '+' || *s == '-' || *s == ' ') {
925 if (*s == '+') {
926 flags |= PF_FLAG_SHOW_SIGN;
927 } else if (*s == ' ') {
928 flags |= PF_FLAG_SPACE_SIGN;
929 }
930 sign = *s++;
931 }
932 if (*s == '#') {
933 flags |= PF_FLAG_SHOW_PREFIX;
934 s++;
935 }
936 if (*s == '0') {
937 if (!align) {
938 align = '=';
939 }
940 if (!fill) {
941 fill = '0';
942 }
943 }
944 s += str_to_int(s, &width);
945 if (*s == ',') {
946 flags |= PF_FLAG_SHOW_COMMA;
947 s++;
948 }
949 if (*s == '.') {
950 s++;
951 s += str_to_int(s, &precision);
952 }
953 if (istype(*s)) {
954 type = *s++;
955 }
956 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100957 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700958 }
959 vstr_free(format_spec);
960 format_spec = NULL;
961 }
962 if (!align) {
963 if (arg_looks_numeric(arg)) {
964 align = '>';
965 } else {
966 align = '<';
967 }
968 }
969 if (!fill) {
970 fill = ' ';
971 }
972
973 if (sign) {
974 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100975 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700976 }
977 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100978 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000979 }
980 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700981 sign = '-';
982 }
983
984 switch (align) {
985 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
986 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
987 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
988 }
989
990 if (arg_looks_integer(arg)) {
991 switch (type) {
992 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -0700993 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700994 continue;
995
996 case 'c':
997 {
998 char ch = mp_obj_get_int(arg);
999 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1000 continue;
1001 }
1002
1003 case '\0': // No explicit format type implies 'd'
1004 case 'n': // I don't think we support locales in uPy so use 'd'
1005 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001006 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001007 continue;
1008
1009 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001010 if (flags & PF_FLAG_SHOW_PREFIX) {
1011 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1012 }
1013
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001014 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001015 continue;
1016
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001017 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001018 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001019 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001020 continue;
1021
1022 case 'e':
1023 case 'E':
1024 case 'f':
1025 case 'F':
1026 case 'g':
1027 case 'G':
1028 case '%':
1029 // The floating point formatters all work with anything that
1030 // looks like an integer
1031 break;
1032
1033 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001034 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001035 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001036 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001037 }
Damien George70f33cd2014-04-02 17:06:05 +01001038
Dave Hylands22fe4d72014-04-02 12:07:31 -07001039 // NOTE: no else here. We need the e, f, g etc formats for integer
1040 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001041 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001042 if (!type) {
1043
1044 // Even though the docs say that an unspecified type is the same
1045 // as 'g', there is one subtle difference, when the exponent
1046 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001047 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001048 // '{:10.1}'.format(0.0) ==> '0e+00'
1049 // '{:10.1g}'.format(0.0) ==> '0'
1050 //
1051 // TODO: Figure out how to deal with this.
1052 //
1053 // A proper solution would involve adding a special flag
1054 // or something to format_float, and create a format_double
1055 // to deal with doubles. In order to fix this when using
1056 // sprintf, we'd need to use the e format and tweak the
1057 // returned result to strip trailing zeros like the g format
1058 // does.
1059 //
1060 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1061 // but with 1.e2 you get 1e+02 and 1.00e+02
1062 //
1063 // Stripping the trailing 0's (like g) does would make the
1064 // e format give us the right format.
1065 //
1066 // CPython sources say:
1067 // Omitted type specifier. Behaves in the same way as repr(x)
1068 // and str(x) if no precision is given, else like 'g', but with
1069 // at least one digit after the decimal point. */
1070
1071 type = 'g';
1072 }
1073 if (type == 'n') {
1074 type = 'g';
1075 }
1076
1077 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1078 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001079#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001080 case 'e':
1081 case 'E':
1082 case 'f':
1083 case 'F':
1084 case 'g':
1085 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001086 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001087 break;
1088
1089 case '%':
1090 flags |= PF_FLAG_ADD_PERCENT;
1091 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1092 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001093#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001094
1095 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001096 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001097 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001098 type, mp_obj_get_type_str(arg)));
1099 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001100 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001101 // arg doesn't look like a number
1102
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001103 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001104 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001105 }
Damien George70f33cd2014-04-02 17:06:05 +01001106
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001107 switch (type) {
1108 case '\0':
1109 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1110 break;
1111
1112 case 's':
1113 {
1114 uint len;
1115 const char *s = mp_obj_str_get_data(arg, &len);
1116 if (precision < 0) {
1117 precision = len;
1118 }
1119 if (len > precision) {
1120 len = precision;
1121 }
1122 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1123 break;
1124 }
1125
1126 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001127 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001128 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001129 type, mp_obj_get_type_str(arg)));
1130 }
Damiend99b0522013-12-21 18:17:45 +00001131 }
1132 }
1133
Damien George2617eeb2014-05-25 22:27:57 +01001134 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001135 vstr_free(vstr);
1136 return s;
Damiend99b0522013-12-21 18:17:45 +00001137}
1138
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001139STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args, mp_obj_t dict) {
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001140 assert(MP_OBJ_IS_STR(pattern));
1141
1142 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001143 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001144 int arg_i = 0;
1145 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001146 pfenv_t pfenv_vstr;
1147 pfenv_vstr.data = vstr;
1148 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1149
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001150 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001151 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001152 if (*str != '%') {
1153 vstr_add_char(vstr, *str);
1154 continue;
1155 }
1156 if (++str >= top) {
1157 break;
1158 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001159 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001160 vstr_add_char(vstr, '%');
1161 continue;
1162 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001163
1164 // Dictionary value lookup
1165 if (*str == '(') {
1166 const byte *key = ++str;
1167 while (*str != ')') {
1168 if (str >= top) {
1169 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1170 }
1171 ++str;
1172 }
1173 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1174 arg = mp_obj_dict_get(dict, k_obj);
1175 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001176 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001177
Dave Hylands6756a372014-04-02 11:42:39 -07001178 int flags = 0;
1179 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001180 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001181 while (str < top) {
1182 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1183 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1184 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001185 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001186 else if (*str == '0') {
1187 flags |= PF_FLAG_PAD_AFTER_SIGN;
1188 fill = '0';
1189 } else break;
1190 str++;
1191 }
1192 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001193 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001194 if (str < top) {
1195 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001196 if (arg_i >= n_args) {
1197 goto not_enough_args;
1198 }
Dave Hylands6756a372014-04-02 11:42:39 -07001199 width = mp_obj_get_int(args[arg_i++]);
1200 str++;
1201 } else {
1202 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1203 width = width * 10 + *str - '0';
1204 }
1205 }
1206 }
1207 int prec = -1;
1208 if (str < top && *str == '.') {
1209 if (++str < top) {
1210 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001211 if (arg_i >= n_args) {
1212 goto not_enough_args;
1213 }
Dave Hylands6756a372014-04-02 11:42:39 -07001214 prec = mp_obj_get_int(args[arg_i++]);
1215 str++;
1216 } else {
1217 prec = 0;
1218 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1219 prec = prec * 10 + *str - '0';
1220 }
1221 }
1222 }
1223 }
1224
1225 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001226 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001227 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001228
1229 // Tuple value lookup
1230 if (arg == MP_OBJ_NULL) {
1231 if (arg_i >= n_args) {
1232not_enough_args:
1233 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1234 }
1235 arg = args[arg_i++];
1236 }
Dave Hylands6756a372014-04-02 11:42:39 -07001237 switch (*str) {
1238 case 'c':
1239 if (MP_OBJ_IS_STR(arg)) {
1240 uint len;
1241 const char *s = mp_obj_str_get_data(arg, &len);
1242 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001243 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001244 break;
1245 }
1246 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1247 break;
1248 }
1249 if (arg_looks_integer(arg)) {
1250 char ch = mp_obj_get_int(arg);
1251 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1252 break;
1253 }
Damien Georgefb510b32014-06-01 13:32:54 +01001254#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001255 // This is what CPython reports, so we report the same.
1256 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001257 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001258
1259 }
1260#endif
Damien George11de8392014-06-05 18:57:38 +01001261 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1262 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001263
1264 case 'd':
1265 case 'i':
1266 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001267 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001268 break;
1269
Damien Georgefb510b32014-06-01 13:32:54 +01001270#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001271 case 'e':
1272 case 'E':
1273 case 'f':
1274 case 'F':
1275 case 'g':
1276 case 'G':
1277 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1278 break;
1279#endif
1280
1281 case 'o':
1282 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001283 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001284 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001285 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001286 break;
1287
1288 case 'r':
1289 case 's':
1290 {
1291 vstr_t *arg_vstr = vstr_new();
1292 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1293 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1294 uint len = vstr_len(arg_vstr);
1295 if (prec < 0) {
1296 prec = len;
1297 }
1298 if (len > prec) {
1299 len = prec;
1300 }
1301 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1302 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001303 break;
1304 }
Dave Hylands6756a372014-04-02 11:42:39 -07001305
Dave Hylands6756a372014-04-02 11:42:39 -07001306 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001307 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001308 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001309 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001310
Dave Hylands6756a372014-04-02 11:42:39 -07001311 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001312 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001313 "unsupported format character '%c' (0x%x) at index %d",
1314 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001315 }
1316 }
1317
1318 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001319 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001320 }
1321
Damien George2617eeb2014-05-25 22:27:57 +01001322 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001323 vstr_free(vstr);
1324 return s;
1325}
1326
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001327STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001328 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001329
Damien Georgeff715422014-04-07 00:39:13 +01001330 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001331 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001332 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001333 if (max_rep == 0) {
1334 return args[0];
1335 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001336 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001337 }
xbe480c15a2014-01-30 22:17:30 -08001338 }
Damien George94f68302014-01-31 23:45:12 +00001339
xbe729be9b2014-04-07 14:46:39 -07001340 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001341
Damien Georgeff715422014-04-07 00:39:13 +01001342 // check argument types
1343
1344 if (!MP_OBJ_IS_STR(args[1])) {
1345 bad_implicit_conversion(args[1]);
1346 }
1347
1348 if (!MP_OBJ_IS_STR(args[2])) {
1349 bad_implicit_conversion(args[2]);
1350 }
1351
1352 // extract string data
1353
xbe480c15a2014-01-30 22:17:30 -08001354 GET_STR_DATA_LEN(args[0], str, str_len);
1355 GET_STR_DATA_LEN(args[1], old, old_len);
1356 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001357
1358 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001359 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001360 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001361 }
1362
Damien George94f68302014-01-31 23:45:12 +00001363 // data for the replaced string
1364 byte *data = NULL;
1365 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001366
Damien George94f68302014-01-31 23:45:12 +00001367 // do 2 passes over the string:
1368 // first pass computes the required length of the replaced string
1369 // second pass does the replacements
1370 for (;;) {
1371 machine_uint_t replaced_str_index = 0;
1372 machine_uint_t num_replacements_done = 0;
1373 const byte *old_occurrence;
1374 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001375 machine_uint_t str_len_remain = str_len;
1376 if (old_len == 0) {
1377 // if old_str is empty, copy new_str to start of replaced string
1378 // copy the replacement string
1379 if (data != NULL) {
1380 memcpy(data, new, new_len);
1381 }
1382 replaced_str_index += new_len;
1383 num_replacements_done++;
1384 }
1385 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1386 if (old_len == 0) {
1387 old_occurrence += 1;
1388 }
Damien George94f68302014-01-31 23:45:12 +00001389 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1390 if (data != NULL) {
1391 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1392 }
1393 replaced_str_index += old_occurrence - offset_ptr;
1394 // copy the replacement string
1395 if (data != NULL) {
1396 memcpy(data + replaced_str_index, new, new_len);
1397 }
1398 replaced_str_index += new_len;
1399 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001400 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001401 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001402 }
1403
1404 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1405 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001406 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001407 }
Damien Georgeff715422014-04-07 00:39:13 +01001408 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001409
1410 if (data == NULL) {
1411 // first pass
1412 if (num_replacements_done == 0) {
1413 // no substr found, return original string
1414 return args[0];
1415 } else {
1416 // substr found, allocate new string
1417 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001418 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001419 }
1420 } else {
1421 // second pass, we are done
1422 break;
1423 }
xbe480c15a2014-01-30 22:17:30 -08001424 }
Damien George94f68302014-01-31 23:45:12 +00001425
xbe480c15a2014-01-30 22:17:30 -08001426 return mp_obj_str_builder_end(replaced_str);
1427}
1428
xbe9e1e8cd2014-03-12 22:57:16 -07001429STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001430 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001431 assert(2 <= n_args && n_args <= 4);
1432 assert(MP_OBJ_IS_STR(args[0]));
1433 assert(MP_OBJ_IS_STR(args[1]));
1434
1435 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1436 GET_STR_DATA_LEN(args[1], needle, needle_len);
1437
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001438 const byte *start = haystack;
1439 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001440 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001441 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001442 }
1443 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001444 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001445 }
1446
Damien George536dde22014-03-13 22:07:55 +00001447 // if needle_len is zero then we count each gap between characters as an occurrence
1448 if (needle_len == 0) {
Paul Sokolovsky26fda6d2014-06-14 18:19:16 +03001449 return MP_OBJ_NEW_SMALL_INT((machine_uint_t)unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001450 }
1451
Damien George536dde22014-03-13 22:07:55 +00001452 // count the occurrences
1453 machine_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001454 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1455 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001456 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001457 haystack_ptr += needle_len;
1458 } else {
1459 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001460 }
xbe9e1e8cd2014-03-12 22:57:16 -07001461 }
1462
1463 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1464}
1465
Damien Georgeb035db32014-03-21 20:39:40 +00001466STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, machine_int_t direction) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001467 if (!is_str_or_bytes(self_in)) {
1468 assert(0);
1469 }
1470 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1471 if (self_type != mp_obj_get_type(arg)) {
1472 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001473 }
Damien Georgeb035db32014-03-21 20:39:40 +00001474
xbe613a8e32014-03-18 00:06:29 -07001475 GET_STR_DATA_LEN(self_in, str, str_len);
1476 GET_STR_DATA_LEN(arg, sep, sep_len);
1477
1478 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001479 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001480 }
Damien Georgeb035db32014-03-21 20:39:40 +00001481
1482 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1483
1484 if (direction > 0) {
1485 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001486 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001487 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001488 }
xbe613a8e32014-03-18 00:06:29 -07001489
xbe17a5a832014-03-23 23:31:58 -07001490 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1491 if (position_ptr != NULL) {
1492 machine_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001493 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001494 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001495 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 -07001496 }
Damien Georgeb035db32014-03-21 20:39:40 +00001497
xbe0a6894c2014-03-21 01:12:26 -07001498 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001499}
1500
Damien Georgeb035db32014-03-21 20:39:40 +00001501STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1502 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001503}
xbe4504ea82014-03-19 00:46:14 -07001504
Damien Georgeb035db32014-03-21 20:39:40 +00001505STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1506 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001507}
1508
Paul Sokolovsky69135212014-05-10 19:47:41 +03001509// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001510STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001511 GET_STR_DATA_LEN(self_in, self_data, self_len);
1512 byte *data;
1513 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1514 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001515 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001516 }
1517 *data = 0;
1518 return mp_obj_str_builder_end(s);
1519}
1520
1521STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001522 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001523}
1524
1525STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001526 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001527}
1528
Damien Georgefcc9cf62014-06-01 18:22:09 +01001529STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001530 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001531
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001532 if (self_len == 0) {
1533 return mp_const_false; // default to False for empty str
1534 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001535
Damien Georgefcc9cf62014-06-01 18:22:09 +01001536 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001537 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001538 if (!f(*self_data++)) {
1539 return mp_const_false;
1540 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001541 }
1542 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001543 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001544
Kim Bautersa3f4b832014-05-31 07:30:03 +01001545 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1546 if (unichar_isalpha(*self_data++)) {
1547 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001548 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1549 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001550 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001551 }
1552 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001553
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001554 if (!contains_alpha) {
1555 return mp_const_false;
1556 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001557 }
1558
1559 return mp_const_true;
1560}
1561
1562STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001563 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001564}
1565
1566STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001567 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001568}
1569
1570STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001571 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001572}
1573
1574STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001575 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001576}
1577
1578STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001579 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001580}
1581
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001582#if MICROPY_CPYTHON_COMPAT
1583// These methods are superfluous in the presense of str() and bytes()
1584// constructors.
1585// TODO: should accept kwargs too
1586STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1587 mp_obj_t new_args[2];
1588 if (n_args == 1) {
1589 new_args[0] = args[0];
1590 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1591 args = new_args;
1592 n_args++;
1593 }
1594 return str_make_new(NULL, n_args, 0, args);
1595}
1596
1597// TODO: should accept kwargs too
1598STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1599 mp_obj_t new_args[2];
1600 if (n_args == 1) {
1601 new_args[0] = args[0];
1602 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1603 args = new_args;
1604 n_args++;
1605 }
1606 return bytes_make_new(NULL, n_args, 0, args);
1607}
1608#endif
1609
Paul Sokolovskycdc020d2014-06-14 01:19:52 +03001610machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
Damien George57a4b4f2014-04-18 22:29:21 +01001611 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001612 GET_STR_DATA_LEN(self_in, str_data, str_len);
1613 bufinfo->buf = (void*)str_data;
1614 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001615 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001616 return 0;
1617 } else {
1618 // can't write to a string
1619 bufinfo->buf = NULL;
1620 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001621 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001622 return 1;
1623 }
1624}
1625
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001626#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001627MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1628MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001629#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001630MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1631MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1632MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1633MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1634MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1635MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1636MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1637MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1638MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1639MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1640MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1641MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1642MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1643MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1644MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1645MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1646MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1647MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1648MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1649MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1650MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1651MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1652MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1653MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001654
Damien George9b196cd2014-03-26 21:47:19 +00001655STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001656#if MICROPY_CPYTHON_COMPAT
1657 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001658 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1659 // If we have separate unicode type, then here we have methods only
1660 // for bytes type, and it should not have encode() methods. Otherwise,
1661 // we have non-compliant-but-practical bytestring type, which shares
1662 // method table with bytes, so they both have encode() and decode()
1663 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001664 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001665 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001666#endif
Damien George9b196cd2014-03-26 21:47:19 +00001667 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1668 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001669 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1670 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001671 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1672 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001673 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001674 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001675 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001676 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001677 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1678 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001679 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1680 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1681 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1682 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1683 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001684 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1685 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001686 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1687 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1688 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1689 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1690 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001691};
Damien George97209d32014-01-07 15:58:30 +00001692
Damien George9b196cd2014-03-26 21:47:19 +00001693STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1694
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001695#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001696const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001697 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001698 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001699 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001700 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001701 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001702 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001703 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001704 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001705 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001706};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001707#endif
Damiend99b0522013-12-21 18:17:45 +00001708
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001709// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001710const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001711 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001712 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001713 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001714 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001715 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001716 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001717 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001718 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001719 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001720};
1721
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001722// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001723STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001724const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1725
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001726mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001727 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001728 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001729 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001730 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001731 byte *p = m_new(byte, len + 1);
1732 o->data = p;
1733 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001734 return o;
1735}
1736
Damien George5fa93b62014-01-22 14:35:10 +00001737mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001738 mp_obj_str_t *o = o_in;
1739 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001740 byte *p = (byte*)o->data;
1741 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001742 return o;
1743}
1744
Damien Georgef600a6a2014-05-25 22:34:34 +01001745mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001746 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001747 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001748 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001749 if (data) {
1750 o->hash = qstr_compute_hash(data, len);
1751 byte *p = m_new(byte, len + 1);
1752 o->data = p;
1753 memcpy(p, data, len * sizeof(byte));
1754 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1755 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001756 return o;
1757}
1758
Damien George2617eeb2014-05-25 22:27:57 +01001759mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001760 if (make_qstr_if_not_already) {
1761 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001762 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001763 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001764 qstr q = qstr_find_strn(data, len);
1765 if (q != MP_QSTR_NULL) {
1766 // qstr with this data already exists
1767 return MP_OBJ_NEW_QSTR(q);
1768 } else {
1769 // no existing qstr, don't make one
1770 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1771 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001772 }
Damien George5fa93b62014-01-22 14:35:10 +00001773}
1774
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001775mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1776 GET_STR_DATA_LEN(str, data, len);
1777 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1778}
1779
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001780mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001781 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001782}
1783
Damien George5fa93b62014-01-22 14:35:10 +00001784bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1785 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1786 return s1 == s2;
1787 } else {
1788 GET_STR_HASH(s1, h1);
1789 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001790 // If any of hashes is 0, it means it's not valid
1791 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001792 return false;
1793 }
1794 GET_STR_DATA_LEN(s1, d1, l1);
1795 GET_STR_DATA_LEN(s2, d2, l2);
1796 if (l1 != l2) {
1797 return false;
1798 }
Damien George1e708fe2014-01-23 18:27:51 +00001799 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001800 }
Damien George5fa93b62014-01-22 14:35:10 +00001801}
1802
Damien Georgedeed0872014-04-06 11:11:15 +01001803STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001804 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "Can't convert '%s' object to str implicitly", mp_obj_get_type_str(self_in)));
Damien Georgeb829b5c2014-01-25 13:51:19 +00001805}
1806
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001807STATIC void arg_type_mixup() {
1808 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1809}
1810
Damien George5fa93b62014-01-22 14:35:10 +00001811uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001812 // TODO: This has too big overhead for hash accessor
1813 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001814 GET_STR_HASH(self_in, h);
1815 return h;
1816 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001817 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001818 }
1819}
1820
1821uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001822 // TODO This has a double check for the type, one in obj.c and one here
1823 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001824 GET_STR_LEN(self_in, l);
1825 return l;
1826 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001827 bad_implicit_conversion(self_in);
1828 }
1829}
1830
1831// use this if you will anyway convert the string to a qstr
1832// will be more efficient for the case where it's already a qstr
1833qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1834 if (MP_OBJ_IS_QSTR(self_in)) {
1835 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001836 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001837 mp_obj_str_t *self = self_in;
1838 return qstr_from_strn((char*)self->data, self->len);
1839 } else {
1840 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001841 }
1842}
1843
1844// only use this function if you need the str data to be zero terminated
1845// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1846const char *mp_obj_str_get_str(mp_obj_t self_in) {
1847 if (MP_OBJ_IS_STR(self_in)) {
1848 GET_STR_DATA_LEN(self_in, s, l);
1849 (void)l; // len unused
1850 return (const char*)s;
1851 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001852 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001853 }
1854}
1855
Damien George698ec212014-02-08 18:17:23 +00001856const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001857 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001858 GET_STR_DATA_LEN(self_in, s, l);
1859 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001860 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001861 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001862 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001863 }
Damiend99b0522013-12-21 18:17:45 +00001864}
xyb8cfc9f02014-01-05 18:47:51 +08001865
1866/******************************************************************************/
1867/* str iterator */
1868
1869typedef struct _mp_obj_str_it_t {
1870 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001871 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001872 machine_uint_t cur;
1873} mp_obj_str_it_t;
1874
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001875#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001876STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001877 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001878 GET_STR_DATA_LEN(self->str, str, len);
1879 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001880 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001881 self->cur += 1;
1882 return o_out;
1883 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001884 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001885 }
1886}
1887
Damien George3e1a5c12014-03-29 13:43:38 +00001888STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001889 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001890 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001891 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001892 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001893};
1894
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001895mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
1896 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
1897 o->base.type = &mp_type_str_it;
1898 o->str = str;
1899 o->cur = 0;
1900 return o;
1901}
1902#endif
1903
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001904STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001905 mp_obj_str_it_t *self = self_in;
1906 GET_STR_DATA_LEN(self->str, str, len);
1907 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001908 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001909 self->cur += 1;
1910 return o_out;
1911 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001912 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001913 }
1914}
1915
Damien George3e1a5c12014-03-29 13:43:38 +00001916STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001917 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001918 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001919 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001920 .iternext = bytes_it_iternext,
1921};
1922
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001923mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1924 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001925 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001926 o->str = str;
1927 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001928 return o;
1929}