blob: d1670b5796942d5a89d1c1900429be105e2de074 [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
Damien Georgeecc88e92014-08-30 00:35:11 +010044STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +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
xyb8cfc9f02014-01-05 18:47:51 +080052/******************************************************************************/
53/* str */
54
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030055void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
56 const byte *str_data, uint str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020057 // this escapes characters, but it will be very slow to print (calling print many times)
58 bool has_single_quote = false;
59 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100060 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020061 if (*s == '\'') {
62 has_single_quote = true;
63 } else if (*s == '"') {
64 has_double_quote = true;
65 }
66 }
67 int quote_char = '\'';
68 if (has_single_quote && !has_double_quote) {
69 quote_char = '"';
70 }
71 print(env, "%c", quote_char);
72 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
73 if (*s == quote_char) {
74 print(env, "\\%c", quote_char);
75 } else if (*s == '\\') {
76 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030077 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
78 // In strings, anything which is not ascii control character
79 // is printed as is, this includes characters in range 0x80-0xff
80 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020081 print(env, "%c", *s);
82 } else if (*s == '\n') {
83 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010084 } else if (*s == '\r') {
85 print(env, "\\r");
86 } else if (*s == '\t') {
87 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020088 } else {
89 print(env, "\\x%02x", *s);
90 }
91 }
92 print(env, "%c", quote_char);
93}
94
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020095STATIC 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 +000096 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +000097 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +020098 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +000099 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200100 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200101 if (is_bytes) {
102 print(env, "b");
103 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300104 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200105 }
Damiend99b0522013-12-21 18:17:45 +0000106}
107
Damien Georgeecc88e92014-08-30 00:35:11 +0100108STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300109#if MICROPY_CPYTHON_COMPAT
110 if (n_kw != 0) {
111 mp_arg_error_unimpl_kw();
112 }
113#endif
114
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200115 switch (n_args) {
116 case 0:
117 return MP_OBJ_NEW_QSTR(MP_QSTR_);
118
119 case 1:
120 {
121 vstr_t *vstr = vstr_new();
122 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100123 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200124 vstr_free(vstr);
125 return s;
126 }
127
128 case 2:
129 case 3:
130 {
131 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000132 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100133 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200134 }
135 GET_STR_DATA_LEN(args[0], str_data, str_len);
136 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100137 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200138 o->data = str_data;
139 o->hash = str_hash;
140 return o;
141 }
142
143 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100144 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200145 }
146}
147
Damien Georgeecc88e92014-08-30 00:35:11 +0100148STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200149 if (n_args == 0) {
150 return mp_const_empty_bytes;
151 }
152
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300153#if MICROPY_CPYTHON_COMPAT
154 if (n_kw != 0) {
155 mp_arg_error_unimpl_kw();
156 }
157#endif
158
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200159 if (MP_OBJ_IS_STR(args[0])) {
160 if (n_args < 2 || n_args > 3) {
161 goto wrong_args;
162 }
163 GET_STR_DATA_LEN(args[0], str_data, str_len);
164 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100165 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200166 o->data = str_data;
167 o->hash = str_hash;
168 return o;
169 }
170
171 if (n_args > 1) {
172 goto wrong_args;
173 }
174
175 if (MP_OBJ_IS_SMALL_INT(args[0])) {
176 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
177 byte *data;
178
Damien George3e1a5c12014-03-29 13:43:38 +0000179 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200180 memset(data, 0, len);
181 return mp_obj_str_builder_end(o);
182 }
183
184 int len;
185 byte *data;
186 vstr_t *vstr = NULL;
187 mp_obj_t o = NULL;
188 // Try to create array of exact len if initializer len is known
189 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
190 if (len_in == MP_OBJ_NULL) {
191 len = -1;
192 vstr = vstr_new();
193 } else {
194 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000195 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200196 }
197
Damien Georged17926d2014-03-30 13:35:08 +0100198 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200199 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100200 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200201 if (len == -1) {
202 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
203 } else {
204 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
205 }
206 }
207
208 if (len == -1) {
209 vstr_shrink(vstr);
210 // TODO: Optimize, borrow buffer from vstr
211 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000212 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200213 memcpy(data, vstr_str(vstr), len);
214 vstr_free(vstr);
215 }
216
217 return mp_obj_str_builder_end(o);
218
219wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100220 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200221}
222
Damien George55baff42014-01-21 21:40:13 +0000223// like strstr but with specified length and allows \0 bytes
224// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100225STATIC 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 +0000226 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100227 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700228 if (direction > 0) {
229 str_index = 0;
230 str_index_end = hlen - nlen;
231 } else {
232 str_index = hlen - nlen;
233 str_index_end = 0;
234 }
235 for (;;) {
236 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
237 //found
238 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000239 }
xbe17a5a832014-03-23 23:31:58 -0700240 if (str_index == str_index_end) {
241 //not found
242 break;
Damien George55baff42014-01-21 21:40:13 +0000243 }
xbe17a5a832014-03-23 23:31:58 -0700244 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000245 }
246 }
247 return NULL;
248}
249
Damien Georgea75b02e2014-08-27 09:20:30 +0100250// Note: this function is used to check if an object is a str or bytes, which
251// works because both those types use it as their binary_op method. Revisit
252// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100253mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000254 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300255 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
256 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000257 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100258 case MP_BINARY_OP_ADD:
259 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300260 if (lhs_type == rhs_type) {
261 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000262
263 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000264 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000265
266 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000267 byte *q_ptr;
268 byte *val = qstr_build_start(alloc_len, &q_ptr);
269 memcpy(val, lhs_data, lhs_len);
270 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000271 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
272 */
273
274 // code for non-qstr
275 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300276 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000277 memcpy(data, lhs_data, lhs_len);
278 memcpy(data + lhs_len, rhs_data, rhs_len);
279 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000280 }
281 break;
Damien George5fa93b62014-01-22 14:35:10 +0000282
Damien Georged17926d2014-03-30 13:35:08 +0100283 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000284 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300285 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000286 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700287 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000288 }
289 break;
Damien George5fa93b62014-01-22 14:35:10 +0000290
Damien Georged0a5bf32014-05-10 13:55:11 +0100291 case MP_BINARY_OP_MULTIPLY: {
Damien George9b7a8ee2014-08-13 13:22:24 +0100292 mp_int_t n;
293 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100294 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200295 }
Damien George9b7a8ee2014-08-13 13:22:24 +0100296 if (n <= 0) {
297 if (lhs_type == &mp_type_str) {
298 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
299 }
300 n = 0;
301 }
Damien George5fa93b62014-01-22 14:35:10 +0000302 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300303 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000304 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
305 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200306 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200307
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300308 case MP_BINARY_OP_MODULO: {
309 mp_obj_t *args;
Damien George9c4cbe22014-08-30 14:04:14 +0100310 mp_uint_t n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300311 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300312 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
313 // TODO: Support tuple subclasses?
314 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300315 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
316 args = NULL;
317 n_args = 0;
318 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300319 } else {
320 args = &rhs_in;
321 n_args = 1;
322 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300323 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300324 }
325
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300326 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
327 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 +0100328 case MP_BINARY_OP_LESS:
329 case MP_BINARY_OP_LESS_EQUAL:
330 case MP_BINARY_OP_MORE:
331 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300332 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200333 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
334 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
335 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300336 if (lhs_type == &mp_type_bytes) {
337 mp_buffer_info_t bufinfo;
338 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
339 goto uncomparable;
340 }
341 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
342 }
343uncomparable:
344 if (op == MP_BINARY_OP_EQUAL) {
345 return mp_const_false;
346 }
Damiend99b0522013-12-21 18:17:45 +0000347 }
348
Damien George6ac5dce2014-05-21 19:42:43 +0100349 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000350}
351
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300352#if !MICROPY_PY_BUILTINS_STR_UNICODE
353// objstrunicode defines own version
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300354const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, uint self_len,
355 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100356 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300357 return self_data + index_val;
358}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300359#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300360
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300361// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
362STATIC 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 +0300363 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100364 GET_STR_DATA_LEN(self_in, self_data, self_len);
365 if (value == MP_OBJ_SENTINEL) {
366 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100367#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100368 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300369 mp_bound_slice_t slice;
370 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300371 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100372 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100373 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100374 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100375 }
376#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300377 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100378 // If we have unicode enabled the type will always be bytes, so take the short cut.
379 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300380 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100381 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300382 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100383 }
384 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100385 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100386 }
387}
388
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200389STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700390 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300391 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000392
Damien Georgefe8fb912014-01-02 16:36:09 +0000393 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000394 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000395
396 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100397 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000398 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000399 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000400 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000401 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100402 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
403 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300404 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100405 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
406 }
407 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000408 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000409
410 // count required length
411 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000412 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300413 if (mp_obj_get_type(seq_items[i]) != self_type) {
414 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
415 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000416 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000417 if (i > 0) {
418 required_len += sep_len;
419 }
Damien George5fa93b62014-01-22 14:35:10 +0000420 GET_STR_LEN(seq_items[i], l);
421 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000422 }
423
424 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000425 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300426 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000427 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000428 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000429 memcpy(data, sep_str, sep_len);
430 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000431 }
Damien George5fa93b62014-01-22 14:35:10 +0000432 GET_STR_DATA_LEN(seq_items[i], s, l);
433 memcpy(data, s, l);
434 data += l;
Damiend99b0522013-12-21 18:17:45 +0000435 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000436
437 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000438 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000439}
440
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200441#define is_ws(c) ((c) == ' ' || (c) == '\t')
442
Damien Georgeecc88e92014-08-30 00:35:11 +0100443STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300444 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100445 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200446 mp_obj_t sep = mp_const_none;
447 if (n_args > 1) {
448 sep = args[1];
449 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100450 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200451 }
452 }
Damien Georgedeed0872014-04-06 11:11:15 +0100453
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200454 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000455 GET_STR_DATA_LEN(args[0], s, len);
456 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200457
Damien Georgedeed0872014-04-06 11:11:15 +0100458 if (sep == mp_const_none) {
459 // sep not given, so separate on whitespace
460
461 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000462 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100463 while (s < top && splits != 0) {
464 const byte *start = s;
465 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100466 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100467 if (s >= top) {
468 break;
469 }
470 while (s < top && is_ws(*s)) s++;
471 if (splits > 0) {
472 splits--;
473 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200474 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200475
Damien Georgedeed0872014-04-06 11:11:15 +0100476 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100477 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100478 }
479
480 } else {
481 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300482 if (mp_obj_get_type(sep) != self_type) {
483 arg_type_mixup();
484 }
Damien Georgedeed0872014-04-06 11:11:15 +0100485
486 uint sep_len;
487 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
488
489 if (sep_len == 0) {
490 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
491 }
492
493 for (;;) {
494 const byte *start = s;
495 for (;;) {
496 if (splits == 0 || s + sep_len > top) {
497 s = top;
498 break;
499 } else if (memcmp(s, sep_str, sep_len) == 0) {
500 break;
501 }
502 s++;
503 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100504 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100505 if (s >= top) {
506 break;
507 }
508 s += sep_len;
509 if (splits > 0) {
510 splits--;
511 }
512 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200513 }
514
515 return res;
516}
517
Damien Georgeecc88e92014-08-30 00:35:11 +0100518STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300519 if (n_args < 3) {
520 // If we don't have split limit, it doesn't matter from which side
521 // we split.
522 return str_split(n_args, args);
523 }
524 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
525 mp_obj_t sep = args[1];
526 GET_STR_DATA_LEN(args[0], s, len);
527
Damien George40f3c022014-07-03 13:25:24 +0100528 mp_int_t splits = mp_obj_get_int(args[2]);
529 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300530 // Preallocate list to the max expected # of elements, as we
531 // will fill it from the end.
532 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
533 int idx = splits;
534
535 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000536 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300537 } else {
538 uint sep_len;
539 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
540
541 if (sep_len == 0) {
542 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
543 }
544
545 const byte *beg = s;
546 const byte *last = s + len;
547 for (;;) {
548 s = last - sep_len;
549 for (;;) {
550 if (splits == 0 || s < beg) {
551 break;
552 } else if (memcmp(s, sep_str, sep_len) == 0) {
553 break;
554 }
555 s--;
556 }
557 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100558 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300559 break;
560 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100561 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 +0300562 last = s;
563 if (splits > 0) {
564 splits--;
565 }
566 }
567 if (idx != 0) {
568 // We split less parts than split limit, now go cleanup surplus
569 int used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100570 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300571 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
572 res->len = used;
573 }
574 }
575
576 return res;
577}
578
Damien Georgeecc88e92014-08-30 00:35:11 +0100579STATIC mp_obj_t str_finder(mp_uint_t n_args, const mp_obj_t *args, mp_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300580 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000581 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000582 assert(MP_OBJ_IS_STR(args[0]));
583 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000584
Damien George5fa93b62014-01-22 14:35:10 +0000585 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
586 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000587
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300588 const byte *start = haystack;
589 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000590 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300591 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000592 }
593 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300594 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000595 }
596
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300597 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000598 if (p == NULL) {
599 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700600 if (is_index) {
601 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
602 } else {
603 return MP_OBJ_NEW_SMALL_INT(-1);
604 }
Damien George23005372014-01-13 19:39:01 +0000605 } else {
606 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300607 #if MICROPY_PY_BUILTINS_STR_UNICODE
608 if (self_type == &mp_type_str) {
609 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
610 }
611 #endif
xbe17a5a832014-03-23 23:31:58 -0700612 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000613 }
John R. Lentone8204912014-01-12 21:53:52 +0000614}
615
Damien Georgeecc88e92014-08-30 00:35:11 +0100616STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700617 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700618}
619
Damien Georgeecc88e92014-08-30 00:35:11 +0100620STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700621 return str_finder(n_args, args, -1, false);
622}
623
Damien Georgeecc88e92014-08-30 00:35:11 +0100624STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700625 return str_finder(n_args, args, 1, true);
626}
627
Damien Georgeecc88e92014-08-30 00:35:11 +0100628STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700629 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700630}
631
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200632// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100633STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300634 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300635 GET_STR_DATA_LEN(args[0], str, str_len);
636 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300637 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300638 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300639 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300640 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300641 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200642 return mp_const_false;
643 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300644 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200645}
646
Damien Georgeecc88e92014-08-30 00:35:11 +0100647STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300648 GET_STR_DATA_LEN(args[0], str, str_len);
649 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
650 assert(n_args == 2);
651
652 if (suffix_len > str_len) {
653 return mp_const_false;
654 }
655 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
656}
657
Paul Sokolovsky88107842014-04-26 06:20:08 +0300658enum { LSTRIP, RSTRIP, STRIP };
659
Damien Georgeecc88e92014-08-30 00:35:11 +0100660STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800661 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700662 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300663 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000664
665 const byte *chars_to_del;
666 uint chars_to_del_len;
667 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800668
669 if (n_args == 1) {
670 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000671 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800672 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300673 if (mp_obj_get_type(args[1]) != self_type) {
674 arg_type_mixup();
675 }
Damien George5fa93b62014-01-22 14:35:10 +0000676 GET_STR_DATA_LEN(args[1], s, l);
677 chars_to_del = s;
678 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800679 }
680
Damien George5fa93b62014-01-22 14:35:10 +0000681 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800682
Damien George40f3c022014-07-03 13:25:24 +0100683 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800684 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100685 mp_uint_t last_good_char_pos = 0;
686 mp_uint_t i = 0;
687 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300688 if (type == RSTRIP) {
689 i = orig_str_len - 1;
690 delta = -1;
691 }
Damien George40f3c022014-07-03 13:25:24 +0100692 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700693 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800694 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300695 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800696 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300697 if (type == LSTRIP) {
698 last_good_char_pos = orig_str_len - 1;
699 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300700 } else if (type == RSTRIP) {
701 first_good_char_pos = 0;
702 last_good_char_pos = i;
703 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300704 }
xbe7b0f39f2014-01-08 14:23:45 -0800705 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300706 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800707 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300708 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800709 }
710
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300711 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000712 // string is all whitespace, return ''
713 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800714 }
715
716 assert(last_good_char_pos >= first_good_char_pos);
717 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100718 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300719 if (stripped_len == orig_str_len) {
720 // If nothing was stripped, don't bother to dup original string
721 // TODO: watch out for this case when we'll get to bytearray.strip()
722 assert(first_good_char_pos == 0);
723 return args[0];
724 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100725 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800726}
727
Damien Georgeecc88e92014-08-30 00:35:11 +0100728STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300729 return str_uni_strip(STRIP, n_args, args);
730}
731
Damien Georgeecc88e92014-08-30 00:35:11 +0100732STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300733 return str_uni_strip(LSTRIP, n_args, args);
734}
735
Damien Georgeecc88e92014-08-30 00:35:11 +0100736STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300737 return str_uni_strip(RSTRIP, n_args, args);
738}
739
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700740// Takes an int arg, but only parses unsigned numbers, and only changes
741// *num if at least one digit was parsed.
742static int str_to_int(const char *str, int *num) {
743 const char *s = str;
744 if (unichar_isdigit(*s)) {
745 *num = 0;
746 do {
747 *num = *num * 10 + (*s - '0');
748 s++;
749 }
750 while (unichar_isdigit(*s));
751 }
752 return s - str;
753}
754
755static bool isalignment(char ch) {
756 return ch && strchr("<>=^", ch) != NULL;
757}
758
759static bool istype(char ch) {
760 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
761}
762
763static bool arg_looks_integer(mp_obj_t arg) {
764 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
765}
766
767static bool arg_looks_numeric(mp_obj_t arg) {
768 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100769#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700770 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
771#endif
772 ;
773}
774
Dave Hylandsc4029e52014-04-07 11:19:51 -0700775static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100776#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700777 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700778
779 // TODO: Needs a way to construct an mpz integer from a float
780
Damien George40f3c022014-07-03 13:25:24 +0100781 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700782 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700783 }
784#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700785 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700786}
787
Damien Georgeecc88e92014-08-30 00:35:11 +0100788mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000789 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000790
Damien George5fa93b62014-01-22 14:35:10 +0000791 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700792 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000793 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700794 pfenv_t pfenv_vstr;
795 pfenv_vstr.data = vstr;
796 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
797
Damien George5fa93b62014-01-22 14:35:10 +0000798 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700799 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000800 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700801 if (str < top && *str == '}') {
802 vstr_add_char(vstr, '}');
803 continue;
804 }
Damien George11de8392014-06-05 18:57:38 +0100805 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700806 }
807 if (*str != '{') {
808 vstr_add_char(vstr, *str);
809 continue;
810 }
811
812 str++;
813 if (str < top && *str == '{') {
814 vstr_add_char(vstr, '{');
815 continue;
816 }
817
818 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
819
820 vstr_t *field_name = NULL;
821 char conversion = '\0';
822 vstr_t *format_spec = NULL;
823
824 if (str < top && *str != '}' && *str != '!' && *str != ':') {
825 field_name = vstr_new();
826 while (str < top && *str != '}' && *str != '!' && *str != ':') {
827 vstr_add_char(field_name, *str++);
828 }
829 vstr_add_char(field_name, '\0');
830 }
831
832 // conversion ::= "r" | "s"
833
834 if (str < top && *str == '!') {
835 str++;
836 if (str < top && (*str == 'r' || *str == 's')) {
837 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200838 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100839 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 -0700840 }
841 }
842
843 if (str < top && *str == ':') {
844 str++;
845 // {:} is the same as {}, which is the same as {!s}
846 // This makes a difference when passing in a True or False
847 // '{}'.format(True) returns 'True'
848 // '{:d}'.format(True) returns '1'
849 // So we treat {:} as {} and this later gets treated to be {!s}
850 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100851 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700852 while (str < top && *str != '}') {
853 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000854 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700855 vstr_add_char(format_spec, '\0');
856 }
857 }
858 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100859 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700860 }
861 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100862 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700863 }
864
865 mp_obj_t arg = mp_const_none;
866
867 if (field_name) {
868 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100869 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 -0700870 }
Damien George3bb8bd82014-04-14 21:20:30 +0100871 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100873 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700874 }
875 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100876 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700877 }
878 arg = args[index + 1];
879 arg_i = -1;
880 vstr_free(field_name);
881 field_name = NULL;
882 } else {
883 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100884 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 -0700885 }
886 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100887 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700888 }
889 arg = args[arg_i + 1];
890 arg_i++;
891 }
892 if (!format_spec && !conversion) {
893 conversion = 's';
894 }
895 if (conversion) {
896 mp_print_kind_t print_kind;
897 if (conversion == 's') {
898 print_kind = PRINT_STR;
899 } else if (conversion == 'r') {
900 print_kind = PRINT_REPR;
901 } else {
Damien George11de8392014-06-05 18:57:38 +0100902 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700903 }
904 vstr_t *arg_vstr = vstr_new();
905 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100906 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700907 vstr_free(arg_vstr);
908 }
909
910 char sign = '\0';
911 char fill = '\0';
912 char align = '\0';
913 int width = -1;
914 int precision = -1;
915 char type = '\0';
916 int flags = 0;
917
918 if (format_spec) {
919 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
920 //
921 // [[fill]align][sign][#][0][width][,][.precision][type]
922 // fill ::= <any character>
923 // align ::= "<" | ">" | "=" | "^"
924 // sign ::= "+" | "-" | " "
925 // width ::= integer
926 // precision ::= integer
927 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
928
929 const char *s = vstr_str(format_spec);
930 if (isalignment(*s)) {
931 align = *s++;
932 } else if (*s && isalignment(s[1])) {
933 fill = *s++;
934 align = *s++;
935 }
936 if (*s == '+' || *s == '-' || *s == ' ') {
937 if (*s == '+') {
938 flags |= PF_FLAG_SHOW_SIGN;
939 } else if (*s == ' ') {
940 flags |= PF_FLAG_SPACE_SIGN;
941 }
942 sign = *s++;
943 }
944 if (*s == '#') {
945 flags |= PF_FLAG_SHOW_PREFIX;
946 s++;
947 }
948 if (*s == '0') {
949 if (!align) {
950 align = '=';
951 }
952 if (!fill) {
953 fill = '0';
954 }
955 }
956 s += str_to_int(s, &width);
957 if (*s == ',') {
958 flags |= PF_FLAG_SHOW_COMMA;
959 s++;
960 }
961 if (*s == '.') {
962 s++;
963 s += str_to_int(s, &precision);
964 }
965 if (istype(*s)) {
966 type = *s++;
967 }
968 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100969 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700970 }
971 vstr_free(format_spec);
972 format_spec = NULL;
973 }
974 if (!align) {
975 if (arg_looks_numeric(arg)) {
976 align = '>';
977 } else {
978 align = '<';
979 }
980 }
981 if (!fill) {
982 fill = ' ';
983 }
984
985 if (sign) {
986 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100987 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700988 }
989 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100990 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000991 }
992 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700993 sign = '-';
994 }
995
996 switch (align) {
997 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
998 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
999 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1000 }
1001
1002 if (arg_looks_integer(arg)) {
1003 switch (type) {
1004 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001005 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001006 continue;
1007
1008 case 'c':
1009 {
1010 char ch = mp_obj_get_int(arg);
1011 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1012 continue;
1013 }
1014
1015 case '\0': // No explicit format type implies 'd'
1016 case 'n': // I don't think we support locales in uPy so use 'd'
1017 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001018 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001019 continue;
1020
1021 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001022 if (flags & PF_FLAG_SHOW_PREFIX) {
1023 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1024 }
1025
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001026 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001027 continue;
1028
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001029 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001030 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001031 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001032 continue;
1033
1034 case 'e':
1035 case 'E':
1036 case 'f':
1037 case 'F':
1038 case 'g':
1039 case 'G':
1040 case '%':
1041 // The floating point formatters all work with anything that
1042 // looks like an integer
1043 break;
1044
1045 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001046 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001047 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001048 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001049 }
Damien George70f33cd2014-04-02 17:06:05 +01001050
Dave Hylands22fe4d72014-04-02 12:07:31 -07001051 // NOTE: no else here. We need the e, f, g etc formats for integer
1052 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001053 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001054 if (!type) {
1055
1056 // Even though the docs say that an unspecified type is the same
1057 // as 'g', there is one subtle difference, when the exponent
1058 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001059 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001060 // '{:10.1}'.format(0.0) ==> '0e+00'
1061 // '{:10.1g}'.format(0.0) ==> '0'
1062 //
1063 // TODO: Figure out how to deal with this.
1064 //
1065 // A proper solution would involve adding a special flag
1066 // or something to format_float, and create a format_double
1067 // to deal with doubles. In order to fix this when using
1068 // sprintf, we'd need to use the e format and tweak the
1069 // returned result to strip trailing zeros like the g format
1070 // does.
1071 //
1072 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1073 // but with 1.e2 you get 1e+02 and 1.00e+02
1074 //
1075 // Stripping the trailing 0's (like g) does would make the
1076 // e format give us the right format.
1077 //
1078 // CPython sources say:
1079 // Omitted type specifier. Behaves in the same way as repr(x)
1080 // and str(x) if no precision is given, else like 'g', but with
1081 // at least one digit after the decimal point. */
1082
1083 type = 'g';
1084 }
1085 if (type == 'n') {
1086 type = 'g';
1087 }
1088
1089 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1090 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001091#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001092 case 'e':
1093 case 'E':
1094 case 'f':
1095 case 'F':
1096 case 'g':
1097 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001098 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001099 break;
1100
1101 case '%':
1102 flags |= PF_FLAG_ADD_PERCENT;
1103 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1104 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001105#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001106
1107 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001108 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001109 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001110 type, mp_obj_get_type_str(arg)));
1111 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001112 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001113 // arg doesn't look like a number
1114
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001115 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001116 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001117 }
Damien George70f33cd2014-04-02 17:06:05 +01001118
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001119 switch (type) {
1120 case '\0':
1121 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1122 break;
1123
1124 case 's':
1125 {
1126 uint len;
1127 const char *s = mp_obj_str_get_data(arg, &len);
1128 if (precision < 0) {
1129 precision = len;
1130 }
1131 if (len > precision) {
1132 len = precision;
1133 }
1134 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1135 break;
1136 }
1137
1138 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001139 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001140 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001141 type, mp_obj_get_type_str(arg)));
1142 }
Damiend99b0522013-12-21 18:17:45 +00001143 }
1144 }
1145
Damien George2617eeb2014-05-25 22:27:57 +01001146 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001147 vstr_free(vstr);
1148 return s;
Damiend99b0522013-12-21 18:17:45 +00001149}
1150
Damien Georgeecc88e92014-08-30 00:35:11 +01001151STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001152 assert(MP_OBJ_IS_STR(pattern));
1153
1154 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001155 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001156 int arg_i = 0;
1157 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001158 pfenv_t pfenv_vstr;
1159 pfenv_vstr.data = vstr;
1160 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1161
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001162 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001163 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001164 if (*str != '%') {
1165 vstr_add_char(vstr, *str);
1166 continue;
1167 }
1168 if (++str >= top) {
1169 break;
1170 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001171 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001172 vstr_add_char(vstr, '%');
1173 continue;
1174 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001175
1176 // Dictionary value lookup
1177 if (*str == '(') {
1178 const byte *key = ++str;
1179 while (*str != ')') {
1180 if (str >= top) {
1181 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1182 }
1183 ++str;
1184 }
1185 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1186 arg = mp_obj_dict_get(dict, k_obj);
1187 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001188 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001189
Dave Hylands6756a372014-04-02 11:42:39 -07001190 int flags = 0;
1191 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001192 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001193 while (str < top) {
1194 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1195 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1196 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001197 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001198 else if (*str == '0') {
1199 flags |= PF_FLAG_PAD_AFTER_SIGN;
1200 fill = '0';
1201 } else break;
1202 str++;
1203 }
1204 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001205 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001206 if (str < top) {
1207 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001208 if (arg_i >= n_args) {
1209 goto not_enough_args;
1210 }
Dave Hylands6756a372014-04-02 11:42:39 -07001211 width = mp_obj_get_int(args[arg_i++]);
1212 str++;
1213 } else {
1214 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1215 width = width * 10 + *str - '0';
1216 }
1217 }
1218 }
1219 int prec = -1;
1220 if (str < top && *str == '.') {
1221 if (++str < top) {
1222 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001223 if (arg_i >= n_args) {
1224 goto not_enough_args;
1225 }
Dave Hylands6756a372014-04-02 11:42:39 -07001226 prec = mp_obj_get_int(args[arg_i++]);
1227 str++;
1228 } else {
1229 prec = 0;
1230 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1231 prec = prec * 10 + *str - '0';
1232 }
1233 }
1234 }
1235 }
1236
1237 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001238 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001239 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001240
1241 // Tuple value lookup
1242 if (arg == MP_OBJ_NULL) {
1243 if (arg_i >= n_args) {
1244not_enough_args:
1245 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1246 }
1247 arg = args[arg_i++];
1248 }
Dave Hylands6756a372014-04-02 11:42:39 -07001249 switch (*str) {
1250 case 'c':
1251 if (MP_OBJ_IS_STR(arg)) {
1252 uint len;
1253 const char *s = mp_obj_str_get_data(arg, &len);
1254 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001255 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001256 break;
1257 }
1258 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1259 break;
1260 }
1261 if (arg_looks_integer(arg)) {
1262 char ch = mp_obj_get_int(arg);
1263 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1264 break;
1265 }
Damien Georgefb510b32014-06-01 13:32:54 +01001266#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001267 // This is what CPython reports, so we report the same.
1268 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001269 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001270
1271 }
1272#endif
Damien George11de8392014-06-05 18:57:38 +01001273 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1274 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001275
1276 case 'd':
1277 case 'i':
1278 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001279 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001280 break;
1281
Damien Georgefb510b32014-06-01 13:32:54 +01001282#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001283 case 'e':
1284 case 'E':
1285 case 'f':
1286 case 'F':
1287 case 'g':
1288 case 'G':
1289 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1290 break;
1291#endif
1292
1293 case 'o':
1294 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001295 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001296 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001297 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001298 break;
1299
1300 case 'r':
1301 case 's':
1302 {
1303 vstr_t *arg_vstr = vstr_new();
1304 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1305 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1306 uint len = vstr_len(arg_vstr);
1307 if (prec < 0) {
1308 prec = len;
1309 }
1310 if (len > prec) {
1311 len = prec;
1312 }
1313 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1314 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001315 break;
1316 }
Dave Hylands6756a372014-04-02 11:42:39 -07001317
Dave Hylands6756a372014-04-02 11:42:39 -07001318 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001319 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001320 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001321 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001322
Dave Hylands6756a372014-04-02 11:42:39 -07001323 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001324 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001325 "unsupported format character '%c' (0x%x) at index %d",
1326 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001327 }
1328 }
1329
1330 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001331 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001332 }
1333
Damien George2617eeb2014-05-25 22:27:57 +01001334 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001335 vstr_free(vstr);
1336 return s;
1337}
1338
Damien Georgeecc88e92014-08-30 00:35:11 +01001339STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001340 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001341
Damien George40f3c022014-07-03 13:25:24 +01001342 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001343 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001344 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001345 if (max_rep == 0) {
1346 return args[0];
1347 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001348 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001349 }
xbe480c15a2014-01-30 22:17:30 -08001350 }
Damien George94f68302014-01-31 23:45:12 +00001351
xbe729be9b2014-04-07 14:46:39 -07001352 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001353
Damien Georgeff715422014-04-07 00:39:13 +01001354 // check argument types
1355
1356 if (!MP_OBJ_IS_STR(args[1])) {
1357 bad_implicit_conversion(args[1]);
1358 }
1359
1360 if (!MP_OBJ_IS_STR(args[2])) {
1361 bad_implicit_conversion(args[2]);
1362 }
1363
1364 // extract string data
1365
xbe480c15a2014-01-30 22:17:30 -08001366 GET_STR_DATA_LEN(args[0], str, str_len);
1367 GET_STR_DATA_LEN(args[1], old, old_len);
1368 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001369
1370 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001371 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001372 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001373 }
1374
Damien George94f68302014-01-31 23:45:12 +00001375 // data for the replaced string
1376 byte *data = NULL;
1377 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001378
Damien George94f68302014-01-31 23:45:12 +00001379 // do 2 passes over the string:
1380 // first pass computes the required length of the replaced string
1381 // second pass does the replacements
1382 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001383 mp_uint_t replaced_str_index = 0;
1384 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001385 const byte *old_occurrence;
1386 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001387 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001388 if (old_len == 0) {
1389 // if old_str is empty, copy new_str to start of replaced string
1390 // copy the replacement string
1391 if (data != NULL) {
1392 memcpy(data, new, new_len);
1393 }
1394 replaced_str_index += new_len;
1395 num_replacements_done++;
1396 }
1397 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1398 if (old_len == 0) {
1399 old_occurrence += 1;
1400 }
Damien George94f68302014-01-31 23:45:12 +00001401 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1402 if (data != NULL) {
1403 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1404 }
1405 replaced_str_index += old_occurrence - offset_ptr;
1406 // copy the replacement string
1407 if (data != NULL) {
1408 memcpy(data + replaced_str_index, new, new_len);
1409 }
1410 replaced_str_index += new_len;
1411 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001412 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001413 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001414 }
1415
1416 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1417 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001418 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001419 }
Damien Georgeff715422014-04-07 00:39:13 +01001420 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001421
1422 if (data == NULL) {
1423 // first pass
1424 if (num_replacements_done == 0) {
1425 // no substr found, return original string
1426 return args[0];
1427 } else {
1428 // substr found, allocate new string
1429 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001430 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001431 }
1432 } else {
1433 // second pass, we are done
1434 break;
1435 }
xbe480c15a2014-01-30 22:17:30 -08001436 }
Damien George94f68302014-01-31 23:45:12 +00001437
xbe480c15a2014-01-30 22:17:30 -08001438 return mp_obj_str_builder_end(replaced_str);
1439}
1440
Damien Georgeecc88e92014-08-30 00:35:11 +01001441STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001442 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001443 assert(2 <= n_args && n_args <= 4);
1444 assert(MP_OBJ_IS_STR(args[0]));
1445 assert(MP_OBJ_IS_STR(args[1]));
1446
1447 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1448 GET_STR_DATA_LEN(args[1], needle, needle_len);
1449
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001450 const byte *start = haystack;
1451 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001452 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001453 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001454 }
1455 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001456 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001457 }
1458
Damien George536dde22014-03-13 22:07:55 +00001459 // if needle_len is zero then we count each gap between characters as an occurrence
1460 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001461 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001462 }
1463
Damien George536dde22014-03-13 22:07:55 +00001464 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001465 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001466 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1467 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001468 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001469 haystack_ptr += needle_len;
1470 } else {
1471 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001472 }
xbe9e1e8cd2014-03-12 22:57:16 -07001473 }
1474
1475 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1476}
1477
Damien George40f3c022014-07-03 13:25:24 +01001478STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001479 if (!MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001480 assert(0);
1481 }
1482 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1483 if (self_type != mp_obj_get_type(arg)) {
1484 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001485 }
Damien Georgeb035db32014-03-21 20:39:40 +00001486
xbe613a8e32014-03-18 00:06:29 -07001487 GET_STR_DATA_LEN(self_in, str, str_len);
1488 GET_STR_DATA_LEN(arg, sep, sep_len);
1489
1490 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001491 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001492 }
Damien Georgeb035db32014-03-21 20:39:40 +00001493
1494 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1495
1496 if (direction > 0) {
1497 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001498 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001499 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001500 }
xbe613a8e32014-03-18 00:06:29 -07001501
xbe17a5a832014-03-23 23:31:58 -07001502 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1503 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001504 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001505 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001506 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001507 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 -07001508 }
Damien Georgeb035db32014-03-21 20:39:40 +00001509
xbe0a6894c2014-03-21 01:12:26 -07001510 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001511}
1512
Damien Georgeb035db32014-03-21 20:39:40 +00001513STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1514 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001515}
xbe4504ea82014-03-19 00:46:14 -07001516
Damien Georgeb035db32014-03-21 20:39:40 +00001517STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1518 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001519}
1520
Paul Sokolovsky69135212014-05-10 19:47:41 +03001521// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001522STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001523 GET_STR_DATA_LEN(self_in, self_data, self_len);
1524 byte *data;
1525 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1526 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001527 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001528 }
1529 *data = 0;
1530 return mp_obj_str_builder_end(s);
1531}
1532
1533STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001534 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001535}
1536
1537STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001538 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001539}
1540
Damien Georgefcc9cf62014-06-01 18:22:09 +01001541STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001542 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001543
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001544 if (self_len == 0) {
1545 return mp_const_false; // default to False for empty str
1546 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001547
Damien Georgefcc9cf62014-06-01 18:22:09 +01001548 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001549 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001550 if (!f(*self_data++)) {
1551 return mp_const_false;
1552 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001553 }
1554 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001555 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001556
Kim Bautersa3f4b832014-05-31 07:30:03 +01001557 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1558 if (unichar_isalpha(*self_data++)) {
1559 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001560 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1561 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001562 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001563 }
1564 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001565
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001566 if (!contains_alpha) {
1567 return mp_const_false;
1568 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001569 }
1570
1571 return mp_const_true;
1572}
1573
1574STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001575 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001576}
1577
1578STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001579 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001580}
1581
1582STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001583 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001584}
1585
1586STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001587 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001588}
1589
1590STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001591 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001592}
1593
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001594#if MICROPY_CPYTHON_COMPAT
1595// These methods are superfluous in the presense of str() and bytes()
1596// constructors.
1597// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001598STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001599 mp_obj_t new_args[2];
1600 if (n_args == 1) {
1601 new_args[0] = args[0];
1602 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1603 args = new_args;
1604 n_args++;
1605 }
1606 return str_make_new(NULL, n_args, 0, args);
1607}
1608
1609// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001610STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001611 mp_obj_t new_args[2];
1612 if (n_args == 1) {
1613 new_args[0] = args[0];
1614 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1615 args = new_args;
1616 n_args++;
1617 }
1618 return bytes_make_new(NULL, n_args, 0, args);
1619}
1620#endif
1621
Damien George40f3c022014-07-03 13:25:24 +01001622mp_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 +01001623 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001624 GET_STR_DATA_LEN(self_in, str_data, str_len);
1625 bufinfo->buf = (void*)str_data;
1626 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001627 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001628 return 0;
1629 } else {
1630 // can't write to a string
1631 bufinfo->buf = NULL;
1632 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001633 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001634 return 1;
1635 }
1636}
1637
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001638#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001639MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1640MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001641#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001642MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1643MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1644MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1645MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1646MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1647MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1648MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1649MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1650MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1651MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1652MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1653MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1654MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1655MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1656MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1657MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1658MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1659MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1660MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1661MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1662MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1663MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1664MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1665MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001666
Damien George9b196cd2014-03-26 21:47:19 +00001667STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001668#if MICROPY_CPYTHON_COMPAT
1669 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001670 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1671 // If we have separate unicode type, then here we have methods only
1672 // for bytes type, and it should not have encode() methods. Otherwise,
1673 // we have non-compliant-but-practical bytestring type, which shares
1674 // method table with bytes, so they both have encode() and decode()
1675 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001676 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001677 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001678#endif
Damien George9b196cd2014-03-26 21:47:19 +00001679 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1680 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001681 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1682 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001683 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1684 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001685 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001686 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001687 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001688 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001689 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1690 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001691 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1692 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1693 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1694 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1695 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001696 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1697 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001698 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1699 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1700 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1701 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1702 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001703};
Damien George97209d32014-01-07 15:58:30 +00001704
Damien George9b196cd2014-03-26 21:47:19 +00001705STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1706
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001707#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001708const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001709 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001710 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001711 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001712 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001713 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001714 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001715 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001716 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001717 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001718};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001719#endif
Damiend99b0522013-12-21 18:17:45 +00001720
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001721// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001722const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001723 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001724 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001725 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001726 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001727 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001728 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001729 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001730 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001731 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001732};
1733
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001734// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001735STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001736const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1737
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001738mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001739 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001740 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001741 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001742 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001743 byte *p = m_new(byte, len + 1);
1744 o->data = p;
1745 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001746 return o;
1747}
1748
Damien George5fa93b62014-01-22 14:35:10 +00001749mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001750 mp_obj_str_t *o = o_in;
1751 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001752 byte *p = (byte*)o->data;
1753 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001754 return o;
1755}
1756
Damien George5f27a7e2014-07-31 10:29:56 +01001757mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1758 mp_obj_str_t *o = o_in;
1759 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1760 o->len = len;
1761 o->hash = qstr_compute_hash(o->data, o->len);
1762 byte *p = (byte*)o->data;
1763 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1764 return o;
1765}
1766
Damien Georgef600a6a2014-05-25 22:34:34 +01001767mp_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 +02001768 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001769 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001770 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001771 if (data) {
1772 o->hash = qstr_compute_hash(data, len);
1773 byte *p = m_new(byte, len + 1);
1774 o->data = p;
1775 memcpy(p, data, len * sizeof(byte));
1776 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1777 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001778 return o;
1779}
1780
Damien George2617eeb2014-05-25 22:27:57 +01001781mp_obj_t mp_obj_new_str(const char* data, uint len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001782 if (make_qstr_if_not_already) {
1783 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001784 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001785 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001786 qstr q = qstr_find_strn(data, len);
1787 if (q != MP_QSTR_NULL) {
1788 // qstr with this data already exists
1789 return MP_OBJ_NEW_QSTR(q);
1790 } else {
1791 // no existing qstr, don't make one
1792 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1793 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001794 }
Damien George5fa93b62014-01-22 14:35:10 +00001795}
1796
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001797mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1798 GET_STR_DATA_LEN(str, data, len);
1799 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1800}
1801
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001802mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001803 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001804}
1805
Damien George5fa93b62014-01-22 14:35:10 +00001806bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1807 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1808 return s1 == s2;
1809 } else {
1810 GET_STR_HASH(s1, h1);
1811 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001812 // If any of hashes is 0, it means it's not valid
1813 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001814 return false;
1815 }
1816 GET_STR_DATA_LEN(s1, d1, l1);
1817 GET_STR_DATA_LEN(s2, d2, l2);
1818 if (l1 != l2) {
1819 return false;
1820 }
Damien George1e708fe2014-01-23 18:27:51 +00001821 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001822 }
Damien George5fa93b62014-01-22 14:35:10 +00001823}
1824
Damien Georgedeed0872014-04-06 11:11:15 +01001825STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001826 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 +00001827}
1828
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001829STATIC void arg_type_mixup() {
1830 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1831}
1832
Damien George5fa93b62014-01-22 14:35:10 +00001833uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001834 // TODO: This has too big overhead for hash accessor
1835 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001836 GET_STR_HASH(self_in, h);
1837 return h;
1838 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001839 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001840 }
1841}
1842
1843uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001844 // TODO This has a double check for the type, one in obj.c and one here
1845 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001846 GET_STR_LEN(self_in, l);
1847 return l;
1848 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001849 bad_implicit_conversion(self_in);
1850 }
1851}
1852
1853// use this if you will anyway convert the string to a qstr
1854// will be more efficient for the case where it's already a qstr
1855qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1856 if (MP_OBJ_IS_QSTR(self_in)) {
1857 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001858 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001859 mp_obj_str_t *self = self_in;
1860 return qstr_from_strn((char*)self->data, self->len);
1861 } else {
1862 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001863 }
1864}
1865
1866// only use this function if you need the str data to be zero terminated
1867// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1868const char *mp_obj_str_get_str(mp_obj_t self_in) {
1869 if (MP_OBJ_IS_STR(self_in)) {
1870 GET_STR_DATA_LEN(self_in, s, l);
1871 (void)l; // len unused
1872 return (const char*)s;
1873 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001874 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001875 }
1876}
1877
Damien George698ec212014-02-08 18:17:23 +00001878const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001879 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001880 GET_STR_DATA_LEN(self_in, s, l);
1881 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001882 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001883 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001884 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001885 }
Damiend99b0522013-12-21 18:17:45 +00001886}
xyb8cfc9f02014-01-05 18:47:51 +08001887
1888/******************************************************************************/
1889/* str iterator */
1890
1891typedef struct _mp_obj_str_it_t {
1892 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001893 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01001894 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08001895} mp_obj_str_it_t;
1896
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001897#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001898STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001899 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001900 GET_STR_DATA_LEN(self->str, str, len);
1901 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001902 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001903 self->cur += 1;
1904 return o_out;
1905 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001906 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001907 }
1908}
1909
Damien George3e1a5c12014-03-29 13:43:38 +00001910STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001911 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001912 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001913 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001914 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001915};
1916
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001917mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
1918 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
1919 o->base.type = &mp_type_str_it;
1920 o->str = str;
1921 o->cur = 0;
1922 return o;
1923}
1924#endif
1925
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001926STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001927 mp_obj_str_it_t *self = self_in;
1928 GET_STR_DATA_LEN(self->str, str, len);
1929 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01001930 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001931 self->cur += 1;
1932 return o_out;
1933 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001934 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001935 }
1936}
1937
Damien George3e1a5c12014-03-29 13:43:38 +00001938STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001939 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001940 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001941 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001942 .iternext = bytes_it_iternext,
1943};
1944
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001945mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1946 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001947 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001948 o->str = str;
1949 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001950 return o;
1951}