blob: c44e9ebf16e3ee47ded23e4efea57f5318f96e24 [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
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
xbeefe34222014-03-16 00:14:26 -070027#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +000028#include <string.h>
29#include <assert.h>
30
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030031#include "mpconfig.h"
Damiend99b0522013-12-21 18:17:45 +000032#include "nlr.h"
33#include "misc.h"
Damien George55baff42014-01-21 21:40:13 +000034#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000035#include "obj.h"
36#include "runtime0.h"
37#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070038#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030039#include "objstr.h"
Damiend99b0522013-12-21 18:17:45 +000040
Paul Sokolovsky4db727a2014-03-31 21:18:28 +030041STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020042const mp_obj_t mp_const_empty_bytes;
43
Damien George5fa93b62014-01-22 14:35:10 +000044// use this macro to extract the string hash
45#define GET_STR_HASH(str_obj_in, str_hash) uint str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)str_obj_in)->hash; }
46
47// use this macro to extract the string length
48#define GET_STR_LEN(str_obj_in, str_len) uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; }
49
50// use this macro to extract the string data and length
51#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) const byte *str_data; uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; str_data = ((mp_obj_str_t*)str_obj_in)->data; }
52
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020053STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
54STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskybe020c22014-03-21 11:39:01 +020055STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len);
Paul Sokolovskye9085912014-04-30 05:35:18 +030056STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030057STATIC NORETURN void arg_type_mixup();
58
59STATIC bool is_str_or_bytes(mp_obj_t o) {
60 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
61}
xyb8cfc9f02014-01-05 18:47:51 +080062
63/******************************************************************************/
64/* str */
65
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020066void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
67 // this escapes characters, but it will be very slow to print (calling print many times)
68 bool has_single_quote = false;
69 bool has_double_quote = false;
70 for (const byte *s = str_data, *top = str_data + str_len; (!has_single_quote || !has_double_quote) && s < top; s++) {
71 if (*s == '\'') {
72 has_single_quote = true;
73 } else if (*s == '"') {
74 has_double_quote = true;
75 }
76 }
77 int quote_char = '\'';
78 if (has_single_quote && !has_double_quote) {
79 quote_char = '"';
80 }
81 print(env, "%c", quote_char);
82 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
83 if (*s == quote_char) {
84 print(env, "\\%c", quote_char);
85 } else if (*s == '\\') {
86 print(env, "\\\\");
87 } else if (32 <= *s && *s <= 126) {
88 print(env, "%c", *s);
89 } else if (*s == '\n') {
90 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010091 } else if (*s == '\r') {
92 print(env, "\\r");
93 } else if (*s == '\t') {
94 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020095 } else {
96 print(env, "\\x%02x", *s);
97 }
98 }
99 print(env, "%c", quote_char);
100}
101
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200102STATIC 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 +0000103 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000104 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200105 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000106 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200107 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200108 if (is_bytes) {
109 print(env, "b");
110 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +0200111 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200112 }
Damiend99b0522013-12-21 18:17:45 +0000113}
114
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200115STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300116#if MICROPY_CPYTHON_COMPAT
117 if (n_kw != 0) {
118 mp_arg_error_unimpl_kw();
119 }
120#endif
121
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200122 switch (n_args) {
123 case 0:
124 return MP_OBJ_NEW_QSTR(MP_QSTR_);
125
126 case 1:
127 {
128 vstr_t *vstr = vstr_new();
129 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
130 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
131 vstr_free(vstr);
132 return s;
133 }
134
135 case 2:
136 case 3:
137 {
138 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000139 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100140 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200141 }
142 GET_STR_DATA_LEN(args[0], str_data, str_len);
143 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000144 mp_obj_str_t *o = str_new(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200145 o->data = str_data;
146 o->hash = str_hash;
147 return o;
148 }
149
150 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100151 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200152 }
153}
154
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200155STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
156 if (n_args == 0) {
157 return mp_const_empty_bytes;
158 }
159
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300160#if MICROPY_CPYTHON_COMPAT
161 if (n_kw != 0) {
162 mp_arg_error_unimpl_kw();
163 }
164#endif
165
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200166 if (MP_OBJ_IS_STR(args[0])) {
167 if (n_args < 2 || n_args > 3) {
168 goto wrong_args;
169 }
170 GET_STR_DATA_LEN(args[0], str_data, str_len);
171 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000172 mp_obj_str_t *o = str_new(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200173 o->data = str_data;
174 o->hash = str_hash;
175 return o;
176 }
177
178 if (n_args > 1) {
179 goto wrong_args;
180 }
181
182 if (MP_OBJ_IS_SMALL_INT(args[0])) {
183 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
184 byte *data;
185
Damien George3e1a5c12014-03-29 13:43:38 +0000186 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200187 memset(data, 0, len);
188 return mp_obj_str_builder_end(o);
189 }
190
191 int len;
192 byte *data;
193 vstr_t *vstr = NULL;
194 mp_obj_t o = NULL;
195 // Try to create array of exact len if initializer len is known
196 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
197 if (len_in == MP_OBJ_NULL) {
198 len = -1;
199 vstr = vstr_new();
200 } else {
201 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000202 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200203 }
204
Damien Georged17926d2014-03-30 13:35:08 +0100205 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200206 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100207 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200208 if (len == -1) {
209 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
210 } else {
211 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
212 }
213 }
214
215 if (len == -1) {
216 vstr_shrink(vstr);
217 // TODO: Optimize, borrow buffer from vstr
218 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000219 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200220 memcpy(data, vstr_str(vstr), len);
221 vstr_free(vstr);
222 }
223
224 return mp_obj_str_builder_end(o);
225
226wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100227 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200228}
229
Damien George55baff42014-01-21 21:40:13 +0000230// like strstr but with specified length and allows \0 bytes
231// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700232STATIC const byte *find_subbytes(const byte *haystack, machine_uint_t hlen, const byte *needle, machine_uint_t nlen, machine_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000233 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700234 machine_uint_t str_index, str_index_end;
235 if (direction > 0) {
236 str_index = 0;
237 str_index_end = hlen - nlen;
238 } else {
239 str_index = hlen - nlen;
240 str_index_end = 0;
241 }
242 for (;;) {
243 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
244 //found
245 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000246 }
xbe17a5a832014-03-23 23:31:58 -0700247 if (str_index == str_index_end) {
248 //not found
249 break;
Damien George55baff42014-01-21 21:40:13 +0000250 }
xbe17a5a832014-03-23 23:31:58 -0700251 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000252 }
253 }
254 return NULL;
255}
256
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200257STATIC mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000258 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300259 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
260 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000261 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100262 case MP_BINARY_OP_ADD:
263 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300264 if (lhs_type == rhs_type) {
265 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000266
267 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000268 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000269
270 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000271 byte *q_ptr;
272 byte *val = qstr_build_start(alloc_len, &q_ptr);
273 memcpy(val, lhs_data, lhs_len);
274 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000275 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
276 */
277
278 // code for non-qstr
279 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300280 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000281 memcpy(data, lhs_data, lhs_len);
282 memcpy(data + lhs_len, rhs_data, rhs_len);
283 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000284 }
285 break;
Damien George5fa93b62014-01-22 14:35:10 +0000286
Damien Georged17926d2014-03-30 13:35:08 +0100287 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000288 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300289 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000290 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700291 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000292 }
293 break;
Damien George5fa93b62014-01-22 14:35:10 +0000294
Damien Georged0a5bf32014-05-10 13:55:11 +0100295 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200296 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien Georged0a5bf32014-05-10 13:55:11 +0100297 return MP_OBJ_NOT_SUPPORTED;
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200298 }
299 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000300 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300301 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000302 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
303 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200304 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200305
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300306 case MP_BINARY_OP_MODULO: {
307 mp_obj_t *args;
308 uint n_args;
309 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
310 // TODO: Support tuple subclasses?
311 mp_obj_tuple_get(rhs_in, &n_args, &args);
312 } else {
313 args = &rhs_in;
314 n_args = 1;
315 }
316 return str_modulo_format(lhs_in, n_args, args);
317 }
318
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300319 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
320 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 +0100321 case MP_BINARY_OP_LESS:
322 case MP_BINARY_OP_LESS_EQUAL:
323 case MP_BINARY_OP_MORE:
324 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300325 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200326 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
327 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
328 }
Damiend99b0522013-12-21 18:17:45 +0000329 }
330
Damien Georgeea8d06c2014-04-17 23:19:36 +0100331 return MP_OBJ_NOT_SUPPORTED;
Damiend99b0522013-12-21 18:17:45 +0000332}
333
Damien George729f7b42014-04-17 22:10:53 +0100334STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
335 GET_STR_DATA_LEN(self_in, self_data, self_len);
336 if (value == MP_OBJ_SENTINEL) {
337 // load
338#if MICROPY_ENABLE_SLICE
339 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
340 machine_uint_t start, stop;
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300341 if (!mp_seq_get_fast_slice_indexes(self_len, index, &start, &stop)) {
Damien George729f7b42014-04-17 22:10:53 +0100342 assert(0);
343 }
344 return mp_obj_new_str(self_data + start, stop - start, false);
345 }
346#endif
347 mp_obj_type_t *type = mp_obj_get_type(self_in);
348 uint index_val = mp_get_index(type, self_len, index, false);
349 if (type == &mp_type_bytes) {
350 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
351 } else {
352 return mp_obj_new_str(self_data + index_val, 1, true);
353 }
354 } else {
355 return MP_OBJ_NOT_SUPPORTED;
356 }
357}
358
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200359STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Damien George5fa93b62014-01-22 14:35:10 +0000360 assert(MP_OBJ_IS_STR(self_in));
Damiend99b0522013-12-21 18:17:45 +0000361
Damien Georgefe8fb912014-01-02 16:36:09 +0000362 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000363 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000364
365 // process args
Damiend99b0522013-12-21 18:17:45 +0000366 uint seq_len;
367 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000368 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000369 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000370 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100371 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
372 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300373 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100374 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
375 }
376 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000377 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000378
379 // count required length
380 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000381 for (int i = 0; i < seq_len; i++) {
Damien George5fa93b62014-01-22 14:35:10 +0000382 if (!MP_OBJ_IS_STR(seq_items[i])) {
Damien Georgea157e4c2014-04-09 19:17:53 +0100383 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "join expected a list of str's"));
Damiend99b0522013-12-21 18:17:45 +0000384 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000385 if (i > 0) {
386 required_len += sep_len;
387 }
Damien George5fa93b62014-01-22 14:35:10 +0000388 GET_STR_LEN(seq_items[i], l);
389 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000390 }
391
392 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000393 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200394 mp_obj_t joined_str = mp_obj_str_builder_start(mp_obj_get_type(self_in), required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000395 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000396 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000397 memcpy(data, sep_str, sep_len);
398 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000399 }
Damien George5fa93b62014-01-22 14:35:10 +0000400 GET_STR_DATA_LEN(seq_items[i], s, l);
401 memcpy(data, s, l);
402 data += l;
Damiend99b0522013-12-21 18:17:45 +0000403 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000404
405 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000406 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000407}
408
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200409#define is_ws(c) ((c) == ' ' || (c) == '\t')
410
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200411STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Damien Georgedeed0872014-04-06 11:11:15 +0100412 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200413 mp_obj_t sep = mp_const_none;
414 if (n_args > 1) {
415 sep = args[1];
416 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100417 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200418 }
419 }
Damien Georgedeed0872014-04-06 11:11:15 +0100420
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200421 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000422 GET_STR_DATA_LEN(args[0], s, len);
423 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200424
Damien Georgedeed0872014-04-06 11:11:15 +0100425 if (sep == mp_const_none) {
426 // sep not given, so separate on whitespace
427
428 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000429 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100430 while (s < top && splits != 0) {
431 const byte *start = s;
432 while (s < top && !is_ws(*s)) s++;
433 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
434 if (s >= top) {
435 break;
436 }
437 while (s < top && is_ws(*s)) s++;
438 if (splits > 0) {
439 splits--;
440 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200441 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200442
Damien Georgedeed0872014-04-06 11:11:15 +0100443 if (s < top) {
444 mp_obj_list_append(res, mp_obj_new_str(s, top - s, false));
445 }
446
447 } else {
448 // sep given
449
450 uint sep_len;
451 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
452
453 if (sep_len == 0) {
454 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
455 }
456
457 for (;;) {
458 const byte *start = s;
459 for (;;) {
460 if (splits == 0 || s + sep_len > top) {
461 s = top;
462 break;
463 } else if (memcmp(s, sep_str, sep_len) == 0) {
464 break;
465 }
466 s++;
467 }
468 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
469 if (s >= top) {
470 break;
471 }
472 s += sep_len;
473 if (splits > 0) {
474 splits--;
475 }
476 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200477 }
478
479 return res;
480}
481
xbe3d9a39e2014-04-08 11:42:19 -0700482STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, machine_int_t direction, bool is_index) {
John R. Lentone8204912014-01-12 21:53:52 +0000483 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000484 assert(MP_OBJ_IS_STR(args[0]));
485 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000486
Damien George5fa93b62014-01-22 14:35:10 +0000487 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
488 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000489
xbec5538882014-03-16 17:58:35 -0700490 machine_uint_t start = 0;
491 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000492 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000493 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000494 }
495 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000496 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000497 }
498
xbe17a5a832014-03-23 23:31:58 -0700499 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000500 if (p == NULL) {
501 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700502 if (is_index) {
503 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
504 } else {
505 return MP_OBJ_NEW_SMALL_INT(-1);
506 }
Damien George23005372014-01-13 19:39:01 +0000507 } else {
508 // found
xbe17a5a832014-03-23 23:31:58 -0700509 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000510 }
John R. Lentone8204912014-01-12 21:53:52 +0000511}
512
xbe17a5a832014-03-23 23:31:58 -0700513STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700514 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700515}
516
517STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700518 return str_finder(n_args, args, -1, false);
519}
520
521STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
522 return str_finder(n_args, args, 1, true);
523}
524
525STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
526 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700527}
528
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200529// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200530STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200531 GET_STR_DATA_LEN(self_in, str, str_len);
532 GET_STR_DATA_LEN(arg, prefix, prefix_len);
533 if (prefix_len > str_len) {
534 return mp_const_false;
535 }
536 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
537}
538
Paul Sokolovsky88107842014-04-26 06:20:08 +0300539enum { LSTRIP, RSTRIP, STRIP };
540
541STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800542 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300543 assert(is_str_or_bytes(args[0]));
544 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000545
546 const byte *chars_to_del;
547 uint chars_to_del_len;
548 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800549
550 if (n_args == 1) {
551 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000552 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800553 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300554 if (mp_obj_get_type(args[1]) != self_type) {
555 arg_type_mixup();
556 }
Damien George5fa93b62014-01-22 14:35:10 +0000557 GET_STR_DATA_LEN(args[1], s, l);
558 chars_to_del = s;
559 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800560 }
561
Damien George5fa93b62014-01-22 14:35:10 +0000562 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800563
xbec5538882014-03-16 17:58:35 -0700564 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800565 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700566 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300567 machine_uint_t i = 0;
568 machine_int_t delta = 1;
569 if (type == RSTRIP) {
570 i = orig_str_len - 1;
571 delta = -1;
572 }
573 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700574 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800575 if (!first_good_char_pos_set) {
576 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300577 if (type == LSTRIP) {
578 last_good_char_pos = orig_str_len - 1;
579 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300580 } else if (type == RSTRIP) {
581 first_good_char_pos = 0;
582 last_good_char_pos = i;
583 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300584 }
xbe7b0f39f2014-01-08 14:23:45 -0800585 first_good_char_pos_set = true;
586 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300587 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800588 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300589 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800590 }
591
592 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000593 // string is all whitespace, return ''
594 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800595 }
596
597 assert(last_good_char_pos >= first_good_char_pos);
598 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700599 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300600 return str_new(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800601}
602
Paul Sokolovsky88107842014-04-26 06:20:08 +0300603STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
604 return str_uni_strip(STRIP, n_args, args);
605}
606
607STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
608 return str_uni_strip(LSTRIP, n_args, args);
609}
610
611STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
612 return str_uni_strip(RSTRIP, n_args, args);
613}
614
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700615// Takes an int arg, but only parses unsigned numbers, and only changes
616// *num if at least one digit was parsed.
617static int str_to_int(const char *str, int *num) {
618 const char *s = str;
619 if (unichar_isdigit(*s)) {
620 *num = 0;
621 do {
622 *num = *num * 10 + (*s - '0');
623 s++;
624 }
625 while (unichar_isdigit(*s));
626 }
627 return s - str;
628}
629
630static bool isalignment(char ch) {
631 return ch && strchr("<>=^", ch) != NULL;
632}
633
634static bool istype(char ch) {
635 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
636}
637
638static bool arg_looks_integer(mp_obj_t arg) {
639 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
640}
641
642static bool arg_looks_numeric(mp_obj_t arg) {
643 return arg_looks_integer(arg)
644#if MICROPY_ENABLE_FLOAT
645 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
646#endif
647 ;
648}
649
Dave Hylandsc4029e52014-04-07 11:19:51 -0700650static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700651#if MICROPY_ENABLE_FLOAT
652 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700653
654 // TODO: Needs a way to construct an mpz integer from a float
655
656 mp_small_int_t num = mp_obj_get_float(arg);
657 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700658 }
659#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700660 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700661}
662
Damien George897fe0c2014-04-15 22:03:55 +0100663mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000664 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000665
Damien George5fa93b62014-01-22 14:35:10 +0000666 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700667 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000668 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700669 pfenv_t pfenv_vstr;
670 pfenv_vstr.data = vstr;
671 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
672
Damien George5fa93b62014-01-22 14:35:10 +0000673 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700674 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000675 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700676 if (str < top && *str == '}') {
677 vstr_add_char(vstr, '}');
678 continue;
679 }
Damien Georgeea13f402014-04-05 18:32:08 +0100680 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700681 }
682 if (*str != '{') {
683 vstr_add_char(vstr, *str);
684 continue;
685 }
686
687 str++;
688 if (str < top && *str == '{') {
689 vstr_add_char(vstr, '{');
690 continue;
691 }
692
693 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
694
695 vstr_t *field_name = NULL;
696 char conversion = '\0';
697 vstr_t *format_spec = NULL;
698
699 if (str < top && *str != '}' && *str != '!' && *str != ':') {
700 field_name = vstr_new();
701 while (str < top && *str != '}' && *str != '!' && *str != ':') {
702 vstr_add_char(field_name, *str++);
703 }
704 vstr_add_char(field_name, '\0');
705 }
706
707 // conversion ::= "r" | "s"
708
709 if (str < top && *str == '!') {
710 str++;
711 if (str < top && (*str == 'r' || *str == 's')) {
712 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200713 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100714 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 -0700715 }
716 }
717
718 if (str < top && *str == ':') {
719 str++;
720 // {:} is the same as {}, which is the same as {!s}
721 // This makes a difference when passing in a True or False
722 // '{}'.format(True) returns 'True'
723 // '{:d}'.format(True) returns '1'
724 // So we treat {:} as {} and this later gets treated to be {!s}
725 if (*str != '}') {
726 format_spec = vstr_new();
727 while (str < top && *str != '}') {
728 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000729 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700730 vstr_add_char(format_spec, '\0');
731 }
732 }
733 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100734 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700735 }
736 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100737 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700738 }
739
740 mp_obj_t arg = mp_const_none;
741
742 if (field_name) {
743 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100744 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700745 }
Damien George3bb8bd82014-04-14 21:20:30 +0100746 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700747 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100748 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700749 }
750 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100751 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700752 }
753 arg = args[index + 1];
754 arg_i = -1;
755 vstr_free(field_name);
756 field_name = NULL;
757 } else {
758 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100759 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700760 }
761 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100762 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700763 }
764 arg = args[arg_i + 1];
765 arg_i++;
766 }
767 if (!format_spec && !conversion) {
768 conversion = 's';
769 }
770 if (conversion) {
771 mp_print_kind_t print_kind;
772 if (conversion == 's') {
773 print_kind = PRINT_STR;
774 } else if (conversion == 'r') {
775 print_kind = PRINT_REPR;
776 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100777 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700778 }
779 vstr_t *arg_vstr = vstr_new();
780 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
781 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
782 vstr_free(arg_vstr);
783 }
784
785 char sign = '\0';
786 char fill = '\0';
787 char align = '\0';
788 int width = -1;
789 int precision = -1;
790 char type = '\0';
791 int flags = 0;
792
793 if (format_spec) {
794 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
795 //
796 // [[fill]align][sign][#][0][width][,][.precision][type]
797 // fill ::= <any character>
798 // align ::= "<" | ">" | "=" | "^"
799 // sign ::= "+" | "-" | " "
800 // width ::= integer
801 // precision ::= integer
802 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
803
804 const char *s = vstr_str(format_spec);
805 if (isalignment(*s)) {
806 align = *s++;
807 } else if (*s && isalignment(s[1])) {
808 fill = *s++;
809 align = *s++;
810 }
811 if (*s == '+' || *s == '-' || *s == ' ') {
812 if (*s == '+') {
813 flags |= PF_FLAG_SHOW_SIGN;
814 } else if (*s == ' ') {
815 flags |= PF_FLAG_SPACE_SIGN;
816 }
817 sign = *s++;
818 }
819 if (*s == '#') {
820 flags |= PF_FLAG_SHOW_PREFIX;
821 s++;
822 }
823 if (*s == '0') {
824 if (!align) {
825 align = '=';
826 }
827 if (!fill) {
828 fill = '0';
829 }
830 }
831 s += str_to_int(s, &width);
832 if (*s == ',') {
833 flags |= PF_FLAG_SHOW_COMMA;
834 s++;
835 }
836 if (*s == '.') {
837 s++;
838 s += str_to_int(s, &precision);
839 }
840 if (istype(*s)) {
841 type = *s++;
842 }
843 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100844 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700845 }
846 vstr_free(format_spec);
847 format_spec = NULL;
848 }
849 if (!align) {
850 if (arg_looks_numeric(arg)) {
851 align = '>';
852 } else {
853 align = '<';
854 }
855 }
856 if (!fill) {
857 fill = ' ';
858 }
859
860 if (sign) {
861 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100862 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700863 }
864 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100865 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000866 }
867 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700868 sign = '-';
869 }
870
871 switch (align) {
872 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
873 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
874 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
875 }
876
877 if (arg_looks_integer(arg)) {
878 switch (type) {
879 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100880 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700881 continue;
882
883 case 'c':
884 {
885 char ch = mp_obj_get_int(arg);
886 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
887 continue;
888 }
889
890 case '\0': // No explicit format type implies 'd'
891 case 'n': // I don't think we support locales in uPy so use 'd'
892 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100893 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700894 continue;
895
896 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700897 if (flags & PF_FLAG_SHOW_PREFIX) {
898 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
899 }
900
Damien Georgea12a0f72014-04-08 01:29:53 +0100901 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902 continue;
903
904 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100905 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700906 continue;
907
908 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100909 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700910 continue;
911
912 case 'e':
913 case 'E':
914 case 'f':
915 case 'F':
916 case 'g':
917 case 'G':
918 case '%':
919 // The floating point formatters all work with anything that
920 // looks like an integer
921 break;
922
923 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100924 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700925 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
926 }
Damien Georgec322c5f2014-04-02 20:04:15 +0100927 }
Damien George70f33cd2014-04-02 17:06:05 +0100928
Dave Hylands22fe4d72014-04-02 12:07:31 -0700929 // NOTE: no else here. We need the e, f, g etc formats for integer
930 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +0100931 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700932 if (!type) {
933
934 // Even though the docs say that an unspecified type is the same
935 // as 'g', there is one subtle difference, when the exponent
936 // is one less than the precision.
937 //
938 // '{:10.1}'.format(0.0) ==> '0e+00'
939 // '{:10.1g}'.format(0.0) ==> '0'
940 //
941 // TODO: Figure out how to deal with this.
942 //
943 // A proper solution would involve adding a special flag
944 // or something to format_float, and create a format_double
945 // to deal with doubles. In order to fix this when using
946 // sprintf, we'd need to use the e format and tweak the
947 // returned result to strip trailing zeros like the g format
948 // does.
949 //
950 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
951 // but with 1.e2 you get 1e+02 and 1.00e+02
952 //
953 // Stripping the trailing 0's (like g) does would make the
954 // e format give us the right format.
955 //
956 // CPython sources say:
957 // Omitted type specifier. Behaves in the same way as repr(x)
958 // and str(x) if no precision is given, else like 'g', but with
959 // at least one digit after the decimal point. */
960
961 type = 'g';
962 }
963 if (type == 'n') {
964 type = 'g';
965 }
966
967 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
968 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +0100969#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700970 case 'e':
971 case 'E':
972 case 'f':
973 case 'F':
974 case 'g':
975 case 'G':
976 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
977 break;
978
979 case '%':
980 flags |= PF_FLAG_ADD_PERCENT;
981 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
982 break;
Damien Georgec322c5f2014-04-02 20:04:15 +0100983#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700984
985 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100986 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700987 "Unknown format code '%c' for object of type 'float'",
988 type, mp_obj_get_type_str(arg)));
989 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700990 } else {
Damien George70f33cd2014-04-02 17:06:05 +0100991 // arg doesn't look like a number
992
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700993 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +0100994 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700995 }
Damien George70f33cd2014-04-02 17:06:05 +0100996
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700997 switch (type) {
998 case '\0':
999 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1000 break;
1001
1002 case 's':
1003 {
1004 uint len;
1005 const char *s = mp_obj_str_get_data(arg, &len);
1006 if (precision < 0) {
1007 precision = len;
1008 }
1009 if (len > precision) {
1010 len = precision;
1011 }
1012 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1013 break;
1014 }
1015
1016 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001017 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001018 "Unknown format code '%c' for object of type 'str'",
1019 type, mp_obj_get_type_str(arg)));
1020 }
Damiend99b0522013-12-21 18:17:45 +00001021 }
1022 }
1023
Damien George5fa93b62014-01-22 14:35:10 +00001024 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1025 vstr_free(vstr);
1026 return s;
Damiend99b0522013-12-21 18:17:45 +00001027}
1028
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001029STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
1030 assert(MP_OBJ_IS_STR(pattern));
1031
1032 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001033 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001034 int arg_i = 0;
1035 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001036 pfenv_t pfenv_vstr;
1037 pfenv_vstr.data = vstr;
1038 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1039
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001040 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -07001041 if (*str != '%') {
1042 vstr_add_char(vstr, *str);
1043 continue;
1044 }
1045 if (++str >= top) {
1046 break;
1047 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001048 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001049 vstr_add_char(vstr, '%');
1050 continue;
1051 }
1052 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001053 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -07001054 }
1055 int flags = 0;
1056 char fill = ' ';
1057 bool alt = false;
1058 while (str < top) {
1059 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1060 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1061 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1062 else if (*str == '#') alt = true;
1063 else if (*str == '0') {
1064 flags |= PF_FLAG_PAD_AFTER_SIGN;
1065 fill = '0';
1066 } else break;
1067 str++;
1068 }
1069 // parse width, if it exists
1070 int width = 0;
1071 if (str < top) {
1072 if (*str == '*') {
1073 width = mp_obj_get_int(args[arg_i++]);
1074 str++;
1075 } else {
1076 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1077 width = width * 10 + *str - '0';
1078 }
1079 }
1080 }
1081 int prec = -1;
1082 if (str < top && *str == '.') {
1083 if (++str < top) {
1084 if (*str == '*') {
1085 prec = mp_obj_get_int(args[arg_i++]);
1086 str++;
1087 } else {
1088 prec = 0;
1089 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1090 prec = prec * 10 + *str - '0';
1091 }
1092 }
1093 }
1094 }
1095
1096 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001097 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001098 }
1099 mp_obj_t arg = args[arg_i];
1100 switch (*str) {
1101 case 'c':
1102 if (MP_OBJ_IS_STR(arg)) {
1103 uint len;
1104 const char *s = mp_obj_str_get_data(arg, &len);
1105 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001106 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001107 break;
1108 }
1109 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1110 break;
1111 }
1112 if (arg_looks_integer(arg)) {
1113 char ch = mp_obj_get_int(arg);
1114 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1115 break;
1116 }
1117#if MICROPY_ENABLE_FLOAT
1118 // This is what CPython reports, so we report the same.
1119 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001120 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001121
1122 }
1123#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001124 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001125 break;
1126
1127 case 'd':
1128 case 'i':
1129 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001130 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001131 break;
1132
1133#if MICROPY_ENABLE_FLOAT
1134 case 'e':
1135 case 'E':
1136 case 'f':
1137 case 'F':
1138 case 'g':
1139 case 'G':
1140 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1141 break;
1142#endif
1143
1144 case 'o':
1145 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001146 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001147 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001148 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001149 break;
1150
1151 case 'r':
1152 case 's':
1153 {
1154 vstr_t *arg_vstr = vstr_new();
1155 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1156 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1157 uint len = vstr_len(arg_vstr);
1158 if (prec < 0) {
1159 prec = len;
1160 }
1161 if (len > prec) {
1162 len = prec;
1163 }
1164 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1165 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001166 break;
1167 }
Dave Hylands6756a372014-04-02 11:42:39 -07001168
1169 case 'x':
1170 if (alt) {
1171 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001172 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001173 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001174 break;
1175
1176 case 'X':
1177 if (alt) {
1178 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001179 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001180 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001181 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001182
Dave Hylands6756a372014-04-02 11:42:39 -07001183 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001184 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001185 "unsupported format character '%c' (0x%x) at index %d",
1186 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001187 }
Dave Hylands6756a372014-04-02 11:42:39 -07001188 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001189 }
1190
1191 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001192 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001193 }
1194
1195 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1196 vstr_free(vstr);
1197 return s;
1198}
1199
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001200STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001201 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001202
Damien Georgeff715422014-04-07 00:39:13 +01001203 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001204 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001205 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001206 if (max_rep == 0) {
1207 return args[0];
1208 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001209 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001210 }
xbe480c15a2014-01-30 22:17:30 -08001211 }
Damien George94f68302014-01-31 23:45:12 +00001212
xbe729be9b2014-04-07 14:46:39 -07001213 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001214
Damien Georgeff715422014-04-07 00:39:13 +01001215 // check argument types
1216
1217 if (!MP_OBJ_IS_STR(args[1])) {
1218 bad_implicit_conversion(args[1]);
1219 }
1220
1221 if (!MP_OBJ_IS_STR(args[2])) {
1222 bad_implicit_conversion(args[2]);
1223 }
1224
1225 // extract string data
1226
xbe480c15a2014-01-30 22:17:30 -08001227 GET_STR_DATA_LEN(args[0], str, str_len);
1228 GET_STR_DATA_LEN(args[1], old, old_len);
1229 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001230
1231 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001232 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001233 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001234 }
1235
Damien George94f68302014-01-31 23:45:12 +00001236 // data for the replaced string
1237 byte *data = NULL;
1238 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001239
Damien George94f68302014-01-31 23:45:12 +00001240 // do 2 passes over the string:
1241 // first pass computes the required length of the replaced string
1242 // second pass does the replacements
1243 for (;;) {
1244 machine_uint_t replaced_str_index = 0;
1245 machine_uint_t num_replacements_done = 0;
1246 const byte *old_occurrence;
1247 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001248 machine_uint_t str_len_remain = str_len;
1249 if (old_len == 0) {
1250 // if old_str is empty, copy new_str to start of replaced string
1251 // copy the replacement string
1252 if (data != NULL) {
1253 memcpy(data, new, new_len);
1254 }
1255 replaced_str_index += new_len;
1256 num_replacements_done++;
1257 }
1258 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1259 if (old_len == 0) {
1260 old_occurrence += 1;
1261 }
Damien George94f68302014-01-31 23:45:12 +00001262 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1263 if (data != NULL) {
1264 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1265 }
1266 replaced_str_index += old_occurrence - offset_ptr;
1267 // copy the replacement string
1268 if (data != NULL) {
1269 memcpy(data + replaced_str_index, new, new_len);
1270 }
1271 replaced_str_index += new_len;
1272 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001273 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001274 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001275 }
1276
1277 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1278 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001279 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001280 }
Damien Georgeff715422014-04-07 00:39:13 +01001281 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001282
1283 if (data == NULL) {
1284 // first pass
1285 if (num_replacements_done == 0) {
1286 // no substr found, return original string
1287 return args[0];
1288 } else {
1289 // substr found, allocate new string
1290 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001291 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001292 }
1293 } else {
1294 // second pass, we are done
1295 break;
1296 }
xbe480c15a2014-01-30 22:17:30 -08001297 }
Damien George94f68302014-01-31 23:45:12 +00001298
xbe480c15a2014-01-30 22:17:30 -08001299 return mp_obj_str_builder_end(replaced_str);
1300}
1301
xbe9e1e8cd2014-03-12 22:57:16 -07001302STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1303 assert(2 <= n_args && n_args <= 4);
1304 assert(MP_OBJ_IS_STR(args[0]));
1305 assert(MP_OBJ_IS_STR(args[1]));
1306
1307 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1308 GET_STR_DATA_LEN(args[1], needle, needle_len);
1309
Damien George536dde22014-03-13 22:07:55 +00001310 machine_uint_t start = 0;
1311 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001312 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001313 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001314 }
1315 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001316 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001317 }
1318
Damien George536dde22014-03-13 22:07:55 +00001319 // if needle_len is zero then we count each gap between characters as an occurrence
1320 if (needle_len == 0) {
1321 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001322 }
1323
Damien George536dde22014-03-13 22:07:55 +00001324 // count the occurrences
1325 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001326 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1327 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1328 num_occurrences++;
1329 haystack_index += needle_len - 1;
1330 }
xbe9e1e8cd2014-03-12 22:57:16 -07001331 }
1332
1333 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1334}
1335
Damien Georgeb035db32014-03-21 20:39:40 +00001336STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, machine_int_t direction) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001337 if (!is_str_or_bytes(self_in)) {
1338 assert(0);
1339 }
1340 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1341 if (self_type != mp_obj_get_type(arg)) {
1342 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001343 }
Damien Georgeb035db32014-03-21 20:39:40 +00001344
xbe613a8e32014-03-18 00:06:29 -07001345 GET_STR_DATA_LEN(self_in, str, str_len);
1346 GET_STR_DATA_LEN(arg, sep, sep_len);
1347
1348 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001349 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001350 }
Damien Georgeb035db32014-03-21 20:39:40 +00001351
1352 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1353
1354 if (direction > 0) {
1355 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001356 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001357 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001358 }
xbe613a8e32014-03-18 00:06:29 -07001359
xbe17a5a832014-03-23 23:31:58 -07001360 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1361 if (position_ptr != NULL) {
1362 machine_uint_t position = position_ptr - str;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001363 result[0] = str_new(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001364 result[1] = arg;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001365 result[2] = str_new(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001366 }
Damien Georgeb035db32014-03-21 20:39:40 +00001367
xbe0a6894c2014-03-21 01:12:26 -07001368 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001369}
1370
Damien Georgeb035db32014-03-21 20:39:40 +00001371STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1372 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001373}
xbe4504ea82014-03-19 00:46:14 -07001374
Damien Georgeb035db32014-03-21 20:39:40 +00001375STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1376 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001377}
1378
Paul Sokolovsky69135212014-05-10 19:47:41 +03001379enum { CASE_UPPER, CASE_LOWER };
1380
1381// Supposedly not too critical operations, so optimize for code size
1382STATIC mp_obj_t str_caseconv(int op, mp_obj_t self_in) {
1383 GET_STR_DATA_LEN(self_in, self_data, self_len);
1384 byte *data;
1385 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1386 for (int i = 0; i < self_len; i++) {
1387 if (op == CASE_UPPER) {
1388 *data++ = unichar_toupper(*self_data++);
1389 } else {
1390 *data++ = unichar_tolower(*self_data++);
1391 }
1392 }
1393 *data = 0;
1394 return mp_obj_str_builder_end(s);
1395}
1396
1397STATIC mp_obj_t str_lower(mp_obj_t self_in) {
1398 return str_caseconv(CASE_LOWER, self_in);
1399}
1400
1401STATIC mp_obj_t str_upper(mp_obj_t self_in) {
1402 return str_caseconv(CASE_UPPER, self_in);
1403}
1404
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001405#if MICROPY_CPYTHON_COMPAT
1406// These methods are superfluous in the presense of str() and bytes()
1407// constructors.
1408// TODO: should accept kwargs too
1409STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1410 mp_obj_t new_args[2];
1411 if (n_args == 1) {
1412 new_args[0] = args[0];
1413 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1414 args = new_args;
1415 n_args++;
1416 }
1417 return str_make_new(NULL, n_args, 0, args);
1418}
1419
1420// TODO: should accept kwargs too
1421STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1422 mp_obj_t new_args[2];
1423 if (n_args == 1) {
1424 new_args[0] = args[0];
1425 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1426 args = new_args;
1427 n_args++;
1428 }
1429 return bytes_make_new(NULL, n_args, 0, args);
1430}
1431#endif
1432
Damien George57a4b4f2014-04-18 22:29:21 +01001433STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1434 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001435 GET_STR_DATA_LEN(self_in, str_data, str_len);
1436 bufinfo->buf = (void*)str_data;
1437 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001438 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001439 return 0;
1440 } else {
1441 // can't write to a string
1442 bufinfo->buf = NULL;
1443 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001444 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001445 return 1;
1446 }
1447}
1448
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001449#if MICROPY_CPYTHON_COMPAT
1450STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1451STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1452#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001453STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001454STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001455STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1456STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001457STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1458STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1459STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1460STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001461STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1462STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001463STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001464STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001465STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001466STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001467STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001468STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1469STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Damiend99b0522013-12-21 18:17:45 +00001470
Damien George9b196cd2014-03-26 21:47:19 +00001471STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001472#if MICROPY_CPYTHON_COMPAT
1473 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1474 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1475#endif
Damien George9b196cd2014-03-26 21:47:19 +00001476 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1477 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001478 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1479 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001480 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1481 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
1482 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1483 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001484 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1485 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001486 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1487 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1488 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1489 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1490 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001491 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1492 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001493};
Damien George97209d32014-01-07 15:58:30 +00001494
Damien George9b196cd2014-03-26 21:47:19 +00001495STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1496
Damien George3e1a5c12014-03-29 13:43:38 +00001497const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001498 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001499 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001500 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001501 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001502 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001503 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001504 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001505 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001506 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001507};
1508
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001509// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001510const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001511 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001512 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001513 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001514 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001515 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001516 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001517 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001518 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001519 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001520};
1521
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001522// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001523STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001524const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1525
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001526mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001527 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001528 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001529 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001530 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001531 byte *p = m_new(byte, len + 1);
1532 o->data = p;
1533 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001534 return o;
1535}
1536
Damien George5fa93b62014-01-22 14:35:10 +00001537mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001538 mp_obj_str_t *o = o_in;
1539 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001540 byte *p = (byte*)o->data;
1541 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001542 return o;
1543}
1544
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001545STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001546 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001547 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001548 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001549 if (data) {
1550 o->hash = qstr_compute_hash(data, len);
1551 byte *p = m_new(byte, len + 1);
1552 o->data = p;
1553 memcpy(p, data, len * sizeof(byte));
1554 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1555 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001556 return o;
1557}
1558
Damien George5fa93b62014-01-22 14:35:10 +00001559mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1560 qstr q = qstr_find_strn(data, len);
1561 if (q != MP_QSTR_NULL) {
1562 // qstr with this data already exists
1563 return MP_OBJ_NEW_QSTR(q);
1564 } else if (make_qstr_if_not_already) {
1565 // no existing qstr, make a new one
1566 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1567 } else {
1568 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001569 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001570 }
Damien George5fa93b62014-01-22 14:35:10 +00001571}
1572
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001573mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001574 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001575}
1576
Damien George5fa93b62014-01-22 14:35:10 +00001577bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1578 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1579 return s1 == s2;
1580 } else {
1581 GET_STR_HASH(s1, h1);
1582 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001583 // If any of hashes is 0, it means it's not valid
1584 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001585 return false;
1586 }
1587 GET_STR_DATA_LEN(s1, d1, l1);
1588 GET_STR_DATA_LEN(s2, d2, l2);
1589 if (l1 != l2) {
1590 return false;
1591 }
Damien George1e708fe2014-01-23 18:27:51 +00001592 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001593 }
Damien George5fa93b62014-01-22 14:35:10 +00001594}
1595
Damien Georgedeed0872014-04-06 11:11:15 +01001596STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001597 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 +00001598}
1599
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001600STATIC void arg_type_mixup() {
1601 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1602}
1603
Damien George5fa93b62014-01-22 14:35:10 +00001604uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001605 // TODO: This has too big overhead for hash accessor
1606 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001607 GET_STR_HASH(self_in, h);
1608 return h;
1609 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001610 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001611 }
1612}
1613
1614uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001615 // TODO This has a double check for the type, one in obj.c and one here
1616 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001617 GET_STR_LEN(self_in, l);
1618 return l;
1619 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001620 bad_implicit_conversion(self_in);
1621 }
1622}
1623
1624// use this if you will anyway convert the string to a qstr
1625// will be more efficient for the case where it's already a qstr
1626qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1627 if (MP_OBJ_IS_QSTR(self_in)) {
1628 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001629 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001630 mp_obj_str_t *self = self_in;
1631 return qstr_from_strn((char*)self->data, self->len);
1632 } else {
1633 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001634 }
1635}
1636
1637// only use this function if you need the str data to be zero terminated
1638// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1639const char *mp_obj_str_get_str(mp_obj_t self_in) {
1640 if (MP_OBJ_IS_STR(self_in)) {
1641 GET_STR_DATA_LEN(self_in, s, l);
1642 (void)l; // len unused
1643 return (const char*)s;
1644 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001645 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001646 }
1647}
1648
Damien George698ec212014-02-08 18:17:23 +00001649const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Damien George5fa93b62014-01-22 14:35:10 +00001650 if (MP_OBJ_IS_STR(self_in)) {
1651 GET_STR_DATA_LEN(self_in, s, l);
1652 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001653 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001654 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001655 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001656 }
Damiend99b0522013-12-21 18:17:45 +00001657}
xyb8cfc9f02014-01-05 18:47:51 +08001658
1659/******************************************************************************/
1660/* str iterator */
1661
1662typedef struct _mp_obj_str_it_t {
1663 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001664 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001665 machine_uint_t cur;
1666} mp_obj_str_it_t;
1667
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001668STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001669 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001670 GET_STR_DATA_LEN(self->str, str, len);
1671 if (self->cur < len) {
1672 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001673 self->cur += 1;
1674 return o_out;
1675 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001676 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001677 }
1678}
1679
Damien George3e1a5c12014-03-29 13:43:38 +00001680STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001681 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001682 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001683 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001684 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001685};
1686
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001687STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001688 mp_obj_str_it_t *self = self_in;
1689 GET_STR_DATA_LEN(self->str, str, len);
1690 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001691 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001692 self->cur += 1;
1693 return o_out;
1694 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001695 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001696 }
1697}
1698
Damien George3e1a5c12014-03-29 13:43:38 +00001699STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001700 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001701 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001702 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001703 .iternext = bytes_it_iternext,
1704};
1705
1706mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001707 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001708 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001709 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001710 o->cur = 0;
1711 return o;
1712}
1713
1714mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1715 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001716 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001717 o->str = str;
1718 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001719 return o;
1720}