blob: 5a8e4d1646849c87227a9082522f28bbfa4f43f0 [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
Damiend99b0522013-12-21 18:17:45 +000028#include <string.h>
29#include <assert.h>
30
Damien George51dfcb42015-01-01 20:27:54 +000031#include "py/nlr.h"
32#include "py/unicode.h"
33#include "py/objstr.h"
34#include "py/objlist.h"
35#include "py/runtime0.h"
36#include "py/runtime.h"
37#include "py/pfenv.h"
Damiend99b0522013-12-21 18:17:45 +000038
Damien Georgeecc88e92014-08-30 00:35:11 +010039STATIC 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 +020040
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030041mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020042STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030043STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030044
xyb8cfc9f02014-01-05 18:47:51 +080045/******************************************************************************/
46/* str */
47
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030048void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
Damien Georged182b982014-08-30 14:19:41 +010049 const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020050 // this escapes characters, but it will be very slow to print (calling print many times)
51 bool has_single_quote = false;
52 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100053 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020054 if (*s == '\'') {
55 has_single_quote = true;
56 } else if (*s == '"') {
57 has_double_quote = true;
58 }
59 }
60 int quote_char = '\'';
61 if (has_single_quote && !has_double_quote) {
62 quote_char = '"';
63 }
64 print(env, "%c", quote_char);
65 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
66 if (*s == quote_char) {
67 print(env, "\\%c", quote_char);
68 } else if (*s == '\\') {
69 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030070 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
71 // In strings, anything which is not ascii control character
72 // is printed as is, this includes characters in range 0x80-0xff
73 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020074 print(env, "%c", *s);
75 } else if (*s == '\n') {
76 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010077 } else if (*s == '\r') {
78 print(env, "\\r");
79 } else if (*s == '\t') {
80 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020081 } else {
82 print(env, "\\x%02x", *s);
83 }
84 }
85 print(env, "%c", quote_char);
86}
87
Damien George612045f2014-09-17 22:56:34 +010088#if MICROPY_PY_UJSON
Damien Georgecde0ca22014-09-25 17:35:56 +010089void mp_str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) {
90 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
91 // 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 +010092 print(env, "\"");
93 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +010094 if (*s == '"' || *s == '\\') {
Damien George612045f2014-09-17 22:56:34 +010095 print(env, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +010096 } else if (*s >= 32) {
97 // this will handle normal and utf-8 encoded chars
Damien George612045f2014-09-17 22:56:34 +010098 print(env, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +010099 } else if (*s == '\n') {
100 print(env, "\\n");
101 } else if (*s == '\r') {
102 print(env, "\\r");
103 } else if (*s == '\t') {
104 print(env, "\\t");
105 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100106 // this will handle control chars
Damien George612045f2014-09-17 22:56:34 +0100107 print(env, "\\u%04x", *s);
108 }
109 }
110 print(env, "\"");
111}
112#endif
113
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200114STATIC 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 +0000115 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100116 #if MICROPY_PY_UJSON
117 if (kind == PRINT_JSON) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100118 mp_str_print_json(print, env, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100119 return;
120 }
121 #endif
Damien Georgecde0ca22014-09-25 17:35:56 +0100122 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200123 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000124 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200125 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200126 if (is_bytes) {
127 print(env, "b");
128 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300129 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200130 }
Damiend99b0522013-12-21 18:17:45 +0000131}
132
Damien George6f5eb842014-11-27 16:55:47 +0000133#if !MICROPY_PY_BUILTINS_STR_UNICODE || MICROPY_CPYTHON_COMPAT
Damien Georgeecc88e92014-08-30 00:35:11 +0100134STATIC 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 +0300135#if MICROPY_CPYTHON_COMPAT
136 if (n_kw != 0) {
137 mp_arg_error_unimpl_kw();
138 }
139#endif
140
Damien George1e9a92f2014-11-06 17:36:16 +0000141 mp_arg_check_num(n_args, n_kw, 0, 3, false);
142
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200143 switch (n_args) {
144 case 0:
145 return MP_OBJ_NEW_QSTR(MP_QSTR_);
146
Damien George1e9a92f2014-11-06 17:36:16 +0000147 case 1: {
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200148 vstr_t *vstr = vstr_new();
149 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100150 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200151 vstr_free(vstr);
152 return s;
153 }
154
Damien George1e9a92f2014-11-06 17:36:16 +0000155 default: // 2 or 3 args
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200156 // TODO: validate 2nd/3rd args
Paul Sokolovskye62a0fe2014-10-30 23:58:08 +0200157 if (MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
158 GET_STR_DATA_LEN(args[0], str_data, str_len);
159 GET_STR_HASH(args[0], str_hash);
160 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
161 o->data = str_data;
162 o->hash = str_hash;
163 return o;
164 } else {
165 mp_buffer_info_t bufinfo;
166 mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
167 return mp_obj_new_str(bufinfo.buf, bufinfo.len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200168 }
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200169 }
170}
Damien George6f5eb842014-11-27 16:55:47 +0000171#endif
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200172
Damien Georgeecc88e92014-08-30 00:35:11 +0100173STATIC 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 +0200174 if (n_args == 0) {
175 return mp_const_empty_bytes;
176 }
177
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300178#if MICROPY_CPYTHON_COMPAT
179 if (n_kw != 0) {
180 mp_arg_error_unimpl_kw();
181 }
182#endif
183
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200184 if (MP_OBJ_IS_STR(args[0])) {
185 if (n_args < 2 || n_args > 3) {
186 goto wrong_args;
187 }
188 GET_STR_DATA_LEN(args[0], str_data, str_len);
189 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100190 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200191 o->data = str_data;
192 o->hash = str_hash;
193 return o;
194 }
195
196 if (n_args > 1) {
197 goto wrong_args;
198 }
199
200 if (MP_OBJ_IS_SMALL_INT(args[0])) {
201 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
202 byte *data;
203
Damien George3e1a5c12014-03-29 13:43:38 +0000204 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200205 memset(data, 0, len);
206 return mp_obj_str_builder_end(o);
207 }
208
Damien George32ef3a32014-12-04 15:46:14 +0000209 // check if argument has the buffer protocol
210 mp_buffer_info_t bufinfo;
211 if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
212 return mp_obj_new_str_of_type(&mp_type_bytes, bufinfo.buf, bufinfo.len);
213 }
214
Damien George39dc1452014-10-03 19:52:22 +0100215 mp_int_t len;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200216 byte *data;
217 vstr_t *vstr = NULL;
Damien George3aa09f52014-10-23 12:06:53 +0100218 mp_obj_t o = MP_OBJ_NULL;
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200219 // Try to create array of exact len if initializer len is known
220 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
221 if (len_in == MP_OBJ_NULL) {
222 len = -1;
223 vstr = vstr_new();
224 } else {
225 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000226 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200227 }
228
Damien Georged17926d2014-03-30 13:35:08 +0100229 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200230 mp_obj_t item;
Damien Georgeea8d06c2014-04-17 23:19:36 +0100231 while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200232 if (len == -1) {
233 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
234 } else {
235 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
236 }
237 }
238
239 if (len == -1) {
240 vstr_shrink(vstr);
241 // TODO: Optimize, borrow buffer from vstr
242 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000243 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200244 memcpy(data, vstr_str(vstr), len);
245 vstr_free(vstr);
246 }
247
248 return mp_obj_str_builder_end(o);
249
250wrong_args:
Damien George1e9a92f2014-11-06 17:36:16 +0000251 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200252}
253
Damien George55baff42014-01-21 21:40:13 +0000254// like strstr but with specified length and allows \0 bytes
255// TODO replace with something more efficient/standard
Damien George40f3c022014-07-03 13:25:24 +0100256STATIC 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 +0000257 if (hlen >= nlen) {
Damien George40f3c022014-07-03 13:25:24 +0100258 mp_uint_t str_index, str_index_end;
xbe17a5a832014-03-23 23:31:58 -0700259 if (direction > 0) {
260 str_index = 0;
261 str_index_end = hlen - nlen;
262 } else {
263 str_index = hlen - nlen;
264 str_index_end = 0;
265 }
266 for (;;) {
267 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
268 //found
269 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000270 }
xbe17a5a832014-03-23 23:31:58 -0700271 if (str_index == str_index_end) {
272 //not found
273 break;
Damien George55baff42014-01-21 21:40:13 +0000274 }
xbe17a5a832014-03-23 23:31:58 -0700275 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000276 }
277 }
278 return NULL;
279}
280
Damien Georgea75b02e2014-08-27 09:20:30 +0100281// Note: this function is used to check if an object is a str or bytes, which
282// works because both those types use it as their binary_op method. Revisit
283// MP_OBJ_IS_STR_OR_BYTES if this fact changes.
Damien Georgeecc88e92014-08-30 00:35:11 +0100284mp_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 +0000285 // check for modulo
286 if (op == MP_BINARY_OP_MODULO) {
287 mp_obj_t *args;
288 mp_uint_t n_args;
289 mp_obj_t dict = MP_OBJ_NULL;
290 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
291 // TODO: Support tuple subclasses?
292 mp_obj_tuple_get(rhs_in, &n_args, &args);
293 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
294 args = NULL;
295 n_args = 0;
296 dict = rhs_in;
297 } else {
298 args = &rhs_in;
299 n_args = 1;
300 }
301 return str_modulo_format(lhs_in, n_args, args, dict);
302 }
303
304 // from now on we need lhs type and data, so extract them
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300305 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
Damien Georgea65c03c2014-11-05 16:30:34 +0000306 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
307
308 // check for multiply
309 if (op == MP_BINARY_OP_MULTIPLY) {
310 mp_int_t n;
311 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
312 return MP_OBJ_NULL; // op not supported
313 }
314 if (n <= 0) {
315 if (lhs_type == &mp_type_str) {
316 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
317 } else {
318 return mp_const_empty_bytes;
319 }
320 }
321 byte *data;
322 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
323 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
324 return mp_obj_str_builder_end(s);
325 }
326
327 // From now on all operations allow:
328 // - str with str
329 // - bytes with bytes
330 // - bytes with bytearray
331 // - bytes with array.array
332 // To do this efficiently we use the buffer protocol to extract the raw
333 // data for the rhs, but only if the lhs is a bytes object.
334 //
335 // NOTE: CPython does not allow comparison between bytes ard array.array
336 // (even if the array is of type 'b'), even though it allows addition of
337 // such types. We are not compatible with this (we do allow comparison
338 // of bytes with anything that has the buffer protocol). It would be
339 // easy to "fix" this with a bit of extra logic below, but it costs code
340 // size and execution time so we don't.
341
342 const byte *rhs_data;
343 mp_uint_t rhs_len;
344 if (lhs_type == mp_obj_get_type(rhs_in)) {
345 GET_STR_DATA_LEN(rhs_in, rhs_data_, rhs_len_);
346 rhs_data = rhs_data_;
347 rhs_len = rhs_len_;
348 } else if (lhs_type == &mp_type_bytes) {
349 mp_buffer_info_t bufinfo;
350 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
Damien Georgee233a552015-01-11 21:07:15 +0000351 return MP_OBJ_NULL; // op not supported
Damien Georgea65c03c2014-11-05 16:30:34 +0000352 }
353 rhs_data = bufinfo.buf;
354 rhs_len = bufinfo.len;
355 } else {
356 // incompatible types
Damien Georgea65c03c2014-11-05 16:30:34 +0000357 return MP_OBJ_NULL; // op not supported
358 }
359
Damiend99b0522013-12-21 18:17:45 +0000360 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100361 case MP_BINARY_OP_ADD:
Damien Georgea65c03c2014-11-05 16:30:34 +0000362 case MP_BINARY_OP_INPLACE_ADD: {
363 mp_uint_t alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000364 byte *data;
Damien Georgea65c03c2014-11-05 16:30:34 +0000365 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
366 memcpy(data, lhs_data, lhs_len);
367 memcpy(data + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000368 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200369 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200370
Damien Georgea65c03c2014-11-05 16:30:34 +0000371 case MP_BINARY_OP_IN:
372 /* NOTE `a in b` is `b.__contains__(a)` */
373 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300374
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300375 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
376 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 +0100377 case MP_BINARY_OP_LESS:
378 case MP_BINARY_OP_LESS_EQUAL:
379 case MP_BINARY_OP_MORE:
380 case MP_BINARY_OP_MORE_EQUAL:
Damien Georgea65c03c2014-11-05 16:30:34 +0000381 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
Damiend99b0522013-12-21 18:17:45 +0000382 }
383
Damien George6ac5dce2014-05-21 19:42:43 +0100384 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000385}
386
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300387#if !MICROPY_PY_BUILTINS_STR_UNICODE
388// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100389const 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 +0300390 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100391 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300392 return self_data + index_val;
393}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300394#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300395
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300396// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
397STATIC 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 +0300398 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100399 GET_STR_DATA_LEN(self_in, self_data, self_len);
400 if (value == MP_OBJ_SENTINEL) {
401 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100402#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100403 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300404 mp_bound_slice_t slice;
405 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300406 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100407 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100408 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100409 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100410 }
411#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300412 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100413 // If we have unicode enabled the type will always be bytes, so take the short cut.
414 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300415 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100416 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300417 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100418 }
419 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100420 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100421 }
422}
423
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200424STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700425 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300426 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000427
Damien Georgefe8fb912014-01-02 16:36:09 +0000428 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000429 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000430
431 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100432 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000433 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000434 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000435 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000436 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100437 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
438 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300439 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100440 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
441 }
442 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000443 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000444
445 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100446 mp_uint_t required_len = 0;
447 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300448 if (mp_obj_get_type(seq_items[i]) != self_type) {
449 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
450 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000451 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000452 if (i > 0) {
453 required_len += sep_len;
454 }
Damien George5fa93b62014-01-22 14:35:10 +0000455 GET_STR_LEN(seq_items[i], l);
456 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000457 }
458
459 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000460 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300461 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damien George39dc1452014-10-03 19:52:22 +0100462 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000463 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000464 memcpy(data, sep_str, sep_len);
465 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000466 }
Damien George5fa93b62014-01-22 14:35:10 +0000467 GET_STR_DATA_LEN(seq_items[i], s, l);
468 memcpy(data, s, l);
469 data += l;
Damiend99b0522013-12-21 18:17:45 +0000470 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000471
472 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000473 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000474}
475
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200476#define is_ws(c) ((c) == ' ' || (c) == '\t')
477
Damien Georgeecc88e92014-08-30 00:35:11 +0100478STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300479 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100480 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200481 mp_obj_t sep = mp_const_none;
482 if (n_args > 1) {
483 sep = args[1];
484 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100485 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200486 }
487 }
Damien Georgedeed0872014-04-06 11:11:15 +0100488
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200489 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000490 GET_STR_DATA_LEN(args[0], s, len);
491 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200492
Damien Georgedeed0872014-04-06 11:11:15 +0100493 if (sep == mp_const_none) {
494 // sep not given, so separate on whitespace
495
496 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000497 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100498 while (s < top && splits != 0) {
499 const byte *start = s;
500 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100501 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100502 if (s >= top) {
503 break;
504 }
505 while (s < top && is_ws(*s)) s++;
506 if (splits > 0) {
507 splits--;
508 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200509 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200510
Damien Georgedeed0872014-04-06 11:11:15 +0100511 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100512 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100513 }
514
515 } else {
516 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300517 if (mp_obj_get_type(sep) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000518 bad_implicit_conversion(sep);
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300519 }
Damien Georgedeed0872014-04-06 11:11:15 +0100520
Damien Georged182b982014-08-30 14:19:41 +0100521 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100522 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
523
524 if (sep_len == 0) {
525 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
526 }
527
528 for (;;) {
529 const byte *start = s;
530 for (;;) {
531 if (splits == 0 || s + sep_len > top) {
532 s = top;
533 break;
534 } else if (memcmp(s, sep_str, sep_len) == 0) {
535 break;
536 }
537 s++;
538 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100539 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100540 if (s >= top) {
541 break;
542 }
543 s += sep_len;
544 if (splits > 0) {
545 splits--;
546 }
547 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200548 }
549
550 return res;
551}
552
Damien Georgeecc88e92014-08-30 00:35:11 +0100553STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300554 if (n_args < 3) {
555 // If we don't have split limit, it doesn't matter from which side
556 // we split.
557 return str_split(n_args, args);
558 }
559 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
560 mp_obj_t sep = args[1];
561 GET_STR_DATA_LEN(args[0], s, len);
562
Damien George40f3c022014-07-03 13:25:24 +0100563 mp_int_t splits = mp_obj_get_int(args[2]);
564 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300565 // Preallocate list to the max expected # of elements, as we
566 // will fill it from the end.
567 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100568 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300569
570 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000571 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300572 } else {
Damien Georged182b982014-08-30 14:19:41 +0100573 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300574 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
575
576 if (sep_len == 0) {
577 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
578 }
579
580 const byte *beg = s;
581 const byte *last = s + len;
582 for (;;) {
583 s = last - sep_len;
584 for (;;) {
585 if (splits == 0 || s < beg) {
586 break;
587 } else if (memcmp(s, sep_str, sep_len) == 0) {
588 break;
589 }
590 s--;
591 }
592 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100593 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300594 break;
595 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100596 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 +0300597 last = s;
598 if (splits > 0) {
599 splits--;
600 }
601 }
602 if (idx != 0) {
603 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100604 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100605 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300606 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
607 res->len = used;
608 }
609 }
610
611 return res;
612}
613
Damien Georgeecc88e92014-08-30 00:35:11 +0100614STATIC 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 +0300615 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000616 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +0000617 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
618
619 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +0000620 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000621 bad_implicit_conversion(args[1]);
622 }
John R. Lentone8204912014-01-12 21:53:52 +0000623
Damien George5fa93b62014-01-22 14:35:10 +0000624 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
625 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000626
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300627 const byte *start = haystack;
628 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000629 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300630 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000631 }
632 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300633 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000634 }
635
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300636 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000637 if (p == NULL) {
638 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700639 if (is_index) {
640 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
641 } else {
642 return MP_OBJ_NEW_SMALL_INT(-1);
643 }
Damien George23005372014-01-13 19:39:01 +0000644 } else {
645 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300646 #if MICROPY_PY_BUILTINS_STR_UNICODE
647 if (self_type == &mp_type_str) {
648 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
649 }
650 #endif
xbe17a5a832014-03-23 23:31:58 -0700651 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000652 }
John R. Lentone8204912014-01-12 21:53:52 +0000653}
654
Damien Georgeecc88e92014-08-30 00:35:11 +0100655STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700656 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700657}
658
Damien Georgeecc88e92014-08-30 00:35:11 +0100659STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700660 return str_finder(n_args, args, -1, false);
661}
662
Damien Georgeecc88e92014-08-30 00:35:11 +0100663STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700664 return str_finder(n_args, args, 1, true);
665}
666
Damien Georgeecc88e92014-08-30 00:35:11 +0100667STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700668 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700669}
670
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200671// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100672STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300673 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300674 GET_STR_DATA_LEN(args[0], str, str_len);
675 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300676 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300677 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300678 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300679 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300680 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200681 return mp_const_false;
682 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300683 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200684}
685
Damien Georgeecc88e92014-08-30 00:35:11 +0100686STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300687 GET_STR_DATA_LEN(args[0], str, str_len);
688 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
689 assert(n_args == 2);
690
691 if (suffix_len > str_len) {
692 return mp_const_false;
693 }
694 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
695}
696
Paul Sokolovsky88107842014-04-26 06:20:08 +0300697enum { LSTRIP, RSTRIP, STRIP };
698
Damien Georgeecc88e92014-08-30 00:35:11 +0100699STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800700 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700701 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300702 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000703
704 const byte *chars_to_del;
705 uint chars_to_del_len;
706 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800707
708 if (n_args == 1) {
709 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000710 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800711 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300712 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgec55a4d82014-12-24 20:28:30 +0000713 bad_implicit_conversion(args[1]);
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300714 }
Damien George5fa93b62014-01-22 14:35:10 +0000715 GET_STR_DATA_LEN(args[1], s, l);
716 chars_to_del = s;
717 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800718 }
719
Damien George5fa93b62014-01-22 14:35:10 +0000720 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800721
Damien George40f3c022014-07-03 13:25:24 +0100722 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800723 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100724 mp_uint_t last_good_char_pos = 0;
725 mp_uint_t i = 0;
726 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300727 if (type == RSTRIP) {
728 i = orig_str_len - 1;
729 delta = -1;
730 }
Damien George40f3c022014-07-03 13:25:24 +0100731 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700732 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800733 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300734 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800735 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300736 if (type == LSTRIP) {
737 last_good_char_pos = orig_str_len - 1;
738 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300739 } else if (type == RSTRIP) {
740 first_good_char_pos = 0;
741 last_good_char_pos = i;
742 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300743 }
xbe7b0f39f2014-01-08 14:23:45 -0800744 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300745 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800746 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300747 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800748 }
749
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300750 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000751 // string is all whitespace, return ''
Damien Georgec55a4d82014-12-24 20:28:30 +0000752 if (self_type == &mp_type_str) {
753 return MP_OBJ_NEW_QSTR(MP_QSTR_);
754 } else {
755 return mp_const_empty_bytes;
756 }
xbe7b0f39f2014-01-08 14:23:45 -0800757 }
758
759 assert(last_good_char_pos >= first_good_char_pos);
760 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100761 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300762 if (stripped_len == orig_str_len) {
763 // If nothing was stripped, don't bother to dup original string
764 // TODO: watch out for this case when we'll get to bytearray.strip()
765 assert(first_good_char_pos == 0);
766 return args[0];
767 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100768 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800769}
770
Damien Georgeecc88e92014-08-30 00:35:11 +0100771STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300772 return str_uni_strip(STRIP, n_args, args);
773}
774
Damien Georgeecc88e92014-08-30 00:35:11 +0100775STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300776 return str_uni_strip(LSTRIP, n_args, args);
777}
778
Damien Georgeecc88e92014-08-30 00:35:11 +0100779STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300780 return str_uni_strip(RSTRIP, n_args, args);
781}
782
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700783// Takes an int arg, but only parses unsigned numbers, and only changes
784// *num if at least one digit was parsed.
785static int str_to_int(const char *str, int *num) {
786 const char *s = str;
Damien George81836c22014-12-21 21:07:03 +0000787 if ('0' <= *s && *s <= '9') {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700788 *num = 0;
789 do {
790 *num = *num * 10 + (*s - '0');
791 s++;
792 }
Damien George81836c22014-12-21 21:07:03 +0000793 while ('0' <= *s && *s <= '9');
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700794 }
795 return s - str;
796}
797
798static bool isalignment(char ch) {
799 return ch && strchr("<>=^", ch) != NULL;
800}
801
802static bool istype(char ch) {
803 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
804}
805
806static bool arg_looks_integer(mp_obj_t arg) {
807 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
808}
809
810static bool arg_looks_numeric(mp_obj_t arg) {
811 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100812#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700813 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
814#endif
815 ;
816}
817
Dave Hylandsc4029e52014-04-07 11:19:51 -0700818static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100819#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700820 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Paul Sokolovsky2c756652014-12-31 02:20:57 +0200821 return mp_obj_new_int_from_float(mp_obj_get_float(arg));
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700822 }
823#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700824 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700825}
826
Damien George1e9a92f2014-11-06 17:36:16 +0000827STATIC NORETURN void terse_str_format_value_error(void) {
828 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "bad format string"));
829}
830
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200831mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
Damien Georgebe8e99c2014-11-05 16:45:54 +0000832 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000833
Damien George5fa93b62014-01-22 14:35:10 +0000834 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700835 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000836 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700837 pfenv_t pfenv_vstr;
838 pfenv_vstr.data = vstr;
839 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
840
Damien George5fa93b62014-01-22 14:35:10 +0000841 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700842 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000843 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700844 if (str < top && *str == '}') {
845 vstr_add_char(vstr, '}');
846 continue;
847 }
Damien George1e9a92f2014-11-06 17:36:16 +0000848 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
849 terse_str_format_value_error();
850 } else {
851 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
852 "single '}' encountered in format string"));
853 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700854 }
855 if (*str != '{') {
856 vstr_add_char(vstr, *str);
857 continue;
858 }
859
860 str++;
861 if (str < top && *str == '{') {
862 vstr_add_char(vstr, '{');
863 continue;
864 }
865
866 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
867
868 vstr_t *field_name = NULL;
869 char conversion = '\0';
870 vstr_t *format_spec = NULL;
871
872 if (str < top && *str != '}' && *str != '!' && *str != ':') {
873 field_name = vstr_new();
874 while (str < top && *str != '}' && *str != '!' && *str != ':') {
875 vstr_add_char(field_name, *str++);
876 }
877 vstr_add_char(field_name, '\0');
878 }
879
880 // conversion ::= "r" | "s"
881
882 if (str < top && *str == '!') {
883 str++;
884 if (str < top && (*str == 'r' || *str == 's')) {
885 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200886 } else {
Damien George1e9a92f2014-11-06 17:36:16 +0000887 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
888 terse_str_format_value_error();
889 } else {
890 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
891 "end of format while looking for conversion specifier"));
892 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700893 }
894 }
895
896 if (str < top && *str == ':') {
897 str++;
898 // {:} is the same as {}, which is the same as {!s}
899 // This makes a difference when passing in a True or False
900 // '{}'.format(True) returns 'True'
901 // '{:d}'.format(True) returns '1'
902 // So we treat {:} as {} and this later gets treated to be {!s}
903 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100904 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 while (str < top && *str != '}') {
906 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000907 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700908 vstr_add_char(format_spec, '\0');
909 }
910 }
911 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +0000912 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
913 terse_str_format_value_error();
914 } else {
915 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
916 "unmatched '{' in format"));
917 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700918 }
919 if (*str != '}') {
Damien George1e9a92f2014-11-06 17:36:16 +0000920 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
921 terse_str_format_value_error();
922 } else {
923 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
924 "expected ':' after format specifier"));
925 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700926 }
927
928 mp_obj_t arg = mp_const_none;
929
930 if (field_name) {
Damien George3bb8bd82014-04-14 21:20:30 +0100931 int index = 0;
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200932 const char *field = vstr_str(field_name);
933 const char *lookup = NULL;
934 if (MP_LIKELY(unichar_isdigit(*field))) {
935 if (arg_i > 0) {
936 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
937 terse_str_format_value_error();
938 } else {
939 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
940 "can't switch from automatic field numbering to manual field specification"));
941 }
942 }
Paul Sokolovskyff8e35b2015-01-04 13:23:44 +0200943 lookup = str_to_int(field, &index) + field;
Damien George963a5a32015-01-16 17:47:07 +0000944 if ((uint)index >= n_args - 1) {
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200945 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
946 }
947 arg = args[index + 1];
948 arg_i = -1;
949 } else {
950 for (lookup = field; *lookup && *lookup != '.' && *lookup != '['; lookup++);
951 mp_obj_t field_q = mp_obj_new_str(field, lookup - field, true/*?*/);
952 mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP);
953 if (key_elem == NULL) {
954 nlr_raise(mp_obj_new_exception_arg1(&mp_type_KeyError, field_q));
955 }
956 arg = key_elem->value;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700957 }
Paul Sokolovskyc1144962015-01-04 00:14:13 +0200958 if (*lookup) {
959 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700960 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700961 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 }
Damien George963a5a32015-01-16 17:47:07 +0000972 if ((uint)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;
Damien George0178aa92015-01-12 21:56:35 +00001209 #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
1210 #define F100 100.0F
1211 #else
1212 #define F100 100.0
1213 #endif
1214 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision);
1215 #undef F100
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001216 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001217#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001218
1219 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001220 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1221 terse_str_format_value_error();
1222 } else {
1223 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1224 "unknown format code '%c' for object of type 'float'",
1225 type, mp_obj_get_type_str(arg)));
1226 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001227 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001228 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001229 // arg doesn't look like a number
1230
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001231 if (align == '=') {
Damien George1e9a92f2014-11-06 17:36:16 +00001232 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1233 terse_str_format_value_error();
1234 } else {
1235 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1236 "'=' alignment not allowed in string format specifier"));
1237 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001238 }
Damien George70f33cd2014-04-02 17:06:05 +01001239
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001240 switch (type) {
1241 case '\0':
1242 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1243 break;
1244
Damien Georged182b982014-08-30 14:19:41 +01001245 case 's': {
1246 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001247 const char *s = mp_obj_str_get_data(arg, &len);
1248 if (precision < 0) {
1249 precision = len;
1250 }
Damien George963a5a32015-01-16 17:47:07 +00001251 if (len > (mp_uint_t)precision) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001252 len = precision;
1253 }
1254 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1255 break;
1256 }
1257
1258 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001259 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1260 terse_str_format_value_error();
1261 } else {
1262 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1263 "unknown format code '%c' for object of type 'str'",
1264 type, mp_obj_get_type_str(arg)));
1265 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001266 }
Damiend99b0522013-12-21 18:17:45 +00001267 }
1268 }
1269
Damien George2617eeb2014-05-25 22:27:57 +01001270 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001271 vstr_free(vstr);
1272 return s;
Damiend99b0522013-12-21 18:17:45 +00001273}
1274
Damien Georgeecc88e92014-08-30 00:35:11 +01001275STATIC 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 +00001276 assert(MP_OBJ_IS_STR_OR_BYTES(pattern));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001277
1278 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001279 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001280 int arg_i = 0;
1281 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001282 pfenv_t pfenv_vstr;
1283 pfenv_vstr.data = vstr;
1284 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1285
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001286 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001287 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001288 if (*str != '%') {
1289 vstr_add_char(vstr, *str);
1290 continue;
1291 }
1292 if (++str >= top) {
1293 break;
1294 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001295 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001296 vstr_add_char(vstr, '%');
1297 continue;
1298 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001299
1300 // Dictionary value lookup
1301 if (*str == '(') {
1302 const byte *key = ++str;
1303 while (*str != ')') {
1304 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001305 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1306 terse_str_format_value_error();
1307 } else {
1308 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1309 "incomplete format key"));
1310 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001311 }
1312 ++str;
1313 }
1314 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1315 arg = mp_obj_dict_get(dict, k_obj);
1316 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001317 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001318
Dave Hylands6756a372014-04-02 11:42:39 -07001319 int flags = 0;
1320 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001321 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001322 while (str < top) {
1323 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1324 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1325 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001326 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001327 else if (*str == '0') {
1328 flags |= PF_FLAG_PAD_AFTER_SIGN;
1329 fill = '0';
1330 } else break;
1331 str++;
1332 }
1333 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001334 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001335 if (str < top) {
1336 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001337 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001338 goto not_enough_args;
1339 }
Dave Hylands6756a372014-04-02 11:42:39 -07001340 width = mp_obj_get_int(args[arg_i++]);
1341 str++;
1342 } else {
Damien George81836c22014-12-21 21:07:03 +00001343 str += str_to_int((const char*)str, &width);
Dave Hylands6756a372014-04-02 11:42:39 -07001344 }
1345 }
1346 int prec = -1;
1347 if (str < top && *str == '.') {
1348 if (++str < top) {
1349 if (*str == '*') {
Damien George963a5a32015-01-16 17:47:07 +00001350 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001351 goto not_enough_args;
1352 }
Dave Hylands6756a372014-04-02 11:42:39 -07001353 prec = mp_obj_get_int(args[arg_i++]);
1354 str++;
1355 } else {
1356 prec = 0;
Damien George81836c22014-12-21 21:07:03 +00001357 str += str_to_int((const char*)str, &prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001358 }
1359 }
1360 }
1361
1362 if (str >= top) {
Damien George1e9a92f2014-11-06 17:36:16 +00001363 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1364 terse_str_format_value_error();
1365 } else {
1366 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError,
1367 "incomplete format"));
1368 }
Dave Hylands6756a372014-04-02 11:42:39 -07001369 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001370
1371 // Tuple value lookup
1372 if (arg == MP_OBJ_NULL) {
Damien George963a5a32015-01-16 17:47:07 +00001373 if ((uint)arg_i >= n_args) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001374not_enough_args:
1375 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1376 }
1377 arg = args[arg_i++];
1378 }
Dave Hylands6756a372014-04-02 11:42:39 -07001379 switch (*str) {
1380 case 'c':
1381 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001382 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001383 const char *s = mp_obj_str_get_data(arg, &len);
1384 if (len != 1) {
Damien George1e9a92f2014-11-06 17:36:16 +00001385 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1386 "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001387 }
1388 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001389 } else if (arg_looks_integer(arg)) {
Dave Hylands6756a372014-04-02 11:42:39 -07001390 char ch = mp_obj_get_int(arg);
1391 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
Damien George1e9a92f2014-11-06 17:36:16 +00001392 } else {
1393 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1394 "integer required"));
Dave Hylands6756a372014-04-02 11:42:39 -07001395 }
Damien George11de8392014-06-05 18:57:38 +01001396 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001397
1398 case 'd':
1399 case 'i':
1400 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001401 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001402 break;
1403
Damien Georgefb510b32014-06-01 13:32:54 +01001404#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001405 case 'e':
1406 case 'E':
1407 case 'f':
1408 case 'F':
1409 case 'g':
1410 case 'G':
1411 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1412 break;
1413#endif
1414
1415 case 'o':
1416 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001417 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001418 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001419 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001420 break;
1421
1422 case 'r':
1423 case 's':
1424 {
1425 vstr_t *arg_vstr = vstr_new();
1426 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1427 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1428 uint len = vstr_len(arg_vstr);
1429 if (prec < 0) {
1430 prec = len;
1431 }
Damien George963a5a32015-01-16 17:47:07 +00001432 if (len > (uint)prec) {
Dave Hylands6756a372014-04-02 11:42:39 -07001433 len = prec;
1434 }
1435 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1436 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001437 break;
1438 }
Dave Hylands6756a372014-04-02 11:42:39 -07001439
Dave Hylands6756a372014-04-02 11:42:39 -07001440 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001441 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001442 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001443 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001444
Dave Hylands6756a372014-04-02 11:42:39 -07001445 default:
Damien George1e9a92f2014-11-06 17:36:16 +00001446 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1447 terse_str_format_value_error();
1448 } else {
1449 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1450 "unsupported format character '%c' (0x%x) at index %d",
1451 *str, *str, str - start_str));
1452 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001453 }
1454 }
1455
Damien George963a5a32015-01-16 17:47:07 +00001456 if ((uint)arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001457 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001458 }
1459
Damien George2617eeb2014-05-25 22:27:57 +01001460 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001461 vstr_free(vstr);
1462 return s;
1463}
1464
Damien Georgeecc88e92014-08-30 00:35:11 +01001465STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001466 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001467
Damien George40f3c022014-07-03 13:25:24 +01001468 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001469 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001470 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001471 if (max_rep == 0) {
1472 return args[0];
1473 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001474 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001475 }
xbe480c15a2014-01-30 22:17:30 -08001476 }
Damien George94f68302014-01-31 23:45:12 +00001477
xbe729be9b2014-04-07 14:46:39 -07001478 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001479
Damien Georgeff715422014-04-07 00:39:13 +01001480 // check argument types
1481
Damien Georgec55a4d82014-12-24 20:28:30 +00001482 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
1483
1484 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001485 bad_implicit_conversion(args[1]);
1486 }
1487
Damien Georgec55a4d82014-12-24 20:28:30 +00001488 if (mp_obj_get_type(args[2]) != self_type) {
Damien Georgeff715422014-04-07 00:39:13 +01001489 bad_implicit_conversion(args[2]);
1490 }
1491
1492 // extract string data
1493
xbe480c15a2014-01-30 22:17:30 -08001494 GET_STR_DATA_LEN(args[0], str, str_len);
1495 GET_STR_DATA_LEN(args[1], old, old_len);
1496 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001497
1498 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001499 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001500 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001501 }
1502
Damien George94f68302014-01-31 23:45:12 +00001503 // data for the replaced string
1504 byte *data = NULL;
1505 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001506
Damien George94f68302014-01-31 23:45:12 +00001507 // do 2 passes over the string:
1508 // first pass computes the required length of the replaced string
1509 // second pass does the replacements
1510 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001511 mp_uint_t replaced_str_index = 0;
1512 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001513 const byte *old_occurrence;
1514 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001515 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001516 if (old_len == 0) {
1517 // if old_str is empty, copy new_str to start of replaced string
1518 // copy the replacement string
1519 if (data != NULL) {
1520 memcpy(data, new, new_len);
1521 }
1522 replaced_str_index += new_len;
1523 num_replacements_done++;
1524 }
Damien George963a5a32015-01-16 17:47:07 +00001525 while (num_replacements_done != (mp_uint_t)max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001526 if (old_len == 0) {
1527 old_occurrence += 1;
1528 }
Damien George94f68302014-01-31 23:45:12 +00001529 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1530 if (data != NULL) {
1531 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1532 }
1533 replaced_str_index += old_occurrence - offset_ptr;
1534 // copy the replacement string
1535 if (data != NULL) {
1536 memcpy(data + replaced_str_index, new, new_len);
1537 }
1538 replaced_str_index += new_len;
1539 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001540 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001541 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001542 }
1543
1544 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1545 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001546 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001547 }
Damien Georgeff715422014-04-07 00:39:13 +01001548 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001549
1550 if (data == NULL) {
1551 // first pass
1552 if (num_replacements_done == 0) {
1553 // no substr found, return original string
1554 return args[0];
1555 } else {
1556 // substr found, allocate new string
Damien Georgec55a4d82014-12-24 20:28:30 +00001557 replaced_str = mp_obj_str_builder_start(self_type, replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001558 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001559 }
1560 } else {
1561 // second pass, we are done
1562 break;
1563 }
xbe480c15a2014-01-30 22:17:30 -08001564 }
Damien George94f68302014-01-31 23:45:12 +00001565
xbe480c15a2014-01-30 22:17:30 -08001566 return mp_obj_str_builder_end(replaced_str);
1567}
1568
Damien Georgeecc88e92014-08-30 00:35:11 +01001569STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001570 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001571 assert(2 <= n_args && n_args <= 4);
Damien Georgebe8e99c2014-11-05 16:45:54 +00001572 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
1573
1574 // check argument type
Damien Georgec55a4d82014-12-24 20:28:30 +00001575 if (mp_obj_get_type(args[1]) != self_type) {
Damien Georgebe8e99c2014-11-05 16:45:54 +00001576 bad_implicit_conversion(args[1]);
1577 }
xbe9e1e8cd2014-03-12 22:57:16 -07001578
1579 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1580 GET_STR_DATA_LEN(args[1], needle, needle_len);
1581
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001582 const byte *start = haystack;
1583 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001584 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001585 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001586 }
1587 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001588 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001589 }
1590
Damien George536dde22014-03-13 22:07:55 +00001591 // if needle_len is zero then we count each gap between characters as an occurrence
1592 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001593 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001594 }
1595
Damien George536dde22014-03-13 22:07:55 +00001596 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001597 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001598 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1599 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001600 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001601 haystack_ptr += needle_len;
1602 } else {
1603 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001604 }
xbe9e1e8cd2014-03-12 22:57:16 -07001605 }
1606
1607 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1608}
1609
Damien George40f3c022014-07-03 13:25:24 +01001610STATIC 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 +00001611 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001612 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1613 if (self_type != mp_obj_get_type(arg)) {
Damien Georgec55a4d82014-12-24 20:28:30 +00001614 bad_implicit_conversion(arg);
xbe613a8e32014-03-18 00:06:29 -07001615 }
Damien Georgeb035db32014-03-21 20:39:40 +00001616
xbe613a8e32014-03-18 00:06:29 -07001617 GET_STR_DATA_LEN(self_in, str, str_len);
1618 GET_STR_DATA_LEN(arg, sep, sep_len);
1619
1620 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001621 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001622 }
Damien Georgeb035db32014-03-21 20:39:40 +00001623
Damien Georgec55a4d82014-12-24 20:28:30 +00001624 mp_obj_t result[3];
1625 if (self_type == &mp_type_str) {
1626 result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1627 result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1628 result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_);
1629 } else {
1630 result[0] = mp_const_empty_bytes;
1631 result[1] = mp_const_empty_bytes;
1632 result[2] = mp_const_empty_bytes;
1633 }
Damien Georgeb035db32014-03-21 20:39:40 +00001634
1635 if (direction > 0) {
1636 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001637 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001638 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001639 }
xbe613a8e32014-03-18 00:06:29 -07001640
xbe17a5a832014-03-23 23:31:58 -07001641 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1642 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001643 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001644 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001645 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001646 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 -07001647 }
Damien Georgeb035db32014-03-21 20:39:40 +00001648
xbe0a6894c2014-03-21 01:12:26 -07001649 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001650}
1651
Damien Georgeb035db32014-03-21 20:39:40 +00001652STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1653 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001654}
xbe4504ea82014-03-19 00:46:14 -07001655
Damien Georgeb035db32014-03-21 20:39:40 +00001656STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1657 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001658}
1659
Paul Sokolovsky69135212014-05-10 19:47:41 +03001660// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001661STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001662 GET_STR_DATA_LEN(self_in, self_data, self_len);
1663 byte *data;
1664 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 +01001665 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001666 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001667 }
1668 *data = 0;
1669 return mp_obj_str_builder_end(s);
1670}
1671
1672STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001673 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001674}
1675
1676STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001677 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001678}
1679
Damien Georgefcc9cf62014-06-01 18:22:09 +01001680STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001681 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001682
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001683 if (self_len == 0) {
1684 return mp_const_false; // default to False for empty str
1685 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001686
Damien Georgefcc9cf62014-06-01 18:22:09 +01001687 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001688 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001689 if (!f(*self_data++)) {
1690 return mp_const_false;
1691 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001692 }
1693 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001694 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001695
Damien George39dc1452014-10-03 19:52:22 +01001696 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001697 if (unichar_isalpha(*self_data++)) {
1698 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001699 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1700 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001701 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001702 }
1703 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001704
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001705 if (!contains_alpha) {
1706 return mp_const_false;
1707 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001708 }
1709
1710 return mp_const_true;
1711}
1712
1713STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001714 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001715}
1716
1717STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001718 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001719}
1720
1721STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001722 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001723}
1724
1725STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001726 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001727}
1728
1729STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001730 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001731}
1732
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001733#if MICROPY_CPYTHON_COMPAT
1734// These methods are superfluous in the presense of str() and bytes()
1735// constructors.
1736// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001737STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001738 mp_obj_t new_args[2];
1739 if (n_args == 1) {
1740 new_args[0] = args[0];
1741 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1742 args = new_args;
1743 n_args++;
1744 }
1745 return str_make_new(NULL, n_args, 0, args);
1746}
1747
1748// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001749STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001750 mp_obj_t new_args[2];
1751 if (n_args == 1) {
1752 new_args[0] = args[0];
1753 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1754 args = new_args;
1755 n_args++;
1756 }
1757 return bytes_make_new(NULL, n_args, 0, args);
1758}
1759#endif
1760
Damien George4d917232014-08-30 14:28:06 +01001761mp_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 +01001762 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001763 GET_STR_DATA_LEN(self_in, str_data, str_len);
1764 bufinfo->buf = (void*)str_data;
1765 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001766 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001767 return 0;
1768 } else {
1769 // can't write to a string
1770 bufinfo->buf = NULL;
1771 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001772 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001773 return 1;
1774 }
1775}
1776
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001777#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001778MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1779MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001780#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001781MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1782MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1783MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1784MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1785MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1786MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1787MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1788MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1789MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1790MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1791MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1792MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
Paul Sokolovskyc1144962015-01-04 00:14:13 +02001793MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format);
Paul Sokolovsky97319122014-06-13 22:01:26 +03001794MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1795MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1796MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1797MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1798MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1799MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1800MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1801MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1802MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1803MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1804MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001805
Damien George9b196cd2014-03-26 21:47:19 +00001806STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001807#if MICROPY_CPYTHON_COMPAT
1808 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001809 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1810 // If we have separate unicode type, then here we have methods only
1811 // for bytes type, and it should not have encode() methods. Otherwise,
1812 // we have non-compliant-but-practical bytestring type, which shares
1813 // method table with bytes, so they both have encode() and decode()
1814 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001815 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001816 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001817#endif
Damien George9b196cd2014-03-26 21:47:19 +00001818 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1819 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001820 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1821 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001822 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1823 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001824 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001825 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001826 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001827 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001828 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1829 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001830 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1831 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1832 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1833 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1834 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001835 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1836 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001837 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1838 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1839 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1840 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1841 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001842};
Damien George97209d32014-01-07 15:58:30 +00001843
Damien George9b196cd2014-03-26 21:47:19 +00001844STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1845
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001846#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001847const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001848 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001849 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001850 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001851 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001852 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001853 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001854 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001855 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001856 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001857};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001858#endif
Damiend99b0522013-12-21 18:17:45 +00001859
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001860// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001861const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001862 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001863 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001864 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001865 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001866 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001867 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001868 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001869 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001870 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001871};
1872
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001873// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001874const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001875
Damien Georged182b982014-08-30 14:19:41 +01001876mp_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 +02001877 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001878 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001879 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001880 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001881 byte *p = m_new(byte, len + 1);
1882 o->data = p;
1883 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001884 return o;
1885}
1886
Damien George5fa93b62014-01-22 14:35:10 +00001887mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001888 mp_obj_str_t *o = o_in;
1889 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001890 byte *p = (byte*)o->data;
1891 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001892 return o;
1893}
1894
Damien George5f27a7e2014-07-31 10:29:56 +01001895mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1896 mp_obj_str_t *o = o_in;
1897 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1898 o->len = len;
1899 o->hash = qstr_compute_hash(o->data, o->len);
1900 byte *p = (byte*)o->data;
1901 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1902 return o;
1903}
1904
Damien George4abff752014-08-30 14:59:21 +01001905mp_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 +02001906 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001907 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001908 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001909 if (data) {
1910 o->hash = qstr_compute_hash(data, len);
1911 byte *p = m_new(byte, len + 1);
1912 o->data = p;
1913 memcpy(p, data, len * sizeof(byte));
1914 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1915 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001916 return o;
1917}
1918
Damien Georged182b982014-08-30 14:19:41 +01001919mp_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 +01001920 if (make_qstr_if_not_already) {
1921 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001922 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001923 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001924 qstr q = qstr_find_strn(data, len);
1925 if (q != MP_QSTR_NULL) {
1926 // qstr with this data already exists
1927 return MP_OBJ_NEW_QSTR(q);
1928 } else {
1929 // no existing qstr, don't make one
1930 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1931 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001932 }
Damien George5fa93b62014-01-22 14:35:10 +00001933}
1934
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001935mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1936 GET_STR_DATA_LEN(str, data, len);
1937 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1938}
1939
Damien Georged182b982014-08-30 14:19:41 +01001940mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001941 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001942}
1943
Damien George5fa93b62014-01-22 14:35:10 +00001944bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1945 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1946 return s1 == s2;
1947 } else {
1948 GET_STR_HASH(s1, h1);
1949 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001950 // If any of hashes is 0, it means it's not valid
1951 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001952 return false;
1953 }
1954 GET_STR_DATA_LEN(s1, d1, l1);
1955 GET_STR_DATA_LEN(s2, d2, l2);
1956 if (l1 != l2) {
1957 return false;
1958 }
Damien George1e708fe2014-01-23 18:27:51 +00001959 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001960 }
Damien George5fa93b62014-01-22 14:35:10 +00001961}
1962
Damien Georgedeed0872014-04-06 11:11:15 +01001963STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien George1e9a92f2014-11-06 17:36:16 +00001964 if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
1965 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
1966 "can't convert to str implicitly"));
1967 } else {
1968 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1969 "can't convert '%s' object to str implicitly",
1970 mp_obj_get_type_str(self_in)));
1971 }
Damien Georgeb829b5c2014-01-25 13:51:19 +00001972}
1973
Damien Georged182b982014-08-30 14:19:41 +01001974mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001975 // TODO: This has too big overhead for hash accessor
Damien Georgebe8e99c2014-11-05 16:45:54 +00001976 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001977 GET_STR_HASH(self_in, h);
1978 return h;
1979 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001980 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001981 }
1982}
1983
Damien Georged182b982014-08-30 14:19:41 +01001984mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001985 // TODO This has a double check for the type, one in obj.c and one here
Damien Georgebe8e99c2014-11-05 16:45:54 +00001986 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001987 GET_STR_LEN(self_in, l);
1988 return l;
1989 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001990 bad_implicit_conversion(self_in);
1991 }
1992}
1993
1994// use this if you will anyway convert the string to a qstr
1995// will be more efficient for the case where it's already a qstr
1996qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1997 if (MP_OBJ_IS_QSTR(self_in)) {
1998 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001999 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002000 mp_obj_str_t *self = self_in;
2001 return qstr_from_strn((char*)self->data, self->len);
2002 } else {
2003 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002004 }
2005}
2006
2007// only use this function if you need the str data to be zero terminated
2008// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
2009const char *mp_obj_str_get_str(mp_obj_t self_in) {
Paul Sokolovsky31619cc2014-10-30 16:36:41 +02002010 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002011 GET_STR_DATA_LEN(self_in, s, l);
2012 (void)l; // len unused
2013 return (const char*)s;
2014 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002015 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002016 }
2017}
2018
Damien Georged182b982014-08-30 14:19:41 +01002019const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07002020 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00002021 GET_STR_DATA_LEN(self_in, s, l);
2022 *len = l;
Damien George698ec212014-02-08 18:17:23 +00002023 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00002024 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00002025 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00002026 }
Damiend99b0522013-12-21 18:17:45 +00002027}
xyb8cfc9f02014-01-05 18:47:51 +08002028
2029/******************************************************************************/
2030/* str iterator */
2031
2032typedef struct _mp_obj_str_it_t {
2033 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00002034 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01002035 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08002036} mp_obj_str_it_t;
2037
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002038#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002039STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08002040 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00002041 GET_STR_DATA_LEN(self->str, str, len);
2042 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01002043 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08002044 self->cur += 1;
2045 return o_out;
2046 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002047 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08002048 }
2049}
2050
Damien George3e1a5c12014-03-29 13:43:38 +00002051STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002052 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002053 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002054 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02002055 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08002056};
2057
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03002058mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
2059 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
2060 o->base.type = &mp_type_str_it;
2061 o->str = str;
2062 o->cur = 0;
2063 return o;
2064}
2065#endif
2066
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02002067STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002068 mp_obj_str_it_t *self = self_in;
2069 GET_STR_DATA_LEN(self->str, str, len);
2070 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01002071 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002072 self->cur += 1;
2073 return o_out;
2074 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01002075 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002076 }
2077}
2078
Damien George3e1a5c12014-03-29 13:43:38 +00002079STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00002080 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00002081 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03002082 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002083 .iternext = bytes_it_iternext,
2084};
2085
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002086mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
2087 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00002088 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02002089 o->str = str;
2090 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08002091 return o;
2092}