summaryrefslogtreecommitdiffstatshomepage
path: root/py/objstr.c
diff options
context:
space:
mode:
authorDamien George <damien.p.george@gmail.com>2014-01-03 17:03:19 -0800
committerDamien George <damien.p.george@gmail.com>2014-01-03 17:03:19 -0800
commitb95d90b2f37e00a39a7cca46c24c9d496bb1e342 (patch)
treedee120c28b998e528b1ba9f7a72d7dee2df7e12f /py/objstr.c
parent9ba9589ef71920132cd6ec5c3a948e9c605b50f7 (diff)
parentf8b9d3c41addea79851c355f014db9f0f256cdaf (diff)
downloadmicropython-b95d90b2f37e00a39a7cca46c24c9d496bb1e342.tar.gz
micropython-b95d90b2f37e00a39a7cca46c24c9d496bb1e342.zip
Merge pull request #59 from pfalcon/slice
Implement basic slice object and string slicing
Diffstat (limited to 'py/objstr.c')
-rw-r--r--py/objstr.c28
1 files changed, 25 insertions, 3 deletions
diff --git a/py/objstr.c b/py/objstr.c
index 48abf4951d..6a0721d45f 100644
--- a/py/objstr.c
+++ b/py/objstr.c
@@ -27,9 +27,31 @@ mp_obj_t str_binary_op(int op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
const char *lhs_str = qstr_str(lhs->qstr);
switch (op) {
case RT_BINARY_OP_SUBSCR:
- // string access
- // XXX a massive hack!
- return mp_obj_new_int(lhs_str[mp_obj_get_int(rhs_in)]);
+ // TODO: need predicate to check for int-like type (bools are such for example)
+ // ["no", "yes"][1 == 2] is common idiom
+ if (MP_OBJ_IS_SMALL_INT(rhs_in)) {
+ // TODO: This implements byte string access for single index so far
+ // TODO: Handle negative indexes.
+ return mp_obj_new_int(lhs_str[mp_obj_get_int(rhs_in)]);
+#if MICROPY_ENABLE_SLICE
+ } else if (MP_OBJ_IS_TYPE(rhs_in, &slice_type)) {
+ int start, stop, step;
+ mp_obj_slice_get(rhs_in, &start, &stop, &step);
+ assert(step == 1);
+ int len = strlen(lhs_str);
+ if (start < 0) {
+ start = len + start;
+ }
+ if (stop <= 0) {
+ stop = len + stop;
+ }
+ return mp_obj_new_str(qstr_from_strn_copy(lhs_str + start, stop - start));
+#endif
+ } else {
+ // Message doesn't match CPython, but we don't have so much bytes as they
+ // to spend them on verbose wording
+ nlr_jump(mp_obj_new_exception_msg(rt_q_TypeError, "index must be int"));
+ }
case RT_BINARY_OP_ADD:
case RT_BINARY_OP_INPLACE_ADD: