blob: 130af8a6af65eb59adce5a83b615accdc28a0dc5 [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"
Paul Sokolovsky5048df02014-06-14 03:15:00 +030035#include "unicode.h"
Damien George55baff42014-01-21 21:40:13 +000036#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000037#include "obj.h"
38#include "runtime0.h"
39#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070040#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030041#include "objstr.h"
Paul Sokolovsky2a273652014-05-13 08:07:08 +030042#include "objlist.h"
Damiend99b0522013-12-21 18:17:45 +000043
Damien Georgeecc88e92014-08-30 00:35:11 +010044STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020045const mp_obj_t mp_const_empty_bytes;
46
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030047mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020048STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030049STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030050STATIC NORETURN void arg_type_mixup();
51
xyb8cfc9f02014-01-05 18:47:51 +080052/******************************************************************************/
53/* str */
54
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030055void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
Damien Georged182b982014-08-30 14:19:41 +010056 const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020057 // this escapes characters, but it will be very slow to print (calling print many times)
58 bool has_single_quote = false;
59 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100060 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020061 if (*s == '\'') {
62 has_single_quote = true;
63 } else if (*s == '"') {
64 has_double_quote = true;
65 }
66 }
67 int quote_char = '\'';
68 if (has_single_quote && !has_double_quote) {
69 quote_char = '"';
70 }
71 print(env, "%c", quote_char);
72 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
73 if (*s == quote_char) {
74 print(env, "\\%c", quote_char);
75 } else if (*s == '\\') {
76 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030077 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
78 // In strings, anything which is not ascii control character
79 // is printed as is, this includes characters in range 0x80-0xff
80 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020081 print(env, "%c", *s);
82 } else if (*s == '\n') {
83 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010084 } else if (*s == '\r') {
85 print(env, "\\r");
86 } else if (*s == '\t') {
87 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020088 } else {
89 print(env, "\\x%02x", *s);
90 }
91 }
92 print(env, "%c", quote_char);
93}
94
Damien George612045f2014-09-17 22:56:34 +010095#if MICROPY_PY_UJSON
96STATIC void str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) {
97 print(env, "\"");
98 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
99 if (*s == '"' || *s == '\\' || *s == '/') {
100 print(env, "\\%c", *s);
101 } else if (32 <= *s && *s <= 126) {
102 print(env, "%c", *s);
103 } else if (*s == '\b') {
104 print(env, "\\b");
105 } else if (*s == '\f') {
106 print(env, "\\f");
107 } else if (*s == '\n') {
108 print(env, "\\n");
109 } else if (*s == '\r') {
110 print(env, "\\r");
111 } else if (*s == '\t') {
112 print(env, "\\t");
113 } else {
114 print(env, "\\u%04x", *s);
115 }
116 }
117 print(env, "\"");
118}
119#endif
120
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200121STATIC 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 +0000122 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +0000123 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Damien George612045f2014-09-17 22:56:34 +0100124 #if MICROPY_PY_UJSON
125 if (kind == PRINT_JSON) {
126 str_print_json(print, env, str_data, str_len);
127 return;
128 }
129 #endif
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200130 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000131 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200132 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200133 if (is_bytes) {
134 print(env, "b");
135 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300136 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200137 }
Damiend99b0522013-12-21 18:17:45 +0000138}
139
Damien Georgeecc88e92014-08-30 00:35:11 +0100140STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300141#if MICROPY_CPYTHON_COMPAT
142 if (n_kw != 0) {
143 mp_arg_error_unimpl_kw();
144 }
145#endif
146
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200147 switch (n_args) {
148 case 0:
149 return MP_OBJ_NEW_QSTR(MP_QSTR_);
150
151 case 1:
152 {
153 vstr_t *vstr = vstr_new();
154 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100155 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200156 vstr_free(vstr);
157 return s;
158 }
159
160 case 2:
161 case 3:
162 {
163 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000164 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100165 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200166 }
167 GET_STR_DATA_LEN(args[0], str_data, str_len);
168 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100169 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200170 o->data = str_data;
171 o->hash = str_hash;
172 return o;
173 }
174
175 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100176 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200177 }
178}
179
Damien Georgeecc88e92014-08-30 00:35:11 +0100180STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200181 if (n_args == 0) {
182 return mp_const_empty_bytes;
183 }
184
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300185#if MICROPY_CPYTHON_COMPAT
186 if (n_kw != 0) {
187 mp_arg_error_unimpl_kw();
188 }
189#endif
190
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200191 if (MP_OBJ_IS_STR(args[0])) {
192 if (n_args < 2 || n_args > 3) {
193 goto wrong_args;
194 }
195 GET_STR_DATA_LEN(args[0], str_data, str_len);
196 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100197 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200198 o->data = str_data;
199 o->hash = str_hash;
200 return o;
201 }
202
203 if (n_args > 1) {
204 goto wrong_args;
205 }
206
207 if (MP_OBJ_IS_SMALL_INT(args[0])) {
208 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
209 byte *data;
210
Damien George3e1a5c12014-03-29 13:43:38 +0000211 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200212 memset(data, 0, len);
213 return mp_obj_str_builder_end(o);
214 }
215
216 int len;
217 byte *data;
218 vstr_t *vstr = NULL;
219 mp_obj_t o = NULL;
220 // Try to create array of exact len if initializer len is known
221 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
222 if (len_in == MP_OBJ_NULL) {
223 len = -1;
224 vstr = vstr_new();
225 } else {
226 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000227 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200228 }
229
Damien Georged17926d2014-03-30 13:35:08 +0100230 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200231 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100232 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200233 if (len == -1) {
234 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
235 } else {
236 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
237 }
238 }
239
240 if (len == -1) {
241 vstr_shrink(vstr);
242 // TODO: Optimize, borrow buffer from vstr
243 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000244 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200245 memcpy(data, vstr_str(vstr), len);
246 vstr_free(vstr);
247 }
248
249 return mp_obj_str_builder_end(o);
250
251wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100252 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200253}
254
Damien George55baff42014-01-21 21:40:13 +0000255// like strstr but with specified length and allows \0 bytes
256// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100257STATIC const byte *find_subbytes(const byte *haystack, mp_uint_t hlen, const byte *needle, mp_uint_t nlen, mp_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000258 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100259 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700260 if (direction > 0) {
261 str_index = 0;
262 str_index_end = hlen - nlen;
263 } else {
264 str_index = hlen - nlen;
265 str_index_end = 0;
266 }
267 for (;;) {
268 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
269 //found
270 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000271 }
xbe17a5a832014-03-23 23:31:58 -0700272 if (str_index == str_index_end) {
273 //not found
274 break;
Damien George55baff42014-01-21 21:40:13 +0000275 }
xbe17a5a832014-03-23 23:31:58 -0700276 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000277 }
278 }
279 return NULL;
280}
281
Damien Georgea75b02e2014-08-27 09:20:30 +0100282// Note: this function is used to check if an object is a str or bytes, which
283// works because both those types use it as their binary_op method. Revisit
284// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100285mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000286 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300287 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
288 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000289 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100290 case MP_BINARY_OP_ADD:
291 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300292 if (lhs_type == rhs_type) {
293 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000294
295 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000296 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000297
298 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000299 byte *q_ptr;
300 byte *val = qstr_build_start(alloc_len, &q_ptr);
301 memcpy(val, lhs_data, lhs_len);
302 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000303 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
304 */
305
306 // code for non-qstr
307 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300308 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000309 memcpy(data, lhs_data, lhs_len);
310 memcpy(data + lhs_len, rhs_data, rhs_len);
311 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000312 }
313 break;
Damien George5fa93b62014-01-22 14:35:10 +0000314
Damien Georged17926d2014-03-30 13:35:08 +0100315 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000316 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300317 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000318 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700319 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000320 }
321 break;
Damien George5fa93b62014-01-22 14:35:10 +0000322
Damien Georged0a5bf32014-05-10 13:55:11 +0100323 case MP_BINARY_OP_MULTIPLY: {
Damien George9b7a8ee2014-08-13 13:22:24 +0100324 mp_int_t n;
325 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100326 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200327 }
Damien George9b7a8ee2014-08-13 13:22:24 +0100328 if (n <= 0) {
329 if (lhs_type == &mp_type_str) {
330 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
331 }
332 n = 0;
333 }
Damien George5fa93b62014-01-22 14:35:10 +0000334 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300335 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000336 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
337 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200338 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200339
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300340 case MP_BINARY_OP_MODULO: {
341 mp_obj_t *args;
Damien George9c4cbe22014-08-30 14:04:14 +0100342 mp_uint_t n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300343 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300344 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
345 // TODO: Support tuple subclasses?
346 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300347 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
348 args = NULL;
349 n_args = 0;
350 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300351 } else {
352 args = &rhs_in;
353 n_args = 1;
354 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300355 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300356 }
357
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300358 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
359 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 +0100360 case MP_BINARY_OP_LESS:
361 case MP_BINARY_OP_LESS_EQUAL:
362 case MP_BINARY_OP_MORE:
363 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300364 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200365 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
366 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
367 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300368 if (lhs_type == &mp_type_bytes) {
369 mp_buffer_info_t bufinfo;
370 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
371 goto uncomparable;
372 }
373 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
374 }
375uncomparable:
376 if (op == MP_BINARY_OP_EQUAL) {
377 return mp_const_false;
378 }
Damiend99b0522013-12-21 18:17:45 +0000379 }
380
Damien George6ac5dce2014-05-21 19:42:43 +0100381 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000382}
383
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300384#if !MICROPY_PY_BUILTINS_STR_UNICODE
385// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100386const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, mp_uint_t self_len,
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300387 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100388 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300389 return self_data + index_val;
390}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300391#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300392
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300393// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
394STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
Paul Sokolovsky5ebd5f02014-05-11 21:22:59 +0300395 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100396 GET_STR_DATA_LEN(self_in, self_data, self_len);
397 if (value == MP_OBJ_SENTINEL) {
398 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100399#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100400 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300401 mp_bound_slice_t slice;
402 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300403 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100404 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100405 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100406 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100407 }
408#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300409 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100410 // If we have unicode enabled the type will always be bytes, so take the short cut.
411 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300412 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100413 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300414 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100415 }
416 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100417 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100418 }
419}
420
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200421STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700422 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300423 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000424
Damien Georgefe8fb912014-01-02 16:36:09 +0000425 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000426 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000427
428 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100429 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000430 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000431 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000432 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000433 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100434 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
435 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300436 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100437 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
438 }
439 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000440 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000441
442 // count required length
443 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000444 for (int i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300445 if (mp_obj_get_type(seq_items[i]) != self_type) {
446 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
447 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000448 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000449 if (i > 0) {
450 required_len += sep_len;
451 }
Damien George5fa93b62014-01-22 14:35:10 +0000452 GET_STR_LEN(seq_items[i], l);
453 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000454 }
455
456 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000457 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300458 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000459 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000460 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000461 memcpy(data, sep_str, sep_len);
462 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000463 }
Damien George5fa93b62014-01-22 14:35:10 +0000464 GET_STR_DATA_LEN(seq_items[i], s, l);
465 memcpy(data, s, l);
466 data += l;
Damiend99b0522013-12-21 18:17:45 +0000467 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000468
469 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000470 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000471}
472
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200473#define is_ws(c) ((c) == ' ' || (c) == '\t')
474
Damien Georgeecc88e92014-08-30 00:35:11 +0100475STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300476 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100477 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200478 mp_obj_t sep = mp_const_none;
479 if (n_args > 1) {
480 sep = args[1];
481 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100482 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200483 }
484 }
Damien Georgedeed0872014-04-06 11:11:15 +0100485
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200486 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000487 GET_STR_DATA_LEN(args[0], s, len);
488 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200489
Damien Georgedeed0872014-04-06 11:11:15 +0100490 if (sep == mp_const_none) {
491 // sep not given, so separate on whitespace
492
493 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000494 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100495 while (s < top && splits != 0) {
496 const byte *start = s;
497 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100498 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100499 if (s >= top) {
500 break;
501 }
502 while (s < top && is_ws(*s)) s++;
503 if (splits > 0) {
504 splits--;
505 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200506 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200507
Damien Georgedeed0872014-04-06 11:11:15 +0100508 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100509 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100510 }
511
512 } else {
513 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300514 if (mp_obj_get_type(sep) != self_type) {
515 arg_type_mixup();
516 }
Damien Georgedeed0872014-04-06 11:11:15 +0100517
Damien Georged182b982014-08-30 14:19:41 +0100518 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100519 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
520
521 if (sep_len == 0) {
522 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
523 }
524
525 for (;;) {
526 const byte *start = s;
527 for (;;) {
528 if (splits == 0 || s + sep_len > top) {
529 s = top;
530 break;
531 } else if (memcmp(s, sep_str, sep_len) == 0) {
532 break;
533 }
534 s++;
535 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100536 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100537 if (s >= top) {
538 break;
539 }
540 s += sep_len;
541 if (splits > 0) {
542 splits--;
543 }
544 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200545 }
546
547 return res;
548}
549
Damien Georgeecc88e92014-08-30 00:35:11 +0100550STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300551 if (n_args < 3) {
552 // If we don't have split limit, it doesn't matter from which side
553 // we split.
554 return str_split(n_args, args);
555 }
556 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
557 mp_obj_t sep = args[1];
558 GET_STR_DATA_LEN(args[0], s, len);
559
Damien George40f3c022014-07-03 13:25:24 +0100560 mp_int_t splits = mp_obj_get_int(args[2]);
561 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300562 // Preallocate list to the max expected # of elements, as we
563 // will fill it from the end.
564 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
565 int idx = splits;
566
567 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000568 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300569 } else {
Damien Georged182b982014-08-30 14:19:41 +0100570 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300571 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
572
573 if (sep_len == 0) {
574 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
575 }
576
577 const byte *beg = s;
578 const byte *last = s + len;
579 for (;;) {
580 s = last - sep_len;
581 for (;;) {
582 if (splits == 0 || s < beg) {
583 break;
584 } else if (memcmp(s, sep_str, sep_len) == 0) {
585 break;
586 }
587 s--;
588 }
589 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100590 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300591 break;
592 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100593 res->items[idx--] = mp_obj_new_str_of_type(self_type, s + sep_len, last - s - sep_len);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300594 last = s;
595 if (splits > 0) {
596 splits--;
597 }
598 }
599 if (idx != 0) {
600 // We split less parts than split limit, now go cleanup surplus
601 int used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100602 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300603 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
604 res->len = used;
605 }
606 }
607
608 return res;
609}
610
Damien Georgeecc88e92014-08-30 00:35:11 +0100611STATIC mp_obj_t str_finder(mp_uint_t n_args, const mp_obj_t *args, mp_int_t direction, bool is_index) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300612 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000613 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000614 assert(MP_OBJ_IS_STR(args[0]));
615 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000616
Damien George5fa93b62014-01-22 14:35:10 +0000617 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
618 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000619
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300620 const byte *start = haystack;
621 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000622 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300623 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000624 }
625 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300626 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000627 }
628
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300629 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000630 if (p == NULL) {
631 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700632 if (is_index) {
633 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
634 } else {
635 return MP_OBJ_NEW_SMALL_INT(-1);
636 }
Damien George23005372014-01-13 19:39:01 +0000637 } else {
638 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300639 #if MICROPY_PY_BUILTINS_STR_UNICODE
640 if (self_type == &mp_type_str) {
641 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
642 }
643 #endif
xbe17a5a832014-03-23 23:31:58 -0700644 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000645 }
John R. Lentone8204912014-01-12 21:53:52 +0000646}
647
Damien Georgeecc88e92014-08-30 00:35:11 +0100648STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700649 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700650}
651
Damien Georgeecc88e92014-08-30 00:35:11 +0100652STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700653 return str_finder(n_args, args, -1, false);
654}
655
Damien Georgeecc88e92014-08-30 00:35:11 +0100656STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700657 return str_finder(n_args, args, 1, true);
658}
659
Damien Georgeecc88e92014-08-30 00:35:11 +0100660STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700661 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700662}
663
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200664// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100665STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300666 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300667 GET_STR_DATA_LEN(args[0], str, str_len);
668 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300669 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300670 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300671 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300672 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300673 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200674 return mp_const_false;
675 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300676 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200677}
678
Damien Georgeecc88e92014-08-30 00:35:11 +0100679STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300680 GET_STR_DATA_LEN(args[0], str, str_len);
681 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
682 assert(n_args == 2);
683
684 if (suffix_len > str_len) {
685 return mp_const_false;
686 }
687 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
688}
689
Paul Sokolovsky88107842014-04-26 06:20:08 +0300690enum { LSTRIP, RSTRIP, STRIP };
691
Damien Georgeecc88e92014-08-30 00:35:11 +0100692STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800693 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700694 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300695 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000696
697 const byte *chars_to_del;
698 uint chars_to_del_len;
699 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800700
701 if (n_args == 1) {
702 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000703 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800704 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300705 if (mp_obj_get_type(args[1]) != self_type) {
706 arg_type_mixup();
707 }
Damien George5fa93b62014-01-22 14:35:10 +0000708 GET_STR_DATA_LEN(args[1], s, l);
709 chars_to_del = s;
710 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800711 }
712
Damien George5fa93b62014-01-22 14:35:10 +0000713 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800714
Damien George40f3c022014-07-03 13:25:24 +0100715 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800716 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100717 mp_uint_t last_good_char_pos = 0;
718 mp_uint_t i = 0;
719 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300720 if (type == RSTRIP) {
721 i = orig_str_len - 1;
722 delta = -1;
723 }
Damien George40f3c022014-07-03 13:25:24 +0100724 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700725 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800726 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300727 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800728 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300729 if (type == LSTRIP) {
730 last_good_char_pos = orig_str_len - 1;
731 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300732 } else if (type == RSTRIP) {
733 first_good_char_pos = 0;
734 last_good_char_pos = i;
735 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300736 }
xbe7b0f39f2014-01-08 14:23:45 -0800737 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300738 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800739 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300740 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800741 }
742
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300743 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000744 // string is all whitespace, return ''
745 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800746 }
747
748 assert(last_good_char_pos >= first_good_char_pos);
749 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100750 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300751 if (stripped_len == orig_str_len) {
752 // If nothing was stripped, don't bother to dup original string
753 // TODO: watch out for this case when we'll get to bytearray.strip()
754 assert(first_good_char_pos == 0);
755 return args[0];
756 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100757 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800758}
759
Damien Georgeecc88e92014-08-30 00:35:11 +0100760STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300761 return str_uni_strip(STRIP, n_args, args);
762}
763
Damien Georgeecc88e92014-08-30 00:35:11 +0100764STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300765 return str_uni_strip(LSTRIP, n_args, args);
766}
767
Damien Georgeecc88e92014-08-30 00:35:11 +0100768STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300769 return str_uni_strip(RSTRIP, n_args, args);
770}
771
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700772// Takes an int arg, but only parses unsigned numbers, and only changes
773// *num if at least one digit was parsed.
774static int str_to_int(const char *str, int *num) {
775 const char *s = str;
776 if (unichar_isdigit(*s)) {
777 *num = 0;
778 do {
779 *num = *num * 10 + (*s - '0');
780 s++;
781 }
782 while (unichar_isdigit(*s));
783 }
784 return s - str;
785}
786
787static bool isalignment(char ch) {
788 return ch && strchr("<>=^", ch) != NULL;
789}
790
791static bool istype(char ch) {
792 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
793}
794
795static bool arg_looks_integer(mp_obj_t arg) {
796 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
797}
798
799static bool arg_looks_numeric(mp_obj_t arg) {
800 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100801#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700802 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
803#endif
804 ;
805}
806
Dave Hylandsc4029e52014-04-07 11:19:51 -0700807static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100808#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700809 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700810
811 // TODO: Needs a way to construct an mpz integer from a float
812
Damien George40f3c022014-07-03 13:25:24 +0100813 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700814 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700815 }
816#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700817 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700818}
819
Damien Georgeecc88e92014-08-30 00:35:11 +0100820mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000821 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000822
Damien George5fa93b62014-01-22 14:35:10 +0000823 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700824 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000825 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700826 pfenv_t pfenv_vstr;
827 pfenv_vstr.data = vstr;
828 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
829
Damien George5fa93b62014-01-22 14:35:10 +0000830 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700831 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000832 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700833 if (str < top && *str == '}') {
834 vstr_add_char(vstr, '}');
835 continue;
836 }
Damien George11de8392014-06-05 18:57:38 +0100837 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700838 }
839 if (*str != '{') {
840 vstr_add_char(vstr, *str);
841 continue;
842 }
843
844 str++;
845 if (str < top && *str == '{') {
846 vstr_add_char(vstr, '{');
847 continue;
848 }
849
850 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
851
852 vstr_t *field_name = NULL;
853 char conversion = '\0';
854 vstr_t *format_spec = NULL;
855
856 if (str < top && *str != '}' && *str != '!' && *str != ':') {
857 field_name = vstr_new();
858 while (str < top && *str != '}' && *str != '!' && *str != ':') {
859 vstr_add_char(field_name, *str++);
860 }
861 vstr_add_char(field_name, '\0');
862 }
863
864 // conversion ::= "r" | "s"
865
866 if (str < top && *str == '!') {
867 str++;
868 if (str < top && (*str == 'r' || *str == 's')) {
869 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200870 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100871 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 -0700872 }
873 }
874
875 if (str < top && *str == ':') {
876 str++;
877 // {:} is the same as {}, which is the same as {!s}
878 // This makes a difference when passing in a True or False
879 // '{}'.format(True) returns 'True'
880 // '{:d}'.format(True) returns '1'
881 // So we treat {:} as {} and this later gets treated to be {!s}
882 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100883 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700884 while (str < top && *str != '}') {
885 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000886 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700887 vstr_add_char(format_spec, '\0');
888 }
889 }
890 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100891 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700892 }
893 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100894 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700895 }
896
897 mp_obj_t arg = mp_const_none;
898
899 if (field_name) {
900 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100901 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902 }
Damien George3bb8bd82014-04-14 21:20:30 +0100903 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700904 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100905 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700906 }
907 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100908 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700909 }
910 arg = args[index + 1];
911 arg_i = -1;
912 vstr_free(field_name);
913 field_name = NULL;
914 } else {
915 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100916 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700917 }
918 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100919 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700920 }
921 arg = args[arg_i + 1];
922 arg_i++;
923 }
924 if (!format_spec && !conversion) {
925 conversion = 's';
926 }
927 if (conversion) {
928 mp_print_kind_t print_kind;
929 if (conversion == 's') {
930 print_kind = PRINT_STR;
931 } else if (conversion == 'r') {
932 print_kind = PRINT_REPR;
933 } else {
Damien George11de8392014-06-05 18:57:38 +0100934 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700935 }
936 vstr_t *arg_vstr = vstr_new();
937 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100938 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700939 vstr_free(arg_vstr);
940 }
941
942 char sign = '\0';
943 char fill = '\0';
944 char align = '\0';
945 int width = -1;
946 int precision = -1;
947 char type = '\0';
948 int flags = 0;
949
950 if (format_spec) {
951 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
952 //
953 // [[fill]align][sign][#][0][width][,][.precision][type]
954 // fill ::= <any character>
955 // align ::= "<" | ">" | "=" | "^"
956 // sign ::= "+" | "-" | " "
957 // width ::= integer
958 // precision ::= integer
959 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
960
961 const char *s = vstr_str(format_spec);
962 if (isalignment(*s)) {
963 align = *s++;
964 } else if (*s && isalignment(s[1])) {
965 fill = *s++;
966 align = *s++;
967 }
968 if (*s == '+' || *s == '-' || *s == ' ') {
969 if (*s == '+') {
970 flags |= PF_FLAG_SHOW_SIGN;
971 } else if (*s == ' ') {
972 flags |= PF_FLAG_SPACE_SIGN;
973 }
974 sign = *s++;
975 }
976 if (*s == '#') {
977 flags |= PF_FLAG_SHOW_PREFIX;
978 s++;
979 }
980 if (*s == '0') {
981 if (!align) {
982 align = '=';
983 }
984 if (!fill) {
985 fill = '0';
986 }
987 }
988 s += str_to_int(s, &width);
989 if (*s == ',') {
990 flags |= PF_FLAG_SHOW_COMMA;
991 s++;
992 }
993 if (*s == '.') {
994 s++;
995 s += str_to_int(s, &precision);
996 }
997 if (istype(*s)) {
998 type = *s++;
999 }
1000 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001001 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001002 }
1003 vstr_free(format_spec);
1004 format_spec = NULL;
1005 }
1006 if (!align) {
1007 if (arg_looks_numeric(arg)) {
1008 align = '>';
1009 } else {
1010 align = '<';
1011 }
1012 }
1013 if (!fill) {
1014 fill = ' ';
1015 }
1016
1017 if (sign) {
1018 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +01001019 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001020 }
1021 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +01001022 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +00001023 }
1024 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001025 sign = '-';
1026 }
1027
1028 switch (align) {
1029 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1030 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1031 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1032 }
1033
1034 if (arg_looks_integer(arg)) {
1035 switch (type) {
1036 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001037 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001038 continue;
1039
1040 case 'c':
1041 {
1042 char ch = mp_obj_get_int(arg);
1043 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1044 continue;
1045 }
1046
1047 case '\0': // No explicit format type implies 'd'
1048 case 'n': // I don't think we support locales in uPy so use 'd'
1049 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001050 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001051 continue;
1052
1053 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001054 if (flags & PF_FLAG_SHOW_PREFIX) {
1055 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1056 }
1057
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001058 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001059 continue;
1060
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001061 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001062 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001063 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001064 continue;
1065
1066 case 'e':
1067 case 'E':
1068 case 'f':
1069 case 'F':
1070 case 'g':
1071 case 'G':
1072 case '%':
1073 // The floating point formatters all work with anything that
1074 // looks like an integer
1075 break;
1076
1077 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001078 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001079 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001080 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001081 }
Damien George70f33cd2014-04-02 17:06:05 +01001082
Dave Hylands22fe4d72014-04-02 12:07:31 -07001083 // NOTE: no else here. We need the e, f, g etc formats for integer
1084 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001085 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001086 if (!type) {
1087
1088 // Even though the docs say that an unspecified type is the same
1089 // as 'g', there is one subtle difference, when the exponent
1090 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001091 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001092 // '{:10.1}'.format(0.0) ==> '0e+00'
1093 // '{:10.1g}'.format(0.0) ==> '0'
1094 //
1095 // TODO: Figure out how to deal with this.
1096 //
1097 // A proper solution would involve adding a special flag
1098 // or something to format_float, and create a format_double
1099 // to deal with doubles. In order to fix this when using
1100 // sprintf, we'd need to use the e format and tweak the
1101 // returned result to strip trailing zeros like the g format
1102 // does.
1103 //
1104 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1105 // but with 1.e2 you get 1e+02 and 1.00e+02
1106 //
1107 // Stripping the trailing 0's (like g) does would make the
1108 // e format give us the right format.
1109 //
1110 // CPython sources say:
1111 // Omitted type specifier. Behaves in the same way as repr(x)
1112 // and str(x) if no precision is given, else like 'g', but with
1113 // at least one digit after the decimal point. */
1114
1115 type = 'g';
1116 }
1117 if (type == 'n') {
1118 type = 'g';
1119 }
1120
1121 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1122 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001123#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001124 case 'e':
1125 case 'E':
1126 case 'f':
1127 case 'F':
1128 case 'g':
1129 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001130 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001131 break;
1132
1133 case '%':
1134 flags |= PF_FLAG_ADD_PERCENT;
1135 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1136 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001137#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001138
1139 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001140 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001141 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001142 type, mp_obj_get_type_str(arg)));
1143 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001144 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001145 // arg doesn't look like a number
1146
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001147 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001148 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001149 }
Damien George70f33cd2014-04-02 17:06:05 +01001150
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001151 switch (type) {
1152 case '\0':
1153 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1154 break;
1155
Damien Georged182b982014-08-30 14:19:41 +01001156 case 's': {
1157 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001158 const char *s = mp_obj_str_get_data(arg, &len);
1159 if (precision < 0) {
1160 precision = len;
1161 }
1162 if (len > precision) {
1163 len = precision;
1164 }
1165 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1166 break;
1167 }
1168
1169 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001170 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001171 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001172 type, mp_obj_get_type_str(arg)));
1173 }
Damiend99b0522013-12-21 18:17:45 +00001174 }
1175 }
1176
Damien George2617eeb2014-05-25 22:27:57 +01001177 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001178 vstr_free(vstr);
1179 return s;
Damiend99b0522013-12-21 18:17:45 +00001180}
1181
Damien Georgeecc88e92014-08-30 00:35:11 +01001182STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001183 assert(MP_OBJ_IS_STR(pattern));
1184
1185 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001186 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001187 int arg_i = 0;
1188 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001189 pfenv_t pfenv_vstr;
1190 pfenv_vstr.data = vstr;
1191 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1192
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001193 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001194 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001195 if (*str != '%') {
1196 vstr_add_char(vstr, *str);
1197 continue;
1198 }
1199 if (++str >= top) {
1200 break;
1201 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001202 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001203 vstr_add_char(vstr, '%');
1204 continue;
1205 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001206
1207 // Dictionary value lookup
1208 if (*str == '(') {
1209 const byte *key = ++str;
1210 while (*str != ')') {
1211 if (str >= top) {
1212 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1213 }
1214 ++str;
1215 }
1216 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1217 arg = mp_obj_dict_get(dict, k_obj);
1218 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001219 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001220
Dave Hylands6756a372014-04-02 11:42:39 -07001221 int flags = 0;
1222 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001223 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001224 while (str < top) {
1225 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1226 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1227 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001228 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001229 else if (*str == '0') {
1230 flags |= PF_FLAG_PAD_AFTER_SIGN;
1231 fill = '0';
1232 } else break;
1233 str++;
1234 }
1235 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001236 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001237 if (str < top) {
1238 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001239 if (arg_i >= n_args) {
1240 goto not_enough_args;
1241 }
Dave Hylands6756a372014-04-02 11:42:39 -07001242 width = mp_obj_get_int(args[arg_i++]);
1243 str++;
1244 } else {
1245 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1246 width = width * 10 + *str - '0';
1247 }
1248 }
1249 }
1250 int prec = -1;
1251 if (str < top && *str == '.') {
1252 if (++str < top) {
1253 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001254 if (arg_i >= n_args) {
1255 goto not_enough_args;
1256 }
Dave Hylands6756a372014-04-02 11:42:39 -07001257 prec = mp_obj_get_int(args[arg_i++]);
1258 str++;
1259 } else {
1260 prec = 0;
1261 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1262 prec = prec * 10 + *str - '0';
1263 }
1264 }
1265 }
1266 }
1267
1268 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001269 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001270 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001271
1272 // Tuple value lookup
1273 if (arg == MP_OBJ_NULL) {
1274 if (arg_i >= n_args) {
1275not_enough_args:
1276 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1277 }
1278 arg = args[arg_i++];
1279 }
Dave Hylands6756a372014-04-02 11:42:39 -07001280 switch (*str) {
1281 case 'c':
1282 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001283 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001284 const char *s = mp_obj_str_get_data(arg, &len);
1285 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001286 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001287 break;
1288 }
1289 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1290 break;
1291 }
1292 if (arg_looks_integer(arg)) {
1293 char ch = mp_obj_get_int(arg);
1294 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1295 break;
1296 }
Damien Georgefb510b32014-06-01 13:32:54 +01001297#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001298 // This is what CPython reports, so we report the same.
1299 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001300 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001301
1302 }
1303#endif
Damien George11de8392014-06-05 18:57:38 +01001304 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1305 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001306
1307 case 'd':
1308 case 'i':
1309 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001310 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001311 break;
1312
Damien Georgefb510b32014-06-01 13:32:54 +01001313#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001314 case 'e':
1315 case 'E':
1316 case 'f':
1317 case 'F':
1318 case 'g':
1319 case 'G':
1320 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1321 break;
1322#endif
1323
1324 case 'o':
1325 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001326 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001327 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001328 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001329 break;
1330
1331 case 'r':
1332 case 's':
1333 {
1334 vstr_t *arg_vstr = vstr_new();
1335 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1336 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1337 uint len = vstr_len(arg_vstr);
1338 if (prec < 0) {
1339 prec = len;
1340 }
1341 if (len > prec) {
1342 len = prec;
1343 }
1344 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1345 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001346 break;
1347 }
Dave Hylands6756a372014-04-02 11:42:39 -07001348
Dave Hylands6756a372014-04-02 11:42:39 -07001349 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001350 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001351 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001352 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001353
Dave Hylands6756a372014-04-02 11:42:39 -07001354 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001355 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001356 "unsupported format character '%c' (0x%x) at index %d",
1357 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001358 }
1359 }
1360
1361 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001362 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001363 }
1364
Damien George2617eeb2014-05-25 22:27:57 +01001365 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001366 vstr_free(vstr);
1367 return s;
1368}
1369
Damien Georgeecc88e92014-08-30 00:35:11 +01001370STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001371 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001372
Damien George40f3c022014-07-03 13:25:24 +01001373 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001374 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001375 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001376 if (max_rep == 0) {
1377 return args[0];
1378 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001379 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001380 }
xbe480c15a2014-01-30 22:17:30 -08001381 }
Damien George94f68302014-01-31 23:45:12 +00001382
xbe729be9b2014-04-07 14:46:39 -07001383 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001384
Damien Georgeff715422014-04-07 00:39:13 +01001385 // check argument types
1386
1387 if (!MP_OBJ_IS_STR(args[1])) {
1388 bad_implicit_conversion(args[1]);
1389 }
1390
1391 if (!MP_OBJ_IS_STR(args[2])) {
1392 bad_implicit_conversion(args[2]);
1393 }
1394
1395 // extract string data
1396
xbe480c15a2014-01-30 22:17:30 -08001397 GET_STR_DATA_LEN(args[0], str, str_len);
1398 GET_STR_DATA_LEN(args[1], old, old_len);
1399 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001400
1401 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001402 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001403 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001404 }
1405
Damien George94f68302014-01-31 23:45:12 +00001406 // data for the replaced string
1407 byte *data = NULL;
1408 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001409
Damien George94f68302014-01-31 23:45:12 +00001410 // do 2 passes over the string:
1411 // first pass computes the required length of the replaced string
1412 // second pass does the replacements
1413 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001414 mp_uint_t replaced_str_index = 0;
1415 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001416 const byte *old_occurrence;
1417 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001418 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001419 if (old_len == 0) {
1420 // if old_str is empty, copy new_str to start of replaced string
1421 // copy the replacement string
1422 if (data != NULL) {
1423 memcpy(data, new, new_len);
1424 }
1425 replaced_str_index += new_len;
1426 num_replacements_done++;
1427 }
1428 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1429 if (old_len == 0) {
1430 old_occurrence += 1;
1431 }
Damien George94f68302014-01-31 23:45:12 +00001432 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1433 if (data != NULL) {
1434 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1435 }
1436 replaced_str_index += old_occurrence - offset_ptr;
1437 // copy the replacement string
1438 if (data != NULL) {
1439 memcpy(data + replaced_str_index, new, new_len);
1440 }
1441 replaced_str_index += new_len;
1442 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001443 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001444 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001445 }
1446
1447 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1448 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001449 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001450 }
Damien Georgeff715422014-04-07 00:39:13 +01001451 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001452
1453 if (data == NULL) {
1454 // first pass
1455 if (num_replacements_done == 0) {
1456 // no substr found, return original string
1457 return args[0];
1458 } else {
1459 // substr found, allocate new string
1460 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001461 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001462 }
1463 } else {
1464 // second pass, we are done
1465 break;
1466 }
xbe480c15a2014-01-30 22:17:30 -08001467 }
Damien George94f68302014-01-31 23:45:12 +00001468
xbe480c15a2014-01-30 22:17:30 -08001469 return mp_obj_str_builder_end(replaced_str);
1470}
1471
Damien Georgeecc88e92014-08-30 00:35:11 +01001472STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001473 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001474 assert(2 <= n_args && n_args <= 4);
1475 assert(MP_OBJ_IS_STR(args[0]));
1476 assert(MP_OBJ_IS_STR(args[1]));
1477
1478 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1479 GET_STR_DATA_LEN(args[1], needle, needle_len);
1480
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001481 const byte *start = haystack;
1482 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001483 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001484 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001485 }
1486 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001487 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001488 }
1489
Damien George536dde22014-03-13 22:07:55 +00001490 // if needle_len is zero then we count each gap between characters as an occurrence
1491 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001492 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001493 }
1494
Damien George536dde22014-03-13 22:07:55 +00001495 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001496 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001497 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1498 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001499 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001500 haystack_ptr += needle_len;
1501 } else {
1502 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001503 }
xbe9e1e8cd2014-03-12 22:57:16 -07001504 }
1505
1506 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1507}
1508
Damien George40f3c022014-07-03 13:25:24 +01001509STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001510 if (!MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001511 assert(0);
1512 }
1513 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1514 if (self_type != mp_obj_get_type(arg)) {
1515 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001516 }
Damien Georgeb035db32014-03-21 20:39:40 +00001517
xbe613a8e32014-03-18 00:06:29 -07001518 GET_STR_DATA_LEN(self_in, str, str_len);
1519 GET_STR_DATA_LEN(arg, sep, sep_len);
1520
1521 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001522 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001523 }
Damien Georgeb035db32014-03-21 20:39:40 +00001524
1525 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1526
1527 if (direction > 0) {
1528 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001529 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001530 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001531 }
xbe613a8e32014-03-18 00:06:29 -07001532
xbe17a5a832014-03-23 23:31:58 -07001533 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1534 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001535 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001536 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001537 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001538 result[2] = mp_obj_new_str_of_type(self_type, str + position + sep_len, str_len - position - sep_len);
xbe613a8e32014-03-18 00:06:29 -07001539 }
Damien Georgeb035db32014-03-21 20:39:40 +00001540
xbe0a6894c2014-03-21 01:12:26 -07001541 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001542}
1543
Damien Georgeb035db32014-03-21 20:39:40 +00001544STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1545 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001546}
xbe4504ea82014-03-19 00:46:14 -07001547
Damien Georgeb035db32014-03-21 20:39:40 +00001548STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1549 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001550}
1551
Paul Sokolovsky69135212014-05-10 19:47:41 +03001552// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001553STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001554 GET_STR_DATA_LEN(self_in, self_data, self_len);
1555 byte *data;
1556 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
1557 for (int i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001558 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001559 }
1560 *data = 0;
1561 return mp_obj_str_builder_end(s);
1562}
1563
1564STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001565 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001566}
1567
1568STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001569 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001570}
1571
Damien Georgefcc9cf62014-06-01 18:22:09 +01001572STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001573 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001574
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001575 if (self_len == 0) {
1576 return mp_const_false; // default to False for empty str
1577 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001578
Damien Georgefcc9cf62014-06-01 18:22:09 +01001579 if (f != unichar_isupper && f != unichar_islower) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001580 for (int i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001581 if (!f(*self_data++)) {
1582 return mp_const_false;
1583 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001584 }
1585 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001586 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001587
Kim Bautersa3f4b832014-05-31 07:30:03 +01001588 for (int i = 0; i < self_len; i++) { // only check alphanumeric characters
1589 if (unichar_isalpha(*self_data++)) {
1590 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001591 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1592 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001593 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001594 }
1595 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001596
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001597 if (!contains_alpha) {
1598 return mp_const_false;
1599 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001600 }
1601
1602 return mp_const_true;
1603}
1604
1605STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001606 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001607}
1608
1609STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001610 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001611}
1612
1613STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001614 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001615}
1616
1617STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001618 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001619}
1620
1621STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001622 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001623}
1624
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001625#if MICROPY_CPYTHON_COMPAT
1626// These methods are superfluous in the presense of str() and bytes()
1627// constructors.
1628// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001629STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001630 mp_obj_t new_args[2];
1631 if (n_args == 1) {
1632 new_args[0] = args[0];
1633 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1634 args = new_args;
1635 n_args++;
1636 }
1637 return str_make_new(NULL, n_args, 0, args);
1638}
1639
1640// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001641STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001642 mp_obj_t new_args[2];
1643 if (n_args == 1) {
1644 new_args[0] = args[0];
1645 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1646 args = new_args;
1647 n_args++;
1648 }
1649 return bytes_make_new(NULL, n_args, 0, args);
1650}
1651#endif
1652
Damien George4d917232014-08-30 14:28:06 +01001653mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
Damien George57a4b4f2014-04-18 22:29:21 +01001654 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001655 GET_STR_DATA_LEN(self_in, str_data, str_len);
1656 bufinfo->buf = (void*)str_data;
1657 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001658 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001659 return 0;
1660 } else {
1661 // can't write to a string
1662 bufinfo->buf = NULL;
1663 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001664 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001665 return 1;
1666 }
1667}
1668
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001669#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001670MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1671MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001672#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001673MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1674MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1675MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1676MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1677MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1678MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1679MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1680MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1681MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1682MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1683MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1684MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1685MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1686MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1687MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1688MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1689MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1690MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1691MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1692MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1693MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1694MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1695MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1696MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001697
Damien George9b196cd2014-03-26 21:47:19 +00001698STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001699#if MICROPY_CPYTHON_COMPAT
1700 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001701 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1702 // If we have separate unicode type, then here we have methods only
1703 // for bytes type, and it should not have encode() methods. Otherwise,
1704 // we have non-compliant-but-practical bytestring type, which shares
1705 // method table with bytes, so they both have encode() and decode()
1706 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001707 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001708 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001709#endif
Damien George9b196cd2014-03-26 21:47:19 +00001710 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1711 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001712 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1713 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001714 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1715 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001716 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001717 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001718 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001719 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001720 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1721 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001722 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1723 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1724 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1725 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1726 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001727 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1728 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001729 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1730 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1731 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1732 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1733 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001734};
Damien George97209d32014-01-07 15:58:30 +00001735
Damien George9b196cd2014-03-26 21:47:19 +00001736STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1737
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001738#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001739const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001740 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001741 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001742 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001743 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001744 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001745 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001746 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001747 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001748 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001749};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001750#endif
Damiend99b0522013-12-21 18:17:45 +00001751
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001752// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001753const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001754 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001755 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001756 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001757 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001758 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001759 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001760 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001761 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001762 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001763};
1764
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001765// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001766STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001767const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1768
Damien Georged182b982014-08-30 14:19:41 +01001769mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, mp_uint_t len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001770 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001771 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001772 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001773 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001774 byte *p = m_new(byte, len + 1);
1775 o->data = p;
1776 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001777 return o;
1778}
1779
Damien George5fa93b62014-01-22 14:35:10 +00001780mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001781 mp_obj_str_t *o = o_in;
1782 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001783 byte *p = (byte*)o->data;
1784 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001785 return o;
1786}
1787
Damien George5f27a7e2014-07-31 10:29:56 +01001788mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1789 mp_obj_str_t *o = o_in;
1790 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1791 o->len = len;
1792 o->hash = qstr_compute_hash(o->data, o->len);
1793 byte *p = (byte*)o->data;
1794 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1795 return o;
1796}
1797
Damien George4abff752014-08-30 14:59:21 +01001798mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, mp_uint_t len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001799 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001800 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001801 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001802 if (data) {
1803 o->hash = qstr_compute_hash(data, len);
1804 byte *p = m_new(byte, len + 1);
1805 o->data = p;
1806 memcpy(p, data, len * sizeof(byte));
1807 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1808 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001809 return o;
1810}
1811
Damien Georged182b982014-08-30 14:19:41 +01001812mp_obj_t mp_obj_new_str(const char* data, mp_uint_t len, bool make_qstr_if_not_already) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001813 if (make_qstr_if_not_already) {
1814 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001815 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001816 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001817 qstr q = qstr_find_strn(data, len);
1818 if (q != MP_QSTR_NULL) {
1819 // qstr with this data already exists
1820 return MP_OBJ_NEW_QSTR(q);
1821 } else {
1822 // no existing qstr, don't make one
1823 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1824 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001825 }
Damien George5fa93b62014-01-22 14:35:10 +00001826}
1827
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001828mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1829 GET_STR_DATA_LEN(str, data, len);
1830 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1831}
1832
Damien Georged182b982014-08-30 14:19:41 +01001833mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001834 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001835}
1836
Damien George5fa93b62014-01-22 14:35:10 +00001837bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1838 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1839 return s1 == s2;
1840 } else {
1841 GET_STR_HASH(s1, h1);
1842 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001843 // If any of hashes is 0, it means it's not valid
1844 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001845 return false;
1846 }
1847 GET_STR_DATA_LEN(s1, d1, l1);
1848 GET_STR_DATA_LEN(s2, d2, l2);
1849 if (l1 != l2) {
1850 return false;
1851 }
Damien George1e708fe2014-01-23 18:27:51 +00001852 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001853 }
Damien George5fa93b62014-01-22 14:35:10 +00001854}
1855
Damien Georgedeed0872014-04-06 11:11:15 +01001856STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001857 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 +00001858}
1859
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001860STATIC void arg_type_mixup() {
1861 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1862}
1863
Damien Georged182b982014-08-30 14:19:41 +01001864mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001865 // TODO: This has too big overhead for hash accessor
1866 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001867 GET_STR_HASH(self_in, h);
1868 return h;
1869 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001870 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001871 }
1872}
1873
Damien Georged182b982014-08-30 14:19:41 +01001874mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001875 // TODO This has a double check for the type, one in obj.c and one here
1876 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001877 GET_STR_LEN(self_in, l);
1878 return l;
1879 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001880 bad_implicit_conversion(self_in);
1881 }
1882}
1883
1884// use this if you will anyway convert the string to a qstr
1885// will be more efficient for the case where it's already a qstr
1886qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1887 if (MP_OBJ_IS_QSTR(self_in)) {
1888 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001889 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001890 mp_obj_str_t *self = self_in;
1891 return qstr_from_strn((char*)self->data, self->len);
1892 } else {
1893 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001894 }
1895}
1896
1897// only use this function if you need the str data to be zero terminated
1898// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1899const char *mp_obj_str_get_str(mp_obj_t self_in) {
1900 if (MP_OBJ_IS_STR(self_in)) {
1901 GET_STR_DATA_LEN(self_in, s, l);
1902 (void)l; // len unused
1903 return (const char*)s;
1904 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001905 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001906 }
1907}
1908
Damien Georged182b982014-08-30 14:19:41 +01001909const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001910 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001911 GET_STR_DATA_LEN(self_in, s, l);
1912 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001913 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001914 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001915 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001916 }
Damiend99b0522013-12-21 18:17:45 +00001917}
xyb8cfc9f02014-01-05 18:47:51 +08001918
1919/******************************************************************************/
1920/* str iterator */
1921
1922typedef struct _mp_obj_str_it_t {
1923 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001924 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01001925 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08001926} mp_obj_str_it_t;
1927
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001928#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001929STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001930 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001931 GET_STR_DATA_LEN(self->str, str, len);
1932 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001933 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001934 self->cur += 1;
1935 return o_out;
1936 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001937 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001938 }
1939}
1940
Damien George3e1a5c12014-03-29 13:43:38 +00001941STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001942 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001943 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001944 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001945 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001946};
1947
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001948mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
1949 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
1950 o->base.type = &mp_type_str_it;
1951 o->str = str;
1952 o->cur = 0;
1953 return o;
1954}
1955#endif
1956
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001957STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001958 mp_obj_str_it_t *self = self_in;
1959 GET_STR_DATA_LEN(self->str, str, len);
1960 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01001961 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001962 self->cur += 1;
1963 return o_out;
1964 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001965 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001966 }
1967}
1968
Damien George3e1a5c12014-03-29 13:43:38 +00001969STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001970 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001971 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001972 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001973 .iternext = bytes_it_iternext,
1974};
1975
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001976mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1977 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001978 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001979 o->str = str;
1980 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001981 return o;
1982}