|
| 1 | +#include <stdlib.h> |
| 2 | +#include <stdint.h> |
| 3 | +#include <string.h> |
| 4 | +#include <assert.h> |
| 5 | + |
| 6 | +#include "nlr.h" |
| 7 | +#include "misc.h" |
| 8 | +#include "mpconfig.h" |
| 9 | +#include "obj.h" |
| 10 | +#include "runtime0.h" |
| 11 | + |
| 12 | +#if MICROPY_ENABLE_SLICE |
| 13 | + |
| 14 | +// TODO: This implements only variant of slice with 2 integer args only. |
| 15 | +// CPython supports 3rd arg (step), plus args can be arbitrary Python objects. |
| 16 | +typedef struct _mp_obj_slice_t { |
| 17 | + mp_obj_base_t base; |
| 18 | + machine_int_t start; |
| 19 | + machine_int_t stop; |
| 20 | +} mp_obj_slice_t; |
| 21 | + |
| 22 | +void slice_print(void (*print)(void *env, const char *fmt, ...), void *env, mp_obj_t o_in) { |
| 23 | + mp_obj_slice_t *o = o_in; |
| 24 | + print(env, "slice(" INT_FMT ", " INT_FMT ")", o->start, o->stop); |
| 25 | +} |
| 26 | + |
| 27 | +const mp_obj_type_t slice_type = { |
| 28 | + { &mp_const_type }, |
| 29 | + "slice", |
| 30 | + slice_print, |
| 31 | + NULL, // call_n |
| 32 | + NULL, // unary_op |
| 33 | + NULL, // binary_op |
| 34 | + NULL, // getiter |
| 35 | + NULL, // iternext |
| 36 | + { { NULL, NULL }, }, // method list |
| 37 | +}; |
| 38 | + |
| 39 | +// TODO: Make sure to handle "empty" values, which are signified by None in CPython |
| 40 | +mp_obj_t mp_obj_new_slice(mp_obj_t ostart, mp_obj_t ostop, mp_obj_t ostep) { |
| 41 | + assert(ostep == NULL); |
| 42 | + machine_int_t start = 0, stop = 0; |
| 43 | + if (ostart != mp_const_none) { |
| 44 | + start = mp_obj_get_int(ostart); |
| 45 | + } |
| 46 | + if (ostop != mp_const_none) { |
| 47 | + stop = mp_obj_get_int(ostop); |
| 48 | + if (stop == 0) { |
| 49 | + // [x:0] is a special case - in our slice object, stop = 0 means |
| 50 | + // "end of sequence". Fortunately, [x:0] is an empty seqence for |
| 51 | + // any x (including negative). [x:x] is also always empty sequence. |
| 52 | + // but x also can be 0. But note that b""[x:x] is b"" for any x (i.e. |
| 53 | + // no IndexError, at least in Python 3.3.3). So, we just use -1's to |
| 54 | + // signify that. -1 is catchy "special" number in case someone will |
| 55 | + // try to print [x:0] slice ever. |
| 56 | + start = stop = -1; |
| 57 | + } |
| 58 | + } |
| 59 | + mp_obj_slice_t *o = m_new(mp_obj_slice_t, 1); |
| 60 | + o->base.type = &slice_type; |
| 61 | + o->start = start; |
| 62 | + o->stop = stop; |
| 63 | + return (mp_obj_t)o; |
| 64 | +} |
| 65 | + |
| 66 | +void mp_obj_slice_get(mp_obj_t self_in, machine_int_t *start, machine_int_t *stop, machine_int_t *step) { |
| 67 | + assert(MP_OBJ_IS_TYPE(self_in, &slice_type)); |
| 68 | + mp_obj_slice_t *self = self_in; |
| 69 | + *start = self->start; |
| 70 | + *stop = self->stop; |
| 71 | + *step = 1; |
| 72 | +} |
| 73 | + |
| 74 | +#endif |
0 commit comments