blob: 16ee2ea1dd924e56fc7d15af9ad7b28f3c677d56 [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)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700830
831 // TODO: Needs a way to construct an mpz integer from a float
832
Damien George40f3c022014-07-03 13:25:24 +0100833 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700834 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700835 }
836#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700837 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700838}
839
Damien George1e9a92f2014-11-06 17:36:16 +0000840STATIC NORETURN void terse_str_format_value_error(void) {
841 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
842}
843
Damien Georgeecc88e92014-08-30 00:35:11 +0100844mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000845 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000846
Damien George5fa93b62014-01-22 14:35:10 +0000847 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700848 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000849 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700850 pfenv_t pfenv_vstr;
851 pfenv_vstr.data = vstr;
852 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
853
Damien George5fa93b62014-01-22 14:35:10 +0000854 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700855 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000856 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857 if (str < top && *str == '}') {
858 vstr_add_char(vstr, '}');
859 continue;
860 }
Damien George1e9a92f2014-11-06 17:36:16 +0000861 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
862 terse_str_format_value_error();
863 } else {
864 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
865 "single '}' encountered in format string"));
866 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700867 }
868 if (*str != '{') {
869 vstr_add_char(vstr, *str);
870 continue;
871 }
872
873 str++;
874 if (str < top && *str == '{') {
875 vstr_add_char(vstr, '{');
876 continue;
877 }
878
879 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
880
881 vstr_t *field_name = NULL;
882 char conversion = '\0';
883 vstr_t *format_spec = NULL;
884
885 if (str < top && *str != '}' && *str != '!' && *str != ':') {
886 field_name = vstr_new();
887 while (str < top && *str != '}' && *str != '!' && *str != ':') {
888 vstr_add_char(field_name, *str++);
889 }
890 vstr_add_char(field_name, '\0');
891 }
892
893 // conversion ::= "r" | "s"
894
895 if (str < top && *str == '!') {
896 str++;
897 if (str < top && (*str == 'r' || *str == 's')) {
898 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200899 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000900 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
901 terse_str_format_value_error();
902 } else {
903 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
904 "end of format while looking for conversion specifier"));
905 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700906 }
907 }
908
909 if (str < top && *str == ':') {
910 str++;
911 // {:} is the same as {}, which is the same as {!s}
912 // This makes a difference when passing in a True or False
913 // '{}'.format(True) returns 'True'
914 // '{:d}'.format(True) returns '1'
915 // So we treat {:} as {} and this later gets treated to be {!s}
916 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100917 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700918 while (str < top && *str != '}') {
919 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000920 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700921 vstr_add_char(format_spec, '\0');
922 }
923 }
924 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000925 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
926 terse_str_format_value_error();
927 } else {
928 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
929 "unmatched '{' in format"));
930 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700931 }
932 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000933 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
934 terse_str_format_value_error();
935 } else {
936 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
937 "expected ':' after format specifier"));
938 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700939 }
940
941 mp_obj_t arg = mp_const_none;
942
943 if (field_name) {
944 if (arg_i > 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000945 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
946 terse_str_format_value_error();
947 } else {
948 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
949 "can't switch from automatic field numbering to manual field specification"));
950 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700951 }
Damien George3bb8bd82014-04-14 21:20:30 +0100952 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700953 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100954 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700955 }
956 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100957 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700958 }
959 arg = args[index + 1];
960 arg_i = -1;
961 vstr_free(field_name);
962 field_name = NULL;
963 } else {
964 if (arg_i < 0) {
Damien George1e9a92f2014-11-06 17:36:16 +0000965 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
966 terse_str_format_value_error();
967 } else {
968 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
969 "can't switch from manual field specification to automatic field numbering"));
970 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700971 }
972 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100973 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700974 }
975 arg = args[arg_i + 1];
976 arg_i++;
977 }
978 if (!format_spec && !conversion) {
979 conversion = 's';
980 }
981 if (conversion) {
982 mp_print_kind_t print_kind;
983 if (conversion == 's') {
984 print_kind = PRINT_STR;
985 } else if (conversion == 'r') {
986 print_kind = PRINT_REPR;
987 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000988 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
989 terse_str_format_value_error();
990 } else {
991 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
992 "unknown conversion specifier %c", conversion));
993 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700994 }
995 vstr_t *arg_vstr = vstr_new();
996 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100997 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700998 vstr_free(arg_vstr);
999 }
1000
1001 char sign = '\0';
1002 char fill = '\0';
1003 char align = '\0';
1004 int width = -1;
1005 int precision = -1;
1006 char type = '\0';
1007 int flags = 0;
1008
1009 if (format_spec) {
1010 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
1011 //
1012 // [[fill]align][sign][#][0][width][,][.precision][type]
1013 // fill ::= <any character>
1014 // align ::= "<" | ">" | "=" | "^"
1015 // sign ::= "+" | "-" | " "
1016 // width ::= integer
1017 // precision ::= integer
1018 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
1019
1020 const char *s = vstr_str(format_spec);
1021 if (isalignment(*s)) {
1022 align = *s++;
1023 } else if (*s && isalignment(s[1])) {
1024 fill = *s++;
1025 align = *s++;
1026 }
1027 if (*s == '+' || *s == '-' || *s == ' ') {
1028 if (*s == '+') {
1029 flags |= PF_FLAG_SHOW_SIGN;
1030 } else if (*s == ' ') {
1031 flags |= PF_FLAG_SPACE_SIGN;
1032 }
1033 sign = *s++;
1034 }
1035 if (*s == '#') {
1036 flags |= PF_FLAG_SHOW_PREFIX;
1037 s++;
1038 }
1039 if (*s == '0') {
1040 if (!align) {
1041 align = '=';
1042 }
1043 if (!fill) {
1044 fill = '0';
1045 }
1046 }
1047 s += str_to_int(s, &width);
1048 if (*s == ',') {
1049 flags |= PF_FLAG_SHOW_COMMA;
1050 s++;
1051 }
1052 if (*s == '.') {
1053 s++;
1054 s += str_to_int(s, &precision);
1055 }
1056 if (istype(*s)) {
1057 type = *s++;
1058 }
1059 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001060 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001061 }
1062 vstr_free(format_spec);
1063 format_spec = NULL;
1064 }
1065 if (!align) {
1066 if (arg_looks_numeric(arg)) {
1067 align = '>';
1068 } else {
1069 align = '<';
1070 }
1071 }
1072 if (!fill) {
1073 fill = ' ';
1074 }
1075
1076 if (sign) {
1077 if (type == 's') {
Damien George1e9a92f2014-11-06 17:36:16 +00001078 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1079 terse_str_format_value_error();
1080 } else {
1081 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1082 "sign not allowed in string format specifier"));
1083 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001084 }
1085 if (type == 'c') {
Damien George1e9a92f2014-11-06 17:36:16 +00001086 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1087 terse_str_format_value_error();
1088 } else {
1089 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1090 "sign not allowed with integer format specifier 'c'"));
1091 }
Damiend99b0522013-12-21 18:17:45 +00001092 }
1093 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001094 sign = '-';
1095 }
1096
1097 switch (align) {
1098 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1099 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1100 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1101 }
1102
1103 if (arg_looks_integer(arg)) {
1104 switch (type) {
1105 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001106 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001107 continue;
1108
1109 case 'c':
1110 {
1111 char ch = mp_obj_get_int(arg);
1112 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1113 continue;
1114 }
1115
1116 case '\0': // No explicit format type implies 'd'
1117 case 'n': // I don't think we support locales in uPy so use 'd'
1118 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001119 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001120 continue;
1121
1122 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001123 if (flags & PF_FLAG_SHOW_PREFIX) {
1124 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1125 }
1126
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001127 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001128 continue;
1129
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001130 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001131 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001132 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001133 continue;
1134
1135 case 'e':
1136 case 'E':
1137 case 'f':
1138 case 'F':
1139 case 'g':
1140 case 'G':
1141 case '%':
1142 // The floating point formatters all work with anything that
1143 // looks like an integer
1144 break;
1145
1146 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001147 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1148 terse_str_format_value_error();
1149 } else {
1150 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1151 "unknown format code '%c' for object of type '%s'",
1152 type, mp_obj_get_type_str(arg)));
1153 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001154 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001155 }
Damien George70f33cd2014-04-02 17:06:05 +01001156
Dave Hylands22fe4d72014-04-02 12:07:31 -07001157 // NOTE: no else here. We need the e, f, g etc formats for integer
1158 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001159 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001160 if (!type) {
1161
1162 // Even though the docs say that an unspecified type is the same
1163 // as 'g', there is one subtle difference, when the exponent
1164 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001165 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001166 // '{:10.1}'.format(0.0) ==> '0e+00'
1167 // '{:10.1g}'.format(0.0) ==> '0'
1168 //
1169 // TODO: Figure out how to deal with this.
1170 //
1171 // A proper solution would involve adding a special flag
1172 // or something to format_float, and create a format_double
1173 // to deal with doubles. In order to fix this when using
1174 // sprintf, we'd need to use the e format and tweak the
1175 // returned result to strip trailing zeros like the g format
1176 // does.
1177 //
1178 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1179 // but with 1.e2 you get 1e+02 and 1.00e+02
1180 //
1181 // Stripping the trailing 0's (like g) does would make the
1182 // e format give us the right format.
1183 //
1184 // CPython sources say:
1185 // Omitted type specifier. Behaves in the same way as repr(x)
1186 // and str(x) if no precision is given, else like 'g', but with
1187 // at least one digit after the decimal point. */
1188
1189 type = 'g';
1190 }
1191 if (type == 'n') {
1192 type = 'g';
1193 }
1194
1195 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1196 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001197#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001198 case 'e':
1199 case 'E':
1200 case 'f':
1201 case 'F':
1202 case 'g':
1203 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001204 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001205 break;
1206
1207 case '%':
1208 flags |= PF_FLAG_ADD_PERCENT;
1209 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1210 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001211#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001212
1213 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001214 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1215 terse_str_format_value_error();
1216 } else {
1217 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1218 "unknown format code '%c' for object of type 'float'",
1219 type, mp_obj_get_type_str(arg)));
1220 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001221 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001222 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001223 // arg doesn't look like a number
1224
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001225 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001226 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1227 terse_str_format_value_error();
1228 } else {
1229 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1230 "'=' alignment not allowed in string format specifier"));
1231 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001232 }
Damien George70f33cd2014-04-02 17:06:05 +01001233
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001234 switch (type) {
1235 case '\0':
1236 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1237 break;
1238
Damien Georged182b982014-08-30 14:19:41 +01001239 case 's': {
1240 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001241 const char *s = mp_obj_str_get_data(arg, &len);
1242 if (precision < 0) {
1243 precision = len;
1244 }
1245 if (len > precision) {
1246 len = precision;
1247 }
1248 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1249 break;
1250 }
1251
1252 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001253 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1254 terse_str_format_value_error();
1255 } else {
1256 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1257 "unknown format code '%c' for object of type 'str'",
1258 type, mp_obj_get_type_str(arg)));
1259 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001260 }
Damiend99b0522013-12-21 18:17:45 +00001261 }
1262 }
1263
Damien George2617eeb2014-05-25 22:27:57 +01001264 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001265 vstr_free(vstr);
1266 return s;
Damiend99b0522013-12-21 18:17:45 +00001267}
1268
Damien Georgeecc88e92014-08-30 00:35:11 +01001269STATIC 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 +00001270 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001271
1272 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001273 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001274 int arg_i = 0;
1275 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001276 pfenv_t pfenv_vstr;
1277 pfenv_vstr.data = vstr;
1278 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1279
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001280 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001281 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001282 if (*str != '%') {
1283 vstr_add_char(vstr, *str);
1284 continue;
1285 }
1286 if (++str >= top) {
1287 break;
1288 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001289 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001290 vstr_add_char(vstr, '%');
1291 continue;
1292 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001293
1294 // Dictionary value lookup
1295 if (*str == '(') {
1296 const byte *key = ++str;
1297 while (*str != ')') {
1298 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001299 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1300 terse_str_format_value_error();
1301 } else {
1302 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1303 "incomplete format key"));
1304 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001305 }
1306 ++str;
1307 }
1308 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1309 arg = mp_obj_dict_get(dict, k_obj);
1310 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001311 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001312
Dave Hylands6756a372014-04-02 11:42:39 -07001313 int flags = 0;
1314 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001315 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001316 while (str < top) {
1317 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1318 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1319 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001320 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001321 else if (*str == '0') {
1322 flags |= PF_FLAG_PAD_AFTER_SIGN;
1323 fill = '0';
1324 } else break;
1325 str++;
1326 }
1327 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001328 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001329 if (str < top) {
1330 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001331 if (arg_i >= n_args) {
1332 goto not_enough_args;
1333 }
Dave Hylands6756a372014-04-02 11:42:39 -07001334 width = mp_obj_get_int(args[arg_i++]);
1335 str++;
1336 } else {
Damien George81836c22014-12-21 21:07:03 +00001337 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001338 }
1339 }
1340 int prec = -1;
1341 if (str < top && *str == '.') {
1342 if (++str < top) {
1343 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001344 if (arg_i >= n_args) {
1345 goto not_enough_args;
1346 }
Dave Hylands6756a372014-04-02 11:42:39 -07001347 prec = mp_obj_get_int(args[arg_i++]);
1348 str++;
1349 } else {
1350 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001351 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001352 }
1353 }
1354 }
1355
1356 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001357 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1358 terse_str_format_value_error();
1359 } else {
1360 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1361 "incomplete format"));
1362 }
Dave Hylands6756a372014-04-02 11:42:39 -07001363 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001364
1365 // Tuple value lookup
1366 if (arg == MP_OBJ_NULL) {
1367 if (arg_i >= n_args) {
1368not_enough_args:
1369 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1370 }
1371 arg = args[arg_i++];
1372 }
Dave Hylands6756a372014-04-02 11:42:39 -07001373 switch (*str) {
1374 case 'c':
1375 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001376 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001377 const char *s = mp_obj_str_get_data(arg, &len);
1378 if (len != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001379 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1380 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001381 }
1382 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001383 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001384 char ch = mp_obj_get_int(arg);
1385 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001386 } else {
1387 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1388 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001389 }
Damien George11de8392014-06-05 18:57:38 +01001390 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001391
1392 case 'd':
1393 case 'i':
1394 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001395 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001396 break;
1397
Damien Georgefb510b32014-06-01 13:32:54 +01001398#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001399 case 'e':
1400 case 'E':
1401 case 'f':
1402 case 'F':
1403 case 'g':
1404 case 'G':
1405 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1406 break;
1407#endif
1408
1409 case 'o':
1410 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001411 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001412 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001413 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001414 break;
1415
1416 case 'r':
1417 case 's':
1418 {
1419 vstr_t *arg_vstr = vstr_new();
1420 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1421 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1422 uint len = vstr_len(arg_vstr);
1423 if (prec < 0) {
1424 prec = len;
1425 }
1426 if (len > prec) {
1427 len = prec;
1428 }
1429 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1430 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001431 break;
1432 }
Dave Hylands6756a372014-04-02 11:42:39 -07001433
Dave Hylands6756a372014-04-02 11:42:39 -07001434 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001435 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001436 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001437 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001438
Dave Hylands6756a372014-04-02 11:42:39 -07001439 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001440 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1441 terse_str_format_value_error();
1442 } else {
1443 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1444 "unsupported format character '%c' (0x%x) at index %d",
1445 *str, *str, str - start_str));
1446 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001447 }
1448 }
1449
1450 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001451 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001452 }
1453
Damien George2617eeb2014-05-25 22:27:57 +01001454 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001455 vstr_free(vstr);
1456 return s;
1457}
1458
Damien Georgeecc88e92014-08-30 00:35:11 +01001459STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001460 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001461
Damien George40f3c022014-07-03 13:25:24 +01001462 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001463 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001464 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001465 if (max_rep == 0) {
1466 return args[0];
1467 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001468 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001469 }
xbe480c15a2014-01-30 22:17:30 -08001470 }
Damien George94f68302014-01-31 23:45:12 +00001471
xbe729be9b2014-04-07 14:46:39 -07001472 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001473
Damien Georgeff715422014-04-07 00:39:13 +01001474 // check argument types
1475
Damien Georgec55a4d82014-12-24 20:28:30 +00001476 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1477
1478 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001479 bad_implicit_conversion(args[1]);
1480 }
1481
Damien Georgec55a4d82014-12-24 20:28:30 +00001482 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001483 bad_implicit_conversion(args[2]);
1484 }
1485
1486 // extract string data
1487
xbe480c15a2014-01-30 22:17:30 -08001488 GET_STR_DATA_LEN(args[0], str, str_len);
1489 GET_STR_DATA_LEN(args[1], old, old_len);
1490 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001491
1492 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001493 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001494 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001495 }
1496
Damien George94f68302014-01-31 23:45:12 +00001497 // data for the replaced string
1498 byte *data = NULL;
1499 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001500
Damien George94f68302014-01-31 23:45:12 +00001501 // do 2 passes over the string:
1502 // first pass computes the required length of the replaced string
1503 // second pass does the replacements
1504 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001505 mp_uint_t replaced_str_index = 0;
1506 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001507 const byte *old_occurrence;
1508 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001509 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001510 if (old_len == 0) {
1511 // if old_str is empty, copy new_str to start of replaced string
1512 // copy the replacement string
1513 if (data != NULL) {
1514 memcpy(data, new, new_len);
1515 }
1516 replaced_str_index += new_len;
1517 num_replacements_done++;
1518 }
1519 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1520 if (old_len == 0) {
1521 old_occurrence += 1;
1522 }
Damien George94f68302014-01-31 23:45:12 +00001523 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1524 if (data != NULL) {
1525 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1526 }
1527 replaced_str_index += old_occurrence - offset_ptr;
1528 // copy the replacement string
1529 if (data != NULL) {
1530 memcpy(data + replaced_str_index, new, new_len);
1531 }
1532 replaced_str_index += new_len;
1533 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001534 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001535 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001536 }
1537
1538 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1539 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001540 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001541 }
Damien Georgeff715422014-04-07 00:39:13 +01001542 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001543
1544 if (data == NULL) {
1545 // first pass
1546 if (num_replacements_done == 0) {
1547 // no substr found, return original string
1548 return args[0];
1549 } else {
1550 // substr found, allocate new string
Damien Georgec55a4d82014-12-24 20:28:30 +00001551 replaced_str = mp_obj_str_builder_start(self_type, replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001552 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001553 }
1554 } else {
1555 // second pass, we are done
1556 break;
1557 }
xbe480c15a2014-01-30 22:17:30 -08001558 }
Damien George94f68302014-01-31 23:45:12 +00001559
xbe480c15a2014-01-30 22:17:30 -08001560 return mp_obj_str_builder_end(replaced_str);
1561}
1562
Damien Georgeecc88e92014-08-30 00:35:11 +01001563STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001564 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001565 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001566 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1567
1568 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001569 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001570 bad_implicit_conversion(args[1]);
1571 }
xbe9e1e8cd2014-03-12 22:57:16 -07001572
1573 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1574 GET_STR_DATA_LEN(args[1], needle, needle_len);
1575
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001576 const byte *start = haystack;
1577 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001578 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001579 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001580 }
1581 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001582 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001583 }
1584
Damien George536dde22014-03-13 22:07:55 +00001585 // if needle_len is zero then we count each gap between characters as an occurrence
1586 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001587 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001588 }
1589
Damien George536dde22014-03-13 22:07:55 +00001590 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001591 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001592 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1593 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001594 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001595 haystack_ptr += needle_len;
1596 } else {
1597 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001598 }
xbe9e1e8cd2014-03-12 22:57:16 -07001599 }
1600
1601 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1602}
1603
Damien George40f3c022014-07-03 13:25:24 +01001604STATIC 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 +00001605 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001606 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1607 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001608 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001609 }
Damien Georgeb035db32014-03-21 20:39:40 +00001610
xbe613a8e32014-03-18 00:06:29 -07001611 GET_STR_DATA_LEN(self_in, str, str_len);
1612 GET_STR_DATA_LEN(arg, sep, sep_len);
1613
1614 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001615 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001616 }
Damien Georgeb035db32014-03-21 20:39:40 +00001617
Damien Georgec55a4d82014-12-24 20:28:30 +00001618 mp_obj_t result[3];
1619 if (self_type == &mp_type_str) {
1620 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1621 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1622 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1623 } else {
1624 result[0] = mp_const_empty_bytes;
1625 result[1] = mp_const_empty_bytes;
1626 result[2] = mp_const_empty_bytes;
1627 }
Damien Georgeb035db32014-03-21 20:39:40 +00001628
1629 if (direction > 0) {
1630 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001631 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001632 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001633 }
xbe613a8e32014-03-18 00:06:29 -07001634
xbe17a5a832014-03-23 23:31:58 -07001635 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1636 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001637 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001638 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001639 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001640 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 -07001641 }
Damien Georgeb035db32014-03-21 20:39:40 +00001642
xbe0a6894c2014-03-21 01:12:26 -07001643 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001644}
1645
Damien Georgeb035db32014-03-21 20:39:40 +00001646STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1647 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001648}
xbe4504ea82014-03-19 00:46:14 -07001649
Damien Georgeb035db32014-03-21 20:39:40 +00001650STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1651 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001652}
1653
Paul Sokolovsky69135212014-05-10 19:47:41 +03001654// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001655STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001656 GET_STR_DATA_LEN(self_in, self_data, self_len);
1657 byte *data;
1658 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 +01001659 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001660 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001661 }
1662 *data = 0;
1663 return mp_obj_str_builder_end(s);
1664}
1665
1666STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001667 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001668}
1669
1670STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001671 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001672}
1673
Damien Georgefcc9cf62014-06-01 18:22:09 +01001674STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001675 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001676
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001677 if (self_len == 0) {
1678 return mp_const_false; // default to False for empty str
1679 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001680
Damien Georgefcc9cf62014-06-01 18:22:09 +01001681 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001682 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001683 if (!f(*self_data++)) {
1684 return mp_const_false;
1685 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001686 }
1687 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001688 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001689
Damien George39dc1452014-10-03 19:52:22 +01001690 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001691 if (unichar_isalpha(*self_data++)) {
1692 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001693 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1694 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001695 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001696 }
1697 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001698
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001699 if (!contains_alpha) {
1700 return mp_const_false;
1701 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001702 }
1703
1704 return mp_const_true;
1705}
1706
1707STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001708 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001709}
1710
1711STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001712 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001713}
1714
1715STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001716 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001717}
1718
1719STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001720 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001721}
1722
1723STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001724 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001725}
1726
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001727#if MICROPY_CPYTHON_COMPAT
1728// These methods are superfluous in the presense of str() and bytes()
1729// constructors.
1730// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001731STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001732 mp_obj_t new_args[2];
1733 if (n_args == 1) {
1734 new_args[0] = args[0];
1735 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1736 args = new_args;
1737 n_args++;
1738 }
1739 return str_make_new(NULL, n_args, 0, args);
1740}
1741
1742// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001743STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001744 mp_obj_t new_args[2];
1745 if (n_args == 1) {
1746 new_args[0] = args[0];
1747 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1748 args = new_args;
1749 n_args++;
1750 }
1751 return bytes_make_new(NULL, n_args, 0, args);
1752}
1753#endif
1754
Damien George4d917232014-08-30 14:28:06 +01001755mp_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 +01001756 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001757 GET_STR_DATA_LEN(self_in, str_data, str_len);
1758 bufinfo->buf = (void*)str_data;
1759 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001760 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001761 return 0;
1762 } else {
1763 // can't write to a string
1764 bufinfo->buf = NULL;
1765 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001766 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001767 return 1;
1768 }
1769}
1770
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001771#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001772MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1773MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001774#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001775MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1776MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1777MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1778MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1779MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1780MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1781MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1782MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1783MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1784MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1785MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1786MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1787MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1788MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1789MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1790MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1791MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1792MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1793MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1794MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1795MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1796MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1797MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1798MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001799
Damien George9b196cd2014-03-26 21:47:19 +00001800STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001801#if MICROPY_CPYTHON_COMPAT
1802 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001803 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1804 // If we have separate unicode type, then here we have methods only
1805 // for bytes type, and it should not have encode() methods. Otherwise,
1806 // we have non-compliant-but-practical bytestring type, which shares
1807 // method table with bytes, so they both have encode() and decode()
1808 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001809 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001810 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001811#endif
Damien George9b196cd2014-03-26 21:47:19 +00001812 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1813 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001814 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1815 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001816 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1817 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001818 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001819 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001820 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001821 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001822 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1823 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001824 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1825 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1826 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1827 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1828 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001829 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1830 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001831 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1832 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1833 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1834 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1835 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001836};
Damien George97209d32014-01-07 15:58:30 +00001837
Damien George9b196cd2014-03-26 21:47:19 +00001838STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1839
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001840#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001841const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001842 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001843 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001844 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001845 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001846 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001847 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001848 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001849 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001850 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001851};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001852#endif
Damiend99b0522013-12-21 18:17:45 +00001853
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001854// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001855const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001856 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001857 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001858 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001859 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001860 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001861 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001862 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001863 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001864 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001865};
1866
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001867// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001868const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001869
Damien Georged182b982014-08-30 14:19:41 +01001870mp_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 +02001871 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001872 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001873 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001874 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001875 byte *p = m_new(byte, len + 1);
1876 o->data = p;
1877 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001878 return o;
1879}
1880
Damien George5fa93b62014-01-22 14:35:10 +00001881mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001882 mp_obj_str_t *o = o_in;
1883 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001884 byte *p = (byte*)o->data;
1885 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001886 return o;
1887}
1888
Damien George5f27a7e2014-07-31 10:29:56 +01001889mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1890 mp_obj_str_t *o = o_in;
1891 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1892 o->len = len;
1893 o->hash = qstr_compute_hash(o->data, o->len);
1894 byte *p = (byte*)o->data;
1895 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1896 return o;
1897}
1898
Damien George4abff752014-08-30 14:59:21 +01001899mp_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 +02001900 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001901 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001902 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001903 if (data) {
1904 o->hash = qstr_compute_hash(data, len);
1905 byte *p = m_new(byte, len + 1);
1906 o->data = p;
1907 memcpy(p, data, len * sizeof(byte));
1908 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1909 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001910 return o;
1911}
1912
Damien Georged182b982014-08-30 14:19:41 +01001913mp_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 +01001914 if (make_qstr_if_not_already) {
1915 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001916 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001917 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001918 qstr q = qstr_find_strn(data, len);
1919 if (q != MP_QSTR_NULL) {
1920 // qstr with this data already exists
1921 return MP_OBJ_NEW_QSTR(q);
1922 } else {
1923 // no existing qstr, don't make one
1924 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1925 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001926 }
Damien George5fa93b62014-01-22 14:35:10 +00001927}
1928
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001929mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1930 GET_STR_DATA_LEN(str, data, len);
1931 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1932}
1933
Damien Georged182b982014-08-30 14:19:41 +01001934mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001935 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001936}
1937
Damien George5fa93b62014-01-22 14:35:10 +00001938bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1939 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1940 return s1 == s2;
1941 } else {
1942 GET_STR_HASH(s1, h1);
1943 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001944 // If any of hashes is 0, it means it's not valid
1945 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001946 return false;
1947 }
1948 GET_STR_DATA_LEN(s1, d1, l1);
1949 GET_STR_DATA_LEN(s2, d2, l2);
1950 if (l1 != l2) {
1951 return false;
1952 }
Damien George1e708fe2014-01-23 18:27:51 +00001953 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001954 }
Damien George5fa93b62014-01-22 14:35:10 +00001955}
1956
Damien Georgedeed0872014-04-06 11:11:15 +01001957STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001958 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1959 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1960 "can't convert to str implicitly"));
1961 } else {
1962 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1963 "can't convert '%s' object to str implicitly",
1964 mp_obj_get_type_str(self_in)));
1965 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001966}
1967
Damien Georged182b982014-08-30 14:19:41 +01001968mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001969 // TODO: This has too big overhead for hash accessor
Damien Georgebe8e99c2014-11-05 16:45:54 +00001970 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001971 GET_STR_HASH(self_in, h);
1972 return h;
1973 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001974 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001975 }
1976}
1977
Damien Georged182b982014-08-30 14:19:41 +01001978mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001979 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001980 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001981 GET_STR_LEN(self_in, l);
1982 return l;
1983 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001984 bad_implicit_conversion(self_in);
1985 }
1986}
1987
1988// use this if you will anyway convert the string to a qstr
1989// will be more efficient for the case where it's already a qstr
1990qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1991 if (MP_OBJ_IS_QSTR(self_in)) {
1992 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001993 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001994 mp_obj_str_t *self = self_in;
1995 return qstr_from_strn((char*)self->data, self->len);
1996 } else {
1997 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001998 }
1999}
2000
2001// only use this function if you need the str data to be zero terminated
2002// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2003const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002004 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002005 GET_STR_DATA_LEN(self_in, s, l);
2006 (void)l; // len unused
2007 return (const char*)s;
2008 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002009 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002010 }
2011}
2012
Damien Georged182b982014-08-30 14:19:41 +01002013const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002014 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002015 GET_STR_DATA_LEN(self_in, s, l);
2016 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002017 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002018 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002019 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002020 }
Damiend99b0522013-12-21 18:17:45 +00002021}
xyb8cfc9f02014-01-05 18:47:51 +08002022
2023/******************************************************************************/
2024/* str iterator */
2025
2026typedef struct _mp_obj_str_it_t {
2027 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002028 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002029 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08002030} mp_obj_str_it_t;
2031
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002032#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002033STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08002034 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002035 GET_STR_DATA_LEN(self->str, str, len);
2036 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002037 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002038 self->cur += 1;
2039 return o_out;
2040 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002041 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002042 }
2043}
2044
Damien George3e1a5c12014-03-29 13:43:38 +00002045STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002046 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002047 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002048 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002049 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002050};
2051
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002052mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2053 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
2054 o->base.type = &mp_type_str_it;
2055 o->str = str;
2056 o->cur = 0;
2057 return o;
2058}
2059#endif
2060
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002061STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002062 mp_obj_str_it_t *self = self_in;
2063 GET_STR_DATA_LEN(self->str, str, len);
2064 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002065 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002066 self->cur += 1;
2067 return o_out;
2068 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002069 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002070 }
2071}
2072
Damien George3e1a5c12014-03-29 13:43:38 +00002073STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002074 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002075 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002076 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002077 .iternext = bytes_it_iternext,
2078};
2079
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002080mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
2081 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002082 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002083 o->str = str;
2084 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002085 return o;
2086}