blob: 7cd44471ec45da3b03277aae6b5908af30a76923 [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);
Damien Georgeb4fe6e22014-12-10 18:05:42 +000049STATIC NORETURN void arg_type_mixup(void);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030050
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 George6f5eb842014-11-27 16:55:47 +0000139#if !MICROPY_PY_BUILTINS_STR_UNICODE || MICROPY_CPYTHON_COMPAT
Damien Georgeecc88e92014-08-30 00:35:11 +0100140STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300141#if MICROPY_CPYTHON_COMPAT
142 if (n_kw != 0) {
143 mp_arg_error_unimpl_kw();
144 }
145#endif
146
Damien George1e9a92f2014-11-06 17:36:16 +0000147 mp_arg_check_num(n_args, n_kw, 0, 3, false);
148
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200149 switch (n_args) {
150 case 0:
151 return MP_OBJ_NEW_QSTR(MP_QSTR_);
152
Damien George1e9a92f2014-11-06 17:36:16 +0000153 case 1: {
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200154 vstr_t *vstr = vstr_new();
155 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100156 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200157 vstr_free(vstr);
158 return s;
159 }
160
Damien George1e9a92f2014-11-06 17:36:16 +0000161 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200162 // 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}
Damien George6f5eb842014-11-27 16:55:47 +0000177#endif
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200178
Damien Georgeecc88e92014-08-30 00:35:11 +0100179STATIC 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 +0200180 if (n_args == 0) {
181 return mp_const_empty_bytes;
182 }
183
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300184#if MICROPY_CPYTHON_COMPAT
185 if (n_kw != 0) {
186 mp_arg_error_unimpl_kw();
187 }
188#endif
189
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200190 if (MP_OBJ_IS_STR(args[0])) {
191 if (n_args < 2 || n_args > 3) {
192 goto wrong_args;
193 }
194 GET_STR_DATA_LEN(args[0], str_data, str_len);
195 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100196 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200197 o->data = str_data;
198 o->hash = str_hash;
199 return o;
200 }
201
202 if (n_args > 1) {
203 goto wrong_args;
204 }
205
206 if (MP_OBJ_IS_SMALL_INT(args[0])) {
207 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
208 byte *data;
209
Damien George3e1a5c12014-03-29 13:43:38 +0000210 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200211 memset(data, 0, len);
212 return mp_obj_str_builder_end(o);
213 }
214
Damien George32ef3a32014-12-04 15:46:14 +0000215 // check if argument has the buffer protocol
216 mp_buffer_info_t bufinfo;
217 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
218 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
219 }
220
Damien George39dc1452014-10-03 19:52:22 +0100221 mp_int_t len;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200222 byte *data;
223 vstr_t *vstr = NULL;
Damien George3aa09f52014-10-23 12:06:53 +0100224 mp_obj_t o = MP_OBJ_NULL;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200225 // Try to create array of exact len if initializer len is known
226 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
227 if (len_in == MP_OBJ_NULL) {
228 len = -1;
229 vstr = vstr_new();
230 } else {
231 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000232 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200233 }
234
Damien Georged17926d2014-03-30 13:35:08 +0100235 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200236 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100237 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200238 if (len == -1) {
239 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
240 } else {
241 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
242 }
243 }
244
245 if (len == -1) {
246 vstr_shrink(vstr);
247 // TODO: Optimize, borrow buffer from vstr
248 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000249 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200250 memcpy(data, vstr_str(vstr), len);
251 vstr_free(vstr);
252 }
253
254 return mp_obj_str_builder_end(o);
255
256wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000257 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200258}
259
Damien George55baff42014-01-21 21:40:13 +0000260// like strstr but with specified length and allows \0 bytes
261// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100262STATIC 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 +0000263 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100264 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700265 if (direction > 0) {
266 str_index = 0;
267 str_index_end = hlen - nlen;
268 } else {
269 str_index = hlen - nlen;
270 str_index_end = 0;
271 }
272 for (;;) {
273 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
274 //found
275 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000276 }
xbe17a5a832014-03-23 23:31:58 -0700277 if (str_index == str_index_end) {
278 //not found
279 break;
Damien George55baff42014-01-21 21:40:13 +0000280 }
xbe17a5a832014-03-23 23:31:58 -0700281 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000282 }
283 }
284 return NULL;
285}
286
Damien Georgea75b02e2014-08-27 09:20:30 +0100287// Note: this function is used to check if an object is a str or bytes, which
288// works because both those types use it as their binary_op method. Revisit
289// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100290mp_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 +0000291 // check for modulo
292 if (op == MP_BINARY_OP_MODULO) {
293 mp_obj_t *args;
294 mp_uint_t n_args;
295 mp_obj_t dict = MP_OBJ_NULL;
296 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
297 // TODO: Support tuple subclasses?
298 mp_obj_tuple_get(rhs_in, &n_args, &args);
299 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
300 args = NULL;
301 n_args = 0;
302 dict = rhs_in;
303 } else {
304 args = &rhs_in;
305 n_args = 1;
306 }
307 return str_modulo_format(lhs_in, n_args, args, dict);
308 }
309
310 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300311 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000312 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
313
314 // check for multiply
315 if (op == MP_BINARY_OP_MULTIPLY) {
316 mp_int_t n;
317 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
318 return MP_OBJ_NULL; // op not supported
319 }
320 if (n <= 0) {
321 if (lhs_type == &mp_type_str) {
322 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
323 } else {
324 return mp_const_empty_bytes;
325 }
326 }
327 byte *data;
328 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
329 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
330 return mp_obj_str_builder_end(s);
331 }
332
333 // From now on all operations allow:
334 // - str with str
335 // - bytes with bytes
336 // - bytes with bytearray
337 // - bytes with array.array
338 // To do this efficiently we use the buffer protocol to extract the raw
339 // data for the rhs, but only if the lhs is a bytes object.
340 //
341 // NOTE: CPython does not allow comparison between bytes ard array.array
342 // (even if the array is of type 'b'), even though it allows addition of
343 // such types. We are not compatible with this (we do allow comparison
344 // of bytes with anything that has the buffer protocol). It would be
345 // easy to "fix" this with a bit of extra logic below, but it costs code
346 // size and execution time so we don't.
347
348 const byte *rhs_data;
349 mp_uint_t rhs_len;
350 if (lhs_type == mp_obj_get_type(rhs_in)) {
351 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
352 rhs_data = rhs_data_;
353 rhs_len = rhs_len_;
354 } else if (lhs_type == &mp_type_bytes) {
355 mp_buffer_info_t bufinfo;
356 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
357 goto incompatible;
358 }
359 rhs_data = bufinfo.buf;
360 rhs_len = bufinfo.len;
361 } else {
362 // incompatible types
363 incompatible:
364 if (op == MP_BINARY_OP_EQUAL) {
365 return mp_const_false; // can check for equality against every type
366 }
367 return MP_OBJ_NULL; // op not supported
368 }
369
Damiend99b0522013-12-21 18:17:45 +0000370 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100371 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000372 case MP_BINARY_OP_INPLACE_ADD: {
373 mp_uint_t alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000374 byte *data;
Damien Georgea65c03c2014-11-05 16:30:34 +0000375 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
376 memcpy(data, lhs_data, lhs_len);
377 memcpy(data + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000378 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200379 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200380
Damien Georgea65c03c2014-11-05 16:30:34 +0000381 case MP_BINARY_OP_IN:
382 /* NOTE `a in b` is `b.__contains__(a)` */
383 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300384
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300385 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
386 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 +0100387 case MP_BINARY_OP_LESS:
388 case MP_BINARY_OP_LESS_EQUAL:
389 case MP_BINARY_OP_MORE:
390 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000391 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000392 }
393
Damien George6ac5dce2014-05-21 19:42:43 +0100394 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000395}
396
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300397#if !MICROPY_PY_BUILTINS_STR_UNICODE
398// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100399const 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 +0300400 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100401 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300402 return self_data + index_val;
403}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300404#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300405
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300406// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
407STATIC 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 +0300408 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100409 GET_STR_DATA_LEN(self_in, self_data, self_len);
410 if (value == MP_OBJ_SENTINEL) {
411 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100412#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100413 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300414 mp_bound_slice_t slice;
415 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300416 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100417 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100418 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100419 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100420 }
421#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300422 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100423 // If we have unicode enabled the type will always be bytes, so take the short cut.
424 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300425 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100426 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300427 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100428 }
429 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100430 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100431 }
432}
433
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200434STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700435 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300436 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000437
Damien Georgefe8fb912014-01-02 16:36:09 +0000438 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000439 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000440
441 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100442 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000443 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000444 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000445 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000446 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100447 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
448 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300449 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100450 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
451 }
452 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000453 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000454
455 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100456 mp_uint_t required_len = 0;
457 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300458 if (mp_obj_get_type(seq_items[i]) != self_type) {
459 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
460 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000461 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000462 if (i > 0) {
463 required_len += sep_len;
464 }
Damien George5fa93b62014-01-22 14:35:10 +0000465 GET_STR_LEN(seq_items[i], l);
466 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000467 }
468
469 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000470 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300471 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damien George39dc1452014-10-03 19:52:22 +0100472 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000473 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000474 memcpy(data, sep_str, sep_len);
475 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000476 }
Damien George5fa93b62014-01-22 14:35:10 +0000477 GET_STR_DATA_LEN(seq_items[i], s, l);
478 memcpy(data, s, l);
479 data += l;
Damiend99b0522013-12-21 18:17:45 +0000480 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000481
482 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000483 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000484}
485
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200486#define is_ws(c) ((c) == ' ' || (c) == '\t')
487
Damien Georgeecc88e92014-08-30 00:35:11 +0100488STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300489 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100490 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200491 mp_obj_t sep = mp_const_none;
492 if (n_args > 1) {
493 sep = args[1];
494 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100495 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200496 }
497 }
Damien Georgedeed0872014-04-06 11:11:15 +0100498
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200499 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000500 GET_STR_DATA_LEN(args[0], s, len);
501 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200502
Damien Georgedeed0872014-04-06 11:11:15 +0100503 if (sep == mp_const_none) {
504 // sep not given, so separate on whitespace
505
506 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000507 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100508 while (s < top && splits != 0) {
509 const byte *start = s;
510 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100511 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100512 if (s >= top) {
513 break;
514 }
515 while (s < top && is_ws(*s)) s++;
516 if (splits > 0) {
517 splits--;
518 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200519 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200520
Damien Georgedeed0872014-04-06 11:11:15 +0100521 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100522 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100523 }
524
525 } else {
526 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300527 if (mp_obj_get_type(sep) != self_type) {
528 arg_type_mixup();
529 }
Damien Georgedeed0872014-04-06 11:11:15 +0100530
Damien Georged182b982014-08-30 14:19:41 +0100531 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100532 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
533
534 if (sep_len == 0) {
535 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
536 }
537
538 for (;;) {
539 const byte *start = s;
540 for (;;) {
541 if (splits == 0 || s + sep_len > top) {
542 s = top;
543 break;
544 } else if (memcmp(s, sep_str, sep_len) == 0) {
545 break;
546 }
547 s++;
548 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100549 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100550 if (s >= top) {
551 break;
552 }
553 s += sep_len;
554 if (splits > 0) {
555 splits--;
556 }
557 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200558 }
559
560 return res;
561}
562
Damien Georgeecc88e92014-08-30 00:35:11 +0100563STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300564 if (n_args < 3) {
565 // If we don't have split limit, it doesn't matter from which side
566 // we split.
567 return str_split(n_args, args);
568 }
569 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
570 mp_obj_t sep = args[1];
571 GET_STR_DATA_LEN(args[0], s, len);
572
Damien George40f3c022014-07-03 13:25:24 +0100573 mp_int_t splits = mp_obj_get_int(args[2]);
574 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300575 // Preallocate list to the max expected # of elements, as we
576 // will fill it from the end.
577 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100578 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300579
580 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000581 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300582 } else {
Damien Georged182b982014-08-30 14:19:41 +0100583 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300584 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
585
586 if (sep_len == 0) {
587 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
588 }
589
590 const byte *beg = s;
591 const byte *last = s + len;
592 for (;;) {
593 s = last - sep_len;
594 for (;;) {
595 if (splits == 0 || s < beg) {
596 break;
597 } else if (memcmp(s, sep_str, sep_len) == 0) {
598 break;
599 }
600 s--;
601 }
602 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100603 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300604 break;
605 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100606 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 +0300607 last = s;
608 if (splits > 0) {
609 splits--;
610 }
611 }
612 if (idx != 0) {
613 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100614 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100615 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300616 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
617 res->len = used;
618 }
619 }
620
621 return res;
622}
623
Damien Georgeecc88e92014-08-30 00:35:11 +0100624STATIC 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 +0300625 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000626 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000627 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
628
629 // check argument type
630 if (!MP_OBJ_IS_STR(args[1])) {
631 bad_implicit_conversion(args[1]);
632 }
John R. Lentone8204912014-01-12 21:53:52 +0000633
Damien George5fa93b62014-01-22 14:35:10 +0000634 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
635 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000636
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300637 const byte *start = haystack;
638 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000639 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300640 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000641 }
642 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300643 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000644 }
645
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300646 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000647 if (p == NULL) {
648 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700649 if (is_index) {
650 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
651 } else {
652 return MP_OBJ_NEW_SMALL_INT(-1);
653 }
Damien George23005372014-01-13 19:39:01 +0000654 } else {
655 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300656 #if MICROPY_PY_BUILTINS_STR_UNICODE
657 if (self_type == &mp_type_str) {
658 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
659 }
660 #endif
xbe17a5a832014-03-23 23:31:58 -0700661 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000662 }
John R. Lentone8204912014-01-12 21:53:52 +0000663}
664
Damien Georgeecc88e92014-08-30 00:35:11 +0100665STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700666 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700667}
668
Damien Georgeecc88e92014-08-30 00:35:11 +0100669STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700670 return str_finder(n_args, args, -1, false);
671}
672
Damien Georgeecc88e92014-08-30 00:35:11 +0100673STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700674 return str_finder(n_args, args, 1, true);
675}
676
Damien Georgeecc88e92014-08-30 00:35:11 +0100677STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700678 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700679}
680
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200681// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100682STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300683 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300684 GET_STR_DATA_LEN(args[0], str, str_len);
685 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300686 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300687 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300688 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300689 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300690 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200691 return mp_const_false;
692 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300693 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200694}
695
Damien Georgeecc88e92014-08-30 00:35:11 +0100696STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300697 GET_STR_DATA_LEN(args[0], str, str_len);
698 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
699 assert(n_args == 2);
700
701 if (suffix_len > str_len) {
702 return mp_const_false;
703 }
704 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
705}
706
Paul Sokolovsky88107842014-04-26 06:20:08 +0300707enum { LSTRIP, RSTRIP, STRIP };
708
Damien Georgeecc88e92014-08-30 00:35:11 +0100709STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800710 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700711 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300712 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000713
714 const byte *chars_to_del;
715 uint chars_to_del_len;
716 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800717
718 if (n_args == 1) {
719 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000720 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800721 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300722 if (mp_obj_get_type(args[1]) != self_type) {
723 arg_type_mixup();
724 }
Damien George5fa93b62014-01-22 14:35:10 +0000725 GET_STR_DATA_LEN(args[1], s, l);
726 chars_to_del = s;
727 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800728 }
729
Damien George5fa93b62014-01-22 14:35:10 +0000730 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800731
Damien George40f3c022014-07-03 13:25:24 +0100732 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800733 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100734 mp_uint_t last_good_char_pos = 0;
735 mp_uint_t i = 0;
736 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300737 if (type == RSTRIP) {
738 i = orig_str_len - 1;
739 delta = -1;
740 }
Damien George40f3c022014-07-03 13:25:24 +0100741 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700742 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800743 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300744 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800745 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300746 if (type == LSTRIP) {
747 last_good_char_pos = orig_str_len - 1;
748 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300749 } else if (type == RSTRIP) {
750 first_good_char_pos = 0;
751 last_good_char_pos = i;
752 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300753 }
xbe7b0f39f2014-01-08 14:23:45 -0800754 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300755 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800756 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300757 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800758 }
759
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300760 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000761 // string is all whitespace, return ''
762 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800763 }
764
765 assert(last_good_char_pos >= first_good_char_pos);
766 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100767 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300768 if (stripped_len == orig_str_len) {
769 // If nothing was stripped, don't bother to dup original string
770 // TODO: watch out for this case when we'll get to bytearray.strip()
771 assert(first_good_char_pos == 0);
772 return args[0];
773 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100774 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800775}
776
Damien Georgeecc88e92014-08-30 00:35:11 +0100777STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300778 return str_uni_strip(STRIP, n_args, args);
779}
780
Damien Georgeecc88e92014-08-30 00:35:11 +0100781STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300782 return str_uni_strip(LSTRIP, n_args, args);
783}
784
Damien Georgeecc88e92014-08-30 00:35:11 +0100785STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300786 return str_uni_strip(RSTRIP, n_args, args);
787}
788
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700789// Takes an int arg, but only parses unsigned numbers, and only changes
790// *num if at least one digit was parsed.
791static int str_to_int(const char *str, int *num) {
792 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000793 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700794 *num = 0;
795 do {
796 *num = *num * 10 + (*s - '0');
797 s++;
798 }
Damien George81836c22014-12-21 21:07:03 +0000799 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700800 }
801 return s - str;
802}
803
804static bool isalignment(char ch) {
805 return ch && strchr("<>=^", ch) != NULL;
806}
807
808static bool istype(char ch) {
809 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
810}
811
812static bool arg_looks_integer(mp_obj_t arg) {
813 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
814}
815
816static bool arg_looks_numeric(mp_obj_t arg) {
817 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100818#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700819 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
820#endif
821 ;
822}
823
Dave Hylandsc4029e52014-04-07 11:19:51 -0700824static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100825#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700826 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700827
828 // TODO: Needs a way to construct an mpz integer from a float
829
Damien George40f3c022014-07-03 13:25:24 +0100830 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700831 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700832 }
833#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700834 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700835}
836
Damien George1e9a92f2014-11-06 17:36:16 +0000837STATIC NORETURN void terse_str_format_value_error(void) {
838 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
839}
840
Damien Georgeecc88e92014-08-30 00:35:11 +0100841mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000842 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000843
Damien George5fa93b62014-01-22 14:35:10 +0000844 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700845 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000846 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700847 pfenv_t pfenv_vstr;
848 pfenv_vstr.data = vstr;
849 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
850
Damien George5fa93b62014-01-22 14:35:10 +0000851 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700852 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000853 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700854 if (str < top && *str == '}') {
855 vstr_add_char(vstr, '}');
856 continue;
857 }
Damien George1e9a92f2014-11-06 17:36:16 +0000858 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
859 terse_str_format_value_error();
860 } else {
861 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
862 "single '}' encountered in format string"));
863 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700864 }
865 if (*str != '{') {
866 vstr_add_char(vstr, *str);
867 continue;
868 }
869
870 str++;
871 if (str < top && *str == '{') {
872 vstr_add_char(vstr, '{');
873 continue;
874 }
875
876 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
877
878 vstr_t *field_name = NULL;
879 char conversion = '\0';
880 vstr_t *format_spec = NULL;
881
882 if (str < top && *str != '}' && *str != '!' && *str != ':') {
883 field_name = vstr_new();
884 while (str < top && *str != '}' && *str != '!' && *str != ':') {
885 vstr_add_char(field_name, *str++);
886 }
887 vstr_add_char(field_name, '\0');
888 }
889
890 // conversion ::= "r" | "s"
891
892 if (str < top && *str == '!') {
893 str++;
894 if (str < top && (*str == 'r' || *str == 's')) {
895 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200896 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000897 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
898 terse_str_format_value_error();
899 } else {
900 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
901 "end of format while looking for conversion specifier"));
902 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700903 }
904 }
905
906 if (str < top && *str == ':') {
907 str++;
908 // {:} is the same as {}, which is the same as {!s}
909 // This makes a difference when passing in a True or False
910 // '{}'.format(True) returns 'True'
911 // '{:d}'.format(True) returns '1'
912 // So we treat {:} as {} and this later gets treated to be {!s}
913 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100914 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700915 while (str < top && *str != '}') {
916 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000917 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700918 vstr_add_char(format_spec, '\0');
919 }
920 }
921 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000922 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
923 terse_str_format_value_error();
924 } else {
925 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
926 "unmatched '{' in format"));
927 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700928 }
929 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000930 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
931 terse_str_format_value_error();
932 } else {
933 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
934 "expected ':' after format specifier"));
935 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700936 }
937
938 mp_obj_t arg = mp_const_none;
939
940 if (field_name) {
941 if (arg_i > 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000942 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
943 terse_str_format_value_error();
944 } else {
945 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
946 "can't switch from automatic field numbering to manual field specification"));
947 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700948 }
Damien George3bb8bd82014-04-14 21:20:30 +0100949 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700950 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100951 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700952 }
953 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100954 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700955 }
956 arg = args[index + 1];
957 arg_i = -1;
958 vstr_free(field_name);
959 field_name = NULL;
960 } else {
961 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000962 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
963 terse_str_format_value_error();
964 } else {
965 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
966 "can't switch from manual field specification to automatic field numbering"));
967 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700968 }
969 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100970 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700971 }
972 arg = args[arg_i + 1];
973 arg_i++;
974 }
975 if (!format_spec && !conversion) {
976 conversion = 's';
977 }
978 if (conversion) {
979 mp_print_kind_t print_kind;
980 if (conversion == 's') {
981 print_kind = PRINT_STR;
982 } else if (conversion == 'r') {
983 print_kind = PRINT_REPR;
984 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000985 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
986 terse_str_format_value_error();
987 } else {
988 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
989 "unknown conversion specifier %c", conversion));
990 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700991 }
992 vstr_t *arg_vstr = vstr_new();
993 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100994 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700995 vstr_free(arg_vstr);
996 }
997
998 char sign = '\0';
999 char fill = '\0';
1000 char align = '\0';
1001 int width = -1;
1002 int precision = -1;
1003 char type = '\0';
1004 int flags = 0;
1005
1006 if (format_spec) {
1007 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1008 //
1009 // [[fill]align][sign][#][0][width][,][.precision][type]
1010 // fill ::= <any character>
1011 // align ::= "<" | ">" | "=" | "^"
1012 // sign ::= "+" | "-" | " "
1013 // width ::= integer
1014 // precision ::= integer
1015 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1016
1017 const char *s = vstr_str(format_spec);
1018 if (isalignment(*s)) {
1019 align = *s++;
1020 } else if (*s && isalignment(s[1])) {
1021 fill = *s++;
1022 align = *s++;
1023 }
1024 if (*s == '+' || *s == '-' || *s == ' ') {
1025 if (*s == '+') {
1026 flags |= PF_FLAG_SHOW_SIGN;
1027 } else if (*s == ' ') {
1028 flags |= PF_FLAG_SPACE_SIGN;
1029 }
1030 sign = *s++;
1031 }
1032 if (*s == '#') {
1033 flags |= PF_FLAG_SHOW_PREFIX;
1034 s++;
1035 }
1036 if (*s == '0') {
1037 if (!align) {
1038 align = '=';
1039 }
1040 if (!fill) {
1041 fill = '0';
1042 }
1043 }
1044 s += str_to_int(s, &width);
1045 if (*s == ',') {
1046 flags |= PF_FLAG_SHOW_COMMA;
1047 s++;
1048 }
1049 if (*s == '.') {
1050 s++;
1051 s += str_to_int(s, &precision);
1052 }
1053 if (istype(*s)) {
1054 type = *s++;
1055 }
1056 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001057 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001058 }
1059 vstr_free(format_spec);
1060 format_spec = NULL;
1061 }
1062 if (!align) {
1063 if (arg_looks_numeric(arg)) {
1064 align = '>';
1065 } else {
1066 align = '<';
1067 }
1068 }
1069 if (!fill) {
1070 fill = ' ';
1071 }
1072
1073 if (sign) {
1074 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001075 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1076 terse_str_format_value_error();
1077 } else {
1078 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1079 "sign not allowed in string format specifier"));
1080 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001081 }
1082 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001083 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1084 terse_str_format_value_error();
1085 } else {
1086 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1087 "sign not allowed with integer format specifier 'c'"));
1088 }
Damiend99b0522013-12-21 18:17:45 +00001089 }
1090 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 sign = '-';
1092 }
1093
1094 switch (align) {
1095 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1096 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1097 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1098 }
1099
1100 if (arg_looks_integer(arg)) {
1101 switch (type) {
1102 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001103 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001104 continue;
1105
1106 case 'c':
1107 {
1108 char ch = mp_obj_get_int(arg);
1109 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1110 continue;
1111 }
1112
1113 case '\0': // No explicit format type implies 'd'
1114 case 'n': // I don't think we support locales in uPy so use 'd'
1115 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001116 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001117 continue;
1118
1119 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001120 if (flags & PF_FLAG_SHOW_PREFIX) {
1121 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1122 }
1123
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001124 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001125 continue;
1126
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001127 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001128 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001129 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001130 continue;
1131
1132 case 'e':
1133 case 'E':
1134 case 'f':
1135 case 'F':
1136 case 'g':
1137 case 'G':
1138 case '%':
1139 // The floating point formatters all work with anything that
1140 // looks like an integer
1141 break;
1142
1143 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001144 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1145 terse_str_format_value_error();
1146 } else {
1147 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1148 "unknown format code '%c' for object of type '%s'",
1149 type, mp_obj_get_type_str(arg)));
1150 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001151 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001152 }
Damien George70f33cd2014-04-02 17:06:05 +01001153
Dave Hylands22fe4d72014-04-02 12:07:31 -07001154 // NOTE: no else here. We need the e, f, g etc formats for integer
1155 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001156 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001157 if (!type) {
1158
1159 // Even though the docs say that an unspecified type is the same
1160 // as 'g', there is one subtle difference, when the exponent
1161 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001162 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001163 // '{:10.1}'.format(0.0) ==> '0e+00'
1164 // '{:10.1g}'.format(0.0) ==> '0'
1165 //
1166 // TODO: Figure out how to deal with this.
1167 //
1168 // A proper solution would involve adding a special flag
1169 // or something to format_float, and create a format_double
1170 // to deal with doubles. In order to fix this when using
1171 // sprintf, we'd need to use the e format and tweak the
1172 // returned result to strip trailing zeros like the g format
1173 // does.
1174 //
1175 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1176 // but with 1.e2 you get 1e+02 and 1.00e+02
1177 //
1178 // Stripping the trailing 0's (like g) does would make the
1179 // e format give us the right format.
1180 //
1181 // CPython sources say:
1182 // Omitted type specifier. Behaves in the same way as repr(x)
1183 // and str(x) if no precision is given, else like 'g', but with
1184 // at least one digit after the decimal point. */
1185
1186 type = 'g';
1187 }
1188 if (type == 'n') {
1189 type = 'g';
1190 }
1191
1192 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1193 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001194#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001195 case 'e':
1196 case 'E':
1197 case 'f':
1198 case 'F':
1199 case 'g':
1200 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001201 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001202 break;
1203
1204 case '%':
1205 flags |= PF_FLAG_ADD_PERCENT;
1206 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1207 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001208#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001209
1210 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001211 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1212 terse_str_format_value_error();
1213 } else {
1214 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1215 "unknown format code '%c' for object of type 'float'",
1216 type, mp_obj_get_type_str(arg)));
1217 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001218 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001219 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001220 // arg doesn't look like a number
1221
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001222 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001223 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1224 terse_str_format_value_error();
1225 } else {
1226 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1227 "'=' alignment not allowed in string format specifier"));
1228 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001229 }
Damien George70f33cd2014-04-02 17:06:05 +01001230
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001231 switch (type) {
1232 case '\0':
1233 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1234 break;
1235
Damien Georged182b982014-08-30 14:19:41 +01001236 case 's': {
1237 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001238 const char *s = mp_obj_str_get_data(arg, &len);
1239 if (precision < 0) {
1240 precision = len;
1241 }
1242 if (len > precision) {
1243 len = precision;
1244 }
1245 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1246 break;
1247 }
1248
1249 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001250 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1251 terse_str_format_value_error();
1252 } else {
1253 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1254 "unknown format code '%c' for object of type 'str'",
1255 type, mp_obj_get_type_str(arg)));
1256 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001257 }
Damiend99b0522013-12-21 18:17:45 +00001258 }
1259 }
1260
Damien George2617eeb2014-05-25 22:27:57 +01001261 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001262 vstr_free(vstr);
1263 return s;
Damiend99b0522013-12-21 18:17:45 +00001264}
1265
Damien Georgeecc88e92014-08-30 00:35:11 +01001266STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001267 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001268
1269 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001270 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001271 int arg_i = 0;
1272 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001273 pfenv_t pfenv_vstr;
1274 pfenv_vstr.data = vstr;
1275 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1276
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001277 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001278 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001279 if (*str != '%') {
1280 vstr_add_char(vstr, *str);
1281 continue;
1282 }
1283 if (++str >= top) {
1284 break;
1285 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001286 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001287 vstr_add_char(vstr, '%');
1288 continue;
1289 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001290
1291 // Dictionary value lookup
1292 if (*str == '(') {
1293 const byte *key = ++str;
1294 while (*str != ')') {
1295 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001296 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1297 terse_str_format_value_error();
1298 } else {
1299 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1300 "incomplete format key"));
1301 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001302 }
1303 ++str;
1304 }
1305 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1306 arg = mp_obj_dict_get(dict, k_obj);
1307 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001308 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001309
Dave Hylands6756a372014-04-02 11:42:39 -07001310 int flags = 0;
1311 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001312 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001313 while (str < top) {
1314 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1315 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1316 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001317 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001318 else if (*str == '0') {
1319 flags |= PF_FLAG_PAD_AFTER_SIGN;
1320 fill = '0';
1321 } else break;
1322 str++;
1323 }
1324 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001325 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001326 if (str < top) {
1327 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001328 if (arg_i >= n_args) {
1329 goto not_enough_args;
1330 }
Dave Hylands6756a372014-04-02 11:42:39 -07001331 width = mp_obj_get_int(args[arg_i++]);
1332 str++;
1333 } else {
Damien George81836c22014-12-21 21:07:03 +00001334 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001335 }
1336 }
1337 int prec = -1;
1338 if (str < top && *str == '.') {
1339 if (++str < top) {
1340 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001341 if (arg_i >= n_args) {
1342 goto not_enough_args;
1343 }
Dave Hylands6756a372014-04-02 11:42:39 -07001344 prec = mp_obj_get_int(args[arg_i++]);
1345 str++;
1346 } else {
1347 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001348 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001349 }
1350 }
1351 }
1352
1353 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001354 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1355 terse_str_format_value_error();
1356 } else {
1357 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1358 "incomplete format"));
1359 }
Dave Hylands6756a372014-04-02 11:42:39 -07001360 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001361
1362 // Tuple value lookup
1363 if (arg == MP_OBJ_NULL) {
1364 if (arg_i >= n_args) {
1365not_enough_args:
1366 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1367 }
1368 arg = args[arg_i++];
1369 }
Dave Hylands6756a372014-04-02 11:42:39 -07001370 switch (*str) {
1371 case 'c':
1372 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001373 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001374 const char *s = mp_obj_str_get_data(arg, &len);
1375 if (len != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001376 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1377 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001378 }
1379 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001380 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001381 char ch = mp_obj_get_int(arg);
1382 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001383 } else {
1384 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1385 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001386 }
Damien George11de8392014-06-05 18:57:38 +01001387 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001388
1389 case 'd':
1390 case 'i':
1391 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001392 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001393 break;
1394
Damien Georgefb510b32014-06-01 13:32:54 +01001395#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001396 case 'e':
1397 case 'E':
1398 case 'f':
1399 case 'F':
1400 case 'g':
1401 case 'G':
1402 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1403 break;
1404#endif
1405
1406 case 'o':
1407 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001408 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001409 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001410 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001411 break;
1412
1413 case 'r':
1414 case 's':
1415 {
1416 vstr_t *arg_vstr = vstr_new();
1417 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1418 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1419 uint len = vstr_len(arg_vstr);
1420 if (prec < 0) {
1421 prec = len;
1422 }
1423 if (len > prec) {
1424 len = prec;
1425 }
1426 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1427 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001428 break;
1429 }
Dave Hylands6756a372014-04-02 11:42:39 -07001430
Dave Hylands6756a372014-04-02 11:42:39 -07001431 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001432 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001433 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001434 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001435
Dave Hylands6756a372014-04-02 11:42:39 -07001436 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001437 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1438 terse_str_format_value_error();
1439 } else {
1440 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1441 "unsupported format character '%c' (0x%x) at index %d",
1442 *str, *str, str - start_str));
1443 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001444 }
1445 }
1446
1447 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001448 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001449 }
1450
Damien George2617eeb2014-05-25 22:27:57 +01001451 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001452 vstr_free(vstr);
1453 return s;
1454}
1455
Damien Georgeecc88e92014-08-30 00:35:11 +01001456STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001457 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001458
Damien George40f3c022014-07-03 13:25:24 +01001459 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001460 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001461 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001462 if (max_rep == 0) {
1463 return args[0];
1464 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001465 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001466 }
xbe480c15a2014-01-30 22:17:30 -08001467 }
Damien George94f68302014-01-31 23:45:12 +00001468
xbe729be9b2014-04-07 14:46:39 -07001469 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001470
Damien Georgeff715422014-04-07 00:39:13 +01001471 // check argument types
1472
1473 if (!MP_OBJ_IS_STR(args[1])) {
1474 bad_implicit_conversion(args[1]);
1475 }
1476
1477 if (!MP_OBJ_IS_STR(args[2])) {
1478 bad_implicit_conversion(args[2]);
1479 }
1480
1481 // extract string data
1482
xbe480c15a2014-01-30 22:17:30 -08001483 GET_STR_DATA_LEN(args[0], str, str_len);
1484 GET_STR_DATA_LEN(args[1], old, old_len);
1485 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001486
1487 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001488 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001489 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001490 }
1491
Damien George94f68302014-01-31 23:45:12 +00001492 // data for the replaced string
1493 byte *data = NULL;
1494 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001495
Damien George94f68302014-01-31 23:45:12 +00001496 // do 2 passes over the string:
1497 // first pass computes the required length of the replaced string
1498 // second pass does the replacements
1499 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001500 mp_uint_t replaced_str_index = 0;
1501 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001502 const byte *old_occurrence;
1503 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001504 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001505 if (old_len == 0) {
1506 // if old_str is empty, copy new_str to start of replaced string
1507 // copy the replacement string
1508 if (data != NULL) {
1509 memcpy(data, new, new_len);
1510 }
1511 replaced_str_index += new_len;
1512 num_replacements_done++;
1513 }
1514 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1515 if (old_len == 0) {
1516 old_occurrence += 1;
1517 }
Damien George94f68302014-01-31 23:45:12 +00001518 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1519 if (data != NULL) {
1520 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1521 }
1522 replaced_str_index += old_occurrence - offset_ptr;
1523 // copy the replacement string
1524 if (data != NULL) {
1525 memcpy(data + replaced_str_index, new, new_len);
1526 }
1527 replaced_str_index += new_len;
1528 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001529 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001530 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001531 }
1532
1533 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1534 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001535 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001536 }
Damien Georgeff715422014-04-07 00:39:13 +01001537 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001538
1539 if (data == NULL) {
1540 // first pass
1541 if (num_replacements_done == 0) {
1542 // no substr found, return original string
1543 return args[0];
1544 } else {
1545 // substr found, allocate new string
1546 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001547 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001548 }
1549 } else {
1550 // second pass, we are done
1551 break;
1552 }
xbe480c15a2014-01-30 22:17:30 -08001553 }
Damien George94f68302014-01-31 23:45:12 +00001554
xbe480c15a2014-01-30 22:17:30 -08001555 return mp_obj_str_builder_end(replaced_str);
1556}
1557
Damien Georgeecc88e92014-08-30 00:35:11 +01001558STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001559 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001560 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001561 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1562
1563 // check argument type
1564 if (!MP_OBJ_IS_STR(args[1])) {
1565 bad_implicit_conversion(args[1]);
1566 }
xbe9e1e8cd2014-03-12 22:57:16 -07001567
1568 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1569 GET_STR_DATA_LEN(args[1], needle, needle_len);
1570
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001571 const byte *start = haystack;
1572 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001573 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001574 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001575 }
1576 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001577 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001578 }
1579
Damien George536dde22014-03-13 22:07:55 +00001580 // if needle_len is zero then we count each gap between characters as an occurrence
1581 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001582 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001583 }
1584
Damien George536dde22014-03-13 22:07:55 +00001585 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001586 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001587 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1588 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001589 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001590 haystack_ptr += needle_len;
1591 } else {
1592 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001593 }
xbe9e1e8cd2014-03-12 22:57:16 -07001594 }
1595
1596 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1597}
1598
Damien George40f3c022014-07-03 13:25:24 +01001599STATIC 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 -07001600 if (!MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001601 assert(0);
1602 }
1603 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1604 if (self_type != mp_obj_get_type(arg)) {
1605 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001606 }
Damien Georgeb035db32014-03-21 20:39:40 +00001607
xbe613a8e32014-03-18 00:06:29 -07001608 GET_STR_DATA_LEN(self_in, str, str_len);
1609 GET_STR_DATA_LEN(arg, sep, sep_len);
1610
1611 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001612 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001613 }
Damien Georgeb035db32014-03-21 20:39:40 +00001614
1615 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1616
1617 if (direction > 0) {
1618 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001619 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001620 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001621 }
xbe613a8e32014-03-18 00:06:29 -07001622
xbe17a5a832014-03-23 23:31:58 -07001623 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1624 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001625 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001626 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001627 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001628 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 -07001629 }
Damien Georgeb035db32014-03-21 20:39:40 +00001630
xbe0a6894c2014-03-21 01:12:26 -07001631 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001632}
1633
Damien Georgeb035db32014-03-21 20:39:40 +00001634STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1635 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001636}
xbe4504ea82014-03-19 00:46:14 -07001637
Damien Georgeb035db32014-03-21 20:39:40 +00001638STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1639 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001640}
1641
Paul Sokolovsky69135212014-05-10 19:47:41 +03001642// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001643STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001644 GET_STR_DATA_LEN(self_in, self_data, self_len);
1645 byte *data;
1646 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 +01001647 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001648 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001649 }
1650 *data = 0;
1651 return mp_obj_str_builder_end(s);
1652}
1653
1654STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001655 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001656}
1657
1658STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001659 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001660}
1661
Damien Georgefcc9cf62014-06-01 18:22:09 +01001662STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001663 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001664
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001665 if (self_len == 0) {
1666 return mp_const_false; // default to False for empty str
1667 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001668
Damien Georgefcc9cf62014-06-01 18:22:09 +01001669 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001670 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001671 if (!f(*self_data++)) {
1672 return mp_const_false;
1673 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001674 }
1675 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001676 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001677
Damien George39dc1452014-10-03 19:52:22 +01001678 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001679 if (unichar_isalpha(*self_data++)) {
1680 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001681 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1682 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001683 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001684 }
1685 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001686
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001687 if (!contains_alpha) {
1688 return mp_const_false;
1689 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001690 }
1691
1692 return mp_const_true;
1693}
1694
1695STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001696 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001697}
1698
1699STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001700 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001701}
1702
1703STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001704 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001705}
1706
1707STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001708 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001709}
1710
1711STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001712 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001713}
1714
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001715#if MICROPY_CPYTHON_COMPAT
1716// These methods are superfluous in the presense of str() and bytes()
1717// constructors.
1718// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001719STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001720 mp_obj_t new_args[2];
1721 if (n_args == 1) {
1722 new_args[0] = args[0];
1723 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1724 args = new_args;
1725 n_args++;
1726 }
1727 return str_make_new(NULL, n_args, 0, args);
1728}
1729
1730// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001731STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001732 mp_obj_t new_args[2];
1733 if (n_args == 1) {
1734 new_args[0] = args[0];
1735 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1736 args = new_args;
1737 n_args++;
1738 }
1739 return bytes_make_new(NULL, n_args, 0, args);
1740}
1741#endif
1742
Damien George4d917232014-08-30 14:28:06 +01001743mp_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 +01001744 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001745 GET_STR_DATA_LEN(self_in, str_data, str_len);
1746 bufinfo->buf = (void*)str_data;
1747 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001748 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001749 return 0;
1750 } else {
1751 // can't write to a string
1752 bufinfo->buf = NULL;
1753 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001754 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001755 return 1;
1756 }
1757}
1758
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001759#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001760MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1761MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001762#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001763MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1764MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1765MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1766MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1767MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1768MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1769MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1770MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1771MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1772MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1773MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1774MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1775MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1776MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1777MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1778MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1779MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1780MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1781MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1782MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1783MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1784MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1785MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1786MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001787
Damien George9b196cd2014-03-26 21:47:19 +00001788STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001789#if MICROPY_CPYTHON_COMPAT
1790 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001791 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1792 // If we have separate unicode type, then here we have methods only
1793 // for bytes type, and it should not have encode() methods. Otherwise,
1794 // we have non-compliant-but-practical bytestring type, which shares
1795 // method table with bytes, so they both have encode() and decode()
1796 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001797 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001798 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001799#endif
Damien George9b196cd2014-03-26 21:47:19 +00001800 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1801 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001802 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1803 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001804 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1805 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001806 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001807 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001808 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001809 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001810 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1811 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001812 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1813 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1814 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1815 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1816 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001817 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1818 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001819 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1820 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1821 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1822 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1823 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001824};
Damien George97209d32014-01-07 15:58:30 +00001825
Damien George9b196cd2014-03-26 21:47:19 +00001826STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1827
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001828#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001829const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001830 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001831 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001832 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001833 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001834 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001835 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001836 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001837 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001838 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001839};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001840#endif
Damiend99b0522013-12-21 18:17:45 +00001841
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001842// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001843const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001844 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001845 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001846 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001847 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001848 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001849 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001850 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001851 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001852 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001853};
1854
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001855// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001856const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001857
Damien Georged182b982014-08-30 14:19:41 +01001858mp_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 +02001859 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001860 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001861 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001862 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001863 byte *p = m_new(byte, len + 1);
1864 o->data = p;
1865 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001866 return o;
1867}
1868
Damien George5fa93b62014-01-22 14:35:10 +00001869mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001870 mp_obj_str_t *o = o_in;
1871 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001872 byte *p = (byte*)o->data;
1873 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001874 return o;
1875}
1876
Damien George5f27a7e2014-07-31 10:29:56 +01001877mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1878 mp_obj_str_t *o = o_in;
1879 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1880 o->len = len;
1881 o->hash = qstr_compute_hash(o->data, o->len);
1882 byte *p = (byte*)o->data;
1883 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1884 return o;
1885}
1886
Damien George4abff752014-08-30 14:59:21 +01001887mp_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 +02001888 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001889 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001890 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001891 if (data) {
1892 o->hash = qstr_compute_hash(data, len);
1893 byte *p = m_new(byte, len + 1);
1894 o->data = p;
1895 memcpy(p, data, len * sizeof(byte));
1896 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1897 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001898 return o;
1899}
1900
Damien Georged182b982014-08-30 14:19:41 +01001901mp_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 +01001902 if (make_qstr_if_not_already) {
1903 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001904 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001905 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001906 qstr q = qstr_find_strn(data, len);
1907 if (q != MP_QSTR_NULL) {
1908 // qstr with this data already exists
1909 return MP_OBJ_NEW_QSTR(q);
1910 } else {
1911 // no existing qstr, don't make one
1912 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1913 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001914 }
Damien George5fa93b62014-01-22 14:35:10 +00001915}
1916
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001917mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1918 GET_STR_DATA_LEN(str, data, len);
1919 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1920}
1921
Damien Georged182b982014-08-30 14:19:41 +01001922mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001923 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001924}
1925
Damien George5fa93b62014-01-22 14:35:10 +00001926bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1927 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1928 return s1 == s2;
1929 } else {
1930 GET_STR_HASH(s1, h1);
1931 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001932 // If any of hashes is 0, it means it's not valid
1933 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001934 return false;
1935 }
1936 GET_STR_DATA_LEN(s1, d1, l1);
1937 GET_STR_DATA_LEN(s2, d2, l2);
1938 if (l1 != l2) {
1939 return false;
1940 }
Damien George1e708fe2014-01-23 18:27:51 +00001941 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001942 }
Damien George5fa93b62014-01-22 14:35:10 +00001943}
1944
Damien Georgedeed0872014-04-06 11:11:15 +01001945STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001946 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1947 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1948 "can't convert to str implicitly"));
1949 } else {
1950 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1951 "can't convert '%s' object to str implicitly",
1952 mp_obj_get_type_str(self_in)));
1953 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001954}
1955
Damien Georgeb4fe6e22014-12-10 18:05:42 +00001956STATIC void arg_type_mixup(void) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001957 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1958}
1959
Damien Georged182b982014-08-30 14:19:41 +01001960mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001961 // TODO: This has too big overhead for hash accessor
Damien Georgebe8e99c2014-11-05 16:45:54 +00001962 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001963 GET_STR_HASH(self_in, h);
1964 return h;
1965 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001966 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001967 }
1968}
1969
Damien Georged182b982014-08-30 14:19:41 +01001970mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001971 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001972 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001973 GET_STR_LEN(self_in, l);
1974 return l;
1975 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001976 bad_implicit_conversion(self_in);
1977 }
1978}
1979
1980// use this if you will anyway convert the string to a qstr
1981// will be more efficient for the case where it's already a qstr
1982qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1983 if (MP_OBJ_IS_QSTR(self_in)) {
1984 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001985 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001986 mp_obj_str_t *self = self_in;
1987 return qstr_from_strn((char*)self->data, self->len);
1988 } else {
1989 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001990 }
1991}
1992
1993// only use this function if you need the str data to be zero terminated
1994// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1995const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02001996 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001997 GET_STR_DATA_LEN(self_in, s, l);
1998 (void)l; // len unused
1999 return (const char*)s;
2000 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002001 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002002 }
2003}
2004
Damien Georged182b982014-08-30 14:19:41 +01002005const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002006 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002007 GET_STR_DATA_LEN(self_in, s, l);
2008 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002009 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002010 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002011 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002012 }
Damiend99b0522013-12-21 18:17:45 +00002013}
xyb8cfc9f02014-01-05 18:47:51 +08002014
2015/******************************************************************************/
2016/* str iterator */
2017
2018typedef struct _mp_obj_str_it_t {
2019 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002020 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002021 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08002022} mp_obj_str_it_t;
2023
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002024#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002025STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08002026 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002027 GET_STR_DATA_LEN(self->str, str, len);
2028 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002029 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002030 self->cur += 1;
2031 return o_out;
2032 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002033 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002034 }
2035}
2036
Damien George3e1a5c12014-03-29 13:43:38 +00002037STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002038 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002039 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002040 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002041 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002042};
2043
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002044mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2045 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
2046 o->base.type = &mp_type_str_it;
2047 o->str = str;
2048 o->cur = 0;
2049 return o;
2050}
2051#endif
2052
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002053STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002054 mp_obj_str_it_t *self = self_in;
2055 GET_STR_DATA_LEN(self->str, str, len);
2056 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002057 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002058 self->cur += 1;
2059 return o_out;
2060 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002061 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002062 }
2063}
2064
Damien George3e1a5c12014-03-29 13:43:38 +00002065STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002066 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002067 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002068 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002069 .iternext = bytes_it_iternext,
2070};
2071
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002072mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
2073 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002074 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002075 o->str = str;
2076 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002077 return o;
2078}