blob: 61fda12a3f3573db8c611d10bdb19b7fc6b6cab9 [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 George6ac5dce2014-05-21 19:42:43 +0100299 return MP_OBJ_NULL; // op 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 George6ac5dce2014-05-21 19:42:43 +0100344 return MP_OBJ_NULL; // op 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 {
Damien George6ac5dce2014-05-21 19:42:43 +0100368 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100369 }
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 Sokolovskyc18ef2a2014-05-15 21:18:34 +0300609STATIC mp_obj_t str_startswith(uint n_args, const mp_obj_t *args) {
610 GET_STR_DATA_LEN(args[0], str, str_len);
611 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
612 uint index_val = 0;
613 if (n_args > 2) {
614 index_val = mp_get_index(&mp_type_str, str_len, args[2], true);
615 }
616 if (prefix_len + index_val > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200617 return mp_const_false;
618 }
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300619 return MP_BOOL(memcmp(str + index_val, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200620}
621
Paul Sokolovsky88107842014-04-26 06:20:08 +0300622enum { LSTRIP, RSTRIP, STRIP };
623
624STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800625 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300626 assert(is_str_or_bytes(args[0]));
627 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000628
629 const byte *chars_to_del;
630 uint chars_to_del_len;
631 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800632
633 if (n_args == 1) {
634 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000635 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800636 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300637 if (mp_obj_get_type(args[1]) != self_type) {
638 arg_type_mixup();
639 }
Damien George5fa93b62014-01-22 14:35:10 +0000640 GET_STR_DATA_LEN(args[1], s, l);
641 chars_to_del = s;
642 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800643 }
644
Damien George5fa93b62014-01-22 14:35:10 +0000645 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800646
xbec5538882014-03-16 17:58:35 -0700647 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800648 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700649 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300650 machine_uint_t i = 0;
651 machine_int_t delta = 1;
652 if (type == RSTRIP) {
653 i = orig_str_len - 1;
654 delta = -1;
655 }
656 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700657 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800658 if (!first_good_char_pos_set) {
659 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300660 if (type == LSTRIP) {
661 last_good_char_pos = orig_str_len - 1;
662 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300663 } else if (type == RSTRIP) {
664 first_good_char_pos = 0;
665 last_good_char_pos = i;
666 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300667 }
xbe7b0f39f2014-01-08 14:23:45 -0800668 first_good_char_pos_set = true;
669 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300670 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800671 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300672 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800673 }
674
675 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000676 // string is all whitespace, return ''
677 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800678 }
679
680 assert(last_good_char_pos >= first_good_char_pos);
681 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700682 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300683 return str_new(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800684}
685
Paul Sokolovsky88107842014-04-26 06:20:08 +0300686STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
687 return str_uni_strip(STRIP, n_args, args);
688}
689
690STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
691 return str_uni_strip(LSTRIP, n_args, args);
692}
693
694STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
695 return str_uni_strip(RSTRIP, n_args, args);
696}
697
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700698// Takes an int arg, but only parses unsigned numbers, and only changes
699// *num if at least one digit was parsed.
700static int str_to_int(const char *str, int *num) {
701 const char *s = str;
702 if (unichar_isdigit(*s)) {
703 *num = 0;
704 do {
705 *num = *num * 10 + (*s - '0');
706 s++;
707 }
708 while (unichar_isdigit(*s));
709 }
710 return s - str;
711}
712
713static bool isalignment(char ch) {
714 return ch && strchr("<>=^", ch) != NULL;
715}
716
717static bool istype(char ch) {
718 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
719}
720
721static bool arg_looks_integer(mp_obj_t arg) {
722 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
723}
724
725static bool arg_looks_numeric(mp_obj_t arg) {
726 return arg_looks_integer(arg)
727#if MICROPY_ENABLE_FLOAT
728 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
729#endif
730 ;
731}
732
Dave Hylandsc4029e52014-04-07 11:19:51 -0700733static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700734#if MICROPY_ENABLE_FLOAT
735 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700736
737 // TODO: Needs a way to construct an mpz integer from a float
738
739 mp_small_int_t num = mp_obj_get_float(arg);
740 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700741 }
742#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700743 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700744}
745
Damien George897fe0c2014-04-15 22:03:55 +0100746mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000747 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000748
Damien George5fa93b62014-01-22 14:35:10 +0000749 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700750 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000751 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700752 pfenv_t pfenv_vstr;
753 pfenv_vstr.data = vstr;
754 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
755
Damien George5fa93b62014-01-22 14:35:10 +0000756 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700757 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000758 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700759 if (str < top && *str == '}') {
760 vstr_add_char(vstr, '}');
761 continue;
762 }
Damien Georgeea13f402014-04-05 18:32:08 +0100763 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700764 }
765 if (*str != '{') {
766 vstr_add_char(vstr, *str);
767 continue;
768 }
769
770 str++;
771 if (str < top && *str == '{') {
772 vstr_add_char(vstr, '{');
773 continue;
774 }
775
776 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
777
778 vstr_t *field_name = NULL;
779 char conversion = '\0';
780 vstr_t *format_spec = NULL;
781
782 if (str < top && *str != '}' && *str != '!' && *str != ':') {
783 field_name = vstr_new();
784 while (str < top && *str != '}' && *str != '!' && *str != ':') {
785 vstr_add_char(field_name, *str++);
786 }
787 vstr_add_char(field_name, '\0');
788 }
789
790 // conversion ::= "r" | "s"
791
792 if (str < top && *str == '!') {
793 str++;
794 if (str < top && (*str == 'r' || *str == 's')) {
795 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200796 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100797 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 -0700798 }
799 }
800
801 if (str < top && *str == ':') {
802 str++;
803 // {:} is the same as {}, which is the same as {!s}
804 // This makes a difference when passing in a True or False
805 // '{}'.format(True) returns 'True'
806 // '{:d}'.format(True) returns '1'
807 // So we treat {:} as {} and this later gets treated to be {!s}
808 if (*str != '}') {
809 format_spec = vstr_new();
810 while (str < top && *str != '}') {
811 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000812 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700813 vstr_add_char(format_spec, '\0');
814 }
815 }
816 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100817 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700818 }
819 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100820 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700821 }
822
823 mp_obj_t arg = mp_const_none;
824
825 if (field_name) {
826 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100827 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 -0700828 }
Damien George3bb8bd82014-04-14 21:20:30 +0100829 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700830 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100831 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700832 }
833 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100834 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700835 }
836 arg = args[index + 1];
837 arg_i = -1;
838 vstr_free(field_name);
839 field_name = NULL;
840 } else {
841 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100842 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 -0700843 }
844 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100845 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700846 }
847 arg = args[arg_i + 1];
848 arg_i++;
849 }
850 if (!format_spec && !conversion) {
851 conversion = 's';
852 }
853 if (conversion) {
854 mp_print_kind_t print_kind;
855 if (conversion == 's') {
856 print_kind = PRINT_STR;
857 } else if (conversion == 'r') {
858 print_kind = PRINT_REPR;
859 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100860 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700861 }
862 vstr_t *arg_vstr = vstr_new();
863 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
864 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
865 vstr_free(arg_vstr);
866 }
867
868 char sign = '\0';
869 char fill = '\0';
870 char align = '\0';
871 int width = -1;
872 int precision = -1;
873 char type = '\0';
874 int flags = 0;
875
876 if (format_spec) {
877 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
878 //
879 // [[fill]align][sign][#][0][width][,][.precision][type]
880 // fill ::= <any character>
881 // align ::= "<" | ">" | "=" | "^"
882 // sign ::= "+" | "-" | " "
883 // width ::= integer
884 // precision ::= integer
885 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
886
887 const char *s = vstr_str(format_spec);
888 if (isalignment(*s)) {
889 align = *s++;
890 } else if (*s && isalignment(s[1])) {
891 fill = *s++;
892 align = *s++;
893 }
894 if (*s == '+' || *s == '-' || *s == ' ') {
895 if (*s == '+') {
896 flags |= PF_FLAG_SHOW_SIGN;
897 } else if (*s == ' ') {
898 flags |= PF_FLAG_SPACE_SIGN;
899 }
900 sign = *s++;
901 }
902 if (*s == '#') {
903 flags |= PF_FLAG_SHOW_PREFIX;
904 s++;
905 }
906 if (*s == '0') {
907 if (!align) {
908 align = '=';
909 }
910 if (!fill) {
911 fill = '0';
912 }
913 }
914 s += str_to_int(s, &width);
915 if (*s == ',') {
916 flags |= PF_FLAG_SHOW_COMMA;
917 s++;
918 }
919 if (*s == '.') {
920 s++;
921 s += str_to_int(s, &precision);
922 }
923 if (istype(*s)) {
924 type = *s++;
925 }
926 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100927 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700928 }
929 vstr_free(format_spec);
930 format_spec = NULL;
931 }
932 if (!align) {
933 if (arg_looks_numeric(arg)) {
934 align = '>';
935 } else {
936 align = '<';
937 }
938 }
939 if (!fill) {
940 fill = ' ';
941 }
942
943 if (sign) {
944 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100945 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700946 }
947 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100948 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000949 }
950 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700951 sign = '-';
952 }
953
954 switch (align) {
955 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
956 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
957 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
958 }
959
960 if (arg_looks_integer(arg)) {
961 switch (type) {
962 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100963 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700964 continue;
965
966 case 'c':
967 {
968 char ch = mp_obj_get_int(arg);
969 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
970 continue;
971 }
972
973 case '\0': // No explicit format type implies 'd'
974 case 'n': // I don't think we support locales in uPy so use 'd'
975 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100976 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700977 continue;
978
979 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700980 if (flags & PF_FLAG_SHOW_PREFIX) {
981 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
982 }
983
Damien Georgea12a0f72014-04-08 01:29:53 +0100984 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, '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 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100992 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700993 continue;
994
995 case 'e':
996 case 'E':
997 case 'f':
998 case 'F':
999 case 'g':
1000 case 'G':
1001 case '%':
1002 // The floating point formatters all work with anything that
1003 // looks like an integer
1004 break;
1005
1006 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001007 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001008 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
1009 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001010 }
Damien George70f33cd2014-04-02 17:06:05 +01001011
Dave Hylands22fe4d72014-04-02 12:07:31 -07001012 // NOTE: no else here. We need the e, f, g etc formats for integer
1013 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001014 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001015 if (!type) {
1016
1017 // Even though the docs say that an unspecified type is the same
1018 // as 'g', there is one subtle difference, when the exponent
1019 // is one less than the precision.
1020 //
1021 // '{:10.1}'.format(0.0) ==> '0e+00'
1022 // '{:10.1g}'.format(0.0) ==> '0'
1023 //
1024 // TODO: Figure out how to deal with this.
1025 //
1026 // A proper solution would involve adding a special flag
1027 // or something to format_float, and create a format_double
1028 // to deal with doubles. In order to fix this when using
1029 // sprintf, we'd need to use the e format and tweak the
1030 // returned result to strip trailing zeros like the g format
1031 // does.
1032 //
1033 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1034 // but with 1.e2 you get 1e+02 and 1.00e+02
1035 //
1036 // Stripping the trailing 0's (like g) does would make the
1037 // e format give us the right format.
1038 //
1039 // CPython sources say:
1040 // Omitted type specifier. Behaves in the same way as repr(x)
1041 // and str(x) if no precision is given, else like 'g', but with
1042 // at least one digit after the decimal point. */
1043
1044 type = 'g';
1045 }
1046 if (type == 'n') {
1047 type = 'g';
1048 }
1049
1050 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1051 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +01001052#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001053 case 'e':
1054 case 'E':
1055 case 'f':
1056 case 'F':
1057 case 'g':
1058 case 'G':
1059 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
1060 break;
1061
1062 case '%':
1063 flags |= PF_FLAG_ADD_PERCENT;
1064 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1065 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001066#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001067
1068 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001069 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001070 "Unknown format code '%c' for object of type 'float'",
1071 type, mp_obj_get_type_str(arg)));
1072 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001073 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001074 // arg doesn't look like a number
1075
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001076 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001077 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001078 }
Damien George70f33cd2014-04-02 17:06:05 +01001079
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001080 switch (type) {
1081 case '\0':
1082 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1083 break;
1084
1085 case 's':
1086 {
1087 uint len;
1088 const char *s = mp_obj_str_get_data(arg, &len);
1089 if (precision < 0) {
1090 precision = len;
1091 }
1092 if (len > precision) {
1093 len = precision;
1094 }
1095 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1096 break;
1097 }
1098
1099 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001100 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001101 "Unknown format code '%c' for object of type 'str'",
1102 type, mp_obj_get_type_str(arg)));
1103 }
Damiend99b0522013-12-21 18:17:45 +00001104 }
1105 }
1106
Damien George5fa93b62014-01-22 14:35:10 +00001107 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1108 vstr_free(vstr);
1109 return s;
Damiend99b0522013-12-21 18:17:45 +00001110}
1111
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001112STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
1113 assert(MP_OBJ_IS_STR(pattern));
1114
1115 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001116 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001117 int arg_i = 0;
1118 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001119 pfenv_t pfenv_vstr;
1120 pfenv_vstr.data = vstr;
1121 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1122
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001123 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -07001124 if (*str != '%') {
1125 vstr_add_char(vstr, *str);
1126 continue;
1127 }
1128 if (++str >= top) {
1129 break;
1130 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001131 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001132 vstr_add_char(vstr, '%');
1133 continue;
1134 }
1135 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001136 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -07001137 }
1138 int flags = 0;
1139 char fill = ' ';
1140 bool alt = false;
1141 while (str < top) {
1142 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1143 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1144 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1145 else if (*str == '#') alt = true;
1146 else if (*str == '0') {
1147 flags |= PF_FLAG_PAD_AFTER_SIGN;
1148 fill = '0';
1149 } else break;
1150 str++;
1151 }
1152 // parse width, if it exists
1153 int width = 0;
1154 if (str < top) {
1155 if (*str == '*') {
1156 width = mp_obj_get_int(args[arg_i++]);
1157 str++;
1158 } else {
1159 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1160 width = width * 10 + *str - '0';
1161 }
1162 }
1163 }
1164 int prec = -1;
1165 if (str < top && *str == '.') {
1166 if (++str < top) {
1167 if (*str == '*') {
1168 prec = mp_obj_get_int(args[arg_i++]);
1169 str++;
1170 } else {
1171 prec = 0;
1172 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1173 prec = prec * 10 + *str - '0';
1174 }
1175 }
1176 }
1177 }
1178
1179 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001180 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001181 }
1182 mp_obj_t arg = args[arg_i];
1183 switch (*str) {
1184 case 'c':
1185 if (MP_OBJ_IS_STR(arg)) {
1186 uint len;
1187 const char *s = mp_obj_str_get_data(arg, &len);
1188 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001189 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001190 break;
1191 }
1192 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1193 break;
1194 }
1195 if (arg_looks_integer(arg)) {
1196 char ch = mp_obj_get_int(arg);
1197 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1198 break;
1199 }
1200#if MICROPY_ENABLE_FLOAT
1201 // This is what CPython reports, so we report the same.
1202 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001203 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001204
1205 }
1206#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001207 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001208 break;
1209
1210 case 'd':
1211 case 'i':
1212 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001213 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001214 break;
1215
1216#if MICROPY_ENABLE_FLOAT
1217 case 'e':
1218 case 'E':
1219 case 'f':
1220 case 'F':
1221 case 'g':
1222 case 'G':
1223 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1224 break;
1225#endif
1226
1227 case 'o':
1228 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001229 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001230 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001231 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001232 break;
1233
1234 case 'r':
1235 case 's':
1236 {
1237 vstr_t *arg_vstr = vstr_new();
1238 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1239 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1240 uint len = vstr_len(arg_vstr);
1241 if (prec < 0) {
1242 prec = len;
1243 }
1244 if (len > prec) {
1245 len = prec;
1246 }
1247 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1248 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001249 break;
1250 }
Dave Hylands6756a372014-04-02 11:42:39 -07001251
1252 case 'x':
1253 if (alt) {
1254 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001255 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001256 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001257 break;
1258
1259 case 'X':
1260 if (alt) {
1261 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001262 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001263 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001264 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001265
Dave Hylands6756a372014-04-02 11:42:39 -07001266 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001267 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001268 "unsupported format character '%c' (0x%x) at index %d",
1269 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001270 }
Dave Hylands6756a372014-04-02 11:42:39 -07001271 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001272 }
1273
1274 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001275 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001276 }
1277
1278 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1279 vstr_free(vstr);
1280 return s;
1281}
1282
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001283STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001284 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001285
Damien Georgeff715422014-04-07 00:39:13 +01001286 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001287 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001288 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001289 if (max_rep == 0) {
1290 return args[0];
1291 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001292 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001293 }
xbe480c15a2014-01-30 22:17:30 -08001294 }
Damien George94f68302014-01-31 23:45:12 +00001295
xbe729be9b2014-04-07 14:46:39 -07001296 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001297
Damien Georgeff715422014-04-07 00:39:13 +01001298 // check argument types
1299
1300 if (!MP_OBJ_IS_STR(args[1])) {
1301 bad_implicit_conversion(args[1]);
1302 }
1303
1304 if (!MP_OBJ_IS_STR(args[2])) {
1305 bad_implicit_conversion(args[2]);
1306 }
1307
1308 // extract string data
1309
xbe480c15a2014-01-30 22:17:30 -08001310 GET_STR_DATA_LEN(args[0], str, str_len);
1311 GET_STR_DATA_LEN(args[1], old, old_len);
1312 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001313
1314 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001315 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001316 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001317 }
1318
Damien George94f68302014-01-31 23:45:12 +00001319 // data for the replaced string
1320 byte *data = NULL;
1321 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001322
Damien George94f68302014-01-31 23:45:12 +00001323 // do 2 passes over the string:
1324 // first pass computes the required length of the replaced string
1325 // second pass does the replacements
1326 for (;;) {
1327 machine_uint_t replaced_str_index = 0;
1328 machine_uint_t num_replacements_done = 0;
1329 const byte *old_occurrence;
1330 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001331 machine_uint_t str_len_remain = str_len;
1332 if (old_len == 0) {
1333 // if old_str is empty, copy new_str to start of replaced string
1334 // copy the replacement string
1335 if (data != NULL) {
1336 memcpy(data, new, new_len);
1337 }
1338 replaced_str_index += new_len;
1339 num_replacements_done++;
1340 }
1341 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1342 if (old_len == 0) {
1343 old_occurrence += 1;
1344 }
Damien George94f68302014-01-31 23:45:12 +00001345 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1346 if (data != NULL) {
1347 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1348 }
1349 replaced_str_index += old_occurrence - offset_ptr;
1350 // copy the replacement string
1351 if (data != NULL) {
1352 memcpy(data + replaced_str_index, new, new_len);
1353 }
1354 replaced_str_index += new_len;
1355 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001356 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001357 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001358 }
1359
1360 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1361 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001362 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001363 }
Damien Georgeff715422014-04-07 00:39:13 +01001364 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001365
1366 if (data == NULL) {
1367 // first pass
1368 if (num_replacements_done == 0) {
1369 // no substr found, return original string
1370 return args[0];
1371 } else {
1372 // substr found, allocate new string
1373 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001374 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001375 }
1376 } else {
1377 // second pass, we are done
1378 break;
1379 }
xbe480c15a2014-01-30 22:17:30 -08001380 }
Damien George94f68302014-01-31 23:45:12 +00001381
xbe480c15a2014-01-30 22:17:30 -08001382 return mp_obj_str_builder_end(replaced_str);
1383}
1384
xbe9e1e8cd2014-03-12 22:57:16 -07001385STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1386 assert(2 <= n_args && n_args <= 4);
1387 assert(MP_OBJ_IS_STR(args[0]));
1388 assert(MP_OBJ_IS_STR(args[1]));
1389
1390 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1391 GET_STR_DATA_LEN(args[1], needle, needle_len);
1392
Damien George536dde22014-03-13 22:07:55 +00001393 machine_uint_t start = 0;
1394 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001395 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001396 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001397 }
1398 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001399 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001400 }
1401
Damien George536dde22014-03-13 22:07:55 +00001402 // if needle_len is zero then we count each gap between characters as an occurrence
1403 if (needle_len == 0) {
1404 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001405 }
1406
Damien George536dde22014-03-13 22:07:55 +00001407 // count the occurrences
1408 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001409 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1410 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1411 num_occurrences++;
1412 haystack_index += needle_len - 1;
1413 }
xbe9e1e8cd2014-03-12 22:57:16 -07001414 }
1415
1416 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1417}
1418
Damien Georgeb035db32014-03-21 20:39:40 +00001419STATIC 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 +03001420 if (!is_str_or_bytes(self_in)) {
1421 assert(0);
1422 }
1423 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1424 if (self_type != mp_obj_get_type(arg)) {
1425 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001426 }
Damien Georgeb035db32014-03-21 20:39:40 +00001427
xbe613a8e32014-03-18 00:06:29 -07001428 GET_STR_DATA_LEN(self_in, str, str_len);
1429 GET_STR_DATA_LEN(arg, sep, sep_len);
1430
1431 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001432 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001433 }
Damien Georgeb035db32014-03-21 20:39:40 +00001434
1435 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1436
1437 if (direction > 0) {
1438 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001439 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001440 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001441 }
xbe613a8e32014-03-18 00:06:29 -07001442
xbe17a5a832014-03-23 23:31:58 -07001443 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1444 if (position_ptr != NULL) {
1445 machine_uint_t position = position_ptr - str;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001446 result[0] = str_new(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001447 result[1] = arg;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001448 result[2] = str_new(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001449 }
Damien Georgeb035db32014-03-21 20:39:40 +00001450
xbe0a6894c2014-03-21 01:12:26 -07001451 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001452}
1453
Damien Georgeb035db32014-03-21 20:39:40 +00001454STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1455 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001456}
xbe4504ea82014-03-19 00:46:14 -07001457
Damien Georgeb035db32014-03-21 20:39:40 +00001458STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1459 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001460}
1461
Paul Sokolovsky69135212014-05-10 19:47:41 +03001462enum { CASE_UPPER, CASE_LOWER };
1463
1464// Supposedly not too critical operations, so optimize for code size
1465STATIC mp_obj_t str_caseconv(int op, mp_obj_t self_in) {
1466 GET_STR_DATA_LEN(self_in, self_data, self_len);
1467 byte *data;
1468 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1469 for (int i = 0; i < self_len; i++) {
1470 if (op == CASE_UPPER) {
1471 *data++ = unichar_toupper(*self_data++);
1472 } else {
1473 *data++ = unichar_tolower(*self_data++);
1474 }
1475 }
1476 *data = 0;
1477 return mp_obj_str_builder_end(s);
1478}
1479
1480STATIC mp_obj_t str_lower(mp_obj_t self_in) {
1481 return str_caseconv(CASE_LOWER, self_in);
1482}
1483
1484STATIC mp_obj_t str_upper(mp_obj_t self_in) {
1485 return str_caseconv(CASE_UPPER, self_in);
1486}
1487
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001488#if MICROPY_CPYTHON_COMPAT
1489// These methods are superfluous in the presense of str() and bytes()
1490// constructors.
1491// TODO: should accept kwargs too
1492STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1493 mp_obj_t new_args[2];
1494 if (n_args == 1) {
1495 new_args[0] = args[0];
1496 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1497 args = new_args;
1498 n_args++;
1499 }
1500 return str_make_new(NULL, n_args, 0, args);
1501}
1502
1503// TODO: should accept kwargs too
1504STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1505 mp_obj_t new_args[2];
1506 if (n_args == 1) {
1507 new_args[0] = args[0];
1508 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1509 args = new_args;
1510 n_args++;
1511 }
1512 return bytes_make_new(NULL, n_args, 0, args);
1513}
1514#endif
1515
Damien George57a4b4f2014-04-18 22:29:21 +01001516STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1517 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001518 GET_STR_DATA_LEN(self_in, str_data, str_len);
1519 bufinfo->buf = (void*)str_data;
1520 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001521 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001522 return 0;
1523 } else {
1524 // can't write to a string
1525 bufinfo->buf = NULL;
1526 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001527 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001528 return 1;
1529 }
1530}
1531
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001532#if MICROPY_CPYTHON_COMPAT
1533STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1534STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1535#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001536STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001537STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001538STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1539STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001540STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1541STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001542STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +03001543STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001544STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001545STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1546STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001547STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001548STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001549STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001550STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001551STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001552STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1553STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Damiend99b0522013-12-21 18:17:45 +00001554
Damien George9b196cd2014-03-26 21:47:19 +00001555STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001556#if MICROPY_CPYTHON_COMPAT
1557 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1558 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1559#endif
Damien George9b196cd2014-03-26 21:47:19 +00001560 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1561 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001562 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1563 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001564 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1565 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001566 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001567 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1568 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001569 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1570 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001571 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1572 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1573 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1574 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1575 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001576 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1577 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001578};
Damien George97209d32014-01-07 15:58:30 +00001579
Damien George9b196cd2014-03-26 21:47:19 +00001580STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1581
Damien George3e1a5c12014-03-29 13:43:38 +00001582const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001583 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001584 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001585 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001586 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001587 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001588 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001589 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001590 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001591 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001592};
1593
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001594// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001595const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001596 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001597 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001598 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001599 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001600 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001601 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001602 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001603 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001604 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001605};
1606
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001607// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001608STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001609const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1610
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001611mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001612 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001613 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001614 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001615 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001616 byte *p = m_new(byte, len + 1);
1617 o->data = p;
1618 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001619 return o;
1620}
1621
Damien George5fa93b62014-01-22 14:35:10 +00001622mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001623 mp_obj_str_t *o = o_in;
1624 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001625 byte *p = (byte*)o->data;
1626 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001627 return o;
1628}
1629
Paul Sokolovskya47b64a2014-05-15 07:28:19 +03001630mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001631 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001632 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001633 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001634 if (data) {
1635 o->hash = qstr_compute_hash(data, len);
1636 byte *p = m_new(byte, len + 1);
1637 o->data = p;
1638 memcpy(p, data, len * sizeof(byte));
1639 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1640 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001641 return o;
1642}
1643
Damien George5fa93b62014-01-22 14:35:10 +00001644mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1645 qstr q = qstr_find_strn(data, len);
1646 if (q != MP_QSTR_NULL) {
1647 // qstr with this data already exists
1648 return MP_OBJ_NEW_QSTR(q);
1649 } else if (make_qstr_if_not_already) {
1650 // no existing qstr, make a new one
1651 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1652 } else {
1653 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001654 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001655 }
Damien George5fa93b62014-01-22 14:35:10 +00001656}
1657
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001658mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001659 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001660}
1661
Damien George5fa93b62014-01-22 14:35:10 +00001662bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1663 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1664 return s1 == s2;
1665 } else {
1666 GET_STR_HASH(s1, h1);
1667 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001668 // If any of hashes is 0, it means it's not valid
1669 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001670 return false;
1671 }
1672 GET_STR_DATA_LEN(s1, d1, l1);
1673 GET_STR_DATA_LEN(s2, d2, l2);
1674 if (l1 != l2) {
1675 return false;
1676 }
Damien George1e708fe2014-01-23 18:27:51 +00001677 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001678 }
Damien George5fa93b62014-01-22 14:35:10 +00001679}
1680
Damien Georgedeed0872014-04-06 11:11:15 +01001681STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001682 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 +00001683}
1684
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001685STATIC void arg_type_mixup() {
1686 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1687}
1688
Damien George5fa93b62014-01-22 14:35:10 +00001689uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001690 // TODO: This has too big overhead for hash accessor
1691 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001692 GET_STR_HASH(self_in, h);
1693 return h;
1694 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001695 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001696 }
1697}
1698
1699uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001700 // TODO This has a double check for the type, one in obj.c and one here
1701 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001702 GET_STR_LEN(self_in, l);
1703 return l;
1704 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001705 bad_implicit_conversion(self_in);
1706 }
1707}
1708
1709// use this if you will anyway convert the string to a qstr
1710// will be more efficient for the case where it's already a qstr
1711qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1712 if (MP_OBJ_IS_QSTR(self_in)) {
1713 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001714 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001715 mp_obj_str_t *self = self_in;
1716 return qstr_from_strn((char*)self->data, self->len);
1717 } else {
1718 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001719 }
1720}
1721
1722// only use this function if you need the str data to be zero terminated
1723// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1724const char *mp_obj_str_get_str(mp_obj_t self_in) {
1725 if (MP_OBJ_IS_STR(self_in)) {
1726 GET_STR_DATA_LEN(self_in, s, l);
1727 (void)l; // len unused
1728 return (const char*)s;
1729 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001730 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001731 }
1732}
1733
Damien George698ec212014-02-08 18:17:23 +00001734const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001735 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001736 GET_STR_DATA_LEN(self_in, s, l);
1737 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001738 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001739 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001740 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001741 }
Damiend99b0522013-12-21 18:17:45 +00001742}
xyb8cfc9f02014-01-05 18:47:51 +08001743
1744/******************************************************************************/
1745/* str iterator */
1746
1747typedef struct _mp_obj_str_it_t {
1748 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001749 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001750 machine_uint_t cur;
1751} mp_obj_str_it_t;
1752
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001753STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001754 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001755 GET_STR_DATA_LEN(self->str, str, len);
1756 if (self->cur < len) {
1757 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001758 self->cur += 1;
1759 return o_out;
1760 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001761 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001762 }
1763}
1764
Damien George3e1a5c12014-03-29 13:43:38 +00001765STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001766 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001767 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001768 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001769 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001770};
1771
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001772STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001773 mp_obj_str_it_t *self = self_in;
1774 GET_STR_DATA_LEN(self->str, str, len);
1775 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001776 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001777 self->cur += 1;
1778 return o_out;
1779 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001780 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001781 }
1782}
1783
Damien George3e1a5c12014-03-29 13:43:38 +00001784STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001785 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001786 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001787 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001788 .iternext = bytes_it_iternext,
1789};
1790
1791mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001792 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001793 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001794 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001795 o->cur = 0;
1796 return o;
1797}
1798
1799mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1800 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001801 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001802 o->str = str;
1803 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001804 return o;
1805}