objarray.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717
  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. } else {
  377. self->free -= len;
  378. }
  379. // extend
  380. mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte);
  381. self->len += len;
  382. return mp_const_none;
  383. }
  384. MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_array_extend_obj, array_extend);
  385. #endif
  386. static mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value) {
  387. if (value == MP_OBJ_NULL) {
  388. // delete item
  389. // TODO implement
  390. // TODO: confirmed that both bytearray and array.array support
  391. // slice deletion
  392. return MP_OBJ_NULL; // op not supported
  393. } else {
  394. mp_obj_array_t *o = MP_OBJ_TO_PTR(self_in);
  395. #if MICROPY_PY_BUILTINS_SLICE
  396. if (mp_obj_is_type(index_in, &mp_type_slice)) {
  397. mp_bound_slice_t slice;
  398. if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) {
  399. mp_raise_NotImplementedError(MP_ERROR_TEXT("only slices with step=1 (aka None) are supported"));
  400. }
  401. if (value != MP_OBJ_SENTINEL) {
  402. #if MICROPY_PY_ARRAY_SLICE_ASSIGN
  403. // Assign
  404. size_t src_len;
  405. void *src_items;
  406. size_t item_sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
  407. 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) {
  408. // value is array, bytearray or memoryview
  409. mp_obj_array_t *src_slice = MP_OBJ_TO_PTR(value);
  410. if (item_sz != mp_binary_get_size('@', src_slice->typecode & TYPECODE_MASK, NULL)) {
  411. compat_error:
  412. mp_raise_ValueError(MP_ERROR_TEXT("lhs and rhs should be compatible"));
  413. }
  414. src_len = src_slice->len;
  415. src_items = src_slice->items;
  416. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  417. if (mp_obj_is_type(value, &mp_type_memoryview)) {
  418. src_items = (uint8_t *)src_items + (src_slice->memview_offset * item_sz);
  419. }
  420. #endif
  421. } else if (mp_obj_is_type(value, &mp_type_bytes)) {
  422. if (item_sz != 1) {
  423. goto compat_error;
  424. }
  425. mp_buffer_info_t bufinfo;
  426. mp_get_buffer_raise(value, &bufinfo, MP_BUFFER_READ);
  427. src_len = bufinfo.len;
  428. src_items = bufinfo.buf;
  429. } else {
  430. mp_raise_NotImplementedError(MP_ERROR_TEXT("array/bytes required on right side"));
  431. }
  432. // TODO: check src/dst compat
  433. mp_int_t len_adj = src_len - (slice.stop - slice.start);
  434. uint8_t *dest_items = o->items;
  435. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  436. if (o->base.type == &mp_type_memoryview) {
  437. if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) {
  438. // store to read-only memoryview not allowed
  439. return MP_OBJ_NULL;
  440. }
  441. if (len_adj != 0) {
  442. goto compat_error;
  443. }
  444. dest_items += o->memview_offset * item_sz;
  445. }
  446. #endif
  447. if (len_adj > 0) {
  448. if ((size_t)len_adj > o->free) {
  449. // TODO: alloc policy; at the moment we go conservative
  450. o->items = m_renew(byte, o->items, (o->len + o->free) * item_sz, (o->len + len_adj) * item_sz);
  451. o->free = len_adj;
  452. dest_items = o->items;
  453. }
  454. mp_seq_replace_slice_grow_inplace(dest_items, o->len,
  455. slice.start, slice.stop, src_items, src_len, len_adj, item_sz);
  456. } else {
  457. mp_seq_replace_slice_no_grow(dest_items, o->len,
  458. slice.start, slice.stop, src_items, src_len, item_sz);
  459. // Clear "freed" elements at the end of list
  460. // TODO: This is actually only needed for typecode=='O'
  461. mp_seq_clear(dest_items, o->len + len_adj, o->len, item_sz);
  462. // TODO: alloc policy after shrinking
  463. }
  464. o->free -= len_adj;
  465. o->len += len_adj;
  466. return mp_const_none;
  467. #else
  468. return MP_OBJ_NULL; // op not supported
  469. #endif
  470. }
  471. mp_obj_array_t *res;
  472. size_t sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
  473. assert(sz > 0);
  474. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  475. if (o->base.type == &mp_type_memoryview) {
  476. if (slice.start > memview_offset_max) {
  477. mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("memoryview offset too large"));
  478. }
  479. res = m_new_obj(mp_obj_array_t);
  480. *res = *o;
  481. res->memview_offset += slice.start;
  482. res->len = slice.stop - slice.start;
  483. } else
  484. #endif
  485. {
  486. res = array_new(o->typecode, slice.stop - slice.start);
  487. memcpy(res->items, (uint8_t *)o->items + slice.start * sz, (slice.stop - slice.start) * sz);
  488. }
  489. return MP_OBJ_FROM_PTR(res);
  490. } else
  491. #endif
  492. {
  493. size_t index = mp_get_index(o->base.type, o->len, index_in, false);
  494. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  495. if (o->base.type == &mp_type_memoryview) {
  496. index += o->memview_offset;
  497. if (value != MP_OBJ_SENTINEL && !(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) {
  498. // store to read-only memoryview
  499. return MP_OBJ_NULL;
  500. }
  501. }
  502. #endif
  503. if (value == MP_OBJ_SENTINEL) {
  504. // load
  505. return mp_binary_get_val_array(o->typecode & TYPECODE_MASK, o->items, index);
  506. } else {
  507. // store
  508. mp_binary_set_val_array(o->typecode & TYPECODE_MASK, o->items, index, value);
  509. return mp_const_none;
  510. }
  511. }
  512. }
  513. }
  514. static mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) {
  515. mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in);
  516. size_t sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL);
  517. bufinfo->buf = o->items;
  518. bufinfo->len = o->len * sz;
  519. bufinfo->typecode = o->typecode & TYPECODE_MASK;
  520. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  521. if (o->base.type == &mp_type_memoryview) {
  522. if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW) && (flags & MP_BUFFER_WRITE)) {
  523. // read-only memoryview
  524. return 1;
  525. }
  526. bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->memview_offset * sz;
  527. }
  528. #else
  529. (void)flags;
  530. #endif
  531. return 0;
  532. }
  533. #if MICROPY_PY_ARRAY
  534. MP_DEFINE_CONST_OBJ_TYPE(
  535. mp_type_array,
  536. MP_QSTR_array,
  537. MP_TYPE_FLAG_ITER_IS_GETITER,
  538. make_new, array_make_new,
  539. print, array_print,
  540. iter, array_iterator_new,
  541. unary_op, array_unary_op,
  542. binary_op, array_binary_op,
  543. subscr, array_subscr,
  544. buffer, array_get_buffer,
  545. locals_dict, &mp_obj_array_locals_dict
  546. );
  547. #endif
  548. #if MICROPY_PY_BUILTINS_BYTEARRAY
  549. MP_DEFINE_CONST_OBJ_TYPE(
  550. mp_type_bytearray,
  551. MP_QSTR_bytearray,
  552. MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER,
  553. make_new, bytearray_make_new,
  554. print, array_print,
  555. iter, array_iterator_new,
  556. unary_op, array_unary_op,
  557. binary_op, array_binary_op,
  558. subscr, array_subscr,
  559. buffer, array_get_buffer,
  560. locals_dict, &mp_obj_bytearray_locals_dict
  561. );
  562. #endif
  563. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  564. #if MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZE
  565. #define MEMORYVIEW_TYPE_ATTR attr, memoryview_attr,
  566. #else
  567. #define MEMORYVIEW_TYPE_ATTR
  568. #endif
  569. #if MICROPY_PY_BUILTINS_BYTES_HEX
  570. #define MEMORYVIEW_TYPE_LOCALS_DICT locals_dict, &mp_obj_memoryview_locals_dict,
  571. #else
  572. #define MEMORYVIEW_TYPE_LOCALS_DICT
  573. #endif
  574. MP_DEFINE_CONST_OBJ_TYPE(
  575. mp_type_memoryview,
  576. MP_QSTR_memoryview,
  577. MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER,
  578. make_new, memoryview_make_new,
  579. iter, array_iterator_new,
  580. unary_op, array_unary_op,
  581. binary_op, array_binary_op,
  582. MEMORYVIEW_TYPE_LOCALS_DICT
  583. MEMORYVIEW_TYPE_ATTR
  584. subscr, array_subscr,
  585. buffer, array_get_buffer
  586. );
  587. #endif // MICROPY_PY_BUILTINS_MEMORYVIEW
  588. /* unused
  589. size_t mp_obj_array_len(mp_obj_t self_in) {
  590. return ((mp_obj_array_t *)self_in)->len;
  591. }
  592. */
  593. #if MICROPY_PY_BUILTINS_BYTEARRAY
  594. mp_obj_t mp_obj_new_bytearray(size_t n, const void *items) {
  595. mp_obj_array_t *o = array_new(BYTEARRAY_TYPECODE, n);
  596. memcpy(o->items, items, n);
  597. return MP_OBJ_FROM_PTR(o);
  598. }
  599. // Create bytearray which references specified memory area
  600. mp_obj_t mp_obj_new_bytearray_by_ref(size_t n, void *items) {
  601. mp_obj_array_t *o = mp_obj_malloc(mp_obj_array_t, &mp_type_bytearray);
  602. o->typecode = BYTEARRAY_TYPECODE;
  603. o->free = 0;
  604. o->len = n;
  605. o->items = items;
  606. return MP_OBJ_FROM_PTR(o);
  607. }
  608. #endif
  609. /******************************************************************************/
  610. // array iterator
  611. typedef struct _mp_obj_array_it_t {
  612. mp_obj_base_t base;
  613. mp_obj_array_t *array;
  614. size_t offset;
  615. size_t cur;
  616. } mp_obj_array_it_t;
  617. static mp_obj_t array_it_iternext(mp_obj_t self_in) {
  618. mp_obj_array_it_t *self = MP_OBJ_TO_PTR(self_in);
  619. if (self->cur < self->array->len) {
  620. return mp_binary_get_val_array(self->array->typecode & TYPECODE_MASK, self->array->items, self->offset + self->cur++);
  621. } else {
  622. return MP_OBJ_STOP_ITERATION;
  623. }
  624. }
  625. static MP_DEFINE_CONST_OBJ_TYPE(
  626. mp_type_array_it,
  627. MP_QSTR_iterator,
  628. MP_TYPE_FLAG_ITER_IS_ITERNEXT,
  629. iter, array_it_iternext
  630. );
  631. static mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf) {
  632. assert(sizeof(mp_obj_array_t) <= sizeof(mp_obj_iter_buf_t));
  633. mp_obj_array_t *array = MP_OBJ_TO_PTR(array_in);
  634. mp_obj_array_it_t *o = (mp_obj_array_it_t *)iter_buf;
  635. o->base.type = &mp_type_array_it;
  636. o->array = array;
  637. o->offset = 0;
  638. o->cur = 0;
  639. #if MICROPY_PY_BUILTINS_MEMORYVIEW
  640. if (array->base.type == &mp_type_memoryview) {
  641. o->offset = array->memview_offset;
  642. }
  643. #endif
  644. return MP_OBJ_FROM_PTR(o);
  645. }
  646. #endif // MICROPY_PY_ARRAY || MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_BUILTINS_MEMORYVIEW