blob: b008dc6c17c7b5bb9e36f5addeb9e7b2d9a72245 [file] [log] [blame]
Damien George04b91472014-05-03 23:27:38 +01001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
Paul Sokolovskyda9f0922014-05-13 08:44:45 +03007 * Copyright (c) 2014 Paul Sokolovsky
Damien George04b91472014-05-03 23:27:38 +01008 *
9 * Permission is hereby granted, free of charge, to any person obtaining a copy
10 * of this software and associated documentation files (the "Software"), to deal
11 * in the Software without restriction, including without limitation the rights
12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 * copies of the Software, and to permit persons to whom the Software is
14 * furnished to do so, subject to the following conditions:
15 *
16 * The above copyright notice and this permission notice shall be included in
17 * all copies or substantial portions of the Software.
18 *
19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 * THE SOFTWARE.
26 */
27
xbeefe34222014-03-16 00:14:26 -070028#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +000029#include <string.h>
30#include <assert.h>
31
Paul Sokolovskyf54bcbf2014-05-02 17:47:01 +030032#include "mpconfig.h"
Damiend99b0522013-12-21 18:17:45 +000033#include "nlr.h"
34#include "misc.h"
Paul Sokolovsky5048df02014-06-14 03:15:00 +030035#include "unicode.h"
Damien George55baff42014-01-21 21:40:13 +000036#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +000037#include "obj.h"
38#include "runtime0.h"
39#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070040#include "pfenv.h"
Paul Sokolovsky58676fc2014-04-14 01:45:06 +030041#include "objstr.h"
Paul Sokolovsky2a273652014-05-13 08:07:08 +030042#include "objlist.h"
Damiend99b0522013-12-21 18:17:45 +000043
Damien Georgeecc88e92014-08-30 00:35:11 +010044STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020045
Paul Sokolovskyd215ee12014-06-13 22:41:45 +030046mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020047STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskye9085912014-04-30 05:35:18 +030048STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in);
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +030049STATIC NORETURN void arg_type_mixup();
50
xyb8cfc9f02014-01-05 18:47:51 +080051/******************************************************************************/
52/* str */
53
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030054void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env,
Damien Georged182b982014-08-30 14:19:41 +010055 const byte *str_data, mp_uint_t str_len, bool is_bytes) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020056 // this escapes characters, but it will be very slow to print (calling print many times)
57 bool has_single_quote = false;
58 bool has_double_quote = false;
Chris Angelico48674132014-06-04 03:26:40 +100059 for (const byte *s = str_data, *top = str_data + str_len; !has_double_quote && s < top; s++) {
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020060 if (*s == '\'') {
61 has_single_quote = true;
62 } else if (*s == '"') {
63 has_double_quote = true;
64 }
65 }
66 int quote_char = '\'';
67 if (has_single_quote && !has_double_quote) {
68 quote_char = '"';
69 }
70 print(env, "%c", quote_char);
71 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
72 if (*s == quote_char) {
73 print(env, "\\%c", quote_char);
74 } else if (*s == '\\') {
75 print(env, "\\\\");
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +030076 } else if (*s >= 0x20 && *s != 0x7f && (!is_bytes || *s < 0x80)) {
77 // In strings, anything which is not ascii control character
78 // is printed as is, this includes characters in range 0x80-0xff
79 // (which can be non-Latin letters, etc.)
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020080 print(env, "%c", *s);
81 } else if (*s == '\n') {
82 print(env, "\\n");
Andrew Scheller12968fb2014-04-08 02:42:50 +010083 } else if (*s == '\r') {
84 print(env, "\\r");
85 } else if (*s == '\t') {
86 print(env, "\\t");
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020087 } else {
88 print(env, "\\x%02x", *s);
89 }
90 }
91 print(env, "%c", quote_char);
92}
93
Damien George612045f2014-09-17 22:56:34 +010094#if MICROPY_PY_UJSON
Damien Georgecde0ca22014-09-25 17:35:56 +010095void mp_str_print_json(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, mp_uint_t str_len) {
96 // for JSON spec, see http://www.ietf.org/rfc/rfc4627.txt
97 // if we are given a valid utf8-encoded string, we will print it in a JSON-conforming way
Damien George612045f2014-09-17 22:56:34 +010098 print(env, "\"");
99 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100100 if (*s == '"' || *s == '\\') {
Damien George612045f2014-09-17 22:56:34 +0100101 print(env, "\\%c", *s);
Damien Georgecde0ca22014-09-25 17:35:56 +0100102 } else if (*s >= 32) {
103 // this will handle normal and utf-8 encoded chars
Damien George612045f2014-09-17 22:56:34 +0100104 print(env, "%c", *s);
Damien George612045f2014-09-17 22:56:34 +0100105 } else if (*s == '\n') {
106 print(env, "\\n");
107 } else if (*s == '\r') {
108 print(env, "\\r");
109 } else if (*s == '\t') {
110 print(env, "\\t");
111 } else {
Damien Georgecde0ca22014-09-25 17:35:56 +0100112 // this will handle control chars
Damien George612045f2014-09-17 22:56:34 +0100113 print(env, "\\u%04x", *s);
114 }
115 }
116 print(env, "\"");
117}
118#endif
119
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200120STATIC void str_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t self_in, mp_print_kind_t kind) {
Damien George5fa93b62014-01-22 14:35:10 +0000121 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100122 #if MICROPY_PY_UJSON
123 if (kind == PRINT_JSON) {
Damien Georgecde0ca22014-09-25 17:35:56 +0100124 mp_str_print_json(print, env, str_data, str_len);
Damien George612045f2014-09-17 22:56:34 +0100125 return;
126 }
127 #endif
Damien Georgecde0ca22014-09-25 17:35:56 +0100128 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200129 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +0000130 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200131 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200132 if (is_bytes) {
133 print(env, "b");
134 }
Paul Sokolovsky2ec38a12014-06-13 21:23:00 +0300135 mp_str_print_quoted(print, env, str_data, str_len, is_bytes);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +0200136 }
Damiend99b0522013-12-21 18:17:45 +0000137}
138
Damien Georgeecc88e92014-08-30 00:35:11 +0100139STATIC mp_obj_t str_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300140#if MICROPY_CPYTHON_COMPAT
141 if (n_kw != 0) {
142 mp_arg_error_unimpl_kw();
143 }
144#endif
145
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200146 switch (n_args) {
147 case 0:
148 return MP_OBJ_NEW_QSTR(MP_QSTR_);
149
150 case 1:
151 {
152 vstr_t *vstr = vstr_new();
153 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
Damien George2617eeb2014-05-25 22:27:57 +0100154 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200155 vstr_free(vstr);
156 return s;
157 }
158
159 case 2:
160 case 3:
161 {
162 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000163 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Damien Georgeea13f402014-04-05 18:32:08 +0100164 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200165 }
166 GET_STR_DATA_LEN(args[0], str_data, str_len);
167 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100168 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200169 o->data = str_data;
170 o->hash = str_hash;
171 return o;
172 }
173
174 default:
Damien Georgeea13f402014-04-05 18:32:08 +0100175 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200176 }
177}
178
Damien Georgeecc88e92014-08-30 00:35:11 +0100179STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200180 if (n_args == 0) {
181 return mp_const_empty_bytes;
182 }
183
Paul Sokolovskyb473d0a2014-05-06 19:30:30 +0300184#if MICROPY_CPYTHON_COMPAT
185 if (n_kw != 0) {
186 mp_arg_error_unimpl_kw();
187 }
188#endif
189
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200190 if (MP_OBJ_IS_STR(args[0])) {
191 if (n_args < 2 || n_args > 3) {
192 goto wrong_args;
193 }
194 GET_STR_DATA_LEN(args[0], str_data, str_len);
195 GET_STR_HASH(args[0], str_hash);
Damien Georgef600a6a2014-05-25 22:34:34 +0100196 mp_obj_str_t *o = mp_obj_new_str_of_type(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200197 o->data = str_data;
198 o->hash = str_hash;
199 return o;
200 }
201
202 if (n_args > 1) {
203 goto wrong_args;
204 }
205
206 if (MP_OBJ_IS_SMALL_INT(args[0])) {
207 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
208 byte *data;
209
Damien George3e1a5c12014-03-29 13:43:38 +0000210 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200211 memset(data, 0, len);
212 return mp_obj_str_builder_end(o);
213 }
214
Damien 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 Georgeea13f402014-04-05 18:32:08 +0100251 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 George5fa93b62014-01-22 14:35:10 +0000285 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300286 mp_obj_type_t *lhs_type = mp_obj_get_type(lhs_in);
287 mp_obj_type_t *rhs_type = mp_obj_get_type(rhs_in);
Damiend99b0522013-12-21 18:17:45 +0000288 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100289 case MP_BINARY_OP_ADD:
290 case MP_BINARY_OP_INPLACE_ADD:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300291 if (lhs_type == rhs_type) {
292 // add 2 strings or bytes
Damien George5fa93b62014-01-22 14:35:10 +0000293
294 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George39dc1452014-10-03 19:52:22 +0100295 mp_uint_t alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000296
297 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000298 byte *q_ptr;
299 byte *val = qstr_build_start(alloc_len, &q_ptr);
300 memcpy(val, lhs_data, lhs_len);
301 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000302 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
303 */
304
305 // code for non-qstr
306 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300307 mp_obj_t s = mp_obj_str_builder_start(lhs_type, alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000308 memcpy(data, lhs_data, lhs_len);
309 memcpy(data + lhs_len, rhs_data, rhs_len);
310 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000311 }
312 break;
Damien George5fa93b62014-01-22 14:35:10 +0000313
Damien Georged17926d2014-03-30 13:35:08 +0100314 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000315 /* NOTE `a in b` is `b.__contains__(a)` */
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300316 if (lhs_type == rhs_type) {
Damien George5fa93b62014-01-22 14:35:10 +0000317 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700318 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000319 }
320 break;
Damien George5fa93b62014-01-22 14:35:10 +0000321
Damien Georged0a5bf32014-05-10 13:55:11 +0100322 case MP_BINARY_OP_MULTIPLY: {
Damien George9b7a8ee2014-08-13 13:22:24 +0100323 mp_int_t n;
324 if (!mp_obj_get_int_maybe(rhs_in, &n)) {
Damien George6ac5dce2014-05-21 19:42:43 +0100325 return MP_OBJ_NULL; // op not supported
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200326 }
Damien George9b7a8ee2014-08-13 13:22:24 +0100327 if (n <= 0) {
328 if (lhs_type == &mp_type_str) {
329 return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str
330 }
331 n = 0;
332 }
Damien George5fa93b62014-01-22 14:35:10 +0000333 byte *data;
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300334 mp_obj_t s = mp_obj_str_builder_start(lhs_type, lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000335 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
336 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200337 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200338
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300339 case MP_BINARY_OP_MODULO: {
340 mp_obj_t *args;
Damien George9c4cbe22014-08-30 14:04:14 +0100341 mp_uint_t n_args;
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300342 mp_obj_t dict = MP_OBJ_NULL;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300343 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
344 // TODO: Support tuple subclasses?
345 mp_obj_tuple_get(rhs_in, &n_args, &args);
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300346 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_dict)) {
347 args = NULL;
348 n_args = 0;
349 dict = rhs_in;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300350 } else {
351 args = &rhs_in;
352 n_args = 1;
353 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +0300354 return str_modulo_format(lhs_in, n_args, args, dict);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300355 }
356
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300357 //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here
358 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 +0100359 case MP_BINARY_OP_LESS:
360 case MP_BINARY_OP_LESS_EQUAL:
361 case MP_BINARY_OP_MORE:
362 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky7b0f9a72014-05-10 04:26:10 +0300363 if (lhs_type == rhs_type) {
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200364 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
365 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
366 }
Paul Sokolovsky70328e42014-05-15 20:58:40 +0300367 if (lhs_type == &mp_type_bytes) {
368 mp_buffer_info_t bufinfo;
369 if (!mp_get_buffer(rhs_in, &bufinfo, MP_BUFFER_READ)) {
370 goto uncomparable;
371 }
372 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, bufinfo.buf, bufinfo.len));
373 }
374uncomparable:
375 if (op == MP_BINARY_OP_EQUAL) {
376 return mp_const_false;
377 }
Damiend99b0522013-12-21 18:17:45 +0000378 }
379
Damien George6ac5dce2014-05-21 19:42:43 +0100380 return MP_OBJ_NULL; // op not supported
Damiend99b0522013-12-21 18:17:45 +0000381}
382
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300383#if !MICROPY_PY_BUILTINS_STR_UNICODE
384// objstrunicode defines own version
Damien George4abff752014-08-30 14:59:21 +0100385const 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 +0300386 mp_obj_t index, bool is_slice) {
Damien George40f3c022014-07-03 13:25:24 +0100387 mp_uint_t index_val = mp_get_index(type, self_len, index, is_slice);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300388 return self_data + index_val;
389}
Paul Sokolovskyea2c9362014-06-15 00:35:09 +0300390#endif
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300391
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300392// This is used for both bytes and 8-bit strings. This is not used for unicode strings.
393STATIC 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 +0300394 mp_obj_type_t *type = mp_obj_get_type(self_in);
Damien George729f7b42014-04-17 22:10:53 +0100395 GET_STR_DATA_LEN(self_in, self_data, self_len);
396 if (value == MP_OBJ_SENTINEL) {
397 // load
Damien Georgefb510b32014-06-01 13:32:54 +0100398#if MICROPY_PY_BUILTINS_SLICE
Damien George729f7b42014-04-17 22:10:53 +0100399 if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
Paul Sokolovskyde4b9322014-05-25 21:21:57 +0300400 mp_bound_slice_t slice;
401 if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) {
Paul Sokolovsky5fd5af92014-05-25 22:12:56 +0300402 nlr_raise(mp_obj_new_exception_msg(&mp_type_NotImplementedError,
Damien George11de8392014-06-05 18:57:38 +0100403 "only slices with step=1 (aka None) are supported"));
Damien George729f7b42014-04-17 22:10:53 +0100404 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100405 return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start);
Damien George729f7b42014-04-17 22:10:53 +0100406 }
407#endif
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300408 mp_uint_t index_val = mp_get_index(type, self_len, index, false);
Damien George2eb1f602014-08-11 23:24:29 +0100409 // If we have unicode enabled the type will always be bytes, so take the short cut.
410 if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300411 return MP_OBJ_NEW_SMALL_INT(self_data[index_val]);
Damien George729f7b42014-04-17 22:10:53 +0100412 } else {
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +0300413 return mp_obj_new_str((char*)&self_data[index_val], 1, true);
Damien George729f7b42014-04-17 22:10:53 +0100414 }
415 } else {
Damien George6ac5dce2014-05-21 19:42:43 +0100416 return MP_OBJ_NULL; // op not supported
Damien George729f7b42014-04-17 22:10:53 +0100417 }
418}
419
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200420STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700421 assert(MP_OBJ_IS_STR_OR_BYTES(self_in));
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300422 const mp_obj_type_t *self_type = mp_obj_get_type(self_in);
Damiend99b0522013-12-21 18:17:45 +0000423
Damien Georgefe8fb912014-01-02 16:36:09 +0000424 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000425 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000426
427 // process args
Damien George9c4cbe22014-08-30 14:04:14 +0100428 mp_uint_t seq_len;
Damiend99b0522013-12-21 18:17:45 +0000429 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000430 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000431 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000432 } else {
Damien Georgea157e4c2014-04-09 19:17:53 +0100433 if (!MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
434 // arg is not a list, try to convert it to one
Paul Sokolovsky881d9af2014-04-10 01:42:40 +0300435 // TODO: Try to optimize?
Damien Georgea157e4c2014-04-09 19:17:53 +0100436 arg = mp_type_list.make_new((mp_obj_t)&mp_type_list, 1, 0, &arg);
437 }
438 mp_obj_list_get(arg, &seq_len, &seq_items);
Damiend99b0522013-12-21 18:17:45 +0000439 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000440
441 // count required length
Damien George39dc1452014-10-03 19:52:22 +0100442 mp_uint_t required_len = 0;
443 for (mp_uint_t i = 0; i < seq_len; i++) {
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300444 if (mp_obj_get_type(seq_items[i]) != self_type) {
445 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError,
446 "join expects a list of str/bytes objects consistent with self object"));
Damiend99b0522013-12-21 18:17:45 +0000447 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000448 if (i > 0) {
449 required_len += sep_len;
450 }
Damien George5fa93b62014-01-22 14:35:10 +0000451 GET_STR_LEN(seq_items[i], l);
452 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000453 }
454
455 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000456 byte *data;
Paul Sokolovsky5e5d69b2014-05-11 21:13:01 +0300457 mp_obj_t joined_str = mp_obj_str_builder_start(self_type, required_len, &data);
Damien George39dc1452014-10-03 19:52:22 +0100458 for (mp_uint_t i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000459 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000460 memcpy(data, sep_str, sep_len);
461 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000462 }
Damien George5fa93b62014-01-22 14:35:10 +0000463 GET_STR_DATA_LEN(seq_items[i], s, l);
464 memcpy(data, s, l);
465 data += l;
Damiend99b0522013-12-21 18:17:45 +0000466 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000467
468 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000469 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000470}
471
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200472#define is_ws(c) ((c) == ' ' || (c) == '\t')
473
Damien Georgeecc88e92014-08-30 00:35:11 +0100474STATIC mp_obj_t str_split(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskybfb88192014-05-11 21:17:28 +0300475 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George40f3c022014-07-03 13:25:24 +0100476 mp_int_t splits = -1;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200477 mp_obj_t sep = mp_const_none;
478 if (n_args > 1) {
479 sep = args[1];
480 if (n_args > 2) {
Damien Georgedeed0872014-04-06 11:11:15 +0100481 splits = mp_obj_get_int(args[2]);
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200482 }
483 }
Damien Georgedeed0872014-04-06 11:11:15 +0100484
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200485 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000486 GET_STR_DATA_LEN(args[0], s, len);
487 const byte *top = s + len;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200488
Damien Georgedeed0872014-04-06 11:11:15 +0100489 if (sep == mp_const_none) {
490 // sep not given, so separate on whitespace
491
492 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000493 while (s < top && is_ws(*s)) s++;
Damien Georgedeed0872014-04-06 11:11:15 +0100494 while (s < top && splits != 0) {
495 const byte *start = s;
496 while (s < top && !is_ws(*s)) s++;
Damien Georgef600a6a2014-05-25 22:34:34 +0100497 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100498 if (s >= top) {
499 break;
500 }
501 while (s < top && is_ws(*s)) s++;
502 if (splits > 0) {
503 splits--;
504 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200505 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200506
Damien Georgedeed0872014-04-06 11:11:15 +0100507 if (s < top) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100508 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, s, top - s));
Damien Georgedeed0872014-04-06 11:11:15 +0100509 }
510
511 } else {
512 // sep given
Paul Sokolovsky0c549852014-08-10 23:14:35 +0300513 if (mp_obj_get_type(sep) != self_type) {
514 arg_type_mixup();
515 }
Damien Georgedeed0872014-04-06 11:11:15 +0100516
Damien Georged182b982014-08-30 14:19:41 +0100517 mp_uint_t sep_len;
Damien Georgedeed0872014-04-06 11:11:15 +0100518 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
519
520 if (sep_len == 0) {
521 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
522 }
523
524 for (;;) {
525 const byte *start = s;
526 for (;;) {
527 if (splits == 0 || s + sep_len > top) {
528 s = top;
529 break;
530 } else if (memcmp(s, sep_str, sep_len) == 0) {
531 break;
532 }
533 s++;
534 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100535 mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start));
Damien Georgedeed0872014-04-06 11:11:15 +0100536 if (s >= top) {
537 break;
538 }
539 s += sep_len;
540 if (splits > 0) {
541 splits--;
542 }
543 }
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200544 }
545
546 return res;
547}
548
Damien Georgeecc88e92014-08-30 00:35:11 +0100549STATIC mp_obj_t str_rsplit(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300550 if (n_args < 3) {
551 // If we don't have split limit, it doesn't matter from which side
552 // we split.
553 return str_split(n_args, args);
554 }
555 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
556 mp_obj_t sep = args[1];
557 GET_STR_DATA_LEN(args[0], s, len);
558
Damien George40f3c022014-07-03 13:25:24 +0100559 mp_int_t splits = mp_obj_get_int(args[2]);
560 mp_int_t org_splits = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300561 // Preallocate list to the max expected # of elements, as we
562 // will fill it from the end.
563 mp_obj_list_t *res = mp_obj_new_list(splits + 1, NULL);
Damien George39dc1452014-10-03 19:52:22 +0100564 mp_int_t idx = splits;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300565
566 if (sep == mp_const_none) {
Chris Angelico9ab8ab22014-06-04 05:04:23 +1000567 assert(!"TODO: rsplit(None,n) not implemented");
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300568 } else {
Damien Georged182b982014-08-30 14:19:41 +0100569 mp_uint_t sep_len;
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300570 const char *sep_str = mp_obj_str_get_data(sep, &sep_len);
571
572 if (sep_len == 0) {
573 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
574 }
575
576 const byte *beg = s;
577 const byte *last = s + len;
578 for (;;) {
579 s = last - sep_len;
580 for (;;) {
581 if (splits == 0 || s < beg) {
582 break;
583 } else if (memcmp(s, sep_str, sep_len) == 0) {
584 break;
585 }
586 s--;
587 }
588 if (s < beg || splits == 0) {
Damien Georgef600a6a2014-05-25 22:34:34 +0100589 res->items[idx] = mp_obj_new_str_of_type(self_type, beg, last - beg);
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300590 break;
591 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100592 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 +0300593 last = s;
594 if (splits > 0) {
595 splits--;
596 }
597 }
598 if (idx != 0) {
599 // We split less parts than split limit, now go cleanup surplus
Damien George39dc1452014-10-03 19:52:22 +0100600 mp_int_t used = org_splits + 1 - idx;
Damien George17ae2392014-08-29 21:07:54 +0100601 memmove(res->items, &res->items[idx], used * sizeof(mp_obj_t));
Paul Sokolovsky2a273652014-05-13 08:07:08 +0300602 mp_seq_clear(res->items, used, res->alloc, sizeof(*res->items));
603 res->len = used;
604 }
605 }
606
607 return res;
608}
609
Damien Georgeecc88e92014-08-30 00:35:11 +0100610STATIC 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 +0300611 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
John R. Lentone8204912014-01-12 21:53:52 +0000612 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000613 assert(MP_OBJ_IS_STR(args[0]));
614 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000615
Damien George5fa93b62014-01-22 14:35:10 +0000616 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
617 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000618
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300619 const byte *start = haystack;
620 const byte *end = haystack + haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000621 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300622 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000623 }
624 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300625 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000626 }
627
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300628 const byte *p = find_subbytes(start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000629 if (p == NULL) {
630 // not found
xbe3d9a39e2014-04-08 11:42:19 -0700631 if (is_index) {
632 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "substring not found"));
633 } else {
634 return MP_OBJ_NEW_SMALL_INT(-1);
635 }
Damien George23005372014-01-13 19:39:01 +0000636 } else {
637 // found
Paul Sokolovsky5048df02014-06-14 03:15:00 +0300638 #if MICROPY_PY_BUILTINS_STR_UNICODE
639 if (self_type == &mp_type_str) {
640 return MP_OBJ_NEW_SMALL_INT(utf8_ptr_to_index(haystack, p));
641 }
642 #endif
xbe17a5a832014-03-23 23:31:58 -0700643 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000644 }
John R. Lentone8204912014-01-12 21:53:52 +0000645}
646
Damien Georgeecc88e92014-08-30 00:35:11 +0100647STATIC mp_obj_t str_find(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700648 return str_finder(n_args, args, 1, false);
xbe17a5a832014-03-23 23:31:58 -0700649}
650
Damien Georgeecc88e92014-08-30 00:35:11 +0100651STATIC mp_obj_t str_rfind(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700652 return str_finder(n_args, args, -1, false);
653}
654
Damien Georgeecc88e92014-08-30 00:35:11 +0100655STATIC mp_obj_t str_index(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700656 return str_finder(n_args, args, 1, true);
657}
658
Damien Georgeecc88e92014-08-30 00:35:11 +0100659STATIC mp_obj_t str_rindex(mp_uint_t n_args, const mp_obj_t *args) {
xbe3d9a39e2014-04-08 11:42:19 -0700660 return str_finder(n_args, args, -1, true);
xbe17a5a832014-03-23 23:31:58 -0700661}
662
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200663// TODO: (Much) more variety in args
Damien Georgeecc88e92014-08-30 00:35:11 +0100664STATIC mp_obj_t str_startswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300665 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300666 GET_STR_DATA_LEN(args[0], str, str_len);
667 GET_STR_DATA_LEN(args[1], prefix, prefix_len);
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300668 const byte *start = str;
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300669 if (n_args > 2) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300670 start = str_index_to_ptr(self_type, str, str_len, args[2], true);
Paul Sokolovskyc18ef2a2014-05-15 21:18:34 +0300671 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300672 if (prefix_len + (start - str) > str_len) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200673 return mp_const_false;
674 }
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +0300675 return MP_BOOL(memcmp(start, prefix, prefix_len) == 0);
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200676}
677
Damien Georgeecc88e92014-08-30 00:35:11 +0100678STATIC mp_obj_t str_endswith(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +0300679 GET_STR_DATA_LEN(args[0], str, str_len);
680 GET_STR_DATA_LEN(args[1], suffix, suffix_len);
681 assert(n_args == 2);
682
683 if (suffix_len > str_len) {
684 return mp_const_false;
685 }
686 return MP_BOOL(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0);
687}
688
Paul Sokolovsky88107842014-04-26 06:20:08 +0300689enum { LSTRIP, RSTRIP, STRIP };
690
Damien Georgeecc88e92014-08-30 00:35:11 +0100691STATIC mp_obj_t str_uni_strip(int type, mp_uint_t n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800692 assert(1 <= n_args && n_args <= 2);
Dave Hylandsb7f7c652014-08-26 12:44:46 -0700693 assert(MP_OBJ_IS_STR_OR_BYTES(args[0]));
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300694 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
Damien George5fa93b62014-01-22 14:35:10 +0000695
696 const byte *chars_to_del;
697 uint chars_to_del_len;
698 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800699
700 if (n_args == 1) {
701 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000702 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800703 } else {
Paul Sokolovskyb2d4fc02014-05-11 13:17:29 +0300704 if (mp_obj_get_type(args[1]) != self_type) {
705 arg_type_mixup();
706 }
Damien George5fa93b62014-01-22 14:35:10 +0000707 GET_STR_DATA_LEN(args[1], s, l);
708 chars_to_del = s;
709 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800710 }
711
Damien George5fa93b62014-01-22 14:35:10 +0000712 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800713
Damien George40f3c022014-07-03 13:25:24 +0100714 mp_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800715 bool first_good_char_pos_set = false;
Damien George40f3c022014-07-03 13:25:24 +0100716 mp_uint_t last_good_char_pos = 0;
717 mp_uint_t i = 0;
718 mp_int_t delta = 1;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300719 if (type == RSTRIP) {
720 i = orig_str_len - 1;
721 delta = -1;
722 }
Damien George40f3c022014-07-03 13:25:24 +0100723 for (mp_uint_t len = orig_str_len; len > 0; len--) {
xbe17a5a832014-03-23 23:31:58 -0700724 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800725 if (!first_good_char_pos_set) {
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300726 first_good_char_pos_set = true;
xbe7b0f39f2014-01-08 14:23:45 -0800727 first_good_char_pos = i;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300728 if (type == LSTRIP) {
729 last_good_char_pos = orig_str_len - 1;
730 break;
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300731 } else if (type == RSTRIP) {
732 first_good_char_pos = 0;
733 last_good_char_pos = i;
734 break;
Paul Sokolovsky88107842014-04-26 06:20:08 +0300735 }
xbe7b0f39f2014-01-08 14:23:45 -0800736 }
Paul Sokolovsky88107842014-04-26 06:20:08 +0300737 last_good_char_pos = i;
xbe7b0f39f2014-01-08 14:23:45 -0800738 }
Paul Sokolovskye14d0962014-04-26 06:48:31 +0300739 i += delta;
xbe7b0f39f2014-01-08 14:23:45 -0800740 }
741
Paul Sokolovskybcdffe52014-05-30 03:07:05 +0300742 if (!first_good_char_pos_set) {
Damien George5fa93b62014-01-22 14:35:10 +0000743 // string is all whitespace, return ''
744 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800745 }
746
747 assert(last_good_char_pos >= first_good_char_pos);
748 //+1 to accomodate the last character
Damien George40f3c022014-07-03 13:25:24 +0100749 mp_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Paul Sokolovsky88276822014-05-30 03:11:44 +0300750 if (stripped_len == orig_str_len) {
751 // If nothing was stripped, don't bother to dup original string
752 // TODO: watch out for this case when we'll get to bytearray.strip()
753 assert(first_good_char_pos == 0);
754 return args[0];
755 }
Damien Georgef600a6a2014-05-25 22:34:34 +0100756 return mp_obj_new_str_of_type(self_type, orig_str + first_good_char_pos, stripped_len);
xbe7b0f39f2014-01-08 14:23:45 -0800757}
758
Damien Georgeecc88e92014-08-30 00:35:11 +0100759STATIC mp_obj_t str_strip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300760 return str_uni_strip(STRIP, n_args, args);
761}
762
Damien Georgeecc88e92014-08-30 00:35:11 +0100763STATIC mp_obj_t str_lstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300764 return str_uni_strip(LSTRIP, n_args, args);
765}
766
Damien Georgeecc88e92014-08-30 00:35:11 +0100767STATIC mp_obj_t str_rstrip(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky88107842014-04-26 06:20:08 +0300768 return str_uni_strip(RSTRIP, n_args, args);
769}
770
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700771// Takes an int arg, but only parses unsigned numbers, and only changes
772// *num if at least one digit was parsed.
773static int str_to_int(const char *str, int *num) {
774 const char *s = str;
775 if (unichar_isdigit(*s)) {
776 *num = 0;
777 do {
778 *num = *num * 10 + (*s - '0');
779 s++;
780 }
781 while (unichar_isdigit(*s));
782 }
783 return s - str;
784}
785
786static bool isalignment(char ch) {
787 return ch && strchr("<>=^", ch) != NULL;
788}
789
790static bool istype(char ch) {
791 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
792}
793
794static bool arg_looks_integer(mp_obj_t arg) {
795 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
796}
797
798static bool arg_looks_numeric(mp_obj_t arg) {
799 return arg_looks_integer(arg)
Damien Georgefb510b32014-06-01 13:32:54 +0100800#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700801 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
802#endif
803 ;
804}
805
Dave Hylandsc4029e52014-04-07 11:19:51 -0700806static mp_obj_t arg_as_int(mp_obj_t arg) {
Damien Georgefb510b32014-06-01 13:32:54 +0100807#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700808 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Dave Hylandsc4029e52014-04-07 11:19:51 -0700809
810 // TODO: Needs a way to construct an mpz integer from a float
811
Damien George40f3c022014-07-03 13:25:24 +0100812 mp_int_t num = mp_obj_get_float(arg);
Dave Hylandsc4029e52014-04-07 11:19:51 -0700813 return MP_OBJ_NEW_SMALL_INT(num);
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700814 }
815#endif
Dave Hylandsc4029e52014-04-07 11:19:51 -0700816 return arg;
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700817}
818
Damien Georgeecc88e92014-08-30 00:35:11 +0100819mp_obj_t mp_obj_str_format(mp_uint_t n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000820 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000821
Damien George5fa93b62014-01-22 14:35:10 +0000822 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700823 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000824 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700825 pfenv_t pfenv_vstr;
826 pfenv_vstr.data = vstr;
827 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
828
Damien George5fa93b62014-01-22 14:35:10 +0000829 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700830 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000831 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700832 if (str < top && *str == '}') {
833 vstr_add_char(vstr, '}');
834 continue;
835 }
Damien George11de8392014-06-05 18:57:38 +0100836 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "single '}' encountered in format string"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700837 }
838 if (*str != '{') {
839 vstr_add_char(vstr, *str);
840 continue;
841 }
842
843 str++;
844 if (str < top && *str == '{') {
845 vstr_add_char(vstr, '{');
846 continue;
847 }
848
849 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
850
851 vstr_t *field_name = NULL;
852 char conversion = '\0';
853 vstr_t *format_spec = NULL;
854
855 if (str < top && *str != '}' && *str != '!' && *str != ':') {
856 field_name = vstr_new();
857 while (str < top && *str != '}' && *str != '!' && *str != ':') {
858 vstr_add_char(field_name, *str++);
859 }
860 vstr_add_char(field_name, '\0');
861 }
862
863 // conversion ::= "r" | "s"
864
865 if (str < top && *str == '!') {
866 str++;
867 if (str < top && (*str == 'r' || *str == 's')) {
868 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200869 } else {
Damien Georgeea13f402014-04-05 18:32:08 +0100870 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "end of format while looking for conversion specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700871 }
872 }
873
874 if (str < top && *str == ':') {
875 str++;
876 // {:} is the same as {}, which is the same as {!s}
877 // This makes a difference when passing in a True or False
878 // '{}'.format(True) returns 'True'
879 // '{:d}'.format(True) returns '1'
880 // So we treat {:} as {} and this later gets treated to be {!s}
881 if (*str != '}') {
Damien George11de8392014-06-05 18:57:38 +0100882 format_spec = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700883 while (str < top && *str != '}') {
884 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000885 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700886 vstr_add_char(format_spec, '\0');
887 }
888 }
889 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +0100890 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700891 }
892 if (*str != '}') {
Damien Georgeea13f402014-04-05 18:32:08 +0100893 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700894 }
895
896 mp_obj_t arg = mp_const_none;
897
898 if (field_name) {
899 if (arg_i > 0) {
Damien George11de8392014-06-05 18:57:38 +0100900 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from automatic field numbering to manual field specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700901 }
Damien George3bb8bd82014-04-14 21:20:30 +0100902 int index = 0;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700903 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100904 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700905 }
906 if (index >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100907 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700908 }
909 arg = args[index + 1];
910 arg_i = -1;
911 vstr_free(field_name);
912 field_name = NULL;
913 } else {
914 if (arg_i < 0) {
Damien George11de8392014-06-05 18:57:38 +0100915 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "can't switch from manual field specification to automatic field numbering"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700916 }
917 if (arg_i >= n_args - 1) {
Damien Georgeea13f402014-04-05 18:32:08 +0100918 nlr_raise(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700919 }
920 arg = args[arg_i + 1];
921 arg_i++;
922 }
923 if (!format_spec && !conversion) {
924 conversion = 's';
925 }
926 if (conversion) {
927 mp_print_kind_t print_kind;
928 if (conversion == 's') {
929 print_kind = PRINT_STR;
930 } else if (conversion == 'r') {
931 print_kind = PRINT_REPR;
932 } else {
Damien George11de8392014-06-05 18:57:38 +0100933 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "unknown conversion specifier %c", conversion));
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700934 }
935 vstr_t *arg_vstr = vstr_new();
936 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
Damien George2617eeb2014-05-25 22:27:57 +0100937 arg = mp_obj_new_str(vstr_str(arg_vstr), vstr_len(arg_vstr), false);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700938 vstr_free(arg_vstr);
939 }
940
941 char sign = '\0';
942 char fill = '\0';
943 char align = '\0';
944 int width = -1;
945 int precision = -1;
946 char type = '\0';
947 int flags = 0;
948
949 if (format_spec) {
950 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
951 //
952 // [[fill]align][sign][#][0][width][,][.precision][type]
953 // fill ::= <any character>
954 // align ::= "<" | ">" | "=" | "^"
955 // sign ::= "+" | "-" | " "
956 // width ::= integer
957 // precision ::= integer
958 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
959
960 const char *s = vstr_str(format_spec);
961 if (isalignment(*s)) {
962 align = *s++;
963 } else if (*s && isalignment(s[1])) {
964 fill = *s++;
965 align = *s++;
966 }
967 if (*s == '+' || *s == '-' || *s == ' ') {
968 if (*s == '+') {
969 flags |= PF_FLAG_SHOW_SIGN;
970 } else if (*s == ' ') {
971 flags |= PF_FLAG_SPACE_SIGN;
972 }
973 sign = *s++;
974 }
975 if (*s == '#') {
976 flags |= PF_FLAG_SHOW_PREFIX;
977 s++;
978 }
979 if (*s == '0') {
980 if (!align) {
981 align = '=';
982 }
983 if (!fill) {
984 fill = '0';
985 }
986 }
987 s += str_to_int(s, &width);
988 if (*s == ',') {
989 flags |= PF_FLAG_SHOW_COMMA;
990 s++;
991 }
992 if (*s == '.') {
993 s++;
994 s += str_to_int(s, &precision);
995 }
996 if (istype(*s)) {
997 type = *s++;
998 }
999 if (*s) {
Damien Georgeea13f402014-04-05 18:32:08 +01001000 nlr_raise(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001001 }
1002 vstr_free(format_spec);
1003 format_spec = NULL;
1004 }
1005 if (!align) {
1006 if (arg_looks_numeric(arg)) {
1007 align = '>';
1008 } else {
1009 align = '<';
1010 }
1011 }
1012 if (!fill) {
1013 fill = ' ';
1014 }
1015
1016 if (sign) {
1017 if (type == 's') {
Damien Georgeea13f402014-04-05 18:32:08 +01001018 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001019 }
1020 if (type == 'c') {
Damien Georgeea13f402014-04-05 18:32:08 +01001021 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +00001022 }
1023 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001024 sign = '-';
1025 }
1026
1027 switch (align) {
1028 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
1029 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
1030 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
1031 }
1032
1033 if (arg_looks_integer(arg)) {
1034 switch (type) {
1035 case 'b':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001036 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 2, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001037 continue;
1038
1039 case 'c':
1040 {
1041 char ch = mp_obj_get_int(arg);
1042 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
1043 continue;
1044 }
1045
1046 case '\0': // No explicit format type implies 'd'
1047 case 'n': // I don't think we support locales in uPy so use 'd'
1048 case 'd':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001049 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 10, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001050 continue;
1051
1052 case 'o':
Dave Hylandsc4029e52014-04-07 11:19:51 -07001053 if (flags & PF_FLAG_SHOW_PREFIX) {
1054 flags |= PF_FLAG_SHOW_OCTAL_LETTER;
1055 }
1056
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001057 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001058 continue;
1059
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001060 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001061 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001062 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, type - ('X' - 'A'), flags, fill, width, 0);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001063 continue;
1064
1065 case 'e':
1066 case 'E':
1067 case 'f':
1068 case 'F':
1069 case 'g':
1070 case 'G':
1071 case '%':
1072 // The floating point formatters all work with anything that
1073 // looks like an integer
1074 break;
1075
1076 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001077 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001078 "unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001079 }
Damien Georgec322c5f2014-04-02 20:04:15 +01001080 }
Damien George70f33cd2014-04-02 17:06:05 +01001081
Dave Hylands22fe4d72014-04-02 12:07:31 -07001082 // NOTE: no else here. We need the e, f, g etc formats for integer
1083 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +01001084 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001085 if (!type) {
1086
1087 // Even though the docs say that an unspecified type is the same
1088 // as 'g', there is one subtle difference, when the exponent
1089 // is one less than the precision.
Damien George11de8392014-06-05 18:57:38 +01001090 //
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001091 // '{:10.1}'.format(0.0) ==> '0e+00'
1092 // '{:10.1g}'.format(0.0) ==> '0'
1093 //
1094 // TODO: Figure out how to deal with this.
1095 //
1096 // A proper solution would involve adding a special flag
1097 // or something to format_float, and create a format_double
1098 // to deal with doubles. In order to fix this when using
1099 // sprintf, we'd need to use the e format and tweak the
1100 // returned result to strip trailing zeros like the g format
1101 // does.
1102 //
1103 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
1104 // but with 1.e2 you get 1e+02 and 1.00e+02
1105 //
1106 // Stripping the trailing 0's (like g) does would make the
1107 // e format give us the right format.
1108 //
1109 // CPython sources say:
1110 // Omitted type specifier. Behaves in the same way as repr(x)
1111 // and str(x) if no precision is given, else like 'g', but with
1112 // at least one digit after the decimal point. */
1113
1114 type = 'g';
1115 }
1116 if (type == 'n') {
1117 type = 'g';
1118 }
1119
1120 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
1121 switch (type) {
Damien Georgefb510b32014-06-01 13:32:54 +01001122#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001123 case 'e':
1124 case 'E':
1125 case 'f':
1126 case 'F':
1127 case 'g':
1128 case 'G':
Damien George11de8392014-06-05 18:57:38 +01001129 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001130 break;
1131
1132 case '%':
1133 flags |= PF_FLAG_ADD_PERCENT;
1134 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
1135 break;
Damien Georgec322c5f2014-04-02 20:04:15 +01001136#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001137
1138 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001139 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001140 "unknown format code '%c' for object of type 'float'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001141 type, mp_obj_get_type_str(arg)));
1142 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001143 } else {
Damien George70f33cd2014-04-02 17:06:05 +01001144 // arg doesn't look like a number
1145
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001146 if (align == '=') {
Damien Georgeea13f402014-04-05 18:32:08 +01001147 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001148 }
Damien George70f33cd2014-04-02 17:06:05 +01001149
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001150 switch (type) {
1151 case '\0':
1152 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
1153 break;
1154
Damien Georged182b982014-08-30 14:19:41 +01001155 case 's': {
1156 mp_uint_t len;
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001157 const char *s = mp_obj_str_get_data(arg, &len);
1158 if (precision < 0) {
1159 precision = len;
1160 }
1161 if (len > precision) {
1162 len = precision;
1163 }
1164 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
1165 break;
1166 }
1167
1168 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001169 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Damien George11de8392014-06-05 18:57:38 +01001170 "unknown format code '%c' for object of type 'str'",
Dave Hylandsbaf6f142014-03-30 21:06:50 -07001171 type, mp_obj_get_type_str(arg)));
1172 }
Damiend99b0522013-12-21 18:17:45 +00001173 }
1174 }
1175
Damien George2617eeb2014-05-25 22:27:57 +01001176 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Damien George5fa93b62014-01-22 14:35:10 +00001177 vstr_free(vstr);
1178 return s;
Damiend99b0522013-12-21 18:17:45 +00001179}
1180
Damien Georgeecc88e92014-08-30 00:35:11 +01001181STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, mp_uint_t n_args, const mp_obj_t *args, mp_obj_t dict) {
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001182 assert(MP_OBJ_IS_STR(pattern));
1183
1184 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -07001185 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001186 int arg_i = 0;
1187 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -07001188 pfenv_t pfenv_vstr;
1189 pfenv_vstr.data = vstr;
1190 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
1191
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001192 for (const byte *top = str + len; str < top; str++) {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001193 mp_obj_t arg = MP_OBJ_NULL;
Dave Hylands6756a372014-04-02 11:42:39 -07001194 if (*str != '%') {
1195 vstr_add_char(vstr, *str);
1196 continue;
1197 }
1198 if (++str >= top) {
1199 break;
1200 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001201 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -07001202 vstr_add_char(vstr, '%');
1203 continue;
1204 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001205
1206 // Dictionary value lookup
1207 if (*str == '(') {
1208 const byte *key = ++str;
1209 while (*str != ')') {
1210 if (str >= top) {
1211 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format key"));
1212 }
1213 ++str;
1214 }
1215 mp_obj_t k_obj = mp_obj_new_str((const char*)key, str - key, true);
1216 arg = mp_obj_dict_get(dict, k_obj);
1217 str++;
Dave Hylands6756a372014-04-02 11:42:39 -07001218 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001219
Dave Hylands6756a372014-04-02 11:42:39 -07001220 int flags = 0;
1221 char fill = ' ';
Damien George11de8392014-06-05 18:57:38 +01001222 int alt = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001223 while (str < top) {
1224 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
1225 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
1226 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
Damien George11de8392014-06-05 18:57:38 +01001227 else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX;
Dave Hylands6756a372014-04-02 11:42:39 -07001228 else if (*str == '0') {
1229 flags |= PF_FLAG_PAD_AFTER_SIGN;
1230 fill = '0';
1231 } else break;
1232 str++;
1233 }
1234 // parse width, if it exists
Damien George11de8392014-06-05 18:57:38 +01001235 int width = 0;
Dave Hylands6756a372014-04-02 11:42:39 -07001236 if (str < top) {
1237 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001238 if (arg_i >= n_args) {
1239 goto not_enough_args;
1240 }
Dave Hylands6756a372014-04-02 11:42:39 -07001241 width = mp_obj_get_int(args[arg_i++]);
1242 str++;
1243 } else {
1244 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1245 width = width * 10 + *str - '0';
1246 }
1247 }
1248 }
1249 int prec = -1;
1250 if (str < top && *str == '.') {
1251 if (++str < top) {
1252 if (*str == '*') {
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001253 if (arg_i >= n_args) {
1254 goto not_enough_args;
1255 }
Dave Hylands6756a372014-04-02 11:42:39 -07001256 prec = mp_obj_get_int(args[arg_i++]);
1257 str++;
1258 } else {
1259 prec = 0;
1260 for (; str < top && '0' <= *str && *str <= '9'; str++) {
1261 prec = prec * 10 + *str - '0';
1262 }
1263 }
1264 }
1265 }
1266
1267 if (str >= top) {
Damien Georgeea13f402014-04-05 18:32:08 +01001268 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
Dave Hylands6756a372014-04-02 11:42:39 -07001269 }
Paul Sokolovsky75ce9252014-06-05 20:02:15 +03001270
1271 // Tuple value lookup
1272 if (arg == MP_OBJ_NULL) {
1273 if (arg_i >= n_args) {
1274not_enough_args:
1275 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
1276 }
1277 arg = args[arg_i++];
1278 }
Dave Hylands6756a372014-04-02 11:42:39 -07001279 switch (*str) {
1280 case 'c':
1281 if (MP_OBJ_IS_STR(arg)) {
Damien Georged182b982014-08-30 14:19:41 +01001282 mp_uint_t len;
Dave Hylands6756a372014-04-02 11:42:39 -07001283 const char *s = mp_obj_str_get_data(arg, &len);
1284 if (len != 1) {
Damien George11de8392014-06-05 18:57:38 +01001285 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "%%c requires int or char"));
Dave Hylands6756a372014-04-02 11:42:39 -07001286 break;
1287 }
1288 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
1289 break;
1290 }
1291 if (arg_looks_integer(arg)) {
1292 char ch = mp_obj_get_int(arg);
1293 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
1294 break;
1295 }
Damien Georgefb510b32014-06-01 13:32:54 +01001296#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001297 // This is what CPython reports, so we report the same.
1298 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
Damien George11de8392014-06-05 18:57:38 +01001299 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
Dave Hylands6756a372014-04-02 11:42:39 -07001300
1301 }
1302#endif
Damien George11de8392014-06-05 18:57:38 +01001303 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
1304 break;
Dave Hylands6756a372014-04-02 11:42:39 -07001305
1306 case 'd':
1307 case 'i':
1308 case 'u':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001309 pfenv_print_mp_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001310 break;
1311
Damien Georgefb510b32014-06-01 13:32:54 +01001312#if MICROPY_PY_BUILTINS_FLOAT
Dave Hylands6756a372014-04-02 11:42:39 -07001313 case 'e':
1314 case 'E':
1315 case 'f':
1316 case 'F':
1317 case 'g':
1318 case 'G':
1319 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1320 break;
1321#endif
1322
1323 case 'o':
1324 if (alt) {
Dave Hylandsc4029e52014-04-07 11:19:51 -07001325 flags |= (PF_FLAG_SHOW_PREFIX | PF_FLAG_SHOW_OCTAL_LETTER);
Dave Hylands6756a372014-04-02 11:42:39 -07001326 }
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001327 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 8, 'a', flags, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001328 break;
1329
1330 case 'r':
1331 case 's':
1332 {
1333 vstr_t *arg_vstr = vstr_new();
1334 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1335 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1336 uint len = vstr_len(arg_vstr);
1337 if (prec < 0) {
1338 prec = len;
1339 }
1340 if (len > prec) {
1341 len = prec;
1342 }
1343 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1344 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001345 break;
1346 }
Dave Hylands6756a372014-04-02 11:42:39 -07001347
Dave Hylands6756a372014-04-02 11:42:39 -07001348 case 'X':
Damien George11de8392014-06-05 18:57:38 +01001349 case 'x':
Dave Hylandsb69f9fa2014-06-05 23:09:02 -07001350 pfenv_print_mp_int(&pfenv_vstr, arg, 1, 16, *str - ('X' - 'A'), flags | alt, fill, width, prec);
Dave Hylands6756a372014-04-02 11:42:39 -07001351 break;
Damien Georgedeed0872014-04-06 11:11:15 +01001352
Dave Hylands6756a372014-04-02 11:42:39 -07001353 default:
Damien Georgeea13f402014-04-05 18:32:08 +01001354 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
Dave Hylands6756a372014-04-02 11:42:39 -07001355 "unsupported format character '%c' (0x%x) at index %d",
1356 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001357 }
1358 }
1359
1360 if (arg_i != n_args) {
Damien Georgeea13f402014-04-05 18:32:08 +01001361 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001362 }
1363
Damien George2617eeb2014-05-25 22:27:57 +01001364 mp_obj_t s = mp_obj_new_str(vstr->buf, vstr->len, false);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001365 vstr_free(vstr);
1366 return s;
1367}
1368
Damien Georgeecc88e92014-08-30 00:35:11 +01001369STATIC mp_obj_t str_replace(mp_uint_t n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001370 assert(MP_OBJ_IS_STR(args[0]));
xbe480c15a2014-01-30 22:17:30 -08001371
Damien George40f3c022014-07-03 13:25:24 +01001372 mp_int_t max_rep = -1;
xbe480c15a2014-01-30 22:17:30 -08001373 if (n_args == 4) {
Damien Georgeff715422014-04-07 00:39:13 +01001374 max_rep = mp_obj_get_int(args[3]);
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001375 if (max_rep == 0) {
1376 return args[0];
1377 } else if (max_rep < 0) {
Damien Georgeff715422014-04-07 00:39:13 +01001378 max_rep = -1;
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001379 }
xbe480c15a2014-01-30 22:17:30 -08001380 }
Damien George94f68302014-01-31 23:45:12 +00001381
xbe729be9b2014-04-07 14:46:39 -07001382 // if max_rep is still -1 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001383
Damien Georgeff715422014-04-07 00:39:13 +01001384 // check argument types
1385
1386 if (!MP_OBJ_IS_STR(args[1])) {
1387 bad_implicit_conversion(args[1]);
1388 }
1389
1390 if (!MP_OBJ_IS_STR(args[2])) {
1391 bad_implicit_conversion(args[2]);
1392 }
1393
1394 // extract string data
1395
xbe480c15a2014-01-30 22:17:30 -08001396 GET_STR_DATA_LEN(args[0], str, str_len);
1397 GET_STR_DATA_LEN(args[1], old, old_len);
1398 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001399
1400 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001401 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001402 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001403 }
1404
Damien George94f68302014-01-31 23:45:12 +00001405 // data for the replaced string
1406 byte *data = NULL;
1407 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001408
Damien George94f68302014-01-31 23:45:12 +00001409 // do 2 passes over the string:
1410 // first pass computes the required length of the replaced string
1411 // second pass does the replacements
1412 for (;;) {
Damien George40f3c022014-07-03 13:25:24 +01001413 mp_uint_t replaced_str_index = 0;
1414 mp_uint_t num_replacements_done = 0;
Damien George94f68302014-01-31 23:45:12 +00001415 const byte *old_occurrence;
1416 const byte *offset_ptr = str;
Damien George40f3c022014-07-03 13:25:24 +01001417 mp_uint_t str_len_remain = str_len;
Damien Georgeff715422014-04-07 00:39:13 +01001418 if (old_len == 0) {
1419 // if old_str is empty, copy new_str to start of replaced string
1420 // copy the replacement string
1421 if (data != NULL) {
1422 memcpy(data, new, new_len);
1423 }
1424 replaced_str_index += new_len;
1425 num_replacements_done++;
1426 }
1427 while (num_replacements_done != max_rep && str_len_remain > 0 && (old_occurrence = find_subbytes(offset_ptr, str_len_remain, old, old_len, 1)) != NULL) {
1428 if (old_len == 0) {
1429 old_occurrence += 1;
1430 }
Damien George94f68302014-01-31 23:45:12 +00001431 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1432 if (data != NULL) {
1433 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1434 }
1435 replaced_str_index += old_occurrence - offset_ptr;
1436 // copy the replacement string
1437 if (data != NULL) {
1438 memcpy(data + replaced_str_index, new, new_len);
1439 }
1440 replaced_str_index += new_len;
1441 offset_ptr = old_occurrence + old_len;
Damien Georgeff715422014-04-07 00:39:13 +01001442 str_len_remain = str + str_len - offset_ptr;
Damien George94f68302014-01-31 23:45:12 +00001443 num_replacements_done++;
Damien George94f68302014-01-31 23:45:12 +00001444 }
1445
1446 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1447 if (data != NULL) {
Damien Georgeff715422014-04-07 00:39:13 +01001448 memcpy(data + replaced_str_index, offset_ptr, str_len_remain);
Damien George94f68302014-01-31 23:45:12 +00001449 }
Damien Georgeff715422014-04-07 00:39:13 +01001450 replaced_str_index += str_len_remain;
Damien George94f68302014-01-31 23:45:12 +00001451
1452 if (data == NULL) {
1453 // first pass
1454 if (num_replacements_done == 0) {
1455 // no substr found, return original string
1456 return args[0];
1457 } else {
1458 // substr found, allocate new string
1459 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
Damien Georgeff715422014-04-07 00:39:13 +01001460 assert(data != NULL);
Damien George94f68302014-01-31 23:45:12 +00001461 }
1462 } else {
1463 // second pass, we are done
1464 break;
1465 }
xbe480c15a2014-01-30 22:17:30 -08001466 }
Damien George94f68302014-01-31 23:45:12 +00001467
xbe480c15a2014-01-30 22:17:30 -08001468 return mp_obj_str_builder_end(replaced_str);
1469}
1470
Damien Georgeecc88e92014-08-30 00:35:11 +01001471STATIC mp_obj_t str_count(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001472 const mp_obj_type_t *self_type = mp_obj_get_type(args[0]);
xbe9e1e8cd2014-03-12 22:57:16 -07001473 assert(2 <= n_args && n_args <= 4);
1474 assert(MP_OBJ_IS_STR(args[0]));
1475 assert(MP_OBJ_IS_STR(args[1]));
1476
1477 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1478 GET_STR_DATA_LEN(args[1], needle, needle_len);
1479
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001480 const byte *start = haystack;
1481 const byte *end = haystack + haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001482 if (n_args >= 3 && args[2] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001483 start = str_index_to_ptr(self_type, haystack, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001484 }
1485 if (n_args >= 4 && args[3] != mp_const_none) {
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001486 end = str_index_to_ptr(self_type, haystack, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001487 }
1488
Damien George536dde22014-03-13 22:07:55 +00001489 // if needle_len is zero then we count each gap between characters as an occurrence
1490 if (needle_len == 0) {
Paul Sokolovsky9e215fa2014-06-28 23:14:30 +03001491 return MP_OBJ_NEW_SMALL_INT(unichar_charlen((const char*)start, end - start) + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001492 }
1493
Damien George536dde22014-03-13 22:07:55 +00001494 // count the occurrences
Damien George40f3c022014-07-03 13:25:24 +01001495 mp_int_t num_occurrences = 0;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001496 for (const byte *haystack_ptr = start; haystack_ptr + needle_len <= end;) {
1497 if (memcmp(haystack_ptr, needle, needle_len) == 0) {
xbec5d70ba2014-03-13 00:29:15 -07001498 num_occurrences++;
Paul Sokolovskye3cfc0d2014-06-14 06:06:36 +03001499 haystack_ptr += needle_len;
1500 } else {
1501 haystack_ptr = utf8_next_char(haystack_ptr);
xbec5d70ba2014-03-13 00:29:15 -07001502 }
xbe9e1e8cd2014-03-12 22:57:16 -07001503 }
1504
1505 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1506}
1507
Damien George40f3c022014-07-03 13:25:24 +01001508STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, mp_int_t direction) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001509 if (!MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001510 assert(0);
1511 }
1512 mp_obj_type_t *self_type = mp_obj_get_type(self_in);
1513 if (self_type != mp_obj_get_type(arg)) {
1514 arg_type_mixup();
xbe613a8e32014-03-18 00:06:29 -07001515 }
Damien Georgeb035db32014-03-21 20:39:40 +00001516
xbe613a8e32014-03-18 00:06:29 -07001517 GET_STR_DATA_LEN(self_in, str, str_len);
1518 GET_STR_DATA_LEN(arg, sep, sep_len);
1519
1520 if (sep_len == 0) {
Damien Georgeea13f402014-04-05 18:32:08 +01001521 nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
xbe613a8e32014-03-18 00:06:29 -07001522 }
Damien Georgeb035db32014-03-21 20:39:40 +00001523
1524 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1525
1526 if (direction > 0) {
1527 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001528 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001529 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001530 }
xbe613a8e32014-03-18 00:06:29 -07001531
xbe17a5a832014-03-23 23:31:58 -07001532 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1533 if (position_ptr != NULL) {
Damien George40f3c022014-07-03 13:25:24 +01001534 mp_uint_t position = position_ptr - str;
Damien Georgef600a6a2014-05-25 22:34:34 +01001535 result[0] = mp_obj_new_str_of_type(self_type, str, position);
xbe17a5a832014-03-23 23:31:58 -07001536 result[1] = arg;
Damien Georgef600a6a2014-05-25 22:34:34 +01001537 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 -07001538 }
Damien Georgeb035db32014-03-21 20:39:40 +00001539
xbe0a6894c2014-03-21 01:12:26 -07001540 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001541}
1542
Damien Georgeb035db32014-03-21 20:39:40 +00001543STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1544 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001545}
xbe4504ea82014-03-19 00:46:14 -07001546
Damien Georgeb035db32014-03-21 20:39:40 +00001547STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1548 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001549}
1550
Paul Sokolovsky69135212014-05-10 19:47:41 +03001551// Supposedly not too critical operations, so optimize for code size
Damien Georgefcc9cf62014-06-01 18:22:09 +01001552STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) {
Paul Sokolovsky69135212014-05-10 19:47:41 +03001553 GET_STR_DATA_LEN(self_in, self_data, self_len);
1554 byte *data;
1555 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 +01001556 for (mp_uint_t i = 0; i < self_len; i++) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001557 *data++ = op(*self_data++);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001558 }
1559 *data = 0;
1560 return mp_obj_str_builder_end(s);
1561}
1562
1563STATIC mp_obj_t str_lower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001564 return str_caseconv(unichar_tolower, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001565}
1566
1567STATIC mp_obj_t str_upper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001568 return str_caseconv(unichar_toupper, self_in);
Paul Sokolovsky69135212014-05-10 19:47:41 +03001569}
1570
Damien Georgefcc9cf62014-06-01 18:22:09 +01001571STATIC mp_obj_t str_uni_istype(bool (*f)(unichar), mp_obj_t self_in) {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001572 GET_STR_DATA_LEN(self_in, self_data, self_len);
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001573
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001574 if (self_len == 0) {
1575 return mp_const_false; // default to False for empty str
1576 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001577
Damien Georgefcc9cf62014-06-01 18:22:09 +01001578 if (f != unichar_isupper && f != unichar_islower) {
Damien George39dc1452014-10-03 19:52:22 +01001579 for (mp_uint_t i = 0; i < self_len; i++) {
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001580 if (!f(*self_data++)) {
1581 return mp_const_false;
1582 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001583 }
1584 } else {
Kim Bautersa3f4b832014-05-31 07:30:03 +01001585 bool contains_alpha = false;
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001586
Damien George39dc1452014-10-03 19:52:22 +01001587 for (mp_uint_t i = 0; i < self_len; i++) { // only check alphanumeric characters
Kim Bautersa3f4b832014-05-31 07:30:03 +01001588 if (unichar_isalpha(*self_data++)) {
1589 contains_alpha = true;
Damien Georgefcc9cf62014-06-01 18:22:09 +01001590 if (!f(*(self_data - 1))) { // -1 because we already incremented above
1591 return mp_const_false;
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001592 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001593 }
1594 }
Paul Sokolovskyae9c82d2014-05-31 11:00:25 +03001595
Paul Sokolovskyf69b9d32014-05-31 10:59:34 +03001596 if (!contains_alpha) {
1597 return mp_const_false;
1598 }
Kim Bautersa3f4b832014-05-31 07:30:03 +01001599 }
1600
1601 return mp_const_true;
1602}
1603
1604STATIC mp_obj_t str_isspace(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001605 return str_uni_istype(unichar_isspace, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001606}
1607
1608STATIC mp_obj_t str_isalpha(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001609 return str_uni_istype(unichar_isalpha, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001610}
1611
1612STATIC mp_obj_t str_isdigit(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001613 return str_uni_istype(unichar_isdigit, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001614}
1615
1616STATIC mp_obj_t str_isupper(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001617 return str_uni_istype(unichar_isupper, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001618}
1619
1620STATIC mp_obj_t str_islower(mp_obj_t self_in) {
Damien Georgefcc9cf62014-06-01 18:22:09 +01001621 return str_uni_istype(unichar_islower, self_in);
Kim Bautersa3f4b832014-05-31 07:30:03 +01001622}
1623
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001624#if MICROPY_CPYTHON_COMPAT
1625// These methods are superfluous in the presense of str() and bytes()
1626// constructors.
1627// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001628STATIC mp_obj_t bytes_decode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001629 mp_obj_t new_args[2];
1630 if (n_args == 1) {
1631 new_args[0] = args[0];
1632 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1633 args = new_args;
1634 n_args++;
1635 }
1636 return str_make_new(NULL, n_args, 0, args);
1637}
1638
1639// TODO: should accept kwargs too
Damien Georgeecc88e92014-08-30 00:35:11 +01001640STATIC mp_obj_t str_encode(mp_uint_t n_args, const mp_obj_t *args) {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001641 mp_obj_t new_args[2];
1642 if (n_args == 1) {
1643 new_args[0] = args[0];
1644 new_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_utf_hyphen_8);
1645 args = new_args;
1646 n_args++;
1647 }
1648 return bytes_make_new(NULL, n_args, 0, args);
1649}
1650#endif
1651
Damien George4d917232014-08-30 14:28:06 +01001652mp_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 +01001653 if (flags == MP_BUFFER_READ) {
Damien George2da98302014-03-09 19:58:18 +00001654 GET_STR_DATA_LEN(self_in, str_data, str_len);
1655 bufinfo->buf = (void*)str_data;
1656 bufinfo->len = str_len;
Damien George57a4b4f2014-04-18 22:29:21 +01001657 bufinfo->typecode = 'b';
Damien George2da98302014-03-09 19:58:18 +00001658 return 0;
1659 } else {
1660 // can't write to a string
1661 bufinfo->buf = NULL;
1662 bufinfo->len = 0;
Damien George57a4b4f2014-04-18 22:29:21 +01001663 bufinfo->typecode = -1;
Damien George2da98302014-03-09 19:58:18 +00001664 return 1;
1665 }
1666}
1667
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001668#if MICROPY_CPYTHON_COMPAT
Paul Sokolovsky97319122014-06-13 22:01:26 +03001669MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bytes_decode_obj, 1, 3, bytes_decode);
1670MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode);
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001671#endif
Paul Sokolovsky97319122014-06-13 22:01:26 +03001672MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
1673MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
1674MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_index_obj, 2, 4, str_index);
1675MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex);
1676MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1677MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1678MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rsplit_obj, 1, 3, str_rsplit);
1679MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith);
1680MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith);
1681MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1682MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_lstrip_obj, 1, 2, str_lstrip);
1683MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip);
1684MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, mp_obj_str_format);
1685MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
1686MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
1687MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
1688MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
1689MP_DEFINE_CONST_FUN_OBJ_1(str_lower_obj, str_lower);
1690MP_DEFINE_CONST_FUN_OBJ_1(str_upper_obj, str_upper);
1691MP_DEFINE_CONST_FUN_OBJ_1(str_isspace_obj, str_isspace);
1692MP_DEFINE_CONST_FUN_OBJ_1(str_isalpha_obj, str_isalpha);
1693MP_DEFINE_CONST_FUN_OBJ_1(str_isdigit_obj, str_isdigit);
1694MP_DEFINE_CONST_FUN_OBJ_1(str_isupper_obj, str_isupper);
1695MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower);
Damiend99b0522013-12-21 18:17:45 +00001696
Damien George9b196cd2014-03-26 21:47:19 +00001697STATIC const mp_map_elem_t str_locals_dict_table[] = {
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001698#if MICROPY_CPYTHON_COMPAT
1699 { MP_OBJ_NEW_QSTR(MP_QSTR_decode), (mp_obj_t)&bytes_decode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001700 #if !MICROPY_PY_BUILTINS_STR_UNICODE
1701 // If we have separate unicode type, then here we have methods only
1702 // for bytes type, and it should not have encode() methods. Otherwise,
1703 // we have non-compliant-but-practical bytestring type, which shares
1704 // method table with bytes, so they both have encode() and decode()
1705 // methods (which should do type checking at runtime).
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001706 { MP_OBJ_NEW_QSTR(MP_QSTR_encode), (mp_obj_t)&str_encode_obj },
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001707 #endif
Paul Sokolovsky73b70272014-04-13 05:28:46 +03001708#endif
Damien George9b196cd2014-03-26 21:47:19 +00001709 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1710 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
xbe3d9a39e2014-04-08 11:42:19 -07001711 { MP_OBJ_NEW_QSTR(MP_QSTR_index), (mp_obj_t)&str_index_obj },
1712 { MP_OBJ_NEW_QSTR(MP_QSTR_rindex), (mp_obj_t)&str_rindex_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001713 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1714 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
Paul Sokolovsky2a273652014-05-13 08:07:08 +03001715 { MP_OBJ_NEW_QSTR(MP_QSTR_rsplit), (mp_obj_t)&str_rsplit_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001716 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
Paul Sokolovskyd098c6b2014-05-24 22:46:51 +03001717 { MP_OBJ_NEW_QSTR(MP_QSTR_endswith), (mp_obj_t)&str_endswith_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001718 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
Paul Sokolovsky88107842014-04-26 06:20:08 +03001719 { MP_OBJ_NEW_QSTR(MP_QSTR_lstrip), (mp_obj_t)&str_lstrip_obj },
1720 { MP_OBJ_NEW_QSTR(MP_QSTR_rstrip), (mp_obj_t)&str_rstrip_obj },
Damien George9b196cd2014-03-26 21:47:19 +00001721 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1722 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1723 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1724 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1725 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
Paul Sokolovsky69135212014-05-10 19:47:41 +03001726 { MP_OBJ_NEW_QSTR(MP_QSTR_lower), (mp_obj_t)&str_lower_obj },
1727 { MP_OBJ_NEW_QSTR(MP_QSTR_upper), (mp_obj_t)&str_upper_obj },
Kim Bautersa3f4b832014-05-31 07:30:03 +01001728 { MP_OBJ_NEW_QSTR(MP_QSTR_isspace), (mp_obj_t)&str_isspace_obj },
1729 { MP_OBJ_NEW_QSTR(MP_QSTR_isalpha), (mp_obj_t)&str_isalpha_obj },
1730 { MP_OBJ_NEW_QSTR(MP_QSTR_isdigit), (mp_obj_t)&str_isdigit_obj },
1731 { MP_OBJ_NEW_QSTR(MP_QSTR_isupper), (mp_obj_t)&str_isupper_obj },
1732 { MP_OBJ_NEW_QSTR(MP_QSTR_islower), (mp_obj_t)&str_islower_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001733};
Damien George97209d32014-01-07 15:58:30 +00001734
Damien George9b196cd2014-03-26 21:47:19 +00001735STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1736
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001737#if !MICROPY_PY_BUILTINS_STR_UNICODE
Damien George3e1a5c12014-03-29 13:43:38 +00001738const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001739 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001740 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001741 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001742 .make_new = str_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001743 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001744 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001745 .getiter = mp_obj_new_str_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001746 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001747 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001748};
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001749#endif
Damiend99b0522013-12-21 18:17:45 +00001750
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001751// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001752const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001753 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001754 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001755 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001756 .make_new = bytes_make_new,
Damien Georgee04a44e2014-06-28 10:27:23 +01001757 .binary_op = mp_obj_str_binary_op,
Paul Sokolovsky9749b2f2014-08-11 22:36:38 +03001758 .subscr = bytes_subscr,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001759 .getiter = mp_obj_new_bytes_iterator,
Damien Georgee04a44e2014-06-28 10:27:23 +01001760 .buffer_p = { .get_buffer = mp_obj_str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001761 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001762};
1763
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001764// the zero-length bytes
Damien George20f59e12014-10-11 17:56:43 +01001765const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001766
Damien Georged182b982014-08-30 14:19:41 +01001767mp_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 +02001768 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001769 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001770 o->len = len;
Paul Sokolovsky504e2332014-04-19 03:09:17 +03001771 o->hash = 0;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001772 byte *p = m_new(byte, len + 1);
1773 o->data = p;
1774 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001775 return o;
1776}
1777
Damien George5fa93b62014-01-22 14:35:10 +00001778mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001779 mp_obj_str_t *o = o_in;
1780 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001781 byte *p = (byte*)o->data;
1782 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001783 return o;
1784}
1785
Damien George5f27a7e2014-07-31 10:29:56 +01001786mp_obj_t mp_obj_str_builder_end_with_len(mp_obj_t o_in, mp_uint_t len) {
1787 mp_obj_str_t *o = o_in;
1788 o->data = m_renew(byte, (byte*)o->data, o->len + 1, len + 1);
1789 o->len = len;
1790 o->hash = qstr_compute_hash(o->data, o->len);
1791 byte *p = (byte*)o->data;
1792 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1793 return o;
1794}
1795
Damien George4abff752014-08-30 14:59:21 +01001796mp_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 +02001797 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001798 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001799 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001800 if (data) {
1801 o->hash = qstr_compute_hash(data, len);
1802 byte *p = m_new(byte, len + 1);
1803 o->data = p;
1804 memcpy(p, data, len * sizeof(byte));
1805 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1806 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001807 return o;
1808}
1809
Damien Georged182b982014-08-30 14:19:41 +01001810mp_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 +01001811 if (make_qstr_if_not_already) {
1812 // use existing, or make a new qstr
Damien George2617eeb2014-05-25 22:27:57 +01001813 return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len));
Damien George5fa93b62014-01-22 14:35:10 +00001814 } else {
Damien Georgef600a6a2014-05-25 22:34:34 +01001815 qstr q = qstr_find_strn(data, len);
1816 if (q != MP_QSTR_NULL) {
1817 // qstr with this data already exists
1818 return MP_OBJ_NEW_QSTR(q);
1819 } else {
1820 // no existing qstr, don't make one
1821 return mp_obj_new_str_of_type(&mp_type_str, (const byte*)data, len);
1822 }
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001823 }
Damien George5fa93b62014-01-22 14:35:10 +00001824}
1825
Paul Sokolovskyb4efac12014-06-08 01:13:35 +03001826mp_obj_t mp_obj_str_intern(mp_obj_t str) {
1827 GET_STR_DATA_LEN(str, data, len);
1828 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1829}
1830
Damien Georged182b982014-08-30 14:19:41 +01001831mp_obj_t mp_obj_new_bytes(const byte* data, mp_uint_t len) {
Damien Georgef600a6a2014-05-25 22:34:34 +01001832 return mp_obj_new_str_of_type(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001833}
1834
Damien George5fa93b62014-01-22 14:35:10 +00001835bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1836 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1837 return s1 == s2;
1838 } else {
1839 GET_STR_HASH(s1, h1);
1840 GET_STR_HASH(s2, h2);
Paul Sokolovsky59e269c2014-04-14 01:43:01 +03001841 // If any of hashes is 0, it means it's not valid
1842 if (h1 != 0 && h2 != 0 && h1 != h2) {
Damien George5fa93b62014-01-22 14:35:10 +00001843 return false;
1844 }
1845 GET_STR_DATA_LEN(s1, d1, l1);
1846 GET_STR_DATA_LEN(s2, d2, l2);
1847 if (l1 != l2) {
1848 return false;
1849 }
Damien George1e708fe2014-01-23 18:27:51 +00001850 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001851 }
Damien George5fa93b62014-01-22 14:35:10 +00001852}
1853
Damien Georgedeed0872014-04-06 11:11:15 +01001854STATIC void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgeea13f402014-04-05 18:32:08 +01001855 nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError, "Can't convert '%s' object to str implicitly", mp_obj_get_type_str(self_in)));
Damien Georgeb829b5c2014-01-25 13:51:19 +00001856}
1857
Paul Sokolovsky69f3eb22014-05-11 02:44:46 +03001858STATIC void arg_type_mixup() {
1859 nlr_raise(mp_obj_new_exception_msg(&mp_type_TypeError, "Can't mix str and bytes arguments"));
1860}
1861
Damien Georged182b982014-08-30 14:19:41 +01001862mp_uint_t mp_obj_str_get_hash(mp_obj_t self_in) {
Paul Sokolovskyf130ca12014-04-13 05:41:00 +03001863 // TODO: This has too big overhead for hash accessor
1864 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001865 GET_STR_HASH(self_in, h);
1866 return h;
1867 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001868 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001869 }
1870}
1871
Damien Georged182b982014-08-30 14:19:41 +01001872mp_uint_t mp_obj_str_get_len(mp_obj_t self_in) {
Damien Georgeee014112014-04-15 23:10:00 +01001873 // TODO This has a double check for the type, one in obj.c and one here
1874 if (MP_OBJ_IS_STR(self_in) || MP_OBJ_IS_TYPE(self_in, &mp_type_bytes)) {
Damien George5fa93b62014-01-22 14:35:10 +00001875 GET_STR_LEN(self_in, l);
1876 return l;
1877 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001878 bad_implicit_conversion(self_in);
1879 }
1880}
1881
1882// use this if you will anyway convert the string to a qstr
1883// will be more efficient for the case where it's already a qstr
1884qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1885 if (MP_OBJ_IS_QSTR(self_in)) {
1886 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001887 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001888 mp_obj_str_t *self = self_in;
1889 return qstr_from_strn((char*)self->data, self->len);
1890 } else {
1891 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001892 }
1893}
1894
1895// only use this function if you need the str data to be zero terminated
1896// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1897const char *mp_obj_str_get_str(mp_obj_t self_in) {
1898 if (MP_OBJ_IS_STR(self_in)) {
1899 GET_STR_DATA_LEN(self_in, s, l);
1900 (void)l; // len unused
1901 return (const char*)s;
1902 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001903 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001904 }
1905}
1906
Damien Georged182b982014-08-30 14:19:41 +01001907const char *mp_obj_str_get_data(mp_obj_t self_in, mp_uint_t *len) {
Dave Hylandsb7f7c652014-08-26 12:44:46 -07001908 if (MP_OBJ_IS_STR_OR_BYTES(self_in)) {
Damien George5fa93b62014-01-22 14:35:10 +00001909 GET_STR_DATA_LEN(self_in, s, l);
1910 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001911 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001912 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001913 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001914 }
Damiend99b0522013-12-21 18:17:45 +00001915}
xyb8cfc9f02014-01-05 18:47:51 +08001916
1917/******************************************************************************/
1918/* str iterator */
1919
1920typedef struct _mp_obj_str_it_t {
1921 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001922 mp_obj_t str;
Damien George40f3c022014-07-03 13:25:24 +01001923 mp_uint_t cur;
xyb8cfc9f02014-01-05 18:47:51 +08001924} mp_obj_str_it_t;
1925
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001926#if !MICROPY_PY_BUILTINS_STR_UNICODE
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001927STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001928 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001929 GET_STR_DATA_LEN(self->str, str, len);
1930 if (self->cur < len) {
Damien George2617eeb2014-05-25 22:27:57 +01001931 mp_obj_t o_out = mp_obj_new_str((const char*)str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001932 self->cur += 1;
1933 return o_out;
1934 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001935 return MP_OBJ_STOP_ITERATION;
xyb8cfc9f02014-01-05 18:47:51 +08001936 }
1937}
1938
Damien George3e1a5c12014-03-29 13:43:38 +00001939STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001940 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001941 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001942 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001943 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001944};
1945
Paul Sokolovskyd215ee12014-06-13 22:41:45 +03001946mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
1947 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
1948 o->base.type = &mp_type_str_it;
1949 o->str = str;
1950 o->cur = 0;
1951 return o;
1952}
1953#endif
1954
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001955STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001956 mp_obj_str_it_t *self = self_in;
1957 GET_STR_DATA_LEN(self->str, str, len);
1958 if (self->cur < len) {
Damien Georgebb4c6f32014-07-31 10:49:14 +01001959 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001960 self->cur += 1;
1961 return o_out;
1962 } else {
Damien Georgeea8d06c2014-04-17 23:19:36 +01001963 return MP_OBJ_STOP_ITERATION;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001964 }
1965}
1966
Damien George3e1a5c12014-03-29 13:43:38 +00001967STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001968 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001969 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001970 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001971 .iternext = bytes_it_iternext,
1972};
1973
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001974mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1975 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001976 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001977 o->str = str;
1978 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001979 return o;
1980}