blob: fb170f83c9d896ea70b38aca532b02e504262073 [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
Damien George40f3c022014-07-03 13:25:24 +0100229STATIC 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 +0000230 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100231 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700232 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
Damien Georgee04a44e2014-06-28 10:27:23 +0100254mp_obj_t mp_obj_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 Sokolovskyea2c9362014-06-15 00:35:09 +0300347#if !MICROPY_PY_BUILTINS_STR_UNICODE
348// objstrunicode defines own version
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300349const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, uint self_len,
350 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100351 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300352 return self_data + index_val;
353}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300354#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300355
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300356// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
357STATIC 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 +0300358 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100359 GET_STR_DATA_LEN(self_in, self_data, self_len);
360 if (value == MP_OBJ_SENTINEL) {
361 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100362#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100363 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300364 mp_bound_slice_t slice;
365 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300366 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100367 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100368 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100369 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100370 }
371#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300372 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George729f7b42014-04-17 22:10:53 +0100373 if (type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300374 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100375 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300376 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100377 }
378 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100379 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100380 }
381}
382
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200383STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300384 assert(is_str_or_bytes(self_in));
385 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000386
Damien Georgefe8fb912014-01-02 16:36:09 +0000387 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000388 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000389
390 // process args
Damiend99b0522013-12-21 18:17:45 +0000391 uint seq_len;
392 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000393 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000394 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000395 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100396 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
397 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300398 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100399 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
400 }
401 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000402 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000403
404 // count required length
405 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000406 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300407 if (mp_obj_get_type(seq_items[i]) != self_type) {
408 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
409 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000410 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000411 if (i > 0) {
412 required_len += sep_len;
413 }
Damien George5fa93b62014-01-22 14:35:10 +0000414 GET_STR_LEN(seq_items[i], l);
415 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000416 }
417
418 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000419 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300420 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000421 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000422 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000423 memcpy(data, sep_str, sep_len);
424 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000425 }
Damien George5fa93b62014-01-22 14:35:10 +0000426 GET_STR_DATA_LEN(seq_items[i], s, l);
427 memcpy(data, s, l);
428 data += l;
Damiend99b0522013-12-21 18:17:45 +0000429 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000430
431 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000432 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000433}
434
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200435#define is_ws(c) ((c) == ' ' || (c) == '\t')
436
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200437STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300438 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100439 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200440 mp_obj_t sep = mp_const_none;
441 if (n_args > 1) {
442 sep = args[1];
443 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100444 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200445 }
446 }
Damien Georgedeed0872014-04-06 11:11:15 +0100447
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200448 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000449 GET_STR_DATA_LEN(args[0], s, len);
450 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200451
Damien Georgedeed0872014-04-06 11:11:15 +0100452 if (sep == mp_const_none) {
453 // sep not given, so separate on whitespace
454
455 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000456 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100457 while (s < top && splits != 0) {
458 const byte *start = s;
459 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100460 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100461 if (s >= top) {
462 break;
463 }
464 while (s < top && is_ws(*s)) s++;
465 if (splits > 0) {
466 splits--;
467 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200468 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200469
Damien Georgedeed0872014-04-06 11:11:15 +0100470 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100471 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100472 }
473
474 } else {
475 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300476 if (mp_obj_get_type(sep) != self_type) {
477 arg_type_mixup();
478 }
Damien Georgedeed0872014-04-06 11:11:15 +0100479
480 uint sep_len;
481 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
482
483 if (sep_len == 0) {
484 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
485 }
486
487 for (;;) {
488 const byte *start = s;
489 for (;;) {
490 if (splits == 0 || s + sep_len > top) {
491 s = top;
492 break;
493 } else if (memcmp(s, sep_str, sep_len) == 0) {
494 break;
495 }
496 s++;
497 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100498 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100499 if (s >= top) {
500 break;
501 }
502 s += sep_len;
503 if (splits > 0) {
504 splits--;
505 }
506 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200507 }
508
509 return res;
510}
511
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300512STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
513 if (n_args < 3) {
514 // If we don't have split limit, it doesn't matter from which side
515 // we split.
516 return str_split(n_args, args);
517 }
518 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
519 mp_obj_t sep = args[1];
520 GET_STR_DATA_LEN(args[0], s, len);
521
Damien George40f3c022014-07-03 13:25:24 +0100522 mp_int_t splits = mp_obj_get_int(args[2]);
523 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300524 // Preallocate list to the max expected # of elements, as we
525 // will fill it from the end.
526 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
527 int idx = splits;
528
529 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000530 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300531 } else {
532 uint sep_len;
533 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
534
535 if (sep_len == 0) {
536 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
537 }
538
539 const byte *beg = s;
540 const byte *last = s + len;
541 for (;;) {
542 s = last - sep_len;
543 for (;;) {
544 if (splits == 0 || s < beg) {
545 break;
546 } else if (memcmp(s, sep_str, sep_len) == 0) {
547 break;
548 }
549 s--;
550 }
551 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100552 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300553 break;
554 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100555 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 +0300556 last = s;
557 if (splits > 0) {
558 splits--;
559 }
560 }
561 if (idx != 0) {
562 // We split less parts than split limit, now go cleanup surplus
563 int used = org_splits + 1 - idx;
564 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
565 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
566 res->len = used;
567 }
568 }
569
570 return res;
571}
572
Damien George40f3c022014-07-03 13:25:24 +0100573STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, mp_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300574 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000575 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000576 assert(MP_OBJ_IS_STR(args[0]));
577 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000578
Damien George5fa93b62014-01-22 14:35:10 +0000579 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
580 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000581
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300582 const byte *start = haystack;
583 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000584 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300585 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000586 }
587 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300588 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000589 }
590
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300591 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000592 if (p == NULL) {
593 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700594 if (is_index) {
595 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
596 } else {
597 return MP_OBJ_NEW_SMALL_INT(-1);
598 }
Damien George23005372014-01-13 19:39:01 +0000599 } else {
600 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300601 #if MICROPY_PY_BUILTINS_STR_UNICODE
602 if (self_type == &mp_type_str) {
603 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
604 }
605 #endif
xbe17a5a832014-03-23 23:31:58 -0700606 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000607 }
John R. Lentone8204912014-01-12 21:53:52 +0000608}
609
xbe17a5a832014-03-23 23:31:58 -0700610STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700611 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700612}
613
614STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700615 return str_finder(n_args, args, -1, false);
616}
617
618STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
619 return str_finder(n_args, args, 1, true);
620}
621
622STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
623 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700624}
625
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200626// TODO: (Much) more variety in args
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300627STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300628 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300629 GET_STR_DATA_LEN(args[0], str, str_len);
630 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300631 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300632 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300633 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300634 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300635 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200636 return mp_const_false;
637 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300638 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200639}
640
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300641STATIC mp_obj_t str_endswith(uint n_args, const mp_obj_t *args) {
642 GET_STR_DATA_LEN(args[0], str, str_len);
643 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
644 assert(n_args == 2);
645
646 if (suffix_len > str_len) {
647 return mp_const_false;
648 }
649 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
650}
651
Paul Sokolovsky88107842014-04-26 06:20:08 +0300652enum { LSTRIP, RSTRIP, STRIP };
653
654STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800655 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300656 assert(is_str_or_bytes(args[0]));
657 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000658
659 const byte *chars_to_del;
660 uint chars_to_del_len;
661 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800662
663 if (n_args == 1) {
664 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000665 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800666 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300667 if (mp_obj_get_type(args[1]) != self_type) {
668 arg_type_mixup();
669 }
Damien George5fa93b62014-01-22 14:35:10 +0000670 GET_STR_DATA_LEN(args[1], s, l);
671 chars_to_del = s;
672 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800673 }
674
Damien George5fa93b62014-01-22 14:35:10 +0000675 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800676
Damien George40f3c022014-07-03 13:25:24 +0100677 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800678 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100679 mp_uint_t last_good_char_pos = 0;
680 mp_uint_t i = 0;
681 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300682 if (type == RSTRIP) {
683 i = orig_str_len - 1;
684 delta = -1;
685 }
Damien George40f3c022014-07-03 13:25:24 +0100686 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700687 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800688 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300689 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800690 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300691 if (type == LSTRIP) {
692 last_good_char_pos = orig_str_len - 1;
693 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300694 } else if (type == RSTRIP) {
695 first_good_char_pos = 0;
696 last_good_char_pos = i;
697 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300698 }
xbe7b0f39f2014-01-08 14:23:45 -0800699 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300700 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800701 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300702 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800703 }
704
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300705 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000706 // string is all whitespace, return ''
707 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800708 }
709
710 assert(last_good_char_pos >= first_good_char_pos);
711 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100712 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300713 if (stripped_len == orig_str_len) {
714 // If nothing was stripped, don't bother to dup original string
715 // TODO: watch out for this case when we'll get to bytearray.strip()
716 assert(first_good_char_pos == 0);
717 return args[0];
718 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100719 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800720}
721
Paul Sokolovsky88107842014-04-26 06:20:08 +0300722STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
723 return str_uni_strip(STRIP, n_args, args);
724}
725
726STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
727 return str_uni_strip(LSTRIP, n_args, args);
728}
729
730STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
731 return str_uni_strip(RSTRIP, n_args, args);
732}
733
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700734// Takes an int arg, but only parses unsigned numbers, and only changes
735// *num if at least one digit was parsed.
736static int str_to_int(const char *str, int *num) {
737 const char *s = str;
738 if (unichar_isdigit(*s)) {
739 *num = 0;
740 do {
741 *num = *num * 10 + (*s - '0');
742 s++;
743 }
744 while (unichar_isdigit(*s));
745 }
746 return s - str;
747}
748
749static bool isalignment(char ch) {
750 return ch && strchr("<>=^", ch) != NULL;
751}
752
753static bool istype(char ch) {
754 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
755}
756
757static bool arg_looks_integer(mp_obj_t arg) {
758 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
759}
760
761static bool arg_looks_numeric(mp_obj_t arg) {
762 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100763#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700764 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
765#endif
766 ;
767}
768
Dave Hylandsc4029e52014-04-07 11:19:51 -0700769static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100770#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700771 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700772
773 // TODO: Needs a way to construct an mpz integer from a float
774
Damien George40f3c022014-07-03 13:25:24 +0100775 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700776 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700777 }
778#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700779 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700780}
781
Damien George897fe0c2014-04-15 22:03:55 +0100782mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000783 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000784
Damien George5fa93b62014-01-22 14:35:10 +0000785 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700786 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000787 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700788 pfenv_t pfenv_vstr;
789 pfenv_vstr.data = vstr;
790 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
791
Damien George5fa93b62014-01-22 14:35:10 +0000792 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700793 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000794 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700795 if (str < top && *str == '}') {
796 vstr_add_char(vstr, '}');
797 continue;
798 }
Damien George11de8392014-06-05 18:57:38 +0100799 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700800 }
801 if (*str != '{') {
802 vstr_add_char(vstr, *str);
803 continue;
804 }
805
806 str++;
807 if (str < top && *str == '{') {
808 vstr_add_char(vstr, '{');
809 continue;
810 }
811
812 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
813
814 vstr_t *field_name = NULL;
815 char conversion = '\0';
816 vstr_t *format_spec = NULL;
817
818 if (str < top && *str != '}' && *str != '!' && *str != ':') {
819 field_name = vstr_new();
820 while (str < top && *str != '}' && *str != '!' && *str != ':') {
821 vstr_add_char(field_name, *str++);
822 }
823 vstr_add_char(field_name, '\0');
824 }
825
826 // conversion ::= "r" | "s"
827
828 if (str < top && *str == '!') {
829 str++;
830 if (str < top && (*str == 'r' || *str == 's')) {
831 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200832 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100833 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 -0700834 }
835 }
836
837 if (str < top && *str == ':') {
838 str++;
839 // {:} is the same as {}, which is the same as {!s}
840 // This makes a difference when passing in a True or False
841 // '{}'.format(True) returns 'True'
842 // '{:d}'.format(True) returns '1'
843 // So we treat {:} as {} and this later gets treated to be {!s}
844 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100845 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700846 while (str < top && *str != '}') {
847 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000848 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700849 vstr_add_char(format_spec, '\0');
850 }
851 }
852 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100853 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700854 }
855 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100856 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857 }
858
859 mp_obj_t arg = mp_const_none;
860
861 if (field_name) {
862 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100863 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 -0700864 }
Damien George3bb8bd82014-04-14 21:20:30 +0100865 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700866 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100867 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700868 }
869 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100870 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700871 }
872 arg = args[index + 1];
873 arg_i = -1;
874 vstr_free(field_name);
875 field_name = NULL;
876 } else {
877 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100878 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 -0700879 }
880 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100881 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700882 }
883 arg = args[arg_i + 1];
884 arg_i++;
885 }
886 if (!format_spec && !conversion) {
887 conversion = 's';
888 }
889 if (conversion) {
890 mp_print_kind_t print_kind;
891 if (conversion == 's') {
892 print_kind = PRINT_STR;
893 } else if (conversion == 'r') {
894 print_kind = PRINT_REPR;
895 } else {
Damien George11de8392014-06-05 18:57:38 +0100896 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700897 }
898 vstr_t *arg_vstr = vstr_new();
899 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100900 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700901 vstr_free(arg_vstr);
902 }
903
904 char sign = '\0';
905 char fill = '\0';
906 char align = '\0';
907 int width = -1;
908 int precision = -1;
909 char type = '\0';
910 int flags = 0;
911
912 if (format_spec) {
913 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
914 //
915 // [[fill]align][sign][#][0][width][,][.precision][type]
916 // fill ::= <any character>
917 // align ::= "<" | ">" | "=" | "^"
918 // sign ::= "+" | "-" | " "
919 // width ::= integer
920 // precision ::= integer
921 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
922
923 const char *s = vstr_str(format_spec);
924 if (isalignment(*s)) {
925 align = *s++;
926 } else if (*s && isalignment(s[1])) {
927 fill = *s++;
928 align = *s++;
929 }
930 if (*s == '+' || *s == '-' || *s == ' ') {
931 if (*s == '+') {
932 flags |= PF_FLAG_SHOW_SIGN;
933 } else if (*s == ' ') {
934 flags |= PF_FLAG_SPACE_SIGN;
935 }
936 sign = *s++;
937 }
938 if (*s == '#') {
939 flags |= PF_FLAG_SHOW_PREFIX;
940 s++;
941 }
942 if (*s == '0') {
943 if (!align) {
944 align = '=';
945 }
946 if (!fill) {
947 fill = '0';
948 }
949 }
950 s += str_to_int(s, &width);
951 if (*s == ',') {
952 flags |= PF_FLAG_SHOW_COMMA;
953 s++;
954 }
955 if (*s == '.') {
956 s++;
957 s += str_to_int(s, &precision);
958 }
959 if (istype(*s)) {
960 type = *s++;
961 }
962 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100963 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700964 }
965 vstr_free(format_spec);
966 format_spec = NULL;
967 }
968 if (!align) {
969 if (arg_looks_numeric(arg)) {
970 align = '>';
971 } else {
972 align = '<';
973 }
974 }
975 if (!fill) {
976 fill = ' ';
977 }
978
979 if (sign) {
980 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100981 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700982 }
983 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100984 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000985 }
986 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700987 sign = '-';
988 }
989
990 switch (align) {
991 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
992 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
993 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
994 }
995
996 if (arg_looks_integer(arg)) {
997 switch (type) {
998 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -0700999 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001000 continue;
1001
1002 case 'c':
1003 {
1004 char ch = mp_obj_get_int(arg);
1005 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1006 continue;
1007 }
1008
1009 case '\0': // No explicit format type implies 'd'
1010 case 'n': // I don't think we support locales in uPy so use 'd'
1011 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001012 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001013 continue;
1014
1015 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001016 if (flags & PF_FLAG_SHOW_PREFIX) {
1017 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1018 }
1019
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001020 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001021 continue;
1022
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001023 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001024 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001025 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001026 continue;
1027
1028 case 'e':
1029 case 'E':
1030 case 'f':
1031 case 'F':
1032 case 'g':
1033 case 'G':
1034 case '%':
1035 // The floating point formatters all work with anything that
1036 // looks like an integer
1037 break;
1038
1039 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001040 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001041 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001042 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001043 }
Damien George70f33cd2014-04-02 17:06:05 +01001044
Dave Hylands22fe4d72014-04-02 12:07:31 -07001045 // NOTE: no else here. We need the e, f, g etc formats for integer
1046 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001047 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001048 if (!type) {
1049
1050 // Even though the docs say that an unspecified type is the same
1051 // as 'g', there is one subtle difference, when the exponent
1052 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001053 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001054 // '{:10.1}'.format(0.0) ==> '0e+00'
1055 // '{:10.1g}'.format(0.0) ==> '0'
1056 //
1057 // TODO: Figure out how to deal with this.
1058 //
1059 // A proper solution would involve adding a special flag
1060 // or something to format_float, and create a format_double
1061 // to deal with doubles. In order to fix this when using
1062 // sprintf, we'd need to use the e format and tweak the
1063 // returned result to strip trailing zeros like the g format
1064 // does.
1065 //
1066 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1067 // but with 1.e2 you get 1e+02 and 1.00e+02
1068 //
1069 // Stripping the trailing 0's (like g) does would make the
1070 // e format give us the right format.
1071 //
1072 // CPython sources say:
1073 // Omitted type specifier. Behaves in the same way as repr(x)
1074 // and str(x) if no precision is given, else like 'g', but with
1075 // at least one digit after the decimal point. */
1076
1077 type = 'g';
1078 }
1079 if (type == 'n') {
1080 type = 'g';
1081 }
1082
1083 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1084 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001085#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001086 case 'e':
1087 case 'E':
1088 case 'f':
1089 case 'F':
1090 case 'g':
1091 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001092 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001093 break;
1094
1095 case '%':
1096 flags |= PF_FLAG_ADD_PERCENT;
1097 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1098 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001099#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001100
1101 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001102 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001103 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001104 type, mp_obj_get_type_str(arg)));
1105 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001106 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001107 // arg doesn't look like a number
1108
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001109 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001110 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001111 }
Damien George70f33cd2014-04-02 17:06:05 +01001112
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001113 switch (type) {
1114 case '\0':
1115 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1116 break;
1117
1118 case 's':
1119 {
1120 uint len;
1121 const char *s = mp_obj_str_get_data(arg, &len);
1122 if (precision < 0) {
1123 precision = len;
1124 }
1125 if (len > precision) {
1126 len = precision;
1127 }
1128 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1129 break;
1130 }
1131
1132 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001133 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001134 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001135 type, mp_obj_get_type_str(arg)));
1136 }
Damiend99b0522013-12-21 18:17:45 +00001137 }
1138 }
1139
Damien George2617eeb2014-05-25 22:27:57 +01001140 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001141 vstr_free(vstr);
1142 return s;
Damiend99b0522013-12-21 18:17:45 +00001143}
1144
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001145STATIC 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 +03001146 assert(MP_OBJ_IS_STR(pattern));
1147
1148 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001149 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001150 int arg_i = 0;
1151 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001152 pfenv_t pfenv_vstr;
1153 pfenv_vstr.data = vstr;
1154 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1155
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001156 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001157 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001158 if (*str != '%') {
1159 vstr_add_char(vstr, *str);
1160 continue;
1161 }
1162 if (++str >= top) {
1163 break;
1164 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001165 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001166 vstr_add_char(vstr, '%');
1167 continue;
1168 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001169
1170 // Dictionary value lookup
1171 if (*str == '(') {
1172 const byte *key = ++str;
1173 while (*str != ')') {
1174 if (str >= top) {
1175 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1176 }
1177 ++str;
1178 }
1179 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1180 arg = mp_obj_dict_get(dict, k_obj);
1181 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001182 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001183
Dave Hylands6756a372014-04-02 11:42:39 -07001184 int flags = 0;
1185 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001186 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001187 while (str < top) {
1188 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1189 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1190 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001191 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001192 else if (*str == '0') {
1193 flags |= PF_FLAG_PAD_AFTER_SIGN;
1194 fill = '0';
1195 } else break;
1196 str++;
1197 }
1198 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001199 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001200 if (str < top) {
1201 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001202 if (arg_i >= n_args) {
1203 goto not_enough_args;
1204 }
Dave Hylands6756a372014-04-02 11:42:39 -07001205 width = mp_obj_get_int(args[arg_i++]);
1206 str++;
1207 } else {
1208 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1209 width = width * 10 + *str - '0';
1210 }
1211 }
1212 }
1213 int prec = -1;
1214 if (str < top && *str == '.') {
1215 if (++str < top) {
1216 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001217 if (arg_i >= n_args) {
1218 goto not_enough_args;
1219 }
Dave Hylands6756a372014-04-02 11:42:39 -07001220 prec = mp_obj_get_int(args[arg_i++]);
1221 str++;
1222 } else {
1223 prec = 0;
1224 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1225 prec = prec * 10 + *str - '0';
1226 }
1227 }
1228 }
1229 }
1230
1231 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001232 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001233 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001234
1235 // Tuple value lookup
1236 if (arg == MP_OBJ_NULL) {
1237 if (arg_i >= n_args) {
1238not_enough_args:
1239 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1240 }
1241 arg = args[arg_i++];
1242 }
Dave Hylands6756a372014-04-02 11:42:39 -07001243 switch (*str) {
1244 case 'c':
1245 if (MP_OBJ_IS_STR(arg)) {
1246 uint len;
1247 const char *s = mp_obj_str_get_data(arg, &len);
1248 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001249 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001250 break;
1251 }
1252 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1253 break;
1254 }
1255 if (arg_looks_integer(arg)) {
1256 char ch = mp_obj_get_int(arg);
1257 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1258 break;
1259 }
Damien Georgefb510b32014-06-01 13:32:54 +01001260#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001261 // This is what CPython reports, so we report the same.
1262 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001263 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001264
1265 }
1266#endif
Damien George11de8392014-06-05 18:57:38 +01001267 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1268 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001269
1270 case 'd':
1271 case 'i':
1272 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001273 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001274 break;
1275
Damien Georgefb510b32014-06-01 13:32:54 +01001276#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001277 case 'e':
1278 case 'E':
1279 case 'f':
1280 case 'F':
1281 case 'g':
1282 case 'G':
1283 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1284 break;
1285#endif
1286
1287 case 'o':
1288 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001289 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001290 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001291 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001292 break;
1293
1294 case 'r':
1295 case 's':
1296 {
1297 vstr_t *arg_vstr = vstr_new();
1298 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1299 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1300 uint len = vstr_len(arg_vstr);
1301 if (prec < 0) {
1302 prec = len;
1303 }
1304 if (len > prec) {
1305 len = prec;
1306 }
1307 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1308 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001309 break;
1310 }
Dave Hylands6756a372014-04-02 11:42:39 -07001311
Dave Hylands6756a372014-04-02 11:42:39 -07001312 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001313 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001314 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001315 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001316
Dave Hylands6756a372014-04-02 11:42:39 -07001317 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001318 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001319 "unsupported format character '%c' (0x%x) at index %d",
1320 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001321 }
1322 }
1323
1324 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001325 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001326 }
1327
Damien George2617eeb2014-05-25 22:27:57 +01001328 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001329 vstr_free(vstr);
1330 return s;
1331}
1332
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001333STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001334 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001335
Damien George40f3c022014-07-03 13:25:24 +01001336 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001337 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001338 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001339 if (max_rep == 0) {
1340 return args[0];
1341 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001342 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001343 }
xbe480c15a2014-01-30 22:17:30 -08001344 }
Damien George94f68302014-01-31 23:45:12 +00001345
xbe729be9b2014-04-07 14:46:39 -07001346 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001347
Damien Georgeff715422014-04-07 00:39:13 +01001348 // check argument types
1349
1350 if (!MP_OBJ_IS_STR(args[1])) {
1351 bad_implicit_conversion(args[1]);
1352 }
1353
1354 if (!MP_OBJ_IS_STR(args[2])) {
1355 bad_implicit_conversion(args[2]);
1356 }
1357
1358 // extract string data
1359
xbe480c15a2014-01-30 22:17:30 -08001360 GET_STR_DATA_LEN(args[0], str, str_len);
1361 GET_STR_DATA_LEN(args[1], old, old_len);
1362 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001363
1364 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001365 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001366 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001367 }
1368
Damien George94f68302014-01-31 23:45:12 +00001369 // data for the replaced string
1370 byte *data = NULL;
1371 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001372
Damien George94f68302014-01-31 23:45:12 +00001373 // do 2 passes over the string:
1374 // first pass computes the required length of the replaced string
1375 // second pass does the replacements
1376 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001377 mp_uint_t replaced_str_index = 0;
1378 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001379 const byte *old_occurrence;
1380 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001381 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001382 if (old_len == 0) {
1383 // if old_str is empty, copy new_str to start of replaced string
1384 // copy the replacement string
1385 if (data != NULL) {
1386 memcpy(data, new, new_len);
1387 }
1388 replaced_str_index += new_len;
1389 num_replacements_done++;
1390 }
1391 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1392 if (old_len == 0) {
1393 old_occurrence += 1;
1394 }
Damien George94f68302014-01-31 23:45:12 +00001395 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1396 if (data != NULL) {
1397 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1398 }
1399 replaced_str_index += old_occurrence - offset_ptr;
1400 // copy the replacement string
1401 if (data != NULL) {
1402 memcpy(data + replaced_str_index, new, new_len);
1403 }
1404 replaced_str_index += new_len;
1405 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001406 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001407 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001408 }
1409
1410 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1411 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001412 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001413 }
Damien Georgeff715422014-04-07 00:39:13 +01001414 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001415
1416 if (data == NULL) {
1417 // first pass
1418 if (num_replacements_done == 0) {
1419 // no substr found, return original string
1420 return args[0];
1421 } else {
1422 // substr found, allocate new string
1423 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001424 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001425 }
1426 } else {
1427 // second pass, we are done
1428 break;
1429 }
xbe480c15a2014-01-30 22:17:30 -08001430 }
Damien George94f68302014-01-31 23:45:12 +00001431
xbe480c15a2014-01-30 22:17:30 -08001432 return mp_obj_str_builder_end(replaced_str);
1433}
1434
xbe9e1e8cd2014-03-12 22:57:16 -07001435STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001436 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001437 assert(2 <= n_args && n_args <= 4);
1438 assert(MP_OBJ_IS_STR(args[0]));
1439 assert(MP_OBJ_IS_STR(args[1]));
1440
1441 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1442 GET_STR_DATA_LEN(args[1], needle, needle_len);
1443
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001444 const byte *start = haystack;
1445 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001446 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001447 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001448 }
1449 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001450 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001451 }
1452
Damien George536dde22014-03-13 22:07:55 +00001453 // if needle_len is zero then we count each gap between characters as an occurrence
1454 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001455 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001456 }
1457
Damien George536dde22014-03-13 22:07:55 +00001458 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001459 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001460 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1461 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001462 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001463 haystack_ptr += needle_len;
1464 } else {
1465 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001466 }
xbe9e1e8cd2014-03-12 22:57:16 -07001467 }
1468
1469 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1470}
1471
Damien George40f3c022014-07-03 13:25:24 +01001472STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001473 if (!is_str_or_bytes(self_in)) {
1474 assert(0);
1475 }
1476 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1477 if (self_type != mp_obj_get_type(arg)) {
1478 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001479 }
Damien Georgeb035db32014-03-21 20:39:40 +00001480
xbe613a8e32014-03-18 00:06:29 -07001481 GET_STR_DATA_LEN(self_in, str, str_len);
1482 GET_STR_DATA_LEN(arg, sep, sep_len);
1483
1484 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001485 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001486 }
Damien Georgeb035db32014-03-21 20:39:40 +00001487
1488 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1489
1490 if (direction > 0) {
1491 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001492 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001493 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001494 }
xbe613a8e32014-03-18 00:06:29 -07001495
xbe17a5a832014-03-23 23:31:58 -07001496 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1497 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001498 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001499 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001500 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001501 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 -07001502 }
Damien Georgeb035db32014-03-21 20:39:40 +00001503
xbe0a6894c2014-03-21 01:12:26 -07001504 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001505}
1506
Damien Georgeb035db32014-03-21 20:39:40 +00001507STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1508 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001509}
xbe4504ea82014-03-19 00:46:14 -07001510
Damien Georgeb035db32014-03-21 20:39:40 +00001511STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1512 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001513}
1514
Paul Sokolovsky69135212014-05-10 19:47:41 +03001515// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001516STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001517 GET_STR_DATA_LEN(self_in, self_data, self_len);
1518 byte *data;
1519 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1520 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001521 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001522 }
1523 *data = 0;
1524 return mp_obj_str_builder_end(s);
1525}
1526
1527STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001528 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001529}
1530
1531STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001532 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001533}
1534
Damien Georgefcc9cf62014-06-01 18:22:09 +01001535STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001536 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001537
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001538 if (self_len == 0) {
1539 return mp_const_false; // default to False for empty str
1540 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001541
Damien Georgefcc9cf62014-06-01 18:22:09 +01001542 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001543 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001544 if (!f(*self_data++)) {
1545 return mp_const_false;
1546 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001547 }
1548 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001549 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001550
Kim Bautersa3f4b832014-05-31 07:30:03 +01001551 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1552 if (unichar_isalpha(*self_data++)) {
1553 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001554 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1555 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001556 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001557 }
1558 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001559
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001560 if (!contains_alpha) {
1561 return mp_const_false;
1562 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001563 }
1564
1565 return mp_const_true;
1566}
1567
1568STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001569 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001570}
1571
1572STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001573 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001574}
1575
1576STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001577 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001578}
1579
1580STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001581 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001582}
1583
1584STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001585 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001586}
1587
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001588#if MICROPY_CPYTHON_COMPAT
1589// These methods are superfluous in the presense of str() and bytes()
1590// constructors.
1591// TODO: should accept kwargs too
1592STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1593 mp_obj_t new_args[2];
1594 if (n_args == 1) {
1595 new_args[0] = args[0];
1596 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1597 args = new_args;
1598 n_args++;
1599 }
1600 return str_make_new(NULL, n_args, 0, args);
1601}
1602
1603// TODO: should accept kwargs too
1604STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1605 mp_obj_t new_args[2];
1606 if (n_args == 1) {
1607 new_args[0] = args[0];
1608 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1609 args = new_args;
1610 n_args++;
1611 }
1612 return bytes_make_new(NULL, n_args, 0, args);
1613}
1614#endif
1615
Damien George40f3c022014-07-03 13:25:24 +01001616mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
Damien George57a4b4f2014-04-18 22:29:21 +01001617 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001618 GET_STR_DATA_LEN(self_in, str_data, str_len);
1619 bufinfo->buf = (void*)str_data;
1620 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001621 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001622 return 0;
1623 } else {
1624 // can't write to a string
1625 bufinfo->buf = NULL;
1626 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001627 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001628 return 1;
1629 }
1630}
1631
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001632#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001633MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1634MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001635#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001636MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1637MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1638MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1639MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1640MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1641MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1642MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1643MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1644MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1645MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1646MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1647MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1648MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1649MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1650MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1651MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1652MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1653MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1654MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1655MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1656MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1657MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1658MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1659MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001660
Damien George9b196cd2014-03-26 21:47:19 +00001661STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001662#if MICROPY_CPYTHON_COMPAT
1663 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001664 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1665 // If we have separate unicode type, then here we have methods only
1666 // for bytes type, and it should not have encode() methods. Otherwise,
1667 // we have non-compliant-but-practical bytestring type, which shares
1668 // method table with bytes, so they both have encode() and decode()
1669 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001670 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001671 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001672#endif
Damien George9b196cd2014-03-26 21:47:19 +00001673 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1674 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001675 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1676 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001677 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1678 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001679 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001680 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001681 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001682 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001683 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1684 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001685 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1686 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1687 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1688 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1689 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001690 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1691 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001692 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1693 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1694 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1695 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1696 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001697};
Damien George97209d32014-01-07 15:58:30 +00001698
Damien George9b196cd2014-03-26 21:47:19 +00001699STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1700
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001701#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001702const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001703 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001704 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001705 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001706 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001707 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001708 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001709 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001710 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001711 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001712};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001713#endif
Damiend99b0522013-12-21 18:17:45 +00001714
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001715// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001716const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001717 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001718 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001719 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001720 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001721 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001722 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001723 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001724 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001725 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001726};
1727
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001728// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001729STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001730const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1731
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001732mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001733 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001734 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001735 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001736 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001737 byte *p = m_new(byte, len + 1);
1738 o->data = p;
1739 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001740 return o;
1741}
1742
Damien George5fa93b62014-01-22 14:35:10 +00001743mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001744 mp_obj_str_t *o = o_in;
1745 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001746 byte *p = (byte*)o->data;
1747 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001748 return o;
1749}
1750
Damien George5f27a7e2014-07-31 10:29:56 +01001751mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1752 mp_obj_str_t *o = o_in;
1753 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1754 o->len = len;
1755 o->hash = qstr_compute_hash(o->data, o->len);
1756 byte *p = (byte*)o->data;
1757 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1758 return o;
1759}
1760
Damien Georgef600a6a2014-05-25 22:34:34 +01001761mp_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 +02001762 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001763 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001764 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001765 if (data) {
1766 o->hash = qstr_compute_hash(data, len);
1767 byte *p = m_new(byte, len + 1);
1768 o->data = p;
1769 memcpy(p, data, len * sizeof(byte));
1770 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1771 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001772 return o;
1773}
1774
Damien George2617eeb2014-05-25 22:27:57 +01001775mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001776 if (make_qstr_if_not_already) {
1777 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001778 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001779 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001780 qstr q = qstr_find_strn(data, len);
1781 if (q != MP_QSTR_NULL) {
1782 // qstr with this data already exists
1783 return MP_OBJ_NEW_QSTR(q);
1784 } else {
1785 // no existing qstr, don't make one
1786 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1787 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001788 }
Damien George5fa93b62014-01-22 14:35:10 +00001789}
1790
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001791mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1792 GET_STR_DATA_LEN(str, data, len);
1793 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1794}
1795
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001796mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001797 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001798}
1799
Damien George5fa93b62014-01-22 14:35:10 +00001800bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1801 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1802 return s1 == s2;
1803 } else {
1804 GET_STR_HASH(s1, h1);
1805 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001806 // If any of hashes is 0, it means it's not valid
1807 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001808 return false;
1809 }
1810 GET_STR_DATA_LEN(s1, d1, l1);
1811 GET_STR_DATA_LEN(s2, d2, l2);
1812 if (l1 != l2) {
1813 return false;
1814 }
Damien George1e708fe2014-01-23 18:27:51 +00001815 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001816 }
Damien George5fa93b62014-01-22 14:35:10 +00001817}
1818
Damien Georgedeed0872014-04-06 11:11:15 +01001819STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001820 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 +00001821}
1822
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001823STATIC void arg_type_mixup() {
1824 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1825}
1826
Damien George5fa93b62014-01-22 14:35:10 +00001827uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001828 // TODO: This has too big overhead for hash accessor
1829 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001830 GET_STR_HASH(self_in, h);
1831 return h;
1832 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001833 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001834 }
1835}
1836
1837uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001838 // TODO This has a double check for the type, one in obj.c and one here
1839 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001840 GET_STR_LEN(self_in, l);
1841 return l;
1842 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001843 bad_implicit_conversion(self_in);
1844 }
1845}
1846
1847// use this if you will anyway convert the string to a qstr
1848// will be more efficient for the case where it's already a qstr
1849qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1850 if (MP_OBJ_IS_QSTR(self_in)) {
1851 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001852 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001853 mp_obj_str_t *self = self_in;
1854 return qstr_from_strn((char*)self->data, self->len);
1855 } else {
1856 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001857 }
1858}
1859
1860// only use this function if you need the str data to be zero terminated
1861// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1862const char *mp_obj_str_get_str(mp_obj_t self_in) {
1863 if (MP_OBJ_IS_STR(self_in)) {
1864 GET_STR_DATA_LEN(self_in, s, l);
1865 (void)l; // len unused
1866 return (const char*)s;
1867 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001868 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001869 }
1870}
1871
Damien George698ec212014-02-08 18:17:23 +00001872const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001873 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001874 GET_STR_DATA_LEN(self_in, s, l);
1875 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001876 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001877 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001878 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001879 }
Damiend99b0522013-12-21 18:17:45 +00001880}
xyb8cfc9f02014-01-05 18:47:51 +08001881
1882/******************************************************************************/
1883/* str iterator */
1884
1885typedef struct _mp_obj_str_it_t {
1886 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001887 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01001888 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08001889} mp_obj_str_it_t;
1890
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001891#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001892STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001893 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001894 GET_STR_DATA_LEN(self->str, str, len);
1895 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001896 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001897 self->cur += 1;
1898 return o_out;
1899 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001900 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001901 }
1902}
1903
Damien George3e1a5c12014-03-29 13:43:38 +00001904STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001905 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001906 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001907 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001908 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001909};
1910
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001911mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
1912 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
1913 o->base.type = &mp_type_str_it;
1914 o->str = str;
1915 o->cur = 0;
1916 return o;
1917}
1918#endif
1919
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001920STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001921 mp_obj_str_it_t *self = self_in;
1922 GET_STR_DATA_LEN(self->str, str, len);
1923 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01001924 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001925 self->cur += 1;
1926 return o_out;
1927 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001928 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001929 }
1930}
1931
Damien George3e1a5c12014-03-29 13:43:38 +00001932STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001933 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001934 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001935 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001936 .iternext = bytes_it_iternext,
1937};
1938
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001939mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1940 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001941 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001942 o->str = str;
1943 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001944 return o;
1945}