objarray.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2013, 2014 Damien P. George
  7. * Copyright (c) 2014 Paul Sokolovsky
  8. *
  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. #include <string.h>
  28. #include <assert.h>
  29. #include <stdint.h>
  30. #include "py/runtime.h"
  31. #include "py/binary.h"
  32. #include "py/objstr.h"
  33. #include "py/objarray.h"
  34. #if MICROPY_PY_ARRAY || MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_BUILTINS_MEMORYVIEW
  35. // About memoryview object: We want to reuse as much code as possible from
  36. // array, and keep the memoryview object 4 words in size so it fits in 1 GC
  37. // block. Also, memoryview must keep a pointer to the base of the buffer so
  38. // that the buffer is not GC'd if the original parent object is no longer
  39. // around (we are assuming that all memoryview'able objects return a pointer
  40. // which points to the start of a GC chunk). Given the above constraints we
  41. // do the following:
  42. // - typecode high bit is set if the buffer is read-write (else read-only)
  43. // - free is the offset in elements to the first item in the memoryview
  44. // - len is the length in elements
  45. // - items points to the start of the original buffer
  46. // Note that we don't handle the case where the original buffer might change
  47. // size due to a resize of the original parent object.
  48. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  49. #define TYPECODE_MASK (0x7f)
  50. #define memview_offset free
  51. #define memview_offset_max ((1LL << MP_OBJ_ARRAY_FREE_SIZE_BITS) - 1)
  52. #else
  53. // make (& TYPECODE_MASK) a null operation if memorview not enabled
  54. #define TYPECODE_MASK (~(size_t)0)
  55. // memview_offset should not be accessed if memoryview is not enabled,
  56. // so not defined to catch errors
  57. #endif
  58. static mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf);
  59. static mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg);
  60. static mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in);
  61. static mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_uint_t flags);
  62. /******************************************************************************/
  63. // array
  64. #if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY
  65. static void array_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) {
  66. (void)kind;
  67. mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in);
  68. if (o->typecode == BYTEARRAY_TYPECODE) {
  69. mp_print_str(print, "bytearray(b");
  70. mp_str_print_quoted(print, o->items, o->len, true);
  71. } else {
  72. mp_printf(print, "array('%c'", o->typecode);
  73. if (o->len > 0) {
  74. mp_print_str(print, ", [");
  75. for (size_t i = 0; i < o->len; i++) {
  76. if (i > 0) {
  77. mp_print_str(print, ", ");
  78. }
  79. mp_obj_print_helper(print, mp_binary_get_val_array(o->typecode, o->items, i), PRINT_REPR);
  80. }
  81. mp_print_str(print, "]");
  82. }
  83. }
  84. mp_print_str(print, ")");
  85. }
  86. #endif
  87. #if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY
  88. static mp_obj_array_t *array_new(char typecode, size_t n) {
  89. int typecode_size = mp_binary_get_size('@', typecode, NULL);
  90. mp_obj_array_t *o = m_new_obj(mp_obj_array_t);
  91. #if MICROPY_PY_BUILTINS_BYTEARRAY && MICROPY_PY_ARRAY
  92. o->base.type = (typecode == BYTEARRAY_TYPECODE) ? &mp_type_bytearray : &mp_type_array;
  93. #elif MICROPY_PY_BUILTINS_BYTEARRAY
  94. o->base.type = &mp_type_bytearray;
  95. #else
  96. o->base.type = &mp_type_array;
  97. #endif
  98. o->typecode = typecode;
  99. o->free = 0;
  100. o->len = n;
  101. o->items = m_new(byte, typecode_size * o->len);
  102. return o;
  103. }
  104. #endif
  105. #if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY
  106. static mp_obj_t array_construct(char typecode, mp_obj_t initializer) {
  107. // bytearrays can be raw-initialised from anything with the buffer protocol
  108. // other arrays can only be raw-initialised from bytes and bytearray objects
  109. mp_buffer_info_t bufinfo;
  110. if (((MICROPY_PY_BUILTINS_BYTEARRAY
  111. && typecode == BYTEARRAY_TYPECODE)
  112. || (MICROPY_PY_ARRAY
  113. && (mp_obj_is_type(initializer, &mp_type_bytes)
  114. || (MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(initializer, &mp_type_bytearray)))))
  115. && mp_get_buffer(initializer, &bufinfo, MP_BUFFER_READ)) {
  116. // construct array from raw bytes
  117. // we round-down the len to make it a multiple of sz (CPython raises error)
  118. size_t sz = mp_binary_get_size('@', typecode, NULL);
  119. size_t len = bufinfo.len / sz;
  120. mp_obj_array_t *o = array_new(typecode, len);
  121. memcpy(o->items, bufinfo.buf, len * sz);
  122. return MP_OBJ_FROM_PTR(o);
  123. }
  124. size_t len;
  125. // Try to create array of exact len if initializer len is known
  126. mp_obj_t len_in = mp_obj_len_maybe(initializer);
  127. if (len_in == MP_OBJ_NULL) {
  128. len = 0;
  129. } else {
  130. len = MP_OBJ_SMALL_INT_VALUE(len_in);
  131. }
  132. mp_obj_array_t *array = array_new(typecode, len);
  133. mp_obj_t iterable = mp_getiter(initializer, NULL);
  134. mp_obj_t item;
  135. size_t i = 0;
  136. while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) {
  137. if (len == 0) {
  138. array_append(MP_OBJ_FROM_PTR(array), item);
  139. } else {
  140. mp_binary_set_val_array(typecode, array->items, i++, item);
  141. }
  142. }
  143. return MP_OBJ_FROM_PTR(array);
  144. }
  145. #endif
  146. #if MICROPY_PY_ARRAY
  147. static mp_obj_t array_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  148. (void)type_in;
  149. mp_arg_check_num(n_args, n_kw, 1, 2, false);
  150. // get typecode
  151. const char *typecode = mp_obj_str_get_str(args[0]);
  152. if (n_args == 1) {
  153. // 1 arg: make an empty array
  154. return MP_OBJ_FROM_PTR(array_new(*typecode, 0));
  155. } else {
  156. // 2 args: construct the array from the given object
  157. return array_construct(*typecode, args[1]);
  158. }
  159. }
  160. #endif
  161. #if MICROPY_PY_BUILTINS_BYTEARRAY
  162. static mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  163. (void)type_in;
  164. // Can take 2nd/3rd arg if constructs from str
  165. mp_arg_check_num(n_args, n_kw, 0, 3, false);
  166. if (n_args == 0) {
  167. // no args: construct an empty bytearray
  168. return MP_OBJ_FROM_PTR(array_new(BYTEARRAY_TYPECODE, 0));
  169. } else if (mp_obj_is_int(args[0])) {
  170. // 1 arg, an integer: construct a blank bytearray of that length
  171. mp_uint_t len = mp_obj_get_int(args[0]);
  172. mp_obj_array_t *o = array_new(BYTEARRAY_TYPECODE, len);
  173. memset(o->items, 0, len);
  174. return MP_OBJ_FROM_PTR(o);
  175. } else {
  176. // 1 arg: construct the bytearray from that
  177. if (mp_obj_is_str(args[0]) && n_args == 1) {
  178. #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE
  179. // Match bytes_make_new.
  180. mp_raise_TypeError(MP_ERROR_TEXT("wrong number of arguments"));
  181. #else
  182. mp_raise_TypeError(MP_ERROR_TEXT("string argument without an encoding"));
  183. #endif
  184. }
  185. return array_construct(BYTEARRAY_TYPECODE, args[0]);
  186. }
  187. }
  188. #endif
  189. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  190. mp_obj_t mp_obj_new_memoryview(byte typecode, size_t nitems, void *items) {
  191. mp_obj_array_t *self = m_new_obj(mp_obj_array_t);
  192. mp_obj_memoryview_init(self, typecode, 0, nitems, items);
  193. return MP_OBJ_FROM_PTR(self);
  194. }
  195. static mp_obj_t memoryview_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  196. (void)type_in;
  197. // TODO possibly allow memoryview constructor to take start/stop so that one
  198. // can do memoryview(b, 4, 8) instead of memoryview(b)[4:8] (uses less RAM)
  199. mp_arg_check_num(n_args, n_kw, 1, 1, false);
  200. mp_buffer_info_t bufinfo;
  201. mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
  202. mp_obj_array_t *self = MP_OBJ_TO_PTR(mp_obj_new_memoryview(bufinfo.typecode,
  203. bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL),
  204. bufinfo.buf));
  205. // If the input object is a memoryview then need to point the items of the
  206. // new memoryview to the start of the buffer so the GC can trace it.
  207. if (mp_obj_get_type(args[0]) == &mp_type_memoryview) {
  208. mp_obj_array_t *other = MP_OBJ_TO_PTR(args[0]);
  209. self->memview_offset = other->memview_offset;
  210. self->items = other->items;
  211. }
  212. // test if the object can be written to
  213. if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_RW)) {
  214. self->typecode |= MP_OBJ_ARRAY_TYPECODE_FLAG_RW; // indicate writable buffer
  215. }
  216. return MP_OBJ_FROM_PTR(self);
  217. }
  218. #if MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZE
  219. static void memoryview_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
  220. if (dest[0] != MP_OBJ_NULL) {
  221. return;
  222. }
  223. if (attr == MP_QSTR_itemsize) {
  224. mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in);
  225. dest[0] = MP_OBJ_NEW_SMALL_INT(mp_binary_get_size('@', self->typecode & TYPECODE_MASK, NULL));
  226. }
  227. #if MICROPY_PY_BUILTINS_BYTES_HEX
  228. else {
  229. // Need to forward to locals dict.
  230. dest[1] = MP_OBJ_SENTINEL;
  231. }
  232. #endif
  233. }
  234. #endif
  235. #endif
  236. static mp_obj_t array_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
  237. mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in);
  238. switch (op) {
  239. case MP_UNARY_OP_BOOL:
  240. return mp_obj_new_bool(o->len != 0);
  241. case MP_UNARY_OP_LEN:
  242. return MP_OBJ_NEW_SMALL_INT(o->len);
  243. default:
  244. return MP_OBJ_NULL; // op not supported
  245. }
  246. }
  247. static int typecode_for_comparison(int typecode, bool *is_unsigned) {
  248. if (typecode == BYTEARRAY_TYPECODE) {
  249. typecode = 'B';
  250. }
  251. if (typecode <= 'Z') {
  252. typecode += 32; // to lowercase
  253. *is_unsigned = true;
  254. }
  255. return typecode;
  256. }
  257. static mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) {
  258. mp_obj_array_t *lhs = MP_OBJ_TO_PTR(lhs_in);
  259. switch (op) {
  260. case MP_BINARY_OP_ADD: {
  261. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  262. if (lhs->base.type == &mp_type_memoryview) {
  263. return MP_OBJ_NULL; // op not supported
  264. }
  265. #endif
  266. // allow to add anything that has the buffer protocol (extension to CPython)
  267. mp_buffer_info_t lhs_bufinfo;
  268. mp_buffer_info_t rhs_bufinfo;
  269. array_get_buffer(lhs_in, &lhs_bufinfo, MP_BUFFER_READ);
  270. mp_get_buffer_raise(rhs_in, &rhs_bufinfo, MP_BUFFER_READ);
  271. size_t sz = mp_binary_get_size('@', lhs_bufinfo.typecode, NULL);
  272. // convert byte count to element count (in case rhs is not multiple of sz)
  273. size_t rhs_len = rhs_bufinfo.len / sz;
  274. // note: lhs->len is element count of lhs, lhs_bufinfo.len is byte count
  275. mp_obj_array_t *res = array_new(lhs_bufinfo.typecode, lhs->len + rhs_len);
  276. mp_seq_cat((byte *)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte);
  277. return MP_OBJ_FROM_PTR(res);
  278. }
  279. case MP_BINARY_OP_INPLACE_ADD: {
  280. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  281. if (lhs->base.type == &mp_type_memoryview) {
  282. return MP_OBJ_NULL; // op not supported
  283. }
  284. #endif
  285. array_extend(lhs_in, rhs_in);
  286. return lhs_in;
  287. }
  288. case MP_BINARY_OP_CONTAINS: {
  289. #if MICROPY_PY_BUILTINS_BYTEARRAY
  290. // Can search string only in bytearray
  291. mp_buffer_info_t lhs_bufinfo;
  292. mp_buffer_info_t rhs_bufinfo;
  293. if (mp_get_buffer(rhs_in, &rhs_bufinfo, MP_BUFFER_READ)) {
  294. if (!mp_obj_is_type(lhs_in, &mp_type_bytearray)) {
  295. return mp_const_false;
  296. }
  297. array_get_buffer(lhs_in, &lhs_bufinfo, MP_BUFFER_READ);
  298. return mp_obj_new_bool(
  299. find_subbytes(lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_bufinfo.len, 1) != NULL);
  300. }
  301. #endif
  302. // Otherwise, can only look for a scalar numeric value in an array
  303. if (mp_obj_is_int(rhs_in) || mp_obj_is_float(rhs_in)) {
  304. mp_raise_NotImplementedError(NULL);
  305. }
  306. return mp_const_false;
  307. }
  308. case MP_BINARY_OP_EQUAL:
  309. case MP_BINARY_OP_LESS:
  310. case MP_BINARY_OP_LESS_EQUAL:
  311. case MP_BINARY_OP_MORE:
  312. case MP_BINARY_OP_MORE_EQUAL: {
  313. mp_buffer_info_t lhs_bufinfo;
  314. mp_buffer_info_t rhs_bufinfo;
  315. array_get_buffer(lhs_in, &lhs_bufinfo, MP_BUFFER_READ);
  316. if (!mp_get_buffer(rhs_in, &rhs_bufinfo, MP_BUFFER_READ)) {
  317. return mp_const_false;
  318. }
  319. // mp_seq_cmp_bytes is used so only compatible representations can be correctly compared.
  320. // The type doesn't matter: array/bytearray/str/bytes all have the same buffer layout, so
  321. // just check if the typecodes are compatible; for testing equality the types should have the
  322. // same code except for signedness, and not be floating point because nan never equals nan.
  323. // For > and < the types should be the same and unsigned.
  324. // Note that typecode_for_comparison always returns lowercase letters to save code size.
  325. // No need for (& TYPECODE_MASK) here: xxx_get_buffer already takes care of that.
  326. bool is_unsigned = false;
  327. const int lhs_code = typecode_for_comparison(lhs_bufinfo.typecode, &is_unsigned);
  328. const int rhs_code = typecode_for_comparison(rhs_bufinfo.typecode, &is_unsigned);
  329. if (lhs_code == rhs_code && lhs_code != 'f' && lhs_code != 'd' && (op == MP_BINARY_OP_EQUAL || is_unsigned)) {
  330. return mp_obj_new_bool(mp_seq_cmp_bytes(op, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_bufinfo.len));
  331. }
  332. // mp_obj_equal_not_equal treats returning MP_OBJ_NULL as 'fall back to pointer comparison'
  333. // for MP_BINARY_OP_EQUAL but that is incompatible with CPython.
  334. mp_raise_NotImplementedError(NULL);
  335. }
  336. default:
  337. return MP_OBJ_NULL; // op not supported
  338. }
  339. }
  340. #if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY
  341. static mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg) {
  342. // self is not a memoryview, so we don't need to use (& TYPECODE_MASK)
  343. assert((MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(self_in, &mp_type_bytearray))
  344. || (MICROPY_PY_ARRAY && mp_obj_is_type(self_in, &mp_type_array)));
  345. mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in);
  346. if (self->free == 0) {
  347. size_t item_sz = mp_binary_get_size('@', self->typecode, NULL);
  348. // TODO: alloc policy
  349. self->free = 8;
  350. self->items = m_renew(byte, self->items, item_sz * self->len, item_sz * (self->len + self->free));
  351. mp_seq_clear(self->items, self->len + 1, self->len + self->free, item_sz);
  352. }
  353. mp_binary_set_val_array(self->typecode, self->items, self->len, arg);
  354. // only update length/free if set succeeded
  355. self->len++;
  356. self->free--;
  357. return mp_const_none; // return None, as per CPython
  358. }
  359. MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_array_append_obj, array_append);
  360. static mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in) {
  361. // self is not a memoryview, so we don't need to use (& TYPECODE_MASK)
  362. assert((MICROPY_PY_BUILTINS_BYTEARRAY && mp_obj_is_type(self_in, &mp_type_bytearray))
  363. || (MICROPY_PY_ARRAY && mp_obj_is_type(self_in, &mp_type_array)));
  364. mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in);
  365. // allow to extend by anything that has the buffer protocol (extension to CPython)
  366. mp_buffer_info_t arg_bufinfo;
  367. mp_get_buffer_raise(arg_in, &arg_bufinfo, MP_BUFFER_READ);
  368. size_t sz = mp_binary_get_size('@', self->typecode, NULL);
  369. // convert byte count to element count
  370. size_t len = arg_bufinfo.len / sz;
  371. // make sure we have enough room to extend
  372. // TODO: alloc policy; at the moment we go conservative
  373. if (self->free < len) {
  374. self->items = m_renew(byte, self->items, (self->len + self->free) * sz, (self->len + len) * sz);
  375. self->free = 0;
  376. if (self_in == arg_in) {
  377. // Get arg_bufinfo again in case self->items has moved
  378. //
  379. // (Note not possible to handle case that arg_in is a memoryview into self)
  380. mp_get_buffer_raise(arg_in, &arg_bufinfo, MP_BUFFER_READ);
  381. }
  382. } else {
  383. self->free -= len;
  384. }
  385. // extend
  386. mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte);
  387. self->len += len;
  388. return mp_const_none;
  389. }
  390. MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_array_extend_obj, array_extend);
  391. #endif
  392. static mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value) {
  393. if (value == MP_OBJ_NULL) {
  394. // delete item
  395. // TODO implement
  396. // TODO: confirmed that both bytearray and array.array support
  397. // slice deletion
  398. return MP_OBJ_NULL; // op not supported
  399. } else {
  400. mp_obj_array_t *o = MP_OBJ_TO_PTR(self_in);
  401. #if MICROPY_PY_BUILTINS_SLICE
  402. if (mp_obj_is_type(index_in, &mp_type_slice)) {
  403. mp_bound_slice_t slice;
  404. if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) {
  405. mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
  406. }
  407. if (value != MP_OBJ_SENTINEL) {
  408. #if MICROPY_PY_ARRAY_SLICE_ASSIGN
  409. // Assign
  410. size_t src_len;
  411. uint8_t *src_items;
  412. size_t src_offs = 0;
  413. size_t item_sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
  414. if (mp_obj_is_obj(value) && MP_OBJ_TYPE_GET_SLOT_OR_NULL(((mp_obj_base_t *)MP_OBJ_TO_PTR(value))->type, subscr) == array_subscr) {
  415. // value is array, bytearray or memoryview
  416. mp_obj_array_t *src_slice = MP_OBJ_TO_PTR(value);
  417. if (item_sz != mp_binary_get_size('@', src_slice->typecode & TYPECODE_MASK, NULL)) {
  418. compat_error:
  419. mp_raise_ValueError(MP_ERROR_TEXT("lhs and rhs should be compatible"));
  420. }
  421. src_len = src_slice->len;
  422. src_items = src_slice->items;
  423. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  424. if (mp_obj_is_type(value, &mp_type_memoryview)) {
  425. src_offs = src_slice->memview_offset * item_sz;
  426. }
  427. #endif
  428. } else if (mp_obj_is_type(value, &mp_type_bytes)) {
  429. if (item_sz != 1) {
  430. goto compat_error;
  431. }
  432. mp_buffer_info_t bufinfo;
  433. mp_get_buffer_raise(value, &bufinfo, MP_BUFFER_READ);
  434. src_len = bufinfo.len;
  435. src_items = bufinfo.buf;
  436. } else {
  437. mp_raise_NotImplementedError(MP_ERROR_TEXT("array/bytes required on right side"));
  438. }
  439. // TODO: check src/dst compat
  440. mp_int_t len_adj = src_len - (slice.stop - slice.start);
  441. uint8_t *dest_items = o->items;
  442. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  443. if (o->base.type == &mp_type_memoryview) {
  444. if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) {
  445. // store to read-only memoryview not allowed
  446. return MP_OBJ_NULL;
  447. }
  448. if (len_adj != 0) {
  449. goto compat_error;
  450. }
  451. dest_items += o->memview_offset * item_sz;
  452. }
  453. #endif
  454. if (len_adj > 0) {
  455. if ((size_t)len_adj > o->free) {
  456. // TODO: alloc policy; at the moment we go conservative
  457. o->items = m_renew(byte, o->items, (o->len + o->free) * item_sz, (o->len + len_adj) * item_sz);
  458. o->free = len_adj;
  459. // m_renew may have moved o->items
  460. if (src_items == dest_items) {
  461. src_items = o->items;
  462. }
  463. dest_items = o->items;
  464. }
  465. mp_seq_replace_slice_grow_inplace(dest_items, o->len,
  466. slice.start, slice.stop, src_items + src_offs, src_len, len_adj, item_sz);
  467. } else {
  468. mp_seq_replace_slice_no_grow(dest_items, o->len,
  469. slice.start, slice.stop, src_items + src_offs, src_len, item_sz);
  470. // Clear "freed" elements at the end of list
  471. // TODO: This is actually only needed for typecode=='O'
  472. mp_seq_clear(dest_items, o->len + len_adj, o->len, item_sz);
  473. // TODO: alloc policy after shrinking
  474. }
  475. o->free -= len_adj;
  476. o->len += len_adj;
  477. return mp_const_none;
  478. #else
  479. return MP_OBJ_NULL; // op not supported
  480. #endif
  481. }
  482. mp_obj_array_t *res;
  483. size_t sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
  484. assert(sz > 0);
  485. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  486. if (o->base.type == &mp_type_memoryview) {
  487. if (slice.start > memview_offset_max) {
  488. mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("memoryview offset too large"));
  489. }
  490. res = m_new_obj(mp_obj_array_t);
  491. *res = *o;
  492. res->memview_offset += slice.start;
  493. res->len = slice.stop - slice.start;
  494. } else
  495. #endif
  496. {
  497. res = array_new(o->typecode, slice.stop - slice.start);
  498. memcpy(res->items, (uint8_t *)o->items + slice.start * sz, (slice.stop - slice.start) * sz);
  499. }
  500. return MP_OBJ_FROM_PTR(res);
  501. } else
  502. #endif
  503. {
  504. size_t index = mp_get_index(o->base.type, o->len, index_in, false);
  505. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  506. if (o->base.type == &mp_type_memoryview) {
  507. index += o->memview_offset;
  508. if (value != MP_OBJ_SENTINEL && !(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) {
  509. // store to read-only memoryview
  510. return MP_OBJ_NULL;
  511. }
  512. }
  513. #endif
  514. if (value == MP_OBJ_SENTINEL) {
  515. // load
  516. return mp_binary_get_val_array(o->typecode & TYPECODE_MASK, o->items, index);
  517. } else {
  518. // store
  519. mp_binary_set_val_array(o->typecode & TYPECODE_MASK, o->items, index, value);
  520. return mp_const_none;
  521. }
  522. }
  523. }
  524. }
  525. static mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  526. mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in);
  527. size_t sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
  528. bufinfo->buf = o->items;
  529. bufinfo->len = o->len * sz;
  530. bufinfo->typecode = o->typecode & TYPECODE_MASK;
  531. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  532. if (o->base.type == &mp_type_memoryview) {
  533. if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW) && (flags & MP_BUFFER_WRITE)) {
  534. // read-only memoryview
  535. return 1;
  536. }
  537. bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->memview_offset * sz;
  538. }
  539. #else
  540. (void)flags;
  541. #endif
  542. return 0;
  543. }
  544. #if MICROPY_PY_ARRAY
  545. MP_DEFINE_CONST_OBJ_TYPE(
  546. mp_type_array,
  547. MP_QSTR_array,
  548. MP_TYPE_FLAG_ITER_IS_GETITER,
  549. make_new, array_make_new,
  550. print, array_print,
  551. iter, array_iterator_new,
  552. unary_op, array_unary_op,
  553. binary_op, array_binary_op,
  554. subscr, array_subscr,
  555. buffer, array_get_buffer,
  556. locals_dict, &mp_obj_array_locals_dict
  557. );
  558. #endif
  559. #if MICROPY_PY_BUILTINS_BYTEARRAY
  560. MP_DEFINE_CONST_OBJ_TYPE(
  561. mp_type_bytearray,
  562. MP_QSTR_bytearray,
  563. MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER,
  564. make_new, bytearray_make_new,
  565. print, array_print,
  566. iter, array_iterator_new,
  567. unary_op, array_unary_op,
  568. binary_op, array_binary_op,
  569. subscr, array_subscr,
  570. buffer, array_get_buffer,
  571. locals_dict, &mp_obj_bytearray_locals_dict
  572. );
  573. #endif
  574. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  575. #if MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZE
  576. #define MEMORYVIEW_TYPE_ATTR attr, memoryview_attr,
  577. #else
  578. #define MEMORYVIEW_TYPE_ATTR
  579. #endif
  580. #if MICROPY_PY_BUILTINS_BYTES_HEX
  581. #define MEMORYVIEW_TYPE_LOCALS_DICT locals_dict, &mp_obj_memoryview_locals_dict,
  582. #else
  583. #define MEMORYVIEW_TYPE_LOCALS_DICT
  584. #endif
  585. MP_DEFINE_CONST_OBJ_TYPE(
  586. mp_type_memoryview,
  587. MP_QSTR_memoryview,
  588. MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER,
  589. make_new, memoryview_make_new,
  590. iter, array_iterator_new,
  591. unary_op, array_unary_op,
  592. binary_op, array_binary_op,
  593. MEMORYVIEW_TYPE_LOCALS_DICT
  594. MEMORYVIEW_TYPE_ATTR
  595. subscr, array_subscr,
  596. buffer, array_get_buffer
  597. );
  598. #endif // MICROPY_PY_BUILTINS_MEMORYVIEW
  599. /* unused
  600. size_t mp_obj_array_len(mp_obj_t self_in) {
  601. return ((mp_obj_array_t *)self_in)->len;
  602. }
  603. */
  604. #if MICROPY_PY_BUILTINS_BYTEARRAY
  605. mp_obj_t mp_obj_new_bytearray(size_t n, const void *items) {
  606. mp_obj_array_t *o = array_new(BYTEARRAY_TYPECODE, n);
  607. memcpy(o->items, items, n);
  608. return MP_OBJ_FROM_PTR(o);
  609. }
  610. // Create bytearray which references specified memory area
  611. mp_obj_t mp_obj_new_bytearray_by_ref(size_t n, void *items) {
  612. mp_obj_array_t *o = mp_obj_malloc(mp_obj_array_t, &mp_type_bytearray);
  613. o->typecode = BYTEARRAY_TYPECODE;
  614. o->free = 0;
  615. o->len = n;
  616. o->items = items;
  617. return MP_OBJ_FROM_PTR(o);
  618. }
  619. #endif
  620. /******************************************************************************/
  621. // array iterator
  622. typedef struct _mp_obj_array_it_t {
  623. mp_obj_base_t base;
  624. mp_obj_array_t *array;
  625. size_t offset;
  626. size_t cur;
  627. } mp_obj_array_it_t;
  628. static mp_obj_t array_it_iternext(mp_obj_t self_in) {
  629. mp_obj_array_it_t *self = MP_OBJ_TO_PTR(self_in);
  630. if (self->cur < self->array->len) {
  631. return mp_binary_get_val_array(self->array->typecode & TYPECODE_MASK, self->array->items, self->offset + self->cur++);
  632. } else {
  633. return MP_OBJ_STOP_ITERATION;
  634. }
  635. }
  636. static MP_DEFINE_CONST_OBJ_TYPE(
  637. mp_type_array_it,
  638. MP_QSTR_iterator,
  639. MP_TYPE_FLAG_ITER_IS_ITERNEXT,
  640. iter, array_it_iternext
  641. );
  642. static mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf) {
  643. assert(sizeof(mp_obj_array_t) <= sizeof(mp_obj_iter_buf_t));
  644. mp_obj_array_t *array = MP_OBJ_TO_PTR(array_in);
  645. mp_obj_array_it_t *o = (mp_obj_array_it_t *)iter_buf;
  646. o->base.type = &mp_type_array_it;
  647. o->array = array;
  648. o->offset = 0;
  649. o->cur = 0;
  650. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  651. if (array->base.type == &mp_type_memoryview) {
  652. o->offset = array->memview_offset;
  653. }
  654. #endif
  655. return MP_OBJ_FROM_PTR(o);
  656. }
  657. #endif // MICROPY_PY_ARRAY || MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_BUILTINS_MEMORYVIEW