blob: ad85b4b6c5809383e2a79cb1e5aa706e9d3e4a13 [file] [log] [blame]
xbeefe34222014-03-16 00:14:26 -07001#include <stdbool.h>
Damiend99b0522013-12-21 18:17:45 +00002#include <string.h>
3#include <assert.h>
4
5#include "nlr.h"
6#include "misc.h"
7#include "mpconfig.h"
Damien George55baff42014-01-21 21:40:13 +00008#include "qstr.h"
Damiend99b0522013-12-21 18:17:45 +00009#include "obj.h"
10#include "runtime0.h"
11#include "runtime.h"
Dave Hylandsbaf6f142014-03-30 21:06:50 -070012#include "pfenv.h"
Damiend99b0522013-12-21 18:17:45 +000013
14typedef struct _mp_obj_str_t {
15 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +000016 machine_uint_t hash : 16; // XXX here we assume the hash size is 16 bits (it is at the moment; see qstr.c)
17 machine_uint_t len : 16; // len == number of bytes used in data, alloc = len + 1 because (at the moment) we also append a null byte
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +020018 const byte *data;
Damiend99b0522013-12-21 18:17:45 +000019} mp_obj_str_t;
20
Paul Sokolovsky4db727a2014-03-31 21:18:28 +030021STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +020022const mp_obj_t mp_const_empty_bytes;
23
Damien George5fa93b62014-01-22 14:35:10 +000024// use this macro to extract the string hash
25#define GET_STR_HASH(str_obj_in, str_hash) uint str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)str_obj_in)->hash; }
26
27// use this macro to extract the string length
28#define GET_STR_LEN(str_obj_in, str_len) uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; }
29
30// use this macro to extract the string data and length
31#define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) const byte *str_data; uint str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } else { str_len = ((mp_obj_str_t*)str_obj_in)->len; str_data = ((mp_obj_str_t*)str_obj_in)->data; }
32
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020033STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str);
34STATIC mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str);
Paul Sokolovskybe020c22014-03-21 11:39:01 +020035STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len);
xyb8cfc9f02014-01-05 18:47:51 +080036
37/******************************************************************************/
38/* str */
39
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020040void mp_str_print_quoted(void (*print)(void *env, const char *fmt, ...), void *env, const byte *str_data, uint str_len) {
41 // this escapes characters, but it will be very slow to print (calling print many times)
42 bool has_single_quote = false;
43 bool has_double_quote = false;
44 for (const byte *s = str_data, *top = str_data + str_len; (!has_single_quote || !has_double_quote) && s < top; s++) {
45 if (*s == '\'') {
46 has_single_quote = true;
47 } else if (*s == '"') {
48 has_double_quote = true;
49 }
50 }
51 int quote_char = '\'';
52 if (has_single_quote && !has_double_quote) {
53 quote_char = '"';
54 }
55 print(env, "%c", quote_char);
56 for (const byte *s = str_data, *top = str_data + str_len; s < top; s++) {
57 if (*s == quote_char) {
58 print(env, "\\%c", quote_char);
59 } else if (*s == '\\') {
60 print(env, "\\\\");
61 } else if (32 <= *s && *s <= 126) {
62 print(env, "%c", *s);
63 } else if (*s == '\n') {
64 print(env, "\\n");
65 // TODO add more escape codes here if we want to match CPython
66 } else {
67 print(env, "\\x%02x", *s);
68 }
69 }
70 print(env, "%c", quote_char);
71}
72
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +020073STATIC 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 +000074 GET_STR_DATA_LEN(self_in, str_data, str_len);
Damien George3e1a5c12014-03-29 13:43:38 +000075 bool is_bytes = MP_OBJ_IS_TYPE(self_in, &mp_type_bytes);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +020076 if (kind == PRINT_STR && !is_bytes) {
Damien George5fa93b62014-01-22 14:35:10 +000077 print(env, "%.*s", str_len, str_data);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +020078 } else {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +020079 if (is_bytes) {
80 print(env, "b");
81 }
Paul Sokolovsky0b7e29c2014-01-28 03:40:06 +020082 mp_str_print_quoted(print, env, str_data, str_len);
Paul Sokolovsky76d982e2014-01-13 19:19:16 +020083 }
Damiend99b0522013-12-21 18:17:45 +000084}
85
Paul Sokolovskybe020c22014-03-21 11:39:01 +020086STATIC mp_obj_t str_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
87 switch (n_args) {
88 case 0:
89 return MP_OBJ_NEW_QSTR(MP_QSTR_);
90
91 case 1:
92 {
93 vstr_t *vstr = vstr_new();
94 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, args[0], PRINT_STR);
95 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
96 vstr_free(vstr);
97 return s;
98 }
99
100 case 2:
101 case 3:
102 {
103 // TODO: validate 2nd/3rd args
Damien George3e1a5c12014-03-29 13:43:38 +0000104 if (!MP_OBJ_IS_TYPE(args[0], &mp_type_bytes)) {
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200105 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "bytes expected"));
106 }
107 GET_STR_DATA_LEN(args[0], str_data, str_len);
108 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000109 mp_obj_str_t *o = str_new(&mp_type_str, NULL, str_len);
Paul Sokolovskybe020c22014-03-21 11:39:01 +0200110 o->data = str_data;
111 o->hash = str_hash;
112 return o;
113 }
114
115 default:
116 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "str takes at most 3 arguments"));
117 }
118}
119
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200120STATIC mp_obj_t bytes_make_new(mp_obj_t type_in, uint n_args, uint n_kw, const mp_obj_t *args) {
121 if (n_args == 0) {
122 return mp_const_empty_bytes;
123 }
124
125 if (MP_OBJ_IS_STR(args[0])) {
126 if (n_args < 2 || n_args > 3) {
127 goto wrong_args;
128 }
129 GET_STR_DATA_LEN(args[0], str_data, str_len);
130 GET_STR_HASH(args[0], str_hash);
Damien George3e1a5c12014-03-29 13:43:38 +0000131 mp_obj_str_t *o = str_new(&mp_type_bytes, NULL, str_len);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200132 o->data = str_data;
133 o->hash = str_hash;
134 return o;
135 }
136
137 if (n_args > 1) {
138 goto wrong_args;
139 }
140
141 if (MP_OBJ_IS_SMALL_INT(args[0])) {
142 uint len = MP_OBJ_SMALL_INT_VALUE(args[0]);
143 byte *data;
144
Damien George3e1a5c12014-03-29 13:43:38 +0000145 mp_obj_t o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200146 memset(data, 0, len);
147 return mp_obj_str_builder_end(o);
148 }
149
150 int len;
151 byte *data;
152 vstr_t *vstr = NULL;
153 mp_obj_t o = NULL;
154 // Try to create array of exact len if initializer len is known
155 mp_obj_t len_in = mp_obj_len_maybe(args[0]);
156 if (len_in == MP_OBJ_NULL) {
157 len = -1;
158 vstr = vstr_new();
159 } else {
160 len = MP_OBJ_SMALL_INT_VALUE(len_in);
Damien George3e1a5c12014-03-29 13:43:38 +0000161 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200162 }
163
Damien Georged17926d2014-03-30 13:35:08 +0100164 mp_obj_t iterable = mp_getiter(args[0]);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200165 mp_obj_t item;
Damien Georged17926d2014-03-30 13:35:08 +0100166 while ((item = mp_iternext(iterable)) != MP_OBJ_NULL) {
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200167 if (len == -1) {
168 vstr_add_char(vstr, MP_OBJ_SMALL_INT_VALUE(item));
169 } else {
170 *data++ = MP_OBJ_SMALL_INT_VALUE(item);
171 }
172 }
173
174 if (len == -1) {
175 vstr_shrink(vstr);
176 // TODO: Optimize, borrow buffer from vstr
177 len = vstr_len(vstr);
Damien George3e1a5c12014-03-29 13:43:38 +0000178 o = mp_obj_str_builder_start(&mp_type_bytes, len, &data);
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +0200179 memcpy(data, vstr_str(vstr), len);
180 vstr_free(vstr);
181 }
182
183 return mp_obj_str_builder_end(o);
184
185wrong_args:
186 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "wrong number of arguments"));
187}
188
Damien George55baff42014-01-21 21:40:13 +0000189// like strstr but with specified length and allows \0 bytes
190// TODO replace with something more efficient/standard
xbe17a5a832014-03-23 23:31:58 -0700191STATIC const byte *find_subbytes(const byte *haystack, machine_uint_t hlen, const byte *needle, machine_uint_t nlen, machine_int_t direction) {
Damien George55baff42014-01-21 21:40:13 +0000192 if (hlen >= nlen) {
xbe17a5a832014-03-23 23:31:58 -0700193 machine_uint_t str_index, str_index_end;
194 if (direction > 0) {
195 str_index = 0;
196 str_index_end = hlen - nlen;
197 } else {
198 str_index = hlen - nlen;
199 str_index_end = 0;
200 }
201 for (;;) {
202 if (memcmp(&haystack[str_index], needle, nlen) == 0) {
203 //found
204 return haystack + str_index;
Damien George55baff42014-01-21 21:40:13 +0000205 }
xbe17a5a832014-03-23 23:31:58 -0700206 if (str_index == str_index_end) {
207 //not found
208 break;
Damien George55baff42014-01-21 21:40:13 +0000209 }
xbe17a5a832014-03-23 23:31:58 -0700210 str_index += direction;
Damien George55baff42014-01-21 21:40:13 +0000211 }
212 }
213 return NULL;
214}
215
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200216STATIC mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
Damien George5fa93b62014-01-22 14:35:10 +0000217 GET_STR_DATA_LEN(lhs_in, lhs_data, lhs_len);
Damiend99b0522013-12-21 18:17:45 +0000218 switch (op) {
Damien Georged17926d2014-03-30 13:35:08 +0100219 case MP_BINARY_OP_SUBSCR:
Paul Sokolovsky31ba60f2014-01-03 02:51:16 +0200220 // TODO: need predicate to check for int-like type (bools are such for example)
221 // ["no", "yes"][1 == 2] is common idiom
222 if (MP_OBJ_IS_SMALL_INT(rhs_in)) {
xbe9e1e8cd2014-03-12 22:57:16 -0700223 uint index = mp_get_index(mp_obj_get_type(lhs_in), lhs_len, rhs_in, false);
Damien George3e1a5c12014-03-29 13:43:38 +0000224 if (MP_OBJ_IS_TYPE(lhs_in, &mp_type_bytes)) {
Damien George7c9c6672014-01-25 00:17:36 +0000225 return MP_OBJ_NEW_SMALL_INT((mp_small_int_t)lhs_data[index]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200226 } else {
227 return mp_obj_new_str(lhs_data + index, 1, true);
228 }
Paul Sokolovskye606cb62014-01-04 01:34:23 +0200229#if MICROPY_ENABLE_SLICE
Damien George3e1a5c12014-03-29 13:43:38 +0000230 } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_slice)) {
Paul Sokolovsky7364af22014-02-02 02:38:22 +0200231 machine_uint_t start, stop;
Paul Sokolovskyea2509d2014-02-02 08:57:05 +0200232 if (!m_seq_get_fast_slice_indexes(lhs_len, rhs_in, &start, &stop)) {
233 assert(0);
234 }
Damien George5fa93b62014-01-22 14:35:10 +0000235 return mp_obj_new_str(lhs_data + start, stop - start, false);
Paul Sokolovskye606cb62014-01-04 01:34:23 +0200236#endif
Paul Sokolovsky31ba60f2014-01-03 02:51:16 +0200237 } else {
Paul Sokolovskyf8b9d3c2014-01-04 01:38:26 +0200238 // Message doesn't match CPython, but we don't have so much bytes as they
239 // to spend them on verbose wording
Damien Georgec5966122014-02-15 16:10:44 +0000240 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "index must be int"));
Paul Sokolovsky31ba60f2014-01-03 02:51:16 +0200241 }
Damiend99b0522013-12-21 18:17:45 +0000242
Damien Georged17926d2014-03-30 13:35:08 +0100243 case MP_BINARY_OP_ADD:
244 case MP_BINARY_OP_INPLACE_ADD:
Damien George5fa93b62014-01-22 14:35:10 +0000245 if (MP_OBJ_IS_STR(rhs_in)) {
Damiend99b0522013-12-21 18:17:45 +0000246 // add 2 strings
Damien George5fa93b62014-01-22 14:35:10 +0000247
248 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
Damien George55baff42014-01-21 21:40:13 +0000249 int alloc_len = lhs_len + rhs_len;
Damien George5fa93b62014-01-22 14:35:10 +0000250
251 /* code for making qstr
Damien George55baff42014-01-21 21:40:13 +0000252 byte *q_ptr;
253 byte *val = qstr_build_start(alloc_len, &q_ptr);
254 memcpy(val, lhs_data, lhs_len);
255 memcpy(val + lhs_len, rhs_data, rhs_len);
Damien George5fa93b62014-01-22 14:35:10 +0000256 return MP_OBJ_NEW_QSTR(qstr_build_end(q_ptr));
257 */
258
259 // code for non-qstr
260 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200261 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(lhs_in), alloc_len, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000262 memcpy(data, lhs_data, lhs_len);
263 memcpy(data + lhs_len, rhs_data, rhs_len);
264 return mp_obj_str_builder_end(s);
Damiend99b0522013-12-21 18:17:45 +0000265 }
266 break;
Damien George5fa93b62014-01-22 14:35:10 +0000267
Damien Georged17926d2014-03-30 13:35:08 +0100268 case MP_BINARY_OP_IN:
John R. Lentonc1bef212014-01-11 12:39:33 +0000269 /* NOTE `a in b` is `b.__contains__(a)` */
Damien George5fa93b62014-01-22 14:35:10 +0000270 if (MP_OBJ_IS_STR(rhs_in)) {
271 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
xbe17a5a832014-03-23 23:31:58 -0700272 return MP_BOOL(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL);
John R. Lentonc1bef212014-01-11 12:39:33 +0000273 }
274 break;
Damien George5fa93b62014-01-22 14:35:10 +0000275
Damien Georged17926d2014-03-30 13:35:08 +0100276 case MP_BINARY_OP_MULTIPLY:
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200277 {
278 if (!MP_OBJ_IS_SMALL_INT(rhs_in)) {
279 return NULL;
280 }
281 int n = MP_OBJ_SMALL_INT_VALUE(rhs_in);
Damien George5fa93b62014-01-22 14:35:10 +0000282 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200283 mp_obj_t s = mp_obj_str_builder_start(mp_obj_get_type(lhs_in), lhs_len * n, &data);
Damien George5fa93b62014-01-22 14:35:10 +0000284 mp_seq_multiply(lhs_data, sizeof(*lhs_data), lhs_len, n, data);
285 return mp_obj_str_builder_end(s);
Paul Sokolovsky545591a2014-01-21 00:27:33 +0200286 }
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200287
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300288 case MP_BINARY_OP_MODULO: {
289 mp_obj_t *args;
290 uint n_args;
291 if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_tuple)) {
292 // TODO: Support tuple subclasses?
293 mp_obj_tuple_get(rhs_in, &n_args, &args);
294 } else {
295 args = &rhs_in;
296 n_args = 1;
297 }
298 return str_modulo_format(lhs_in, n_args, args);
299 }
300
Damien Georged17926d2014-03-30 13:35:08 +0100301 // These 2 are never passed here, dealt with as a special case in mp_binary_op().
302 //case MP_BINARY_OP_EQUAL:
303 //case MP_BINARY_OP_NOT_EQUAL:
304 case MP_BINARY_OP_LESS:
305 case MP_BINARY_OP_LESS_EQUAL:
306 case MP_BINARY_OP_MORE:
307 case MP_BINARY_OP_MORE_EQUAL:
Paul Sokolovsky87e85b72014-02-02 08:24:07 +0200308 if (MP_OBJ_IS_STR(rhs_in)) {
309 GET_STR_DATA_LEN(rhs_in, rhs_data, rhs_len);
310 return MP_BOOL(mp_seq_cmp_bytes(op, lhs_data, lhs_len, rhs_data, rhs_len));
311 }
Damiend99b0522013-12-21 18:17:45 +0000312 }
313
314 return MP_OBJ_NULL; // op not supported
315}
316
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200317STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) {
Damien George5fa93b62014-01-22 14:35:10 +0000318 assert(MP_OBJ_IS_STR(self_in));
Damiend99b0522013-12-21 18:17:45 +0000319
Damien Georgefe8fb912014-01-02 16:36:09 +0000320 // get separation string
Damien George5fa93b62014-01-22 14:35:10 +0000321 GET_STR_DATA_LEN(self_in, sep_str, sep_len);
Damien Georgefe8fb912014-01-02 16:36:09 +0000322
323 // process args
Damiend99b0522013-12-21 18:17:45 +0000324 uint seq_len;
325 mp_obj_t *seq_items;
Damien George07ddab52014-03-29 13:15:08 +0000326 if (MP_OBJ_IS_TYPE(arg, &mp_type_tuple)) {
Damiend99b0522013-12-21 18:17:45 +0000327 mp_obj_tuple_get(arg, &seq_len, &seq_items);
Damien George3e1a5c12014-03-29 13:43:38 +0000328 } else if (MP_OBJ_IS_TYPE(arg, &mp_type_list)) {
Damiend99b0522013-12-21 18:17:45 +0000329 mp_obj_list_get(arg, &seq_len, &seq_items);
330 } else {
331 goto bad_arg;
332 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000333
334 // count required length
335 int required_len = 0;
Damiend99b0522013-12-21 18:17:45 +0000336 for (int i = 0; i < seq_len; i++) {
Damien George5fa93b62014-01-22 14:35:10 +0000337 if (!MP_OBJ_IS_STR(seq_items[i])) {
Damiend99b0522013-12-21 18:17:45 +0000338 goto bad_arg;
339 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000340 if (i > 0) {
341 required_len += sep_len;
342 }
Damien George5fa93b62014-01-22 14:35:10 +0000343 GET_STR_LEN(seq_items[i], l);
344 required_len += l;
Damiend99b0522013-12-21 18:17:45 +0000345 }
346
347 // make joined string
Damien George5fa93b62014-01-22 14:35:10 +0000348 byte *data;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +0200349 mp_obj_t joined_str = mp_obj_str_builder_start(mp_obj_get_type(self_in), required_len, &data);
Damiend99b0522013-12-21 18:17:45 +0000350 for (int i = 0; i < seq_len; i++) {
Damiend99b0522013-12-21 18:17:45 +0000351 if (i > 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000352 memcpy(data, sep_str, sep_len);
353 data += sep_len;
Damiend99b0522013-12-21 18:17:45 +0000354 }
Damien George5fa93b62014-01-22 14:35:10 +0000355 GET_STR_DATA_LEN(seq_items[i], s, l);
356 memcpy(data, s, l);
357 data += l;
Damiend99b0522013-12-21 18:17:45 +0000358 }
Damien Georgefe8fb912014-01-02 16:36:09 +0000359
360 // return joined string
Damien George5fa93b62014-01-22 14:35:10 +0000361 return mp_obj_str_builder_end(joined_str);
Damiend99b0522013-12-21 18:17:45 +0000362
363bad_arg:
Damien Georgec5966122014-02-15 16:10:44 +0000364 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "?str.join expecting a list of str's"));
Damiend99b0522013-12-21 18:17:45 +0000365}
366
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200367#define is_ws(c) ((c) == ' ' || (c) == '\t')
368
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200369STATIC mp_obj_t str_split(uint n_args, const mp_obj_t *args) {
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200370 int splits = -1;
371 mp_obj_t sep = mp_const_none;
372 if (n_args > 1) {
373 sep = args[1];
374 if (n_args > 2) {
375 splits = MP_OBJ_SMALL_INT_VALUE(args[2]);
376 }
377 }
378 assert(sep == mp_const_none);
Damien George12eacca2014-01-21 21:54:15 +0000379 (void)sep; // unused; to hush compiler warning
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200380 mp_obj_t res = mp_obj_new_list(0, NULL);
Damien George5fa93b62014-01-22 14:35:10 +0000381 GET_STR_DATA_LEN(args[0], s, len);
382 const byte *top = s + len;
383 const byte *start;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200384
385 // Initial whitespace is not counted as split, so we pre-do it
Damien George5fa93b62014-01-22 14:35:10 +0000386 while (s < top && is_ws(*s)) s++;
387 while (s < top && splits != 0) {
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200388 start = s;
Damien George5fa93b62014-01-22 14:35:10 +0000389 while (s < top && !is_ws(*s)) s++;
Damien George15d18062014-03-31 16:28:13 +0100390 mp_obj_list_append(res, mp_obj_new_str(start, s - start, false));
Damien George5fa93b62014-01-22 14:35:10 +0000391 if (s >= top) {
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200392 break;
393 }
Damien George5fa93b62014-01-22 14:35:10 +0000394 while (s < top && is_ws(*s)) s++;
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200395 if (splits > 0) {
396 splits--;
397 }
398 }
399
Damien George5fa93b62014-01-22 14:35:10 +0000400 if (s < top) {
Damien George15d18062014-03-31 16:28:13 +0100401 mp_obj_list_append(res, mp_obj_new_str(s, top - s, false));
Paul Sokolovsky4c316552014-01-21 05:00:21 +0200402 }
403
404 return res;
405}
406
xbe17a5a832014-03-23 23:31:58 -0700407STATIC mp_obj_t str_finder(uint n_args, const mp_obj_t *args, machine_int_t direction) {
John R. Lentone8204912014-01-12 21:53:52 +0000408 assert(2 <= n_args && n_args <= 4);
Damien George5fa93b62014-01-22 14:35:10 +0000409 assert(MP_OBJ_IS_STR(args[0]));
410 assert(MP_OBJ_IS_STR(args[1]));
John R. Lentone8204912014-01-12 21:53:52 +0000411
Damien George5fa93b62014-01-22 14:35:10 +0000412 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
413 GET_STR_DATA_LEN(args[1], needle, needle_len);
John R. Lentone8204912014-01-12 21:53:52 +0000414
xbec5538882014-03-16 17:58:35 -0700415 machine_uint_t start = 0;
416 machine_uint_t end = haystack_len;
John R. Lentone8204912014-01-12 21:53:52 +0000417 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000418 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
John R. Lentone8204912014-01-12 21:53:52 +0000419 }
420 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +0000421 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
John R. Lentone8204912014-01-12 21:53:52 +0000422 }
423
xbe17a5a832014-03-23 23:31:58 -0700424 const byte *p = find_subbytes(haystack + start, end - start, needle, needle_len, direction);
Damien George23005372014-01-13 19:39:01 +0000425 if (p == NULL) {
426 // not found
427 return MP_OBJ_NEW_SMALL_INT(-1);
428 } else {
429 // found
xbe17a5a832014-03-23 23:31:58 -0700430 return MP_OBJ_NEW_SMALL_INT(p - haystack);
John R. Lentone8204912014-01-12 21:53:52 +0000431 }
John R. Lentone8204912014-01-12 21:53:52 +0000432}
433
xbe17a5a832014-03-23 23:31:58 -0700434STATIC mp_obj_t str_find(uint n_args, const mp_obj_t *args) {
435 return str_finder(n_args, args, 1);
436}
437
438STATIC mp_obj_t str_rfind(uint n_args, const mp_obj_t *args) {
439 return str_finder(n_args, args, -1);
440}
441
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200442// TODO: (Much) more variety in args
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200443STATIC mp_obj_t str_startswith(mp_obj_t self_in, mp_obj_t arg) {
Paul Sokolovsky1eacefe2014-01-23 01:20:40 +0200444 GET_STR_DATA_LEN(self_in, str, str_len);
445 GET_STR_DATA_LEN(arg, prefix, prefix_len);
446 if (prefix_len > str_len) {
447 return mp_const_false;
448 }
449 return MP_BOOL(memcmp(str, prefix, prefix_len) == 0);
450}
451
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +0200452STATIC mp_obj_t str_strip(uint n_args, const mp_obj_t *args) {
xbe7b0f39f2014-01-08 14:23:45 -0800453 assert(1 <= n_args && n_args <= 2);
Damien George5fa93b62014-01-22 14:35:10 +0000454 assert(MP_OBJ_IS_STR(args[0]));
455
456 const byte *chars_to_del;
457 uint chars_to_del_len;
458 static const byte whitespace[] = " \t\n\r\v\f";
xbe7b0f39f2014-01-08 14:23:45 -0800459
460 if (n_args == 1) {
461 chars_to_del = whitespace;
Damien George5fa93b62014-01-22 14:35:10 +0000462 chars_to_del_len = sizeof(whitespace);
xbe7b0f39f2014-01-08 14:23:45 -0800463 } else {
Damien George5fa93b62014-01-22 14:35:10 +0000464 assert(MP_OBJ_IS_STR(args[1]));
465 GET_STR_DATA_LEN(args[1], s, l);
466 chars_to_del = s;
467 chars_to_del_len = l;
xbe7b0f39f2014-01-08 14:23:45 -0800468 }
469
Damien George5fa93b62014-01-22 14:35:10 +0000470 GET_STR_DATA_LEN(args[0], orig_str, orig_str_len);
xbe7b0f39f2014-01-08 14:23:45 -0800471
xbec5538882014-03-16 17:58:35 -0700472 machine_uint_t first_good_char_pos = 0;
xbe7b0f39f2014-01-08 14:23:45 -0800473 bool first_good_char_pos_set = false;
xbec5538882014-03-16 17:58:35 -0700474 machine_uint_t last_good_char_pos = 0;
475 for (machine_uint_t i = 0; i < orig_str_len; i++) {
xbe17a5a832014-03-23 23:31:58 -0700476 if (find_subbytes(chars_to_del, chars_to_del_len, &orig_str[i], 1, 1) == NULL) {
xbe7b0f39f2014-01-08 14:23:45 -0800477 last_good_char_pos = i;
478 if (!first_good_char_pos_set) {
479 first_good_char_pos = i;
480 first_good_char_pos_set = true;
481 }
482 }
483 }
484
485 if (first_good_char_pos == 0 && last_good_char_pos == 0) {
Damien George5fa93b62014-01-22 14:35:10 +0000486 // string is all whitespace, return ''
487 return MP_OBJ_NEW_QSTR(MP_QSTR_);
xbe7b0f39f2014-01-08 14:23:45 -0800488 }
489
490 assert(last_good_char_pos >= first_good_char_pos);
491 //+1 to accomodate the last character
xbec5538882014-03-16 17:58:35 -0700492 machine_uint_t stripped_len = last_good_char_pos - first_good_char_pos + 1;
Damien George5fa93b62014-01-22 14:35:10 +0000493 return mp_obj_new_str(orig_str + first_good_char_pos, stripped_len, false);
xbe7b0f39f2014-01-08 14:23:45 -0800494}
495
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700496// Takes an int arg, but only parses unsigned numbers, and only changes
497// *num if at least one digit was parsed.
498static int str_to_int(const char *str, int *num) {
499 const char *s = str;
500 if (unichar_isdigit(*s)) {
501 *num = 0;
502 do {
503 *num = *num * 10 + (*s - '0');
504 s++;
505 }
506 while (unichar_isdigit(*s));
507 }
508 return s - str;
509}
510
511static bool isalignment(char ch) {
512 return ch && strchr("<>=^", ch) != NULL;
513}
514
515static bool istype(char ch) {
516 return ch && strchr("bcdeEfFgGnosxX%", ch) != NULL;
517}
518
519static bool arg_looks_integer(mp_obj_t arg) {
520 return MP_OBJ_IS_TYPE(arg, &mp_type_bool) || MP_OBJ_IS_INT(arg);
521}
522
523static bool arg_looks_numeric(mp_obj_t arg) {
524 return arg_looks_integer(arg)
525#if MICROPY_ENABLE_FLOAT
526 || MP_OBJ_IS_TYPE(arg, &mp_type_float)
527#endif
528 ;
529}
530
Dave Hylandsf81a49e2014-04-05 08:21:45 -0700531static machine_int_t arg_as_int(mp_obj_t arg) {
532#if MICROPY_ENABLE_FLOAT
533 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
534 return mp_obj_get_float(arg);
535 }
536#endif
537 return mp_obj_get_int(arg);
538}
539
Damien Georgea11ceca2014-01-19 16:02:09 +0000540mp_obj_t str_format(uint n_args, const mp_obj_t *args) {
Damien George5fa93b62014-01-22 14:35:10 +0000541 assert(MP_OBJ_IS_STR(args[0]));
Damiend99b0522013-12-21 18:17:45 +0000542
Damien George5fa93b62014-01-22 14:35:10 +0000543 GET_STR_DATA_LEN(args[0], str, len);
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700544 int arg_i = 0;
Damiend99b0522013-12-21 18:17:45 +0000545 vstr_t *vstr = vstr_new();
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700546 pfenv_t pfenv_vstr;
547 pfenv_vstr.data = vstr;
548 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
549
Damien George5fa93b62014-01-22 14:35:10 +0000550 for (const byte *top = str + len; str < top; str++) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700551 if (*str == '}') {
Damiend99b0522013-12-21 18:17:45 +0000552 str++;
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700553 if (str < top && *str == '}') {
554 vstr_add_char(vstr, '}');
555 continue;
556 }
557 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "Single '}' encountered in format string"));
558 }
559 if (*str != '{') {
560 vstr_add_char(vstr, *str);
561 continue;
562 }
563
564 str++;
565 if (str < top && *str == '{') {
566 vstr_add_char(vstr, '{');
567 continue;
568 }
569
570 // replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"
571
572 vstr_t *field_name = NULL;
573 char conversion = '\0';
574 vstr_t *format_spec = NULL;
575
576 if (str < top && *str != '}' && *str != '!' && *str != ':') {
577 field_name = vstr_new();
578 while (str < top && *str != '}' && *str != '!' && *str != ':') {
579 vstr_add_char(field_name, *str++);
580 }
581 vstr_add_char(field_name, '\0');
582 }
583
584 // conversion ::= "r" | "s"
585
586 if (str < top && *str == '!') {
587 str++;
588 if (str < top && (*str == 'r' || *str == 's')) {
589 conversion = *str++;
Paul Sokolovskyf2b796e2014-01-15 22:45:20 +0200590 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700591 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "end of format while looking for conversion specifier"));
592 }
593 }
594
595 if (str < top && *str == ':') {
596 str++;
597 // {:} is the same as {}, which is the same as {!s}
598 // This makes a difference when passing in a True or False
599 // '{}'.format(True) returns 'True'
600 // '{:d}'.format(True) returns '1'
601 // So we treat {:} as {} and this later gets treated to be {!s}
602 if (*str != '}') {
603 format_spec = vstr_new();
604 while (str < top && *str != '}') {
605 vstr_add_char(format_spec, *str++);
Damiend99b0522013-12-21 18:17:45 +0000606 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700607 vstr_add_char(format_spec, '\0');
608 }
609 }
610 if (str >= top) {
611 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "unmatched '{' in format"));
612 }
613 if (*str != '}') {
614 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "expected ':' after format specifier"));
615 }
616
617 mp_obj_t arg = mp_const_none;
618
619 if (field_name) {
620 if (arg_i > 0) {
621 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from automatic field numbering to manual field specification"));
622 }
623 int index;
624 if (str_to_int(vstr_str(field_name), &index) != vstr_len(field_name) - 1) {
625 nlr_jump(mp_obj_new_exception_msg(&mp_type_KeyError, "attributes not supported yet"));
626 }
627 if (index >= n_args - 1) {
628 nlr_jump(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
629 }
630 arg = args[index + 1];
631 arg_i = -1;
632 vstr_free(field_name);
633 field_name = NULL;
634 } else {
635 if (arg_i < 0) {
636 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "cannot switch from manual field specification to automatic field numbering"));
637 }
638 if (arg_i >= n_args - 1) {
639 nlr_jump(mp_obj_new_exception_msg(&mp_type_IndexError, "tuple index out of range"));
640 }
641 arg = args[arg_i + 1];
642 arg_i++;
643 }
644 if (!format_spec && !conversion) {
645 conversion = 's';
646 }
647 if (conversion) {
648 mp_print_kind_t print_kind;
649 if (conversion == 's') {
650 print_kind = PRINT_STR;
651 } else if (conversion == 'r') {
652 print_kind = PRINT_REPR;
653 } else {
654 nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ValueError, "Unknown conversion specifier %c", conversion));
655 }
656 vstr_t *arg_vstr = vstr_new();
657 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, arg_vstr, arg, print_kind);
658 arg = mp_obj_new_str((const byte *)vstr_str(arg_vstr), vstr_len(arg_vstr), false);
659 vstr_free(arg_vstr);
660 }
661
662 char sign = '\0';
663 char fill = '\0';
664 char align = '\0';
665 int width = -1;
666 int precision = -1;
667 char type = '\0';
668 int flags = 0;
669
670 if (format_spec) {
671 // The format specifier (from http://docs.python.org/2/library/string.html#formatspec)
672 //
673 // [[fill]align][sign][#][0][width][,][.precision][type]
674 // fill ::= <any character>
675 // align ::= "<" | ">" | "=" | "^"
676 // sign ::= "+" | "-" | " "
677 // width ::= integer
678 // precision ::= integer
679 // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
680
681 const char *s = vstr_str(format_spec);
682 if (isalignment(*s)) {
683 align = *s++;
684 } else if (*s && isalignment(s[1])) {
685 fill = *s++;
686 align = *s++;
687 }
688 if (*s == '+' || *s == '-' || *s == ' ') {
689 if (*s == '+') {
690 flags |= PF_FLAG_SHOW_SIGN;
691 } else if (*s == ' ') {
692 flags |= PF_FLAG_SPACE_SIGN;
693 }
694 sign = *s++;
695 }
696 if (*s == '#') {
697 flags |= PF_FLAG_SHOW_PREFIX;
698 s++;
699 }
700 if (*s == '0') {
701 if (!align) {
702 align = '=';
703 }
704 if (!fill) {
705 fill = '0';
706 }
707 }
708 s += str_to_int(s, &width);
709 if (*s == ',') {
710 flags |= PF_FLAG_SHOW_COMMA;
711 s++;
712 }
713 if (*s == '.') {
714 s++;
715 s += str_to_int(s, &precision);
716 }
717 if (istype(*s)) {
718 type = *s++;
719 }
720 if (*s) {
721 nlr_jump(mp_obj_new_exception_msg(&mp_type_KeyError, "Invalid conversion specification"));
722 }
723 vstr_free(format_spec);
724 format_spec = NULL;
725 }
726 if (!align) {
727 if (arg_looks_numeric(arg)) {
728 align = '>';
729 } else {
730 align = '<';
731 }
732 }
733 if (!fill) {
734 fill = ' ';
735 }
736
737 if (sign) {
738 if (type == 's') {
739 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed in string format specifier"));
740 }
741 if (type == 'c') {
742 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "Sign not allowed with integer format specifier 'c'"));
Damiend99b0522013-12-21 18:17:45 +0000743 }
744 } else {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700745 sign = '-';
746 }
747
748 switch (align) {
749 case '<': flags |= PF_FLAG_LEFT_ADJUST; break;
750 case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break;
751 case '^': flags |= PF_FLAG_CENTER_ADJUST; break;
752 }
753
754 if (arg_looks_integer(arg)) {
755 switch (type) {
756 case 'b':
757 pfenv_print_int(&pfenv_vstr, mp_obj_get_int(arg), 1, 2, 'a', flags, fill, width);
758 continue;
759
760 case 'c':
761 {
762 char ch = mp_obj_get_int(arg);
763 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, fill, width);
764 continue;
765 }
766
767 case '\0': // No explicit format type implies 'd'
768 case 'n': // I don't think we support locales in uPy so use 'd'
769 case 'd':
770 pfenv_print_int(&pfenv_vstr, mp_obj_get_int(arg), 1, 10, 'a', flags, fill, width);
771 continue;
772
773 case 'o':
774 pfenv_print_int(&pfenv_vstr, mp_obj_get_int(arg), 1, 8, 'a', flags, fill, width);
775 continue;
776
777 case 'x':
778 pfenv_print_int(&pfenv_vstr, mp_obj_get_int(arg), 1, 16, 'a', flags, fill, width);
779 continue;
780
781 case 'X':
782 pfenv_print_int(&pfenv_vstr, mp_obj_get_int(arg), 1, 16, 'A', flags, fill, width);
783 continue;
784
785 case 'e':
786 case 'E':
787 case 'f':
788 case 'F':
789 case 'g':
790 case 'G':
791 case '%':
792 // The floating point formatters all work with anything that
793 // looks like an integer
794 break;
795
796 default:
797 nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
798 "Unknown format code '%c' for object of type '%s'", type, mp_obj_get_type_str(arg)));
799 }
Damien Georgec322c5f2014-04-02 20:04:15 +0100800 }
Damien George70f33cd2014-04-02 17:06:05 +0100801
Dave Hylands22fe4d72014-04-02 12:07:31 -0700802 // NOTE: no else here. We need the e, f, g etc formats for integer
803 // arguments (from above if) to take this if.
Damien Georgec322c5f2014-04-02 20:04:15 +0100804 if (arg_looks_numeric(arg)) {
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700805 if (!type) {
806
807 // Even though the docs say that an unspecified type is the same
808 // as 'g', there is one subtle difference, when the exponent
809 // is one less than the precision.
810 //
811 // '{:10.1}'.format(0.0) ==> '0e+00'
812 // '{:10.1g}'.format(0.0) ==> '0'
813 //
814 // TODO: Figure out how to deal with this.
815 //
816 // A proper solution would involve adding a special flag
817 // or something to format_float, and create a format_double
818 // to deal with doubles. In order to fix this when using
819 // sprintf, we'd need to use the e format and tweak the
820 // returned result to strip trailing zeros like the g format
821 // does.
822 //
823 // {:10.3} and {:10.2e} with 1.23e2 both produce 1.23e+02
824 // but with 1.e2 you get 1e+02 and 1.00e+02
825 //
826 // Stripping the trailing 0's (like g) does would make the
827 // e format give us the right format.
828 //
829 // CPython sources say:
830 // Omitted type specifier. Behaves in the same way as repr(x)
831 // and str(x) if no precision is given, else like 'g', but with
832 // at least one digit after the decimal point. */
833
834 type = 'g';
835 }
836 if (type == 'n') {
837 type = 'g';
838 }
839
840 flags |= PF_FLAG_PAD_NAN_INF; // '{:06e}'.format(float('-inf')) should give '-00inf'
841 switch (type) {
Damien Georgec322c5f2014-04-02 20:04:15 +0100842#if MICROPY_ENABLE_FLOAT
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700843 case 'e':
844 case 'E':
845 case 'f':
846 case 'F':
847 case 'g':
848 case 'G':
849 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), type, flags, fill, width, precision);
850 break;
851
852 case '%':
853 flags |= PF_FLAG_ADD_PERCENT;
854 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg) * 100.0F, 'f', flags, fill, width, precision);
855 break;
Damien Georgec322c5f2014-04-02 20:04:15 +0100856#endif
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700857
858 default:
859 nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
860 "Unknown format code '%c' for object of type 'float'",
861 type, mp_obj_get_type_str(arg)));
862 }
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700863 } else {
Damien George70f33cd2014-04-02 17:06:05 +0100864 // arg doesn't look like a number
865
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700866 if (align == '=') {
867 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "'=' alignment not allowed in string format specifier"));
868 }
Damien George70f33cd2014-04-02 17:06:05 +0100869
Dave Hylandsbaf6f142014-03-30 21:06:50 -0700870 switch (type) {
871 case '\0':
872 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf, vstr, arg, PRINT_STR);
873 break;
874
875 case 's':
876 {
877 uint len;
878 const char *s = mp_obj_str_get_data(arg, &len);
879 if (precision < 0) {
880 precision = len;
881 }
882 if (len > precision) {
883 len = precision;
884 }
885 pfenv_print_strn(&pfenv_vstr, s, len, flags, fill, width);
886 break;
887 }
888
889 default:
890 nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
891 "Unknown format code '%c' for object of type 'str'",
892 type, mp_obj_get_type_str(arg)));
893 }
Damiend99b0522013-12-21 18:17:45 +0000894 }
895 }
896
Damien George5fa93b62014-01-22 14:35:10 +0000897 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
898 vstr_free(vstr);
899 return s;
Damiend99b0522013-12-21 18:17:45 +0000900}
901
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300902STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, uint n_args, const mp_obj_t *args) {
903 assert(MP_OBJ_IS_STR(pattern));
904
905 GET_STR_DATA_LEN(pattern, str, len);
Dave Hylands6756a372014-04-02 11:42:39 -0700906 const byte *start_str = str;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300907 int arg_i = 0;
908 vstr_t *vstr = vstr_new();
Dave Hylands6756a372014-04-02 11:42:39 -0700909 pfenv_t pfenv_vstr;
910 pfenv_vstr.data = vstr;
911 pfenv_vstr.print_strn = pfenv_vstr_add_strn;
912
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300913 for (const byte *top = str + len; str < top; str++) {
Dave Hylands6756a372014-04-02 11:42:39 -0700914 if (*str != '%') {
915 vstr_add_char(vstr, *str);
916 continue;
917 }
918 if (++str >= top) {
919 break;
920 }
Paul Sokolovsky4db727a2014-03-31 21:18:28 +0300921 if (*str == '%') {
Dave Hylands6756a372014-04-02 11:42:39 -0700922 vstr_add_char(vstr, '%');
923 continue;
924 }
925 if (arg_i >= n_args) {
926 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "not enough arguments for format string"));
927 }
928 int flags = 0;
929 char fill = ' ';
930 bool alt = false;
931 while (str < top) {
932 if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST;
933 else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN;
934 else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN;
935 else if (*str == '#') alt = true;
936 else if (*str == '0') {
937 flags |= PF_FLAG_PAD_AFTER_SIGN;
938 fill = '0';
939 } else break;
940 str++;
941 }
942 // parse width, if it exists
943 int width = 0;
944 if (str < top) {
945 if (*str == '*') {
946 width = mp_obj_get_int(args[arg_i++]);
947 str++;
948 } else {
949 for (; str < top && '0' <= *str && *str <= '9'; str++) {
950 width = width * 10 + *str - '0';
951 }
952 }
953 }
954 int prec = -1;
955 if (str < top && *str == '.') {
956 if (++str < top) {
957 if (*str == '*') {
958 prec = mp_obj_get_int(args[arg_i++]);
959 str++;
960 } else {
961 prec = 0;
962 for (; str < top && '0' <= *str && *str <= '9'; str++) {
963 prec = prec * 10 + *str - '0';
964 }
965 }
966 }
967 }
968
969 if (str >= top) {
970 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "incomplete format"));
971 }
972 mp_obj_t arg = args[arg_i];
973 switch (*str) {
974 case 'c':
975 if (MP_OBJ_IS_STR(arg)) {
976 uint len;
977 const char *s = mp_obj_str_get_data(arg, &len);
978 if (len != 1) {
979 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "%c requires int or char"));
980 break;
981 }
982 pfenv_print_strn(&pfenv_vstr, s, 1, flags, ' ', width);
983 break;
984 }
985 if (arg_looks_integer(arg)) {
986 char ch = mp_obj_get_int(arg);
987 pfenv_print_strn(&pfenv_vstr, &ch, 1, flags, ' ', width);
988 break;
989 }
990#if MICROPY_ENABLE_FLOAT
991 // This is what CPython reports, so we report the same.
992 if (MP_OBJ_IS_TYPE(arg, &mp_type_float)) {
993 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "integer argument expected, got float"));
994
995 }
996#endif
997 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "an integer is required"));
998 break;
999
1000 case 'd':
1001 case 'i':
1002 case 'u':
Dave Hylandsf81a49e2014-04-05 08:21:45 -07001003 pfenv_print_int(&pfenv_vstr, arg_as_int(arg), 1, 10, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001004 break;
1005
1006#if MICROPY_ENABLE_FLOAT
1007 case 'e':
1008 case 'E':
1009 case 'f':
1010 case 'F':
1011 case 'g':
1012 case 'G':
1013 pfenv_print_float(&pfenv_vstr, mp_obj_get_float(arg), *str, flags, fill, width, prec);
1014 break;
1015#endif
1016
1017 case 'o':
1018 if (alt) {
1019 flags |= PF_FLAG_SHOW_PREFIX;
1020 }
Dave Hylandsf81a49e2014-04-05 08:21:45 -07001021 pfenv_print_int(&pfenv_vstr, arg_as_int(arg), 1, 8, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001022 break;
1023
1024 case 'r':
1025 case 's':
1026 {
1027 vstr_t *arg_vstr = vstr_new();
1028 mp_obj_print_helper((void (*)(void*, const char*, ...))vstr_printf,
1029 arg_vstr, arg, *str == 'r' ? PRINT_REPR : PRINT_STR);
1030 uint len = vstr_len(arg_vstr);
1031 if (prec < 0) {
1032 prec = len;
1033 }
1034 if (len > prec) {
1035 len = prec;
1036 }
1037 pfenv_print_strn(&pfenv_vstr, vstr_str(arg_vstr), len, flags, ' ', width);
1038 vstr_free(arg_vstr);
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001039 break;
1040 }
Dave Hylands6756a372014-04-02 11:42:39 -07001041
1042 case 'x':
1043 if (alt) {
1044 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001045 }
Dave Hylandsf81a49e2014-04-05 08:21:45 -07001046 pfenv_print_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'a', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001047 break;
1048
1049 case 'X':
1050 if (alt) {
1051 flags |= PF_FLAG_SHOW_PREFIX;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001052 }
Dave Hylandsf81a49e2014-04-05 08:21:45 -07001053 pfenv_print_int(&pfenv_vstr, arg_as_int(arg), 1, 16, 'A', flags, fill, width);
Dave Hylands6756a372014-04-02 11:42:39 -07001054 break;
1055
1056 default:
1057 nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_ValueError,
1058 "unsupported format character '%c' (0x%x) at index %d",
1059 *str, *str, str - start_str));
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001060 }
Dave Hylands6756a372014-04-02 11:42:39 -07001061 arg_i++;
Paul Sokolovsky4db727a2014-03-31 21:18:28 +03001062 }
1063
1064 if (arg_i != n_args) {
1065 nlr_jump(mp_obj_new_exception_msg(&mp_type_TypeError, "not all arguments converted during string formatting"));
1066 }
1067
1068 mp_obj_t s = mp_obj_new_str((byte*)vstr->buf, vstr->len, false);
1069 vstr_free(vstr);
1070 return s;
1071}
1072
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001073STATIC mp_obj_t str_replace(uint n_args, const mp_obj_t *args) {
xbe480c15a2014-01-30 22:17:30 -08001074 assert(MP_OBJ_IS_STR(args[0]));
1075 assert(MP_OBJ_IS_STR(args[1]));
1076 assert(MP_OBJ_IS_STR(args[2]));
1077
Damien George94f68302014-01-31 23:45:12 +00001078 machine_int_t max_rep = 0;
xbe480c15a2014-01-30 22:17:30 -08001079 if (n_args == 4) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001080 assert(MP_OBJ_IS_SMALL_INT(args[3]));
1081 max_rep = MP_OBJ_SMALL_INT_VALUE(args[3]);
1082 if (max_rep == 0) {
1083 return args[0];
1084 } else if (max_rep < 0) {
1085 max_rep = 0;
1086 }
xbe480c15a2014-01-30 22:17:30 -08001087 }
Damien George94f68302014-01-31 23:45:12 +00001088
1089 // if max_rep is still 0 by this point we will need to do all possible replacements
xbe480c15a2014-01-30 22:17:30 -08001090
1091 GET_STR_DATA_LEN(args[0], str, str_len);
1092 GET_STR_DATA_LEN(args[1], old, old_len);
1093 GET_STR_DATA_LEN(args[2], new, new_len);
Damien George94f68302014-01-31 23:45:12 +00001094
1095 // old won't exist in str if it's longer, so nothing to replace
xbe480c15a2014-01-30 22:17:30 -08001096 if (old_len > str_len) {
Paul Sokolovsky4e246082014-02-11 15:29:55 +02001097 return args[0];
xbe480c15a2014-01-30 22:17:30 -08001098 }
1099
Damien George94f68302014-01-31 23:45:12 +00001100 // data for the replaced string
1101 byte *data = NULL;
1102 mp_obj_t replaced_str = MP_OBJ_NULL;
xbe480c15a2014-01-30 22:17:30 -08001103
Damien George94f68302014-01-31 23:45:12 +00001104 // do 2 passes over the string:
1105 // first pass computes the required length of the replaced string
1106 // second pass does the replacements
1107 for (;;) {
1108 machine_uint_t replaced_str_index = 0;
1109 machine_uint_t num_replacements_done = 0;
1110 const byte *old_occurrence;
1111 const byte *offset_ptr = str;
1112 machine_uint_t offset_num = 0;
xbe17a5a832014-03-23 23:31:58 -07001113 while ((old_occurrence = find_subbytes(offset_ptr, str_len - offset_num, old, old_len, 1)) != NULL) {
Damien George94f68302014-01-31 23:45:12 +00001114 // copy from just after end of last occurrence of to-be-replaced string to right before start of next occurrence
1115 if (data != NULL) {
1116 memcpy(data + replaced_str_index, offset_ptr, old_occurrence - offset_ptr);
1117 }
1118 replaced_str_index += old_occurrence - offset_ptr;
1119 // copy the replacement string
1120 if (data != NULL) {
1121 memcpy(data + replaced_str_index, new, new_len);
1122 }
1123 replaced_str_index += new_len;
1124 offset_ptr = old_occurrence + old_len;
1125 offset_num = offset_ptr - str;
xbe480c15a2014-01-30 22:17:30 -08001126
Damien George94f68302014-01-31 23:45:12 +00001127 num_replacements_done++;
1128 if (max_rep != 0 && num_replacements_done == max_rep){
1129 break;
1130 }
1131 }
1132
1133 // copy from just after end of last occurrence of to-be-replaced string to end of old string
1134 if (data != NULL) {
1135 memcpy(data + replaced_str_index, offset_ptr, str_len - offset_num);
1136 }
1137 replaced_str_index += str_len - offset_num;
1138
1139 if (data == NULL) {
1140 // first pass
1141 if (num_replacements_done == 0) {
1142 // no substr found, return original string
1143 return args[0];
1144 } else {
1145 // substr found, allocate new string
1146 replaced_str = mp_obj_str_builder_start(mp_obj_get_type(args[0]), replaced_str_index, &data);
1147 }
1148 } else {
1149 // second pass, we are done
1150 break;
1151 }
xbe480c15a2014-01-30 22:17:30 -08001152 }
Damien George94f68302014-01-31 23:45:12 +00001153
xbe480c15a2014-01-30 22:17:30 -08001154 return mp_obj_str_builder_end(replaced_str);
1155}
1156
xbe9e1e8cd2014-03-12 22:57:16 -07001157STATIC mp_obj_t str_count(uint n_args, const mp_obj_t *args) {
1158 assert(2 <= n_args && n_args <= 4);
1159 assert(MP_OBJ_IS_STR(args[0]));
1160 assert(MP_OBJ_IS_STR(args[1]));
1161
1162 GET_STR_DATA_LEN(args[0], haystack, haystack_len);
1163 GET_STR_DATA_LEN(args[1], needle, needle_len);
1164
Damien George536dde22014-03-13 22:07:55 +00001165 machine_uint_t start = 0;
1166 machine_uint_t end = haystack_len;
xbe9e1e8cd2014-03-12 22:57:16 -07001167 if (n_args >= 3 && args[2] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001168 start = mp_get_index(&mp_type_str, haystack_len, args[2], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001169 }
1170 if (n_args >= 4 && args[3] != mp_const_none) {
Damien George3e1a5c12014-03-29 13:43:38 +00001171 end = mp_get_index(&mp_type_str, haystack_len, args[3], true);
xbe9e1e8cd2014-03-12 22:57:16 -07001172 }
1173
Damien George536dde22014-03-13 22:07:55 +00001174 // if needle_len is zero then we count each gap between characters as an occurrence
1175 if (needle_len == 0) {
1176 return MP_OBJ_NEW_SMALL_INT(end - start + 1);
xbe9e1e8cd2014-03-12 22:57:16 -07001177 }
1178
Damien George536dde22014-03-13 22:07:55 +00001179 // count the occurrences
1180 machine_int_t num_occurrences = 0;
xbec5d70ba2014-03-13 00:29:15 -07001181 for (machine_uint_t haystack_index = start; haystack_index + needle_len <= end; haystack_index++) {
1182 if (memcmp(&haystack[haystack_index], needle, needle_len) == 0) {
1183 num_occurrences++;
1184 haystack_index += needle_len - 1;
1185 }
xbe9e1e8cd2014-03-12 22:57:16 -07001186 }
1187
1188 return MP_OBJ_NEW_SMALL_INT(num_occurrences);
1189}
1190
Damien Georgeb035db32014-03-21 20:39:40 +00001191STATIC mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, machine_int_t direction) {
xbe613a8e32014-03-18 00:06:29 -07001192 assert(MP_OBJ_IS_STR(self_in));
1193 if (!MP_OBJ_IS_STR(arg)) {
1194 nlr_jump(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
1195 "Can't convert '%s' object to str implicitly", mp_obj_get_type_str(arg)));
1196 }
Damien Georgeb035db32014-03-21 20:39:40 +00001197
xbe613a8e32014-03-18 00:06:29 -07001198 GET_STR_DATA_LEN(self_in, str, str_len);
1199 GET_STR_DATA_LEN(arg, sep, sep_len);
1200
1201 if (sep_len == 0) {
1202 nlr_jump(mp_obj_new_exception_msg(&mp_type_ValueError, "empty separator"));
1203 }
Damien Georgeb035db32014-03-21 20:39:40 +00001204
1205 mp_obj_t result[] = {MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_), MP_OBJ_NEW_QSTR(MP_QSTR_)};
1206
1207 if (direction > 0) {
1208 result[0] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001209 } else {
Damien Georgeb035db32014-03-21 20:39:40 +00001210 result[2] = self_in;
xbe0a6894c2014-03-21 01:12:26 -07001211 }
xbe613a8e32014-03-18 00:06:29 -07001212
xbe17a5a832014-03-23 23:31:58 -07001213 const byte *position_ptr = find_subbytes(str, str_len, sep, sep_len, direction);
1214 if (position_ptr != NULL) {
1215 machine_uint_t position = position_ptr - str;
1216 result[0] = mp_obj_new_str(str, position, false);
1217 result[1] = arg;
1218 result[2] = mp_obj_new_str(str + position + sep_len, str_len - position - sep_len, false);
xbe613a8e32014-03-18 00:06:29 -07001219 }
Damien Georgeb035db32014-03-21 20:39:40 +00001220
xbe0a6894c2014-03-21 01:12:26 -07001221 return mp_obj_new_tuple(3, result);
xbe613a8e32014-03-18 00:06:29 -07001222}
1223
Damien Georgeb035db32014-03-21 20:39:40 +00001224STATIC mp_obj_t str_partition(mp_obj_t self_in, mp_obj_t arg) {
1225 return str_partitioner(self_in, arg, 1);
xbe0a6894c2014-03-21 01:12:26 -07001226}
xbe4504ea82014-03-19 00:46:14 -07001227
Damien Georgeb035db32014-03-21 20:39:40 +00001228STATIC mp_obj_t str_rpartition(mp_obj_t self_in, mp_obj_t arg) {
1229 return str_partitioner(self_in, arg, -1);
xbe4504ea82014-03-19 00:46:14 -07001230}
1231
Damien George2da98302014-03-09 19:58:18 +00001232STATIC machine_int_t str_get_buffer(mp_obj_t self_in, buffer_info_t *bufinfo, int flags) {
1233 if (flags == BUFFER_READ) {
1234 GET_STR_DATA_LEN(self_in, str_data, str_len);
1235 bufinfo->buf = (void*)str_data;
1236 bufinfo->len = str_len;
1237 return 0;
1238 } else {
1239 // can't write to a string
1240 bufinfo->buf = NULL;
1241 bufinfo->len = 0;
1242 return 1;
1243 }
1244}
1245
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001246STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_find_obj, 2, 4, str_find);
xbe17a5a832014-03-23 23:31:58 -07001247STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rfind_obj, 2, 4, str_rfind);
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001248STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_join_obj, str_join);
1249STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_split_obj, 1, 3, str_split);
1250STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_startswith_obj, str_startswith);
1251STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_strip_obj, 1, 2, str_strip);
1252STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(str_format_obj, 1, str_format);
1253STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_replace_obj, 3, 4, str_replace);
xbe9e1e8cd2014-03-12 22:57:16 -07001254STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_count_obj, 2, 4, str_count);
xbe613a8e32014-03-18 00:06:29 -07001255STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_partition_obj, str_partition);
xbe4504ea82014-03-19 00:46:14 -07001256STATIC MP_DEFINE_CONST_FUN_OBJ_2(str_rpartition_obj, str_rpartition);
Damiend99b0522013-12-21 18:17:45 +00001257
Damien George9b196cd2014-03-26 21:47:19 +00001258STATIC const mp_map_elem_t str_locals_dict_table[] = {
1259 { MP_OBJ_NEW_QSTR(MP_QSTR_find), (mp_obj_t)&str_find_obj },
1260 { MP_OBJ_NEW_QSTR(MP_QSTR_rfind), (mp_obj_t)&str_rfind_obj },
1261 { MP_OBJ_NEW_QSTR(MP_QSTR_join), (mp_obj_t)&str_join_obj },
1262 { MP_OBJ_NEW_QSTR(MP_QSTR_split), (mp_obj_t)&str_split_obj },
1263 { MP_OBJ_NEW_QSTR(MP_QSTR_startswith), (mp_obj_t)&str_startswith_obj },
1264 { MP_OBJ_NEW_QSTR(MP_QSTR_strip), (mp_obj_t)&str_strip_obj },
1265 { MP_OBJ_NEW_QSTR(MP_QSTR_format), (mp_obj_t)&str_format_obj },
1266 { MP_OBJ_NEW_QSTR(MP_QSTR_replace), (mp_obj_t)&str_replace_obj },
1267 { MP_OBJ_NEW_QSTR(MP_QSTR_count), (mp_obj_t)&str_count_obj },
1268 { MP_OBJ_NEW_QSTR(MP_QSTR_partition), (mp_obj_t)&str_partition_obj },
1269 { MP_OBJ_NEW_QSTR(MP_QSTR_rpartition), (mp_obj_t)&str_rpartition_obj },
ian-v7a16fad2014-01-06 09:52:29 -08001270};
Damien George97209d32014-01-07 15:58:30 +00001271
Damien George9b196cd2014-03-26 21:47:19 +00001272STATIC MP_DEFINE_CONST_DICT(str_locals_dict, str_locals_dict_table);
1273
Damien George3e1a5c12014-03-29 13:43:38 +00001274const mp_obj_type_t mp_type_str = {
Damien Georgec5966122014-02-15 16:10:44 +00001275 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001276 .name = MP_QSTR_str,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001277 .print = str_print,
Paul Sokolovskybe020c22014-03-21 11:39:01 +02001278 .make_new = str_make_new,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001279 .binary_op = str_binary_op,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001280 .getiter = mp_obj_new_str_iterator,
Damien George2da98302014-03-09 19:58:18 +00001281 .buffer_p = { .get_buffer = str_get_buffer },
Damien George9b196cd2014-03-26 21:47:19 +00001282 .locals_dict = (mp_obj_t)&str_locals_dict,
Damiend99b0522013-12-21 18:17:45 +00001283};
1284
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001285// Reuses most of methods from str
Damien George3e1a5c12014-03-29 13:43:38 +00001286const mp_obj_type_t mp_type_bytes = {
Damien Georgec5966122014-02-15 16:10:44 +00001287 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001288 .name = MP_QSTR_bytes,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001289 .print = str_print,
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001290 .make_new = bytes_make_new,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001291 .binary_op = str_binary_op,
1292 .getiter = mp_obj_new_bytes_iterator,
Damien George9b196cd2014-03-26 21:47:19 +00001293 .locals_dict = (mp_obj_t)&str_locals_dict,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001294};
1295
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001296// the zero-length bytes
Damien George3e1a5c12014-03-29 13:43:38 +00001297STATIC const mp_obj_str_t empty_bytes_obj = {{&mp_type_bytes}, 0, 0, NULL};
Paul Sokolovsky1ecea7c2014-03-21 23:46:59 +02001298const mp_obj_t mp_const_empty_bytes = (mp_obj_t)&empty_bytes_obj;
1299
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001300mp_obj_t mp_obj_str_builder_start(const mp_obj_type_t *type, uint len, byte **data) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001301 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001302 o->base.type = type;
Damien George5fa93b62014-01-22 14:35:10 +00001303 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001304 byte *p = m_new(byte, len + 1);
1305 o->data = p;
1306 *data = p;
Damiend99b0522013-12-21 18:17:45 +00001307 return o;
1308}
1309
Damien George5fa93b62014-01-22 14:35:10 +00001310mp_obj_t mp_obj_str_builder_end(mp_obj_t o_in) {
Damien George5fa93b62014-01-22 14:35:10 +00001311 mp_obj_str_t *o = o_in;
1312 o->hash = qstr_compute_hash(o->data, o->len);
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001313 byte *p = (byte*)o->data;
1314 p[o->len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
Damien George5fa93b62014-01-22 14:35:10 +00001315 return o;
1316}
1317
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001318STATIC mp_obj_t str_new(const mp_obj_type_t *type, const byte* data, uint len) {
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001319 mp_obj_str_t *o = m_new_obj(mp_obj_str_t);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001320 o->base.type = type;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001321 o->len = len;
Paul Sokolovsky5972b4c2014-03-20 16:47:44 +02001322 if (data) {
1323 o->hash = qstr_compute_hash(data, len);
1324 byte *p = m_new(byte, len + 1);
1325 o->data = p;
1326 memcpy(p, data, len * sizeof(byte));
1327 p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings
1328 }
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001329 return o;
1330}
1331
Damien George5fa93b62014-01-22 14:35:10 +00001332mp_obj_t mp_obj_new_str(const byte* data, uint len, bool make_qstr_if_not_already) {
1333 qstr q = qstr_find_strn(data, len);
1334 if (q != MP_QSTR_NULL) {
1335 // qstr with this data already exists
1336 return MP_OBJ_NEW_QSTR(q);
1337 } else if (make_qstr_if_not_already) {
1338 // no existing qstr, make a new one
1339 return MP_OBJ_NEW_QSTR(qstr_from_strn((const char*)data, len));
1340 } else {
1341 // no existing qstr, don't make one
Damien George3e1a5c12014-03-29 13:43:38 +00001342 return str_new(&mp_type_str, data, len);
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001343 }
Damien George5fa93b62014-01-22 14:35:10 +00001344}
1345
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001346mp_obj_t mp_obj_new_bytes(const byte* data, uint len) {
Damien George3e1a5c12014-03-29 13:43:38 +00001347 return str_new(&mp_type_bytes, data, len);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001348}
1349
Damien George5fa93b62014-01-22 14:35:10 +00001350bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) {
1351 if (MP_OBJ_IS_QSTR(s1) && MP_OBJ_IS_QSTR(s2)) {
1352 return s1 == s2;
1353 } else {
1354 GET_STR_HASH(s1, h1);
1355 GET_STR_HASH(s2, h2);
1356 if (h1 != h2) {
1357 return false;
1358 }
1359 GET_STR_DATA_LEN(s1, d1, l1);
1360 GET_STR_DATA_LEN(s2, d2, l2);
1361 if (l1 != l2) {
1362 return false;
1363 }
Damien George1e708fe2014-01-23 18:27:51 +00001364 return memcmp(d1, d2, l1) == 0;
Paul Sokolovsky8965a5e2014-01-20 23:33:19 +02001365 }
Damien George5fa93b62014-01-22 14:35:10 +00001366}
1367
Damien Georgeb829b5c2014-01-25 13:51:19 +00001368void bad_implicit_conversion(mp_obj_t self_in) __attribute__((noreturn));
1369void bad_implicit_conversion(mp_obj_t self_in) {
Damien Georgec5966122014-02-15 16:10:44 +00001370 nlr_jump(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 +00001371}
1372
Damien George5fa93b62014-01-22 14:35:10 +00001373uint mp_obj_str_get_hash(mp_obj_t self_in) {
1374 if (MP_OBJ_IS_STR(self_in)) {
1375 GET_STR_HASH(self_in, h);
1376 return h;
1377 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001378 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001379 }
1380}
1381
1382uint mp_obj_str_get_len(mp_obj_t self_in) {
1383 if (MP_OBJ_IS_STR(self_in)) {
1384 GET_STR_LEN(self_in, l);
1385 return l;
1386 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001387 bad_implicit_conversion(self_in);
1388 }
1389}
1390
1391// use this if you will anyway convert the string to a qstr
1392// will be more efficient for the case where it's already a qstr
1393qstr mp_obj_str_get_qstr(mp_obj_t self_in) {
1394 if (MP_OBJ_IS_QSTR(self_in)) {
1395 return MP_OBJ_QSTR_VALUE(self_in);
Damien George3e1a5c12014-03-29 13:43:38 +00001396 } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001397 mp_obj_str_t *self = self_in;
1398 return qstr_from_strn((char*)self->data, self->len);
1399 } else {
1400 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001401 }
1402}
1403
1404// only use this function if you need the str data to be zero terminated
1405// at the moment all strings are zero terminated to help with C ASCIIZ compatibility
1406const char *mp_obj_str_get_str(mp_obj_t self_in) {
1407 if (MP_OBJ_IS_STR(self_in)) {
1408 GET_STR_DATA_LEN(self_in, s, l);
1409 (void)l; // len unused
1410 return (const char*)s;
1411 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001412 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001413 }
1414}
1415
Damien George698ec212014-02-08 18:17:23 +00001416const char *mp_obj_str_get_data(mp_obj_t self_in, uint *len) {
Damien George5fa93b62014-01-22 14:35:10 +00001417 if (MP_OBJ_IS_STR(self_in)) {
1418 GET_STR_DATA_LEN(self_in, s, l);
1419 *len = l;
Damien George698ec212014-02-08 18:17:23 +00001420 return (const char*)s;
Damien George5fa93b62014-01-22 14:35:10 +00001421 } else {
Damien Georgeb829b5c2014-01-25 13:51:19 +00001422 bad_implicit_conversion(self_in);
Damien George5fa93b62014-01-22 14:35:10 +00001423 }
Damiend99b0522013-12-21 18:17:45 +00001424}
xyb8cfc9f02014-01-05 18:47:51 +08001425
1426/******************************************************************************/
1427/* str iterator */
1428
1429typedef struct _mp_obj_str_it_t {
1430 mp_obj_base_t base;
Damien George5fa93b62014-01-22 14:35:10 +00001431 mp_obj_t str;
xyb8cfc9f02014-01-05 18:47:51 +08001432 machine_uint_t cur;
1433} mp_obj_str_it_t;
1434
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001435STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) {
xyb8cfc9f02014-01-05 18:47:51 +08001436 mp_obj_str_it_t *self = self_in;
Damien George5fa93b62014-01-22 14:35:10 +00001437 GET_STR_DATA_LEN(self->str, str, len);
1438 if (self->cur < len) {
1439 mp_obj_t o_out = mp_obj_new_str(str + self->cur, 1, true);
xyb8cfc9f02014-01-05 18:47:51 +08001440 self->cur += 1;
1441 return o_out;
1442 } else {
Damien George66eaf842014-03-26 19:27:58 +00001443 return MP_OBJ_NULL;
xyb8cfc9f02014-01-05 18:47:51 +08001444 }
1445}
1446
Damien George3e1a5c12014-03-29 13:43:38 +00001447STATIC const mp_obj_type_t mp_type_str_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001448 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001449 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001450 .getiter = mp_identity,
Paul Sokolovsky860ffb02014-01-05 22:34:09 +02001451 .iternext = str_it_iternext,
xyb8cfc9f02014-01-05 18:47:51 +08001452};
1453
Paul Sokolovskyd5df6cd2014-02-12 18:15:40 +02001454STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) {
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001455 mp_obj_str_it_t *self = self_in;
1456 GET_STR_DATA_LEN(self->str, str, len);
1457 if (self->cur < len) {
Damien George7c9c6672014-01-25 00:17:36 +00001458 mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT((mp_small_int_t)str[self->cur]);
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001459 self->cur += 1;
1460 return o_out;
1461 } else {
Damien George66eaf842014-03-26 19:27:58 +00001462 return MP_OBJ_NULL;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001463 }
1464}
1465
Damien George3e1a5c12014-03-29 13:43:38 +00001466STATIC const mp_obj_type_t mp_type_bytes_it = {
Damien Georgec5966122014-02-15 16:10:44 +00001467 { &mp_type_type },
Damien Georgea71c83a2014-02-15 11:34:50 +00001468 .name = MP_QSTR_iterator,
Paul Sokolovskyf7eaf602014-03-30 22:00:12 +03001469 .getiter = mp_identity,
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001470 .iternext = bytes_it_iternext,
1471};
1472
1473mp_obj_t mp_obj_new_str_iterator(mp_obj_t str) {
xyb8cfc9f02014-01-05 18:47:51 +08001474 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001475 o->base.type = &mp_type_str_it;
xyb8cfc9f02014-01-05 18:47:51 +08001476 o->str = str;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001477 o->cur = 0;
1478 return o;
1479}
1480
1481mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str) {
1482 mp_obj_str_it_t *o = m_new_obj(mp_obj_str_it_t);
Damien George3e1a5c12014-03-29 13:43:38 +00001483 o->base.type = &mp_type_bytes_it;
Paul Sokolovsky91fb1c92014-01-24 22:50:40 +02001484 o->str = str;
1485 o->cur = 0;
xyb8cfc9f02014-01-05 18:47:51 +08001486 return o;
1487}