blob: 3a4b0b97f37ebe44defd8415bda0234bdd42b33b [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"
Damiend99b0522013-12-21 18:17:45 +000041
Paul Sokolovsky4db727a2014-03-31 21:18:28 +030042STATIC 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 +020043const mp_obj_t mp_const_empty_bytes;
44
Damien George5fa93b62014-01-22 14:35:10 +000045// use this macro to extract the string hash
46#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; }
47
48// use this macro to extract the string length
49#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; }
50
51// use this macro to extract the string data and length
52#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; }
53
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020054STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
55STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskybe020c22014-03-21 11:39:01 +020056STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len);
Paul Sokolovskye9085912014-04-30 05:35:18 +030057STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030058STATIC NORETURN void arg_type_mixup();
59
60STATIC bool is_str_or_bytes(mp_obj_t o) {
61 return MP_OBJ_IS_STR(o) || MP_OBJ_IS_TYPE(o, &mp_type_bytes);
62}
xyb8cfc9f02014-01-05 18:47:51 +080063
64/******************************************************************************/
65/* str */
66
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020067void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
68 // this escapes characters, but it will be very slow to print (calling print many times)
69 bool has_single_quote = false;
70 bool has_double_quote = false;
71 for (const byte *s = str_data, *top = str_data + str_len; (!has_single_quote || !has_double_quote) && s < top; s++) {
72 if (*s == '\'') {
73 has_single_quote = true;
74 } else if (*s == '"') {
75 has_double_quote = true;
76 }
77 }
78 int quote_char = '\'';
79 if (has_single_quote && !has_double_quote) {
80 quote_char = '"';
81 }
82 print(env, "%c", quote_char);
83 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
84 if (*s == quote_char) {
85 print(env, "\\%c", quote_char);
86 } else if (*s == '\\') {
87 print(env, "\\\\");
88 } else if (32 <= *s && *s <= 126) {
89 print(env, "%c", *s);
90 } else if (*s == '\n') {
91 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010092 } else if (*s == '\r') {
93 print(env, "\\r");
94 } else if (*s == '\t') {
95 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020096 } else {
97 print(env, "\\x%02x", *s);
98 }
99 }
100 print(env, "%c", quote_char);
101}
102
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200103STATIC 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 +0000104 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000105 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200106 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000107 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200108 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200109 if (is_bytes) {
110 print(env, "b");
111 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +0200112 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200113 }
Damiend99b0522013-12-21 18:17:45 +0000114}
115
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200116STATIC 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 +0300117#if MICROPY_CPYTHON_COMPAT
118 if (n_kw != 0) {
119 mp_arg_error_unimpl_kw();
120 }
121#endif
122
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200123 switch (n_args) {
124 case 0:
125 return MP_OBJ_NEW_QSTR(MP_QSTR_);
126
127 case 1:
128 {
129 vstr_t *vstr = vstr_new();
130 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
131 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
132 vstr_free(vstr);
133 return s;
134 }
135
136 case 2:
137 case 3:
138 {
139 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000140 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100141 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200142 }
143 GET_STR_DATA_LEN(args[0], str_data, str_len);
144 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000145 mp_obj_str_t *o = str_new(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200146 o->data = str_data;
147 o->hash = str_hash;
148 return o;
149 }
150
151 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100152 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200153 }
154}
155
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200156STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
157 if (n_args == 0) {
158 return mp_const_empty_bytes;
159 }
160
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300161#if MICROPY_CPYTHON_COMPAT
162 if (n_kw != 0) {
163 mp_arg_error_unimpl_kw();
164 }
165#endif
166
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200167 if (MP_OBJ_IS_STR(args[0])) {
168 if (n_args < 2 || n_args > 3) {
169 goto wrong_args;
170 }
171 GET_STR_DATA_LEN(args[0], str_data, str_len);
172 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000173 mp_obj_str_t *o = str_new(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200174 o->data = str_data;
175 o->hash = str_hash;
176 return o;
177 }
178
179 if (n_args > 1) {
180 goto wrong_args;
181 }
182
183 if (MP_OBJ_IS_SMALL_INT(args[0])) {
184 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
185 byte *data;
186
Damien George3e1a5c12014-03-29 13:43:38 +0000187 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200188 memset(data, 0, len);
189 return mp_obj_str_builder_end(o);
190 }
191
192 int len;
193 byte *data;
194 vstr_t *vstr = NULL;
195 mp_obj_t o = NULL;
196 // Try to create array of exact len if initializer len is known
197 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
198 if (len_in == MP_OBJ_NULL) {
199 len = -1;
200 vstr = vstr_new();
201 } else {
202 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000203 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200204 }
205
Damien Georged17926d2014-03-30 13:35:08 +0100206 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200207 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100208 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200209 if (len == -1) {
210 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
211 } else {
212 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
213 }
214 }
215
216 if (len == -1) {
217 vstr_shrink(vstr);
218 // TODO: Optimize, borrow buffer from vstr
219 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000220 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200221 memcpy(data, vstr_str(vstr), len);
222 vstr_free(vstr);
223 }
224
225 return mp_obj_str_builder_end(o);
226
227wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100228 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200229}
230
Damien George55baff42014-01-21 21:40:13 +0000231// like strstr but with specified length and allows \0 bytes
232// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700233STATIC 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 +0000234 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700235 machine_uint_t str_index, str_index_end;
236 if (direction > 0) {
237 str_index = 0;
238 str_index_end = hlen - nlen;
239 } else {
240 str_index = hlen - nlen;
241 str_index_end = 0;
242 }
243 for (;;) {
244 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
245 //found
246 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000247 }
xbe17a5a832014-03-23 23:31:58 -0700248 if (str_index == str_index_end) {
249 //not found
250 break;
Damien George55baff42014-01-21 21:40:13 +0000251 }
xbe17a5a832014-03-23 23:31:58 -0700252 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000253 }
254 }
255 return NULL;
256}
257
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200258STATIC 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 +0000259 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300260 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
261 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000262 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100263 case MP_BINARY_OP_ADD:
264 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300265 if (lhs_type == rhs_type) {
266 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000267
268 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000269 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000270
271 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000272 byte *q_ptr;
273 byte *val = qstr_build_start(alloc_len, &q_ptr);
274 memcpy(val, lhs_data, lhs_len);
275 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000276 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
277 */
278
279 // code for non-qstr
280 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300281 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000282 memcpy(data, lhs_data, lhs_len);
283 memcpy(data + lhs_len, rhs_data, rhs_len);
284 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000285 }
286 break;
Damien George5fa93b62014-01-22 14:35:10 +0000287
Damien Georged17926d2014-03-30 13:35:08 +0100288 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000289 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300290 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000291 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700292 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000293 }
294 break;
Damien George5fa93b62014-01-22 14:35:10 +0000295
Damien Georged0a5bf32014-05-10 13:55:11 +0100296 case MP_BINARY_OP_MULTIPLY: {
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200297 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
Damien Georged0a5bf32014-05-10 13:55:11 +0100298 return MP_OBJ_NOT_SUPPORTED;
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200299 }
300 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000301 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300302 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000303 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
304 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200305 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200306
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300307 case MP_BINARY_OP_MODULO: {
308 mp_obj_t *args;
309 uint n_args;
310 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
311 // TODO: Support tuple subclasses?
312 mp_obj_tuple_get(rhs_in, &n_args, &args);
313 } else {
314 args = &rhs_in;
315 n_args = 1;
316 }
317 return str_modulo_format(lhs_in, n_args, args);
318 }
319
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300320 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
321 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 +0100322 case MP_BINARY_OP_LESS:
323 case MP_BINARY_OP_LESS_EQUAL:
324 case MP_BINARY_OP_MORE:
325 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300326 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200327 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
328 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
329 }
Damiend99b0522013-12-21 18:17:45 +0000330 }
331
Damien Georgeea8d06c2014-04-17 23:19:36 +0100332 return MP_OBJ_NOT_SUPPORTED;
Damiend99b0522013-12-21 18:17:45 +0000333}
334
Damien George729f7b42014-04-17 22:10:53 +0100335STATIC 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 +0300336 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100337 GET_STR_DATA_LEN(self_in, self_data, self_len);
338 if (value == MP_OBJ_SENTINEL) {
339 // load
340#if MICROPY_ENABLE_SLICE
341 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
342 machine_uint_t start, stop;
Paul Sokolovskyd915a522014-05-10 21:36:33 +0300343 if (!mp_seq_get_fast_slice_indexes(self_len, index, &start, &stop)) {
Damien George729f7b42014-04-17 22:10:53 +0100344 assert(0);
345 }
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300346 return str_new(type, self_data + start, stop - start);
Damien George729f7b42014-04-17 22:10:53 +0100347 }
348#endif
Damien George729f7b42014-04-17 22:10:53 +0100349 uint index_val = mp_get_index(type, self_len, index, false);
350 if (type == &mp_type_bytes) {
351 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)self_data[index_val]);
352 } else {
353 return mp_obj_new_str(self_data + index_val, 1, true);
354 }
355 } else {
356 return MP_OBJ_NOT_SUPPORTED;
357 }
358}
359
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200360STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300361 assert(is_str_or_bytes(self_in));
362 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000363
Damien Georgefe8fb912014-01-02 16:36:09 +0000364 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000365 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000366
367 // process args
Damiend99b0522013-12-21 18:17:45 +0000368 uint seq_len;
369 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000370 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000371 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000372 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100373 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
374 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300375 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100376 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
377 }
378 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000379 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000380
381 // count required length
382 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000383 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300384 if (mp_obj_get_type(seq_items[i]) != self_type) {
385 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
386 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000387 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000388 if (i > 0) {
389 required_len += sep_len;
390 }
Damien George5fa93b62014-01-22 14:35:10 +0000391 GET_STR_LEN(seq_items[i], l);
392 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000393 }
394
395 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000396 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300397 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000398 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000399 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000400 memcpy(data, sep_str, sep_len);
401 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000402 }
Damien George5fa93b62014-01-22 14:35:10 +0000403 GET_STR_DATA_LEN(seq_items[i], s, l);
404 memcpy(data, s, l);
405 data += l;
Damiend99b0522013-12-21 18:17:45 +0000406 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000407
408 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000409 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000410}
411
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200412#define is_ws(c) ((c) == ' ' || (c) == '\t')
413
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200414STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300415 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien Georgedeed0872014-04-06 11:11:15 +0100416 machine_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200417 mp_obj_t sep = mp_const_none;
418 if (n_args > 1) {
419 sep = args[1];
420 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100421 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200422 }
423 }
Damien Georgedeed0872014-04-06 11:11:15 +0100424
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200425 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000426 GET_STR_DATA_LEN(args[0], s, len);
427 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200428
Damien Georgedeed0872014-04-06 11:11:15 +0100429 if (sep == mp_const_none) {
430 // sep not given, so separate on whitespace
431
432 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000433 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100434 while (s < top && splits != 0) {
435 const byte *start = s;
436 while (s < top && !is_ws(*s)) s++;
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300437 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100438 if (s >= top) {
439 break;
440 }
441 while (s < top && is_ws(*s)) s++;
442 if (splits > 0) {
443 splits--;
444 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200445 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200446
Damien Georgedeed0872014-04-06 11:11:15 +0100447 if (s < top) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300448 mp_obj_list_append(res, str_new(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100449 }
450
451 } else {
452 // sep given
453
454 uint sep_len;
455 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
456
457 if (sep_len == 0) {
458 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
459 }
460
461 for (;;) {
462 const byte *start = s;
463 for (;;) {
464 if (splits == 0 || s + sep_len > top) {
465 s = top;
466 break;
467 } else if (memcmp(s, sep_str, sep_len) == 0) {
468 break;
469 }
470 s++;
471 }
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300472 mp_obj_list_append(res, str_new(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100473 if (s >= top) {
474 break;
475 }
476 s += sep_len;
477 if (splits > 0) {
478 splits--;
479 }
480 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200481 }
482
483 return res;
484}
485
xbe3d9a39e2014-04-08 11:42:19 -0700486STATIC 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 +0000487 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000488 assert(MP_OBJ_IS_STR(args[0]));
489 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000490
Damien George5fa93b62014-01-22 14:35:10 +0000491 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
492 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000493
xbec5538882014-03-16 17:58:35 -0700494 machine_uint_t start = 0;
495 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000496 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000497 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000498 }
499 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000500 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000501 }
502
xbe17a5a832014-03-23 23:31:58 -0700503 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000504 if (p == NULL) {
505 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700506 if (is_index) {
507 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
508 } else {
509 return MP_OBJ_NEW_SMALL_INT(-1);
510 }
Damien George23005372014-01-13 19:39:01 +0000511 } else {
512 // found
xbe17a5a832014-03-23 23:31:58 -0700513 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000514 }
John R. Lentone8204912014-01-12 21:53:52 +0000515}
516
xbe17a5a832014-03-23 23:31:58 -0700517STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700518 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700519}
520
521STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700522 return str_finder(n_args, args, -1, false);
523}
524
525STATIC mp_obj_t str_index(uint n_args, const mp_obj_t *args) {
526 return str_finder(n_args, args, 1, true);
527}
528
529STATIC mp_obj_t str_rindex(uint n_args, const mp_obj_t *args) {
530 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700531}
532
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200533// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200534STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200535 GET_STR_DATA_LEN(self_in, str, str_len);
536 GET_STR_DATA_LEN(arg, prefix, prefix_len);
537 if (prefix_len > str_len) {
538 return mp_const_false;
539 }
540 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
541}
542
Paul Sokolovsky88107842014-04-26 06:20:08 +0300543enum { LSTRIP, RSTRIP, STRIP };
544
545STATIC mp_obj_t str_uni_strip(int type, uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800546 assert(1 <= n_args && n_args <= 2);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300547 assert(is_str_or_bytes(args[0]));
548 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000549
550 const byte *chars_to_del;
551 uint chars_to_del_len;
552 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800553
554 if (n_args == 1) {
555 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000556 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800557 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300558 if (mp_obj_get_type(args[1]) != self_type) {
559 arg_type_mixup();
560 }
Damien George5fa93b62014-01-22 14:35:10 +0000561 GET_STR_DATA_LEN(args[1], s, l);
562 chars_to_del = s;
563 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800564 }
565
Damien George5fa93b62014-01-22 14:35:10 +0000566 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800567
xbec5538882014-03-16 17:58:35 -0700568 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800569 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700570 machine_uint_t last_good_char_pos = 0;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300571 machine_uint_t i = 0;
572 machine_int_t delta = 1;
573 if (type == RSTRIP) {
574 i = orig_str_len - 1;
575 delta = -1;
576 }
577 for (machine_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700578 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800579 if (!first_good_char_pos_set) {
580 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300581 if (type == LSTRIP) {
582 last_good_char_pos = orig_str_len - 1;
583 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300584 } else if (type == RSTRIP) {
585 first_good_char_pos = 0;
586 last_good_char_pos = i;
587 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300588 }
xbe7b0f39f2014-01-08 14:23:45 -0800589 first_good_char_pos_set = true;
590 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300591 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800592 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300593 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800594 }
595
596 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000597 // string is all whitespace, return ''
598 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800599 }
600
601 assert(last_good_char_pos >= first_good_char_pos);
602 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700603 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300604 return str_new(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800605}
606
Paul Sokolovsky88107842014-04-26 06:20:08 +0300607STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
608 return str_uni_strip(STRIP, n_args, args);
609}
610
611STATIC mp_obj_t str_lstrip(uint n_args, const mp_obj_t *args) {
612 return str_uni_strip(LSTRIP, n_args, args);
613}
614
615STATIC mp_obj_t str_rstrip(uint n_args, const mp_obj_t *args) {
616 return str_uni_strip(RSTRIP, n_args, args);
617}
618
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700619// Takes an int arg, but only parses unsigned numbers, and only changes
620// *num if at least one digit was parsed.
621static int str_to_int(const char *str, int *num) {
622 const char *s = str;
623 if (unichar_isdigit(*s)) {
624 *num = 0;
625 do {
626 *num = *num * 10 + (*s - '0');
627 s++;
628 }
629 while (unichar_isdigit(*s));
630 }
631 return s - str;
632}
633
634static bool isalignment(char ch) {
635 return ch && strchr("<>=^", ch) != NULL;
636}
637
638static bool istype(char ch) {
639 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
640}
641
642static bool arg_looks_integer(mp_obj_t arg) {
643 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
644}
645
646static bool arg_looks_numeric(mp_obj_t arg) {
647 return arg_looks_integer(arg)
648#if MICROPY_ENABLE_FLOAT
649 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
650#endif
651 ;
652}
653
Dave Hylandsc4029e52014-04-07 11:19:51 -0700654static mp_obj_t arg_as_int(mp_obj_t arg) {
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700655#if MICROPY_ENABLE_FLOAT
656 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700657
658 // TODO: Needs a way to construct an mpz integer from a float
659
660 mp_small_int_t num = mp_obj_get_float(arg);
661 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700662 }
663#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700664 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700665}
666
Damien George897fe0c2014-04-15 22:03:55 +0100667mp_obj_t mp_obj_str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000668 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000669
Damien George5fa93b62014-01-22 14:35:10 +0000670 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700671 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000672 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700673 pfenv_t pfenv_vstr;
674 pfenv_vstr.data = vstr;
675 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
676
Damien George5fa93b62014-01-22 14:35:10 +0000677 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700678 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000679 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700680 if (str < top && *str == '}') {
681 vstr_add_char(vstr, '}');
682 continue;
683 }
Damien Georgeea13f402014-04-05 18:32:08 +0100684 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700685 }
686 if (*str != '{') {
687 vstr_add_char(vstr, *str);
688 continue;
689 }
690
691 str++;
692 if (str < top && *str == '{') {
693 vstr_add_char(vstr, '{');
694 continue;
695 }
696
697 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
698
699 vstr_t *field_name = NULL;
700 char conversion = '\0';
701 vstr_t *format_spec = NULL;
702
703 if (str < top && *str != '}' && *str != '!' && *str != ':') {
704 field_name = vstr_new();
705 while (str < top && *str != '}' && *str != '!' && *str != ':') {
706 vstr_add_char(field_name, *str++);
707 }
708 vstr_add_char(field_name, '\0');
709 }
710
711 // conversion ::= "r" | "s"
712
713 if (str < top && *str == '!') {
714 str++;
715 if (str < top && (*str == 'r' || *str == 's')) {
716 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200717 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100718 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 -0700719 }
720 }
721
722 if (str < top && *str == ':') {
723 str++;
724 // {:} is the same as {}, which is the same as {!s}
725 // This makes a difference when passing in a True or False
726 // '{}'.format(True) returns 'True'
727 // '{:d}'.format(True) returns '1'
728 // So we treat {:} as {} and this later gets treated to be {!s}
729 if (*str != '}') {
730 format_spec = vstr_new();
731 while (str < top && *str != '}') {
732 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000733 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700734 vstr_add_char(format_spec, '\0');
735 }
736 }
737 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100738 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700739 }
740 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100741 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700742 }
743
744 mp_obj_t arg = mp_const_none;
745
746 if (field_name) {
747 if (arg_i > 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100748 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 -0700749 }
Damien George3bb8bd82014-04-14 21:20:30 +0100750 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700751 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100752 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700753 }
754 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100755 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700756 }
757 arg = args[index + 1];
758 arg_i = -1;
759 vstr_free(field_name);
760 field_name = NULL;
761 } else {
762 if (arg_i < 0) {
Damien Georgeea13f402014-04-05 18:32:08 +0100763 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 -0700764 }
765 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100766 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700767 }
768 arg = args[arg_i + 1];
769 arg_i++;
770 }
771 if (!format_spec && !conversion) {
772 conversion = 's';
773 }
774 if (conversion) {
775 mp_print_kind_t print_kind;
776 if (conversion == 's') {
777 print_kind = PRINT_STR;
778 } else if (conversion == 'r') {
779 print_kind = PRINT_REPR;
780 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100781 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700782 }
783 vstr_t *arg_vstr = vstr_new();
784 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
785 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
786 vstr_free(arg_vstr);
787 }
788
789 char sign = '\0';
790 char fill = '\0';
791 char align = '\0';
792 int width = -1;
793 int precision = -1;
794 char type = '\0';
795 int flags = 0;
796
797 if (format_spec) {
798 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
799 //
800 // [[fill]align][sign][#][0][width][,][.precision][type]
801 // fill ::= <any character>
802 // align ::= "<" | ">" | "=" | "^"
803 // sign ::= "+" | "-" | " "
804 // width ::= integer
805 // precision ::= integer
806 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
807
808 const char *s = vstr_str(format_spec);
809 if (isalignment(*s)) {
810 align = *s++;
811 } else if (*s && isalignment(s[1])) {
812 fill = *s++;
813 align = *s++;
814 }
815 if (*s == '+' || *s == '-' || *s == ' ') {
816 if (*s == '+') {
817 flags |= PF_FLAG_SHOW_SIGN;
818 } else if (*s == ' ') {
819 flags |= PF_FLAG_SPACE_SIGN;
820 }
821 sign = *s++;
822 }
823 if (*s == '#') {
824 flags |= PF_FLAG_SHOW_PREFIX;
825 s++;
826 }
827 if (*s == '0') {
828 if (!align) {
829 align = '=';
830 }
831 if (!fill) {
832 fill = '0';
833 }
834 }
835 s += str_to_int(s, &width);
836 if (*s == ',') {
837 flags |= PF_FLAG_SHOW_COMMA;
838 s++;
839 }
840 if (*s == '.') {
841 s++;
842 s += str_to_int(s, &precision);
843 }
844 if (istype(*s)) {
845 type = *s++;
846 }
847 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +0100848 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700849 }
850 vstr_free(format_spec);
851 format_spec = NULL;
852 }
853 if (!align) {
854 if (arg_looks_numeric(arg)) {
855 align = '>';
856 } else {
857 align = '<';
858 }
859 }
860 if (!fill) {
861 fill = ' ';
862 }
863
864 if (sign) {
865 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +0100866 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700867 }
868 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +0100869 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000870 }
871 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700872 sign = '-';
873 }
874
875 switch (align) {
876 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
877 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
878 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
879 }
880
881 if (arg_looks_integer(arg)) {
882 switch (type) {
883 case 'b':
Damien Georgea12a0f72014-04-08 01:29:53 +0100884 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700885 continue;
886
887 case 'c':
888 {
889 char ch = mp_obj_get_int(arg);
890 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
891 continue;
892 }
893
894 case '\0': // No explicit format type implies 'd'
895 case 'n': // I don't think we support locales in uPy so use 'd'
896 case 'd':
Damien Georgea12a0f72014-04-08 01:29:53 +0100897 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700898 continue;
899
900 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -0700901 if (flags & PF_FLAG_SHOW_PREFIX) {
902 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
903 }
904
Damien Georgea12a0f72014-04-08 01:29:53 +0100905 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700906 continue;
907
908 case 'x':
Damien Georgea12a0f72014-04-08 01:29:53 +0100909 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'a', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700910 continue;
911
912 case 'X':
Damien Georgea12a0f72014-04-08 01:29:53 +0100913 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, 'A', flags, fill, width);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700914 continue;
915
916 case 'e':
917 case 'E':
918 case 'f':
919 case 'F':
920 case 'g':
921 case 'G':
922 case '%':
923 // The floating point formatters all work with anything that
924 // looks like an integer
925 break;
926
927 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100928 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700929 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
930 }
Damien Georgec322c5f2014-04-02 20:04:15 +0100931 }
Damien George70f33cd2014-04-02 17:06:05 +0100932
Dave Hylands22fe4d72014-04-02 12:07:31 -0700933 // NOTE: no else here. We need the e, f, g etc formats for integer
934 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +0100935 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700936 if (!type) {
937
938 // Even though the docs say that an unspecified type is the same
939 // as 'g', there is one subtle difference, when the exponent
940 // is one less than the precision.
941 //
942 // '{:10.1}'.format(0.0) ==> '0e+00'
943 // '{:10.1g}'.format(0.0) ==> '0'
944 //
945 // TODO: Figure out how to deal with this.
946 //
947 // A proper solution would involve adding a special flag
948 // or something to format_float, and create a format_double
949 // to deal with doubles. In order to fix this when using
950 // sprintf, we'd need to use the e format and tweak the
951 // returned result to strip trailing zeros like the g format
952 // does.
953 //
954 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
955 // but with 1.e2 you get 1e+02 and 1.00e+02
956 //
957 // Stripping the trailing 0's (like g) does would make the
958 // e format give us the right format.
959 //
960 // CPython sources say:
961 // Omitted type specifier. Behaves in the same way as repr(x)
962 // and str(x) if no precision is given, else like 'g', but with
963 // at least one digit after the decimal point. */
964
965 type = 'g';
966 }
967 if (type == 'n') {
968 type = 'g';
969 }
970
971 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
972 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +0100973#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700974 case 'e':
975 case 'E':
976 case 'f':
977 case 'F':
978 case 'g':
979 case 'G':
980 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
981 break;
982
983 case '%':
984 flags |= PF_FLAG_ADD_PERCENT;
985 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
986 break;
Damien Georgec322c5f2014-04-02 20:04:15 +0100987#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700988
989 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100990 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700991 "Unknown format code '%c' for object of type 'float'",
992 type, mp_obj_get_type_str(arg)));
993 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700994 } else {
Damien George70f33cd2014-04-02 17:06:05 +0100995 // arg doesn't look like a number
996
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700997 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +0100998 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700999 }
Damien George70f33cd2014-04-02 17:06:05 +01001000
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001001 switch (type) {
1002 case '\0':
1003 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1004 break;
1005
1006 case 's':
1007 {
1008 uint len;
1009 const char *s = mp_obj_str_get_data(arg, &len);
1010 if (precision < 0) {
1011 precision = len;
1012 }
1013 if (len > precision) {
1014 len = precision;
1015 }
1016 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1017 break;
1018 }
1019
1020 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001021 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001022 "Unknown format code '%c' for object of type 'str'",
1023 type, mp_obj_get_type_str(arg)));
1024 }
Damiend99b0522013-12-21 18:17:45 +00001025 }
1026 }
1027
Damien George5fa93b62014-01-22 14:35:10 +00001028 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1029 vstr_free(vstr);
1030 return s;
Damiend99b0522013-12-21 18:17:45 +00001031}
1032
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001033STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
1034 assert(MP_OBJ_IS_STR(pattern));
1035
1036 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001037 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001038 int arg_i = 0;
1039 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001040 pfenv_t pfenv_vstr;
1041 pfenv_vstr.data = vstr;
1042 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1043
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001044 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -07001045 if (*str != '%') {
1046 vstr_add_char(vstr, *str);
1047 continue;
1048 }
1049 if (++str >= top) {
1050 break;
1051 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001052 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001053 vstr_add_char(vstr, '%');
1054 continue;
1055 }
1056 if (arg_i >= n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001057 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
Dave Hylands6756a372014-04-02 11:42:39 -07001058 }
1059 int flags = 0;
1060 char fill = ' ';
1061 bool alt = false;
1062 while (str < top) {
1063 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1064 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1065 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
1066 else if (*str == '#') alt = true;
1067 else if (*str == '0') {
1068 flags |= PF_FLAG_PAD_AFTER_SIGN;
1069 fill = '0';
1070 } else break;
1071 str++;
1072 }
1073 // parse width, if it exists
1074 int width = 0;
1075 if (str < top) {
1076 if (*str == '*') {
1077 width = mp_obj_get_int(args[arg_i++]);
1078 str++;
1079 } else {
1080 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1081 width = width * 10 + *str - '0';
1082 }
1083 }
1084 }
1085 int prec = -1;
1086 if (str < top && *str == '.') {
1087 if (++str < top) {
1088 if (*str == '*') {
1089 prec = mp_obj_get_int(args[arg_i++]);
1090 str++;
1091 } else {
1092 prec = 0;
1093 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1094 prec = prec * 10 + *str - '0';
1095 }
1096 }
1097 }
1098 }
1099
1100 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001101 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001102 }
1103 mp_obj_t arg = args[arg_i];
1104 switch (*str) {
1105 case 'c':
1106 if (MP_OBJ_IS_STR(arg)) {
1107 uint len;
1108 const char *s = mp_obj_str_get_data(arg, &len);
1109 if (len != 1) {
Damien Georgeea13f402014-04-05 18:32:08 +01001110 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001111 break;
1112 }
1113 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1114 break;
1115 }
1116 if (arg_looks_integer(arg)) {
1117 char ch = mp_obj_get_int(arg);
1118 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1119 break;
1120 }
1121#if MICROPY_ENABLE_FLOAT
1122 // This is what CPython reports, so we report the same.
1123 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien Georgeea13f402014-04-05 18:32:08 +01001124 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001125
1126 }
1127#endif
Damien Georgeea13f402014-04-05 18:32:08 +01001128 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001129 break;
1130
1131 case 'd':
1132 case 'i':
1133 case 'u':
Damien Georgea12a0f72014-04-08 01:29:53 +01001134 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001135 break;
1136
1137#if MICROPY_ENABLE_FLOAT
1138 case 'e':
1139 case 'E':
1140 case 'f':
1141 case 'F':
1142 case 'g':
1143 case 'G':
1144 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1145 break;
1146#endif
1147
1148 case 'o':
1149 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001150 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001151 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001152 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001153 break;
1154
1155 case 'r':
1156 case 's':
1157 {
1158 vstr_t *arg_vstr = vstr_new();
1159 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1160 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1161 uint len = vstr_len(arg_vstr);
1162 if (prec < 0) {
1163 prec = len;
1164 }
1165 if (len > prec) {
1166 len = prec;
1167 }
1168 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1169 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001170 break;
1171 }
Dave Hylands6756a372014-04-02 11:42:39 -07001172
1173 case 'x':
1174 if (alt) {
1175 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001176 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001177 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001178 break;
1179
1180 case 'X':
1181 if (alt) {
1182 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001183 }
Damien Georgea12a0f72014-04-08 01:29:53 +01001184 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001185 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001186
Dave Hylands6756a372014-04-02 11:42:39 -07001187 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001188 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001189 "unsupported format character '%c' (0x%x) at index %d",
1190 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001191 }
Dave Hylands6756a372014-04-02 11:42:39 -07001192 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001193 }
1194
1195 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001196 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001197 }
1198
1199 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1200 vstr_free(vstr);
1201 return s;
1202}
1203
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001204STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001205 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001206
Damien Georgeff715422014-04-07 00:39:13 +01001207 machine_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001208 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001209 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001210 if (max_rep == 0) {
1211 return args[0];
1212 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001213 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001214 }
xbe480c15a2014-01-30 22:17:30 -08001215 }
Damien George94f68302014-01-31 23:45:12 +00001216
xbe729be9b2014-04-07 14:46:39 -07001217 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001218
Damien Georgeff715422014-04-07 00:39:13 +01001219 // check argument types
1220
1221 if (!MP_OBJ_IS_STR(args[1])) {
1222 bad_implicit_conversion(args[1]);
1223 }
1224
1225 if (!MP_OBJ_IS_STR(args[2])) {
1226 bad_implicit_conversion(args[2]);
1227 }
1228
1229 // extract string data
1230
xbe480c15a2014-01-30 22:17:30 -08001231 GET_STR_DATA_LEN(args[0], str, str_len);
1232 GET_STR_DATA_LEN(args[1], old, old_len);
1233 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001234
1235 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001236 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001237 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001238 }
1239
Damien George94f68302014-01-31 23:45:12 +00001240 // data for the replaced string
1241 byte *data = NULL;
1242 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001243
Damien George94f68302014-01-31 23:45:12 +00001244 // do 2 passes over the string:
1245 // first pass computes the required length of the replaced string
1246 // second pass does the replacements
1247 for (;;) {
1248 machine_uint_t replaced_str_index = 0;
1249 machine_uint_t num_replacements_done = 0;
1250 const byte *old_occurrence;
1251 const byte *offset_ptr = str;
Damien Georgeff715422014-04-07 00:39:13 +01001252 machine_uint_t str_len_remain = str_len;
1253 if (old_len == 0) {
1254 // if old_str is empty, copy new_str to start of replaced string
1255 // copy the replacement string
1256 if (data != NULL) {
1257 memcpy(data, new, new_len);
1258 }
1259 replaced_str_index += new_len;
1260 num_replacements_done++;
1261 }
1262 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1263 if (old_len == 0) {
1264 old_occurrence += 1;
1265 }
Damien George94f68302014-01-31 23:45:12 +00001266 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1267 if (data != NULL) {
1268 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1269 }
1270 replaced_str_index += old_occurrence - offset_ptr;
1271 // copy the replacement string
1272 if (data != NULL) {
1273 memcpy(data + replaced_str_index, new, new_len);
1274 }
1275 replaced_str_index += new_len;
1276 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001277 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001278 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001279 }
1280
1281 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1282 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001283 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001284 }
Damien Georgeff715422014-04-07 00:39:13 +01001285 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001286
1287 if (data == NULL) {
1288 // first pass
1289 if (num_replacements_done == 0) {
1290 // no substr found, return original string
1291 return args[0];
1292 } else {
1293 // substr found, allocate new string
1294 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001295 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001296 }
1297 } else {
1298 // second pass, we are done
1299 break;
1300 }
xbe480c15a2014-01-30 22:17:30 -08001301 }
Damien George94f68302014-01-31 23:45:12 +00001302
xbe480c15a2014-01-30 22:17:30 -08001303 return mp_obj_str_builder_end(replaced_str);
1304}
1305
xbe9e1e8cd2014-03-12 22:57:16 -07001306STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1307 assert(2 <= n_args && n_args <= 4);
1308 assert(MP_OBJ_IS_STR(args[0]));
1309 assert(MP_OBJ_IS_STR(args[1]));
1310
1311 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1312 GET_STR_DATA_LEN(args[1], needle, needle_len);
1313
Damien George536dde22014-03-13 22:07:55 +00001314 machine_uint_t start = 0;
1315 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001316 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001317 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001318 }
1319 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001320 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001321 }
1322
Damien George536dde22014-03-13 22:07:55 +00001323 // if needle_len is zero then we count each gap between characters as an occurrence
1324 if (needle_len == 0) {
1325 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001326 }
1327
Damien George536dde22014-03-13 22:07:55 +00001328 // count the occurrences
1329 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001330 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1331 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1332 num_occurrences++;
1333 haystack_index += needle_len - 1;
1334 }
xbe9e1e8cd2014-03-12 22:57:16 -07001335 }
1336
1337 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1338}
1339
Damien Georgeb035db32014-03-21 20:39:40 +00001340STATIC 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 +03001341 if (!is_str_or_bytes(self_in)) {
1342 assert(0);
1343 }
1344 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1345 if (self_type != mp_obj_get_type(arg)) {
1346 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001347 }
Damien Georgeb035db32014-03-21 20:39:40 +00001348
xbe613a8e32014-03-18 00:06:29 -07001349 GET_STR_DATA_LEN(self_in, str, str_len);
1350 GET_STR_DATA_LEN(arg, sep, sep_len);
1351
1352 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001353 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001354 }
Damien Georgeb035db32014-03-21 20:39:40 +00001355
1356 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1357
1358 if (direction > 0) {
1359 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001360 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001361 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001362 }
xbe613a8e32014-03-18 00:06:29 -07001363
xbe17a5a832014-03-23 23:31:58 -07001364 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1365 if (position_ptr != NULL) {
1366 machine_uint_t position = position_ptr - str;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001367 result[0] = str_new(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001368 result[1] = arg;
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001369 result[2] = str_new(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001370 }
Damien Georgeb035db32014-03-21 20:39:40 +00001371
xbe0a6894c2014-03-21 01:12:26 -07001372 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001373}
1374
Damien Georgeb035db32014-03-21 20:39:40 +00001375STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1376 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001377}
xbe4504ea82014-03-19 00:46:14 -07001378
Damien Georgeb035db32014-03-21 20:39:40 +00001379STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1380 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001381}
1382
Paul Sokolovsky69135212014-05-10 19:47:41 +03001383enum { CASE_UPPER, CASE_LOWER };
1384
1385// Supposedly not too critical operations, so optimize for code size
1386STATIC mp_obj_t str_caseconv(int op, mp_obj_t self_in) {
1387 GET_STR_DATA_LEN(self_in, self_data, self_len);
1388 byte *data;
1389 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1390 for (int i = 0; i < self_len; i++) {
1391 if (op == CASE_UPPER) {
1392 *data++ = unichar_toupper(*self_data++);
1393 } else {
1394 *data++ = unichar_tolower(*self_data++);
1395 }
1396 }
1397 *data = 0;
1398 return mp_obj_str_builder_end(s);
1399}
1400
1401STATIC mp_obj_t str_lower(mp_obj_t self_in) {
1402 return str_caseconv(CASE_LOWER, self_in);
1403}
1404
1405STATIC mp_obj_t str_upper(mp_obj_t self_in) {
1406 return str_caseconv(CASE_UPPER, self_in);
1407}
1408
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001409#if MICROPY_CPYTHON_COMPAT
1410// These methods are superfluous in the presense of str() and bytes()
1411// constructors.
1412// TODO: should accept kwargs too
1413STATIC mp_obj_t bytes_decode(uint n_args, const mp_obj_t *args) {
1414 mp_obj_t new_args[2];
1415 if (n_args == 1) {
1416 new_args[0] = args[0];
1417 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1418 args = new_args;
1419 n_args++;
1420 }
1421 return str_make_new(NULL, n_args, 0, args);
1422}
1423
1424// TODO: should accept kwargs too
1425STATIC mp_obj_t str_encode(uint n_args, const mp_obj_t *args) {
1426 mp_obj_t new_args[2];
1427 if (n_args == 1) {
1428 new_args[0] = args[0];
1429 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1430 args = new_args;
1431 n_args++;
1432 }
1433 return bytes_make_new(NULL, n_args, 0, args);
1434}
1435#endif
1436
Damien George57a4b4f2014-04-18 22:29:21 +01001437STATIC machine_int_t str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, int flags) {
1438 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001439 GET_STR_DATA_LEN(self_in, str_data, str_len);
1440 bufinfo->buf = (void*)str_data;
1441 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001442 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001443 return 0;
1444 } else {
1445 // can't write to a string
1446 bufinfo->buf = NULL;
1447 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001448 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001449 return 1;
1450 }
1451}
1452
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001453#if MICROPY_CPYTHON_COMPAT
1454STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1455STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
1456#endif
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001457STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001458STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
xbe3d9a39e2014-04-08 11:42:19 -07001459STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1460STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001461STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1462STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1463STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1464STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
Paul Sokolovsky88107842014-04-26 06:20:08 +03001465STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1466STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Damien George897fe0c2014-04-15 22:03:55 +01001467STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001468STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001469STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001470STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001471STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001472STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1473STATIC MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
Damiend99b0522013-12-21 18:17:45 +00001474
Damien George9b196cd2014-03-26 21:47:19 +00001475STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001476#if MICROPY_CPYTHON_COMPAT
1477 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
1478 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
1479#endif
Damien George9b196cd2014-03-26 21:47:19 +00001480 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1481 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001482 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1483 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001484 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1485 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
1486 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1487 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001488 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1489 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001490 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1491 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1492 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1493 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1494 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001495 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1496 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001497};
Damien George97209d32014-01-07 15:58:30 +00001498
Damien George9b196cd2014-03-26 21:47:19 +00001499STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1500
Damien George3e1a5c12014-03-29 13:43:38 +00001501const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001502 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001503 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001504 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001505 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001506 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001507 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001508 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001509 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001510 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001511};
1512
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001513// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001514const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001515 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001516 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001517 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001518 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001519 .binary_op = str_binary_op,
Damien George729f7b42014-04-17 22:10:53 +01001520 .subscr = str_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001521 .getiter = mp_obj_new_bytes_iterator,
Paul Sokolovsky7a70a3a2014-04-08 17:30:47 +03001522 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001523 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001524};
1525
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001526// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001527STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001528const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1529
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001530mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001531 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001532 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001533 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001534 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001535 byte *p = m_new(byte, len + 1);
1536 o->data = p;
1537 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001538 return o;
1539}
1540
Damien George5fa93b62014-01-22 14:35:10 +00001541mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001542 mp_obj_str_t *o = o_in;
1543 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001544 byte *p = (byte*)o->data;
1545 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001546 return o;
1547}
1548
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001549STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001550 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001551 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001552 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001553 if (data) {
1554 o->hash = qstr_compute_hash(data, len);
1555 byte *p = m_new(byte, len + 1);
1556 o->data = p;
1557 memcpy(p, data, len * sizeof(byte));
1558 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1559 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001560 return o;
1561}
1562
Damien George5fa93b62014-01-22 14:35:10 +00001563mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1564 qstr q = qstr_find_strn(data, len);
1565 if (q != MP_QSTR_NULL) {
1566 // qstr with this data already exists
1567 return MP_OBJ_NEW_QSTR(q);
1568 } else if (make_qstr_if_not_already) {
1569 // no existing qstr, make a new one
1570 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1571 } else {
1572 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001573 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001574 }
Damien George5fa93b62014-01-22 14:35:10 +00001575}
1576
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001577mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001578 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001579}
1580
Damien George5fa93b62014-01-22 14:35:10 +00001581bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1582 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1583 return s1 == s2;
1584 } else {
1585 GET_STR_HASH(s1, h1);
1586 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001587 // If any of hashes is 0, it means it's not valid
1588 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001589 return false;
1590 }
1591 GET_STR_DATA_LEN(s1, d1, l1);
1592 GET_STR_DATA_LEN(s2, d2, l2);
1593 if (l1 != l2) {
1594 return false;
1595 }
Damien George1e708fe2014-01-23 18:27:51 +00001596 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001597 }
Damien George5fa93b62014-01-22 14:35:10 +00001598}
1599
Damien Georgedeed0872014-04-06 11:11:15 +01001600STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001601 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 +00001602}
1603
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001604STATIC void arg_type_mixup() {
1605 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1606}
1607
Damien George5fa93b62014-01-22 14:35:10 +00001608uint mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001609 // TODO: This has too big overhead for hash accessor
1610 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001611 GET_STR_HASH(self_in, h);
1612 return h;
1613 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001614 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001615 }
1616}
1617
1618uint mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001619 // TODO This has a double check for the type, one in obj.c and one here
1620 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001621 GET_STR_LEN(self_in, l);
1622 return l;
1623 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001624 bad_implicit_conversion(self_in);
1625 }
1626}
1627
1628// use this if you will anyway convert the string to a qstr
1629// will be more efficient for the case where it's already a qstr
1630qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1631 if (MP_OBJ_IS_QSTR(self_in)) {
1632 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001633 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001634 mp_obj_str_t *self = self_in;
1635 return qstr_from_strn((char*)self->data, self->len);
1636 } else {
1637 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001638 }
1639}
1640
1641// only use this function if you need the str data to be zero terminated
1642// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1643const char *mp_obj_str_get_str(mp_obj_t self_in) {
1644 if (MP_OBJ_IS_STR(self_in)) {
1645 GET_STR_DATA_LEN(self_in, s, l);
1646 (void)l; // len unused
1647 return (const char*)s;
1648 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001649 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001650 }
1651}
1652
Damien George698ec212014-02-08 18:17:23 +00001653const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Paul Sokolovskyeea01182014-05-11 13:51:24 +03001654 if (is_str_or_bytes(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001655 GET_STR_DATA_LEN(self_in, s, l);
1656 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001657 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001658 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001659 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001660 }
Damiend99b0522013-12-21 18:17:45 +00001661}
xyb8cfc9f02014-01-05 18:47:51 +08001662
1663/******************************************************************************/
1664/* str iterator */
1665
1666typedef struct _mp_obj_str_it_t {
1667 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001668 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001669 machine_uint_t cur;
1670} mp_obj_str_it_t;
1671
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001672STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001673 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001674 GET_STR_DATA_LEN(self->str, str, len);
1675 if (self->cur < len) {
1676 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001677 self->cur += 1;
1678 return o_out;
1679 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001680 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001681 }
1682}
1683
Damien George3e1a5c12014-03-29 13:43:38 +00001684STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001685 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001686 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001687 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001688 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001689};
1690
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001691STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001692 mp_obj_str_it_t *self = self_in;
1693 GET_STR_DATA_LEN(self->str, str, len);
1694 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001695 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001696 self->cur += 1;
1697 return o_out;
1698 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001699 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001700 }
1701}
1702
Damien George3e1a5c12014-03-29 13:43:38 +00001703STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001704 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001705 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001706 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001707 .iternext = bytes_it_iternext,
1708};
1709
1710mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001711 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001712 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001713 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001714 o->cur = 0;
1715 return o;
1716}
1717
1718mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1719 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001720 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001721 o->str = str;
1722 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001723 return o;
1724}