blob: d6cfa8be16218a972da9bf88682992d795e10829 [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 +020045
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030046mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020047STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030048STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030049STATIC NORETURN void arg_type_mixup();
50
xyb8cfc9f02014-01-05 18:47:51 +080051/******************************************************************************/
52/* str */
53
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030054void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
Damien Georged182b982014-08-30 14:19:41 +010055 const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020056 // this escapes characters, but it will be very slow to print (calling print many times)
57 bool has_single_quote = false;
58 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100059 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020060 if (*s == '\'') {
61 has_single_quote = true;
62 } else if (*s == '"') {
63 has_double_quote = true;
64 }
65 }
66 int quote_char = '\'';
67 if (has_single_quote && !has_double_quote) {
68 quote_char = '"';
69 }
70 print(env, "%c", quote_char);
71 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
72 if (*s == quote_char) {
73 print(env, "\\%c", quote_char);
74 } else if (*s == '\\') {
75 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030076 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
77 // In strings, anything which is not ascii control character
78 // is printed as is, this includes characters in range 0x80-0xff
79 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020080 print(env, "%c", *s);
81 } else if (*s == '\n') {
82 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010083 } else if (*s == '\r') {
84 print(env, "\\r");
85 } else if (*s == '\t') {
86 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020087 } else {
88 print(env, "\\x%02x", *s);
89 }
90 }
91 print(env, "%c", quote_char);
92}
93
Damien George612045f2014-09-17 22:56:34 +010094#if MICROPY_PY_UJSON
Damien Georgecde0ca22014-09-25 17:35:56 +010095void mp_str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) {
96 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
97 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George612045f2014-09-17 22:56:34 +010098 print(env, "\"");
99 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100100 if (*s == '"' || *s == '\\') {
Damien George612045f2014-09-17 22:56:34 +0100101 print(env, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +0100102 } else if (*s >= 32) {
103 // this will handle normal and utf-8 encoded chars
Damien George612045f2014-09-17 22:56:34 +0100104 print(env, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +0100105 } else if (*s == '\n') {
106 print(env, "\\n");
107 } else if (*s == '\r') {
108 print(env, "\\r");
109 } else if (*s == '\t') {
110 print(env, "\\t");
111 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100112 // this will handle control chars
Damien George612045f2014-09-17 22:56:34 +0100113 print(env, "\\u%04x", *s);
114 }
115 }
116 print(env, "\"");
117}
118#endif
119
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200120STATIC 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 +0000121 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100122 #if MICROPY_PY_UJSON
123 if (kind == PRINT_JSON) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100124 mp_str_print_json(print, env, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100125 return;
126 }
127 #endif
Damien Georgecde0ca22014-09-25 17:35:56 +0100128 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200129 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000130 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200131 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200132 if (is_bytes) {
133 print(env, "b");
134 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300135 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200136 }
Damiend99b0522013-12-21 18:17:45 +0000137}
138
Damien Georgeecc88e92014-08-30 00:35:11 +0100139STATIC 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 +0300140#if MICROPY_CPYTHON_COMPAT
141 if (n_kw != 0) {
142 mp_arg_error_unimpl_kw();
143 }
144#endif
145
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200146 switch (n_args) {
147 case 0:
148 return MP_OBJ_NEW_QSTR(MP_QSTR_);
149
150 case 1:
151 {
152 vstr_t *vstr = vstr_new();
153 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100154 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200155 vstr_free(vstr);
156 return s;
157 }
158
159 case 2:
160 case 3:
161 {
162 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200163 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
164 GET_STR_DATA_LEN(args[0], str_data, str_len);
165 GET_STR_HASH(args[0], str_hash);
166 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
167 o->data = str_data;
168 o->hash = str_hash;
169 return o;
170 } else {
171 mp_buffer_info_t bufinfo;
172 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
173 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200174 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200175 }
176
177 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100178 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200179 }
180}
181
Damien Georgeecc88e92014-08-30 00:35:11 +0100182STATIC 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 +0200183 if (n_args == 0) {
184 return mp_const_empty_bytes;
185 }
186
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300187#if MICROPY_CPYTHON_COMPAT
188 if (n_kw != 0) {
189 mp_arg_error_unimpl_kw();
190 }
191#endif
192
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200193 if (MP_OBJ_IS_STR(args[0])) {
194 if (n_args < 2 || n_args > 3) {
195 goto wrong_args;
196 }
197 GET_STR_DATA_LEN(args[0], str_data, str_len);
198 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100199 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200200 o->data = str_data;
201 o->hash = str_hash;
202 return o;
203 }
204
205 if (n_args > 1) {
206 goto wrong_args;
207 }
208
209 if (MP_OBJ_IS_SMALL_INT(args[0])) {
210 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
211 byte *data;
212
Damien George3e1a5c12014-03-29 13:43:38 +0000213 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200214 memset(data, 0, len);
215 return mp_obj_str_builder_end(o);
216 }
217
Damien George39dc1452014-10-03 19:52:22 +0100218 mp_int_t len;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200219 byte *data;
220 vstr_t *vstr = NULL;
Damien George3aa09f52014-10-23 12:06:53 +0100221 mp_obj_t o = MP_OBJ_NULL;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200222 // Try to create array of exact len if initializer len is known
223 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
224 if (len_in == MP_OBJ_NULL) {
225 len = -1;
226 vstr = vstr_new();
227 } else {
228 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000229 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200230 }
231
Damien Georged17926d2014-03-30 13:35:08 +0100232 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200233 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100234 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200235 if (len == -1) {
236 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
237 } else {
238 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
239 }
240 }
241
242 if (len == -1) {
243 vstr_shrink(vstr);
244 // TODO: Optimize, borrow buffer from vstr
245 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000246 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200247 memcpy(data, vstr_str(vstr), len);
248 vstr_free(vstr);
249 }
250
251 return mp_obj_str_builder_end(o);
252
253wrong_args:
Damien Georgeea13f402014-04-05 18:32:08 +0100254 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200255}
256
Damien George55baff42014-01-21 21:40:13 +0000257// like strstr but with specified length and allows \0 bytes
258// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100259STATIC 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 +0000260 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100261 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700262 if (direction > 0) {
263 str_index = 0;
264 str_index_end = hlen - nlen;
265 } else {
266 str_index = hlen - nlen;
267 str_index_end = 0;
268 }
269 for (;;) {
270 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
271 //found
272 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000273 }
xbe17a5a832014-03-23 23:31:58 -0700274 if (str_index == str_index_end) {
275 //not found
276 break;
Damien George55baff42014-01-21 21:40:13 +0000277 }
xbe17a5a832014-03-23 23:31:58 -0700278 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000279 }
280 }
281 return NULL;
282}
283
Damien Georgea75b02e2014-08-27 09:20:30 +0100284// Note: this function is used to check if an object is a str or bytes, which
285// works because both those types use it as their binary_op method. Revisit
286// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100287mp_obj_t mp_obj_str_binary_op(mp_uint_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien Georgea65c03c2014-11-05 16:30:34 +0000288 // check for modulo
289 if (op == MP_BINARY_OP_MODULO) {
290 mp_obj_t *args;
291 mp_uint_t n_args;
292 mp_obj_t dict = MP_OBJ_NULL;
293 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
294 // TODO: Support tuple subclasses?
295 mp_obj_tuple_get(rhs_in, &n_args, &args);
296 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
297 args = NULL;
298 n_args = 0;
299 dict = rhs_in;
300 } else {
301 args = &rhs_in;
302 n_args = 1;
303 }
304 return str_modulo_format(lhs_in, n_args, args, dict);
305 }
306
307 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300308 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000309 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
310
311 // check for multiply
312 if (op == MP_BINARY_OP_MULTIPLY) {
313 mp_int_t n;
314 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
315 return MP_OBJ_NULL; // op not supported
316 }
317 if (n <= 0) {
318 if (lhs_type == &mp_type_str) {
319 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
320 } else {
321 return mp_const_empty_bytes;
322 }
323 }
324 byte *data;
325 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
326 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
327 return mp_obj_str_builder_end(s);
328 }
329
330 // From now on all operations allow:
331 // - str with str
332 // - bytes with bytes
333 // - bytes with bytearray
334 // - bytes with array.array
335 // To do this efficiently we use the buffer protocol to extract the raw
336 // data for the rhs, but only if the lhs is a bytes object.
337 //
338 // NOTE: CPython does not allow comparison between bytes ard array.array
339 // (even if the array is of type 'b'), even though it allows addition of
340 // such types. We are not compatible with this (we do allow comparison
341 // of bytes with anything that has the buffer protocol). It would be
342 // easy to "fix" this with a bit of extra logic below, but it costs code
343 // size and execution time so we don't.
344
345 const byte *rhs_data;
346 mp_uint_t rhs_len;
347 if (lhs_type == mp_obj_get_type(rhs_in)) {
348 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
349 rhs_data = rhs_data_;
350 rhs_len = rhs_len_;
351 } else if (lhs_type == &mp_type_bytes) {
352 mp_buffer_info_t bufinfo;
353 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
354 goto incompatible;
355 }
356 rhs_data = bufinfo.buf;
357 rhs_len = bufinfo.len;
358 } else {
359 // incompatible types
360 incompatible:
361 if (op == MP_BINARY_OP_EQUAL) {
362 return mp_const_false; // can check for equality against every type
363 }
364 return MP_OBJ_NULL; // op not supported
365 }
366
Damiend99b0522013-12-21 18:17:45 +0000367 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100368 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000369 case MP_BINARY_OP_INPLACE_ADD: {
370 mp_uint_t alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000371 byte *data;
Damien Georgea65c03c2014-11-05 16:30:34 +0000372 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
373 memcpy(data, lhs_data, lhs_len);
374 memcpy(data + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000375 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200376 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200377
Damien Georgea65c03c2014-11-05 16:30:34 +0000378 case MP_BINARY_OP_IN:
379 /* NOTE `a in b` is `b.__contains__(a)` */
380 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300381
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300382 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
383 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 +0100384 case MP_BINARY_OP_LESS:
385 case MP_BINARY_OP_LESS_EQUAL:
386 case MP_BINARY_OP_MORE:
387 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000388 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000389 }
390
Damien George6ac5dce2014-05-21 19:42:43 +0100391 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000392}
393
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300394#if !MICROPY_PY_BUILTINS_STR_UNICODE
395// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100396const 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 +0300397 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100398 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300399 return self_data + index_val;
400}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300401#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300402
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300403// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
404STATIC 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 +0300405 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100406 GET_STR_DATA_LEN(self_in, self_data, self_len);
407 if (value == MP_OBJ_SENTINEL) {
408 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100409#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100410 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300411 mp_bound_slice_t slice;
412 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300413 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100414 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100415 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100416 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100417 }
418#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300419 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100420 // If we have unicode enabled the type will always be bytes, so take the short cut.
421 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300422 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100423 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300424 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100425 }
426 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100427 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100428 }
429}
430
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200431STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700432 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300433 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000434
Damien Georgefe8fb912014-01-02 16:36:09 +0000435 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000436 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000437
438 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100439 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000440 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000441 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000442 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000443 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100444 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
445 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300446 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100447 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
448 }
449 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000450 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000451
452 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100453 mp_uint_t required_len = 0;
454 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300455 if (mp_obj_get_type(seq_items[i]) != self_type) {
456 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
457 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000458 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000459 if (i > 0) {
460 required_len += sep_len;
461 }
Damien George5fa93b62014-01-22 14:35:10 +0000462 GET_STR_LEN(seq_items[i], l);
463 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000464 }
465
466 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000467 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300468 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damien George39dc1452014-10-03 19:52:22 +0100469 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000470 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000471 memcpy(data, sep_str, sep_len);
472 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000473 }
Damien George5fa93b62014-01-22 14:35:10 +0000474 GET_STR_DATA_LEN(seq_items[i], s, l);
475 memcpy(data, s, l);
476 data += l;
Damiend99b0522013-12-21 18:17:45 +0000477 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000478
479 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000480 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000481}
482
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200483#define is_ws(c) ((c) == ' ' || (c) == '\t')
484
Damien Georgeecc88e92014-08-30 00:35:11 +0100485STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300486 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100487 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200488 mp_obj_t sep = mp_const_none;
489 if (n_args > 1) {
490 sep = args[1];
491 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100492 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200493 }
494 }
Damien Georgedeed0872014-04-06 11:11:15 +0100495
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200496 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000497 GET_STR_DATA_LEN(args[0], s, len);
498 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200499
Damien Georgedeed0872014-04-06 11:11:15 +0100500 if (sep == mp_const_none) {
501 // sep not given, so separate on whitespace
502
503 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000504 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100505 while (s < top && splits != 0) {
506 const byte *start = s;
507 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100508 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100509 if (s >= top) {
510 break;
511 }
512 while (s < top && is_ws(*s)) s++;
513 if (splits > 0) {
514 splits--;
515 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200516 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200517
Damien Georgedeed0872014-04-06 11:11:15 +0100518 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100519 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100520 }
521
522 } else {
523 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300524 if (mp_obj_get_type(sep) != self_type) {
525 arg_type_mixup();
526 }
Damien Georgedeed0872014-04-06 11:11:15 +0100527
Damien Georged182b982014-08-30 14:19:41 +0100528 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100529 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
530
531 if (sep_len == 0) {
532 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
533 }
534
535 for (;;) {
536 const byte *start = s;
537 for (;;) {
538 if (splits == 0 || s + sep_len > top) {
539 s = top;
540 break;
541 } else if (memcmp(s, sep_str, sep_len) == 0) {
542 break;
543 }
544 s++;
545 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100546 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100547 if (s >= top) {
548 break;
549 }
550 s += sep_len;
551 if (splits > 0) {
552 splits--;
553 }
554 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200555 }
556
557 return res;
558}
559
Damien Georgeecc88e92014-08-30 00:35:11 +0100560STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300561 if (n_args < 3) {
562 // If we don't have split limit, it doesn't matter from which side
563 // we split.
564 return str_split(n_args, args);
565 }
566 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
567 mp_obj_t sep = args[1];
568 GET_STR_DATA_LEN(args[0], s, len);
569
Damien George40f3c022014-07-03 13:25:24 +0100570 mp_int_t splits = mp_obj_get_int(args[2]);
571 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300572 // Preallocate list to the max expected # of elements, as we
573 // will fill it from the end.
574 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100575 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300576
577 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000578 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300579 } else {
Damien Georged182b982014-08-30 14:19:41 +0100580 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300581 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
582
583 if (sep_len == 0) {
584 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
585 }
586
587 const byte *beg = s;
588 const byte *last = s + len;
589 for (;;) {
590 s = last - sep_len;
591 for (;;) {
592 if (splits == 0 || s < beg) {
593 break;
594 } else if (memcmp(s, sep_str, sep_len) == 0) {
595 break;
596 }
597 s--;
598 }
599 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100600 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300601 break;
602 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100603 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 +0300604 last = s;
605 if (splits > 0) {
606 splits--;
607 }
608 }
609 if (idx != 0) {
610 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100611 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100612 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300613 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
614 res->len = used;
615 }
616 }
617
618 return res;
619}
620
Damien Georgeecc88e92014-08-30 00:35:11 +0100621STATIC 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 +0300622 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000623 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000624 assert(MP_OBJ_IS_STR(args[0]));
625 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000626
Damien George5fa93b62014-01-22 14:35:10 +0000627 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
628 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000629
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300630 const byte *start = haystack;
631 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000632 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300633 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000634 }
635 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300636 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000637 }
638
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300639 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000640 if (p == NULL) {
641 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700642 if (is_index) {
643 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
644 } else {
645 return MP_OBJ_NEW_SMALL_INT(-1);
646 }
Damien George23005372014-01-13 19:39:01 +0000647 } else {
648 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300649 #if MICROPY_PY_BUILTINS_STR_UNICODE
650 if (self_type == &mp_type_str) {
651 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
652 }
653 #endif
xbe17a5a832014-03-23 23:31:58 -0700654 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000655 }
John R. Lentone8204912014-01-12 21:53:52 +0000656}
657
Damien Georgeecc88e92014-08-30 00:35:11 +0100658STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700659 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700660}
661
Damien Georgeecc88e92014-08-30 00:35:11 +0100662STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700663 return str_finder(n_args, args, -1, false);
664}
665
Damien Georgeecc88e92014-08-30 00:35:11 +0100666STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700667 return str_finder(n_args, args, 1, true);
668}
669
Damien Georgeecc88e92014-08-30 00:35:11 +0100670STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700671 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700672}
673
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200674// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100675STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300676 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300677 GET_STR_DATA_LEN(args[0], str, str_len);
678 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300679 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300680 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300681 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300682 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300683 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200684 return mp_const_false;
685 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300686 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200687}
688
Damien Georgeecc88e92014-08-30 00:35:11 +0100689STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300690 GET_STR_DATA_LEN(args[0], str, str_len);
691 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
692 assert(n_args == 2);
693
694 if (suffix_len > str_len) {
695 return mp_const_false;
696 }
697 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
698}
699
Paul Sokolovsky88107842014-04-26 06:20:08 +0300700enum { LSTRIP, RSTRIP, STRIP };
701
Damien Georgeecc88e92014-08-30 00:35:11 +0100702STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800703 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700704 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300705 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000706
707 const byte *chars_to_del;
708 uint chars_to_del_len;
709 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800710
711 if (n_args == 1) {
712 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000713 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800714 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300715 if (mp_obj_get_type(args[1]) != self_type) {
716 arg_type_mixup();
717 }
Damien George5fa93b62014-01-22 14:35:10 +0000718 GET_STR_DATA_LEN(args[1], s, l);
719 chars_to_del = s;
720 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800721 }
722
Damien George5fa93b62014-01-22 14:35:10 +0000723 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800724
Damien George40f3c022014-07-03 13:25:24 +0100725 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800726 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100727 mp_uint_t last_good_char_pos = 0;
728 mp_uint_t i = 0;
729 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300730 if (type == RSTRIP) {
731 i = orig_str_len - 1;
732 delta = -1;
733 }
Damien George40f3c022014-07-03 13:25:24 +0100734 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700735 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800736 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300737 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800738 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300739 if (type == LSTRIP) {
740 last_good_char_pos = orig_str_len - 1;
741 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300742 } else if (type == RSTRIP) {
743 first_good_char_pos = 0;
744 last_good_char_pos = i;
745 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300746 }
xbe7b0f39f2014-01-08 14:23:45 -0800747 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300748 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800749 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300750 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800751 }
752
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300753 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000754 // string is all whitespace, return ''
755 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800756 }
757
758 assert(last_good_char_pos >= first_good_char_pos);
759 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100760 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300761 if (stripped_len == orig_str_len) {
762 // If nothing was stripped, don't bother to dup original string
763 // TODO: watch out for this case when we'll get to bytearray.strip()
764 assert(first_good_char_pos == 0);
765 return args[0];
766 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100767 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800768}
769
Damien Georgeecc88e92014-08-30 00:35:11 +0100770STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300771 return str_uni_strip(STRIP, n_args, args);
772}
773
Damien Georgeecc88e92014-08-30 00:35:11 +0100774STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300775 return str_uni_strip(LSTRIP, n_args, args);
776}
777
Damien Georgeecc88e92014-08-30 00:35:11 +0100778STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300779 return str_uni_strip(RSTRIP, n_args, args);
780}
781
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700782// Takes an int arg, but only parses unsigned numbers, and only changes
783// *num if at least one digit was parsed.
784static int str_to_int(const char *str, int *num) {
785 const char *s = str;
786 if (unichar_isdigit(*s)) {
787 *num = 0;
788 do {
789 *num = *num * 10 + (*s - '0');
790 s++;
791 }
792 while (unichar_isdigit(*s));
793 }
794 return s - str;
795}
796
797static bool isalignment(char ch) {
798 return ch && strchr("<>=^", ch) != NULL;
799}
800
801static bool istype(char ch) {
802 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
803}
804
805static bool arg_looks_integer(mp_obj_t arg) {
806 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
807}
808
809static bool arg_looks_numeric(mp_obj_t arg) {
810 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100811#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700812 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
813#endif
814 ;
815}
816
Dave Hylandsc4029e52014-04-07 11:19:51 -0700817static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100818#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700819 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700820
821 // TODO: Needs a way to construct an mpz integer from a float
822
Damien George40f3c022014-07-03 13:25:24 +0100823 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700824 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700825 }
826#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700827 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700828}
829
Damien Georgeecc88e92014-08-30 00:35:11 +0100830mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000831 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000832
Damien George5fa93b62014-01-22 14:35:10 +0000833 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700834 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000835 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700836 pfenv_t pfenv_vstr;
837 pfenv_vstr.data = vstr;
838 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
839
Damien George5fa93b62014-01-22 14:35:10 +0000840 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700841 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000842 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700843 if (str < top && *str == '}') {
844 vstr_add_char(vstr, '}');
845 continue;
846 }
Damien George11de8392014-06-05 18:57:38 +0100847 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700848 }
849 if (*str != '{') {
850 vstr_add_char(vstr, *str);
851 continue;
852 }
853
854 str++;
855 if (str < top && *str == '{') {
856 vstr_add_char(vstr, '{');
857 continue;
858 }
859
860 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
861
862 vstr_t *field_name = NULL;
863 char conversion = '\0';
864 vstr_t *format_spec = NULL;
865
866 if (str < top && *str != '}' && *str != '!' && *str != ':') {
867 field_name = vstr_new();
868 while (str < top && *str != '}' && *str != '!' && *str != ':') {
869 vstr_add_char(field_name, *str++);
870 }
871 vstr_add_char(field_name, '\0');
872 }
873
874 // conversion ::= "r" | "s"
875
876 if (str < top && *str == '!') {
877 str++;
878 if (str < top && (*str == 'r' || *str == 's')) {
879 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200880 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100881 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 -0700882 }
883 }
884
885 if (str < top && *str == ':') {
886 str++;
887 // {:} is the same as {}, which is the same as {!s}
888 // This makes a difference when passing in a True or False
889 // '{}'.format(True) returns 'True'
890 // '{:d}'.format(True) returns '1'
891 // So we treat {:} as {} and this later gets treated to be {!s}
892 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100893 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700894 while (str < top && *str != '}') {
895 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000896 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700897 vstr_add_char(format_spec, '\0');
898 }
899 }
900 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100901 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902 }
903 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100904 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 }
906
907 mp_obj_t arg = mp_const_none;
908
909 if (field_name) {
910 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100911 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 -0700912 }
Damien George3bb8bd82014-04-14 21:20:30 +0100913 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700914 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100915 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700916 }
917 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100918 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700919 }
920 arg = args[index + 1];
921 arg_i = -1;
922 vstr_free(field_name);
923 field_name = NULL;
924 } else {
925 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100926 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 -0700927 }
928 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100929 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700930 }
931 arg = args[arg_i + 1];
932 arg_i++;
933 }
934 if (!format_spec && !conversion) {
935 conversion = 's';
936 }
937 if (conversion) {
938 mp_print_kind_t print_kind;
939 if (conversion == 's') {
940 print_kind = PRINT_STR;
941 } else if (conversion == 'r') {
942 print_kind = PRINT_REPR;
943 } else {
Damien George11de8392014-06-05 18:57:38 +0100944 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700945 }
946 vstr_t *arg_vstr = vstr_new();
947 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100948 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700949 vstr_free(arg_vstr);
950 }
951
952 char sign = '\0';
953 char fill = '\0';
954 char align = '\0';
955 int width = -1;
956 int precision = -1;
957 char type = '\0';
958 int flags = 0;
959
960 if (format_spec) {
961 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
962 //
963 // [[fill]align][sign][#][0][width][,][.precision][type]
964 // fill ::= <any character>
965 // align ::= "<" | ">" | "=" | "^"
966 // sign ::= "+" | "-" | " "
967 // width ::= integer
968 // precision ::= integer
969 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
970
971 const char *s = vstr_str(format_spec);
972 if (isalignment(*s)) {
973 align = *s++;
974 } else if (*s && isalignment(s[1])) {
975 fill = *s++;
976 align = *s++;
977 }
978 if (*s == '+' || *s == '-' || *s == ' ') {
979 if (*s == '+') {
980 flags |= PF_FLAG_SHOW_SIGN;
981 } else if (*s == ' ') {
982 flags |= PF_FLAG_SPACE_SIGN;
983 }
984 sign = *s++;
985 }
986 if (*s == '#') {
987 flags |= PF_FLAG_SHOW_PREFIX;
988 s++;
989 }
990 if (*s == '0') {
991 if (!align) {
992 align = '=';
993 }
994 if (!fill) {
995 fill = '0';
996 }
997 }
998 s += str_to_int(s, &width);
999 if (*s == ',') {
1000 flags |= PF_FLAG_SHOW_COMMA;
1001 s++;
1002 }
1003 if (*s == '.') {
1004 s++;
1005 s += str_to_int(s, &precision);
1006 }
1007 if (istype(*s)) {
1008 type = *s++;
1009 }
1010 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001011 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001012 }
1013 vstr_free(format_spec);
1014 format_spec = NULL;
1015 }
1016 if (!align) {
1017 if (arg_looks_numeric(arg)) {
1018 align = '>';
1019 } else {
1020 align = '<';
1021 }
1022 }
1023 if (!fill) {
1024 fill = ' ';
1025 }
1026
1027 if (sign) {
1028 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +01001029 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001030 }
1031 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +01001032 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +00001033 }
1034 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001035 sign = '-';
1036 }
1037
1038 switch (align) {
1039 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1040 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1041 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1042 }
1043
1044 if (arg_looks_integer(arg)) {
1045 switch (type) {
1046 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001047 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001048 continue;
1049
1050 case 'c':
1051 {
1052 char ch = mp_obj_get_int(arg);
1053 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1054 continue;
1055 }
1056
1057 case '\0': // No explicit format type implies 'd'
1058 case 'n': // I don't think we support locales in uPy so use 'd'
1059 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001060 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001061 continue;
1062
1063 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001064 if (flags & PF_FLAG_SHOW_PREFIX) {
1065 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1066 }
1067
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001068 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001069 continue;
1070
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001071 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001072 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001073 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001074 continue;
1075
1076 case 'e':
1077 case 'E':
1078 case 'f':
1079 case 'F':
1080 case 'g':
1081 case 'G':
1082 case '%':
1083 // The floating point formatters all work with anything that
1084 // looks like an integer
1085 break;
1086
1087 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001088 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001089 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001090 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001091 }
Damien George70f33cd2014-04-02 17:06:05 +01001092
Dave Hylands22fe4d72014-04-02 12:07:31 -07001093 // NOTE: no else here. We need the e, f, g etc formats for integer
1094 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001095 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001096 if (!type) {
1097
1098 // Even though the docs say that an unspecified type is the same
1099 // as 'g', there is one subtle difference, when the exponent
1100 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001101 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001102 // '{:10.1}'.format(0.0) ==> '0e+00'
1103 // '{:10.1g}'.format(0.0) ==> '0'
1104 //
1105 // TODO: Figure out how to deal with this.
1106 //
1107 // A proper solution would involve adding a special flag
1108 // or something to format_float, and create a format_double
1109 // to deal with doubles. In order to fix this when using
1110 // sprintf, we'd need to use the e format and tweak the
1111 // returned result to strip trailing zeros like the g format
1112 // does.
1113 //
1114 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1115 // but with 1.e2 you get 1e+02 and 1.00e+02
1116 //
1117 // Stripping the trailing 0's (like g) does would make the
1118 // e format give us the right format.
1119 //
1120 // CPython sources say:
1121 // Omitted type specifier. Behaves in the same way as repr(x)
1122 // and str(x) if no precision is given, else like 'g', but with
1123 // at least one digit after the decimal point. */
1124
1125 type = 'g';
1126 }
1127 if (type == 'n') {
1128 type = 'g';
1129 }
1130
1131 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1132 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001133#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001134 case 'e':
1135 case 'E':
1136 case 'f':
1137 case 'F':
1138 case 'g':
1139 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001140 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001141 break;
1142
1143 case '%':
1144 flags |= PF_FLAG_ADD_PERCENT;
1145 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1146 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001147#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001148
1149 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001150 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001151 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001152 type, mp_obj_get_type_str(arg)));
1153 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001154 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001155 // arg doesn't look like a number
1156
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001157 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001158 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001159 }
Damien George70f33cd2014-04-02 17:06:05 +01001160
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001161 switch (type) {
1162 case '\0':
1163 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1164 break;
1165
Damien Georged182b982014-08-30 14:19:41 +01001166 case 's': {
1167 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001168 const char *s = mp_obj_str_get_data(arg, &len);
1169 if (precision < 0) {
1170 precision = len;
1171 }
1172 if (len > precision) {
1173 len = precision;
1174 }
1175 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1176 break;
1177 }
1178
1179 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001180 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001181 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001182 type, mp_obj_get_type_str(arg)));
1183 }
Damiend99b0522013-12-21 18:17:45 +00001184 }
1185 }
1186
Damien George2617eeb2014-05-25 22:27:57 +01001187 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001188 vstr_free(vstr);
1189 return s;
Damiend99b0522013-12-21 18:17:45 +00001190}
1191
Damien Georgeecc88e92014-08-30 00:35:11 +01001192STATIC 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 +03001193 assert(MP_OBJ_IS_STR(pattern));
1194
1195 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001196 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001197 int arg_i = 0;
1198 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001199 pfenv_t pfenv_vstr;
1200 pfenv_vstr.data = vstr;
1201 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1202
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001203 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001204 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001205 if (*str != '%') {
1206 vstr_add_char(vstr, *str);
1207 continue;
1208 }
1209 if (++str >= top) {
1210 break;
1211 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001212 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001213 vstr_add_char(vstr, '%');
1214 continue;
1215 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001216
1217 // Dictionary value lookup
1218 if (*str == '(') {
1219 const byte *key = ++str;
1220 while (*str != ')') {
1221 if (str >= top) {
1222 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1223 }
1224 ++str;
1225 }
1226 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1227 arg = mp_obj_dict_get(dict, k_obj);
1228 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001229 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001230
Dave Hylands6756a372014-04-02 11:42:39 -07001231 int flags = 0;
1232 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001233 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001234 while (str < top) {
1235 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1236 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1237 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001238 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001239 else if (*str == '0') {
1240 flags |= PF_FLAG_PAD_AFTER_SIGN;
1241 fill = '0';
1242 } else break;
1243 str++;
1244 }
1245 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001246 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001247 if (str < top) {
1248 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001249 if (arg_i >= n_args) {
1250 goto not_enough_args;
1251 }
Dave Hylands6756a372014-04-02 11:42:39 -07001252 width = mp_obj_get_int(args[arg_i++]);
1253 str++;
1254 } else {
1255 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1256 width = width * 10 + *str - '0';
1257 }
1258 }
1259 }
1260 int prec = -1;
1261 if (str < top && *str == '.') {
1262 if (++str < top) {
1263 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001264 if (arg_i >= n_args) {
1265 goto not_enough_args;
1266 }
Dave Hylands6756a372014-04-02 11:42:39 -07001267 prec = mp_obj_get_int(args[arg_i++]);
1268 str++;
1269 } else {
1270 prec = 0;
1271 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1272 prec = prec * 10 + *str - '0';
1273 }
1274 }
1275 }
1276 }
1277
1278 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001279 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001280 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001281
1282 // Tuple value lookup
1283 if (arg == MP_OBJ_NULL) {
1284 if (arg_i >= n_args) {
1285not_enough_args:
1286 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1287 }
1288 arg = args[arg_i++];
1289 }
Dave Hylands6756a372014-04-02 11:42:39 -07001290 switch (*str) {
1291 case 'c':
1292 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001293 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001294 const char *s = mp_obj_str_get_data(arg, &len);
1295 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001296 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001297 break;
1298 }
1299 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1300 break;
1301 }
1302 if (arg_looks_integer(arg)) {
1303 char ch = mp_obj_get_int(arg);
1304 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1305 break;
1306 }
Damien Georgefb510b32014-06-01 13:32:54 +01001307#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001308 // This is what CPython reports, so we report the same.
1309 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001310 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001311
1312 }
1313#endif
Damien George11de8392014-06-05 18:57:38 +01001314 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1315 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001316
1317 case 'd':
1318 case 'i':
1319 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001320 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001321 break;
1322
Damien Georgefb510b32014-06-01 13:32:54 +01001323#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001324 case 'e':
1325 case 'E':
1326 case 'f':
1327 case 'F':
1328 case 'g':
1329 case 'G':
1330 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1331 break;
1332#endif
1333
1334 case 'o':
1335 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001336 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001337 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001338 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001339 break;
1340
1341 case 'r':
1342 case 's':
1343 {
1344 vstr_t *arg_vstr = vstr_new();
1345 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1346 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1347 uint len = vstr_len(arg_vstr);
1348 if (prec < 0) {
1349 prec = len;
1350 }
1351 if (len > prec) {
1352 len = prec;
1353 }
1354 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1355 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001356 break;
1357 }
Dave Hylands6756a372014-04-02 11:42:39 -07001358
Dave Hylands6756a372014-04-02 11:42:39 -07001359 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001360 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001361 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001362 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001363
Dave Hylands6756a372014-04-02 11:42:39 -07001364 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001365 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001366 "unsupported format character '%c' (0x%x) at index %d",
1367 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001368 }
1369 }
1370
1371 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001372 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001373 }
1374
Damien George2617eeb2014-05-25 22:27:57 +01001375 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001376 vstr_free(vstr);
1377 return s;
1378}
1379
Damien Georgeecc88e92014-08-30 00:35:11 +01001380STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001381 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001382
Damien George40f3c022014-07-03 13:25:24 +01001383 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001384 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001385 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001386 if (max_rep == 0) {
1387 return args[0];
1388 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001389 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001390 }
xbe480c15a2014-01-30 22:17:30 -08001391 }
Damien George94f68302014-01-31 23:45:12 +00001392
xbe729be9b2014-04-07 14:46:39 -07001393 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001394
Damien Georgeff715422014-04-07 00:39:13 +01001395 // check argument types
1396
1397 if (!MP_OBJ_IS_STR(args[1])) {
1398 bad_implicit_conversion(args[1]);
1399 }
1400
1401 if (!MP_OBJ_IS_STR(args[2])) {
1402 bad_implicit_conversion(args[2]);
1403 }
1404
1405 // extract string data
1406
xbe480c15a2014-01-30 22:17:30 -08001407 GET_STR_DATA_LEN(args[0], str, str_len);
1408 GET_STR_DATA_LEN(args[1], old, old_len);
1409 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001410
1411 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001412 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001413 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001414 }
1415
Damien George94f68302014-01-31 23:45:12 +00001416 // data for the replaced string
1417 byte *data = NULL;
1418 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001419
Damien George94f68302014-01-31 23:45:12 +00001420 // do 2 passes over the string:
1421 // first pass computes the required length of the replaced string
1422 // second pass does the replacements
1423 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001424 mp_uint_t replaced_str_index = 0;
1425 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001426 const byte *old_occurrence;
1427 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001428 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001429 if (old_len == 0) {
1430 // if old_str is empty, copy new_str to start of replaced string
1431 // copy the replacement string
1432 if (data != NULL) {
1433 memcpy(data, new, new_len);
1434 }
1435 replaced_str_index += new_len;
1436 num_replacements_done++;
1437 }
1438 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1439 if (old_len == 0) {
1440 old_occurrence += 1;
1441 }
Damien George94f68302014-01-31 23:45:12 +00001442 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1443 if (data != NULL) {
1444 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1445 }
1446 replaced_str_index += old_occurrence - offset_ptr;
1447 // copy the replacement string
1448 if (data != NULL) {
1449 memcpy(data + replaced_str_index, new, new_len);
1450 }
1451 replaced_str_index += new_len;
1452 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001453 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001454 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001455 }
1456
1457 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1458 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001459 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001460 }
Damien Georgeff715422014-04-07 00:39:13 +01001461 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001462
1463 if (data == NULL) {
1464 // first pass
1465 if (num_replacements_done == 0) {
1466 // no substr found, return original string
1467 return args[0];
1468 } else {
1469 // substr found, allocate new string
1470 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001471 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001472 }
1473 } else {
1474 // second pass, we are done
1475 break;
1476 }
xbe480c15a2014-01-30 22:17:30 -08001477 }
Damien George94f68302014-01-31 23:45:12 +00001478
xbe480c15a2014-01-30 22:17:30 -08001479 return mp_obj_str_builder_end(replaced_str);
1480}
1481
Damien Georgeecc88e92014-08-30 00:35:11 +01001482STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001483 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001484 assert(2 <= n_args && n_args <= 4);
1485 assert(MP_OBJ_IS_STR(args[0]));
1486 assert(MP_OBJ_IS_STR(args[1]));
1487
1488 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1489 GET_STR_DATA_LEN(args[1], needle, needle_len);
1490
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001491 const byte *start = haystack;
1492 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001493 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001494 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001495 }
1496 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001497 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001498 }
1499
Damien George536dde22014-03-13 22:07:55 +00001500 // if needle_len is zero then we count each gap between characters as an occurrence
1501 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001502 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001503 }
1504
Damien George536dde22014-03-13 22:07:55 +00001505 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001506 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001507 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1508 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001509 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001510 haystack_ptr += needle_len;
1511 } else {
1512 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001513 }
xbe9e1e8cd2014-03-12 22:57:16 -07001514 }
1515
1516 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1517}
1518
Damien George40f3c022014-07-03 13:25:24 +01001519STATIC 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 -07001520 if (!MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001521 assert(0);
1522 }
1523 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1524 if (self_type != mp_obj_get_type(arg)) {
1525 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001526 }
Damien Georgeb035db32014-03-21 20:39:40 +00001527
xbe613a8e32014-03-18 00:06:29 -07001528 GET_STR_DATA_LEN(self_in, str, str_len);
1529 GET_STR_DATA_LEN(arg, sep, sep_len);
1530
1531 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001532 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001533 }
Damien Georgeb035db32014-03-21 20:39:40 +00001534
1535 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1536
1537 if (direction > 0) {
1538 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001539 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001540 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001541 }
xbe613a8e32014-03-18 00:06:29 -07001542
xbe17a5a832014-03-23 23:31:58 -07001543 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1544 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001545 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001546 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001547 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001548 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 -07001549 }
Damien Georgeb035db32014-03-21 20:39:40 +00001550
xbe0a6894c2014-03-21 01:12:26 -07001551 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001552}
1553
Damien Georgeb035db32014-03-21 20:39:40 +00001554STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1555 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001556}
xbe4504ea82014-03-19 00:46:14 -07001557
Damien Georgeb035db32014-03-21 20:39:40 +00001558STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1559 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001560}
1561
Paul Sokolovsky69135212014-05-10 19:47:41 +03001562// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001563STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001564 GET_STR_DATA_LEN(self_in, self_data, self_len);
1565 byte *data;
1566 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(self_in), self_len, &data);
Damien George39dc1452014-10-03 19:52:22 +01001567 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001568 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001569 }
1570 *data = 0;
1571 return mp_obj_str_builder_end(s);
1572}
1573
1574STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001575 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001576}
1577
1578STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001579 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001580}
1581
Damien Georgefcc9cf62014-06-01 18:22:09 +01001582STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001583 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001584
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001585 if (self_len == 0) {
1586 return mp_const_false; // default to False for empty str
1587 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001588
Damien Georgefcc9cf62014-06-01 18:22:09 +01001589 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001590 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001591 if (!f(*self_data++)) {
1592 return mp_const_false;
1593 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001594 }
1595 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001596 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001597
Damien George39dc1452014-10-03 19:52:22 +01001598 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001599 if (unichar_isalpha(*self_data++)) {
1600 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001601 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1602 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001603 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001604 }
1605 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001606
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001607 if (!contains_alpha) {
1608 return mp_const_false;
1609 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001610 }
1611
1612 return mp_const_true;
1613}
1614
1615STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001616 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001617}
1618
1619STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001620 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001621}
1622
1623STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001624 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001625}
1626
1627STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001628 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001629}
1630
1631STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001632 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001633}
1634
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001635#if MICROPY_CPYTHON_COMPAT
1636// These methods are superfluous in the presense of str() and bytes()
1637// constructors.
1638// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001639STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001640 mp_obj_t new_args[2];
1641 if (n_args == 1) {
1642 new_args[0] = args[0];
1643 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1644 args = new_args;
1645 n_args++;
1646 }
1647 return str_make_new(NULL, n_args, 0, args);
1648}
1649
1650// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001651STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001652 mp_obj_t new_args[2];
1653 if (n_args == 1) {
1654 new_args[0] = args[0];
1655 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1656 args = new_args;
1657 n_args++;
1658 }
1659 return bytes_make_new(NULL, n_args, 0, args);
1660}
1661#endif
1662
Damien George4d917232014-08-30 14:28:06 +01001663mp_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 +01001664 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001665 GET_STR_DATA_LEN(self_in, str_data, str_len);
1666 bufinfo->buf = (void*)str_data;
1667 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001668 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001669 return 0;
1670 } else {
1671 // can't write to a string
1672 bufinfo->buf = NULL;
1673 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001674 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001675 return 1;
1676 }
1677}
1678
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001679#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001680MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1681MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001682#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001683MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1684MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1685MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1686MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1687MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1688MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1689MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1690MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1691MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1692MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1693MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1694MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1695MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1696MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1697MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1698MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1699MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1700MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1701MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1702MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1703MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1704MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1705MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1706MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001707
Damien George9b196cd2014-03-26 21:47:19 +00001708STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001709#if MICROPY_CPYTHON_COMPAT
1710 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001711 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1712 // If we have separate unicode type, then here we have methods only
1713 // for bytes type, and it should not have encode() methods. Otherwise,
1714 // we have non-compliant-but-practical bytestring type, which shares
1715 // method table with bytes, so they both have encode() and decode()
1716 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001717 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001718 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001719#endif
Damien George9b196cd2014-03-26 21:47:19 +00001720 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1721 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001722 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1723 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001724 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1725 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001726 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001727 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001728 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001729 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001730 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1731 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001732 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1733 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1734 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1735 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1736 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001737 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1738 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001739 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1740 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1741 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1742 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1743 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001744};
Damien George97209d32014-01-07 15:58:30 +00001745
Damien George9b196cd2014-03-26 21:47:19 +00001746STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1747
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001748#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001749const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001750 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001751 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001752 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001753 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001754 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001755 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001756 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001757 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001758 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001759};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001760#endif
Damiend99b0522013-12-21 18:17:45 +00001761
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001762// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001763const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001764 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001765 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001766 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001767 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001768 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001769 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001770 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001771 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001772 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001773};
1774
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001775// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001776const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001777
Damien Georged182b982014-08-30 14:19:41 +01001778mp_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 +02001779 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001780 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001781 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001782 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001783 byte *p = m_new(byte, len + 1);
1784 o->data = p;
1785 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001786 return o;
1787}
1788
Damien George5fa93b62014-01-22 14:35:10 +00001789mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001790 mp_obj_str_t *o = o_in;
1791 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001792 byte *p = (byte*)o->data;
1793 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001794 return o;
1795}
1796
Damien George5f27a7e2014-07-31 10:29:56 +01001797mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1798 mp_obj_str_t *o = o_in;
1799 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1800 o->len = len;
1801 o->hash = qstr_compute_hash(o->data, o->len);
1802 byte *p = (byte*)o->data;
1803 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1804 return o;
1805}
1806
Damien George4abff752014-08-30 14:59:21 +01001807mp_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 +02001808 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001809 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001810 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001811 if (data) {
1812 o->hash = qstr_compute_hash(data, len);
1813 byte *p = m_new(byte, len + 1);
1814 o->data = p;
1815 memcpy(p, data, len * sizeof(byte));
1816 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1817 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001818 return o;
1819}
1820
Damien Georged182b982014-08-30 14:19:41 +01001821mp_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 +01001822 if (make_qstr_if_not_already) {
1823 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001824 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001825 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001826 qstr q = qstr_find_strn(data, len);
1827 if (q != MP_QSTR_NULL) {
1828 // qstr with this data already exists
1829 return MP_OBJ_NEW_QSTR(q);
1830 } else {
1831 // no existing qstr, don't make one
1832 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1833 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001834 }
Damien George5fa93b62014-01-22 14:35:10 +00001835}
1836
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001837mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1838 GET_STR_DATA_LEN(str, data, len);
1839 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1840}
1841
Damien Georged182b982014-08-30 14:19:41 +01001842mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001843 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001844}
1845
Damien George5fa93b62014-01-22 14:35:10 +00001846bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1847 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1848 return s1 == s2;
1849 } else {
1850 GET_STR_HASH(s1, h1);
1851 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001852 // If any of hashes is 0, it means it's not valid
1853 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001854 return false;
1855 }
1856 GET_STR_DATA_LEN(s1, d1, l1);
1857 GET_STR_DATA_LEN(s2, d2, l2);
1858 if (l1 != l2) {
1859 return false;
1860 }
Damien George1e708fe2014-01-23 18:27:51 +00001861 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001862 }
Damien George5fa93b62014-01-22 14:35:10 +00001863}
1864
Damien Georgedeed0872014-04-06 11:11:15 +01001865STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001866 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 +00001867}
1868
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001869STATIC void arg_type_mixup() {
1870 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1871}
1872
Damien Georged182b982014-08-30 14:19:41 +01001873mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001874 // TODO: This has too big overhead for hash accessor
1875 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001876 GET_STR_HASH(self_in, h);
1877 return h;
1878 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001879 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001880 }
1881}
1882
Damien Georged182b982014-08-30 14:19:41 +01001883mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001884 // TODO This has a double check for the type, one in obj.c and one here
1885 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001886 GET_STR_LEN(self_in, l);
1887 return l;
1888 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001889 bad_implicit_conversion(self_in);
1890 }
1891}
1892
1893// use this if you will anyway convert the string to a qstr
1894// will be more efficient for the case where it's already a qstr
1895qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1896 if (MP_OBJ_IS_QSTR(self_in)) {
1897 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001898 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001899 mp_obj_str_t *self = self_in;
1900 return qstr_from_strn((char*)self->data, self->len);
1901 } else {
1902 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001903 }
1904}
1905
1906// only use this function if you need the str data to be zero terminated
1907// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1908const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02001909 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001910 GET_STR_DATA_LEN(self_in, s, l);
1911 (void)l; // len unused
1912 return (const char*)s;
1913 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001914 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001915 }
1916}
1917
Damien Georged182b982014-08-30 14:19:41 +01001918const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001919 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001920 GET_STR_DATA_LEN(self_in, s, l);
1921 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001922 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001923 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001924 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001925 }
Damiend99b0522013-12-21 18:17:45 +00001926}
xyb8cfc9f02014-01-05 18:47:51 +08001927
1928/******************************************************************************/
1929/* str iterator */
1930
1931typedef struct _mp_obj_str_it_t {
1932 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001933 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01001934 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08001935} mp_obj_str_it_t;
1936
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001937#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001938STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001939 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001940 GET_STR_DATA_LEN(self->str, str, len);
1941 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001942 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001943 self->cur += 1;
1944 return o_out;
1945 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001946 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001947 }
1948}
1949
Damien George3e1a5c12014-03-29 13:43:38 +00001950STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001951 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001952 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001953 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001954 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001955};
1956
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001957mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
1958 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
1959 o->base.type = &mp_type_str_it;
1960 o->str = str;
1961 o->cur = 0;
1962 return o;
1963}
1964#endif
1965
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001966STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001967 mp_obj_str_it_t *self = self_in;
1968 GET_STR_DATA_LEN(self->str, str, len);
1969 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01001970 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001971 self->cur += 1;
1972 return o_out;
1973 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001974 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001975 }
1976}
1977
Damien George3e1a5c12014-03-29 13:43:38 +00001978STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001979 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001980 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001981 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001982 .iternext = bytes_it_iternext,
1983};
1984
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001985mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1986 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001987 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001988 o->str = str;
1989 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001990 return o;
1991}