blob: 3d9fd6f5e83c66a19d97648002e3a80d75a92c68 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
xbeefe34222014-03-16 00:14:26 -070028#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +000029#include <string.h>
30#include <assert.h>
31
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030032#include "mpconfig.h"
Damiend99b0522013-12-21 18:17:45 +000033#include "nlr.h"
34#include "misc.h"
Paul Sokolovsky5048df02014-06-14 03:15:00 +030035#include "unicode.h"
Damien George55baff42014-01-21 21:40:13 +000036#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000037#include "obj.h"
38#include "runtime0.h"
39#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070040#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030041#include "objstr.h"
Paul Sokolovsky2a273652014-05-13 08:07:08 +030042#include "objlist.h"
Damiend99b0522013-12-21 18:17:45 +000043
Damien Georgeecc88e92014-08-30 00:35:11 +010044STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020045
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030046mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020047STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030048STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030049
xyb8cfc9f02014-01-05 18:47:51 +080050/******************************************************************************/
51/* str */
52
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030053void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
Damien Georged182b982014-08-30 14:19:41 +010054 const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020055 // this escapes characters, but it will be very slow to print (calling print many times)
56 bool has_single_quote = false;
57 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100058 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020059 if (*s == '\'') {
60 has_single_quote = true;
61 } else if (*s == '"') {
62 has_double_quote = true;
63 }
64 }
65 int quote_char = '\'';
66 if (has_single_quote && !has_double_quote) {
67 quote_char = '"';
68 }
69 print(env, "%c", quote_char);
70 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
71 if (*s == quote_char) {
72 print(env, "\\%c", quote_char);
73 } else if (*s == '\\') {
74 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030075 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
76 // In strings, anything which is not ascii control character
77 // is printed as is, this includes characters in range 0x80-0xff
78 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020079 print(env, "%c", *s);
80 } else if (*s == '\n') {
81 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010082 } else if (*s == '\r') {
83 print(env, "\\r");
84 } else if (*s == '\t') {
85 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020086 } else {
87 print(env, "\\x%02x", *s);
88 }
89 }
90 print(env, "%c", quote_char);
91}
92
Damien George612045f2014-09-17 22:56:34 +010093#if MICROPY_PY_UJSON
Damien Georgecde0ca22014-09-25 17:35:56 +010094void mp_str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) {
95 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
96 // 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 +010097 print(env, "\"");
98 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010099 if (*s == '"' || *s == '\\') {
Damien George612045f2014-09-17 22:56:34 +0100100 print(env, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +0100101 } else if (*s >= 32) {
102 // this will handle normal and utf-8 encoded chars
Damien George612045f2014-09-17 22:56:34 +0100103 print(env, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +0100104 } else if (*s == '\n') {
105 print(env, "\\n");
106 } else if (*s == '\r') {
107 print(env, "\\r");
108 } else if (*s == '\t') {
109 print(env, "\\t");
110 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100111 // this will handle control chars
Damien George612045f2014-09-17 22:56:34 +0100112 print(env, "\\u%04x", *s);
113 }
114 }
115 print(env, "\"");
116}
117#endif
118
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200119STATIC 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 +0000120 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100121 #if MICROPY_PY_UJSON
122 if (kind == PRINT_JSON) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100123 mp_str_print_json(print, env, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100124 return;
125 }
126 #endif
Damien Georgecde0ca22014-09-25 17:35:56 +0100127 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200128 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000129 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200130 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200131 if (is_bytes) {
132 print(env, "b");
133 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300134 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200135 }
Damiend99b0522013-12-21 18:17:45 +0000136}
137
Damien George6f5eb842014-11-27 16:55:47 +0000138#if !MICROPY_PY_BUILTINS_STR_UNICODE || MICROPY_CPYTHON_COMPAT
Damien Georgeecc88e92014-08-30 00:35:11 +0100139STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300140#if MICROPY_CPYTHON_COMPAT
141 if (n_kw != 0) {
142 mp_arg_error_unimpl_kw();
143 }
144#endif
145
Damien George1e9a92f2014-11-06 17:36:16 +0000146 mp_arg_check_num(n_args, n_kw, 0, 3, false);
147
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200148 switch (n_args) {
149 case 0:
150 return MP_OBJ_NEW_QSTR(MP_QSTR_);
151
Damien George1e9a92f2014-11-06 17:36:16 +0000152 case 1: {
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200153 vstr_t *vstr = vstr_new();
154 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100155 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200156 vstr_free(vstr);
157 return s;
158 }
159
Damien George1e9a92f2014-11-06 17:36:16 +0000160 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200161 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200162 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
163 GET_STR_DATA_LEN(args[0], str_data, str_len);
164 GET_STR_HASH(args[0], str_hash);
165 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
166 o->data = str_data;
167 o->hash = str_hash;
168 return o;
169 } else {
170 mp_buffer_info_t bufinfo;
171 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
172 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200173 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200174 }
175}
Damien George6f5eb842014-11-27 16:55:47 +0000176#endif
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200177
Damien Georgeecc88e92014-08-30 00:35:11 +0100178STATIC 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 +0200179 if (n_args == 0) {
180 return mp_const_empty_bytes;
181 }
182
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300183#if MICROPY_CPYTHON_COMPAT
184 if (n_kw != 0) {
185 mp_arg_error_unimpl_kw();
186 }
187#endif
188
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200189 if (MP_OBJ_IS_STR(args[0])) {
190 if (n_args < 2 || n_args > 3) {
191 goto wrong_args;
192 }
193 GET_STR_DATA_LEN(args[0], str_data, str_len);
194 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100195 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200196 o->data = str_data;
197 o->hash = str_hash;
198 return o;
199 }
200
201 if (n_args > 1) {
202 goto wrong_args;
203 }
204
205 if (MP_OBJ_IS_SMALL_INT(args[0])) {
206 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
207 byte *data;
208
Damien George3e1a5c12014-03-29 13:43:38 +0000209 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200210 memset(data, 0, len);
211 return mp_obj_str_builder_end(o);
212 }
213
Damien George32ef3a32014-12-04 15:46:14 +0000214 // check if argument has the buffer protocol
215 mp_buffer_info_t bufinfo;
216 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
217 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
218 }
219
Damien George39dc1452014-10-03 19:52:22 +0100220 mp_int_t len;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200221 byte *data;
222 vstr_t *vstr = NULL;
Damien George3aa09f52014-10-23 12:06:53 +0100223 mp_obj_t o = MP_OBJ_NULL;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200224 // Try to create array of exact len if initializer len is known
225 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
226 if (len_in == MP_OBJ_NULL) {
227 len = -1;
228 vstr = vstr_new();
229 } else {
230 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000231 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200232 }
233
Damien Georged17926d2014-03-30 13:35:08 +0100234 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200235 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100236 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200237 if (len == -1) {
238 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
239 } else {
240 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
241 }
242 }
243
244 if (len == -1) {
245 vstr_shrink(vstr);
246 // TODO: Optimize, borrow buffer from vstr
247 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000248 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200249 memcpy(data, vstr_str(vstr), len);
250 vstr_free(vstr);
251 }
252
253 return mp_obj_str_builder_end(o);
254
255wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000256 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200257}
258
Damien George55baff42014-01-21 21:40:13 +0000259// like strstr but with specified length and allows \0 bytes
260// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100261STATIC 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 +0000262 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100263 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700264 if (direction > 0) {
265 str_index = 0;
266 str_index_end = hlen - nlen;
267 } else {
268 str_index = hlen - nlen;
269 str_index_end = 0;
270 }
271 for (;;) {
272 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
273 //found
274 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000275 }
xbe17a5a832014-03-23 23:31:58 -0700276 if (str_index == str_index_end) {
277 //not found
278 break;
Damien George55baff42014-01-21 21:40:13 +0000279 }
xbe17a5a832014-03-23 23:31:58 -0700280 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000281 }
282 }
283 return NULL;
284}
285
Damien Georgea75b02e2014-08-27 09:20:30 +0100286// Note: this function is used to check if an object is a str or bytes, which
287// works because both those types use it as their binary_op method. Revisit
288// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100289mp_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 +0000290 // check for modulo
291 if (op == MP_BINARY_OP_MODULO) {
292 mp_obj_t *args;
293 mp_uint_t n_args;
294 mp_obj_t dict = MP_OBJ_NULL;
295 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
296 // TODO: Support tuple subclasses?
297 mp_obj_tuple_get(rhs_in, &n_args, &args);
298 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
299 args = NULL;
300 n_args = 0;
301 dict = rhs_in;
302 } else {
303 args = &rhs_in;
304 n_args = 1;
305 }
306 return str_modulo_format(lhs_in, n_args, args, dict);
307 }
308
309 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300310 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000311 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
312
313 // check for multiply
314 if (op == MP_BINARY_OP_MULTIPLY) {
315 mp_int_t n;
316 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
317 return MP_OBJ_NULL; // op not supported
318 }
319 if (n <= 0) {
320 if (lhs_type == &mp_type_str) {
321 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
322 } else {
323 return mp_const_empty_bytes;
324 }
325 }
326 byte *data;
327 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
328 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
329 return mp_obj_str_builder_end(s);
330 }
331
332 // From now on all operations allow:
333 // - str with str
334 // - bytes with bytes
335 // - bytes with bytearray
336 // - bytes with array.array
337 // To do this efficiently we use the buffer protocol to extract the raw
338 // data for the rhs, but only if the lhs is a bytes object.
339 //
340 // NOTE: CPython does not allow comparison between bytes ard array.array
341 // (even if the array is of type 'b'), even though it allows addition of
342 // such types. We are not compatible with this (we do allow comparison
343 // of bytes with anything that has the buffer protocol). It would be
344 // easy to "fix" this with a bit of extra logic below, but it costs code
345 // size and execution time so we don't.
346
347 const byte *rhs_data;
348 mp_uint_t rhs_len;
349 if (lhs_type == mp_obj_get_type(rhs_in)) {
350 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
351 rhs_data = rhs_data_;
352 rhs_len = rhs_len_;
353 } else if (lhs_type == &mp_type_bytes) {
354 mp_buffer_info_t bufinfo;
355 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
356 goto incompatible;
357 }
358 rhs_data = bufinfo.buf;
359 rhs_len = bufinfo.len;
360 } else {
361 // incompatible types
362 incompatible:
363 if (op == MP_BINARY_OP_EQUAL) {
364 return mp_const_false; // can check for equality against every type
365 }
366 return MP_OBJ_NULL; // op not supported
367 }
368
Damiend99b0522013-12-21 18:17:45 +0000369 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100370 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000371 case MP_BINARY_OP_INPLACE_ADD: {
372 mp_uint_t alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000373 byte *data;
Damien Georgea65c03c2014-11-05 16:30:34 +0000374 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
375 memcpy(data, lhs_data, lhs_len);
376 memcpy(data + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000377 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200378 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200379
Damien Georgea65c03c2014-11-05 16:30:34 +0000380 case MP_BINARY_OP_IN:
381 /* NOTE `a in b` is `b.__contains__(a)` */
382 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300383
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300384 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
385 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 +0100386 case MP_BINARY_OP_LESS:
387 case MP_BINARY_OP_LESS_EQUAL:
388 case MP_BINARY_OP_MORE:
389 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000390 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000391 }
392
Damien George6ac5dce2014-05-21 19:42:43 +0100393 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000394}
395
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300396#if !MICROPY_PY_BUILTINS_STR_UNICODE
397// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100398const 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 +0300399 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100400 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300401 return self_data + index_val;
402}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300403#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300404
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300405// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
406STATIC 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 +0300407 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100408 GET_STR_DATA_LEN(self_in, self_data, self_len);
409 if (value == MP_OBJ_SENTINEL) {
410 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100411#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100412 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300413 mp_bound_slice_t slice;
414 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300415 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100416 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100417 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100418 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100419 }
420#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300421 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100422 // If we have unicode enabled the type will always be bytes, so take the short cut.
423 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300424 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100425 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300426 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100427 }
428 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100429 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100430 }
431}
432
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200433STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700434 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300435 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000436
Damien Georgefe8fb912014-01-02 16:36:09 +0000437 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000438 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000439
440 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100441 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000442 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000443 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000444 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000445 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100446 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
447 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300448 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100449 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
450 }
451 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000452 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000453
454 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100455 mp_uint_t required_len = 0;
456 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300457 if (mp_obj_get_type(seq_items[i]) != self_type) {
458 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
459 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000460 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000461 if (i > 0) {
462 required_len += sep_len;
463 }
Damien George5fa93b62014-01-22 14:35:10 +0000464 GET_STR_LEN(seq_items[i], l);
465 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000466 }
467
468 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000469 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300470 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damien George39dc1452014-10-03 19:52:22 +0100471 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000472 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000473 memcpy(data, sep_str, sep_len);
474 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000475 }
Damien George5fa93b62014-01-22 14:35:10 +0000476 GET_STR_DATA_LEN(seq_items[i], s, l);
477 memcpy(data, s, l);
478 data += l;
Damiend99b0522013-12-21 18:17:45 +0000479 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000480
481 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000482 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000483}
484
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200485#define is_ws(c) ((c) == ' ' || (c) == '\t')
486
Damien Georgeecc88e92014-08-30 00:35:11 +0100487STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300488 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100489 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200490 mp_obj_t sep = mp_const_none;
491 if (n_args > 1) {
492 sep = args[1];
493 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100494 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200495 }
496 }
Damien Georgedeed0872014-04-06 11:11:15 +0100497
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200498 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000499 GET_STR_DATA_LEN(args[0], s, len);
500 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200501
Damien Georgedeed0872014-04-06 11:11:15 +0100502 if (sep == mp_const_none) {
503 // sep not given, so separate on whitespace
504
505 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000506 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100507 while (s < top && splits != 0) {
508 const byte *start = s;
509 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100510 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100511 if (s >= top) {
512 break;
513 }
514 while (s < top && is_ws(*s)) s++;
515 if (splits > 0) {
516 splits--;
517 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200518 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200519
Damien Georgedeed0872014-04-06 11:11:15 +0100520 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100521 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100522 }
523
524 } else {
525 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300526 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000527 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300528 }
Damien Georgedeed0872014-04-06 11:11:15 +0100529
Damien Georged182b982014-08-30 14:19:41 +0100530 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100531 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
532
533 if (sep_len == 0) {
534 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
535 }
536
537 for (;;) {
538 const byte *start = s;
539 for (;;) {
540 if (splits == 0 || s + sep_len > top) {
541 s = top;
542 break;
543 } else if (memcmp(s, sep_str, sep_len) == 0) {
544 break;
545 }
546 s++;
547 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100548 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100549 if (s >= top) {
550 break;
551 }
552 s += sep_len;
553 if (splits > 0) {
554 splits--;
555 }
556 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200557 }
558
559 return res;
560}
561
Damien Georgeecc88e92014-08-30 00:35:11 +0100562STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300563 if (n_args < 3) {
564 // If we don't have split limit, it doesn't matter from which side
565 // we split.
566 return str_split(n_args, args);
567 }
568 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
569 mp_obj_t sep = args[1];
570 GET_STR_DATA_LEN(args[0], s, len);
571
Damien George40f3c022014-07-03 13:25:24 +0100572 mp_int_t splits = mp_obj_get_int(args[2]);
573 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300574 // Preallocate list to the max expected # of elements, as we
575 // will fill it from the end.
576 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100577 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300578
579 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000580 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300581 } else {
Damien Georged182b982014-08-30 14:19:41 +0100582 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300583 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
584
585 if (sep_len == 0) {
586 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
587 }
588
589 const byte *beg = s;
590 const byte *last = s + len;
591 for (;;) {
592 s = last - sep_len;
593 for (;;) {
594 if (splits == 0 || s < beg) {
595 break;
596 } else if (memcmp(s, sep_str, sep_len) == 0) {
597 break;
598 }
599 s--;
600 }
601 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100602 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300603 break;
604 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100605 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 +0300606 last = s;
607 if (splits > 0) {
608 splits--;
609 }
610 }
611 if (idx != 0) {
612 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100613 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100614 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300615 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
616 res->len = used;
617 }
618 }
619
620 return res;
621}
622
Damien Georgeecc88e92014-08-30 00:35:11 +0100623STATIC 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 +0300624 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000625 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000626 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
627
628 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000629 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000630 bad_implicit_conversion(args[1]);
631 }
John R. Lentone8204912014-01-12 21:53:52 +0000632
Damien George5fa93b62014-01-22 14:35:10 +0000633 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
634 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000635
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300636 const byte *start = haystack;
637 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000638 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300639 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000640 }
641 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300642 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000643 }
644
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300645 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000646 if (p == NULL) {
647 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700648 if (is_index) {
649 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
650 } else {
651 return MP_OBJ_NEW_SMALL_INT(-1);
652 }
Damien George23005372014-01-13 19:39:01 +0000653 } else {
654 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300655 #if MICROPY_PY_BUILTINS_STR_UNICODE
656 if (self_type == &mp_type_str) {
657 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
658 }
659 #endif
xbe17a5a832014-03-23 23:31:58 -0700660 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000661 }
John R. Lentone8204912014-01-12 21:53:52 +0000662}
663
Damien Georgeecc88e92014-08-30 00:35:11 +0100664STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700665 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700666}
667
Damien Georgeecc88e92014-08-30 00:35:11 +0100668STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700669 return str_finder(n_args, args, -1, false);
670}
671
Damien Georgeecc88e92014-08-30 00:35:11 +0100672STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700673 return str_finder(n_args, args, 1, true);
674}
675
Damien Georgeecc88e92014-08-30 00:35:11 +0100676STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700677 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700678}
679
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200680// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100681STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300682 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300683 GET_STR_DATA_LEN(args[0], str, str_len);
684 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300685 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300686 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300687 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300688 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300689 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200690 return mp_const_false;
691 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300692 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200693}
694
Damien Georgeecc88e92014-08-30 00:35:11 +0100695STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300696 GET_STR_DATA_LEN(args[0], str, str_len);
697 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
698 assert(n_args == 2);
699
700 if (suffix_len > str_len) {
701 return mp_const_false;
702 }
703 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
704}
705
Paul Sokolovsky88107842014-04-26 06:20:08 +0300706enum { LSTRIP, RSTRIP, STRIP };
707
Damien Georgeecc88e92014-08-30 00:35:11 +0100708STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800709 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700710 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300711 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000712
713 const byte *chars_to_del;
714 uint chars_to_del_len;
715 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800716
717 if (n_args == 1) {
718 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000719 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800720 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300721 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000722 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300723 }
Damien George5fa93b62014-01-22 14:35:10 +0000724 GET_STR_DATA_LEN(args[1], s, l);
725 chars_to_del = s;
726 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800727 }
728
Damien George5fa93b62014-01-22 14:35:10 +0000729 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800730
Damien George40f3c022014-07-03 13:25:24 +0100731 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800732 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100733 mp_uint_t last_good_char_pos = 0;
734 mp_uint_t i = 0;
735 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300736 if (type == RSTRIP) {
737 i = orig_str_len - 1;
738 delta = -1;
739 }
Damien George40f3c022014-07-03 13:25:24 +0100740 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700741 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800742 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300743 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800744 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300745 if (type == LSTRIP) {
746 last_good_char_pos = orig_str_len - 1;
747 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300748 } else if (type == RSTRIP) {
749 first_good_char_pos = 0;
750 last_good_char_pos = i;
751 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300752 }
xbe7b0f39f2014-01-08 14:23:45 -0800753 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300754 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800755 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300756 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800757 }
758
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300759 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000760 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000761 if (self_type == &mp_type_str) {
762 return MP_OBJ_NEW_QSTR(MP_QSTR_);
763 } else {
764 return mp_const_empty_bytes;
765 }
xbe7b0f39f2014-01-08 14:23:45 -0800766 }
767
768 assert(last_good_char_pos >= first_good_char_pos);
769 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100770 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300771 if (stripped_len == orig_str_len) {
772 // If nothing was stripped, don't bother to dup original string
773 // TODO: watch out for this case when we'll get to bytearray.strip()
774 assert(first_good_char_pos == 0);
775 return args[0];
776 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100777 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800778}
779
Damien Georgeecc88e92014-08-30 00:35:11 +0100780STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300781 return str_uni_strip(STRIP, n_args, args);
782}
783
Damien Georgeecc88e92014-08-30 00:35:11 +0100784STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300785 return str_uni_strip(LSTRIP, n_args, args);
786}
787
Damien Georgeecc88e92014-08-30 00:35:11 +0100788STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300789 return str_uni_strip(RSTRIP, n_args, args);
790}
791
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700792// Takes an int arg, but only parses unsigned numbers, and only changes
793// *num if at least one digit was parsed.
794static int str_to_int(const char *str, int *num) {
795 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000796 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700797 *num = 0;
798 do {
799 *num = *num * 10 + (*s - '0');
800 s++;
801 }
Damien George81836c22014-12-21 21:07:03 +0000802 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700803 }
804 return s - str;
805}
806
807static bool isalignment(char ch) {
808 return ch && strchr("<>=^", ch) != NULL;
809}
810
811static bool istype(char ch) {
812 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
813}
814
815static bool arg_looks_integer(mp_obj_t arg) {
816 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
817}
818
819static bool arg_looks_numeric(mp_obj_t arg) {
820 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100821#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700822 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
823#endif
824 ;
825}
826
Dave Hylandsc4029e52014-04-07 11:19:51 -0700827static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100828#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700829 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Paul Sokolovsky2c756652014-12-31 02:20:57 +0200830 return mp_obj_new_int_from_float(mp_obj_get_float(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700831 }
832#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700833 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700834}
835
Damien George1e9a92f2014-11-06 17:36:16 +0000836STATIC NORETURN void terse_str_format_value_error(void) {
837 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
838}
839
Damien Georgeecc88e92014-08-30 00:35:11 +0100840mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000841 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000842
Damien George5fa93b62014-01-22 14:35:10 +0000843 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700844 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000845 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700846 pfenv_t pfenv_vstr;
847 pfenv_vstr.data = vstr;
848 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
849
Damien George5fa93b62014-01-22 14:35:10 +0000850 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700851 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000852 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700853 if (str < top && *str == '}') {
854 vstr_add_char(vstr, '}');
855 continue;
856 }
Damien George1e9a92f2014-11-06 17:36:16 +0000857 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
858 terse_str_format_value_error();
859 } else {
860 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
861 "single '}' encountered in format string"));
862 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700863 }
864 if (*str != '{') {
865 vstr_add_char(vstr, *str);
866 continue;
867 }
868
869 str++;
870 if (str < top && *str == '{') {
871 vstr_add_char(vstr, '{');
872 continue;
873 }
874
875 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
876
877 vstr_t *field_name = NULL;
878 char conversion = '\0';
879 vstr_t *format_spec = NULL;
880
881 if (str < top && *str != '}' && *str != '!' && *str != ':') {
882 field_name = vstr_new();
883 while (str < top && *str != '}' && *str != '!' && *str != ':') {
884 vstr_add_char(field_name, *str++);
885 }
886 vstr_add_char(field_name, '\0');
887 }
888
889 // conversion ::= "r" | "s"
890
891 if (str < top && *str == '!') {
892 str++;
893 if (str < top && (*str == 'r' || *str == 's')) {
894 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200895 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000896 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
897 terse_str_format_value_error();
898 } else {
899 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
900 "end of format while looking for conversion specifier"));
901 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700902 }
903 }
904
905 if (str < top && *str == ':') {
906 str++;
907 // {:} is the same as {}, which is the same as {!s}
908 // This makes a difference when passing in a True or False
909 // '{}'.format(True) returns 'True'
910 // '{:d}'.format(True) returns '1'
911 // So we treat {:} as {} and this later gets treated to be {!s}
912 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100913 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700914 while (str < top && *str != '}') {
915 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000916 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700917 vstr_add_char(format_spec, '\0');
918 }
919 }
920 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000921 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
922 terse_str_format_value_error();
923 } else {
924 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
925 "unmatched '{' in format"));
926 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700927 }
928 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000929 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
930 terse_str_format_value_error();
931 } else {
932 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
933 "expected ':' after format specifier"));
934 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700935 }
936
937 mp_obj_t arg = mp_const_none;
938
939 if (field_name) {
940 if (arg_i > 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000941 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
942 terse_str_format_value_error();
943 } else {
944 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
945 "can't switch from automatic field numbering to manual field specification"));
946 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700947 }
Damien George3bb8bd82014-04-14 21:20:30 +0100948 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700949 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100950 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700951 }
952 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100953 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700954 }
955 arg = args[index + 1];
956 arg_i = -1;
957 vstr_free(field_name);
958 field_name = NULL;
959 } else {
960 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000961 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
962 terse_str_format_value_error();
963 } else {
964 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
965 "can't switch from manual field specification to automatic field numbering"));
966 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700967 }
968 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100969 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700970 }
971 arg = args[arg_i + 1];
972 arg_i++;
973 }
974 if (!format_spec && !conversion) {
975 conversion = 's';
976 }
977 if (conversion) {
978 mp_print_kind_t print_kind;
979 if (conversion == 's') {
980 print_kind = PRINT_STR;
981 } else if (conversion == 'r') {
982 print_kind = PRINT_REPR;
983 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000984 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
985 terse_str_format_value_error();
986 } else {
987 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
988 "unknown conversion specifier %c", conversion));
989 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700990 }
991 vstr_t *arg_vstr = vstr_new();
992 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100993 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700994 vstr_free(arg_vstr);
995 }
996
997 char sign = '\0';
998 char fill = '\0';
999 char align = '\0';
1000 int width = -1;
1001 int precision = -1;
1002 char type = '\0';
1003 int flags = 0;
1004
1005 if (format_spec) {
1006 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1007 //
1008 // [[fill]align][sign][#][0][width][,][.precision][type]
1009 // fill ::= <any character>
1010 // align ::= "<" | ">" | "=" | "^"
1011 // sign ::= "+" | "-" | " "
1012 // width ::= integer
1013 // precision ::= integer
1014 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1015
1016 const char *s = vstr_str(format_spec);
1017 if (isalignment(*s)) {
1018 align = *s++;
1019 } else if (*s && isalignment(s[1])) {
1020 fill = *s++;
1021 align = *s++;
1022 }
1023 if (*s == '+' || *s == '-' || *s == ' ') {
1024 if (*s == '+') {
1025 flags |= PF_FLAG_SHOW_SIGN;
1026 } else if (*s == ' ') {
1027 flags |= PF_FLAG_SPACE_SIGN;
1028 }
1029 sign = *s++;
1030 }
1031 if (*s == '#') {
1032 flags |= PF_FLAG_SHOW_PREFIX;
1033 s++;
1034 }
1035 if (*s == '0') {
1036 if (!align) {
1037 align = '=';
1038 }
1039 if (!fill) {
1040 fill = '0';
1041 }
1042 }
1043 s += str_to_int(s, &width);
1044 if (*s == ',') {
1045 flags |= PF_FLAG_SHOW_COMMA;
1046 s++;
1047 }
1048 if (*s == '.') {
1049 s++;
1050 s += str_to_int(s, &precision);
1051 }
1052 if (istype(*s)) {
1053 type = *s++;
1054 }
1055 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001056 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001057 }
1058 vstr_free(format_spec);
1059 format_spec = NULL;
1060 }
1061 if (!align) {
1062 if (arg_looks_numeric(arg)) {
1063 align = '>';
1064 } else {
1065 align = '<';
1066 }
1067 }
1068 if (!fill) {
1069 fill = ' ';
1070 }
1071
1072 if (sign) {
1073 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001074 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1075 terse_str_format_value_error();
1076 } else {
1077 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1078 "sign not allowed in string format specifier"));
1079 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001080 }
1081 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001082 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1083 terse_str_format_value_error();
1084 } else {
1085 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1086 "sign not allowed with integer format specifier 'c'"));
1087 }
Damiend99b0522013-12-21 18:17:45 +00001088 }
1089 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001090 sign = '-';
1091 }
1092
1093 switch (align) {
1094 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1095 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1096 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1097 }
1098
1099 if (arg_looks_integer(arg)) {
1100 switch (type) {
1101 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001102 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001103 continue;
1104
1105 case 'c':
1106 {
1107 char ch = mp_obj_get_int(arg);
1108 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1109 continue;
1110 }
1111
1112 case '\0': // No explicit format type implies 'd'
1113 case 'n': // I don't think we support locales in uPy so use 'd'
1114 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001115 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001116 continue;
1117
1118 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001119 if (flags & PF_FLAG_SHOW_PREFIX) {
1120 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1121 }
1122
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001123 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001124 continue;
1125
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001126 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001127 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001128 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001129 continue;
1130
1131 case 'e':
1132 case 'E':
1133 case 'f':
1134 case 'F':
1135 case 'g':
1136 case 'G':
1137 case '%':
1138 // The floating point formatters all work with anything that
1139 // looks like an integer
1140 break;
1141
1142 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001143 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1144 terse_str_format_value_error();
1145 } else {
1146 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1147 "unknown format code '%c' for object of type '%s'",
1148 type, mp_obj_get_type_str(arg)));
1149 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001151 }
Damien George70f33cd2014-04-02 17:06:05 +01001152
Dave Hylands22fe4d72014-04-02 12:07:31 -07001153 // NOTE: no else here. We need the e, f, g etc formats for integer
1154 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001155 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001156 if (!type) {
1157
1158 // Even though the docs say that an unspecified type is the same
1159 // as 'g', there is one subtle difference, when the exponent
1160 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001161 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001162 // '{:10.1}'.format(0.0) ==> '0e+00'
1163 // '{:10.1g}'.format(0.0) ==> '0'
1164 //
1165 // TODO: Figure out how to deal with this.
1166 //
1167 // A proper solution would involve adding a special flag
1168 // or something to format_float, and create a format_double
1169 // to deal with doubles. In order to fix this when using
1170 // sprintf, we'd need to use the e format and tweak the
1171 // returned result to strip trailing zeros like the g format
1172 // does.
1173 //
1174 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1175 // but with 1.e2 you get 1e+02 and 1.00e+02
1176 //
1177 // Stripping the trailing 0's (like g) does would make the
1178 // e format give us the right format.
1179 //
1180 // CPython sources say:
1181 // Omitted type specifier. Behaves in the same way as repr(x)
1182 // and str(x) if no precision is given, else like 'g', but with
1183 // at least one digit after the decimal point. */
1184
1185 type = 'g';
1186 }
1187 if (type == 'n') {
1188 type = 'g';
1189 }
1190
1191 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1192 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001193#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001194 case 'e':
1195 case 'E':
1196 case 'f':
1197 case 'F':
1198 case 'g':
1199 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001200 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001201 break;
1202
1203 case '%':
1204 flags |= PF_FLAG_ADD_PERCENT;
1205 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1206 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001207#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001208
1209 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001210 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1211 terse_str_format_value_error();
1212 } else {
1213 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1214 "unknown format code '%c' for object of type 'float'",
1215 type, mp_obj_get_type_str(arg)));
1216 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001217 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001218 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001219 // arg doesn't look like a number
1220
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001221 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001222 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1223 terse_str_format_value_error();
1224 } else {
1225 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1226 "'=' alignment not allowed in string format specifier"));
1227 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001228 }
Damien George70f33cd2014-04-02 17:06:05 +01001229
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001230 switch (type) {
1231 case '\0':
1232 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1233 break;
1234
Damien Georged182b982014-08-30 14:19:41 +01001235 case 's': {
1236 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001237 const char *s = mp_obj_str_get_data(arg, &len);
1238 if (precision < 0) {
1239 precision = len;
1240 }
1241 if (len > precision) {
1242 len = precision;
1243 }
1244 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1245 break;
1246 }
1247
1248 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001249 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1250 terse_str_format_value_error();
1251 } else {
1252 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1253 "unknown format code '%c' for object of type 'str'",
1254 type, mp_obj_get_type_str(arg)));
1255 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001256 }
Damiend99b0522013-12-21 18:17:45 +00001257 }
1258 }
1259
Damien George2617eeb2014-05-25 22:27:57 +01001260 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001261 vstr_free(vstr);
1262 return s;
Damiend99b0522013-12-21 18:17:45 +00001263}
1264
Damien Georgeecc88e92014-08-30 00:35:11 +01001265STATIC 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 +00001266 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001267
1268 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001269 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001270 int arg_i = 0;
1271 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001272 pfenv_t pfenv_vstr;
1273 pfenv_vstr.data = vstr;
1274 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1275
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001276 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001277 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001278 if (*str != '%') {
1279 vstr_add_char(vstr, *str);
1280 continue;
1281 }
1282 if (++str >= top) {
1283 break;
1284 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001285 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001286 vstr_add_char(vstr, '%');
1287 continue;
1288 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001289
1290 // Dictionary value lookup
1291 if (*str == '(') {
1292 const byte *key = ++str;
1293 while (*str != ')') {
1294 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001295 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1296 terse_str_format_value_error();
1297 } else {
1298 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1299 "incomplete format key"));
1300 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001301 }
1302 ++str;
1303 }
1304 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1305 arg = mp_obj_dict_get(dict, k_obj);
1306 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001307 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001308
Dave Hylands6756a372014-04-02 11:42:39 -07001309 int flags = 0;
1310 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001311 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001312 while (str < top) {
1313 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1314 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1315 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001316 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001317 else if (*str == '0') {
1318 flags |= PF_FLAG_PAD_AFTER_SIGN;
1319 fill = '0';
1320 } else break;
1321 str++;
1322 }
1323 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001324 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001325 if (str < top) {
1326 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001327 if (arg_i >= n_args) {
1328 goto not_enough_args;
1329 }
Dave Hylands6756a372014-04-02 11:42:39 -07001330 width = mp_obj_get_int(args[arg_i++]);
1331 str++;
1332 } else {
Damien George81836c22014-12-21 21:07:03 +00001333 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001334 }
1335 }
1336 int prec = -1;
1337 if (str < top && *str == '.') {
1338 if (++str < top) {
1339 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001340 if (arg_i >= n_args) {
1341 goto not_enough_args;
1342 }
Dave Hylands6756a372014-04-02 11:42:39 -07001343 prec = mp_obj_get_int(args[arg_i++]);
1344 str++;
1345 } else {
1346 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001347 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001348 }
1349 }
1350 }
1351
1352 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001353 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1354 terse_str_format_value_error();
1355 } else {
1356 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1357 "incomplete format"));
1358 }
Dave Hylands6756a372014-04-02 11:42:39 -07001359 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001360
1361 // Tuple value lookup
1362 if (arg == MP_OBJ_NULL) {
1363 if (arg_i >= n_args) {
1364not_enough_args:
1365 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1366 }
1367 arg = args[arg_i++];
1368 }
Dave Hylands6756a372014-04-02 11:42:39 -07001369 switch (*str) {
1370 case 'c':
1371 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001372 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001373 const char *s = mp_obj_str_get_data(arg, &len);
1374 if (len != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001375 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1376 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001377 }
1378 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001379 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001380 char ch = mp_obj_get_int(arg);
1381 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001382 } else {
1383 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1384 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001385 }
Damien George11de8392014-06-05 18:57:38 +01001386 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001387
1388 case 'd':
1389 case 'i':
1390 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001391 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001392 break;
1393
Damien Georgefb510b32014-06-01 13:32:54 +01001394#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001395 case 'e':
1396 case 'E':
1397 case 'f':
1398 case 'F':
1399 case 'g':
1400 case 'G':
1401 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1402 break;
1403#endif
1404
1405 case 'o':
1406 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001407 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001408 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001409 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001410 break;
1411
1412 case 'r':
1413 case 's':
1414 {
1415 vstr_t *arg_vstr = vstr_new();
1416 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1417 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1418 uint len = vstr_len(arg_vstr);
1419 if (prec < 0) {
1420 prec = len;
1421 }
1422 if (len > prec) {
1423 len = prec;
1424 }
1425 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1426 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001427 break;
1428 }
Dave Hylands6756a372014-04-02 11:42:39 -07001429
Dave Hylands6756a372014-04-02 11:42:39 -07001430 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001431 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001432 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001433 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001434
Dave Hylands6756a372014-04-02 11:42:39 -07001435 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001436 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1437 terse_str_format_value_error();
1438 } else {
1439 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1440 "unsupported format character '%c' (0x%x) at index %d",
1441 *str, *str, str - start_str));
1442 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001443 }
1444 }
1445
1446 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001447 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001448 }
1449
Damien George2617eeb2014-05-25 22:27:57 +01001450 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001451 vstr_free(vstr);
1452 return s;
1453}
1454
Damien Georgeecc88e92014-08-30 00:35:11 +01001455STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001456 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001457
Damien George40f3c022014-07-03 13:25:24 +01001458 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001459 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001460 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001461 if (max_rep == 0) {
1462 return args[0];
1463 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001464 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001465 }
xbe480c15a2014-01-30 22:17:30 -08001466 }
Damien George94f68302014-01-31 23:45:12 +00001467
xbe729be9b2014-04-07 14:46:39 -07001468 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001469
Damien Georgeff715422014-04-07 00:39:13 +01001470 // check argument types
1471
Damien Georgec55a4d82014-12-24 20:28:30 +00001472 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1473
1474 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001475 bad_implicit_conversion(args[1]);
1476 }
1477
Damien Georgec55a4d82014-12-24 20:28:30 +00001478 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001479 bad_implicit_conversion(args[2]);
1480 }
1481
1482 // extract string data
1483
xbe480c15a2014-01-30 22:17:30 -08001484 GET_STR_DATA_LEN(args[0], str, str_len);
1485 GET_STR_DATA_LEN(args[1], old, old_len);
1486 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001487
1488 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001489 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001490 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001491 }
1492
Damien George94f68302014-01-31 23:45:12 +00001493 // data for the replaced string
1494 byte *data = NULL;
1495 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001496
Damien George94f68302014-01-31 23:45:12 +00001497 // do 2 passes over the string:
1498 // first pass computes the required length of the replaced string
1499 // second pass does the replacements
1500 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001501 mp_uint_t replaced_str_index = 0;
1502 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001503 const byte *old_occurrence;
1504 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001505 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001506 if (old_len == 0) {
1507 // if old_str is empty, copy new_str to start of replaced string
1508 // copy the replacement string
1509 if (data != NULL) {
1510 memcpy(data, new, new_len);
1511 }
1512 replaced_str_index += new_len;
1513 num_replacements_done++;
1514 }
1515 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1516 if (old_len == 0) {
1517 old_occurrence += 1;
1518 }
Damien George94f68302014-01-31 23:45:12 +00001519 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1520 if (data != NULL) {
1521 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1522 }
1523 replaced_str_index += old_occurrence - offset_ptr;
1524 // copy the replacement string
1525 if (data != NULL) {
1526 memcpy(data + replaced_str_index, new, new_len);
1527 }
1528 replaced_str_index += new_len;
1529 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001530 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001531 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001532 }
1533
1534 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1535 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001536 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001537 }
Damien Georgeff715422014-04-07 00:39:13 +01001538 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001539
1540 if (data == NULL) {
1541 // first pass
1542 if (num_replacements_done == 0) {
1543 // no substr found, return original string
1544 return args[0];
1545 } else {
1546 // substr found, allocate new string
Damien Georgec55a4d82014-12-24 20:28:30 +00001547 replaced_str = mp_obj_str_builder_start(self_type, replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001548 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001549 }
1550 } else {
1551 // second pass, we are done
1552 break;
1553 }
xbe480c15a2014-01-30 22:17:30 -08001554 }
Damien George94f68302014-01-31 23:45:12 +00001555
xbe480c15a2014-01-30 22:17:30 -08001556 return mp_obj_str_builder_end(replaced_str);
1557}
1558
Damien Georgeecc88e92014-08-30 00:35:11 +01001559STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001560 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001561 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001562 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1563
1564 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001565 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001566 bad_implicit_conversion(args[1]);
1567 }
xbe9e1e8cd2014-03-12 22:57:16 -07001568
1569 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1570 GET_STR_DATA_LEN(args[1], needle, needle_len);
1571
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001572 const byte *start = haystack;
1573 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001574 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001575 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001576 }
1577 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001578 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001579 }
1580
Damien George536dde22014-03-13 22:07:55 +00001581 // if needle_len is zero then we count each gap between characters as an occurrence
1582 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001583 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001584 }
1585
Damien George536dde22014-03-13 22:07:55 +00001586 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001587 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001588 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1589 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001590 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001591 haystack_ptr += needle_len;
1592 } else {
1593 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001594 }
xbe9e1e8cd2014-03-12 22:57:16 -07001595 }
1596
1597 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1598}
1599
Damien George40f3c022014-07-03 13:25:24 +01001600STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001601 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001602 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1603 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001604 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001605 }
Damien Georgeb035db32014-03-21 20:39:40 +00001606
xbe613a8e32014-03-18 00:06:29 -07001607 GET_STR_DATA_LEN(self_in, str, str_len);
1608 GET_STR_DATA_LEN(arg, sep, sep_len);
1609
1610 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001611 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001612 }
Damien Georgeb035db32014-03-21 20:39:40 +00001613
Damien Georgec55a4d82014-12-24 20:28:30 +00001614 mp_obj_t result[3];
1615 if (self_type == &mp_type_str) {
1616 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1617 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1618 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1619 } else {
1620 result[0] = mp_const_empty_bytes;
1621 result[1] = mp_const_empty_bytes;
1622 result[2] = mp_const_empty_bytes;
1623 }
Damien Georgeb035db32014-03-21 20:39:40 +00001624
1625 if (direction > 0) {
1626 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001627 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001628 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001629 }
xbe613a8e32014-03-18 00:06:29 -07001630
xbe17a5a832014-03-23 23:31:58 -07001631 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1632 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001633 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001634 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001635 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001636 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 -07001637 }
Damien Georgeb035db32014-03-21 20:39:40 +00001638
xbe0a6894c2014-03-21 01:12:26 -07001639 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001640}
1641
Damien Georgeb035db32014-03-21 20:39:40 +00001642STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1643 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001644}
xbe4504ea82014-03-19 00:46:14 -07001645
Damien Georgeb035db32014-03-21 20:39:40 +00001646STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1647 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001648}
1649
Paul Sokolovsky69135212014-05-10 19:47:41 +03001650// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001651STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001652 GET_STR_DATA_LEN(self_in, self_data, self_len);
1653 byte *data;
1654 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 +01001655 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001656 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001657 }
1658 *data = 0;
1659 return mp_obj_str_builder_end(s);
1660}
1661
1662STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001663 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001664}
1665
1666STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001667 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001668}
1669
Damien Georgefcc9cf62014-06-01 18:22:09 +01001670STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001671 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001672
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001673 if (self_len == 0) {
1674 return mp_const_false; // default to False for empty str
1675 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001676
Damien Georgefcc9cf62014-06-01 18:22:09 +01001677 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001678 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001679 if (!f(*self_data++)) {
1680 return mp_const_false;
1681 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001682 }
1683 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001684 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001685
Damien George39dc1452014-10-03 19:52:22 +01001686 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001687 if (unichar_isalpha(*self_data++)) {
1688 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001689 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1690 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001691 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001692 }
1693 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001694
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001695 if (!contains_alpha) {
1696 return mp_const_false;
1697 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001698 }
1699
1700 return mp_const_true;
1701}
1702
1703STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001704 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001705}
1706
1707STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001708 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001709}
1710
1711STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001712 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001713}
1714
1715STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001716 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001717}
1718
1719STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001720 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001721}
1722
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001723#if MICROPY_CPYTHON_COMPAT
1724// These methods are superfluous in the presense of str() and bytes()
1725// constructors.
1726// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001727STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001728 mp_obj_t new_args[2];
1729 if (n_args == 1) {
1730 new_args[0] = args[0];
1731 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1732 args = new_args;
1733 n_args++;
1734 }
1735 return str_make_new(NULL, n_args, 0, args);
1736}
1737
1738// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001739STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001740 mp_obj_t new_args[2];
1741 if (n_args == 1) {
1742 new_args[0] = args[0];
1743 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1744 args = new_args;
1745 n_args++;
1746 }
1747 return bytes_make_new(NULL, n_args, 0, args);
1748}
1749#endif
1750
Damien George4d917232014-08-30 14:28:06 +01001751mp_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 +01001752 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001753 GET_STR_DATA_LEN(self_in, str_data, str_len);
1754 bufinfo->buf = (void*)str_data;
1755 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001756 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001757 return 0;
1758 } else {
1759 // can't write to a string
1760 bufinfo->buf = NULL;
1761 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001762 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001763 return 1;
1764 }
1765}
1766
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001767#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001768MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1769MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001770#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001771MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1772MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1773MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1774MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1775MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1776MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1777MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1778MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1779MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1780MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1781MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1782MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1783MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1784MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1785MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1786MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1787MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1788MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1789MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1790MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1791MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1792MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1793MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1794MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001795
Damien George9b196cd2014-03-26 21:47:19 +00001796STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001797#if MICROPY_CPYTHON_COMPAT
1798 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001799 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1800 // If we have separate unicode type, then here we have methods only
1801 // for bytes type, and it should not have encode() methods. Otherwise,
1802 // we have non-compliant-but-practical bytestring type, which shares
1803 // method table with bytes, so they both have encode() and decode()
1804 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001805 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001806 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001807#endif
Damien George9b196cd2014-03-26 21:47:19 +00001808 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1809 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001810 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1811 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001812 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1813 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001814 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001815 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001816 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001817 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001818 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1819 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001820 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1821 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1822 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1823 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1824 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001825 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1826 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001827 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1828 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1829 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1830 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1831 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001832};
Damien George97209d32014-01-07 15:58:30 +00001833
Damien George9b196cd2014-03-26 21:47:19 +00001834STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1835
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001836#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001837const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001838 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001839 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001840 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001841 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001842 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001843 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001844 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001845 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001846 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001847};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001848#endif
Damiend99b0522013-12-21 18:17:45 +00001849
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001850// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001851const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001852 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001853 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001854 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001855 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001856 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001857 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001858 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001859 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001860 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001861};
1862
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001863// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001864const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001865
Damien Georged182b982014-08-30 14:19:41 +01001866mp_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 +02001867 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001868 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001869 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001870 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001871 byte *p = m_new(byte, len + 1);
1872 o->data = p;
1873 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001874 return o;
1875}
1876
Damien George5fa93b62014-01-22 14:35:10 +00001877mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001878 mp_obj_str_t *o = o_in;
1879 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001880 byte *p = (byte*)o->data;
1881 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001882 return o;
1883}
1884
Damien George5f27a7e2014-07-31 10:29:56 +01001885mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1886 mp_obj_str_t *o = o_in;
1887 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1888 o->len = len;
1889 o->hash = qstr_compute_hash(o->data, o->len);
1890 byte *p = (byte*)o->data;
1891 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1892 return o;
1893}
1894
Damien George4abff752014-08-30 14:59:21 +01001895mp_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 +02001896 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001897 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001898 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001899 if (data) {
1900 o->hash = qstr_compute_hash(data, len);
1901 byte *p = m_new(byte, len + 1);
1902 o->data = p;
1903 memcpy(p, data, len * sizeof(byte));
1904 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1905 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001906 return o;
1907}
1908
Damien Georged182b982014-08-30 14:19:41 +01001909mp_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 +01001910 if (make_qstr_if_not_already) {
1911 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001912 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001913 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001914 qstr q = qstr_find_strn(data, len);
1915 if (q != MP_QSTR_NULL) {
1916 // qstr with this data already exists
1917 return MP_OBJ_NEW_QSTR(q);
1918 } else {
1919 // no existing qstr, don't make one
1920 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1921 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001922 }
Damien George5fa93b62014-01-22 14:35:10 +00001923}
1924
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001925mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1926 GET_STR_DATA_LEN(str, data, len);
1927 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1928}
1929
Damien Georged182b982014-08-30 14:19:41 +01001930mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001931 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001932}
1933
Damien George5fa93b62014-01-22 14:35:10 +00001934bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1935 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1936 return s1 == s2;
1937 } else {
1938 GET_STR_HASH(s1, h1);
1939 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001940 // If any of hashes is 0, it means it's not valid
1941 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001942 return false;
1943 }
1944 GET_STR_DATA_LEN(s1, d1, l1);
1945 GET_STR_DATA_LEN(s2, d2, l2);
1946 if (l1 != l2) {
1947 return false;
1948 }
Damien George1e708fe2014-01-23 18:27:51 +00001949 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001950 }
Damien George5fa93b62014-01-22 14:35:10 +00001951}
1952
Damien Georgedeed0872014-04-06 11:11:15 +01001953STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001954 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1955 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1956 "can't convert to str implicitly"));
1957 } else {
1958 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1959 "can't convert '%s' object to str implicitly",
1960 mp_obj_get_type_str(self_in)));
1961 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001962}
1963
Damien Georged182b982014-08-30 14:19:41 +01001964mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001965 // TODO: This has too big overhead for hash accessor
Damien Georgebe8e99c2014-11-05 16:45:54 +00001966 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001967 GET_STR_HASH(self_in, h);
1968 return h;
1969 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001970 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001971 }
1972}
1973
Damien Georged182b982014-08-30 14:19:41 +01001974mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001975 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001976 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001977 GET_STR_LEN(self_in, l);
1978 return l;
1979 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001980 bad_implicit_conversion(self_in);
1981 }
1982}
1983
1984// use this if you will anyway convert the string to a qstr
1985// will be more efficient for the case where it's already a qstr
1986qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1987 if (MP_OBJ_IS_QSTR(self_in)) {
1988 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001989 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001990 mp_obj_str_t *self = self_in;
1991 return qstr_from_strn((char*)self->data, self->len);
1992 } else {
1993 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001994 }
1995}
1996
1997// only use this function if you need the str data to be zero terminated
1998// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1999const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002000 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002001 GET_STR_DATA_LEN(self_in, s, l);
2002 (void)l; // len unused
2003 return (const char*)s;
2004 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002005 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002006 }
2007}
2008
Damien Georged182b982014-08-30 14:19:41 +01002009const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002010 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002011 GET_STR_DATA_LEN(self_in, s, l);
2012 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002013 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002014 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002015 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002016 }
Damiend99b0522013-12-21 18:17:45 +00002017}
xyb8cfc9f02014-01-05 18:47:51 +08002018
2019/******************************************************************************/
2020/* str iterator */
2021
2022typedef struct _mp_obj_str_it_t {
2023 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002024 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002025 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08002026} mp_obj_str_it_t;
2027
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002028#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002029STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08002030 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002031 GET_STR_DATA_LEN(self->str, str, len);
2032 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002033 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002034 self->cur += 1;
2035 return o_out;
2036 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002037 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002038 }
2039}
2040
Damien George3e1a5c12014-03-29 13:43:38 +00002041STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002042 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002043 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002044 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002045 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002046};
2047
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002048mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2049 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
2050 o->base.type = &mp_type_str_it;
2051 o->str = str;
2052 o->cur = 0;
2053 return o;
2054}
2055#endif
2056
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002057STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002058 mp_obj_str_it_t *self = self_in;
2059 GET_STR_DATA_LEN(self->str, str, len);
2060 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002061 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002062 self->cur += 1;
2063 return o_out;
2064 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002065 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002066 }
2067}
2068
Damien George3e1a5c12014-03-29 13:43:38 +00002069STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002070 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002071 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002072 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002073 .iternext = bytes_it_iternext,
2074};
2075
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002076mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
2077 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002078 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002079 o->str = str;
2080 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002081 return o;
2082}