blob: a16033806919000a189c52f7ddb5f7c475f225fa [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
xbeefe34222014-03-16 00:14:26 -070028#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +000029#include <string.h>
30#include <assert.h>
31
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030032#include "mpconfig.h"
Damiend99b0522013-12-21 18:17:45 +000033#include "nlr.h"
34#include "misc.h"
Damien George55baff42014-01-21 21:40:13 +000035#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000036#include "obj.h"
37#include "runtime0.h"
38#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070039#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030040#include "objstr.h"
Paul Sokolovsky2a273652014-05-13 08:07:08 +030041#include "objlist.h"
Damiend99b0522013-12-21 18:17:45 +000042
Paul Sokolovsky4db727a2014-03-31 21:18:28 +030043STATIC 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 +020044const mp_obj_t mp_const_empty_bytes;
45
Damien George5fa93b62014-01-22 14:35:10 +000046// use this macro to extract the string hash
47#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; }
48
49// use this macro to extract the string length
50#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; }
51
52// use this macro to extract the string data and length
53#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; }
54
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020055STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
56STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskya47b64a2014-05-15 07:28:19 +030057mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len);
Paul Sokolovskye9085912014-04-30 05:35:18 +030058STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030059STATIC NORETURN void arg_type_mixup();
60
61STATIC bool is_str_or_bytes(mp_obj_t o) {
62 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
63}
xyb8cfc9f02014-01-05 18:47:51 +080064
65/******************************************************************************/
66/* str */
67
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020068void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
69 // this escapes characters, but it will be very slow to print (calling print many times)
70 bool has_single_quote = false;
71 bool has_double_quote = false;
72 for (const byte *s = str_data, *top = str_data + str_len; (!has_single_quote || !has_double_quote) && s < top; s++) {
73 if (*s == '\'') {
74 has_single_quote = true;
75 } else if (*s == '"') {
76 has_double_quote = true;
77 }
78 }
79 int quote_char = '\'';
80 if (has_single_quote && !has_double_quote) {
81 quote_char = '"';
82 }
83 print(env, "%c", quote_char);
84 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
85 if (*s == quote_char) {
86 print(env, "\\%c", quote_char);
87 } else if (*s == '\\') {
88 print(env, "\\\\");
89 } else if (32 <= *s && *s <= 126) {
90 print(env, "%c", *s);
91 } else if (*s == '\n') {
92 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010093 } else if (*s == '\r') {
94 print(env, "\\r");
95 } else if (*s == '\t') {
96 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020097 } else {
98 print(env, "\\x%02x", *s);
99 }
100 }
101 print(env, "%c", quote_char);
102}
103
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200104STATIC 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 +0000105 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000106 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200107 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000108 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200109 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200110 if (is_bytes) {
111 print(env, "b");
112 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +0200113 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200114 }
Damiend99b0522013-12-21 18:17:45 +0000115}
116
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200117STATIC 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 +0300118#if MICROPY_CPYTHON_COMPAT
119 if (n_kw != 0) {
120 mp_arg_error_unimpl_kw();
121 }
122#endif
123
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200124 switch (n_args) {
125 case 0:
126 return MP_OBJ_NEW_QSTR(MP_QSTR_);
127
128 case 1:
129 {
130 vstr_t *vstr = vstr_new();
131 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
132 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
133 vstr_free(vstr);
134 return s;
135 }
136
137 case 2:
138 case 3:
139 {
140 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000141 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100142 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200143 }
144 GET_STR_DATA_LEN(args[0], str_data, str_len);
145 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000146 mp_obj_str_t *o = str_new(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200147 o->data = str_data;
148 o->hash = str_hash;
149 return o;
150 }
151
152 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100153 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200154 }
155}
156
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200157STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
158 if (n_args == 0) {
159 return mp_const_empty_bytes;
160 }
161
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300162#if MICROPY_CPYTHON_COMPAT
163 if (n_kw != 0) {
164 mp_arg_error_unimpl_kw();
165 }
166#endif
167
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200168 if (MP_OBJ_IS_STR(args[0])) {
169 if (n_args < 2 || n_args > 3) {
170 goto wrong_args;
171 }
172 GET_STR_DATA_LEN(args[0], str_data, str_len);
173 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000174 mp_obj_str_t *o = str_new(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200175 o->data = str_data;
176 o->hash = str_hash;
177 return o;
178 }
179
180 if (n_args > 1) {
181 goto wrong_args;
182 }
183
184 if (MP_OBJ_IS_SMALL_INT(args[0])) {
185 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
186 byte *data;
187
Damien George3e1a5c12014-03-29 13:43:38 +0000188 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200189 memset(data, 0, len);
190 return mp_obj_str_builder_end(o);
191 }
192
193 int len;
194 byte *data;
195 vstr_t *vstr = NULL;
196 mp_obj_t o = NULL;
197 // Try to create array of exact len if initializer len is known
198 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
199 if (len_in == MP_OBJ_NULL) {
200 len = -1;
201 vstr = vstr_new();
202 } else {
203 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000204 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200205 }
206
Damien Georged17926d2014-03-30 13:35:08 +0100207 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200208 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100209 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200210 if (len == -1) {
211 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
212 } else {
213 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
214 }
215 }
216
217 if (len == -1) {
218 vstr_shrink(vstr);
219 // TODO: Optimize, borrow buffer from vstr
220 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000221 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200222 memcpy(data, vstr_str(vstr), len);
223 vstr_free(vstr);
224 }
225
226 return mp_obj_str_builder_end(o);
227
228wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100229 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200230}
231
Damien George55baff42014-01-21 21:40:13 +0000232// like strstr but with specified length and allows \0 bytes
233// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700234STATIC 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 +0000235 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700236 machine_uint_t str_index, str_index_end;
237 if (direction > 0) {
238 str_index = 0;
239 str_index_end = hlen - nlen;
240 } else {
241 str_index = hlen - nlen;
242 str_index_end = 0;
243 }
244 for (;;) {
245 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
246 //found
247 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000248 }
xbe17a5a832014-03-23 23:31:58 -0700249 if (str_index == str_index_end) {
250 //not found
251 break;
Damien George55baff42014-01-21 21:40:13 +0000252 }
xbe17a5a832014-03-23 23:31:58 -0700253 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000254 }
255 }
256 return NULL;
257}
258
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200259STATIC 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 +0000260 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300261 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
262 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000263 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100264 case MP_BINARY_OP_ADD:
265 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300266 if (lhs_type == rhs_type) {
267 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000268
269 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000270 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000271
272 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000273 byte *q_ptr;
274 byte *val = qstr_build_start(alloc_len, &q_ptr);
275 memcpy(val, lhs_data, lhs_len);
276 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000277 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
278 */
279
280 // code for non-qstr
281 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300282 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000283 memcpy(data, lhs_data, lhs_len);
284 memcpy(data + lhs_len, rhs_data, rhs_len);
285 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000286 }
287 break;
Damien George5fa93b62014-01-22 14:35:10 +0000288
Damien Georged17926d2014-03-30 13:35:08 +0100289 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000290 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300291 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000292 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700293 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000294 }
295 break;
Damien George5fa93b62014-01-22 14:35:10 +0000296
Damien Georged0a5bf32014-05-10 13:55:11 +0100297 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200298 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien Georged0a5bf32014-05-10 13:55:11 +0100299 return MP_OBJ_NOT_SUPPORTED;
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200300 }
301 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000302 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300303 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000304 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
305 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200306 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200307
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300308 case MP_BINARY_OP_MODULO: {
309 mp_obj_t *args;
310 uint n_args;
311 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
312 // TODO: Support tuple subclasses?
313 mp_obj_tuple_get(rhs_in, &n_args, &args);
314 } else {
315 args = &rhs_in;
316 n_args = 1;
317 }
318 return str_modulo_format(lhs_in, n_args, args);
319 }
320
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300321 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
322 case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal()
Damien Georged17926d2014-03-30 13:35:08 +0100323 case MP_BINARY_OP_LESS:
324 case MP_BINARY_OP_LESS_EQUAL:
325 case MP_BINARY_OP_MORE:
326 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300327 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200328 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
329 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
330 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300331 if (lhs_type == &mp_type_bytes) {
332 mp_buffer_info_t bufinfo;
333 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
334 goto uncomparable;
335 }
336 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
337 }
338uncomparable:
339 if (op == MP_BINARY_OP_EQUAL) {
340 return mp_const_false;
341 }
Damiend99b0522013-12-21 18:17:45 +0000342 }
343
Damien Georgeea8d06c2014-04-17 23:19:36 +0100344 return MP_OBJ_NOT_SUPPORTED;
Damiend99b0522013-12-21 18:17:45 +0000345}
346
Damien George729f7b42014-04-17 22:10:53 +0100347STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300348 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100349 GET_STR_DATA_LEN(self_in, self_data, self_len);
350 if (value == MP_OBJ_SENTINEL) {
351 // load
352#if MICROPY_ENABLE_SLICE
353 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
354 machine_uint_t start, stop;
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300355 if (!mp_seq_get_fast_slice_indexes(self_len, index, &start, &stop)) {
Damien George729f7b42014-04-17 22:10:53 +0100356 assert(0);
357 }
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300358 return str_new(type, self_data + start, stop - start);
Damien George729f7b42014-04-17 22:10:53 +0100359 }
360#endif
Damien George729f7b42014-04-17 22:10:53 +0100361 uint index_val = mp_get_index(type, self_len, index, false);
362 if (type == &mp_type_bytes) {
363 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
364 } else {
365 return mp_obj_new_str(self_data + index_val, 1, true);
366 }
367 } else {
368 return MP_OBJ_NOT_SUPPORTED;
369 }
370}
371
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200372STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300373 assert(is_str_or_bytes(self_in));
374 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000375
Damien Georgefe8fb912014-01-02 16:36:09 +0000376 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000377 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000378
379 // process args
Damiend99b0522013-12-21 18:17:45 +0000380 uint seq_len;
381 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000382 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000383 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000384 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100385 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
386 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300387 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100388 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
389 }
390 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000391 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000392
393 // count required length
394 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000395 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300396 if (mp_obj_get_type(seq_items[i]) != self_type) {
397 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
398 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000399 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000400 if (i > 0) {
401 required_len += sep_len;
402 }
Damien George5fa93b62014-01-22 14:35:10 +0000403 GET_STR_LEN(seq_items[i], l);
404 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000405 }
406
407 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000408 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300409 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000410 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000411 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000412 memcpy(data, sep_str, sep_len);
413 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000414 }
Damien George5fa93b62014-01-22 14:35:10 +0000415 GET_STR_DATA_LEN(seq_items[i], s, l);
416 memcpy(data, s, l);
417 data += l;
Damiend99b0522013-12-21 18:17:45 +0000418 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000419
420 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000421 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000422}
423
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200424#define is_ws(c) ((c) == ' ' || (c) == '\t')
425
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200426STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300427 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100428 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200429 mp_obj_t sep = mp_const_none;
430 if (n_args > 1) {
431 sep = args[1];
432 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100433 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200434 }
435 }
Damien Georgedeed0872014-04-06 11:11:15 +0100436
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200437 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000438 GET_STR_DATA_LEN(args[0], s, len);
439 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200440
Damien Georgedeed0872014-04-06 11:11:15 +0100441 if (sep == mp_const_none) {
442 // sep not given, so separate on whitespace
443
444 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000445 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100446 while (s < top && splits != 0) {
447 const byte *start = s;
448 while (s < top && !is_ws(*s)) s++;
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300449 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100450 if (s >= top) {
451 break;
452 }
453 while (s < top && is_ws(*s)) s++;
454 if (splits > 0) {
455 splits--;
456 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200457 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200458
Damien Georgedeed0872014-04-06 11:11:15 +0100459 if (s < top) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300460 mp_obj_list_append(res, str_new(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100461 }
462
463 } else {
464 // sep given
465
466 uint sep_len;
467 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
468
469 if (sep_len == 0) {
470 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
471 }
472
473 for (;;) {
474 const byte *start = s;
475 for (;;) {
476 if (splits == 0 || s + sep_len > top) {
477 s = top;
478 break;
479 } else if (memcmp(s, sep_str, sep_len) == 0) {
480 break;
481 }
482 s++;
483 }
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300484 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100485 if (s >= top) {
486 break;
487 }
488 s += sep_len;
489 if (splits > 0) {
490 splits--;
491 }
492 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200493 }
494
495 return res;
496}
497
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300498STATIC mp_obj_t str_rsplit(uint n_args, const mp_obj_t *args) {
499 if (n_args < 3) {
500 // If we don't have split limit, it doesn't matter from which side
501 // we split.
502 return str_split(n_args, args);
503 }
504 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
505 mp_obj_t sep = args[1];
506 GET_STR_DATA_LEN(args[0], s, len);
507
508 machine_int_t splits = mp_obj_get_int(args[2]);
509 machine_int_t org_splits = splits;
510 // Preallocate list to the max expected # of elements, as we
511 // will fill it from the end.
512 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
513 int idx = splits;
514
515 if (sep == mp_const_none) {
516 // TODO
517 assert(0);
518 } else {
519 uint sep_len;
520 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
521
522 if (sep_len == 0) {
523 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
524 }
525
526 const byte *beg = s;
527 const byte *last = s + len;
528 for (;;) {
529 s = last - sep_len;
530 for (;;) {
531 if (splits == 0 || s < beg) {
532 break;
533 } else if (memcmp(s, sep_str, sep_len) == 0) {
534 break;
535 }
536 s--;
537 }
538 if (s < beg || splits == 0) {
539 res->items[idx] = str_new(self_type, beg, last - beg);
540 break;
541 }
542 res->items[idx--] = str_new(self_type, s + sep_len, last - s - sep_len);
543 last = s;
544 if (splits > 0) {
545 splits--;
546 }
547 }
548 if (idx != 0) {
549 // We split less parts than split limit, now go cleanup surplus
550 int used = org_splits + 1 - idx;
551 memcpy(res->items, &res->items[idx], used * sizeof(mp_obj_t));
552 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
553 res->len = used;
554 }
555 }
556
557 return res;
558}
559
560
xbe3d9a39e2014-04-08 11:42:19 -0700561STATIC 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 +0000562 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000563 assert(MP_OBJ_IS_STR(args[0]));
564 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000565
Damien George5fa93b62014-01-22 14:35:10 +0000566 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
567 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000568
xbec5538882014-03-16 17:58:35 -0700569 machine_uint_t start = 0;
570 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000571 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000572 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000573 }
574 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000575 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000576 }
577
xbe17a5a832014-03-23 23:31:58 -0700578 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000579 if (p == NULL) {
580 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700581 if (is_index) {
582 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
583 } else {
584 return MP_OBJ_NEW_SMALL_INT(-1);
585 }
Damien George23005372014-01-13 19:39:01 +0000586 } else {
587 // found
xbe17a5a832014-03-23 23:31:58 -0700588 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000589 }
John R. Lentone8204912014-01-12 21:53:52 +0000590}
591
xbe17a5a832014-03-23 23:31:58 -0700592STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700593 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700594}
595
596STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700597 return str_finder(n_args, args, -1, false);
598}
599
600STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
601 return str_finder(n_args, args, 1, true);
602}
603
604STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
605 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700606}
607
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200608// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200609STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200610 GET_STR_DATA_LEN(self_in, str, str_len);
611 GET_STR_DATA_LEN(arg, prefix, prefix_len);
612 if (prefix_len > str_len) {
613 return mp_const_false;
614 }
615 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
616}
617
Paul Sokolovsky88107842014-04-26 06:20:08 +0300618enum { LSTRIP, RSTRIP, STRIP };
619
620STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800621 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300622 assert(is_str_or_bytes(args[0]));
623 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000624
625 const byte *chars_to_del;
626 uint chars_to_del_len;
627 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800628
629 if (n_args == 1) {
630 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000631 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800632 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300633 if (mp_obj_get_type(args[1]) != self_type) {
634 arg_type_mixup();
635 }
Damien George5fa93b62014-01-22 14:35:10 +0000636 GET_STR_DATA_LEN(args[1], s, l);
637 chars_to_del = s;
638 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800639 }
640
Damien George5fa93b62014-01-22 14:35:10 +0000641 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800642
xbec5538882014-03-16 17:58:35 -0700643 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800644 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700645 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300646 machine_uint_t i = 0;
647 machine_int_t delta = 1;
648 if (type == RSTRIP) {
649 i = orig_str_len - 1;
650 delta = -1;
651 }
652 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700653 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800654 if (!first_good_char_pos_set) {
655 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300656 if (type == LSTRIP) {
657 last_good_char_pos = orig_str_len - 1;
658 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300659 } else if (type == RSTRIP) {
660 first_good_char_pos = 0;
661 last_good_char_pos = i;
662 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300663 }
xbe7b0f39f2014-01-08 14:23:45 -0800664 first_good_char_pos_set = true;
665 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300666 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800667 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300668 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800669 }
670
671 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000672 // string is all whitespace, return ''
673 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800674 }
675
676 assert(last_good_char_pos >= first_good_char_pos);
677 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700678 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300679 return str_new(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800680}
681
Paul Sokolovsky88107842014-04-26 06:20:08 +0300682STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
683 return str_uni_strip(STRIP, n_args, args);
684}
685
686STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
687 return str_uni_strip(LSTRIP, n_args, args);
688}
689
690STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
691 return str_uni_strip(RSTRIP, n_args, args);
692}
693
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700694// Takes an int arg, but only parses unsigned numbers, and only changes
695// *num if at least one digit was parsed.
696static int str_to_int(const char *str, int *num) {
697 const char *s = str;
698 if (unichar_isdigit(*s)) {
699 *num = 0;
700 do {
701 *num = *num * 10 + (*s - '0');
702 s++;
703 }
704 while (unichar_isdigit(*s));
705 }
706 return s - str;
707}
708
709static bool isalignment(char ch) {
710 return ch && strchr("<>=^", ch) != NULL;
711}
712
713static bool istype(char ch) {
714 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
715}
716
717static bool arg_looks_integer(mp_obj_t arg) {
718 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
719}
720
721static bool arg_looks_numeric(mp_obj_t arg) {
722 return arg_looks_integer(arg)
723#if MICROPY_ENABLE_FLOAT
724 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
725#endif
726 ;
727}
728
Dave Hylandsc4029e52014-04-07 11:19:51 -0700729static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700730#if MICROPY_ENABLE_FLOAT
731 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700732
733 // TODO: Needs a way to construct an mpz integer from a float
734
735 mp_small_int_t num = mp_obj_get_float(arg);
736 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700737 }
738#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700739 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700740}
741
Damien George897fe0c2014-04-15 22:03:55 +0100742mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000743 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000744
Damien George5fa93b62014-01-22 14:35:10 +0000745 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700746 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000747 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700748 pfenv_t pfenv_vstr;
749 pfenv_vstr.data = vstr;
750 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
751
Damien George5fa93b62014-01-22 14:35:10 +0000752 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700753 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000754 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700755 if (str < top && *str == '}') {
756 vstr_add_char(vstr, '}');
757 continue;
758 }
Damien Georgeea13f402014-04-05 18:32:08 +0100759 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700760 }
761 if (*str != '{') {
762 vstr_add_char(vstr, *str);
763 continue;
764 }
765
766 str++;
767 if (str < top && *str == '{') {
768 vstr_add_char(vstr, '{');
769 continue;
770 }
771
772 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
773
774 vstr_t *field_name = NULL;
775 char conversion = '\0';
776 vstr_t *format_spec = NULL;
777
778 if (str < top && *str != '}' && *str != '!' && *str != ':') {
779 field_name = vstr_new();
780 while (str < top && *str != '}' && *str != '!' && *str != ':') {
781 vstr_add_char(field_name, *str++);
782 }
783 vstr_add_char(field_name, '\0');
784 }
785
786 // conversion ::= "r" | "s"
787
788 if (str < top && *str == '!') {
789 str++;
790 if (str < top && (*str == 'r' || *str == 's')) {
791 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200792 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100793 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 -0700794 }
795 }
796
797 if (str < top && *str == ':') {
798 str++;
799 // {:} is the same as {}, which is the same as {!s}
800 // This makes a difference when passing in a True or False
801 // '{}'.format(True) returns 'True'
802 // '{:d}'.format(True) returns '1'
803 // So we treat {:} as {} and this later gets treated to be {!s}
804 if (*str != '}') {
805 format_spec = vstr_new();
806 while (str < top && *str != '}') {
807 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000808 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700809 vstr_add_char(format_spec, '\0');
810 }
811 }
812 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100813 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700814 }
815 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100816 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700817 }
818
819 mp_obj_t arg = mp_const_none;
820
821 if (field_name) {
822 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100823 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 -0700824 }
Damien George3bb8bd82014-04-14 21:20:30 +0100825 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700826 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100827 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700828 }
829 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100830 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700831 }
832 arg = args[index + 1];
833 arg_i = -1;
834 vstr_free(field_name);
835 field_name = NULL;
836 } else {
837 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100838 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 -0700839 }
840 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100841 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700842 }
843 arg = args[arg_i + 1];
844 arg_i++;
845 }
846 if (!format_spec && !conversion) {
847 conversion = 's';
848 }
849 if (conversion) {
850 mp_print_kind_t print_kind;
851 if (conversion == 's') {
852 print_kind = PRINT_STR;
853 } else if (conversion == 'r') {
854 print_kind = PRINT_REPR;
855 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100856 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857 }
858 vstr_t *arg_vstr = vstr_new();
859 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
860 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
861 vstr_free(arg_vstr);
862 }
863
864 char sign = '\0';
865 char fill = '\0';
866 char align = '\0';
867 int width = -1;
868 int precision = -1;
869 char type = '\0';
870 int flags = 0;
871
872 if (format_spec) {
873 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
874 //
875 // [[fill]align][sign][#][0][width][,][.precision][type]
876 // fill ::= <any character>
877 // align ::= "<" | ">" | "=" | "^"
878 // sign ::= "+" | "-" | " "
879 // width ::= integer
880 // precision ::= integer
881 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
882
883 const char *s = vstr_str(format_spec);
884 if (isalignment(*s)) {
885 align = *s++;
886 } else if (*s && isalignment(s[1])) {
887 fill = *s++;
888 align = *s++;
889 }
890 if (*s == '+' || *s == '-' || *s == ' ') {
891 if (*s == '+') {
892 flags |= PF_FLAG_SHOW_SIGN;
893 } else if (*s == ' ') {
894 flags |= PF_FLAG_SPACE_SIGN;
895 }
896 sign = *s++;
897 }
898 if (*s == '#') {
899 flags |= PF_FLAG_SHOW_PREFIX;
900 s++;
901 }
902 if (*s == '0') {
903 if (!align) {
904 align = '=';
905 }
906 if (!fill) {
907 fill = '0';
908 }
909 }
910 s += str_to_int(s, &width);
911 if (*s == ',') {
912 flags |= PF_FLAG_SHOW_COMMA;
913 s++;
914 }
915 if (*s == '.') {
916 s++;
917 s += str_to_int(s, &precision);
918 }
919 if (istype(*s)) {
920 type = *s++;
921 }
922 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100923 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700924 }
925 vstr_free(format_spec);
926 format_spec = NULL;
927 }
928 if (!align) {
929 if (arg_looks_numeric(arg)) {
930 align = '>';
931 } else {
932 align = '<';
933 }
934 }
935 if (!fill) {
936 fill = ' ';
937 }
938
939 if (sign) {
940 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100941 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700942 }
943 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100944 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000945 }
946 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700947 sign = '-';
948 }
949
950 switch (align) {
951 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
952 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
953 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
954 }
955
956 if (arg_looks_integer(arg)) {
957 switch (type) {
958 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100959 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700960 continue;
961
962 case 'c':
963 {
964 char ch = mp_obj_get_int(arg);
965 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
966 continue;
967 }
968
969 case '\0': // No explicit format type implies 'd'
970 case 'n': // I don't think we support locales in uPy so use 'd'
971 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100972 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700973 continue;
974
975 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700976 if (flags & PF_FLAG_SHOW_PREFIX) {
977 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
978 }
979
Damien Georgea12a0f72014-04-08 01:29:53 +0100980 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700981 continue;
982
983 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100984 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700985 continue;
986
987 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100988 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700989 continue;
990
991 case 'e':
992 case 'E':
993 case 'f':
994 case 'F':
995 case 'g':
996 case 'G':
997 case '%':
998 // The floating point formatters all work with anything that
999 // looks like an integer
1000 break;
1001
1002 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001003 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001004 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
1005 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001006 }
Damien George70f33cd2014-04-02 17:06:05 +01001007
Dave Hylands22fe4d72014-04-02 12:07:31 -07001008 // NOTE: no else here. We need the e, f, g etc formats for integer
1009 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001010 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001011 if (!type) {
1012
1013 // Even though the docs say that an unspecified type is the same
1014 // as 'g', there is one subtle difference, when the exponent
1015 // is one less than the precision.
1016 //
1017 // '{:10.1}'.format(0.0) ==> '0e+00'
1018 // '{:10.1g}'.format(0.0) ==> '0'
1019 //
1020 // TODO: Figure out how to deal with this.
1021 //
1022 // A proper solution would involve adding a special flag
1023 // or something to format_float, and create a format_double
1024 // to deal with doubles. In order to fix this when using
1025 // sprintf, we'd need to use the e format and tweak the
1026 // returned result to strip trailing zeros like the g format
1027 // does.
1028 //
1029 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1030 // but with 1.e2 you get 1e+02 and 1.00e+02
1031 //
1032 // Stripping the trailing 0's (like g) does would make the
1033 // e format give us the right format.
1034 //
1035 // CPython sources say:
1036 // Omitted type specifier. Behaves in the same way as repr(x)
1037 // and str(x) if no precision is given, else like 'g', but with
1038 // at least one digit after the decimal point. */
1039
1040 type = 'g';
1041 }
1042 if (type == 'n') {
1043 type = 'g';
1044 }
1045
1046 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1047 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +01001048#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001049 case 'e':
1050 case 'E':
1051 case 'f':
1052 case 'F':
1053 case 'g':
1054 case 'G':
1055 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
1056 break;
1057
1058 case '%':
1059 flags |= PF_FLAG_ADD_PERCENT;
1060 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1061 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001062#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001063
1064 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001065 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001066 "Unknown format code '%c' for object of type 'float'",
1067 type, mp_obj_get_type_str(arg)));
1068 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001069 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001070 // arg doesn't look like a number
1071
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001072 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001073 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001074 }
Damien George70f33cd2014-04-02 17:06:05 +01001075
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001076 switch (type) {
1077 case '\0':
1078 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1079 break;
1080
1081 case 's':
1082 {
1083 uint len;
1084 const char *s = mp_obj_str_get_data(arg, &len);
1085 if (precision < 0) {
1086 precision = len;
1087 }
1088 if (len > precision) {
1089 len = precision;
1090 }
1091 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1092 break;
1093 }
1094
1095 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001096 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001097 "Unknown format code '%c' for object of type 'str'",
1098 type, mp_obj_get_type_str(arg)));
1099 }
Damiend99b0522013-12-21 18:17:45 +00001100 }
1101 }
1102
Damien George5fa93b62014-01-22 14:35:10 +00001103 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1104 vstr_free(vstr);
1105 return s;
Damiend99b0522013-12-21 18:17:45 +00001106}
1107
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001108STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
1109 assert(MP_OBJ_IS_STR(pattern));
1110
1111 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001112 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001113 int arg_i = 0;
1114 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001115 pfenv_t pfenv_vstr;
1116 pfenv_vstr.data = vstr;
1117 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1118
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001119 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -07001120 if (*str != '%') {
1121 vstr_add_char(vstr, *str);
1122 continue;
1123 }
1124 if (++str >= top) {
1125 break;
1126 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001127 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001128 vstr_add_char(vstr, '%');
1129 continue;
1130 }
1131 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001132 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -07001133 }
1134 int flags = 0;
1135 char fill = ' ';
1136 bool alt = false;
1137 while (str < top) {
1138 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1139 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1140 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1141 else if (*str == '#') alt = true;
1142 else if (*str == '0') {
1143 flags |= PF_FLAG_PAD_AFTER_SIGN;
1144 fill = '0';
1145 } else break;
1146 str++;
1147 }
1148 // parse width, if it exists
1149 int width = 0;
1150 if (str < top) {
1151 if (*str == '*') {
1152 width = mp_obj_get_int(args[arg_i++]);
1153 str++;
1154 } else {
1155 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1156 width = width * 10 + *str - '0';
1157 }
1158 }
1159 }
1160 int prec = -1;
1161 if (str < top && *str == '.') {
1162 if (++str < top) {
1163 if (*str == '*') {
1164 prec = mp_obj_get_int(args[arg_i++]);
1165 str++;
1166 } else {
1167 prec = 0;
1168 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1169 prec = prec * 10 + *str - '0';
1170 }
1171 }
1172 }
1173 }
1174
1175 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001176 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001177 }
1178 mp_obj_t arg = args[arg_i];
1179 switch (*str) {
1180 case 'c':
1181 if (MP_OBJ_IS_STR(arg)) {
1182 uint len;
1183 const char *s = mp_obj_str_get_data(arg, &len);
1184 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001185 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001186 break;
1187 }
1188 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1189 break;
1190 }
1191 if (arg_looks_integer(arg)) {
1192 char ch = mp_obj_get_int(arg);
1193 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1194 break;
1195 }
1196#if MICROPY_ENABLE_FLOAT
1197 // This is what CPython reports, so we report the same.
1198 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001199 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001200
1201 }
1202#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001203 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001204 break;
1205
1206 case 'd':
1207 case 'i':
1208 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001209 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001210 break;
1211
1212#if MICROPY_ENABLE_FLOAT
1213 case 'e':
1214 case 'E':
1215 case 'f':
1216 case 'F':
1217 case 'g':
1218 case 'G':
1219 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1220 break;
1221#endif
1222
1223 case 'o':
1224 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001225 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001226 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001227 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001228 break;
1229
1230 case 'r':
1231 case 's':
1232 {
1233 vstr_t *arg_vstr = vstr_new();
1234 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1235 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1236 uint len = vstr_len(arg_vstr);
1237 if (prec < 0) {
1238 prec = len;
1239 }
1240 if (len > prec) {
1241 len = prec;
1242 }
1243 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1244 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001245 break;
1246 }
Dave Hylands6756a372014-04-02 11:42:39 -07001247
1248 case 'x':
1249 if (alt) {
1250 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001251 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001252 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001253 break;
1254
1255 case 'X':
1256 if (alt) {
1257 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001258 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001259 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001260 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001261
Dave Hylands6756a372014-04-02 11:42:39 -07001262 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001263 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001264 "unsupported format character '%c' (0x%x) at index %d",
1265 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001266 }
Dave Hylands6756a372014-04-02 11:42:39 -07001267 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001268 }
1269
1270 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001271 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001272 }
1273
1274 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1275 vstr_free(vstr);
1276 return s;
1277}
1278
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001279STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001280 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001281
Damien Georgeff715422014-04-07 00:39:13 +01001282 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001283 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001284 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001285 if (max_rep == 0) {
1286 return args[0];
1287 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001288 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001289 }
xbe480c15a2014-01-30 22:17:30 -08001290 }
Damien George94f68302014-01-31 23:45:12 +00001291
xbe729be9b2014-04-07 14:46:39 -07001292 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001293
Damien Georgeff715422014-04-07 00:39:13 +01001294 // check argument types
1295
1296 if (!MP_OBJ_IS_STR(args[1])) {
1297 bad_implicit_conversion(args[1]);
1298 }
1299
1300 if (!MP_OBJ_IS_STR(args[2])) {
1301 bad_implicit_conversion(args[2]);
1302 }
1303
1304 // extract string data
1305
xbe480c15a2014-01-30 22:17:30 -08001306 GET_STR_DATA_LEN(args[0], str, str_len);
1307 GET_STR_DATA_LEN(args[1], old, old_len);
1308 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001309
1310 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001311 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001312 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001313 }
1314
Damien George94f68302014-01-31 23:45:12 +00001315 // data for the replaced string
1316 byte *data = NULL;
1317 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001318
Damien George94f68302014-01-31 23:45:12 +00001319 // do 2 passes over the string:
1320 // first pass computes the required length of the replaced string
1321 // second pass does the replacements
1322 for (;;) {
1323 machine_uint_t replaced_str_index = 0;
1324 machine_uint_t num_replacements_done = 0;
1325 const byte *old_occurrence;
1326 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001327 machine_uint_t str_len_remain = str_len;
1328 if (old_len == 0) {
1329 // if old_str is empty, copy new_str to start of replaced string
1330 // copy the replacement string
1331 if (data != NULL) {
1332 memcpy(data, new, new_len);
1333 }
1334 replaced_str_index += new_len;
1335 num_replacements_done++;
1336 }
1337 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1338 if (old_len == 0) {
1339 old_occurrence += 1;
1340 }
Damien George94f68302014-01-31 23:45:12 +00001341 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1342 if (data != NULL) {
1343 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1344 }
1345 replaced_str_index += old_occurrence - offset_ptr;
1346 // copy the replacement string
1347 if (data != NULL) {
1348 memcpy(data + replaced_str_index, new, new_len);
1349 }
1350 replaced_str_index += new_len;
1351 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001352 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001353 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001354 }
1355
1356 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1357 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001358 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001359 }
Damien Georgeff715422014-04-07 00:39:13 +01001360 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001361
1362 if (data == NULL) {
1363 // first pass
1364 if (num_replacements_done == 0) {
1365 // no substr found, return original string
1366 return args[0];
1367 } else {
1368 // substr found, allocate new string
1369 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001370 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001371 }
1372 } else {
1373 // second pass, we are done
1374 break;
1375 }
xbe480c15a2014-01-30 22:17:30 -08001376 }
Damien George94f68302014-01-31 23:45:12 +00001377
xbe480c15a2014-01-30 22:17:30 -08001378 return mp_obj_str_builder_end(replaced_str);
1379}
1380
xbe9e1e8cd2014-03-12 22:57:16 -07001381STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1382 assert(2 <= n_args && n_args <= 4);
1383 assert(MP_OBJ_IS_STR(args[0]));
1384 assert(MP_OBJ_IS_STR(args[1]));
1385
1386 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1387 GET_STR_DATA_LEN(args[1], needle, needle_len);
1388
Damien George536dde22014-03-13 22:07:55 +00001389 machine_uint_t start = 0;
1390 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001391 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001392 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001393 }
1394 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001395 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001396 }
1397
Damien George536dde22014-03-13 22:07:55 +00001398 // if needle_len is zero then we count each gap between characters as an occurrence
1399 if (needle_len == 0) {
1400 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001401 }
1402
Damien George536dde22014-03-13 22:07:55 +00001403 // count the occurrences
1404 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001405 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1406 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1407 num_occurrences++;
1408 haystack_index += needle_len - 1;
1409 }
xbe9e1e8cd2014-03-12 22:57:16 -07001410 }
1411
1412 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1413}
1414
Damien Georgeb035db32014-03-21 20:39:40 +00001415STATIC 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 +03001416 if (!is_str_or_bytes(self_in)) {
1417 assert(0);
1418 }
1419 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1420 if (self_type != mp_obj_get_type(arg)) {
1421 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001422 }
Damien Georgeb035db32014-03-21 20:39:40 +00001423
xbe613a8e32014-03-18 00:06:29 -07001424 GET_STR_DATA_LEN(self_in, str, str_len);
1425 GET_STR_DATA_LEN(arg, sep, sep_len);
1426
1427 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001428 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001429 }
Damien Georgeb035db32014-03-21 20:39:40 +00001430
1431 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1432
1433 if (direction > 0) {
1434 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001435 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001436 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001437 }
xbe613a8e32014-03-18 00:06:29 -07001438
xbe17a5a832014-03-23 23:31:58 -07001439 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1440 if (position_ptr != NULL) {
1441 machine_uint_t position = position_ptr - str;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001442 result[0] = str_new(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001443 result[1] = arg;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001444 result[2] = str_new(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001445 }
Damien Georgeb035db32014-03-21 20:39:40 +00001446
xbe0a6894c2014-03-21 01:12:26 -07001447 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001448}
1449
Damien Georgeb035db32014-03-21 20:39:40 +00001450STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1451 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001452}
xbe4504ea82014-03-19 00:46:14 -07001453
Damien Georgeb035db32014-03-21 20:39:40 +00001454STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1455 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001456}
1457
Paul Sokolovsky69135212014-05-10 19:47:41 +03001458enum { CASE_UPPER, CASE_LOWER };
1459
1460// Supposedly not too critical operations, so optimize for code size
1461STATIC mp_obj_t str_caseconv(int op, mp_obj_t self_in) {
1462 GET_STR_DATA_LEN(self_in, self_data, self_len);
1463 byte *data;
1464 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1465 for (int i = 0; i < self_len; i++) {
1466 if (op == CASE_UPPER) {
1467 *data++ = unichar_toupper(*self_data++);
1468 } else {
1469 *data++ = unichar_tolower(*self_data++);
1470 }
1471 }
1472 *data = 0;
1473 return mp_obj_str_builder_end(s);
1474}
1475
1476STATIC mp_obj_t str_lower(mp_obj_t self_in) {
1477 return str_caseconv(CASE_LOWER, self_in);
1478}
1479
1480STATIC mp_obj_t str_upper(mp_obj_t self_in) {
1481 return str_caseconv(CASE_UPPER, self_in);
1482}
1483
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001484#if MICROPY_CPYTHON_COMPAT
1485// These methods are superfluous in the presense of str() and bytes()
1486// constructors.
1487// TODO: should accept kwargs too
1488STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1489 mp_obj_t new_args[2];
1490 if (n_args == 1) {
1491 new_args[0] = args[0];
1492 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1493 args = new_args;
1494 n_args++;
1495 }
1496 return str_make_new(NULL, n_args, 0, args);
1497}
1498
1499// TODO: should accept kwargs too
1500STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1501 mp_obj_t new_args[2];
1502 if (n_args == 1) {
1503 new_args[0] = args[0];
1504 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1505 args = new_args;
1506 n_args++;
1507 }
1508 return bytes_make_new(NULL, n_args, 0, args);
1509}
1510#endif
1511
Damien George57a4b4f2014-04-18 22:29:21 +01001512STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1513 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001514 GET_STR_DATA_LEN(self_in, str_data, str_len);
1515 bufinfo->buf = (void*)str_data;
1516 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001517 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001518 return 0;
1519 } else {
1520 // can't write to a string
1521 bufinfo->buf = NULL;
1522 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001523 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001524 return 1;
1525 }
1526}
1527
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001528#if MICROPY_CPYTHON_COMPAT
1529STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1530STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1531#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001532STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001533STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001534STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1535STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001536STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1537STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001538STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001539STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1540STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001541STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1542STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001543STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001544STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001545STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001546STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001547STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001548STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1549STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Damiend99b0522013-12-21 18:17:45 +00001550
Damien George9b196cd2014-03-26 21:47:19 +00001551STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001552#if MICROPY_CPYTHON_COMPAT
1553 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1554 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1555#endif
Damien George9b196cd2014-03-26 21:47:19 +00001556 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1557 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001558 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1559 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001560 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1561 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001562 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001563 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1564 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001565 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1566 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001567 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1568 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1569 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1570 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1571 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001572 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1573 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001574};
Damien George97209d32014-01-07 15:58:30 +00001575
Damien George9b196cd2014-03-26 21:47:19 +00001576STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1577
Damien George3e1a5c12014-03-29 13:43:38 +00001578const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001579 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001580 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001581 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001582 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001583 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001584 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001585 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001586 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001587 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001588};
1589
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001590// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001591const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001592 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001593 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001594 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001595 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001596 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001597 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001598 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001599 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001600 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001601};
1602
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001603// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001604STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001605const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1606
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001607mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001608 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001609 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001610 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001611 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001612 byte *p = m_new(byte, len + 1);
1613 o->data = p;
1614 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001615 return o;
1616}
1617
Damien George5fa93b62014-01-22 14:35:10 +00001618mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001619 mp_obj_str_t *o = o_in;
1620 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001621 byte *p = (byte*)o->data;
1622 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001623 return o;
1624}
1625
Paul Sokolovskya47b64a2014-05-15 07:28:19 +03001626mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001627 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001628 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001629 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001630 if (data) {
1631 o->hash = qstr_compute_hash(data, len);
1632 byte *p = m_new(byte, len + 1);
1633 o->data = p;
1634 memcpy(p, data, len * sizeof(byte));
1635 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1636 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001637 return o;
1638}
1639
Damien George5fa93b62014-01-22 14:35:10 +00001640mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1641 qstr q = qstr_find_strn(data, len);
1642 if (q != MP_QSTR_NULL) {
1643 // qstr with this data already exists
1644 return MP_OBJ_NEW_QSTR(q);
1645 } else if (make_qstr_if_not_already) {
1646 // no existing qstr, make a new one
1647 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1648 } else {
1649 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001650 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001651 }
Damien George5fa93b62014-01-22 14:35:10 +00001652}
1653
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001654mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001655 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001656}
1657
Damien George5fa93b62014-01-22 14:35:10 +00001658bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1659 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1660 return s1 == s2;
1661 } else {
1662 GET_STR_HASH(s1, h1);
1663 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001664 // If any of hashes is 0, it means it's not valid
1665 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001666 return false;
1667 }
1668 GET_STR_DATA_LEN(s1, d1, l1);
1669 GET_STR_DATA_LEN(s2, d2, l2);
1670 if (l1 != l2) {
1671 return false;
1672 }
Damien George1e708fe2014-01-23 18:27:51 +00001673 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001674 }
Damien George5fa93b62014-01-22 14:35:10 +00001675}
1676
Damien Georgedeed0872014-04-06 11:11:15 +01001677STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001678 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 +00001679}
1680
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001681STATIC void arg_type_mixup() {
1682 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1683}
1684
Damien George5fa93b62014-01-22 14:35:10 +00001685uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001686 // TODO: This has too big overhead for hash accessor
1687 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001688 GET_STR_HASH(self_in, h);
1689 return h;
1690 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001691 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001692 }
1693}
1694
1695uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001696 // TODO This has a double check for the type, one in obj.c and one here
1697 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001698 GET_STR_LEN(self_in, l);
1699 return l;
1700 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001701 bad_implicit_conversion(self_in);
1702 }
1703}
1704
1705// use this if you will anyway convert the string to a qstr
1706// will be more efficient for the case where it's already a qstr
1707qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1708 if (MP_OBJ_IS_QSTR(self_in)) {
1709 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001710 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001711 mp_obj_str_t *self = self_in;
1712 return qstr_from_strn((char*)self->data, self->len);
1713 } else {
1714 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001715 }
1716}
1717
1718// only use this function if you need the str data to be zero terminated
1719// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1720const char *mp_obj_str_get_str(mp_obj_t self_in) {
1721 if (MP_OBJ_IS_STR(self_in)) {
1722 GET_STR_DATA_LEN(self_in, s, l);
1723 (void)l; // len unused
1724 return (const char*)s;
1725 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001726 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001727 }
1728}
1729
Damien George698ec212014-02-08 18:17:23 +00001730const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001731 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001732 GET_STR_DATA_LEN(self_in, s, l);
1733 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001734 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001735 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001736 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001737 }
Damiend99b0522013-12-21 18:17:45 +00001738}
xyb8cfc9f02014-01-05 18:47:51 +08001739
1740/******************************************************************************/
1741/* str iterator */
1742
1743typedef struct _mp_obj_str_it_t {
1744 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001745 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001746 machine_uint_t cur;
1747} mp_obj_str_it_t;
1748
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001749STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001750 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001751 GET_STR_DATA_LEN(self->str, str, len);
1752 if (self->cur < len) {
1753 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001754 self->cur += 1;
1755 return o_out;
1756 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001757 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001758 }
1759}
1760
Damien George3e1a5c12014-03-29 13:43:38 +00001761STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001762 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001763 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001764 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001765 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001766};
1767
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001768STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001769 mp_obj_str_it_t *self = self_in;
1770 GET_STR_DATA_LEN(self->str, str, len);
1771 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001772 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001773 self->cur += 1;
1774 return o_out;
1775 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001776 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001777 }
1778}
1779
Damien George3e1a5c12014-03-29 13:43:38 +00001780STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001781 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001782 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001783 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001784 .iternext = bytes_it_iternext,
1785};
1786
1787mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001788 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001789 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001790 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001791 o->cur = 0;
1792 return o;
1793}
1794
1795mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1796 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001797 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001798 o->str = str;
1799 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001800 return o;
1801}