blob: d062f05f8ca5f27f198805911f15302ca55dc533 [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) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300360 assert(is_str_or_bytes(self_in));
361 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000362
Damien Georgefe8fb912014-01-02 16:36:09 +0000363 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000364 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000365
366 // process args
Damiend99b0522013-12-21 18:17:45 +0000367 uint seq_len;
368 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000369 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000370 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000371 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100372 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
373 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300374 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100375 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
376 }
377 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000378 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000379
380 // count required length
381 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000382 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300383 if (mp_obj_get_type(seq_items[i]) != self_type) {
384 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
385 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000386 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000387 if (i > 0) {
388 required_len += sep_len;
389 }
Damien George5fa93b62014-01-22 14:35:10 +0000390 GET_STR_LEN(seq_items[i], l);
391 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000392 }
393
394 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000395 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300396 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000397 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000398 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000399 memcpy(data, sep_str, sep_len);
400 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000401 }
Damien George5fa93b62014-01-22 14:35:10 +0000402 GET_STR_DATA_LEN(seq_items[i], s, l);
403 memcpy(data, s, l);
404 data += l;
Damiend99b0522013-12-21 18:17:45 +0000405 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000406
407 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000408 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000409}
410
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200411#define is_ws(c) ((c) == ' ' || (c) == '\t')
412
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200413STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300414 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100415 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200416 mp_obj_t sep = mp_const_none;
417 if (n_args > 1) {
418 sep = args[1];
419 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100420 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200421 }
422 }
Damien Georgedeed0872014-04-06 11:11:15 +0100423
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200424 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000425 GET_STR_DATA_LEN(args[0], s, len);
426 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200427
Damien Georgedeed0872014-04-06 11:11:15 +0100428 if (sep == mp_const_none) {
429 // sep not given, so separate on whitespace
430
431 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000432 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100433 while (s < top && splits != 0) {
434 const byte *start = s;
435 while (s < top && !is_ws(*s)) s++;
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300436 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100437 if (s >= top) {
438 break;
439 }
440 while (s < top && is_ws(*s)) s++;
441 if (splits > 0) {
442 splits--;
443 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200444 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200445
Damien Georgedeed0872014-04-06 11:11:15 +0100446 if (s < top) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300447 mp_obj_list_append(res, str_new(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100448 }
449
450 } else {
451 // sep given
452
453 uint sep_len;
454 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
455
456 if (sep_len == 0) {
457 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
458 }
459
460 for (;;) {
461 const byte *start = s;
462 for (;;) {
463 if (splits == 0 || s + sep_len > top) {
464 s = top;
465 break;
466 } else if (memcmp(s, sep_str, sep_len) == 0) {
467 break;
468 }
469 s++;
470 }
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300471 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100472 if (s >= top) {
473 break;
474 }
475 s += sep_len;
476 if (splits > 0) {
477 splits--;
478 }
479 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200480 }
481
482 return res;
483}
484
xbe3d9a39e2014-04-08 11:42:19 -0700485STATIC 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 +0000486 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000487 assert(MP_OBJ_IS_STR(args[0]));
488 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000489
Damien George5fa93b62014-01-22 14:35:10 +0000490 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
491 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000492
xbec5538882014-03-16 17:58:35 -0700493 machine_uint_t start = 0;
494 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000495 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000496 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000497 }
498 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000499 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000500 }
501
xbe17a5a832014-03-23 23:31:58 -0700502 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000503 if (p == NULL) {
504 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700505 if (is_index) {
506 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
507 } else {
508 return MP_OBJ_NEW_SMALL_INT(-1);
509 }
Damien George23005372014-01-13 19:39:01 +0000510 } else {
511 // found
xbe17a5a832014-03-23 23:31:58 -0700512 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000513 }
John R. Lentone8204912014-01-12 21:53:52 +0000514}
515
xbe17a5a832014-03-23 23:31:58 -0700516STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700517 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700518}
519
520STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700521 return str_finder(n_args, args, -1, false);
522}
523
524STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
525 return str_finder(n_args, args, 1, true);
526}
527
528STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
529 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700530}
531
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200532// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200533STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200534 GET_STR_DATA_LEN(self_in, str, str_len);
535 GET_STR_DATA_LEN(arg, prefix, prefix_len);
536 if (prefix_len > str_len) {
537 return mp_const_false;
538 }
539 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
540}
541
Paul Sokolovsky88107842014-04-26 06:20:08 +0300542enum { LSTRIP, RSTRIP, STRIP };
543
544STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800545 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300546 assert(is_str_or_bytes(args[0]));
547 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000548
549 const byte *chars_to_del;
550 uint chars_to_del_len;
551 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800552
553 if (n_args == 1) {
554 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000555 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800556 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300557 if (mp_obj_get_type(args[1]) != self_type) {
558 arg_type_mixup();
559 }
Damien George5fa93b62014-01-22 14:35:10 +0000560 GET_STR_DATA_LEN(args[1], s, l);
561 chars_to_del = s;
562 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800563 }
564
Damien George5fa93b62014-01-22 14:35:10 +0000565 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800566
xbec5538882014-03-16 17:58:35 -0700567 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800568 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700569 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300570 machine_uint_t i = 0;
571 machine_int_t delta = 1;
572 if (type == RSTRIP) {
573 i = orig_str_len - 1;
574 delta = -1;
575 }
576 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700577 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800578 if (!first_good_char_pos_set) {
579 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300580 if (type == LSTRIP) {
581 last_good_char_pos = orig_str_len - 1;
582 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300583 } else if (type == RSTRIP) {
584 first_good_char_pos = 0;
585 last_good_char_pos = i;
586 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300587 }
xbe7b0f39f2014-01-08 14:23:45 -0800588 first_good_char_pos_set = true;
589 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300590 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800591 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300592 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800593 }
594
595 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000596 // string is all whitespace, return ''
597 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800598 }
599
600 assert(last_good_char_pos >= first_good_char_pos);
601 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700602 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300603 return str_new(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800604}
605
Paul Sokolovsky88107842014-04-26 06:20:08 +0300606STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
607 return str_uni_strip(STRIP, n_args, args);
608}
609
610STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
611 return str_uni_strip(LSTRIP, n_args, args);
612}
613
614STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
615 return str_uni_strip(RSTRIP, n_args, args);
616}
617
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700618// Takes an int arg, but only parses unsigned numbers, and only changes
619// *num if at least one digit was parsed.
620static int str_to_int(const char *str, int *num) {
621 const char *s = str;
622 if (unichar_isdigit(*s)) {
623 *num = 0;
624 do {
625 *num = *num * 10 + (*s - '0');
626 s++;
627 }
628 while (unichar_isdigit(*s));
629 }
630 return s - str;
631}
632
633static bool isalignment(char ch) {
634 return ch && strchr("<>=^", ch) != NULL;
635}
636
637static bool istype(char ch) {
638 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
639}
640
641static bool arg_looks_integer(mp_obj_t arg) {
642 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
643}
644
645static bool arg_looks_numeric(mp_obj_t arg) {
646 return arg_looks_integer(arg)
647#if MICROPY_ENABLE_FLOAT
648 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
649#endif
650 ;
651}
652
Dave Hylandsc4029e52014-04-07 11:19:51 -0700653static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700654#if MICROPY_ENABLE_FLOAT
655 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700656
657 // TODO: Needs a way to construct an mpz integer from a float
658
659 mp_small_int_t num = mp_obj_get_float(arg);
660 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700661 }
662#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700663 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700664}
665
Damien George897fe0c2014-04-15 22:03:55 +0100666mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000667 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000668
Damien George5fa93b62014-01-22 14:35:10 +0000669 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700670 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000671 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700672 pfenv_t pfenv_vstr;
673 pfenv_vstr.data = vstr;
674 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
675
Damien George5fa93b62014-01-22 14:35:10 +0000676 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700677 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000678 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700679 if (str < top && *str == '}') {
680 vstr_add_char(vstr, '}');
681 continue;
682 }
Damien Georgeea13f402014-04-05 18:32:08 +0100683 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700684 }
685 if (*str != '{') {
686 vstr_add_char(vstr, *str);
687 continue;
688 }
689
690 str++;
691 if (str < top && *str == '{') {
692 vstr_add_char(vstr, '{');
693 continue;
694 }
695
696 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
697
698 vstr_t *field_name = NULL;
699 char conversion = '\0';
700 vstr_t *format_spec = NULL;
701
702 if (str < top && *str != '}' && *str != '!' && *str != ':') {
703 field_name = vstr_new();
704 while (str < top && *str != '}' && *str != '!' && *str != ':') {
705 vstr_add_char(field_name, *str++);
706 }
707 vstr_add_char(field_name, '\0');
708 }
709
710 // conversion ::= "r" | "s"
711
712 if (str < top && *str == '!') {
713 str++;
714 if (str < top && (*str == 'r' || *str == 's')) {
715 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200716 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100717 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 -0700718 }
719 }
720
721 if (str < top && *str == ':') {
722 str++;
723 // {:} is the same as {}, which is the same as {!s}
724 // This makes a difference when passing in a True or False
725 // '{}'.format(True) returns 'True'
726 // '{:d}'.format(True) returns '1'
727 // So we treat {:} as {} and this later gets treated to be {!s}
728 if (*str != '}') {
729 format_spec = vstr_new();
730 while (str < top && *str != '}') {
731 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000732 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700733 vstr_add_char(format_spec, '\0');
734 }
735 }
736 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100737 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700738 }
739 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100740 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700741 }
742
743 mp_obj_t arg = mp_const_none;
744
745 if (field_name) {
746 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100747 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 -0700748 }
Damien George3bb8bd82014-04-14 21:20:30 +0100749 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700750 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100751 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700752 }
753 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100754 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700755 }
756 arg = args[index + 1];
757 arg_i = -1;
758 vstr_free(field_name);
759 field_name = NULL;
760 } else {
761 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100762 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 -0700763 }
764 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100765 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700766 }
767 arg = args[arg_i + 1];
768 arg_i++;
769 }
770 if (!format_spec && !conversion) {
771 conversion = 's';
772 }
773 if (conversion) {
774 mp_print_kind_t print_kind;
775 if (conversion == 's') {
776 print_kind = PRINT_STR;
777 } else if (conversion == 'r') {
778 print_kind = PRINT_REPR;
779 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100780 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700781 }
782 vstr_t *arg_vstr = vstr_new();
783 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
784 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
785 vstr_free(arg_vstr);
786 }
787
788 char sign = '\0';
789 char fill = '\0';
790 char align = '\0';
791 int width = -1;
792 int precision = -1;
793 char type = '\0';
794 int flags = 0;
795
796 if (format_spec) {
797 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
798 //
799 // [[fill]align][sign][#][0][width][,][.precision][type]
800 // fill ::= <any character>
801 // align ::= "<" | ">" | "=" | "^"
802 // sign ::= "+" | "-" | " "
803 // width ::= integer
804 // precision ::= integer
805 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
806
807 const char *s = vstr_str(format_spec);
808 if (isalignment(*s)) {
809 align = *s++;
810 } else if (*s && isalignment(s[1])) {
811 fill = *s++;
812 align = *s++;
813 }
814 if (*s == '+' || *s == '-' || *s == ' ') {
815 if (*s == '+') {
816 flags |= PF_FLAG_SHOW_SIGN;
817 } else if (*s == ' ') {
818 flags |= PF_FLAG_SPACE_SIGN;
819 }
820 sign = *s++;
821 }
822 if (*s == '#') {
823 flags |= PF_FLAG_SHOW_PREFIX;
824 s++;
825 }
826 if (*s == '0') {
827 if (!align) {
828 align = '=';
829 }
830 if (!fill) {
831 fill = '0';
832 }
833 }
834 s += str_to_int(s, &width);
835 if (*s == ',') {
836 flags |= PF_FLAG_SHOW_COMMA;
837 s++;
838 }
839 if (*s == '.') {
840 s++;
841 s += str_to_int(s, &precision);
842 }
843 if (istype(*s)) {
844 type = *s++;
845 }
846 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100847 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700848 }
849 vstr_free(format_spec);
850 format_spec = NULL;
851 }
852 if (!align) {
853 if (arg_looks_numeric(arg)) {
854 align = '>';
855 } else {
856 align = '<';
857 }
858 }
859 if (!fill) {
860 fill = ' ';
861 }
862
863 if (sign) {
864 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100865 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700866 }
867 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100868 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000869 }
870 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700871 sign = '-';
872 }
873
874 switch (align) {
875 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
876 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
877 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
878 }
879
880 if (arg_looks_integer(arg)) {
881 switch (type) {
882 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100883 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700884 continue;
885
886 case 'c':
887 {
888 char ch = mp_obj_get_int(arg);
889 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
890 continue;
891 }
892
893 case '\0': // No explicit format type implies 'd'
894 case 'n': // I don't think we support locales in uPy so use 'd'
895 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100896 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700897 continue;
898
899 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700900 if (flags & PF_FLAG_SHOW_PREFIX) {
901 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
902 }
903
Damien Georgea12a0f72014-04-08 01:29:53 +0100904 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 continue;
906
907 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100908 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700909 continue;
910
911 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100912 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700913 continue;
914
915 case 'e':
916 case 'E':
917 case 'f':
918 case 'F':
919 case 'g':
920 case 'G':
921 case '%':
922 // The floating point formatters all work with anything that
923 // looks like an integer
924 break;
925
926 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100927 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700928 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
929 }
Damien Georgec322c5f2014-04-02 20:04:15 +0100930 }
Damien George70f33cd2014-04-02 17:06:05 +0100931
Dave Hylands22fe4d72014-04-02 12:07:31 -0700932 // NOTE: no else here. We need the e, f, g etc formats for integer
933 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +0100934 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700935 if (!type) {
936
937 // Even though the docs say that an unspecified type is the same
938 // as 'g', there is one subtle difference, when the exponent
939 // is one less than the precision.
940 //
941 // '{:10.1}'.format(0.0) ==> '0e+00'
942 // '{:10.1g}'.format(0.0) ==> '0'
943 //
944 // TODO: Figure out how to deal with this.
945 //
946 // A proper solution would involve adding a special flag
947 // or something to format_float, and create a format_double
948 // to deal with doubles. In order to fix this when using
949 // sprintf, we'd need to use the e format and tweak the
950 // returned result to strip trailing zeros like the g format
951 // does.
952 //
953 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
954 // but with 1.e2 you get 1e+02 and 1.00e+02
955 //
956 // Stripping the trailing 0's (like g) does would make the
957 // e format give us the right format.
958 //
959 // CPython sources say:
960 // Omitted type specifier. Behaves in the same way as repr(x)
961 // and str(x) if no precision is given, else like 'g', but with
962 // at least one digit after the decimal point. */
963
964 type = 'g';
965 }
966 if (type == 'n') {
967 type = 'g';
968 }
969
970 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
971 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +0100972#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700973 case 'e':
974 case 'E':
975 case 'f':
976 case 'F':
977 case 'g':
978 case 'G':
979 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
980 break;
981
982 case '%':
983 flags |= PF_FLAG_ADD_PERCENT;
984 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
985 break;
Damien Georgec322c5f2014-04-02 20:04:15 +0100986#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700987
988 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100989 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700990 "Unknown format code '%c' for object of type 'float'",
991 type, mp_obj_get_type_str(arg)));
992 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700993 } else {
Damien George70f33cd2014-04-02 17:06:05 +0100994 // arg doesn't look like a number
995
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700996 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +0100997 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700998 }
Damien George70f33cd2014-04-02 17:06:05 +0100999
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001000 switch (type) {
1001 case '\0':
1002 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1003 break;
1004
1005 case 's':
1006 {
1007 uint len;
1008 const char *s = mp_obj_str_get_data(arg, &len);
1009 if (precision < 0) {
1010 precision = len;
1011 }
1012 if (len > precision) {
1013 len = precision;
1014 }
1015 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1016 break;
1017 }
1018
1019 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001020 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001021 "Unknown format code '%c' for object of type 'str'",
1022 type, mp_obj_get_type_str(arg)));
1023 }
Damiend99b0522013-12-21 18:17:45 +00001024 }
1025 }
1026
Damien George5fa93b62014-01-22 14:35:10 +00001027 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1028 vstr_free(vstr);
1029 return s;
Damiend99b0522013-12-21 18:17:45 +00001030}
1031
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001032STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
1033 assert(MP_OBJ_IS_STR(pattern));
1034
1035 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001036 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001037 int arg_i = 0;
1038 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001039 pfenv_t pfenv_vstr;
1040 pfenv_vstr.data = vstr;
1041 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1042
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001043 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -07001044 if (*str != '%') {
1045 vstr_add_char(vstr, *str);
1046 continue;
1047 }
1048 if (++str >= top) {
1049 break;
1050 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001051 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001052 vstr_add_char(vstr, '%');
1053 continue;
1054 }
1055 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001056 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -07001057 }
1058 int flags = 0;
1059 char fill = ' ';
1060 bool alt = false;
1061 while (str < top) {
1062 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1063 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1064 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1065 else if (*str == '#') alt = true;
1066 else if (*str == '0') {
1067 flags |= PF_FLAG_PAD_AFTER_SIGN;
1068 fill = '0';
1069 } else break;
1070 str++;
1071 }
1072 // parse width, if it exists
1073 int width = 0;
1074 if (str < top) {
1075 if (*str == '*') {
1076 width = mp_obj_get_int(args[arg_i++]);
1077 str++;
1078 } else {
1079 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1080 width = width * 10 + *str - '0';
1081 }
1082 }
1083 }
1084 int prec = -1;
1085 if (str < top && *str == '.') {
1086 if (++str < top) {
1087 if (*str == '*') {
1088 prec = mp_obj_get_int(args[arg_i++]);
1089 str++;
1090 } else {
1091 prec = 0;
1092 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1093 prec = prec * 10 + *str - '0';
1094 }
1095 }
1096 }
1097 }
1098
1099 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001100 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001101 }
1102 mp_obj_t arg = args[arg_i];
1103 switch (*str) {
1104 case 'c':
1105 if (MP_OBJ_IS_STR(arg)) {
1106 uint len;
1107 const char *s = mp_obj_str_get_data(arg, &len);
1108 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001109 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001110 break;
1111 }
1112 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1113 break;
1114 }
1115 if (arg_looks_integer(arg)) {
1116 char ch = mp_obj_get_int(arg);
1117 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1118 break;
1119 }
1120#if MICROPY_ENABLE_FLOAT
1121 // This is what CPython reports, so we report the same.
1122 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001123 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001124
1125 }
1126#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001127 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001128 break;
1129
1130 case 'd':
1131 case 'i':
1132 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001133 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001134 break;
1135
1136#if MICROPY_ENABLE_FLOAT
1137 case 'e':
1138 case 'E':
1139 case 'f':
1140 case 'F':
1141 case 'g':
1142 case 'G':
1143 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1144 break;
1145#endif
1146
1147 case 'o':
1148 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001149 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001150 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001151 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001152 break;
1153
1154 case 'r':
1155 case 's':
1156 {
1157 vstr_t *arg_vstr = vstr_new();
1158 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1159 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1160 uint len = vstr_len(arg_vstr);
1161 if (prec < 0) {
1162 prec = len;
1163 }
1164 if (len > prec) {
1165 len = prec;
1166 }
1167 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1168 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001169 break;
1170 }
Dave Hylands6756a372014-04-02 11:42:39 -07001171
1172 case 'x':
1173 if (alt) {
1174 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001175 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001176 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001177 break;
1178
1179 case 'X':
1180 if (alt) {
1181 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001182 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001183 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001184 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001185
Dave Hylands6756a372014-04-02 11:42:39 -07001186 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001187 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001188 "unsupported format character '%c' (0x%x) at index %d",
1189 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001190 }
Dave Hylands6756a372014-04-02 11:42:39 -07001191 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001192 }
1193
1194 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001195 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001196 }
1197
1198 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1199 vstr_free(vstr);
1200 return s;
1201}
1202
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001203STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001204 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001205
Damien Georgeff715422014-04-07 00:39:13 +01001206 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001207 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001208 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001209 if (max_rep == 0) {
1210 return args[0];
1211 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001212 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001213 }
xbe480c15a2014-01-30 22:17:30 -08001214 }
Damien George94f68302014-01-31 23:45:12 +00001215
xbe729be9b2014-04-07 14:46:39 -07001216 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001217
Damien Georgeff715422014-04-07 00:39:13 +01001218 // check argument types
1219
1220 if (!MP_OBJ_IS_STR(args[1])) {
1221 bad_implicit_conversion(args[1]);
1222 }
1223
1224 if (!MP_OBJ_IS_STR(args[2])) {
1225 bad_implicit_conversion(args[2]);
1226 }
1227
1228 // extract string data
1229
xbe480c15a2014-01-30 22:17:30 -08001230 GET_STR_DATA_LEN(args[0], str, str_len);
1231 GET_STR_DATA_LEN(args[1], old, old_len);
1232 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001233
1234 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001235 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001236 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001237 }
1238
Damien George94f68302014-01-31 23:45:12 +00001239 // data for the replaced string
1240 byte *data = NULL;
1241 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001242
Damien George94f68302014-01-31 23:45:12 +00001243 // do 2 passes over the string:
1244 // first pass computes the required length of the replaced string
1245 // second pass does the replacements
1246 for (;;) {
1247 machine_uint_t replaced_str_index = 0;
1248 machine_uint_t num_replacements_done = 0;
1249 const byte *old_occurrence;
1250 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001251 machine_uint_t str_len_remain = str_len;
1252 if (old_len == 0) {
1253 // if old_str is empty, copy new_str to start of replaced string
1254 // copy the replacement string
1255 if (data != NULL) {
1256 memcpy(data, new, new_len);
1257 }
1258 replaced_str_index += new_len;
1259 num_replacements_done++;
1260 }
1261 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1262 if (old_len == 0) {
1263 old_occurrence += 1;
1264 }
Damien George94f68302014-01-31 23:45:12 +00001265 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1266 if (data != NULL) {
1267 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1268 }
1269 replaced_str_index += old_occurrence - offset_ptr;
1270 // copy the replacement string
1271 if (data != NULL) {
1272 memcpy(data + replaced_str_index, new, new_len);
1273 }
1274 replaced_str_index += new_len;
1275 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001276 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001277 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001278 }
1279
1280 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1281 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001282 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001283 }
Damien Georgeff715422014-04-07 00:39:13 +01001284 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001285
1286 if (data == NULL) {
1287 // first pass
1288 if (num_replacements_done == 0) {
1289 // no substr found, return original string
1290 return args[0];
1291 } else {
1292 // substr found, allocate new string
1293 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001294 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001295 }
1296 } else {
1297 // second pass, we are done
1298 break;
1299 }
xbe480c15a2014-01-30 22:17:30 -08001300 }
Damien George94f68302014-01-31 23:45:12 +00001301
xbe480c15a2014-01-30 22:17:30 -08001302 return mp_obj_str_builder_end(replaced_str);
1303}
1304
xbe9e1e8cd2014-03-12 22:57:16 -07001305STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1306 assert(2 <= n_args && n_args <= 4);
1307 assert(MP_OBJ_IS_STR(args[0]));
1308 assert(MP_OBJ_IS_STR(args[1]));
1309
1310 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1311 GET_STR_DATA_LEN(args[1], needle, needle_len);
1312
Damien George536dde22014-03-13 22:07:55 +00001313 machine_uint_t start = 0;
1314 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001315 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001316 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001317 }
1318 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001319 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001320 }
1321
Damien George536dde22014-03-13 22:07:55 +00001322 // if needle_len is zero then we count each gap between characters as an occurrence
1323 if (needle_len == 0) {
1324 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001325 }
1326
Damien George536dde22014-03-13 22:07:55 +00001327 // count the occurrences
1328 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001329 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1330 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1331 num_occurrences++;
1332 haystack_index += needle_len - 1;
1333 }
xbe9e1e8cd2014-03-12 22:57:16 -07001334 }
1335
1336 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1337}
1338
Damien Georgeb035db32014-03-21 20:39:40 +00001339STATIC 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 +03001340 if (!is_str_or_bytes(self_in)) {
1341 assert(0);
1342 }
1343 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1344 if (self_type != mp_obj_get_type(arg)) {
1345 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001346 }
Damien Georgeb035db32014-03-21 20:39:40 +00001347
xbe613a8e32014-03-18 00:06:29 -07001348 GET_STR_DATA_LEN(self_in, str, str_len);
1349 GET_STR_DATA_LEN(arg, sep, sep_len);
1350
1351 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001352 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001353 }
Damien Georgeb035db32014-03-21 20:39:40 +00001354
1355 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1356
1357 if (direction > 0) {
1358 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001359 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001360 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001361 }
xbe613a8e32014-03-18 00:06:29 -07001362
xbe17a5a832014-03-23 23:31:58 -07001363 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1364 if (position_ptr != NULL) {
1365 machine_uint_t position = position_ptr - str;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001366 result[0] = str_new(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001367 result[1] = arg;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001368 result[2] = str_new(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001369 }
Damien Georgeb035db32014-03-21 20:39:40 +00001370
xbe0a6894c2014-03-21 01:12:26 -07001371 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001372}
1373
Damien Georgeb035db32014-03-21 20:39:40 +00001374STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1375 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001376}
xbe4504ea82014-03-19 00:46:14 -07001377
Damien Georgeb035db32014-03-21 20:39:40 +00001378STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1379 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001380}
1381
Paul Sokolovsky69135212014-05-10 19:47:41 +03001382enum { CASE_UPPER, CASE_LOWER };
1383
1384// Supposedly not too critical operations, so optimize for code size
1385STATIC mp_obj_t str_caseconv(int op, mp_obj_t self_in) {
1386 GET_STR_DATA_LEN(self_in, self_data, self_len);
1387 byte *data;
1388 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1389 for (int i = 0; i < self_len; i++) {
1390 if (op == CASE_UPPER) {
1391 *data++ = unichar_toupper(*self_data++);
1392 } else {
1393 *data++ = unichar_tolower(*self_data++);
1394 }
1395 }
1396 *data = 0;
1397 return mp_obj_str_builder_end(s);
1398}
1399
1400STATIC mp_obj_t str_lower(mp_obj_t self_in) {
1401 return str_caseconv(CASE_LOWER, self_in);
1402}
1403
1404STATIC mp_obj_t str_upper(mp_obj_t self_in) {
1405 return str_caseconv(CASE_UPPER, self_in);
1406}
1407
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001408#if MICROPY_CPYTHON_COMPAT
1409// These methods are superfluous in the presense of str() and bytes()
1410// constructors.
1411// TODO: should accept kwargs too
1412STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1413 mp_obj_t new_args[2];
1414 if (n_args == 1) {
1415 new_args[0] = args[0];
1416 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1417 args = new_args;
1418 n_args++;
1419 }
1420 return str_make_new(NULL, n_args, 0, args);
1421}
1422
1423// TODO: should accept kwargs too
1424STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1425 mp_obj_t new_args[2];
1426 if (n_args == 1) {
1427 new_args[0] = args[0];
1428 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1429 args = new_args;
1430 n_args++;
1431 }
1432 return bytes_make_new(NULL, n_args, 0, args);
1433}
1434#endif
1435
Damien George57a4b4f2014-04-18 22:29:21 +01001436STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1437 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001438 GET_STR_DATA_LEN(self_in, str_data, str_len);
1439 bufinfo->buf = (void*)str_data;
1440 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001441 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001442 return 0;
1443 } else {
1444 // can't write to a string
1445 bufinfo->buf = NULL;
1446 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001447 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001448 return 1;
1449 }
1450}
1451
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001452#if MICROPY_CPYTHON_COMPAT
1453STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1454STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1455#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001456STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001457STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001458STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1459STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001460STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1461STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1462STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1463STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001464STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1465STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001466STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001467STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001468STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001469STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001470STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001471STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1472STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Damiend99b0522013-12-21 18:17:45 +00001473
Damien George9b196cd2014-03-26 21:47:19 +00001474STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001475#if MICROPY_CPYTHON_COMPAT
1476 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1477 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1478#endif
Damien George9b196cd2014-03-26 21:47:19 +00001479 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1480 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001481 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1482 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001483 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1484 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
1485 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1486 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001487 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1488 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001489 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1490 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1491 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1492 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1493 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001494 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1495 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001496};
Damien George97209d32014-01-07 15:58:30 +00001497
Damien George9b196cd2014-03-26 21:47:19 +00001498STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1499
Damien George3e1a5c12014-03-29 13:43:38 +00001500const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001501 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001502 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001503 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001504 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001505 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001506 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001507 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001508 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001509 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001510};
1511
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001512// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001513const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001514 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001515 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001516 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001517 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001518 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001519 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001520 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001521 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001522 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001523};
1524
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001525// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001526STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001527const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1528
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001529mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001530 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001531 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001532 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001533 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001534 byte *p = m_new(byte, len + 1);
1535 o->data = p;
1536 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001537 return o;
1538}
1539
Damien George5fa93b62014-01-22 14:35:10 +00001540mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001541 mp_obj_str_t *o = o_in;
1542 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001543 byte *p = (byte*)o->data;
1544 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001545 return o;
1546}
1547
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001548STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001549 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001550 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001551 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001552 if (data) {
1553 o->hash = qstr_compute_hash(data, len);
1554 byte *p = m_new(byte, len + 1);
1555 o->data = p;
1556 memcpy(p, data, len * sizeof(byte));
1557 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1558 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001559 return o;
1560}
1561
Damien George5fa93b62014-01-22 14:35:10 +00001562mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1563 qstr q = qstr_find_strn(data, len);
1564 if (q != MP_QSTR_NULL) {
1565 // qstr with this data already exists
1566 return MP_OBJ_NEW_QSTR(q);
1567 } else if (make_qstr_if_not_already) {
1568 // no existing qstr, make a new one
1569 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1570 } else {
1571 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001572 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001573 }
Damien George5fa93b62014-01-22 14:35:10 +00001574}
1575
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001576mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001577 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001578}
1579
Damien George5fa93b62014-01-22 14:35:10 +00001580bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1581 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1582 return s1 == s2;
1583 } else {
1584 GET_STR_HASH(s1, h1);
1585 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001586 // If any of hashes is 0, it means it's not valid
1587 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001588 return false;
1589 }
1590 GET_STR_DATA_LEN(s1, d1, l1);
1591 GET_STR_DATA_LEN(s2, d2, l2);
1592 if (l1 != l2) {
1593 return false;
1594 }
Damien George1e708fe2014-01-23 18:27:51 +00001595 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001596 }
Damien George5fa93b62014-01-22 14:35:10 +00001597}
1598
Damien Georgedeed0872014-04-06 11:11:15 +01001599STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001600 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 +00001601}
1602
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001603STATIC void arg_type_mixup() {
1604 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1605}
1606
Damien George5fa93b62014-01-22 14:35:10 +00001607uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001608 // TODO: This has too big overhead for hash accessor
1609 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001610 GET_STR_HASH(self_in, h);
1611 return h;
1612 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001613 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001614 }
1615}
1616
1617uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001618 // TODO This has a double check for the type, one in obj.c and one here
1619 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001620 GET_STR_LEN(self_in, l);
1621 return l;
1622 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001623 bad_implicit_conversion(self_in);
1624 }
1625}
1626
1627// use this if you will anyway convert the string to a qstr
1628// will be more efficient for the case where it's already a qstr
1629qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1630 if (MP_OBJ_IS_QSTR(self_in)) {
1631 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001632 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001633 mp_obj_str_t *self = self_in;
1634 return qstr_from_strn((char*)self->data, self->len);
1635 } else {
1636 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001637 }
1638}
1639
1640// only use this function if you need the str data to be zero terminated
1641// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1642const char *mp_obj_str_get_str(mp_obj_t self_in) {
1643 if (MP_OBJ_IS_STR(self_in)) {
1644 GET_STR_DATA_LEN(self_in, s, l);
1645 (void)l; // len unused
1646 return (const char*)s;
1647 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001648 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001649 }
1650}
1651
Damien George698ec212014-02-08 18:17:23 +00001652const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001653 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001654 GET_STR_DATA_LEN(self_in, s, l);
1655 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001656 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001657 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001658 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001659 }
Damiend99b0522013-12-21 18:17:45 +00001660}
xyb8cfc9f02014-01-05 18:47:51 +08001661
1662/******************************************************************************/
1663/* str iterator */
1664
1665typedef struct _mp_obj_str_it_t {
1666 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001667 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001668 machine_uint_t cur;
1669} mp_obj_str_it_t;
1670
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001671STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001672 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001673 GET_STR_DATA_LEN(self->str, str, len);
1674 if (self->cur < len) {
1675 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001676 self->cur += 1;
1677 return o_out;
1678 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001679 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001680 }
1681}
1682
Damien George3e1a5c12014-03-29 13:43:38 +00001683STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001684 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001685 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001686 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001687 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001688};
1689
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001690STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001691 mp_obj_str_it_t *self = self_in;
1692 GET_STR_DATA_LEN(self->str, str, len);
1693 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001694 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001695 self->cur += 1;
1696 return o_out;
1697 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001698 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001699 }
1700}
1701
Damien George3e1a5c12014-03-29 13:43:38 +00001702STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001703 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001704 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001705 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001706 .iternext = bytes_it_iternext,
1707};
1708
1709mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001710 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001711 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001712 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001713 o->cur = 0;
1714 return o;
1715}
1716
1717mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1718 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001719 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001720 o->str = str;
1721 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001722 return o;
1723}