arraymodule.c 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138
  1. /* Array object implementation */
  2. /* An array is a uniform list -- all items have the same type.
  3. The item type is restricted to simple C types like int or float */
  4. #ifndef Py_BUILD_CORE_BUILTIN
  5. # define Py_BUILD_CORE_MODULE 1
  6. #endif
  7. #define PY_SSIZE_T_CLEAN
  8. #include "Python.h"
  9. #include "pycore_moduleobject.h" // _PyModule_GetState()
  10. #include "pycore_bytesobject.h" // _PyBytes_Repeat
  11. #include "structmember.h" // PyMemberDef
  12. #include <stddef.h> // offsetof()
  13. /*[clinic input]
  14. module array
  15. [clinic start generated code]*/
  16. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7d1b8d7f5958fd83]*/
  17. struct arrayobject; /* Forward */
  18. static struct PyModuleDef arraymodule;
  19. /* All possible arraydescr values are defined in the vector "descriptors"
  20. * below. That's defined later because the appropriate get and set
  21. * functions aren't visible yet.
  22. */
  23. struct arraydescr {
  24. char typecode;
  25. int itemsize;
  26. PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
  27. int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
  28. int (*compareitems)(const void *, const void *, Py_ssize_t);
  29. const char *formats;
  30. int is_integer_type;
  31. int is_signed;
  32. };
  33. typedef struct arrayobject {
  34. PyObject_VAR_HEAD
  35. char *ob_item;
  36. Py_ssize_t allocated;
  37. const struct arraydescr *ob_descr;
  38. PyObject *weakreflist; /* List of weak references */
  39. Py_ssize_t ob_exports; /* Number of exported buffers */
  40. } arrayobject;
  41. typedef struct {
  42. PyObject_HEAD
  43. Py_ssize_t index;
  44. arrayobject *ao;
  45. PyObject* (*getitem)(struct arrayobject *, Py_ssize_t);
  46. } arrayiterobject;
  47. typedef struct {
  48. PyTypeObject *ArrayType;
  49. PyTypeObject *ArrayIterType;
  50. PyObject *array_reconstructor;
  51. PyObject *str_read;
  52. PyObject *str_write;
  53. PyObject *str___dict__;
  54. PyObject *str_iter;
  55. } array_state;
  56. static array_state *
  57. get_array_state(PyObject *module)
  58. {
  59. return (array_state *)_PyModule_GetState(module);
  60. }
  61. #define find_array_state_by_type(tp) \
  62. (get_array_state(PyType_GetModuleByDef(tp, &arraymodule)))
  63. #define get_array_state_by_class(cls) \
  64. (get_array_state(PyType_GetModule(cls)))
  65. enum machine_format_code {
  66. UNKNOWN_FORMAT = -1,
  67. /* UNKNOWN_FORMAT is used to indicate that the machine format for an
  68. * array type code cannot be interpreted. When this occurs, a list of
  69. * Python objects is used to represent the content of the array
  70. * instead of using the memory content of the array directly. In that
  71. * case, the array_reconstructor mechanism is bypassed completely, and
  72. * the standard array constructor is used instead.
  73. *
  74. * This is will most likely occur when the machine doesn't use IEEE
  75. * floating-point numbers.
  76. */
  77. UNSIGNED_INT8 = 0,
  78. SIGNED_INT8 = 1,
  79. UNSIGNED_INT16_LE = 2,
  80. UNSIGNED_INT16_BE = 3,
  81. SIGNED_INT16_LE = 4,
  82. SIGNED_INT16_BE = 5,
  83. UNSIGNED_INT32_LE = 6,
  84. UNSIGNED_INT32_BE = 7,
  85. SIGNED_INT32_LE = 8,
  86. SIGNED_INT32_BE = 9,
  87. UNSIGNED_INT64_LE = 10,
  88. UNSIGNED_INT64_BE = 11,
  89. SIGNED_INT64_LE = 12,
  90. SIGNED_INT64_BE = 13,
  91. IEEE_754_FLOAT_LE = 14,
  92. IEEE_754_FLOAT_BE = 15,
  93. IEEE_754_DOUBLE_LE = 16,
  94. IEEE_754_DOUBLE_BE = 17,
  95. UTF16_LE = 18,
  96. UTF16_BE = 19,
  97. UTF32_LE = 20,
  98. UTF32_BE = 21
  99. };
  100. #define MACHINE_FORMAT_CODE_MIN 0
  101. #define MACHINE_FORMAT_CODE_MAX 21
  102. /*
  103. * Must come after arrayobject, arrayiterobject,
  104. * and enum machine_code_type definitions.
  105. */
  106. #include "clinic/arraymodule.c.h"
  107. #define array_Check(op, state) PyObject_TypeCheck(op, state->ArrayType)
  108. static int
  109. array_resize(arrayobject *self, Py_ssize_t newsize)
  110. {
  111. char *items;
  112. size_t _new_size;
  113. if (self->ob_exports > 0 && newsize != Py_SIZE(self)) {
  114. PyErr_SetString(PyExc_BufferError,
  115. "cannot resize an array that is exporting buffers");
  116. return -1;
  117. }
  118. /* Bypass realloc() when a previous overallocation is large enough
  119. to accommodate the newsize. If the newsize is 16 smaller than the
  120. current size, then proceed with the realloc() to shrink the array.
  121. */
  122. if (self->allocated >= newsize &&
  123. Py_SIZE(self) < newsize + 16 &&
  124. self->ob_item != NULL) {
  125. Py_SET_SIZE(self, newsize);
  126. return 0;
  127. }
  128. if (newsize == 0) {
  129. PyMem_Free(self->ob_item);
  130. self->ob_item = NULL;
  131. Py_SET_SIZE(self, 0);
  132. self->allocated = 0;
  133. return 0;
  134. }
  135. /* This over-allocates proportional to the array size, making room
  136. * for additional growth. The over-allocation is mild, but is
  137. * enough to give linear-time amortized behavior over a long
  138. * sequence of appends() in the presence of a poorly-performing
  139. * system realloc().
  140. * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
  141. * Note, the pattern starts out the same as for lists but then
  142. * grows at a smaller rate so that larger arrays only overallocate
  143. * by about 1/16th -- this is done because arrays are presumed to be more
  144. * memory critical.
  145. */
  146. _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
  147. items = self->ob_item;
  148. /* XXX The following multiplication and division does not optimize away
  149. like it does for lists since the size is not known at compile time */
  150. if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
  151. PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
  152. else
  153. items = NULL;
  154. if (items == NULL) {
  155. PyErr_NoMemory();
  156. return -1;
  157. }
  158. self->ob_item = items;
  159. Py_SET_SIZE(self, newsize);
  160. self->allocated = _new_size;
  161. return 0;
  162. }
  163. /****************************************************************************
  164. Get and Set functions for each type.
  165. A Get function takes an arrayobject* and an integer index, returning the
  166. array value at that index wrapped in an appropriate PyObject*.
  167. A Set function takes an arrayobject, integer index, and PyObject*; sets
  168. the array value at that index to the raw C data extracted from the PyObject*,
  169. and returns 0 if successful, else nonzero on failure (PyObject* not of an
  170. appropriate type or value).
  171. Note that the basic Get and Set functions do NOT check that the index is
  172. in bounds; that's the responsibility of the caller.
  173. ****************************************************************************/
  174. static PyObject *
  175. b_getitem(arrayobject *ap, Py_ssize_t i)
  176. {
  177. long x = ((signed char *)ap->ob_item)[i];
  178. return PyLong_FromLong(x);
  179. }
  180. static int
  181. b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  182. {
  183. short x;
  184. /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
  185. must use the next size up that is signed ('h') and manually do
  186. the overflow checking */
  187. if (!PyArg_Parse(v, "h;array item must be integer", &x))
  188. return -1;
  189. else if (x < -128) {
  190. PyErr_SetString(PyExc_OverflowError,
  191. "signed char is less than minimum");
  192. return -1;
  193. }
  194. else if (x > 127) {
  195. PyErr_SetString(PyExc_OverflowError,
  196. "signed char is greater than maximum");
  197. return -1;
  198. }
  199. if (i >= 0)
  200. ((char *)ap->ob_item)[i] = (char)x;
  201. return 0;
  202. }
  203. static PyObject *
  204. BB_getitem(arrayobject *ap, Py_ssize_t i)
  205. {
  206. long x = ((unsigned char *)ap->ob_item)[i];
  207. return PyLong_FromLong(x);
  208. }
  209. static int
  210. BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  211. {
  212. unsigned char x;
  213. /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
  214. if (!PyArg_Parse(v, "b;array item must be integer", &x))
  215. return -1;
  216. if (i >= 0)
  217. ((unsigned char *)ap->ob_item)[i] = x;
  218. return 0;
  219. }
  220. static PyObject *
  221. u_getitem(arrayobject *ap, Py_ssize_t i)
  222. {
  223. return PyUnicode_FromOrdinal(((wchar_t *) ap->ob_item)[i]);
  224. }
  225. static int
  226. u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  227. {
  228. PyObject *u;
  229. if (!PyArg_Parse(v, "U;array item must be unicode character", &u)) {
  230. return -1;
  231. }
  232. Py_ssize_t len = PyUnicode_AsWideChar(u, NULL, 0);
  233. if (len != 2) {
  234. PyErr_SetString(PyExc_TypeError,
  235. "array item must be unicode character");
  236. return -1;
  237. }
  238. wchar_t w;
  239. len = PyUnicode_AsWideChar(u, &w, 1);
  240. assert(len == 1);
  241. if (i >= 0) {
  242. ((wchar_t *)ap->ob_item)[i] = w;
  243. }
  244. return 0;
  245. }
  246. static PyObject *
  247. h_getitem(arrayobject *ap, Py_ssize_t i)
  248. {
  249. return PyLong_FromLong((long) ((short *)ap->ob_item)[i]);
  250. }
  251. static int
  252. h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  253. {
  254. short x;
  255. /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
  256. if (!PyArg_Parse(v, "h;array item must be integer", &x))
  257. return -1;
  258. if (i >= 0)
  259. ((short *)ap->ob_item)[i] = x;
  260. return 0;
  261. }
  262. static PyObject *
  263. HH_getitem(arrayobject *ap, Py_ssize_t i)
  264. {
  265. return PyLong_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
  266. }
  267. static int
  268. HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  269. {
  270. int x;
  271. /* PyArg_Parse's 'h' formatter is for a signed short, therefore
  272. must use the next size up and manually do the overflow checking */
  273. if (!PyArg_Parse(v, "i;array item must be integer", &x))
  274. return -1;
  275. else if (x < 0) {
  276. PyErr_SetString(PyExc_OverflowError,
  277. "unsigned short is less than minimum");
  278. return -1;
  279. }
  280. else if (x > USHRT_MAX) {
  281. PyErr_SetString(PyExc_OverflowError,
  282. "unsigned short is greater than maximum");
  283. return -1;
  284. }
  285. if (i >= 0)
  286. ((short *)ap->ob_item)[i] = (short)x;
  287. return 0;
  288. }
  289. static PyObject *
  290. i_getitem(arrayobject *ap, Py_ssize_t i)
  291. {
  292. return PyLong_FromLong((long) ((int *)ap->ob_item)[i]);
  293. }
  294. static int
  295. i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  296. {
  297. int x;
  298. /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
  299. if (!PyArg_Parse(v, "i;array item must be integer", &x))
  300. return -1;
  301. if (i >= 0)
  302. ((int *)ap->ob_item)[i] = x;
  303. return 0;
  304. }
  305. static PyObject *
  306. II_getitem(arrayobject *ap, Py_ssize_t i)
  307. {
  308. return PyLong_FromUnsignedLong(
  309. (unsigned long) ((unsigned int *)ap->ob_item)[i]);
  310. }
  311. static int
  312. II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  313. {
  314. unsigned long x;
  315. int do_decref = 0; /* if nb_int was called */
  316. if (!PyLong_Check(v)) {
  317. v = _PyNumber_Index(v);
  318. if (NULL == v) {
  319. return -1;
  320. }
  321. do_decref = 1;
  322. }
  323. x = PyLong_AsUnsignedLong(v);
  324. if (x == (unsigned long)-1 && PyErr_Occurred()) {
  325. if (do_decref) {
  326. Py_DECREF(v);
  327. }
  328. return -1;
  329. }
  330. if (x > UINT_MAX) {
  331. PyErr_SetString(PyExc_OverflowError,
  332. "unsigned int is greater than maximum");
  333. if (do_decref) {
  334. Py_DECREF(v);
  335. }
  336. return -1;
  337. }
  338. if (i >= 0)
  339. ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
  340. if (do_decref) {
  341. Py_DECREF(v);
  342. }
  343. return 0;
  344. }
  345. static PyObject *
  346. l_getitem(arrayobject *ap, Py_ssize_t i)
  347. {
  348. return PyLong_FromLong(((long *)ap->ob_item)[i]);
  349. }
  350. static int
  351. l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  352. {
  353. long x;
  354. if (!PyArg_Parse(v, "l;array item must be integer", &x))
  355. return -1;
  356. if (i >= 0)
  357. ((long *)ap->ob_item)[i] = x;
  358. return 0;
  359. }
  360. static PyObject *
  361. LL_getitem(arrayobject *ap, Py_ssize_t i)
  362. {
  363. return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
  364. }
  365. static int
  366. LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  367. {
  368. unsigned long x;
  369. int do_decref = 0; /* if nb_int was called */
  370. if (!PyLong_Check(v)) {
  371. v = _PyNumber_Index(v);
  372. if (NULL == v) {
  373. return -1;
  374. }
  375. do_decref = 1;
  376. }
  377. x = PyLong_AsUnsignedLong(v);
  378. if (x == (unsigned long)-1 && PyErr_Occurred()) {
  379. if (do_decref) {
  380. Py_DECREF(v);
  381. }
  382. return -1;
  383. }
  384. if (i >= 0)
  385. ((unsigned long *)ap->ob_item)[i] = x;
  386. if (do_decref) {
  387. Py_DECREF(v);
  388. }
  389. return 0;
  390. }
  391. static PyObject *
  392. q_getitem(arrayobject *ap, Py_ssize_t i)
  393. {
  394. return PyLong_FromLongLong(((long long *)ap->ob_item)[i]);
  395. }
  396. static int
  397. q_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  398. {
  399. long long x;
  400. if (!PyArg_Parse(v, "L;array item must be integer", &x))
  401. return -1;
  402. if (i >= 0)
  403. ((long long *)ap->ob_item)[i] = x;
  404. return 0;
  405. }
  406. static PyObject *
  407. QQ_getitem(arrayobject *ap, Py_ssize_t i)
  408. {
  409. return PyLong_FromUnsignedLongLong(
  410. ((unsigned long long *)ap->ob_item)[i]);
  411. }
  412. static int
  413. QQ_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  414. {
  415. unsigned long long x;
  416. int do_decref = 0; /* if nb_int was called */
  417. if (!PyLong_Check(v)) {
  418. v = _PyNumber_Index(v);
  419. if (NULL == v) {
  420. return -1;
  421. }
  422. do_decref = 1;
  423. }
  424. x = PyLong_AsUnsignedLongLong(v);
  425. if (x == (unsigned long long)-1 && PyErr_Occurred()) {
  426. if (do_decref) {
  427. Py_DECREF(v);
  428. }
  429. return -1;
  430. }
  431. if (i >= 0)
  432. ((unsigned long long *)ap->ob_item)[i] = x;
  433. if (do_decref) {
  434. Py_DECREF(v);
  435. }
  436. return 0;
  437. }
  438. static PyObject *
  439. f_getitem(arrayobject *ap, Py_ssize_t i)
  440. {
  441. return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
  442. }
  443. static int
  444. f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  445. {
  446. float x;
  447. if (!PyArg_Parse(v, "f;array item must be float", &x))
  448. return -1;
  449. if (i >= 0)
  450. ((float *)ap->ob_item)[i] = x;
  451. return 0;
  452. }
  453. static PyObject *
  454. d_getitem(arrayobject *ap, Py_ssize_t i)
  455. {
  456. return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
  457. }
  458. static int
  459. d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
  460. {
  461. double x;
  462. if (!PyArg_Parse(v, "d;array item must be float", &x))
  463. return -1;
  464. if (i >= 0)
  465. ((double *)ap->ob_item)[i] = x;
  466. return 0;
  467. }
  468. #define DEFINE_COMPAREITEMS(code, type) \
  469. static int \
  470. code##_compareitems(const void *lhs, const void *rhs, Py_ssize_t length) \
  471. { \
  472. const type *a = lhs, *b = rhs; \
  473. for (Py_ssize_t i = 0; i < length; ++i) \
  474. if (a[i] != b[i]) \
  475. return a[i] < b[i] ? -1 : 1; \
  476. return 0; \
  477. }
  478. DEFINE_COMPAREITEMS(b, signed char)
  479. DEFINE_COMPAREITEMS(BB, unsigned char)
  480. DEFINE_COMPAREITEMS(u, wchar_t)
  481. DEFINE_COMPAREITEMS(h, short)
  482. DEFINE_COMPAREITEMS(HH, unsigned short)
  483. DEFINE_COMPAREITEMS(i, int)
  484. DEFINE_COMPAREITEMS(II, unsigned int)
  485. DEFINE_COMPAREITEMS(l, long)
  486. DEFINE_COMPAREITEMS(LL, unsigned long)
  487. DEFINE_COMPAREITEMS(q, long long)
  488. DEFINE_COMPAREITEMS(QQ, unsigned long long)
  489. /* Description of types.
  490. *
  491. * Don't forget to update typecode_to_mformat_code() if you add a new
  492. * typecode.
  493. */
  494. static const struct arraydescr descriptors[] = {
  495. {'b', 1, b_getitem, b_setitem, b_compareitems, "b", 1, 1},
  496. {'B', 1, BB_getitem, BB_setitem, BB_compareitems, "B", 1, 0},
  497. {'u', sizeof(wchar_t), u_getitem, u_setitem, u_compareitems, "u", 0, 0},
  498. {'h', sizeof(short), h_getitem, h_setitem, h_compareitems, "h", 1, 1},
  499. {'H', sizeof(short), HH_getitem, HH_setitem, HH_compareitems, "H", 1, 0},
  500. {'i', sizeof(int), i_getitem, i_setitem, i_compareitems, "i", 1, 1},
  501. {'I', sizeof(int), II_getitem, II_setitem, II_compareitems, "I", 1, 0},
  502. {'l', sizeof(long), l_getitem, l_setitem, l_compareitems, "l", 1, 1},
  503. {'L', sizeof(long), LL_getitem, LL_setitem, LL_compareitems, "L", 1, 0},
  504. {'q', sizeof(long long), q_getitem, q_setitem, q_compareitems, "q", 1, 1},
  505. {'Q', sizeof(long long), QQ_getitem, QQ_setitem, QQ_compareitems, "Q", 1, 0},
  506. {'f', sizeof(float), f_getitem, f_setitem, NULL, "f", 0, 0},
  507. {'d', sizeof(double), d_getitem, d_setitem, NULL, "d", 0, 0},
  508. {'\0', 0, 0, 0, 0, 0, 0} /* Sentinel */
  509. };
  510. /****************************************************************************
  511. Implementations of array object methods.
  512. ****************************************************************************/
  513. /*[clinic input]
  514. class array.array "arrayobject *" "ArrayType"
  515. [clinic start generated code]*/
  516. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=a5c29edf59f176a3]*/
  517. static PyObject *
  518. newarrayobject(PyTypeObject *type, Py_ssize_t size, const struct arraydescr *descr)
  519. {
  520. arrayobject *op;
  521. size_t nbytes;
  522. if (size < 0) {
  523. PyErr_BadInternalCall();
  524. return NULL;
  525. }
  526. /* Check for overflow */
  527. if (size > PY_SSIZE_T_MAX / descr->itemsize) {
  528. return PyErr_NoMemory();
  529. }
  530. nbytes = size * descr->itemsize;
  531. op = (arrayobject *) type->tp_alloc(type, 0);
  532. if (op == NULL) {
  533. return NULL;
  534. }
  535. op->ob_descr = descr;
  536. op->allocated = size;
  537. op->weakreflist = NULL;
  538. Py_SET_SIZE(op, size);
  539. if (size <= 0) {
  540. op->ob_item = NULL;
  541. }
  542. else {
  543. op->ob_item = PyMem_NEW(char, nbytes);
  544. if (op->ob_item == NULL) {
  545. Py_DECREF(op);
  546. return PyErr_NoMemory();
  547. }
  548. }
  549. op->ob_exports = 0;
  550. return (PyObject *) op;
  551. }
  552. static PyObject *
  553. getarrayitem(PyObject *op, Py_ssize_t i)
  554. {
  555. #ifndef NDEBUG
  556. array_state *state = find_array_state_by_type(Py_TYPE(op));
  557. assert(array_Check(op, state));
  558. #endif
  559. arrayobject *ap;
  560. ap = (arrayobject *)op;
  561. assert(i>=0 && i<Py_SIZE(ap));
  562. return (*ap->ob_descr->getitem)(ap, i);
  563. }
  564. static int
  565. ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
  566. {
  567. char *items;
  568. Py_ssize_t n = Py_SIZE(self);
  569. if (v == NULL) {
  570. PyErr_BadInternalCall();
  571. return -1;
  572. }
  573. if ((*self->ob_descr->setitem)(self, -1, v) < 0)
  574. return -1;
  575. if (array_resize(self, n+1) == -1)
  576. return -1;
  577. items = self->ob_item;
  578. if (where < 0) {
  579. where += n;
  580. if (where < 0)
  581. where = 0;
  582. }
  583. if (where > n)
  584. where = n;
  585. /* appends don't need to call memmove() */
  586. if (where != n)
  587. memmove(items + (where+1)*self->ob_descr->itemsize,
  588. items + where*self->ob_descr->itemsize,
  589. (n-where)*self->ob_descr->itemsize);
  590. return (*self->ob_descr->setitem)(self, where, v);
  591. }
  592. /* Methods */
  593. static int
  594. array_tp_traverse(arrayobject *op, visitproc visit, void *arg)
  595. {
  596. Py_VISIT(Py_TYPE(op));
  597. return 0;
  598. }
  599. static void
  600. array_dealloc(arrayobject *op)
  601. {
  602. PyTypeObject *tp = Py_TYPE(op);
  603. PyObject_GC_UnTrack(op);
  604. if (op->weakreflist != NULL)
  605. PyObject_ClearWeakRefs((PyObject *) op);
  606. if (op->ob_item != NULL)
  607. PyMem_Free(op->ob_item);
  608. tp->tp_free(op);
  609. Py_DECREF(tp);
  610. }
  611. static PyObject *
  612. array_richcompare(PyObject *v, PyObject *w, int op)
  613. {
  614. array_state *state = find_array_state_by_type(Py_TYPE(v));
  615. arrayobject *va, *wa;
  616. PyObject *vi = NULL;
  617. PyObject *wi = NULL;
  618. Py_ssize_t i, k;
  619. PyObject *res;
  620. if (!array_Check(v, state) || !array_Check(w, state))
  621. Py_RETURN_NOTIMPLEMENTED;
  622. va = (arrayobject *)v;
  623. wa = (arrayobject *)w;
  624. if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
  625. /* Shortcut: if the lengths differ, the arrays differ */
  626. if (op == Py_EQ)
  627. res = Py_False;
  628. else
  629. res = Py_True;
  630. return Py_NewRef(res);
  631. }
  632. if (va->ob_descr == wa->ob_descr && va->ob_descr->compareitems != NULL) {
  633. /* Fast path:
  634. arrays with same types can have their buffers compared directly */
  635. Py_ssize_t common_length = Py_MIN(Py_SIZE(va), Py_SIZE(wa));
  636. int result = va->ob_descr->compareitems(va->ob_item, wa->ob_item,
  637. common_length);
  638. if (result == 0)
  639. goto compare_sizes;
  640. int cmp;
  641. switch (op) {
  642. case Py_LT: cmp = result < 0; break;
  643. case Py_LE: cmp = result <= 0; break;
  644. case Py_EQ: cmp = result == 0; break;
  645. case Py_NE: cmp = result != 0; break;
  646. case Py_GT: cmp = result > 0; break;
  647. case Py_GE: cmp = result >= 0; break;
  648. default: return NULL; /* cannot happen */
  649. }
  650. PyObject *res = cmp ? Py_True : Py_False;
  651. return Py_NewRef(res);
  652. }
  653. /* Search for the first index where items are different */
  654. k = 1;
  655. for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
  656. vi = getarrayitem(v, i);
  657. if (vi == NULL) {
  658. return NULL;
  659. }
  660. wi = getarrayitem(w, i);
  661. if (wi == NULL) {
  662. Py_DECREF(vi);
  663. return NULL;
  664. }
  665. k = PyObject_RichCompareBool(vi, wi, Py_EQ);
  666. if (k == 0)
  667. break; /* Keeping vi and wi alive! */
  668. Py_DECREF(vi);
  669. Py_DECREF(wi);
  670. if (k < 0)
  671. return NULL;
  672. }
  673. if (k) {
  674. /* No more items to compare -- compare sizes */
  675. compare_sizes: ;
  676. Py_ssize_t vs = Py_SIZE(va);
  677. Py_ssize_t ws = Py_SIZE(wa);
  678. int cmp;
  679. switch (op) {
  680. case Py_LT: cmp = vs < ws; break;
  681. case Py_LE: cmp = vs <= ws; break;
  682. /* If the lengths were not equal,
  683. the earlier fast-path check would have caught that. */
  684. case Py_EQ: assert(vs == ws); cmp = 1; break;
  685. case Py_NE: assert(vs == ws); cmp = 0; break;
  686. case Py_GT: cmp = vs > ws; break;
  687. case Py_GE: cmp = vs >= ws; break;
  688. default: return NULL; /* cannot happen */
  689. }
  690. if (cmp)
  691. res = Py_True;
  692. else
  693. res = Py_False;
  694. return Py_NewRef(res);
  695. }
  696. /* We have an item that differs. First, shortcuts for EQ/NE */
  697. if (op == Py_EQ) {
  698. res = Py_NewRef(Py_False);
  699. }
  700. else if (op == Py_NE) {
  701. res = Py_NewRef(Py_True);
  702. }
  703. else {
  704. /* Compare the final item again using the proper operator */
  705. res = PyObject_RichCompare(vi, wi, op);
  706. }
  707. Py_DECREF(vi);
  708. Py_DECREF(wi);
  709. return res;
  710. }
  711. static Py_ssize_t
  712. array_length(arrayobject *a)
  713. {
  714. return Py_SIZE(a);
  715. }
  716. static PyObject *
  717. array_item(arrayobject *a, Py_ssize_t i)
  718. {
  719. if (i < 0 || i >= Py_SIZE(a)) {
  720. PyErr_SetString(PyExc_IndexError, "array index out of range");
  721. return NULL;
  722. }
  723. return getarrayitem((PyObject *)a, i);
  724. }
  725. static PyObject *
  726. array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  727. {
  728. array_state *state = find_array_state_by_type(Py_TYPE(a));
  729. arrayobject *np;
  730. if (ilow < 0)
  731. ilow = 0;
  732. else if (ilow > Py_SIZE(a))
  733. ilow = Py_SIZE(a);
  734. if (ihigh < 0)
  735. ihigh = 0;
  736. if (ihigh < ilow)
  737. ihigh = ilow;
  738. else if (ihigh > Py_SIZE(a))
  739. ihigh = Py_SIZE(a);
  740. np = (arrayobject *) newarrayobject(state->ArrayType, ihigh - ilow, a->ob_descr);
  741. if (np == NULL)
  742. return NULL;
  743. if (ihigh > ilow) {
  744. memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
  745. (ihigh-ilow) * a->ob_descr->itemsize);
  746. }
  747. return (PyObject *)np;
  748. }
  749. /*[clinic input]
  750. array.array.__copy__
  751. Return a copy of the array.
  752. [clinic start generated code]*/
  753. static PyObject *
  754. array_array___copy___impl(arrayobject *self)
  755. /*[clinic end generated code: output=dec7c3f925d9619e input=ad1ee5b086965f09]*/
  756. {
  757. return array_slice(self, 0, Py_SIZE(self));
  758. }
  759. /*[clinic input]
  760. array.array.__deepcopy__
  761. unused: object
  762. /
  763. Return a copy of the array.
  764. [clinic start generated code]*/
  765. static PyObject *
  766. array_array___deepcopy__(arrayobject *self, PyObject *unused)
  767. /*[clinic end generated code: output=1ec748d8e14a9faa input=2405ecb4933748c4]*/
  768. {
  769. return array_array___copy___impl(self);
  770. }
  771. static PyObject *
  772. array_concat(arrayobject *a, PyObject *bb)
  773. {
  774. array_state *state = find_array_state_by_type(Py_TYPE(a));
  775. Py_ssize_t size;
  776. arrayobject *np;
  777. if (!array_Check(bb, state)) {
  778. PyErr_Format(PyExc_TypeError,
  779. "can only append array (not \"%.200s\") to array",
  780. Py_TYPE(bb)->tp_name);
  781. return NULL;
  782. }
  783. #define b ((arrayobject *)bb)
  784. if (a->ob_descr != b->ob_descr) {
  785. PyErr_BadArgument();
  786. return NULL;
  787. }
  788. if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
  789. return PyErr_NoMemory();
  790. }
  791. size = Py_SIZE(a) + Py_SIZE(b);
  792. np = (arrayobject *) newarrayobject(state->ArrayType, size, a->ob_descr);
  793. if (np == NULL) {
  794. return NULL;
  795. }
  796. if (Py_SIZE(a) > 0) {
  797. memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
  798. }
  799. if (Py_SIZE(b) > 0) {
  800. memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
  801. b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
  802. }
  803. return (PyObject *)np;
  804. #undef b
  805. }
  806. static PyObject *
  807. array_repeat(arrayobject *a, Py_ssize_t n)
  808. {
  809. array_state *state = find_array_state_by_type(Py_TYPE(a));
  810. if (n < 0)
  811. n = 0;
  812. const Py_ssize_t array_length = Py_SIZE(a);
  813. if ((array_length != 0) && (n > PY_SSIZE_T_MAX / array_length)) {
  814. return PyErr_NoMemory();
  815. }
  816. Py_ssize_t size = array_length * n;
  817. arrayobject* np = (arrayobject *) newarrayobject(state->ArrayType, size, a->ob_descr);
  818. if (np == NULL)
  819. return NULL;
  820. if (size == 0)
  821. return (PyObject *)np;
  822. const Py_ssize_t oldbytes = array_length * a->ob_descr->itemsize;
  823. const Py_ssize_t newbytes = oldbytes * n;
  824. _PyBytes_Repeat(np->ob_item, newbytes, a->ob_item, oldbytes);
  825. return (PyObject *)np;
  826. }
  827. static int
  828. array_del_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  829. {
  830. char *item;
  831. Py_ssize_t d; /* Change in size */
  832. if (ilow < 0)
  833. ilow = 0;
  834. else if (ilow > Py_SIZE(a))
  835. ilow = Py_SIZE(a);
  836. if (ihigh < 0)
  837. ihigh = 0;
  838. if (ihigh < ilow)
  839. ihigh = ilow;
  840. else if (ihigh > Py_SIZE(a))
  841. ihigh = Py_SIZE(a);
  842. item = a->ob_item;
  843. d = ihigh-ilow;
  844. /* Issue #4509: If the array has exported buffers and the slice
  845. assignment would change the size of the array, fail early to make
  846. sure we don't modify it. */
  847. if (d != 0 && a->ob_exports > 0) {
  848. PyErr_SetString(PyExc_BufferError,
  849. "cannot resize an array that is exporting buffers");
  850. return -1;
  851. }
  852. if (d > 0) { /* Delete d items */
  853. memmove(item + (ihigh-d)*a->ob_descr->itemsize,
  854. item + ihigh*a->ob_descr->itemsize,
  855. (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
  856. if (array_resize(a, Py_SIZE(a) - d) == -1)
  857. return -1;
  858. }
  859. return 0;
  860. }
  861. static int
  862. array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
  863. {
  864. if (i < 0 || i >= Py_SIZE(a)) {
  865. PyErr_SetString(PyExc_IndexError,
  866. "array assignment index out of range");
  867. return -1;
  868. }
  869. if (v == NULL)
  870. return array_del_slice(a, i, i+1);
  871. return (*a->ob_descr->setitem)(a, i, v);
  872. }
  873. static int
  874. setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
  875. {
  876. #ifndef NDEBUG
  877. array_state *state = find_array_state_by_type(Py_TYPE(a));
  878. assert(array_Check(a, state));
  879. #endif
  880. return array_ass_item((arrayobject *)a, i, v);
  881. }
  882. static int
  883. array_iter_extend(arrayobject *self, PyObject *bb)
  884. {
  885. PyObject *it, *v;
  886. it = PyObject_GetIter(bb);
  887. if (it == NULL)
  888. return -1;
  889. while ((v = PyIter_Next(it)) != NULL) {
  890. if (ins1(self, Py_SIZE(self), v) != 0) {
  891. Py_DECREF(v);
  892. Py_DECREF(it);
  893. return -1;
  894. }
  895. Py_DECREF(v);
  896. }
  897. Py_DECREF(it);
  898. if (PyErr_Occurred())
  899. return -1;
  900. return 0;
  901. }
  902. static int
  903. array_do_extend(array_state *state, arrayobject *self, PyObject *bb)
  904. {
  905. Py_ssize_t size, oldsize, bbsize;
  906. if (!array_Check(bb, state))
  907. return array_iter_extend(self, bb);
  908. #define b ((arrayobject *)bb)
  909. if (self->ob_descr != b->ob_descr) {
  910. PyErr_SetString(PyExc_TypeError,
  911. "can only extend with array of same kind");
  912. return -1;
  913. }
  914. if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
  915. ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
  916. PyErr_NoMemory();
  917. return -1;
  918. }
  919. oldsize = Py_SIZE(self);
  920. /* Get the size of bb before resizing the array since bb could be self. */
  921. bbsize = Py_SIZE(bb);
  922. size = oldsize + Py_SIZE(b);
  923. if (array_resize(self, size) == -1)
  924. return -1;
  925. if (bbsize > 0) {
  926. memcpy(self->ob_item + oldsize * self->ob_descr->itemsize,
  927. b->ob_item, bbsize * b->ob_descr->itemsize);
  928. }
  929. return 0;
  930. #undef b
  931. }
  932. static PyObject *
  933. array_inplace_concat(arrayobject *self, PyObject *bb)
  934. {
  935. array_state *state = find_array_state_by_type(Py_TYPE(self));
  936. if (!array_Check(bb, state)) {
  937. PyErr_Format(PyExc_TypeError,
  938. "can only extend array with array (not \"%.200s\")",
  939. Py_TYPE(bb)->tp_name);
  940. return NULL;
  941. }
  942. if (array_do_extend(state, self, bb) == -1)
  943. return NULL;
  944. return Py_NewRef(self);
  945. }
  946. static PyObject *
  947. array_inplace_repeat(arrayobject *self, Py_ssize_t n)
  948. {
  949. const Py_ssize_t array_size = Py_SIZE(self);
  950. if (array_size > 0 && n != 1 ) {
  951. if (n < 0)
  952. n = 0;
  953. if ((self->ob_descr->itemsize != 0) &&
  954. (array_size > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
  955. return PyErr_NoMemory();
  956. }
  957. Py_ssize_t size = array_size * self->ob_descr->itemsize;
  958. if (n > 0 && size > PY_SSIZE_T_MAX / n) {
  959. return PyErr_NoMemory();
  960. }
  961. if (array_resize(self, n * array_size) == -1)
  962. return NULL;
  963. _PyBytes_Repeat(self->ob_item, n*size, self->ob_item, size);
  964. }
  965. return Py_NewRef(self);
  966. }
  967. static PyObject *
  968. ins(arrayobject *self, Py_ssize_t where, PyObject *v)
  969. {
  970. if (ins1(self, where, v) != 0)
  971. return NULL;
  972. Py_RETURN_NONE;
  973. }
  974. /*[clinic input]
  975. array.array.count
  976. v: object
  977. /
  978. Return number of occurrences of v in the array.
  979. [clinic start generated code]*/
  980. static PyObject *
  981. array_array_count(arrayobject *self, PyObject *v)
  982. /*[clinic end generated code: output=3dd3624bf7135a3a input=d9bce9d65e39d1f5]*/
  983. {
  984. Py_ssize_t count = 0;
  985. Py_ssize_t i;
  986. for (i = 0; i < Py_SIZE(self); i++) {
  987. PyObject *selfi;
  988. int cmp;
  989. selfi = getarrayitem((PyObject *)self, i);
  990. if (selfi == NULL)
  991. return NULL;
  992. cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
  993. Py_DECREF(selfi);
  994. if (cmp > 0)
  995. count++;
  996. else if (cmp < 0)
  997. return NULL;
  998. }
  999. return PyLong_FromSsize_t(count);
  1000. }
  1001. /*[clinic input]
  1002. array.array.index
  1003. v: object
  1004. start: slice_index(accept={int}) = 0
  1005. stop: slice_index(accept={int}, c_default="PY_SSIZE_T_MAX") = sys.maxsize
  1006. /
  1007. Return index of first occurrence of v in the array.
  1008. Raise ValueError if the value is not present.
  1009. [clinic start generated code]*/
  1010. static PyObject *
  1011. array_array_index_impl(arrayobject *self, PyObject *v, Py_ssize_t start,
  1012. Py_ssize_t stop)
  1013. /*[clinic end generated code: output=c45e777880c99f52 input=089dff7baa7e5a7e]*/
  1014. {
  1015. if (start < 0) {
  1016. start += Py_SIZE(self);
  1017. if (start < 0) {
  1018. start = 0;
  1019. }
  1020. }
  1021. if (stop < 0) {
  1022. stop += Py_SIZE(self);
  1023. }
  1024. // Use Py_SIZE() for every iteration in case the array is mutated
  1025. // during PyObject_RichCompareBool()
  1026. for (Py_ssize_t i = start; i < stop && i < Py_SIZE(self); i++) {
  1027. PyObject *selfi;
  1028. int cmp;
  1029. selfi = getarrayitem((PyObject *)self, i);
  1030. if (selfi == NULL)
  1031. return NULL;
  1032. cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
  1033. Py_DECREF(selfi);
  1034. if (cmp > 0) {
  1035. return PyLong_FromSsize_t(i);
  1036. }
  1037. else if (cmp < 0)
  1038. return NULL;
  1039. }
  1040. PyErr_SetString(PyExc_ValueError, "array.index(x): x not in array");
  1041. return NULL;
  1042. }
  1043. static int
  1044. array_contains(arrayobject *self, PyObject *v)
  1045. {
  1046. Py_ssize_t i;
  1047. int cmp;
  1048. for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
  1049. PyObject *selfi = getarrayitem((PyObject *)self, i);
  1050. if (selfi == NULL)
  1051. return -1;
  1052. cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
  1053. Py_DECREF(selfi);
  1054. }
  1055. return cmp;
  1056. }
  1057. /*[clinic input]
  1058. array.array.remove
  1059. v: object
  1060. /
  1061. Remove the first occurrence of v in the array.
  1062. [clinic start generated code]*/
  1063. static PyObject *
  1064. array_array_remove(arrayobject *self, PyObject *v)
  1065. /*[clinic end generated code: output=bef06be9fdf9dceb input=0b1e5aed25590027]*/
  1066. {
  1067. Py_ssize_t i;
  1068. for (i = 0; i < Py_SIZE(self); i++) {
  1069. PyObject *selfi;
  1070. int cmp;
  1071. selfi = getarrayitem((PyObject *)self,i);
  1072. if (selfi == NULL)
  1073. return NULL;
  1074. cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
  1075. Py_DECREF(selfi);
  1076. if (cmp > 0) {
  1077. if (array_del_slice(self, i, i+1) != 0)
  1078. return NULL;
  1079. Py_RETURN_NONE;
  1080. }
  1081. else if (cmp < 0)
  1082. return NULL;
  1083. }
  1084. PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in array");
  1085. return NULL;
  1086. }
  1087. /*[clinic input]
  1088. array.array.pop
  1089. i: Py_ssize_t = -1
  1090. /
  1091. Return the i-th element and delete it from the array.
  1092. i defaults to -1.
  1093. [clinic start generated code]*/
  1094. static PyObject *
  1095. array_array_pop_impl(arrayobject *self, Py_ssize_t i)
  1096. /*[clinic end generated code: output=bc1f0c54fe5308e4 input=8e5feb4c1a11cd44]*/
  1097. {
  1098. PyObject *v;
  1099. if (Py_SIZE(self) == 0) {
  1100. /* Special-case most common failure cause */
  1101. PyErr_SetString(PyExc_IndexError, "pop from empty array");
  1102. return NULL;
  1103. }
  1104. if (i < 0)
  1105. i += Py_SIZE(self);
  1106. if (i < 0 || i >= Py_SIZE(self)) {
  1107. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  1108. return NULL;
  1109. }
  1110. v = getarrayitem((PyObject *)self, i);
  1111. if (v == NULL)
  1112. return NULL;
  1113. if (array_del_slice(self, i, i+1) != 0) {
  1114. Py_DECREF(v);
  1115. return NULL;
  1116. }
  1117. return v;
  1118. }
  1119. /*[clinic input]
  1120. array.array.extend
  1121. cls: defining_class
  1122. bb: object
  1123. /
  1124. Append items to the end of the array.
  1125. [clinic start generated code]*/
  1126. static PyObject *
  1127. array_array_extend_impl(arrayobject *self, PyTypeObject *cls, PyObject *bb)
  1128. /*[clinic end generated code: output=e65eb7588f0bc266 input=8eb6817ec4d2cb62]*/
  1129. {
  1130. array_state *state = get_array_state_by_class(cls);
  1131. if (array_do_extend(state, self, bb) == -1)
  1132. return NULL;
  1133. Py_RETURN_NONE;
  1134. }
  1135. /*[clinic input]
  1136. array.array.insert
  1137. i: Py_ssize_t
  1138. v: object
  1139. /
  1140. Insert a new item v into the array before position i.
  1141. [clinic start generated code]*/
  1142. static PyObject *
  1143. array_array_insert_impl(arrayobject *self, Py_ssize_t i, PyObject *v)
  1144. /*[clinic end generated code: output=5a3648e278348564 input=5577d1b4383e9313]*/
  1145. {
  1146. return ins(self, i, v);
  1147. }
  1148. /*[clinic input]
  1149. array.array.buffer_info
  1150. Return a tuple (address, length) giving the current memory address and the length in items of the buffer used to hold array's contents.
  1151. The length should be multiplied by the itemsize attribute to calculate
  1152. the buffer length in bytes.
  1153. [clinic start generated code]*/
  1154. static PyObject *
  1155. array_array_buffer_info_impl(arrayobject *self)
  1156. /*[clinic end generated code: output=9b2a4ec3ae7e98e7 input=a58bae5c6e1ac6a6]*/
  1157. {
  1158. PyObject *retval = NULL, *v;
  1159. retval = PyTuple_New(2);
  1160. if (!retval)
  1161. return NULL;
  1162. v = PyLong_FromVoidPtr(self->ob_item);
  1163. if (v == NULL) {
  1164. Py_DECREF(retval);
  1165. return NULL;
  1166. }
  1167. PyTuple_SET_ITEM(retval, 0, v);
  1168. v = PyLong_FromSsize_t(Py_SIZE(self));
  1169. if (v == NULL) {
  1170. Py_DECREF(retval);
  1171. return NULL;
  1172. }
  1173. PyTuple_SET_ITEM(retval, 1, v);
  1174. return retval;
  1175. }
  1176. /*[clinic input]
  1177. array.array.append
  1178. v: object
  1179. /
  1180. Append new value v to the end of the array.
  1181. [clinic start generated code]*/
  1182. static PyObject *
  1183. array_array_append(arrayobject *self, PyObject *v)
  1184. /*[clinic end generated code: output=745a0669bf8db0e2 input=0b98d9d78e78f0fa]*/
  1185. {
  1186. return ins(self, Py_SIZE(self), v);
  1187. }
  1188. /*[clinic input]
  1189. array.array.byteswap
  1190. Byteswap all items of the array.
  1191. If the items in the array are not 1, 2, 4, or 8 bytes in size, RuntimeError is
  1192. raised.
  1193. [clinic start generated code]*/
  1194. static PyObject *
  1195. array_array_byteswap_impl(arrayobject *self)
  1196. /*[clinic end generated code: output=5f8236cbdf0d90b5 input=6a85591b950a0186]*/
  1197. {
  1198. char *p;
  1199. Py_ssize_t i;
  1200. switch (self->ob_descr->itemsize) {
  1201. case 1:
  1202. break;
  1203. case 2:
  1204. for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
  1205. char p0 = p[0];
  1206. p[0] = p[1];
  1207. p[1] = p0;
  1208. }
  1209. break;
  1210. case 4:
  1211. for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
  1212. char p0 = p[0];
  1213. char p1 = p[1];
  1214. p[0] = p[3];
  1215. p[1] = p[2];
  1216. p[2] = p1;
  1217. p[3] = p0;
  1218. }
  1219. break;
  1220. case 8:
  1221. for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
  1222. char p0 = p[0];
  1223. char p1 = p[1];
  1224. char p2 = p[2];
  1225. char p3 = p[3];
  1226. p[0] = p[7];
  1227. p[1] = p[6];
  1228. p[2] = p[5];
  1229. p[3] = p[4];
  1230. p[4] = p3;
  1231. p[5] = p2;
  1232. p[6] = p1;
  1233. p[7] = p0;
  1234. }
  1235. break;
  1236. default:
  1237. PyErr_SetString(PyExc_RuntimeError,
  1238. "don't know how to byteswap this array type");
  1239. return NULL;
  1240. }
  1241. Py_RETURN_NONE;
  1242. }
  1243. /*[clinic input]
  1244. array.array.reverse
  1245. Reverse the order of the items in the array.
  1246. [clinic start generated code]*/
  1247. static PyObject *
  1248. array_array_reverse_impl(arrayobject *self)
  1249. /*[clinic end generated code: output=c04868b36f6f4089 input=cd904f01b27d966a]*/
  1250. {
  1251. Py_ssize_t itemsize = self->ob_descr->itemsize;
  1252. char *p, *q;
  1253. /* little buffer to hold items while swapping */
  1254. char tmp[256]; /* 8 is probably enough -- but why skimp */
  1255. assert((size_t)itemsize <= sizeof(tmp));
  1256. if (Py_SIZE(self) > 1) {
  1257. for (p = self->ob_item,
  1258. q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
  1259. p < q;
  1260. p += itemsize, q -= itemsize) {
  1261. /* memory areas guaranteed disjoint, so memcpy
  1262. * is safe (& memmove may be slower).
  1263. */
  1264. memcpy(tmp, p, itemsize);
  1265. memcpy(p, q, itemsize);
  1266. memcpy(q, tmp, itemsize);
  1267. }
  1268. }
  1269. Py_RETURN_NONE;
  1270. }
  1271. /*[clinic input]
  1272. array.array.fromfile
  1273. cls: defining_class
  1274. f: object
  1275. n: Py_ssize_t
  1276. /
  1277. Read n objects from the file object f and append them to the end of the array.
  1278. [clinic start generated code]*/
  1279. static PyObject *
  1280. array_array_fromfile_impl(arrayobject *self, PyTypeObject *cls, PyObject *f,
  1281. Py_ssize_t n)
  1282. /*[clinic end generated code: output=83a667080b345ebc input=3822e907c1c11f1a]*/
  1283. {
  1284. PyObject *b, *res;
  1285. Py_ssize_t itemsize = self->ob_descr->itemsize;
  1286. Py_ssize_t nbytes;
  1287. int not_enough_bytes;
  1288. if (n < 0) {
  1289. PyErr_SetString(PyExc_ValueError, "negative count");
  1290. return NULL;
  1291. }
  1292. if (n > PY_SSIZE_T_MAX / itemsize) {
  1293. PyErr_NoMemory();
  1294. return NULL;
  1295. }
  1296. array_state *state = get_array_state_by_class(cls);
  1297. assert(state != NULL);
  1298. nbytes = n * itemsize;
  1299. b = _PyObject_CallMethod(f, state->str_read, "n", nbytes);
  1300. if (b == NULL)
  1301. return NULL;
  1302. if (!PyBytes_Check(b)) {
  1303. PyErr_SetString(PyExc_TypeError,
  1304. "read() didn't return bytes");
  1305. Py_DECREF(b);
  1306. return NULL;
  1307. }
  1308. not_enough_bytes = (PyBytes_GET_SIZE(b) != nbytes);
  1309. res = array_array_frombytes(self, b);
  1310. Py_DECREF(b);
  1311. if (res == NULL)
  1312. return NULL;
  1313. if (not_enough_bytes) {
  1314. PyErr_SetString(PyExc_EOFError,
  1315. "read() didn't return enough bytes");
  1316. Py_DECREF(res);
  1317. return NULL;
  1318. }
  1319. return res;
  1320. }
  1321. /*[clinic input]
  1322. array.array.tofile
  1323. cls: defining_class
  1324. f: object
  1325. /
  1326. Write all items (as machine values) to the file object f.
  1327. [clinic start generated code]*/
  1328. static PyObject *
  1329. array_array_tofile_impl(arrayobject *self, PyTypeObject *cls, PyObject *f)
  1330. /*[clinic end generated code: output=4560c628d9c18bc2 input=5a24da7a7b407b52]*/
  1331. {
  1332. Py_ssize_t nbytes = Py_SIZE(self) * self->ob_descr->itemsize;
  1333. /* Write 64K blocks at a time */
  1334. /* XXX Make the block size settable */
  1335. int BLOCKSIZE = 64*1024;
  1336. Py_ssize_t nblocks = (nbytes + BLOCKSIZE - 1) / BLOCKSIZE;
  1337. Py_ssize_t i;
  1338. if (Py_SIZE(self) == 0)
  1339. goto done;
  1340. array_state *state = get_array_state_by_class(cls);
  1341. assert(state != NULL);
  1342. for (i = 0; i < nblocks; i++) {
  1343. char* ptr = self->ob_item + i*BLOCKSIZE;
  1344. Py_ssize_t size = BLOCKSIZE;
  1345. PyObject *bytes, *res;
  1346. if (i*BLOCKSIZE + size > nbytes)
  1347. size = nbytes - i*BLOCKSIZE;
  1348. bytes = PyBytes_FromStringAndSize(ptr, size);
  1349. if (bytes == NULL)
  1350. return NULL;
  1351. res = PyObject_CallMethodOneArg(f, state->str_write, bytes);
  1352. Py_DECREF(bytes);
  1353. if (res == NULL)
  1354. return NULL;
  1355. Py_DECREF(res); /* drop write result */
  1356. }
  1357. done:
  1358. Py_RETURN_NONE;
  1359. }
  1360. /*[clinic input]
  1361. array.array.fromlist
  1362. list: object
  1363. /
  1364. Append items to array from list.
  1365. [clinic start generated code]*/
  1366. static PyObject *
  1367. array_array_fromlist(arrayobject *self, PyObject *list)
  1368. /*[clinic end generated code: output=26411c2d228a3e3f input=be2605a96c49680f]*/
  1369. {
  1370. Py_ssize_t n;
  1371. if (!PyList_Check(list)) {
  1372. PyErr_SetString(PyExc_TypeError, "arg must be list");
  1373. return NULL;
  1374. }
  1375. n = PyList_Size(list);
  1376. if (n > 0) {
  1377. Py_ssize_t i, old_size;
  1378. old_size = Py_SIZE(self);
  1379. if (array_resize(self, old_size + n) == -1)
  1380. return NULL;
  1381. for (i = 0; i < n; i++) {
  1382. PyObject *v = PyList_GET_ITEM(list, i);
  1383. if ((*self->ob_descr->setitem)(self,
  1384. Py_SIZE(self) - n + i, v) != 0) {
  1385. array_resize(self, old_size);
  1386. return NULL;
  1387. }
  1388. if (n != PyList_GET_SIZE(list)) {
  1389. PyErr_SetString(PyExc_RuntimeError,
  1390. "list changed size during iteration");
  1391. array_resize(self, old_size);
  1392. return NULL;
  1393. }
  1394. }
  1395. }
  1396. Py_RETURN_NONE;
  1397. }
  1398. /*[clinic input]
  1399. array.array.tolist
  1400. Convert array to an ordinary list with the same items.
  1401. [clinic start generated code]*/
  1402. static PyObject *
  1403. array_array_tolist_impl(arrayobject *self)
  1404. /*[clinic end generated code: output=00b60cc9eab8ef89 input=a8d7784a94f86b53]*/
  1405. {
  1406. PyObject *list = PyList_New(Py_SIZE(self));
  1407. Py_ssize_t i;
  1408. if (list == NULL)
  1409. return NULL;
  1410. for (i = 0; i < Py_SIZE(self); i++) {
  1411. PyObject *v = getarrayitem((PyObject *)self, i);
  1412. if (v == NULL)
  1413. goto error;
  1414. PyList_SET_ITEM(list, i, v);
  1415. }
  1416. return list;
  1417. error:
  1418. Py_DECREF(list);
  1419. return NULL;
  1420. }
  1421. static PyObject *
  1422. frombytes(arrayobject *self, Py_buffer *buffer)
  1423. {
  1424. int itemsize = self->ob_descr->itemsize;
  1425. Py_ssize_t n;
  1426. if (buffer->itemsize != 1) {
  1427. PyBuffer_Release(buffer);
  1428. PyErr_SetString(PyExc_TypeError, "a bytes-like object is required");
  1429. return NULL;
  1430. }
  1431. n = buffer->len;
  1432. if (n % itemsize != 0) {
  1433. PyBuffer_Release(buffer);
  1434. PyErr_SetString(PyExc_ValueError,
  1435. "bytes length not a multiple of item size");
  1436. return NULL;
  1437. }
  1438. n = n / itemsize;
  1439. if (n > 0) {
  1440. Py_ssize_t old_size = Py_SIZE(self);
  1441. if ((n > PY_SSIZE_T_MAX - old_size) ||
  1442. ((old_size + n) > PY_SSIZE_T_MAX / itemsize)) {
  1443. PyBuffer_Release(buffer);
  1444. return PyErr_NoMemory();
  1445. }
  1446. if (array_resize(self, old_size + n) == -1) {
  1447. PyBuffer_Release(buffer);
  1448. return NULL;
  1449. }
  1450. memcpy(self->ob_item + old_size * itemsize,
  1451. buffer->buf, n * itemsize);
  1452. }
  1453. PyBuffer_Release(buffer);
  1454. Py_RETURN_NONE;
  1455. }
  1456. /*[clinic input]
  1457. array.array.frombytes
  1458. buffer: Py_buffer
  1459. /
  1460. Appends items from the string, interpreting it as an array of machine values, as if it had been read from a file using the fromfile() method.
  1461. [clinic start generated code]*/
  1462. static PyObject *
  1463. array_array_frombytes_impl(arrayobject *self, Py_buffer *buffer)
  1464. /*[clinic end generated code: output=d9842c8f7510a516 input=378db226dfac949e]*/
  1465. {
  1466. return frombytes(self, buffer);
  1467. }
  1468. /*[clinic input]
  1469. array.array.tobytes
  1470. Convert the array to an array of machine values and return the bytes representation.
  1471. [clinic start generated code]*/
  1472. static PyObject *
  1473. array_array_tobytes_impl(arrayobject *self)
  1474. /*[clinic end generated code: output=87318e4edcdc2bb6 input=90ee495f96de34f5]*/
  1475. {
  1476. if (Py_SIZE(self) <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
  1477. return PyBytes_FromStringAndSize(self->ob_item,
  1478. Py_SIZE(self) * self->ob_descr->itemsize);
  1479. } else {
  1480. return PyErr_NoMemory();
  1481. }
  1482. }
  1483. /*[clinic input]
  1484. array.array.fromunicode
  1485. ustr: unicode
  1486. /
  1487. Extends this array with data from the unicode string ustr.
  1488. The array must be a unicode type array; otherwise a ValueError is raised.
  1489. Use array.frombytes(ustr.encode(...)) to append Unicode data to an array of
  1490. some other type.
  1491. [clinic start generated code]*/
  1492. static PyObject *
  1493. array_array_fromunicode_impl(arrayobject *self, PyObject *ustr)
  1494. /*[clinic end generated code: output=24359f5e001a7f2b input=025db1fdade7a4ce]*/
  1495. {
  1496. if (self->ob_descr->typecode != 'u') {
  1497. PyErr_SetString(PyExc_ValueError,
  1498. "fromunicode() may only be called on "
  1499. "unicode type arrays");
  1500. return NULL;
  1501. }
  1502. Py_ssize_t ustr_length = PyUnicode_AsWideChar(ustr, NULL, 0);
  1503. assert(ustr_length > 0);
  1504. if (ustr_length > 1) {
  1505. ustr_length--; /* trim trailing NUL character */
  1506. Py_ssize_t old_size = Py_SIZE(self);
  1507. if (array_resize(self, old_size + ustr_length) == -1) {
  1508. return NULL;
  1509. }
  1510. // must not fail
  1511. PyUnicode_AsWideChar(
  1512. ustr, ((wchar_t *)self->ob_item) + old_size, ustr_length);
  1513. }
  1514. Py_RETURN_NONE;
  1515. }
  1516. /*[clinic input]
  1517. array.array.tounicode
  1518. Extends this array with data from the unicode string ustr.
  1519. Convert the array to a unicode string. The array must be a unicode type array;
  1520. otherwise a ValueError is raised. Use array.tobytes().decode() to obtain a
  1521. unicode string from an array of some other type.
  1522. [clinic start generated code]*/
  1523. static PyObject *
  1524. array_array_tounicode_impl(arrayobject *self)
  1525. /*[clinic end generated code: output=08e442378336e1ef input=127242eebe70b66d]*/
  1526. {
  1527. if (self->ob_descr->typecode != 'u') {
  1528. PyErr_SetString(PyExc_ValueError,
  1529. "tounicode() may only be called on unicode type arrays");
  1530. return NULL;
  1531. }
  1532. return PyUnicode_FromWideChar((wchar_t *) self->ob_item, Py_SIZE(self));
  1533. }
  1534. /*[clinic input]
  1535. array.array.__sizeof__
  1536. Size of the array in memory, in bytes.
  1537. [clinic start generated code]*/
  1538. static PyObject *
  1539. array_array___sizeof___impl(arrayobject *self)
  1540. /*[clinic end generated code: output=d8e1c61ebbe3eaed input=805586565bf2b3c6]*/
  1541. {
  1542. size_t res = _PyObject_SIZE(Py_TYPE(self));
  1543. res += (size_t)self->allocated * (size_t)self->ob_descr->itemsize;
  1544. return PyLong_FromSize_t(res);
  1545. }
  1546. /*********************** Pickling support ************************/
  1547. static const struct mformatdescr {
  1548. size_t size;
  1549. int is_signed;
  1550. int is_big_endian;
  1551. } mformat_descriptors[] = {
  1552. {1, 0, 0}, /* 0: UNSIGNED_INT8 */
  1553. {1, 1, 0}, /* 1: SIGNED_INT8 */
  1554. {2, 0, 0}, /* 2: UNSIGNED_INT16_LE */
  1555. {2, 0, 1}, /* 3: UNSIGNED_INT16_BE */
  1556. {2, 1, 0}, /* 4: SIGNED_INT16_LE */
  1557. {2, 1, 1}, /* 5: SIGNED_INT16_BE */
  1558. {4, 0, 0}, /* 6: UNSIGNED_INT32_LE */
  1559. {4, 0, 1}, /* 7: UNSIGNED_INT32_BE */
  1560. {4, 1, 0}, /* 8: SIGNED_INT32_LE */
  1561. {4, 1, 1}, /* 9: SIGNED_INT32_BE */
  1562. {8, 0, 0}, /* 10: UNSIGNED_INT64_LE */
  1563. {8, 0, 1}, /* 11: UNSIGNED_INT64_BE */
  1564. {8, 1, 0}, /* 12: SIGNED_INT64_LE */
  1565. {8, 1, 1}, /* 13: SIGNED_INT64_BE */
  1566. {4, 0, 0}, /* 14: IEEE_754_FLOAT_LE */
  1567. {4, 0, 1}, /* 15: IEEE_754_FLOAT_BE */
  1568. {8, 0, 0}, /* 16: IEEE_754_DOUBLE_LE */
  1569. {8, 0, 1}, /* 17: IEEE_754_DOUBLE_BE */
  1570. {4, 0, 0}, /* 18: UTF16_LE */
  1571. {4, 0, 1}, /* 19: UTF16_BE */
  1572. {8, 0, 0}, /* 20: UTF32_LE */
  1573. {8, 0, 1} /* 21: UTF32_BE */
  1574. };
  1575. /*
  1576. * Internal: This function is used to find the machine format of a given
  1577. * array type code. This returns UNKNOWN_FORMAT when the machine format cannot
  1578. * be found.
  1579. */
  1580. static enum machine_format_code
  1581. typecode_to_mformat_code(char typecode)
  1582. {
  1583. const int is_big_endian = PY_BIG_ENDIAN;
  1584. size_t intsize;
  1585. int is_signed;
  1586. switch (typecode) {
  1587. case 'b':
  1588. return SIGNED_INT8;
  1589. case 'B':
  1590. return UNSIGNED_INT8;
  1591. case 'u':
  1592. if (sizeof(Py_UNICODE) == 2) {
  1593. return UTF16_LE + is_big_endian;
  1594. }
  1595. if (sizeof(Py_UNICODE) == 4) {
  1596. return UTF32_LE + is_big_endian;
  1597. }
  1598. return UNKNOWN_FORMAT;
  1599. case 'f':
  1600. if (sizeof(float) == 4) {
  1601. const float y = 16711938.0;
  1602. if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
  1603. return IEEE_754_FLOAT_BE;
  1604. if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
  1605. return IEEE_754_FLOAT_LE;
  1606. }
  1607. return UNKNOWN_FORMAT;
  1608. case 'd':
  1609. if (sizeof(double) == 8) {
  1610. const double x = 9006104071832581.0;
  1611. if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
  1612. return IEEE_754_DOUBLE_BE;
  1613. if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
  1614. return IEEE_754_DOUBLE_LE;
  1615. }
  1616. return UNKNOWN_FORMAT;
  1617. /* Integers */
  1618. case 'h':
  1619. intsize = sizeof(short);
  1620. is_signed = 1;
  1621. break;
  1622. case 'H':
  1623. intsize = sizeof(short);
  1624. is_signed = 0;
  1625. break;
  1626. case 'i':
  1627. intsize = sizeof(int);
  1628. is_signed = 1;
  1629. break;
  1630. case 'I':
  1631. intsize = sizeof(int);
  1632. is_signed = 0;
  1633. break;
  1634. case 'l':
  1635. intsize = sizeof(long);
  1636. is_signed = 1;
  1637. break;
  1638. case 'L':
  1639. intsize = sizeof(long);
  1640. is_signed = 0;
  1641. break;
  1642. case 'q':
  1643. intsize = sizeof(long long);
  1644. is_signed = 1;
  1645. break;
  1646. case 'Q':
  1647. intsize = sizeof(long long);
  1648. is_signed = 0;
  1649. break;
  1650. default:
  1651. return UNKNOWN_FORMAT;
  1652. }
  1653. switch (intsize) {
  1654. case 2:
  1655. return UNSIGNED_INT16_LE + is_big_endian + (2 * is_signed);
  1656. case 4:
  1657. return UNSIGNED_INT32_LE + is_big_endian + (2 * is_signed);
  1658. case 8:
  1659. return UNSIGNED_INT64_LE + is_big_endian + (2 * is_signed);
  1660. default:
  1661. return UNKNOWN_FORMAT;
  1662. }
  1663. }
  1664. /* Forward declaration. */
  1665. static PyObject *array_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
  1666. /*
  1667. * Internal: This function wraps the array constructor--i.e., array_new()--to
  1668. * allow the creation of array objects from C code without having to deal
  1669. * directly the tuple argument of array_new(). The typecode argument is a
  1670. * Unicode character value, like 'i' or 'f' for example, representing an array
  1671. * type code. The items argument is a bytes or a list object from which
  1672. * contains the initial value of the array.
  1673. *
  1674. * On success, this functions returns the array object created. Otherwise,
  1675. * NULL is returned to indicate a failure.
  1676. */
  1677. static PyObject *
  1678. make_array(PyTypeObject *arraytype, char typecode, PyObject *items)
  1679. {
  1680. PyObject *new_args;
  1681. PyObject *array_obj;
  1682. PyObject *typecode_obj;
  1683. assert(arraytype != NULL);
  1684. assert(items != NULL);
  1685. typecode_obj = PyUnicode_FromOrdinal(typecode);
  1686. if (typecode_obj == NULL)
  1687. return NULL;
  1688. new_args = PyTuple_New(2);
  1689. if (new_args == NULL) {
  1690. Py_DECREF(typecode_obj);
  1691. return NULL;
  1692. }
  1693. PyTuple_SET_ITEM(new_args, 0, typecode_obj);
  1694. PyTuple_SET_ITEM(new_args, 1, Py_NewRef(items));
  1695. array_obj = array_new(arraytype, new_args, NULL);
  1696. Py_DECREF(new_args);
  1697. if (array_obj == NULL)
  1698. return NULL;
  1699. return array_obj;
  1700. }
  1701. /*
  1702. * This functions is a special constructor used when unpickling an array. It
  1703. * provides a portable way to rebuild an array from its memory representation.
  1704. */
  1705. /*[clinic input]
  1706. array._array_reconstructor
  1707. arraytype: object(type="PyTypeObject *")
  1708. typecode: int(accept={str})
  1709. mformat_code: int(type="enum machine_format_code")
  1710. items: object
  1711. /
  1712. Internal. Used for pickling support.
  1713. [clinic start generated code]*/
  1714. static PyObject *
  1715. array__array_reconstructor_impl(PyObject *module, PyTypeObject *arraytype,
  1716. int typecode,
  1717. enum machine_format_code mformat_code,
  1718. PyObject *items)
  1719. /*[clinic end generated code: output=e05263141ba28365 input=2464dc8f4c7736b5]*/
  1720. {
  1721. array_state *state = get_array_state(module);
  1722. PyObject *converted_items;
  1723. PyObject *result;
  1724. const struct arraydescr *descr;
  1725. if (!PyType_Check(arraytype)) {
  1726. PyErr_Format(PyExc_TypeError,
  1727. "first argument must be a type object, not %.200s",
  1728. Py_TYPE(arraytype)->tp_name);
  1729. return NULL;
  1730. }
  1731. if (!PyType_IsSubtype(arraytype, state->ArrayType)) {
  1732. PyErr_Format(PyExc_TypeError,
  1733. "%.200s is not a subtype of %.200s",
  1734. arraytype->tp_name, state->ArrayType->tp_name);
  1735. return NULL;
  1736. }
  1737. for (descr = descriptors; descr->typecode != '\0'; descr++) {
  1738. if ((int)descr->typecode == typecode)
  1739. break;
  1740. }
  1741. if (descr->typecode == '\0') {
  1742. PyErr_SetString(PyExc_ValueError,
  1743. "second argument must be a valid type code");
  1744. return NULL;
  1745. }
  1746. if (mformat_code < MACHINE_FORMAT_CODE_MIN ||
  1747. mformat_code > MACHINE_FORMAT_CODE_MAX) {
  1748. PyErr_SetString(PyExc_ValueError,
  1749. "third argument must be a valid machine format code.");
  1750. return NULL;
  1751. }
  1752. if (!PyBytes_Check(items)) {
  1753. PyErr_Format(PyExc_TypeError,
  1754. "fourth argument should be bytes, not %.200s",
  1755. Py_TYPE(items)->tp_name);
  1756. return NULL;
  1757. }
  1758. /* Fast path: No decoding has to be done. */
  1759. if (mformat_code == typecode_to_mformat_code((char)typecode) ||
  1760. mformat_code == UNKNOWN_FORMAT) {
  1761. return make_array(arraytype, (char)typecode, items);
  1762. }
  1763. /* Slow path: Decode the byte string according to the given machine
  1764. * format code. This occurs when the computer unpickling the array
  1765. * object is architecturally different from the one that pickled the
  1766. * array.
  1767. */
  1768. if (Py_SIZE(items) % mformat_descriptors[mformat_code].size != 0) {
  1769. PyErr_SetString(PyExc_ValueError,
  1770. "string length not a multiple of item size");
  1771. return NULL;
  1772. }
  1773. switch (mformat_code) {
  1774. case IEEE_754_FLOAT_LE:
  1775. case IEEE_754_FLOAT_BE: {
  1776. Py_ssize_t i;
  1777. int le = (mformat_code == IEEE_754_FLOAT_LE) ? 1 : 0;
  1778. Py_ssize_t itemcount = Py_SIZE(items) / 4;
  1779. const char *memstr = PyBytes_AS_STRING(items);
  1780. converted_items = PyList_New(itemcount);
  1781. if (converted_items == NULL)
  1782. return NULL;
  1783. for (i = 0; i < itemcount; i++) {
  1784. PyObject *pyfloat = PyFloat_FromDouble(
  1785. PyFloat_Unpack4(&memstr[i * 4], le));
  1786. if (pyfloat == NULL) {
  1787. Py_DECREF(converted_items);
  1788. return NULL;
  1789. }
  1790. PyList_SET_ITEM(converted_items, i, pyfloat);
  1791. }
  1792. break;
  1793. }
  1794. case IEEE_754_DOUBLE_LE:
  1795. case IEEE_754_DOUBLE_BE: {
  1796. Py_ssize_t i;
  1797. int le = (mformat_code == IEEE_754_DOUBLE_LE) ? 1 : 0;
  1798. Py_ssize_t itemcount = Py_SIZE(items) / 8;
  1799. const char *memstr = PyBytes_AS_STRING(items);
  1800. converted_items = PyList_New(itemcount);
  1801. if (converted_items == NULL)
  1802. return NULL;
  1803. for (i = 0; i < itemcount; i++) {
  1804. PyObject *pyfloat = PyFloat_FromDouble(
  1805. PyFloat_Unpack8(&memstr[i * 8], le));
  1806. if (pyfloat == NULL) {
  1807. Py_DECREF(converted_items);
  1808. return NULL;
  1809. }
  1810. PyList_SET_ITEM(converted_items, i, pyfloat);
  1811. }
  1812. break;
  1813. }
  1814. case UTF16_LE:
  1815. case UTF16_BE: {
  1816. int byteorder = (mformat_code == UTF16_LE) ? -1 : 1;
  1817. converted_items = PyUnicode_DecodeUTF16(
  1818. PyBytes_AS_STRING(items), Py_SIZE(items),
  1819. "strict", &byteorder);
  1820. if (converted_items == NULL)
  1821. return NULL;
  1822. break;
  1823. }
  1824. case UTF32_LE:
  1825. case UTF32_BE: {
  1826. int byteorder = (mformat_code == UTF32_LE) ? -1 : 1;
  1827. converted_items = PyUnicode_DecodeUTF32(
  1828. PyBytes_AS_STRING(items), Py_SIZE(items),
  1829. "strict", &byteorder);
  1830. if (converted_items == NULL)
  1831. return NULL;
  1832. break;
  1833. }
  1834. case UNSIGNED_INT8:
  1835. case SIGNED_INT8:
  1836. case UNSIGNED_INT16_LE:
  1837. case UNSIGNED_INT16_BE:
  1838. case SIGNED_INT16_LE:
  1839. case SIGNED_INT16_BE:
  1840. case UNSIGNED_INT32_LE:
  1841. case UNSIGNED_INT32_BE:
  1842. case SIGNED_INT32_LE:
  1843. case SIGNED_INT32_BE:
  1844. case UNSIGNED_INT64_LE:
  1845. case UNSIGNED_INT64_BE:
  1846. case SIGNED_INT64_LE:
  1847. case SIGNED_INT64_BE: {
  1848. Py_ssize_t i;
  1849. const struct mformatdescr mf_descr =
  1850. mformat_descriptors[mformat_code];
  1851. Py_ssize_t itemcount = Py_SIZE(items) / mf_descr.size;
  1852. const unsigned char *memstr =
  1853. (unsigned char *)PyBytes_AS_STRING(items);
  1854. const struct arraydescr *descr;
  1855. /* If possible, try to pack array's items using a data type
  1856. * that fits better. This may result in an array with narrower
  1857. * or wider elements.
  1858. *
  1859. * For example, if a 32-bit machine pickles an L-code array of
  1860. * unsigned longs, then the array will be unpickled by 64-bit
  1861. * machine as an I-code array of unsigned ints.
  1862. *
  1863. * XXX: Is it possible to write a unit test for this?
  1864. */
  1865. for (descr = descriptors; descr->typecode != '\0'; descr++) {
  1866. if (descr->is_integer_type &&
  1867. (size_t)descr->itemsize == mf_descr.size &&
  1868. descr->is_signed == mf_descr.is_signed)
  1869. typecode = descr->typecode;
  1870. }
  1871. converted_items = PyList_New(itemcount);
  1872. if (converted_items == NULL)
  1873. return NULL;
  1874. for (i = 0; i < itemcount; i++) {
  1875. PyObject *pylong;
  1876. pylong = _PyLong_FromByteArray(
  1877. &memstr[i * mf_descr.size],
  1878. mf_descr.size,
  1879. !mf_descr.is_big_endian,
  1880. mf_descr.is_signed);
  1881. if (pylong == NULL) {
  1882. Py_DECREF(converted_items);
  1883. return NULL;
  1884. }
  1885. PyList_SET_ITEM(converted_items, i, pylong);
  1886. }
  1887. break;
  1888. }
  1889. case UNKNOWN_FORMAT:
  1890. /* Impossible, but needed to shut up GCC about the unhandled
  1891. * enumeration value.
  1892. */
  1893. default:
  1894. PyErr_BadArgument();
  1895. return NULL;
  1896. }
  1897. result = make_array(arraytype, (char)typecode, converted_items);
  1898. Py_DECREF(converted_items);
  1899. return result;
  1900. }
  1901. /*[clinic input]
  1902. array.array.__reduce_ex__
  1903. cls: defining_class
  1904. value: object
  1905. /
  1906. Return state information for pickling.
  1907. [clinic start generated code]*/
  1908. static PyObject *
  1909. array_array___reduce_ex___impl(arrayobject *self, PyTypeObject *cls,
  1910. PyObject *value)
  1911. /*[clinic end generated code: output=4958ee5d79452ad5 input=19968cf0f91d3eea]*/
  1912. {
  1913. PyObject *dict;
  1914. PyObject *result;
  1915. PyObject *array_str;
  1916. int typecode = self->ob_descr->typecode;
  1917. int mformat_code;
  1918. long protocol;
  1919. array_state *state = get_array_state_by_class(cls);
  1920. assert(state != NULL);
  1921. if (state->array_reconstructor == NULL) {
  1922. state->array_reconstructor = _PyImport_GetModuleAttrString(
  1923. "array", "_array_reconstructor");
  1924. if (state->array_reconstructor == NULL) {
  1925. return NULL;
  1926. }
  1927. }
  1928. if (!PyLong_Check(value)) {
  1929. PyErr_SetString(PyExc_TypeError,
  1930. "__reduce_ex__ argument should be an integer");
  1931. return NULL;
  1932. }
  1933. protocol = PyLong_AsLong(value);
  1934. if (protocol == -1 && PyErr_Occurred())
  1935. return NULL;
  1936. if (_PyObject_LookupAttr((PyObject *)self, state->str___dict__, &dict) < 0) {
  1937. return NULL;
  1938. }
  1939. if (dict == NULL) {
  1940. dict = Py_NewRef(Py_None);
  1941. }
  1942. mformat_code = typecode_to_mformat_code(typecode);
  1943. if (mformat_code == UNKNOWN_FORMAT || protocol < 3) {
  1944. /* Convert the array to a list if we got something weird
  1945. * (e.g., non-IEEE floats), or we are pickling the array using
  1946. * a Python 2.x compatible protocol.
  1947. *
  1948. * It is necessary to use a list representation for Python 2.x
  1949. * compatible pickle protocol, since Python 2's str objects
  1950. * are unpickled as unicode by Python 3. Thus it is impossible
  1951. * to make arrays unpicklable by Python 3 by using their memory
  1952. * representation, unless we resort to ugly hacks such as
  1953. * coercing unicode objects to bytes in array_reconstructor.
  1954. */
  1955. PyObject *list;
  1956. list = array_array_tolist_impl(self);
  1957. if (list == NULL) {
  1958. Py_DECREF(dict);
  1959. return NULL;
  1960. }
  1961. result = Py_BuildValue(
  1962. "O(CO)O", Py_TYPE(self), typecode, list, dict);
  1963. Py_DECREF(list);
  1964. Py_DECREF(dict);
  1965. return result;
  1966. }
  1967. array_str = array_array_tobytes_impl(self);
  1968. if (array_str == NULL) {
  1969. Py_DECREF(dict);
  1970. return NULL;
  1971. }
  1972. assert(state->array_reconstructor != NULL);
  1973. result = Py_BuildValue(
  1974. "O(OCiN)O", state->array_reconstructor, Py_TYPE(self), typecode,
  1975. mformat_code, array_str, dict);
  1976. Py_DECREF(dict);
  1977. return result;
  1978. }
  1979. static PyObject *
  1980. array_get_typecode(arrayobject *a, void *closure)
  1981. {
  1982. char typecode = a->ob_descr->typecode;
  1983. return PyUnicode_FromOrdinal(typecode);
  1984. }
  1985. static PyObject *
  1986. array_get_itemsize(arrayobject *a, void *closure)
  1987. {
  1988. return PyLong_FromLong((long)a->ob_descr->itemsize);
  1989. }
  1990. static PyGetSetDef array_getsets [] = {
  1991. {"typecode", (getter) array_get_typecode, NULL,
  1992. "the typecode character used to create the array"},
  1993. {"itemsize", (getter) array_get_itemsize, NULL,
  1994. "the size, in bytes, of one array item"},
  1995. {NULL}
  1996. };
  1997. static PyMethodDef array_methods[] = {
  1998. ARRAY_ARRAY_APPEND_METHODDEF
  1999. ARRAY_ARRAY_BUFFER_INFO_METHODDEF
  2000. ARRAY_ARRAY_BYTESWAP_METHODDEF
  2001. ARRAY_ARRAY___COPY___METHODDEF
  2002. ARRAY_ARRAY_COUNT_METHODDEF
  2003. ARRAY_ARRAY___DEEPCOPY___METHODDEF
  2004. ARRAY_ARRAY_EXTEND_METHODDEF
  2005. ARRAY_ARRAY_FROMFILE_METHODDEF
  2006. ARRAY_ARRAY_FROMLIST_METHODDEF
  2007. ARRAY_ARRAY_FROMBYTES_METHODDEF
  2008. ARRAY_ARRAY_FROMUNICODE_METHODDEF
  2009. ARRAY_ARRAY_INDEX_METHODDEF
  2010. ARRAY_ARRAY_INSERT_METHODDEF
  2011. ARRAY_ARRAY_POP_METHODDEF
  2012. ARRAY_ARRAY___REDUCE_EX___METHODDEF
  2013. ARRAY_ARRAY_REMOVE_METHODDEF
  2014. ARRAY_ARRAY_REVERSE_METHODDEF
  2015. ARRAY_ARRAY_TOFILE_METHODDEF
  2016. ARRAY_ARRAY_TOLIST_METHODDEF
  2017. ARRAY_ARRAY_TOBYTES_METHODDEF
  2018. ARRAY_ARRAY_TOUNICODE_METHODDEF
  2019. ARRAY_ARRAY___SIZEOF___METHODDEF
  2020. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  2021. {NULL, NULL} /* sentinel */
  2022. };
  2023. static PyObject *
  2024. array_repr(arrayobject *a)
  2025. {
  2026. char typecode;
  2027. PyObject *s, *v = NULL;
  2028. Py_ssize_t len;
  2029. len = Py_SIZE(a);
  2030. typecode = a->ob_descr->typecode;
  2031. if (len == 0) {
  2032. return PyUnicode_FromFormat("%s('%c')",
  2033. _PyType_Name(Py_TYPE(a)), (int)typecode);
  2034. }
  2035. if (typecode == 'u') {
  2036. v = array_array_tounicode_impl(a);
  2037. } else {
  2038. v = array_array_tolist_impl(a);
  2039. }
  2040. if (v == NULL)
  2041. return NULL;
  2042. s = PyUnicode_FromFormat("%s('%c', %R)",
  2043. _PyType_Name(Py_TYPE(a)), (int)typecode, v);
  2044. Py_DECREF(v);
  2045. return s;
  2046. }
  2047. static PyObject*
  2048. array_subscr(arrayobject* self, PyObject* item)
  2049. {
  2050. array_state *state = find_array_state_by_type(Py_TYPE(self));
  2051. if (PyIndex_Check(item)) {
  2052. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  2053. if (i==-1 && PyErr_Occurred()) {
  2054. return NULL;
  2055. }
  2056. if (i < 0)
  2057. i += Py_SIZE(self);
  2058. return array_item(self, i);
  2059. }
  2060. else if (PySlice_Check(item)) {
  2061. Py_ssize_t start, stop, step, slicelength, i;
  2062. size_t cur;
  2063. PyObject* result;
  2064. arrayobject* ar;
  2065. int itemsize = self->ob_descr->itemsize;
  2066. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  2067. return NULL;
  2068. }
  2069. slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
  2070. step);
  2071. if (slicelength <= 0) {
  2072. return newarrayobject(state->ArrayType, 0, self->ob_descr);
  2073. }
  2074. else if (step == 1) {
  2075. PyObject *result = newarrayobject(state->ArrayType,
  2076. slicelength, self->ob_descr);
  2077. if (result == NULL)
  2078. return NULL;
  2079. memcpy(((arrayobject *)result)->ob_item,
  2080. self->ob_item + start * itemsize,
  2081. slicelength * itemsize);
  2082. return result;
  2083. }
  2084. else {
  2085. result = newarrayobject(state->ArrayType, slicelength, self->ob_descr);
  2086. if (!result) return NULL;
  2087. ar = (arrayobject*)result;
  2088. for (cur = start, i = 0; i < slicelength;
  2089. cur += step, i++) {
  2090. memcpy(ar->ob_item + i*itemsize,
  2091. self->ob_item + cur*itemsize,
  2092. itemsize);
  2093. }
  2094. return result;
  2095. }
  2096. }
  2097. else {
  2098. PyErr_SetString(PyExc_TypeError,
  2099. "array indices must be integers");
  2100. return NULL;
  2101. }
  2102. }
  2103. static int
  2104. array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
  2105. {
  2106. Py_ssize_t start, stop, step, slicelength, needed;
  2107. array_state* state = find_array_state_by_type(Py_TYPE(self));
  2108. arrayobject* other;
  2109. int itemsize;
  2110. if (PyIndex_Check(item)) {
  2111. Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
  2112. if (i == -1 && PyErr_Occurred())
  2113. return -1;
  2114. if (i < 0)
  2115. i += Py_SIZE(self);
  2116. if (i < 0 || i >= Py_SIZE(self)) {
  2117. PyErr_SetString(PyExc_IndexError,
  2118. "array assignment index out of range");
  2119. return -1;
  2120. }
  2121. if (value == NULL) {
  2122. /* Fall through to slice assignment */
  2123. start = i;
  2124. stop = i + 1;
  2125. step = 1;
  2126. slicelength = 1;
  2127. }
  2128. else
  2129. return (*self->ob_descr->setitem)(self, i, value);
  2130. }
  2131. else if (PySlice_Check(item)) {
  2132. if (PySlice_Unpack(item, &start, &stop, &step) < 0) {
  2133. return -1;
  2134. }
  2135. slicelength = PySlice_AdjustIndices(Py_SIZE(self), &start, &stop,
  2136. step);
  2137. }
  2138. else {
  2139. PyErr_SetString(PyExc_TypeError,
  2140. "array indices must be integers");
  2141. return -1;
  2142. }
  2143. if (value == NULL) {
  2144. other = NULL;
  2145. needed = 0;
  2146. }
  2147. else if (array_Check(value, state)) {
  2148. other = (arrayobject *)value;
  2149. needed = Py_SIZE(other);
  2150. if (self == other) {
  2151. /* Special case "self[i:j] = self" -- copy self first */
  2152. int ret;
  2153. value = array_slice(other, 0, needed);
  2154. if (value == NULL)
  2155. return -1;
  2156. ret = array_ass_subscr(self, item, value);
  2157. Py_DECREF(value);
  2158. return ret;
  2159. }
  2160. if (other->ob_descr != self->ob_descr) {
  2161. PyErr_BadArgument();
  2162. return -1;
  2163. }
  2164. }
  2165. else {
  2166. PyErr_Format(PyExc_TypeError,
  2167. "can only assign array (not \"%.200s\") to array slice",
  2168. Py_TYPE(value)->tp_name);
  2169. return -1;
  2170. }
  2171. itemsize = self->ob_descr->itemsize;
  2172. /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
  2173. if ((step > 0 && stop < start) ||
  2174. (step < 0 && stop > start))
  2175. stop = start;
  2176. /* Issue #4509: If the array has exported buffers and the slice
  2177. assignment would change the size of the array, fail early to make
  2178. sure we don't modify it. */
  2179. if ((needed == 0 || slicelength != needed) && self->ob_exports > 0) {
  2180. PyErr_SetString(PyExc_BufferError,
  2181. "cannot resize an array that is exporting buffers");
  2182. return -1;
  2183. }
  2184. if (step == 1) {
  2185. if (slicelength > needed) {
  2186. memmove(self->ob_item + (start + needed) * itemsize,
  2187. self->ob_item + stop * itemsize,
  2188. (Py_SIZE(self) - stop) * itemsize);
  2189. if (array_resize(self, Py_SIZE(self) +
  2190. needed - slicelength) < 0)
  2191. return -1;
  2192. }
  2193. else if (slicelength < needed) {
  2194. if (array_resize(self, Py_SIZE(self) +
  2195. needed - slicelength) < 0)
  2196. return -1;
  2197. memmove(self->ob_item + (start + needed) * itemsize,
  2198. self->ob_item + stop * itemsize,
  2199. (Py_SIZE(self) - start - needed) * itemsize);
  2200. }
  2201. if (needed > 0)
  2202. memcpy(self->ob_item + start * itemsize,
  2203. other->ob_item, needed * itemsize);
  2204. return 0;
  2205. }
  2206. else if (needed == 0) {
  2207. /* Delete slice */
  2208. size_t cur;
  2209. Py_ssize_t i;
  2210. if (step < 0) {
  2211. stop = start + 1;
  2212. start = stop + step * (slicelength - 1) - 1;
  2213. step = -step;
  2214. }
  2215. for (cur = start, i = 0; i < slicelength;
  2216. cur += step, i++) {
  2217. Py_ssize_t lim = step - 1;
  2218. if (cur + step >= (size_t)Py_SIZE(self))
  2219. lim = Py_SIZE(self) - cur - 1;
  2220. memmove(self->ob_item + (cur - i) * itemsize,
  2221. self->ob_item + (cur + 1) * itemsize,
  2222. lim * itemsize);
  2223. }
  2224. cur = start + (size_t)slicelength * step;
  2225. if (cur < (size_t)Py_SIZE(self)) {
  2226. memmove(self->ob_item + (cur-slicelength) * itemsize,
  2227. self->ob_item + cur * itemsize,
  2228. (Py_SIZE(self) - cur) * itemsize);
  2229. }
  2230. if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
  2231. return -1;
  2232. return 0;
  2233. }
  2234. else {
  2235. size_t cur;
  2236. Py_ssize_t i;
  2237. if (needed != slicelength) {
  2238. PyErr_Format(PyExc_ValueError,
  2239. "attempt to assign array of size %zd "
  2240. "to extended slice of size %zd",
  2241. needed, slicelength);
  2242. return -1;
  2243. }
  2244. for (cur = start, i = 0; i < slicelength;
  2245. cur += step, i++) {
  2246. memcpy(self->ob_item + cur * itemsize,
  2247. other->ob_item + i * itemsize,
  2248. itemsize);
  2249. }
  2250. return 0;
  2251. }
  2252. }
  2253. static const void *emptybuf = "";
  2254. static int
  2255. array_buffer_getbuf(arrayobject *self, Py_buffer *view, int flags)
  2256. {
  2257. if (view == NULL) {
  2258. PyErr_SetString(PyExc_BufferError,
  2259. "array_buffer_getbuf: view==NULL argument is obsolete");
  2260. return -1;
  2261. }
  2262. view->buf = (void *)self->ob_item;
  2263. view->obj = Py_NewRef(self);
  2264. if (view->buf == NULL)
  2265. view->buf = (void *)emptybuf;
  2266. view->len = Py_SIZE(self) * self->ob_descr->itemsize;
  2267. view->readonly = 0;
  2268. view->ndim = 1;
  2269. view->itemsize = self->ob_descr->itemsize;
  2270. view->suboffsets = NULL;
  2271. view->shape = NULL;
  2272. if ((flags & PyBUF_ND)==PyBUF_ND) {
  2273. view->shape = &((PyVarObject*)self)->ob_size;
  2274. }
  2275. view->strides = NULL;
  2276. if ((flags & PyBUF_STRIDES)==PyBUF_STRIDES)
  2277. view->strides = &(view->itemsize);
  2278. view->format = NULL;
  2279. view->internal = NULL;
  2280. if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
  2281. view->format = (char *)self->ob_descr->formats;
  2282. #ifdef Py_UNICODE_WIDE
  2283. if (self->ob_descr->typecode == 'u') {
  2284. view->format = "w";
  2285. }
  2286. #endif
  2287. }
  2288. self->ob_exports++;
  2289. return 0;
  2290. }
  2291. static void
  2292. array_buffer_relbuf(arrayobject *self, Py_buffer *view)
  2293. {
  2294. self->ob_exports--;
  2295. }
  2296. static PyObject *
  2297. array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  2298. {
  2299. array_state *state = find_array_state_by_type(type);
  2300. int c;
  2301. PyObject *initial = NULL, *it = NULL;
  2302. const struct arraydescr *descr;
  2303. if ((type == state->ArrayType ||
  2304. type->tp_init == state->ArrayType->tp_init) &&
  2305. !_PyArg_NoKeywords("array.array", kwds))
  2306. return NULL;
  2307. if (!PyArg_ParseTuple(args, "C|O:array", &c, &initial))
  2308. return NULL;
  2309. if (PySys_Audit("array.__new__", "CO",
  2310. c, initial ? initial : Py_None) < 0) {
  2311. return NULL;
  2312. }
  2313. if (initial && c != 'u') {
  2314. if (PyUnicode_Check(initial)) {
  2315. PyErr_Format(PyExc_TypeError, "cannot use a str to initialize "
  2316. "an array with typecode '%c'", c);
  2317. return NULL;
  2318. }
  2319. else if (array_Check(initial, state) &&
  2320. ((arrayobject*)initial)->ob_descr->typecode == 'u') {
  2321. PyErr_Format(PyExc_TypeError, "cannot use a unicode array to "
  2322. "initialize an array with typecode '%c'", c);
  2323. return NULL;
  2324. }
  2325. }
  2326. if (!(initial == NULL || PyList_Check(initial)
  2327. || PyByteArray_Check(initial)
  2328. || PyBytes_Check(initial)
  2329. || PyTuple_Check(initial)
  2330. || ((c=='u') && PyUnicode_Check(initial))
  2331. || (array_Check(initial, state)
  2332. && c == ((arrayobject*)initial)->ob_descr->typecode))) {
  2333. it = PyObject_GetIter(initial);
  2334. if (it == NULL)
  2335. return NULL;
  2336. /* We set initial to NULL so that the subsequent code
  2337. will create an empty array of the appropriate type
  2338. and afterwards we can use array_iter_extend to populate
  2339. the array.
  2340. */
  2341. initial = NULL;
  2342. }
  2343. for (descr = descriptors; descr->typecode != '\0'; descr++) {
  2344. if (descr->typecode == c) {
  2345. PyObject *a;
  2346. Py_ssize_t len;
  2347. if (initial == NULL)
  2348. len = 0;
  2349. else if (PyList_Check(initial))
  2350. len = PyList_GET_SIZE(initial);
  2351. else if (PyTuple_Check(initial) || array_Check(initial, state))
  2352. len = Py_SIZE(initial);
  2353. else
  2354. len = 0;
  2355. a = newarrayobject(type, len, descr);
  2356. if (a == NULL)
  2357. return NULL;
  2358. if (len > 0 && !array_Check(initial, state)) {
  2359. Py_ssize_t i;
  2360. for (i = 0; i < len; i++) {
  2361. PyObject *v =
  2362. PySequence_GetItem(initial, i);
  2363. if (v == NULL) {
  2364. Py_DECREF(a);
  2365. return NULL;
  2366. }
  2367. if (setarrayitem(a, i, v) != 0) {
  2368. Py_DECREF(v);
  2369. Py_DECREF(a);
  2370. return NULL;
  2371. }
  2372. Py_DECREF(v);
  2373. }
  2374. }
  2375. else if (initial != NULL && (PyByteArray_Check(initial) ||
  2376. PyBytes_Check(initial))) {
  2377. PyObject *v;
  2378. v = array_array_frombytes((arrayobject *)a,
  2379. initial);
  2380. if (v == NULL) {
  2381. Py_DECREF(a);
  2382. return NULL;
  2383. }
  2384. Py_DECREF(v);
  2385. }
  2386. else if (initial != NULL && PyUnicode_Check(initial)) {
  2387. Py_ssize_t n;
  2388. wchar_t *ustr = PyUnicode_AsWideCharString(initial, &n);
  2389. if (ustr == NULL) {
  2390. Py_DECREF(a);
  2391. return NULL;
  2392. }
  2393. if (n > 0) {
  2394. arrayobject *self = (arrayobject *)a;
  2395. // self->ob_item may be NULL but it is safe.
  2396. PyMem_Free(self->ob_item);
  2397. self->ob_item = (char *)ustr;
  2398. Py_SET_SIZE(self, n);
  2399. self->allocated = n;
  2400. }
  2401. }
  2402. else if (initial != NULL && array_Check(initial, state) && len > 0) {
  2403. arrayobject *self = (arrayobject *)a;
  2404. arrayobject *other = (arrayobject *)initial;
  2405. memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
  2406. }
  2407. if (it != NULL) {
  2408. if (array_iter_extend((arrayobject *)a, it) == -1) {
  2409. Py_DECREF(it);
  2410. Py_DECREF(a);
  2411. return NULL;
  2412. }
  2413. Py_DECREF(it);
  2414. }
  2415. return a;
  2416. }
  2417. }
  2418. PyErr_SetString(PyExc_ValueError,
  2419. "bad typecode (must be b, B, u, h, H, i, I, l, L, q, Q, f or d)");
  2420. return NULL;
  2421. }
  2422. PyDoc_STRVAR(module_doc,
  2423. "This module defines an object type which can efficiently represent\n\
  2424. an array of basic values: characters, integers, floating-point\n\
  2425. numbers. Arrays are sequence types and behave very much like lists,\n\
  2426. except that the type of objects stored in them is constrained.\n");
  2427. PyDoc_STRVAR(arraytype_doc,
  2428. "array(typecode [, initializer]) -> array\n\
  2429. \n\
  2430. Return a new array whose items are restricted by typecode, and\n\
  2431. initialized from the optional initializer value, which must be a list,\n\
  2432. string or iterable over elements of the appropriate type.\n\
  2433. \n\
  2434. Arrays represent basic values and behave very much like lists, except\n\
  2435. the type of objects stored in them is constrained. The type is specified\n\
  2436. at object creation time by using a type code, which is a single character.\n\
  2437. The following type codes are defined:\n\
  2438. \n\
  2439. Type code C Type Minimum size in bytes\n\
  2440. 'b' signed integer 1\n\
  2441. 'B' unsigned integer 1\n\
  2442. 'u' Unicode character 2 (see note)\n\
  2443. 'h' signed integer 2\n\
  2444. 'H' unsigned integer 2\n\
  2445. 'i' signed integer 2\n\
  2446. 'I' unsigned integer 2\n\
  2447. 'l' signed integer 4\n\
  2448. 'L' unsigned integer 4\n\
  2449. 'q' signed integer 8 (see note)\n\
  2450. 'Q' unsigned integer 8 (see note)\n\
  2451. 'f' floating-point 4\n\
  2452. 'd' floating-point 8\n\
  2453. \n\
  2454. NOTE: The 'u' typecode corresponds to Python's unicode character. On\n\
  2455. narrow builds this is 2-bytes on wide builds this is 4-bytes.\n\
  2456. \n\
  2457. NOTE: The 'q' and 'Q' type codes are only available if the platform\n\
  2458. C compiler used to build Python supports 'long long', or, on Windows,\n\
  2459. '__int64'.\n\
  2460. \n\
  2461. Methods:\n\
  2462. \n\
  2463. append() -- append a new item to the end of the array\n\
  2464. buffer_info() -- return information giving the current memory info\n\
  2465. byteswap() -- byteswap all the items of the array\n\
  2466. count() -- return number of occurrences of an object\n\
  2467. extend() -- extend array by appending multiple elements from an iterable\n\
  2468. fromfile() -- read items from a file object\n\
  2469. fromlist() -- append items from the list\n\
  2470. frombytes() -- append items from the string\n\
  2471. index() -- return index of first occurrence of an object\n\
  2472. insert() -- insert a new item into the array at a provided position\n\
  2473. pop() -- remove and return item (default last)\n\
  2474. remove() -- remove first occurrence of an object\n\
  2475. reverse() -- reverse the order of the items in the array\n\
  2476. tofile() -- write all items to a file object\n\
  2477. tolist() -- return the array converted to an ordinary list\n\
  2478. tobytes() -- return the array converted to a string\n\
  2479. \n\
  2480. Attributes:\n\
  2481. \n\
  2482. typecode -- the typecode character used to create the array\n\
  2483. itemsize -- the length in bytes of one array item\n\
  2484. ");
  2485. static PyObject *array_iter(arrayobject *ao);
  2486. static struct PyMemberDef array_members[] = {
  2487. {"__weaklistoffset__", T_PYSSIZET, offsetof(arrayobject, weakreflist), READONLY},
  2488. {NULL},
  2489. };
  2490. static PyType_Slot array_slots[] = {
  2491. {Py_tp_dealloc, array_dealloc},
  2492. {Py_tp_repr, array_repr},
  2493. {Py_tp_getattro, PyObject_GenericGetAttr},
  2494. {Py_tp_doc, (void *)arraytype_doc},
  2495. {Py_tp_richcompare, array_richcompare},
  2496. {Py_tp_iter, array_iter},
  2497. {Py_tp_methods, array_methods},
  2498. {Py_tp_members, array_members},
  2499. {Py_tp_getset, array_getsets},
  2500. {Py_tp_alloc, PyType_GenericAlloc},
  2501. {Py_tp_new, array_new},
  2502. {Py_tp_traverse, array_tp_traverse},
  2503. /* as sequence */
  2504. {Py_sq_length, array_length},
  2505. {Py_sq_concat, array_concat},
  2506. {Py_sq_repeat, array_repeat},
  2507. {Py_sq_item, array_item},
  2508. {Py_sq_ass_item, array_ass_item},
  2509. {Py_sq_contains, array_contains},
  2510. {Py_sq_inplace_concat, array_inplace_concat},
  2511. {Py_sq_inplace_repeat, array_inplace_repeat},
  2512. /* as mapping */
  2513. {Py_mp_length, array_length},
  2514. {Py_mp_subscript, array_subscr},
  2515. {Py_mp_ass_subscript, array_ass_subscr},
  2516. /* as buffer */
  2517. {Py_bf_getbuffer, array_buffer_getbuf},
  2518. {Py_bf_releasebuffer, array_buffer_relbuf},
  2519. {0, NULL},
  2520. };
  2521. static PyType_Spec array_spec = {
  2522. .name = "array.array",
  2523. .basicsize = sizeof(arrayobject),
  2524. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  2525. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_HAVE_GC |
  2526. Py_TPFLAGS_SEQUENCE),
  2527. .slots = array_slots,
  2528. };
  2529. /*********************** Array Iterator **************************/
  2530. /*[clinic input]
  2531. class array.arrayiterator "arrayiterobject *" "find_array_state_by_type(type)->ArrayIterType"
  2532. [clinic start generated code]*/
  2533. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=fb46d5ef98dd95ff]*/
  2534. static PyObject *
  2535. array_iter(arrayobject *ao)
  2536. {
  2537. array_state *state = find_array_state_by_type(Py_TYPE(ao));
  2538. arrayiterobject *it;
  2539. if (!array_Check(ao, state)) {
  2540. PyErr_BadInternalCall();
  2541. return NULL;
  2542. }
  2543. it = PyObject_GC_New(arrayiterobject, state->ArrayIterType);
  2544. if (it == NULL)
  2545. return NULL;
  2546. it->ao = (arrayobject*)Py_NewRef(ao);
  2547. it->index = 0;
  2548. it->getitem = ao->ob_descr->getitem;
  2549. PyObject_GC_Track(it);
  2550. return (PyObject *)it;
  2551. }
  2552. static PyObject *
  2553. arrayiter_next(arrayiterobject *it)
  2554. {
  2555. arrayobject *ao;
  2556. assert(it != NULL);
  2557. #ifndef NDEBUG
  2558. array_state *state = find_array_state_by_type(Py_TYPE(it));
  2559. assert(PyObject_TypeCheck(it, state->ArrayIterType));
  2560. #endif
  2561. ao = it->ao;
  2562. if (ao == NULL) {
  2563. return NULL;
  2564. }
  2565. #ifndef NDEBUG
  2566. assert(array_Check(ao, state));
  2567. #endif
  2568. if (it->index < Py_SIZE(ao)) {
  2569. return (*it->getitem)(ao, it->index++);
  2570. }
  2571. it->ao = NULL;
  2572. Py_DECREF(ao);
  2573. return NULL;
  2574. }
  2575. static void
  2576. arrayiter_dealloc(arrayiterobject *it)
  2577. {
  2578. PyTypeObject *tp = Py_TYPE(it);
  2579. PyObject_GC_UnTrack(it);
  2580. Py_XDECREF(it->ao);
  2581. PyObject_GC_Del(it);
  2582. Py_DECREF(tp);
  2583. }
  2584. static int
  2585. arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
  2586. {
  2587. Py_VISIT(Py_TYPE(it));
  2588. Py_VISIT(it->ao);
  2589. return 0;
  2590. }
  2591. /*[clinic input]
  2592. array.arrayiterator.__reduce__
  2593. cls: defining_class
  2594. /
  2595. Return state information for pickling.
  2596. [clinic start generated code]*/
  2597. static PyObject *
  2598. array_arrayiterator___reduce___impl(arrayiterobject *self, PyTypeObject *cls)
  2599. /*[clinic end generated code: output=4b032417a2c8f5e6 input=ac64e65a87ad452e]*/
  2600. {
  2601. array_state *state = get_array_state_by_class(cls);
  2602. assert(state != NULL);
  2603. PyObject *func = _PyEval_GetBuiltin(state->str_iter);
  2604. if (self->ao == NULL) {
  2605. return Py_BuildValue("N(())", func);
  2606. }
  2607. return Py_BuildValue("N(O)n", func, self->ao, self->index);
  2608. }
  2609. /*[clinic input]
  2610. array.arrayiterator.__setstate__
  2611. state: object
  2612. /
  2613. Set state information for unpickling.
  2614. [clinic start generated code]*/
  2615. static PyObject *
  2616. array_arrayiterator___setstate__(arrayiterobject *self, PyObject *state)
  2617. /*[clinic end generated code: output=397da9904e443cbe input=f47d5ceda19e787b]*/
  2618. {
  2619. Py_ssize_t index = PyLong_AsSsize_t(state);
  2620. if (index == -1 && PyErr_Occurred())
  2621. return NULL;
  2622. if (index < 0)
  2623. index = 0;
  2624. else if (index > Py_SIZE(self->ao))
  2625. index = Py_SIZE(self->ao); /* iterator exhausted */
  2626. self->index = index;
  2627. Py_RETURN_NONE;
  2628. }
  2629. static PyMethodDef arrayiter_methods[] = {
  2630. ARRAY_ARRAYITERATOR___REDUCE___METHODDEF
  2631. ARRAY_ARRAYITERATOR___SETSTATE___METHODDEF
  2632. {NULL, NULL} /* sentinel */
  2633. };
  2634. static PyType_Slot arrayiter_slots[] = {
  2635. {Py_tp_dealloc, arrayiter_dealloc},
  2636. {Py_tp_getattro, PyObject_GenericGetAttr},
  2637. {Py_tp_traverse, arrayiter_traverse},
  2638. {Py_tp_iter, PyObject_SelfIter},
  2639. {Py_tp_iternext, arrayiter_next},
  2640. {Py_tp_methods, arrayiter_methods},
  2641. {0, NULL},
  2642. };
  2643. static PyType_Spec arrayiter_spec = {
  2644. .name = "array.arrayiterator",
  2645. .basicsize = sizeof(arrayiterobject),
  2646. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  2647. Py_TPFLAGS_DISALLOW_INSTANTIATION | Py_TPFLAGS_IMMUTABLETYPE),
  2648. .slots = arrayiter_slots,
  2649. };
  2650. /*********************** Install Module **************************/
  2651. static int
  2652. array_traverse(PyObject *module, visitproc visit, void *arg)
  2653. {
  2654. array_state *state = get_array_state(module);
  2655. Py_VISIT(state->ArrayType);
  2656. Py_VISIT(state->ArrayIterType);
  2657. Py_VISIT(state->array_reconstructor);
  2658. return 0;
  2659. }
  2660. static int
  2661. array_clear(PyObject *module)
  2662. {
  2663. array_state *state = get_array_state(module);
  2664. Py_CLEAR(state->ArrayType);
  2665. Py_CLEAR(state->ArrayIterType);
  2666. Py_CLEAR(state->array_reconstructor);
  2667. Py_CLEAR(state->str_read);
  2668. Py_CLEAR(state->str_write);
  2669. Py_CLEAR(state->str___dict__);
  2670. Py_CLEAR(state->str_iter);
  2671. return 0;
  2672. }
  2673. static void
  2674. array_free(void *module)
  2675. {
  2676. array_clear((PyObject *)module);
  2677. }
  2678. /* No functions in array module. */
  2679. static PyMethodDef a_methods[] = {
  2680. ARRAY__ARRAY_RECONSTRUCTOR_METHODDEF
  2681. {NULL, NULL, 0, NULL} /* Sentinel */
  2682. };
  2683. #define CREATE_TYPE(module, type, spec) \
  2684. do { \
  2685. type = (PyTypeObject *)PyType_FromModuleAndSpec(module, spec, NULL); \
  2686. if (type == NULL) { \
  2687. return -1; \
  2688. } \
  2689. } while (0)
  2690. #define ADD_INTERNED(state, string) \
  2691. do { \
  2692. PyObject *tmp = PyUnicode_InternFromString(#string); \
  2693. if (tmp == NULL) { \
  2694. return -1; \
  2695. } \
  2696. state->str_ ## string = tmp; \
  2697. } while (0)
  2698. static int
  2699. array_modexec(PyObject *m)
  2700. {
  2701. array_state *state = get_array_state(m);
  2702. char buffer[Py_ARRAY_LENGTH(descriptors)], *p;
  2703. PyObject *typecodes;
  2704. const struct arraydescr *descr;
  2705. state->array_reconstructor = NULL;
  2706. /* Add interned strings */
  2707. ADD_INTERNED(state, read);
  2708. ADD_INTERNED(state, write);
  2709. ADD_INTERNED(state, __dict__);
  2710. ADD_INTERNED(state, iter);
  2711. CREATE_TYPE(m, state->ArrayType, &array_spec);
  2712. CREATE_TYPE(m, state->ArrayIterType, &arrayiter_spec);
  2713. Py_SET_TYPE(state->ArrayIterType, &PyType_Type);
  2714. if (PyModule_AddObject(m, "ArrayType",
  2715. Py_NewRef((PyObject *)state->ArrayType)) < 0) {
  2716. Py_DECREF((PyObject *)state->ArrayType);
  2717. return -1;
  2718. }
  2719. PyObject *mutablesequence = _PyImport_GetModuleAttrString(
  2720. "collections.abc", "MutableSequence");
  2721. if (!mutablesequence) {
  2722. Py_DECREF((PyObject *)state->ArrayType);
  2723. return -1;
  2724. }
  2725. PyObject *res = PyObject_CallMethod(mutablesequence, "register", "O",
  2726. (PyObject *)state->ArrayType);
  2727. Py_DECREF(mutablesequence);
  2728. if (!res) {
  2729. Py_DECREF((PyObject *)state->ArrayType);
  2730. return -1;
  2731. }
  2732. Py_DECREF(res);
  2733. if (PyModule_AddType(m, state->ArrayType) < 0) {
  2734. return -1;
  2735. }
  2736. p = buffer;
  2737. for (descr = descriptors; descr->typecode != '\0'; descr++) {
  2738. *p++ = (char)descr->typecode;
  2739. }
  2740. typecodes = PyUnicode_DecodeASCII(buffer, p - buffer, NULL);
  2741. if (PyModule_AddObject(m, "typecodes", typecodes) < 0) {
  2742. Py_XDECREF(typecodes);
  2743. return -1;
  2744. }
  2745. return 0;
  2746. }
  2747. static PyModuleDef_Slot arrayslots[] = {
  2748. {Py_mod_exec, array_modexec},
  2749. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  2750. {0, NULL}
  2751. };
  2752. static struct PyModuleDef arraymodule = {
  2753. .m_base = PyModuleDef_HEAD_INIT,
  2754. .m_name = "array",
  2755. .m_size = sizeof(array_state),
  2756. .m_doc = module_doc,
  2757. .m_methods = a_methods,
  2758. .m_slots = arrayslots,
  2759. .m_traverse = array_traverse,
  2760. .m_clear = array_clear,
  2761. .m_free = array_free,
  2762. };
  2763. PyMODINIT_FUNC
  2764. PyInit_array(void)
  2765. {
  2766. return PyModuleDef_Init(&arraymodule);
  2767. }