_collectionsmodule.c 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595
  1. #include "Python.h"
  2. #include "pycore_call.h" // _PyObject_CallNoArgs()
  3. #include "pycore_long.h" // _PyLong_GetZero()
  4. #include "pycore_moduleobject.h" // _PyModule_GetState()
  5. #include "pycore_typeobject.h" // _PyType_GetModuleState()
  6. #include "structmember.h" // PyMemberDef
  7. #include <stddef.h>
  8. typedef struct {
  9. PyTypeObject *deque_type;
  10. PyTypeObject *defdict_type;
  11. PyTypeObject *dequeiter_type;
  12. PyTypeObject *dequereviter_type;
  13. PyTypeObject *tuplegetter_type;
  14. } collections_state;
  15. static inline collections_state *
  16. get_module_state(PyObject *mod)
  17. {
  18. void *state = _PyModule_GetState(mod);
  19. assert(state != NULL);
  20. return (collections_state *)state;
  21. }
  22. static inline collections_state *
  23. get_module_state_by_cls(PyTypeObject *cls)
  24. {
  25. void *state = _PyType_GetModuleState(cls);
  26. assert(state != NULL);
  27. return (collections_state *)state;
  28. }
  29. static struct PyModuleDef _collectionsmodule;
  30. static inline collections_state *
  31. find_module_state_by_def(PyTypeObject *type)
  32. {
  33. PyObject *mod = PyType_GetModuleByDef(type, &_collectionsmodule);
  34. assert(mod != NULL);
  35. return get_module_state(mod);
  36. }
  37. /*[clinic input]
  38. module _collections
  39. class _tuplegetter "_tuplegetterobject *" "clinic_state()->tuplegetter_type"
  40. [clinic start generated code]*/
  41. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=7356042a89862e0e]*/
  42. /* We can safely assume type to be the defining class,
  43. * since tuplegetter is not a base type */
  44. #define clinic_state() (get_module_state_by_cls(type))
  45. #include "clinic/_collectionsmodule.c.h"
  46. #undef clinic_state
  47. /* collections module implementation of a deque() datatype
  48. Written and maintained by Raymond D. Hettinger <python@rcn.com>
  49. */
  50. /* The block length may be set to any number over 1. Larger numbers
  51. * reduce the number of calls to the memory allocator, give faster
  52. * indexing and rotation, and reduce the link to data overhead ratio.
  53. * Making the block length a power of two speeds-up the modulo
  54. * and division calculations in deque_item() and deque_ass_item().
  55. */
  56. #define BLOCKLEN 64
  57. #define CENTER ((BLOCKLEN - 1) / 2)
  58. #define MAXFREEBLOCKS 16
  59. /* Data for deque objects is stored in a doubly-linked list of fixed
  60. * length blocks. This assures that appends or pops never move any
  61. * other data elements besides the one being appended or popped.
  62. *
  63. * Another advantage is that it completely avoids use of realloc(),
  64. * resulting in more predictable performance.
  65. *
  66. * Textbook implementations of doubly-linked lists store one datum
  67. * per link, but that gives them a 200% memory overhead (a prev and
  68. * next link for each datum) and it costs one malloc() call per data
  69. * element. By using fixed-length blocks, the link to data ratio is
  70. * significantly improved and there are proportionally fewer calls
  71. * to malloc() and free(). The data blocks of consecutive pointers
  72. * also improve cache locality.
  73. *
  74. * The list of blocks is never empty, so d.leftblock and d.rightblock
  75. * are never equal to NULL. The list is not circular.
  76. *
  77. * A deque d's first element is at d.leftblock[leftindex]
  78. * and its last element is at d.rightblock[rightindex].
  79. *
  80. * Unlike Python slice indices, these indices are inclusive on both
  81. * ends. This makes the algorithms for left and right operations
  82. * more symmetrical and it simplifies the design.
  83. *
  84. * The indices, d.leftindex and d.rightindex are always in the range:
  85. * 0 <= index < BLOCKLEN
  86. *
  87. * And their exact relationship is:
  88. * (d.leftindex + d.len - 1) % BLOCKLEN == d.rightindex
  89. *
  90. * Whenever d.leftblock == d.rightblock, then:
  91. * d.leftindex + d.len - 1 == d.rightindex
  92. *
  93. * However, when d.leftblock != d.rightblock, the d.leftindex and
  94. * d.rightindex become indices into distinct blocks and either may
  95. * be larger than the other.
  96. *
  97. * Empty deques have:
  98. * d.len == 0
  99. * d.leftblock == d.rightblock
  100. * d.leftindex == CENTER + 1
  101. * d.rightindex == CENTER
  102. *
  103. * Checking for d.len == 0 is the intended way to see whether d is empty.
  104. */
  105. typedef struct BLOCK {
  106. struct BLOCK *leftlink;
  107. PyObject *data[BLOCKLEN];
  108. struct BLOCK *rightlink;
  109. } block;
  110. typedef struct {
  111. PyObject_VAR_HEAD
  112. block *leftblock;
  113. block *rightblock;
  114. Py_ssize_t leftindex; /* 0 <= leftindex < BLOCKLEN */
  115. Py_ssize_t rightindex; /* 0 <= rightindex < BLOCKLEN */
  116. size_t state; /* incremented whenever the indices move */
  117. Py_ssize_t maxlen; /* maxlen is -1 for unbounded deques */
  118. Py_ssize_t numfreeblocks;
  119. block *freeblocks[MAXFREEBLOCKS];
  120. PyObject *weakreflist;
  121. } dequeobject;
  122. /* For debug builds, add error checking to track the endpoints
  123. * in the chain of links. The goal is to make sure that link
  124. * assignments only take place at endpoints so that links already
  125. * in use do not get overwritten.
  126. *
  127. * CHECK_END should happen before each assignment to a block's link field.
  128. * MARK_END should happen whenever a link field becomes a new endpoint.
  129. * This happens when new blocks are added or whenever an existing
  130. * block is freed leaving another existing block as the new endpoint.
  131. */
  132. #ifndef NDEBUG
  133. #define MARK_END(link) link = NULL;
  134. #define CHECK_END(link) assert(link == NULL);
  135. #define CHECK_NOT_END(link) assert(link != NULL);
  136. #else
  137. #define MARK_END(link)
  138. #define CHECK_END(link)
  139. #define CHECK_NOT_END(link)
  140. #endif
  141. /* A simple freelisting scheme is used to minimize calls to the memory
  142. allocator. It accommodates common use cases where new blocks are being
  143. added at about the same rate as old blocks are being freed.
  144. */
  145. static inline block *
  146. newblock(dequeobject *deque) {
  147. block *b;
  148. if (deque->numfreeblocks) {
  149. deque->numfreeblocks--;
  150. return deque->freeblocks[deque->numfreeblocks];
  151. }
  152. b = PyMem_Malloc(sizeof(block));
  153. if (b != NULL) {
  154. return b;
  155. }
  156. PyErr_NoMemory();
  157. return NULL;
  158. }
  159. static inline void
  160. freeblock(dequeobject *deque, block *b)
  161. {
  162. if (deque->numfreeblocks < MAXFREEBLOCKS) {
  163. deque->freeblocks[deque->numfreeblocks] = b;
  164. deque->numfreeblocks++;
  165. } else {
  166. PyMem_Free(b);
  167. }
  168. }
  169. static PyObject *
  170. deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  171. {
  172. dequeobject *deque;
  173. block *b;
  174. /* create dequeobject structure */
  175. deque = (dequeobject *)type->tp_alloc(type, 0);
  176. if (deque == NULL)
  177. return NULL;
  178. b = newblock(deque);
  179. if (b == NULL) {
  180. Py_DECREF(deque);
  181. return NULL;
  182. }
  183. MARK_END(b->leftlink);
  184. MARK_END(b->rightlink);
  185. assert(BLOCKLEN >= 2);
  186. Py_SET_SIZE(deque, 0);
  187. deque->leftblock = b;
  188. deque->rightblock = b;
  189. deque->leftindex = CENTER + 1;
  190. deque->rightindex = CENTER;
  191. deque->state = 0;
  192. deque->maxlen = -1;
  193. deque->numfreeblocks = 0;
  194. deque->weakreflist = NULL;
  195. return (PyObject *)deque;
  196. }
  197. static PyObject *
  198. deque_pop(dequeobject *deque, PyObject *unused)
  199. {
  200. PyObject *item;
  201. block *prevblock;
  202. if (Py_SIZE(deque) == 0) {
  203. PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
  204. return NULL;
  205. }
  206. item = deque->rightblock->data[deque->rightindex];
  207. deque->rightindex--;
  208. Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
  209. deque->state++;
  210. if (deque->rightindex < 0) {
  211. if (Py_SIZE(deque)) {
  212. prevblock = deque->rightblock->leftlink;
  213. assert(deque->leftblock != deque->rightblock);
  214. freeblock(deque, deque->rightblock);
  215. CHECK_NOT_END(prevblock);
  216. MARK_END(prevblock->rightlink);
  217. deque->rightblock = prevblock;
  218. deque->rightindex = BLOCKLEN - 1;
  219. } else {
  220. assert(deque->leftblock == deque->rightblock);
  221. assert(deque->leftindex == deque->rightindex+1);
  222. /* re-center instead of freeing a block */
  223. deque->leftindex = CENTER + 1;
  224. deque->rightindex = CENTER;
  225. }
  226. }
  227. return item;
  228. }
  229. PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
  230. static PyObject *
  231. deque_popleft(dequeobject *deque, PyObject *unused)
  232. {
  233. PyObject *item;
  234. block *prevblock;
  235. if (Py_SIZE(deque) == 0) {
  236. PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
  237. return NULL;
  238. }
  239. assert(deque->leftblock != NULL);
  240. item = deque->leftblock->data[deque->leftindex];
  241. deque->leftindex++;
  242. Py_SET_SIZE(deque, Py_SIZE(deque) - 1);
  243. deque->state++;
  244. if (deque->leftindex == BLOCKLEN) {
  245. if (Py_SIZE(deque)) {
  246. assert(deque->leftblock != deque->rightblock);
  247. prevblock = deque->leftblock->rightlink;
  248. freeblock(deque, deque->leftblock);
  249. CHECK_NOT_END(prevblock);
  250. MARK_END(prevblock->leftlink);
  251. deque->leftblock = prevblock;
  252. deque->leftindex = 0;
  253. } else {
  254. assert(deque->leftblock == deque->rightblock);
  255. assert(deque->leftindex == deque->rightindex+1);
  256. /* re-center instead of freeing a block */
  257. deque->leftindex = CENTER + 1;
  258. deque->rightindex = CENTER;
  259. }
  260. }
  261. return item;
  262. }
  263. PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
  264. /* The deque's size limit is d.maxlen. The limit can be zero or positive.
  265. * If there is no limit, then d.maxlen == -1.
  266. *
  267. * After an item is added to a deque, we check to see if the size has
  268. * grown past the limit. If it has, we get the size back down to the limit
  269. * by popping an item off of the opposite end. The methods that can
  270. * trigger this are append(), appendleft(), extend(), and extendleft().
  271. *
  272. * The macro to check whether a deque needs to be trimmed uses a single
  273. * unsigned test that returns true whenever 0 <= maxlen < Py_SIZE(deque).
  274. */
  275. #define NEEDS_TRIM(deque, maxlen) ((size_t)(maxlen) < (size_t)(Py_SIZE(deque)))
  276. static inline int
  277. deque_append_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
  278. {
  279. if (deque->rightindex == BLOCKLEN - 1) {
  280. block *b = newblock(deque);
  281. if (b == NULL)
  282. return -1;
  283. b->leftlink = deque->rightblock;
  284. CHECK_END(deque->rightblock->rightlink);
  285. deque->rightblock->rightlink = b;
  286. deque->rightblock = b;
  287. MARK_END(b->rightlink);
  288. deque->rightindex = -1;
  289. }
  290. Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
  291. deque->rightindex++;
  292. deque->rightblock->data[deque->rightindex] = item;
  293. if (NEEDS_TRIM(deque, maxlen)) {
  294. PyObject *olditem = deque_popleft(deque, NULL);
  295. Py_DECREF(olditem);
  296. } else {
  297. deque->state++;
  298. }
  299. return 0;
  300. }
  301. static PyObject *
  302. deque_append(dequeobject *deque, PyObject *item)
  303. {
  304. if (deque_append_internal(deque, Py_NewRef(item), deque->maxlen) < 0)
  305. return NULL;
  306. Py_RETURN_NONE;
  307. }
  308. PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
  309. static inline int
  310. deque_appendleft_internal(dequeobject *deque, PyObject *item, Py_ssize_t maxlen)
  311. {
  312. if (deque->leftindex == 0) {
  313. block *b = newblock(deque);
  314. if (b == NULL)
  315. return -1;
  316. b->rightlink = deque->leftblock;
  317. CHECK_END(deque->leftblock->leftlink);
  318. deque->leftblock->leftlink = b;
  319. deque->leftblock = b;
  320. MARK_END(b->leftlink);
  321. deque->leftindex = BLOCKLEN;
  322. }
  323. Py_SET_SIZE(deque, Py_SIZE(deque) + 1);
  324. deque->leftindex--;
  325. deque->leftblock->data[deque->leftindex] = item;
  326. if (NEEDS_TRIM(deque, deque->maxlen)) {
  327. PyObject *olditem = deque_pop(deque, NULL);
  328. Py_DECREF(olditem);
  329. } else {
  330. deque->state++;
  331. }
  332. return 0;
  333. }
  334. static PyObject *
  335. deque_appendleft(dequeobject *deque, PyObject *item)
  336. {
  337. if (deque_appendleft_internal(deque, Py_NewRef(item), deque->maxlen) < 0)
  338. return NULL;
  339. Py_RETURN_NONE;
  340. }
  341. PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
  342. static PyObject*
  343. finalize_iterator(PyObject *it)
  344. {
  345. if (PyErr_Occurred()) {
  346. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  347. PyErr_Clear();
  348. else {
  349. Py_DECREF(it);
  350. return NULL;
  351. }
  352. }
  353. Py_DECREF(it);
  354. Py_RETURN_NONE;
  355. }
  356. /* Run an iterator to exhaustion. Shortcut for
  357. the extend/extendleft methods when maxlen == 0. */
  358. static PyObject*
  359. consume_iterator(PyObject *it)
  360. {
  361. PyObject *(*iternext)(PyObject *);
  362. PyObject *item;
  363. iternext = *Py_TYPE(it)->tp_iternext;
  364. while ((item = iternext(it)) != NULL) {
  365. Py_DECREF(item);
  366. }
  367. return finalize_iterator(it);
  368. }
  369. static PyObject *
  370. deque_extend(dequeobject *deque, PyObject *iterable)
  371. {
  372. PyObject *it, *item;
  373. PyObject *(*iternext)(PyObject *);
  374. Py_ssize_t maxlen = deque->maxlen;
  375. /* Handle case where id(deque) == id(iterable) */
  376. if ((PyObject *)deque == iterable) {
  377. PyObject *result;
  378. PyObject *s = PySequence_List(iterable);
  379. if (s == NULL)
  380. return NULL;
  381. result = deque_extend(deque, s);
  382. Py_DECREF(s);
  383. return result;
  384. }
  385. it = PyObject_GetIter(iterable);
  386. if (it == NULL)
  387. return NULL;
  388. if (maxlen == 0)
  389. return consume_iterator(it);
  390. /* Space saving heuristic. Start filling from the left */
  391. if (Py_SIZE(deque) == 0) {
  392. assert(deque->leftblock == deque->rightblock);
  393. assert(deque->leftindex == deque->rightindex+1);
  394. deque->leftindex = 1;
  395. deque->rightindex = 0;
  396. }
  397. iternext = *Py_TYPE(it)->tp_iternext;
  398. while ((item = iternext(it)) != NULL) {
  399. if (deque_append_internal(deque, item, maxlen) == -1) {
  400. Py_DECREF(item);
  401. Py_DECREF(it);
  402. return NULL;
  403. }
  404. }
  405. return finalize_iterator(it);
  406. }
  407. PyDoc_STRVAR(extend_doc,
  408. "Extend the right side of the deque with elements from the iterable");
  409. static PyObject *
  410. deque_extendleft(dequeobject *deque, PyObject *iterable)
  411. {
  412. PyObject *it, *item;
  413. PyObject *(*iternext)(PyObject *);
  414. Py_ssize_t maxlen = deque->maxlen;
  415. /* Handle case where id(deque) == id(iterable) */
  416. if ((PyObject *)deque == iterable) {
  417. PyObject *result;
  418. PyObject *s = PySequence_List(iterable);
  419. if (s == NULL)
  420. return NULL;
  421. result = deque_extendleft(deque, s);
  422. Py_DECREF(s);
  423. return result;
  424. }
  425. it = PyObject_GetIter(iterable);
  426. if (it == NULL)
  427. return NULL;
  428. if (maxlen == 0)
  429. return consume_iterator(it);
  430. /* Space saving heuristic. Start filling from the right */
  431. if (Py_SIZE(deque) == 0) {
  432. assert(deque->leftblock == deque->rightblock);
  433. assert(deque->leftindex == deque->rightindex+1);
  434. deque->leftindex = BLOCKLEN - 1;
  435. deque->rightindex = BLOCKLEN - 2;
  436. }
  437. iternext = *Py_TYPE(it)->tp_iternext;
  438. while ((item = iternext(it)) != NULL) {
  439. if (deque_appendleft_internal(deque, item, maxlen) == -1) {
  440. Py_DECREF(item);
  441. Py_DECREF(it);
  442. return NULL;
  443. }
  444. }
  445. return finalize_iterator(it);
  446. }
  447. PyDoc_STRVAR(extendleft_doc,
  448. "Extend the left side of the deque with elements from the iterable");
  449. static PyObject *
  450. deque_inplace_concat(dequeobject *deque, PyObject *other)
  451. {
  452. PyObject *result;
  453. result = deque_extend(deque, other);
  454. if (result == NULL)
  455. return result;
  456. Py_INCREF(deque);
  457. Py_DECREF(result);
  458. return (PyObject *)deque;
  459. }
  460. static PyObject *
  461. deque_copy(PyObject *deque, PyObject *Py_UNUSED(ignored))
  462. {
  463. PyObject *result;
  464. dequeobject *old_deque = (dequeobject *)deque;
  465. collections_state *state = find_module_state_by_def(Py_TYPE(deque));
  466. if (Py_IS_TYPE(deque, state->deque_type)) {
  467. dequeobject *new_deque;
  468. PyObject *rv;
  469. new_deque = (dequeobject *)deque_new(state->deque_type,
  470. (PyObject *)NULL, (PyObject *)NULL);
  471. if (new_deque == NULL)
  472. return NULL;
  473. new_deque->maxlen = old_deque->maxlen;
  474. /* Fast path for the deque_repeat() common case where len(deque) == 1 */
  475. if (Py_SIZE(deque) == 1) {
  476. PyObject *item = old_deque->leftblock->data[old_deque->leftindex];
  477. rv = deque_append(new_deque, item);
  478. } else {
  479. rv = deque_extend(new_deque, deque);
  480. }
  481. if (rv != NULL) {
  482. Py_DECREF(rv);
  483. return (PyObject *)new_deque;
  484. }
  485. Py_DECREF(new_deque);
  486. return NULL;
  487. }
  488. if (old_deque->maxlen < 0)
  489. result = PyObject_CallOneArg((PyObject *)(Py_TYPE(deque)), deque);
  490. else
  491. result = PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
  492. deque, old_deque->maxlen, NULL);
  493. if (result != NULL && !PyObject_TypeCheck(result, state->deque_type)) {
  494. PyErr_Format(PyExc_TypeError,
  495. "%.200s() must return a deque, not %.200s",
  496. Py_TYPE(deque)->tp_name, Py_TYPE(result)->tp_name);
  497. Py_DECREF(result);
  498. return NULL;
  499. }
  500. return result;
  501. }
  502. PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
  503. static PyObject *
  504. deque_concat(dequeobject *deque, PyObject *other)
  505. {
  506. PyObject *new_deque, *result;
  507. int rv;
  508. collections_state *state = find_module_state_by_def(Py_TYPE(deque));
  509. rv = PyObject_IsInstance(other, (PyObject *)state->deque_type);
  510. if (rv <= 0) {
  511. if (rv == 0) {
  512. PyErr_Format(PyExc_TypeError,
  513. "can only concatenate deque (not \"%.200s\") to deque",
  514. Py_TYPE(other)->tp_name);
  515. }
  516. return NULL;
  517. }
  518. new_deque = deque_copy((PyObject *)deque, NULL);
  519. if (new_deque == NULL)
  520. return NULL;
  521. result = deque_extend((dequeobject *)new_deque, other);
  522. if (result == NULL) {
  523. Py_DECREF(new_deque);
  524. return NULL;
  525. }
  526. Py_DECREF(result);
  527. return new_deque;
  528. }
  529. static int
  530. deque_clear(dequeobject *deque)
  531. {
  532. block *b;
  533. block *prevblock;
  534. block *leftblock;
  535. Py_ssize_t leftindex;
  536. Py_ssize_t n, m;
  537. PyObject *item;
  538. PyObject **itemptr, **limit;
  539. if (Py_SIZE(deque) == 0)
  540. return 0;
  541. /* During the process of clearing a deque, decrefs can cause the
  542. deque to mutate. To avoid fatal confusion, we have to make the
  543. deque empty before clearing the blocks and never refer to
  544. anything via deque->ref while clearing. (This is the same
  545. technique used for clearing lists, sets, and dicts.)
  546. Making the deque empty requires allocating a new empty block. In
  547. the unlikely event that memory is full, we fall back to an
  548. alternate method that doesn't require a new block. Repeating
  549. pops in a while-loop is slower, possibly re-entrant (and a clever
  550. adversary could cause it to never terminate).
  551. */
  552. b = newblock(deque);
  553. if (b == NULL) {
  554. PyErr_Clear();
  555. goto alternate_method;
  556. }
  557. /* Remember the old size, leftblock, and leftindex */
  558. n = Py_SIZE(deque);
  559. leftblock = deque->leftblock;
  560. leftindex = deque->leftindex;
  561. /* Set the deque to be empty using the newly allocated block */
  562. MARK_END(b->leftlink);
  563. MARK_END(b->rightlink);
  564. Py_SET_SIZE(deque, 0);
  565. deque->leftblock = b;
  566. deque->rightblock = b;
  567. deque->leftindex = CENTER + 1;
  568. deque->rightindex = CENTER;
  569. deque->state++;
  570. /* Now the old size, leftblock, and leftindex are disconnected from
  571. the empty deque and we can use them to decref the pointers.
  572. */
  573. m = (BLOCKLEN - leftindex > n) ? n : BLOCKLEN - leftindex;
  574. itemptr = &leftblock->data[leftindex];
  575. limit = itemptr + m;
  576. n -= m;
  577. while (1) {
  578. if (itemptr == limit) {
  579. if (n == 0)
  580. break;
  581. CHECK_NOT_END(leftblock->rightlink);
  582. prevblock = leftblock;
  583. leftblock = leftblock->rightlink;
  584. m = (n > BLOCKLEN) ? BLOCKLEN : n;
  585. itemptr = leftblock->data;
  586. limit = itemptr + m;
  587. n -= m;
  588. freeblock(deque, prevblock);
  589. }
  590. item = *(itemptr++);
  591. Py_DECREF(item);
  592. }
  593. CHECK_END(leftblock->rightlink);
  594. freeblock(deque, leftblock);
  595. return 0;
  596. alternate_method:
  597. while (Py_SIZE(deque)) {
  598. item = deque_pop(deque, NULL);
  599. assert (item != NULL);
  600. Py_DECREF(item);
  601. }
  602. return 0;
  603. }
  604. static PyObject *
  605. deque_clearmethod(dequeobject *deque, PyObject *Py_UNUSED(ignored))
  606. {
  607. deque_clear(deque);
  608. Py_RETURN_NONE;
  609. }
  610. PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
  611. static PyObject *
  612. deque_inplace_repeat(dequeobject *deque, Py_ssize_t n)
  613. {
  614. Py_ssize_t i, m, size;
  615. PyObject *seq;
  616. PyObject *rv;
  617. size = Py_SIZE(deque);
  618. if (size == 0 || n == 1) {
  619. return Py_NewRef(deque);
  620. }
  621. if (n <= 0) {
  622. deque_clear(deque);
  623. return Py_NewRef(deque);
  624. }
  625. if (size == 1) {
  626. /* common case, repeating a single element */
  627. PyObject *item = deque->leftblock->data[deque->leftindex];
  628. if (deque->maxlen >= 0 && n > deque->maxlen)
  629. n = deque->maxlen;
  630. deque->state++;
  631. for (i = 0 ; i < n-1 ; ) {
  632. if (deque->rightindex == BLOCKLEN - 1) {
  633. block *b = newblock(deque);
  634. if (b == NULL) {
  635. Py_SET_SIZE(deque, Py_SIZE(deque) + i);
  636. return NULL;
  637. }
  638. b->leftlink = deque->rightblock;
  639. CHECK_END(deque->rightblock->rightlink);
  640. deque->rightblock->rightlink = b;
  641. deque->rightblock = b;
  642. MARK_END(b->rightlink);
  643. deque->rightindex = -1;
  644. }
  645. m = n - 1 - i;
  646. if (m > BLOCKLEN - 1 - deque->rightindex)
  647. m = BLOCKLEN - 1 - deque->rightindex;
  648. i += m;
  649. while (m--) {
  650. deque->rightindex++;
  651. deque->rightblock->data[deque->rightindex] = Py_NewRef(item);
  652. }
  653. }
  654. Py_SET_SIZE(deque, Py_SIZE(deque) + i);
  655. return Py_NewRef(deque);
  656. }
  657. if ((size_t)size > PY_SSIZE_T_MAX / (size_t)n) {
  658. return PyErr_NoMemory();
  659. }
  660. seq = PySequence_List((PyObject *)deque);
  661. if (seq == NULL)
  662. return seq;
  663. /* Reduce the number of repetitions when maxlen would be exceeded */
  664. if (deque->maxlen >= 0 && n * size > deque->maxlen)
  665. n = (deque->maxlen + size - 1) / size;
  666. for (i = 0 ; i < n-1 ; i++) {
  667. rv = deque_extend(deque, seq);
  668. if (rv == NULL) {
  669. Py_DECREF(seq);
  670. return NULL;
  671. }
  672. Py_DECREF(rv);
  673. }
  674. Py_INCREF(deque);
  675. Py_DECREF(seq);
  676. return (PyObject *)deque;
  677. }
  678. static PyObject *
  679. deque_repeat(dequeobject *deque, Py_ssize_t n)
  680. {
  681. dequeobject *new_deque;
  682. PyObject *rv;
  683. new_deque = (dequeobject *)deque_copy((PyObject *) deque, NULL);
  684. if (new_deque == NULL)
  685. return NULL;
  686. rv = deque_inplace_repeat(new_deque, n);
  687. Py_DECREF(new_deque);
  688. return rv;
  689. }
  690. /* The rotate() method is part of the public API and is used internally
  691. as a primitive for other methods.
  692. Rotation by 1 or -1 is a common case, so any optimizations for high
  693. volume rotations should take care not to penalize the common case.
  694. Conceptually, a rotate by one is equivalent to a pop on one side and an
  695. append on the other. However, a pop/append pair is unnecessarily slow
  696. because it requires an incref/decref pair for an object located randomly
  697. in memory. It is better to just move the object pointer from one block
  698. to the next without changing the reference count.
  699. When moving batches of pointers, it is tempting to use memcpy() but that
  700. proved to be slower than a simple loop for a variety of reasons.
  701. Memcpy() cannot know in advance that we're copying pointers instead of
  702. bytes, that the source and destination are pointer aligned and
  703. non-overlapping, that moving just one pointer is a common case, that we
  704. never need to move more than BLOCKLEN pointers, and that at least one
  705. pointer is always moved.
  706. For high volume rotations, newblock() and freeblock() are never called
  707. more than once. Previously emptied blocks are immediately reused as a
  708. destination block. If a block is left-over at the end, it is freed.
  709. */
  710. static int
  711. _deque_rotate(dequeobject *deque, Py_ssize_t n)
  712. {
  713. block *b = NULL;
  714. block *leftblock = deque->leftblock;
  715. block *rightblock = deque->rightblock;
  716. Py_ssize_t leftindex = deque->leftindex;
  717. Py_ssize_t rightindex = deque->rightindex;
  718. Py_ssize_t len=Py_SIZE(deque), halflen=len>>1;
  719. int rv = -1;
  720. if (len <= 1)
  721. return 0;
  722. if (n > halflen || n < -halflen) {
  723. n %= len;
  724. if (n > halflen)
  725. n -= len;
  726. else if (n < -halflen)
  727. n += len;
  728. }
  729. assert(len > 1);
  730. assert(-halflen <= n && n <= halflen);
  731. deque->state++;
  732. while (n > 0) {
  733. if (leftindex == 0) {
  734. if (b == NULL) {
  735. b = newblock(deque);
  736. if (b == NULL)
  737. goto done;
  738. }
  739. b->rightlink = leftblock;
  740. CHECK_END(leftblock->leftlink);
  741. leftblock->leftlink = b;
  742. leftblock = b;
  743. MARK_END(b->leftlink);
  744. leftindex = BLOCKLEN;
  745. b = NULL;
  746. }
  747. assert(leftindex > 0);
  748. {
  749. PyObject **src, **dest;
  750. Py_ssize_t m = n;
  751. if (m > rightindex + 1)
  752. m = rightindex + 1;
  753. if (m > leftindex)
  754. m = leftindex;
  755. assert (m > 0 && m <= len);
  756. rightindex -= m;
  757. leftindex -= m;
  758. src = &rightblock->data[rightindex + 1];
  759. dest = &leftblock->data[leftindex];
  760. n -= m;
  761. do {
  762. *(dest++) = *(src++);
  763. } while (--m);
  764. }
  765. if (rightindex < 0) {
  766. assert(leftblock != rightblock);
  767. assert(b == NULL);
  768. b = rightblock;
  769. CHECK_NOT_END(rightblock->leftlink);
  770. rightblock = rightblock->leftlink;
  771. MARK_END(rightblock->rightlink);
  772. rightindex = BLOCKLEN - 1;
  773. }
  774. }
  775. while (n < 0) {
  776. if (rightindex == BLOCKLEN - 1) {
  777. if (b == NULL) {
  778. b = newblock(deque);
  779. if (b == NULL)
  780. goto done;
  781. }
  782. b->leftlink = rightblock;
  783. CHECK_END(rightblock->rightlink);
  784. rightblock->rightlink = b;
  785. rightblock = b;
  786. MARK_END(b->rightlink);
  787. rightindex = -1;
  788. b = NULL;
  789. }
  790. assert (rightindex < BLOCKLEN - 1);
  791. {
  792. PyObject **src, **dest;
  793. Py_ssize_t m = -n;
  794. if (m > BLOCKLEN - leftindex)
  795. m = BLOCKLEN - leftindex;
  796. if (m > BLOCKLEN - 1 - rightindex)
  797. m = BLOCKLEN - 1 - rightindex;
  798. assert (m > 0 && m <= len);
  799. src = &leftblock->data[leftindex];
  800. dest = &rightblock->data[rightindex + 1];
  801. leftindex += m;
  802. rightindex += m;
  803. n += m;
  804. do {
  805. *(dest++) = *(src++);
  806. } while (--m);
  807. }
  808. if (leftindex == BLOCKLEN) {
  809. assert(leftblock != rightblock);
  810. assert(b == NULL);
  811. b = leftblock;
  812. CHECK_NOT_END(leftblock->rightlink);
  813. leftblock = leftblock->rightlink;
  814. MARK_END(leftblock->leftlink);
  815. leftindex = 0;
  816. }
  817. }
  818. rv = 0;
  819. done:
  820. if (b != NULL)
  821. freeblock(deque, b);
  822. deque->leftblock = leftblock;
  823. deque->rightblock = rightblock;
  824. deque->leftindex = leftindex;
  825. deque->rightindex = rightindex;
  826. return rv;
  827. }
  828. static PyObject *
  829. deque_rotate(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
  830. {
  831. Py_ssize_t n=1;
  832. if (!_PyArg_CheckPositional("deque.rotate", nargs, 0, 1)) {
  833. return NULL;
  834. }
  835. if (nargs) {
  836. PyObject *index = _PyNumber_Index(args[0]);
  837. if (index == NULL) {
  838. return NULL;
  839. }
  840. n = PyLong_AsSsize_t(index);
  841. Py_DECREF(index);
  842. if (n == -1 && PyErr_Occurred()) {
  843. return NULL;
  844. }
  845. }
  846. if (!_deque_rotate(deque, n))
  847. Py_RETURN_NONE;
  848. return NULL;
  849. }
  850. PyDoc_STRVAR(rotate_doc,
  851. "Rotate the deque n steps to the right (default n=1). If n is negative, rotates left.");
  852. static PyObject *
  853. deque_reverse(dequeobject *deque, PyObject *unused)
  854. {
  855. block *leftblock = deque->leftblock;
  856. block *rightblock = deque->rightblock;
  857. Py_ssize_t leftindex = deque->leftindex;
  858. Py_ssize_t rightindex = deque->rightindex;
  859. Py_ssize_t n = Py_SIZE(deque) >> 1;
  860. PyObject *tmp;
  861. while (--n >= 0) {
  862. /* Validate that pointers haven't met in the middle */
  863. assert(leftblock != rightblock || leftindex < rightindex);
  864. CHECK_NOT_END(leftblock);
  865. CHECK_NOT_END(rightblock);
  866. /* Swap */
  867. tmp = leftblock->data[leftindex];
  868. leftblock->data[leftindex] = rightblock->data[rightindex];
  869. rightblock->data[rightindex] = tmp;
  870. /* Advance left block/index pair */
  871. leftindex++;
  872. if (leftindex == BLOCKLEN) {
  873. leftblock = leftblock->rightlink;
  874. leftindex = 0;
  875. }
  876. /* Step backwards with the right block/index pair */
  877. rightindex--;
  878. if (rightindex < 0) {
  879. rightblock = rightblock->leftlink;
  880. rightindex = BLOCKLEN - 1;
  881. }
  882. }
  883. Py_RETURN_NONE;
  884. }
  885. PyDoc_STRVAR(reverse_doc,
  886. "D.reverse() -- reverse *IN PLACE*");
  887. static PyObject *
  888. deque_count(dequeobject *deque, PyObject *v)
  889. {
  890. block *b = deque->leftblock;
  891. Py_ssize_t index = deque->leftindex;
  892. Py_ssize_t n = Py_SIZE(deque);
  893. Py_ssize_t count = 0;
  894. size_t start_state = deque->state;
  895. PyObject *item;
  896. int cmp;
  897. while (--n >= 0) {
  898. CHECK_NOT_END(b);
  899. item = Py_NewRef(b->data[index]);
  900. cmp = PyObject_RichCompareBool(item, v, Py_EQ);
  901. Py_DECREF(item);
  902. if (cmp < 0)
  903. return NULL;
  904. count += cmp;
  905. if (start_state != deque->state) {
  906. PyErr_SetString(PyExc_RuntimeError,
  907. "deque mutated during iteration");
  908. return NULL;
  909. }
  910. /* Advance left block/index pair */
  911. index++;
  912. if (index == BLOCKLEN) {
  913. b = b->rightlink;
  914. index = 0;
  915. }
  916. }
  917. return PyLong_FromSsize_t(count);
  918. }
  919. PyDoc_STRVAR(count_doc,
  920. "D.count(value) -- return number of occurrences of value");
  921. static int
  922. deque_contains(dequeobject *deque, PyObject *v)
  923. {
  924. block *b = deque->leftblock;
  925. Py_ssize_t index = deque->leftindex;
  926. Py_ssize_t n = Py_SIZE(deque);
  927. size_t start_state = deque->state;
  928. PyObject *item;
  929. int cmp;
  930. while (--n >= 0) {
  931. CHECK_NOT_END(b);
  932. item = Py_NewRef(b->data[index]);
  933. cmp = PyObject_RichCompareBool(item, v, Py_EQ);
  934. Py_DECREF(item);
  935. if (cmp) {
  936. return cmp;
  937. }
  938. if (start_state != deque->state) {
  939. PyErr_SetString(PyExc_RuntimeError,
  940. "deque mutated during iteration");
  941. return -1;
  942. }
  943. index++;
  944. if (index == BLOCKLEN) {
  945. b = b->rightlink;
  946. index = 0;
  947. }
  948. }
  949. return 0;
  950. }
  951. static Py_ssize_t
  952. deque_len(dequeobject *deque)
  953. {
  954. return Py_SIZE(deque);
  955. }
  956. static PyObject *
  957. deque_index(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
  958. {
  959. Py_ssize_t i, n, start=0, stop=Py_SIZE(deque);
  960. PyObject *v, *item;
  961. block *b = deque->leftblock;
  962. Py_ssize_t index = deque->leftindex;
  963. size_t start_state = deque->state;
  964. int cmp;
  965. if (!_PyArg_ParseStack(args, nargs, "O|O&O&:index", &v,
  966. _PyEval_SliceIndexNotNone, &start,
  967. _PyEval_SliceIndexNotNone, &stop)) {
  968. return NULL;
  969. }
  970. if (start < 0) {
  971. start += Py_SIZE(deque);
  972. if (start < 0)
  973. start = 0;
  974. }
  975. if (stop < 0) {
  976. stop += Py_SIZE(deque);
  977. if (stop < 0)
  978. stop = 0;
  979. }
  980. if (stop > Py_SIZE(deque))
  981. stop = Py_SIZE(deque);
  982. if (start > stop)
  983. start = stop;
  984. assert(0 <= start && start <= stop && stop <= Py_SIZE(deque));
  985. for (i=0 ; i < start - BLOCKLEN ; i += BLOCKLEN) {
  986. b = b->rightlink;
  987. }
  988. for ( ; i < start ; i++) {
  989. index++;
  990. if (index == BLOCKLEN) {
  991. b = b->rightlink;
  992. index = 0;
  993. }
  994. }
  995. n = stop - i;
  996. while (--n >= 0) {
  997. CHECK_NOT_END(b);
  998. item = Py_NewRef(b->data[index]);
  999. cmp = PyObject_RichCompareBool(item, v, Py_EQ);
  1000. Py_DECREF(item);
  1001. if (cmp > 0)
  1002. return PyLong_FromSsize_t(stop - n - 1);
  1003. if (cmp < 0)
  1004. return NULL;
  1005. if (start_state != deque->state) {
  1006. PyErr_SetString(PyExc_RuntimeError,
  1007. "deque mutated during iteration");
  1008. return NULL;
  1009. }
  1010. index++;
  1011. if (index == BLOCKLEN) {
  1012. b = b->rightlink;
  1013. index = 0;
  1014. }
  1015. }
  1016. PyErr_Format(PyExc_ValueError, "%R is not in deque", v);
  1017. return NULL;
  1018. }
  1019. PyDoc_STRVAR(index_doc,
  1020. "D.index(value, [start, [stop]]) -- return first index of value.\n"
  1021. "Raises ValueError if the value is not present.");
  1022. /* insert(), remove(), and delitem() are implemented in terms of
  1023. rotate() for simplicity and reasonable performance near the end
  1024. points. If for some reason these methods become popular, it is not
  1025. hard to re-implement this using direct data movement (similar to
  1026. the code used in list slice assignments) and achieve a performance
  1027. boost (by moving each pointer only once instead of twice).
  1028. */
  1029. static PyObject *
  1030. deque_insert(dequeobject *deque, PyObject *const *args, Py_ssize_t nargs)
  1031. {
  1032. Py_ssize_t index;
  1033. Py_ssize_t n = Py_SIZE(deque);
  1034. PyObject *value;
  1035. PyObject *rv;
  1036. if (!_PyArg_ParseStack(args, nargs, "nO:insert", &index, &value)) {
  1037. return NULL;
  1038. }
  1039. if (deque->maxlen == Py_SIZE(deque)) {
  1040. PyErr_SetString(PyExc_IndexError, "deque already at its maximum size");
  1041. return NULL;
  1042. }
  1043. if (index >= n)
  1044. return deque_append(deque, value);
  1045. if (index <= -n || index == 0)
  1046. return deque_appendleft(deque, value);
  1047. if (_deque_rotate(deque, -index))
  1048. return NULL;
  1049. if (index < 0)
  1050. rv = deque_append(deque, value);
  1051. else
  1052. rv = deque_appendleft(deque, value);
  1053. if (rv == NULL)
  1054. return NULL;
  1055. Py_DECREF(rv);
  1056. if (_deque_rotate(deque, index))
  1057. return NULL;
  1058. Py_RETURN_NONE;
  1059. }
  1060. PyDoc_STRVAR(insert_doc,
  1061. "D.insert(index, object) -- insert object before index");
  1062. PyDoc_STRVAR(remove_doc,
  1063. "D.remove(value) -- remove first occurrence of value.");
  1064. static int
  1065. valid_index(Py_ssize_t i, Py_ssize_t limit)
  1066. {
  1067. /* The cast to size_t lets us use just a single comparison
  1068. to check whether i is in the range: 0 <= i < limit */
  1069. return (size_t) i < (size_t) limit;
  1070. }
  1071. static PyObject *
  1072. deque_item(dequeobject *deque, Py_ssize_t i)
  1073. {
  1074. block *b;
  1075. PyObject *item;
  1076. Py_ssize_t n, index=i;
  1077. if (!valid_index(i, Py_SIZE(deque))) {
  1078. PyErr_SetString(PyExc_IndexError, "deque index out of range");
  1079. return NULL;
  1080. }
  1081. if (i == 0) {
  1082. i = deque->leftindex;
  1083. b = deque->leftblock;
  1084. } else if (i == Py_SIZE(deque) - 1) {
  1085. i = deque->rightindex;
  1086. b = deque->rightblock;
  1087. } else {
  1088. i += deque->leftindex;
  1089. n = (Py_ssize_t)((size_t) i / BLOCKLEN);
  1090. i = (Py_ssize_t)((size_t) i % BLOCKLEN);
  1091. if (index < (Py_SIZE(deque) >> 1)) {
  1092. b = deque->leftblock;
  1093. while (--n >= 0)
  1094. b = b->rightlink;
  1095. } else {
  1096. n = (Py_ssize_t)(
  1097. ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
  1098. / BLOCKLEN - n);
  1099. b = deque->rightblock;
  1100. while (--n >= 0)
  1101. b = b->leftlink;
  1102. }
  1103. }
  1104. item = b->data[i];
  1105. return Py_NewRef(item);
  1106. }
  1107. static int
  1108. deque_del_item(dequeobject *deque, Py_ssize_t i)
  1109. {
  1110. PyObject *item;
  1111. int rv;
  1112. assert (i >= 0 && i < Py_SIZE(deque));
  1113. if (_deque_rotate(deque, -i))
  1114. return -1;
  1115. item = deque_popleft(deque, NULL);
  1116. rv = _deque_rotate(deque, i);
  1117. assert (item != NULL);
  1118. Py_DECREF(item);
  1119. return rv;
  1120. }
  1121. static PyObject *
  1122. deque_remove(dequeobject *deque, PyObject *value)
  1123. {
  1124. PyObject *item;
  1125. block *b = deque->leftblock;
  1126. Py_ssize_t i, n = Py_SIZE(deque), index = deque->leftindex;
  1127. size_t start_state = deque->state;
  1128. int cmp, rv;
  1129. for (i = 0 ; i < n; i++) {
  1130. item = Py_NewRef(b->data[index]);
  1131. cmp = PyObject_RichCompareBool(item, value, Py_EQ);
  1132. Py_DECREF(item);
  1133. if (cmp < 0) {
  1134. return NULL;
  1135. }
  1136. if (start_state != deque->state) {
  1137. PyErr_SetString(PyExc_IndexError,
  1138. "deque mutated during iteration");
  1139. return NULL;
  1140. }
  1141. if (cmp > 0) {
  1142. break;
  1143. }
  1144. index++;
  1145. if (index == BLOCKLEN) {
  1146. b = b->rightlink;
  1147. index = 0;
  1148. }
  1149. }
  1150. if (i == n) {
  1151. PyErr_Format(PyExc_ValueError, "%R is not in deque", value);
  1152. return NULL;
  1153. }
  1154. rv = deque_del_item(deque, i);
  1155. if (rv == -1) {
  1156. return NULL;
  1157. }
  1158. Py_RETURN_NONE;
  1159. }
  1160. static int
  1161. deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
  1162. {
  1163. block *b;
  1164. Py_ssize_t n, len=Py_SIZE(deque), halflen=(len+1)>>1, index=i;
  1165. if (!valid_index(i, len)) {
  1166. PyErr_SetString(PyExc_IndexError, "deque index out of range");
  1167. return -1;
  1168. }
  1169. if (v == NULL)
  1170. return deque_del_item(deque, i);
  1171. i += deque->leftindex;
  1172. n = (Py_ssize_t)((size_t) i / BLOCKLEN);
  1173. i = (Py_ssize_t)((size_t) i % BLOCKLEN);
  1174. if (index <= halflen) {
  1175. b = deque->leftblock;
  1176. while (--n >= 0)
  1177. b = b->rightlink;
  1178. } else {
  1179. n = (Py_ssize_t)(
  1180. ((size_t)(deque->leftindex + Py_SIZE(deque) - 1))
  1181. / BLOCKLEN - n);
  1182. b = deque->rightblock;
  1183. while (--n >= 0)
  1184. b = b->leftlink;
  1185. }
  1186. Py_SETREF(b->data[i], Py_NewRef(v));
  1187. return 0;
  1188. }
  1189. static void
  1190. deque_dealloc(dequeobject *deque)
  1191. {
  1192. PyTypeObject *tp = Py_TYPE(deque);
  1193. Py_ssize_t i;
  1194. PyObject_GC_UnTrack(deque);
  1195. if (deque->weakreflist != NULL)
  1196. PyObject_ClearWeakRefs((PyObject *) deque);
  1197. if (deque->leftblock != NULL) {
  1198. deque_clear(deque);
  1199. assert(deque->leftblock != NULL);
  1200. freeblock(deque, deque->leftblock);
  1201. }
  1202. deque->leftblock = NULL;
  1203. deque->rightblock = NULL;
  1204. for (i=0 ; i < deque->numfreeblocks ; i++) {
  1205. PyMem_Free(deque->freeblocks[i]);
  1206. }
  1207. tp->tp_free(deque);
  1208. Py_DECREF(tp);
  1209. }
  1210. static int
  1211. deque_traverse(dequeobject *deque, visitproc visit, void *arg)
  1212. {
  1213. Py_VISIT(Py_TYPE(deque));
  1214. block *b;
  1215. PyObject *item;
  1216. Py_ssize_t index;
  1217. Py_ssize_t indexlo = deque->leftindex;
  1218. Py_ssize_t indexhigh;
  1219. for (b = deque->leftblock; b != deque->rightblock; b = b->rightlink) {
  1220. for (index = indexlo; index < BLOCKLEN ; index++) {
  1221. item = b->data[index];
  1222. Py_VISIT(item);
  1223. }
  1224. indexlo = 0;
  1225. }
  1226. indexhigh = deque->rightindex;
  1227. for (index = indexlo; index <= indexhigh; index++) {
  1228. item = b->data[index];
  1229. Py_VISIT(item);
  1230. }
  1231. return 0;
  1232. }
  1233. static PyObject *
  1234. deque_reduce(dequeobject *deque, PyObject *Py_UNUSED(ignored))
  1235. {
  1236. PyObject *state, *it;
  1237. state = _PyObject_GetState((PyObject *)deque);
  1238. if (state == NULL) {
  1239. return NULL;
  1240. }
  1241. it = PyObject_GetIter((PyObject *)deque);
  1242. if (it == NULL) {
  1243. Py_DECREF(state);
  1244. return NULL;
  1245. }
  1246. if (deque->maxlen < 0) {
  1247. return Py_BuildValue("O()NN", Py_TYPE(deque), state, it);
  1248. }
  1249. else {
  1250. return Py_BuildValue("O(()n)NN", Py_TYPE(deque), deque->maxlen, state, it);
  1251. }
  1252. }
  1253. PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
  1254. static PyObject *
  1255. deque_repr(PyObject *deque)
  1256. {
  1257. PyObject *aslist, *result;
  1258. int i;
  1259. i = Py_ReprEnter(deque);
  1260. if (i != 0) {
  1261. if (i < 0)
  1262. return NULL;
  1263. return PyUnicode_FromString("[...]");
  1264. }
  1265. aslist = PySequence_List(deque);
  1266. if (aslist == NULL) {
  1267. Py_ReprLeave(deque);
  1268. return NULL;
  1269. }
  1270. if (((dequeobject *)deque)->maxlen >= 0)
  1271. result = PyUnicode_FromFormat("%s(%R, maxlen=%zd)",
  1272. _PyType_Name(Py_TYPE(deque)), aslist,
  1273. ((dequeobject *)deque)->maxlen);
  1274. else
  1275. result = PyUnicode_FromFormat("%s(%R)",
  1276. _PyType_Name(Py_TYPE(deque)), aslist);
  1277. Py_ReprLeave(deque);
  1278. Py_DECREF(aslist);
  1279. return result;
  1280. }
  1281. static PyObject *
  1282. deque_richcompare(PyObject *v, PyObject *w, int op)
  1283. {
  1284. PyObject *it1=NULL, *it2=NULL, *x, *y;
  1285. Py_ssize_t vs, ws;
  1286. int b, cmp=-1;
  1287. collections_state *state = find_module_state_by_def(Py_TYPE(v));
  1288. if (!PyObject_TypeCheck(v, state->deque_type) ||
  1289. !PyObject_TypeCheck(w, state->deque_type)) {
  1290. Py_RETURN_NOTIMPLEMENTED;
  1291. }
  1292. /* Shortcuts */
  1293. vs = Py_SIZE((dequeobject *)v);
  1294. ws = Py_SIZE((dequeobject *)w);
  1295. if (op == Py_EQ) {
  1296. if (v == w)
  1297. Py_RETURN_TRUE;
  1298. if (vs != ws)
  1299. Py_RETURN_FALSE;
  1300. }
  1301. if (op == Py_NE) {
  1302. if (v == w)
  1303. Py_RETURN_FALSE;
  1304. if (vs != ws)
  1305. Py_RETURN_TRUE;
  1306. }
  1307. /* Search for the first index where items are different */
  1308. it1 = PyObject_GetIter(v);
  1309. if (it1 == NULL)
  1310. goto done;
  1311. it2 = PyObject_GetIter(w);
  1312. if (it2 == NULL)
  1313. goto done;
  1314. for (;;) {
  1315. x = PyIter_Next(it1);
  1316. if (x == NULL && PyErr_Occurred())
  1317. goto done;
  1318. y = PyIter_Next(it2);
  1319. if (x == NULL || y == NULL)
  1320. break;
  1321. b = PyObject_RichCompareBool(x, y, Py_EQ);
  1322. if (b == 0) {
  1323. cmp = PyObject_RichCompareBool(x, y, op);
  1324. Py_DECREF(x);
  1325. Py_DECREF(y);
  1326. goto done;
  1327. }
  1328. Py_DECREF(x);
  1329. Py_DECREF(y);
  1330. if (b < 0)
  1331. goto done;
  1332. }
  1333. /* We reached the end of one deque or both */
  1334. Py_XDECREF(x);
  1335. Py_XDECREF(y);
  1336. if (PyErr_Occurred())
  1337. goto done;
  1338. switch (op) {
  1339. case Py_LT: cmp = y != NULL; break; /* if w was longer */
  1340. case Py_LE: cmp = x == NULL; break; /* if v was not longer */
  1341. case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
  1342. case Py_NE: cmp = x != y; break; /* if one deque continues */
  1343. case Py_GT: cmp = x != NULL; break; /* if v was longer */
  1344. case Py_GE: cmp = y == NULL; break; /* if w was not longer */
  1345. }
  1346. done:
  1347. Py_XDECREF(it1);
  1348. Py_XDECREF(it2);
  1349. if (cmp == 1)
  1350. Py_RETURN_TRUE;
  1351. if (cmp == 0)
  1352. Py_RETURN_FALSE;
  1353. return NULL;
  1354. }
  1355. static int
  1356. deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
  1357. {
  1358. PyObject *iterable = NULL;
  1359. PyObject *maxlenobj = NULL;
  1360. Py_ssize_t maxlen = -1;
  1361. char *kwlist[] = {"iterable", "maxlen", 0};
  1362. if (kwdargs == NULL && PyTuple_GET_SIZE(args) <= 2) {
  1363. if (PyTuple_GET_SIZE(args) > 0) {
  1364. iterable = PyTuple_GET_ITEM(args, 0);
  1365. }
  1366. if (PyTuple_GET_SIZE(args) > 1) {
  1367. maxlenobj = PyTuple_GET_ITEM(args, 1);
  1368. }
  1369. } else {
  1370. if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist,
  1371. &iterable, &maxlenobj))
  1372. return -1;
  1373. }
  1374. if (maxlenobj != NULL && maxlenobj != Py_None) {
  1375. maxlen = PyLong_AsSsize_t(maxlenobj);
  1376. if (maxlen == -1 && PyErr_Occurred())
  1377. return -1;
  1378. if (maxlen < 0) {
  1379. PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
  1380. return -1;
  1381. }
  1382. }
  1383. deque->maxlen = maxlen;
  1384. if (Py_SIZE(deque) > 0)
  1385. deque_clear(deque);
  1386. if (iterable != NULL) {
  1387. PyObject *rv = deque_extend(deque, iterable);
  1388. if (rv == NULL)
  1389. return -1;
  1390. Py_DECREF(rv);
  1391. }
  1392. return 0;
  1393. }
  1394. static PyObject *
  1395. deque_sizeof(dequeobject *deque, void *unused)
  1396. {
  1397. size_t res = _PyObject_SIZE(Py_TYPE(deque));
  1398. size_t blocks;
  1399. blocks = (size_t)(deque->leftindex + Py_SIZE(deque) + BLOCKLEN - 1) / BLOCKLEN;
  1400. assert(((size_t)deque->leftindex + (size_t)Py_SIZE(deque) - 1) ==
  1401. ((blocks - 1) * BLOCKLEN + (size_t)deque->rightindex));
  1402. res += blocks * sizeof(block);
  1403. return PyLong_FromSize_t(res);
  1404. }
  1405. PyDoc_STRVAR(sizeof_doc,
  1406. "D.__sizeof__() -- size of D in memory, in bytes");
  1407. static PyObject *
  1408. deque_get_maxlen(dequeobject *deque, void *Py_UNUSED(ignored))
  1409. {
  1410. if (deque->maxlen < 0)
  1411. Py_RETURN_NONE;
  1412. return PyLong_FromSsize_t(deque->maxlen);
  1413. }
  1414. /* deque object ********************************************************/
  1415. static PyGetSetDef deque_getset[] = {
  1416. {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
  1417. "maximum size of a deque or None if unbounded"},
  1418. {0}
  1419. };
  1420. static PyObject *deque_iter(dequeobject *deque);
  1421. static PyObject *deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored));
  1422. PyDoc_STRVAR(reversed_doc,
  1423. "D.__reversed__() -- return a reverse iterator over the deque");
  1424. static PyMethodDef deque_methods[] = {
  1425. {"append", (PyCFunction)deque_append,
  1426. METH_O, append_doc},
  1427. {"appendleft", (PyCFunction)deque_appendleft,
  1428. METH_O, appendleft_doc},
  1429. {"clear", (PyCFunction)deque_clearmethod,
  1430. METH_NOARGS, clear_doc},
  1431. {"__copy__", deque_copy,
  1432. METH_NOARGS, copy_doc},
  1433. {"copy", deque_copy,
  1434. METH_NOARGS, copy_doc},
  1435. {"count", (PyCFunction)deque_count,
  1436. METH_O, count_doc},
  1437. {"extend", (PyCFunction)deque_extend,
  1438. METH_O, extend_doc},
  1439. {"extendleft", (PyCFunction)deque_extendleft,
  1440. METH_O, extendleft_doc},
  1441. {"index", _PyCFunction_CAST(deque_index),
  1442. METH_FASTCALL, index_doc},
  1443. {"insert", _PyCFunction_CAST(deque_insert),
  1444. METH_FASTCALL, insert_doc},
  1445. {"pop", (PyCFunction)deque_pop,
  1446. METH_NOARGS, pop_doc},
  1447. {"popleft", (PyCFunction)deque_popleft,
  1448. METH_NOARGS, popleft_doc},
  1449. {"__reduce__", (PyCFunction)deque_reduce,
  1450. METH_NOARGS, reduce_doc},
  1451. {"remove", (PyCFunction)deque_remove,
  1452. METH_O, remove_doc},
  1453. {"__reversed__", (PyCFunction)deque_reviter,
  1454. METH_NOARGS, reversed_doc},
  1455. {"reverse", (PyCFunction)deque_reverse,
  1456. METH_NOARGS, reverse_doc},
  1457. {"rotate", _PyCFunction_CAST(deque_rotate),
  1458. METH_FASTCALL, rotate_doc},
  1459. {"__sizeof__", (PyCFunction)deque_sizeof,
  1460. METH_NOARGS, sizeof_doc},
  1461. {"__class_getitem__", Py_GenericAlias,
  1462. METH_O|METH_CLASS, PyDoc_STR("See PEP 585")},
  1463. {NULL, NULL} /* sentinel */
  1464. };
  1465. static PyMemberDef deque_members[] = {
  1466. {"__weaklistoffset__", T_PYSSIZET, offsetof(dequeobject, weakreflist), READONLY},
  1467. {NULL},
  1468. };
  1469. PyDoc_STRVAR(deque_doc,
  1470. "deque([iterable[, maxlen]]) --> deque object\n\
  1471. \n\
  1472. A list-like sequence optimized for data accesses near its endpoints.");
  1473. static PyType_Slot deque_slots[] = {
  1474. {Py_tp_dealloc, deque_dealloc},
  1475. {Py_tp_repr, deque_repr},
  1476. {Py_tp_hash, PyObject_HashNotImplemented},
  1477. {Py_tp_getattro, PyObject_GenericGetAttr},
  1478. {Py_tp_doc, (void *)deque_doc},
  1479. {Py_tp_traverse, deque_traverse},
  1480. {Py_tp_clear, deque_clear},
  1481. {Py_tp_richcompare, deque_richcompare},
  1482. {Py_tp_iter, deque_iter},
  1483. {Py_tp_getset, deque_getset},
  1484. {Py_tp_init, deque_init},
  1485. {Py_tp_alloc, PyType_GenericAlloc},
  1486. {Py_tp_new, deque_new},
  1487. {Py_tp_free, PyObject_GC_Del},
  1488. {Py_tp_methods, deque_methods},
  1489. {Py_tp_members, deque_members},
  1490. // Sequence protocol
  1491. {Py_sq_length, deque_len},
  1492. {Py_sq_concat, deque_concat},
  1493. {Py_sq_repeat, deque_repeat},
  1494. {Py_sq_item, deque_item},
  1495. {Py_sq_ass_item, deque_ass_item},
  1496. {Py_sq_contains, deque_contains},
  1497. {Py_sq_inplace_concat, deque_inplace_concat},
  1498. {Py_sq_inplace_repeat, deque_inplace_repeat},
  1499. {0, NULL},
  1500. };
  1501. static PyType_Spec deque_spec = {
  1502. .name = "collections.deque",
  1503. .basicsize = sizeof(dequeobject),
  1504. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  1505. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_SEQUENCE |
  1506. Py_TPFLAGS_IMMUTABLETYPE),
  1507. .slots = deque_slots,
  1508. };
  1509. /*********************** Deque Iterator **************************/
  1510. typedef struct {
  1511. PyObject_HEAD
  1512. block *b;
  1513. Py_ssize_t index;
  1514. dequeobject *deque;
  1515. size_t state; /* state when the iterator is created */
  1516. Py_ssize_t counter; /* number of items remaining for iteration */
  1517. } dequeiterobject;
  1518. static PyObject *
  1519. deque_iter(dequeobject *deque)
  1520. {
  1521. dequeiterobject *it;
  1522. collections_state *state = find_module_state_by_def(Py_TYPE(deque));
  1523. it = PyObject_GC_New(dequeiterobject, state->dequeiter_type);
  1524. if (it == NULL)
  1525. return NULL;
  1526. it->b = deque->leftblock;
  1527. it->index = deque->leftindex;
  1528. it->deque = (dequeobject*)Py_NewRef(deque);
  1529. it->state = deque->state;
  1530. it->counter = Py_SIZE(deque);
  1531. PyObject_GC_Track(it);
  1532. return (PyObject *)it;
  1533. }
  1534. static int
  1535. dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
  1536. {
  1537. Py_VISIT(Py_TYPE(dio));
  1538. Py_VISIT(dio->deque);
  1539. return 0;
  1540. }
  1541. static int
  1542. dequeiter_clear(dequeiterobject *dio)
  1543. {
  1544. Py_CLEAR(dio->deque);
  1545. return 0;
  1546. }
  1547. static void
  1548. dequeiter_dealloc(dequeiterobject *dio)
  1549. {
  1550. /* bpo-31095: UnTrack is needed before calling any callbacks */
  1551. PyTypeObject *tp = Py_TYPE(dio);
  1552. PyObject_GC_UnTrack(dio);
  1553. (void)dequeiter_clear(dio);
  1554. PyObject_GC_Del(dio);
  1555. Py_DECREF(tp);
  1556. }
  1557. static PyObject *
  1558. dequeiter_next(dequeiterobject *it)
  1559. {
  1560. PyObject *item;
  1561. if (it->deque->state != it->state) {
  1562. it->counter = 0;
  1563. PyErr_SetString(PyExc_RuntimeError,
  1564. "deque mutated during iteration");
  1565. return NULL;
  1566. }
  1567. if (it->counter == 0)
  1568. return NULL;
  1569. assert (!(it->b == it->deque->rightblock &&
  1570. it->index > it->deque->rightindex));
  1571. item = it->b->data[it->index];
  1572. it->index++;
  1573. it->counter--;
  1574. if (it->index == BLOCKLEN && it->counter > 0) {
  1575. CHECK_NOT_END(it->b->rightlink);
  1576. it->b = it->b->rightlink;
  1577. it->index = 0;
  1578. }
  1579. return Py_NewRef(item);
  1580. }
  1581. static PyObject *
  1582. dequeiter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1583. {
  1584. Py_ssize_t i, index=0;
  1585. PyObject *deque;
  1586. dequeiterobject *it;
  1587. collections_state *state = get_module_state_by_cls(type);
  1588. if (!PyArg_ParseTuple(args, "O!|n", state->deque_type, &deque, &index))
  1589. return NULL;
  1590. assert(type == state->dequeiter_type);
  1591. it = (dequeiterobject*)deque_iter((dequeobject *)deque);
  1592. if (!it)
  1593. return NULL;
  1594. /* consume items from the queue */
  1595. for(i=0; i<index; i++) {
  1596. PyObject *item = dequeiter_next(it);
  1597. if (item) {
  1598. Py_DECREF(item);
  1599. } else {
  1600. if (it->counter) {
  1601. Py_DECREF(it);
  1602. return NULL;
  1603. } else
  1604. break;
  1605. }
  1606. }
  1607. return (PyObject*)it;
  1608. }
  1609. static PyObject *
  1610. dequeiter_len(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
  1611. {
  1612. return PyLong_FromSsize_t(it->counter);
  1613. }
  1614. PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
  1615. static PyObject *
  1616. dequeiter_reduce(dequeiterobject *it, PyObject *Py_UNUSED(ignored))
  1617. {
  1618. return Py_BuildValue("O(On)", Py_TYPE(it), it->deque, Py_SIZE(it->deque) - it->counter);
  1619. }
  1620. static PyMethodDef dequeiter_methods[] = {
  1621. {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
  1622. {"__reduce__", (PyCFunction)dequeiter_reduce, METH_NOARGS, reduce_doc},
  1623. {NULL, NULL} /* sentinel */
  1624. };
  1625. static PyType_Slot dequeiter_slots[] = {
  1626. {Py_tp_dealloc, dequeiter_dealloc},
  1627. {Py_tp_getattro, PyObject_GenericGetAttr},
  1628. {Py_tp_traverse, dequeiter_traverse},
  1629. {Py_tp_clear, dequeiter_clear},
  1630. {Py_tp_iter, PyObject_SelfIter},
  1631. {Py_tp_iternext, dequeiter_next},
  1632. {Py_tp_methods, dequeiter_methods},
  1633. {Py_tp_new, dequeiter_new},
  1634. {0, NULL},
  1635. };
  1636. static PyType_Spec dequeiter_spec = {
  1637. .name = "collections._deque_iterator",
  1638. .basicsize = sizeof(dequeiterobject),
  1639. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1640. Py_TPFLAGS_IMMUTABLETYPE),
  1641. .slots = dequeiter_slots,
  1642. };
  1643. /*********************** Deque Reverse Iterator **************************/
  1644. static PyObject *
  1645. deque_reviter(dequeobject *deque, PyObject *Py_UNUSED(ignored))
  1646. {
  1647. dequeiterobject *it;
  1648. collections_state *state = find_module_state_by_def(Py_TYPE(deque));
  1649. it = PyObject_GC_New(dequeiterobject, state->dequereviter_type);
  1650. if (it == NULL)
  1651. return NULL;
  1652. it->b = deque->rightblock;
  1653. it->index = deque->rightindex;
  1654. it->deque = (dequeobject*)Py_NewRef(deque);
  1655. it->state = deque->state;
  1656. it->counter = Py_SIZE(deque);
  1657. PyObject_GC_Track(it);
  1658. return (PyObject *)it;
  1659. }
  1660. static PyObject *
  1661. dequereviter_next(dequeiterobject *it)
  1662. {
  1663. PyObject *item;
  1664. if (it->counter == 0)
  1665. return NULL;
  1666. if (it->deque->state != it->state) {
  1667. it->counter = 0;
  1668. PyErr_SetString(PyExc_RuntimeError,
  1669. "deque mutated during iteration");
  1670. return NULL;
  1671. }
  1672. assert (!(it->b == it->deque->leftblock &&
  1673. it->index < it->deque->leftindex));
  1674. item = it->b->data[it->index];
  1675. it->index--;
  1676. it->counter--;
  1677. if (it->index < 0 && it->counter > 0) {
  1678. CHECK_NOT_END(it->b->leftlink);
  1679. it->b = it->b->leftlink;
  1680. it->index = BLOCKLEN - 1;
  1681. }
  1682. return Py_NewRef(item);
  1683. }
  1684. static PyObject *
  1685. dequereviter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  1686. {
  1687. Py_ssize_t i, index=0;
  1688. PyObject *deque;
  1689. dequeiterobject *it;
  1690. collections_state *state = get_module_state_by_cls(type);
  1691. if (!PyArg_ParseTuple(args, "O!|n", state->deque_type, &deque, &index))
  1692. return NULL;
  1693. assert(type == state->dequereviter_type);
  1694. it = (dequeiterobject*)deque_reviter((dequeobject *)deque, NULL);
  1695. if (!it)
  1696. return NULL;
  1697. /* consume items from the queue */
  1698. for(i=0; i<index; i++) {
  1699. PyObject *item = dequereviter_next(it);
  1700. if (item) {
  1701. Py_DECREF(item);
  1702. } else {
  1703. if (it->counter) {
  1704. Py_DECREF(it);
  1705. return NULL;
  1706. } else
  1707. break;
  1708. }
  1709. }
  1710. return (PyObject*)it;
  1711. }
  1712. static PyType_Slot dequereviter_slots[] = {
  1713. {Py_tp_dealloc, dequeiter_dealloc},
  1714. {Py_tp_getattro, PyObject_GenericGetAttr},
  1715. {Py_tp_traverse, dequeiter_traverse},
  1716. {Py_tp_clear, dequeiter_clear},
  1717. {Py_tp_iter, PyObject_SelfIter},
  1718. {Py_tp_iternext, dequereviter_next},
  1719. {Py_tp_methods, dequeiter_methods},
  1720. {Py_tp_new, dequereviter_new},
  1721. {0, NULL},
  1722. };
  1723. static PyType_Spec dequereviter_spec = {
  1724. .name = "collections._deque_reverse_iterator",
  1725. .basicsize = sizeof(dequeiterobject),
  1726. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  1727. Py_TPFLAGS_IMMUTABLETYPE),
  1728. .slots = dequereviter_slots,
  1729. };
  1730. /* defaultdict type *********************************************************/
  1731. typedef struct {
  1732. PyDictObject dict;
  1733. PyObject *default_factory;
  1734. } defdictobject;
  1735. PyDoc_STRVAR(defdict_missing_doc,
  1736. "__missing__(key) # Called by __getitem__ for missing key; pseudo-code:\n\
  1737. if self.default_factory is None: raise KeyError((key,))\n\
  1738. self[key] = value = self.default_factory()\n\
  1739. return value\n\
  1740. ");
  1741. static PyObject *
  1742. defdict_missing(defdictobject *dd, PyObject *key)
  1743. {
  1744. PyObject *factory = dd->default_factory;
  1745. PyObject *value;
  1746. if (factory == NULL || factory == Py_None) {
  1747. /* XXX Call dict.__missing__(key) */
  1748. PyObject *tup;
  1749. tup = PyTuple_Pack(1, key);
  1750. if (!tup) return NULL;
  1751. PyErr_SetObject(PyExc_KeyError, tup);
  1752. Py_DECREF(tup);
  1753. return NULL;
  1754. }
  1755. value = _PyObject_CallNoArgs(factory);
  1756. if (value == NULL)
  1757. return value;
  1758. if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
  1759. Py_DECREF(value);
  1760. return NULL;
  1761. }
  1762. return value;
  1763. }
  1764. static inline PyObject*
  1765. new_defdict(defdictobject *dd, PyObject *arg)
  1766. {
  1767. return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
  1768. dd->default_factory ? dd->default_factory : Py_None, arg, NULL);
  1769. }
  1770. PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
  1771. static PyObject *
  1772. defdict_copy(defdictobject *dd, PyObject *Py_UNUSED(ignored))
  1773. {
  1774. /* This calls the object's class. That only works for subclasses
  1775. whose class constructor has the same signature. Subclasses that
  1776. define a different constructor signature must override copy().
  1777. */
  1778. return new_defdict(dd, (PyObject*)dd);
  1779. }
  1780. static PyObject *
  1781. defdict_reduce(defdictobject *dd, PyObject *Py_UNUSED(ignored))
  1782. {
  1783. /* __reduce__ must return a 5-tuple as follows:
  1784. - factory function
  1785. - tuple of args for the factory function
  1786. - additional state (here None)
  1787. - sequence iterator (here None)
  1788. - dictionary iterator (yielding successive (key, value) pairs
  1789. This API is used by pickle.py and copy.py.
  1790. For this to be useful with pickle.py, the default_factory
  1791. must be picklable; e.g., None, a built-in, or a global
  1792. function in a module or package.
  1793. Both shallow and deep copying are supported, but for deep
  1794. copying, the default_factory must be deep-copyable; e.g. None,
  1795. or a built-in (functions are not copyable at this time).
  1796. This only works for subclasses as long as their constructor
  1797. signature is compatible; the first argument must be the
  1798. optional default_factory, defaulting to None.
  1799. */
  1800. PyObject *args;
  1801. PyObject *items;
  1802. PyObject *iter;
  1803. PyObject *result;
  1804. if (dd->default_factory == NULL || dd->default_factory == Py_None)
  1805. args = PyTuple_New(0);
  1806. else
  1807. args = PyTuple_Pack(1, dd->default_factory);
  1808. if (args == NULL)
  1809. return NULL;
  1810. items = PyObject_CallMethodNoArgs((PyObject *)dd, &_Py_ID(items));
  1811. if (items == NULL) {
  1812. Py_DECREF(args);
  1813. return NULL;
  1814. }
  1815. iter = PyObject_GetIter(items);
  1816. if (iter == NULL) {
  1817. Py_DECREF(items);
  1818. Py_DECREF(args);
  1819. return NULL;
  1820. }
  1821. result = PyTuple_Pack(5, Py_TYPE(dd), args,
  1822. Py_None, Py_None, iter);
  1823. Py_DECREF(iter);
  1824. Py_DECREF(items);
  1825. Py_DECREF(args);
  1826. return result;
  1827. }
  1828. static PyMethodDef defdict_methods[] = {
  1829. {"__missing__", (PyCFunction)defdict_missing, METH_O,
  1830. defdict_missing_doc},
  1831. {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
  1832. defdict_copy_doc},
  1833. {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
  1834. defdict_copy_doc},
  1835. {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
  1836. reduce_doc},
  1837. {"__class_getitem__", Py_GenericAlias, METH_O|METH_CLASS,
  1838. PyDoc_STR("See PEP 585")},
  1839. {NULL}
  1840. };
  1841. static PyMemberDef defdict_members[] = {
  1842. {"default_factory", T_OBJECT,
  1843. offsetof(defdictobject, default_factory), 0,
  1844. PyDoc_STR("Factory for default value called by __missing__().")},
  1845. {NULL}
  1846. };
  1847. static void
  1848. defdict_dealloc(defdictobject *dd)
  1849. {
  1850. /* bpo-31095: UnTrack is needed before calling any callbacks */
  1851. PyTypeObject *tp = Py_TYPE(dd);
  1852. PyObject_GC_UnTrack(dd);
  1853. Py_CLEAR(dd->default_factory);
  1854. PyDict_Type.tp_dealloc((PyObject *)dd);
  1855. Py_DECREF(tp);
  1856. }
  1857. static PyObject *
  1858. defdict_repr(defdictobject *dd)
  1859. {
  1860. PyObject *baserepr;
  1861. PyObject *defrepr;
  1862. PyObject *result;
  1863. baserepr = PyDict_Type.tp_repr((PyObject *)dd);
  1864. if (baserepr == NULL)
  1865. return NULL;
  1866. if (dd->default_factory == NULL)
  1867. defrepr = PyUnicode_FromString("None");
  1868. else
  1869. {
  1870. int status = Py_ReprEnter(dd->default_factory);
  1871. if (status != 0) {
  1872. if (status < 0) {
  1873. Py_DECREF(baserepr);
  1874. return NULL;
  1875. }
  1876. defrepr = PyUnicode_FromString("...");
  1877. }
  1878. else
  1879. defrepr = PyObject_Repr(dd->default_factory);
  1880. Py_ReprLeave(dd->default_factory);
  1881. }
  1882. if (defrepr == NULL) {
  1883. Py_DECREF(baserepr);
  1884. return NULL;
  1885. }
  1886. result = PyUnicode_FromFormat("%s(%U, %U)",
  1887. _PyType_Name(Py_TYPE(dd)),
  1888. defrepr, baserepr);
  1889. Py_DECREF(defrepr);
  1890. Py_DECREF(baserepr);
  1891. return result;
  1892. }
  1893. static PyObject*
  1894. defdict_or(PyObject* left, PyObject* right)
  1895. {
  1896. PyObject *self, *other;
  1897. // Find module state
  1898. PyTypeObject *tp = Py_TYPE(left);
  1899. PyObject *mod = PyType_GetModuleByDef(tp, &_collectionsmodule);
  1900. if (mod == NULL) {
  1901. PyErr_Clear();
  1902. tp = Py_TYPE(right);
  1903. mod = PyType_GetModuleByDef(tp, &_collectionsmodule);
  1904. }
  1905. assert(mod != NULL);
  1906. collections_state *state = get_module_state(mod);
  1907. if (PyObject_TypeCheck(left, state->defdict_type)) {
  1908. self = left;
  1909. other = right;
  1910. }
  1911. else {
  1912. assert(PyObject_TypeCheck(right, state->defdict_type));
  1913. self = right;
  1914. other = left;
  1915. }
  1916. if (!PyDict_Check(other)) {
  1917. Py_RETURN_NOTIMPLEMENTED;
  1918. }
  1919. // Like copy(), this calls the object's class.
  1920. // Override __or__/__ror__ for subclasses with different constructors.
  1921. PyObject *new = new_defdict((defdictobject*)self, left);
  1922. if (!new) {
  1923. return NULL;
  1924. }
  1925. if (PyDict_Update(new, right)) {
  1926. Py_DECREF(new);
  1927. return NULL;
  1928. }
  1929. return new;
  1930. }
  1931. static int
  1932. defdict_traverse(PyObject *self, visitproc visit, void *arg)
  1933. {
  1934. Py_VISIT(Py_TYPE(self));
  1935. Py_VISIT(((defdictobject *)self)->default_factory);
  1936. return PyDict_Type.tp_traverse(self, visit, arg);
  1937. }
  1938. static int
  1939. defdict_tp_clear(defdictobject *dd)
  1940. {
  1941. Py_CLEAR(dd->default_factory);
  1942. return PyDict_Type.tp_clear((PyObject *)dd);
  1943. }
  1944. static int
  1945. defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
  1946. {
  1947. defdictobject *dd = (defdictobject *)self;
  1948. PyObject *olddefault = dd->default_factory;
  1949. PyObject *newdefault = NULL;
  1950. PyObject *newargs;
  1951. int result;
  1952. if (args == NULL || !PyTuple_Check(args))
  1953. newargs = PyTuple_New(0);
  1954. else {
  1955. Py_ssize_t n = PyTuple_GET_SIZE(args);
  1956. if (n > 0) {
  1957. newdefault = PyTuple_GET_ITEM(args, 0);
  1958. if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
  1959. PyErr_SetString(PyExc_TypeError,
  1960. "first argument must be callable or None");
  1961. return -1;
  1962. }
  1963. }
  1964. newargs = PySequence_GetSlice(args, 1, n);
  1965. }
  1966. if (newargs == NULL)
  1967. return -1;
  1968. dd->default_factory = Py_XNewRef(newdefault);
  1969. result = PyDict_Type.tp_init(self, newargs, kwds);
  1970. Py_DECREF(newargs);
  1971. Py_XDECREF(olddefault);
  1972. return result;
  1973. }
  1974. PyDoc_STRVAR(defdict_doc,
  1975. "defaultdict(default_factory=None, /, [...]) --> dict with default factory\n\
  1976. \n\
  1977. The default factory is called without arguments to produce\n\
  1978. a new value when a key is not present, in __getitem__ only.\n\
  1979. A defaultdict compares equal to a dict with the same items.\n\
  1980. All remaining arguments are treated the same as if they were\n\
  1981. passed to the dict constructor, including keyword arguments.\n\
  1982. ");
  1983. /* See comment in xxsubtype.c */
  1984. #define DEFERRED_ADDRESS(ADDR) 0
  1985. static PyType_Slot defdict_slots[] = {
  1986. {Py_tp_dealloc, defdict_dealloc},
  1987. {Py_tp_repr, defdict_repr},
  1988. {Py_nb_or, defdict_or},
  1989. {Py_tp_getattro, PyObject_GenericGetAttr},
  1990. {Py_tp_doc, (void *)defdict_doc},
  1991. {Py_tp_traverse, defdict_traverse},
  1992. {Py_tp_clear, defdict_tp_clear},
  1993. {Py_tp_methods, defdict_methods},
  1994. {Py_tp_members, defdict_members},
  1995. {Py_tp_init, defdict_init},
  1996. {Py_tp_alloc, PyType_GenericAlloc},
  1997. {Py_tp_free, PyObject_GC_Del},
  1998. {0, NULL},
  1999. };
  2000. static PyType_Spec defdict_spec = {
  2001. .name = "collections.defaultdict",
  2002. .basicsize = sizeof(defdictobject),
  2003. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  2004. Py_TPFLAGS_IMMUTABLETYPE),
  2005. .slots = defdict_slots,
  2006. };
  2007. /* helper function for Counter *********************************************/
  2008. /*[clinic input]
  2009. _collections._count_elements
  2010. mapping: object
  2011. iterable: object
  2012. /
  2013. Count elements in the iterable, updating the mapping
  2014. [clinic start generated code]*/
  2015. static PyObject *
  2016. _collections__count_elements_impl(PyObject *module, PyObject *mapping,
  2017. PyObject *iterable)
  2018. /*[clinic end generated code: output=7e0c1789636b3d8f input=e79fad04534a0b45]*/
  2019. {
  2020. PyObject *it, *oldval;
  2021. PyObject *newval = NULL;
  2022. PyObject *key = NULL;
  2023. PyObject *bound_get = NULL;
  2024. PyObject *mapping_get;
  2025. PyObject *dict_get;
  2026. PyObject *mapping_setitem;
  2027. PyObject *dict_setitem;
  2028. PyObject *one = _PyLong_GetOne(); // borrowed reference
  2029. it = PyObject_GetIter(iterable);
  2030. if (it == NULL)
  2031. return NULL;
  2032. /* Only take the fast path when get() and __setitem__()
  2033. * have not been overridden.
  2034. */
  2035. mapping_get = _PyType_Lookup(Py_TYPE(mapping), &_Py_ID(get));
  2036. dict_get = _PyType_Lookup(&PyDict_Type, &_Py_ID(get));
  2037. mapping_setitem = _PyType_Lookup(Py_TYPE(mapping), &_Py_ID(__setitem__));
  2038. dict_setitem = _PyType_Lookup(&PyDict_Type, &_Py_ID(__setitem__));
  2039. if (mapping_get != NULL && mapping_get == dict_get &&
  2040. mapping_setitem != NULL && mapping_setitem == dict_setitem &&
  2041. PyDict_Check(mapping))
  2042. {
  2043. while (1) {
  2044. /* Fast path advantages:
  2045. 1. Eliminate double hashing
  2046. (by re-using the same hash for both the get and set)
  2047. 2. Avoid argument overhead of PyObject_CallFunctionObjArgs
  2048. (argument tuple creation and parsing)
  2049. 3. Avoid indirection through a bound method object
  2050. (creates another argument tuple)
  2051. 4. Avoid initial increment from zero
  2052. (reuse an existing one-object instead)
  2053. */
  2054. Py_hash_t hash;
  2055. key = PyIter_Next(it);
  2056. if (key == NULL)
  2057. break;
  2058. if (!PyUnicode_CheckExact(key) ||
  2059. (hash = _PyASCIIObject_CAST(key)->hash) == -1)
  2060. {
  2061. hash = PyObject_Hash(key);
  2062. if (hash == -1)
  2063. goto done;
  2064. }
  2065. oldval = _PyDict_GetItem_KnownHash(mapping, key, hash);
  2066. if (oldval == NULL) {
  2067. if (PyErr_Occurred())
  2068. goto done;
  2069. if (_PyDict_SetItem_KnownHash(mapping, key, one, hash) < 0)
  2070. goto done;
  2071. } else {
  2072. newval = PyNumber_Add(oldval, one);
  2073. if (newval == NULL)
  2074. goto done;
  2075. if (_PyDict_SetItem_KnownHash(mapping, key, newval, hash) < 0)
  2076. goto done;
  2077. Py_CLEAR(newval);
  2078. }
  2079. Py_DECREF(key);
  2080. }
  2081. }
  2082. else {
  2083. bound_get = PyObject_GetAttr(mapping, &_Py_ID(get));
  2084. if (bound_get == NULL)
  2085. goto done;
  2086. PyObject *zero = _PyLong_GetZero(); // borrowed reference
  2087. while (1) {
  2088. key = PyIter_Next(it);
  2089. if (key == NULL)
  2090. break;
  2091. oldval = PyObject_CallFunctionObjArgs(bound_get, key, zero, NULL);
  2092. if (oldval == NULL)
  2093. break;
  2094. newval = PyNumber_Add(oldval, one);
  2095. Py_DECREF(oldval);
  2096. if (newval == NULL)
  2097. break;
  2098. if (PyObject_SetItem(mapping, key, newval) < 0)
  2099. break;
  2100. Py_CLEAR(newval);
  2101. Py_DECREF(key);
  2102. }
  2103. }
  2104. done:
  2105. Py_DECREF(it);
  2106. Py_XDECREF(key);
  2107. Py_XDECREF(newval);
  2108. Py_XDECREF(bound_get);
  2109. if (PyErr_Occurred())
  2110. return NULL;
  2111. Py_RETURN_NONE;
  2112. }
  2113. /* Helper function for namedtuple() ************************************/
  2114. typedef struct {
  2115. PyObject_HEAD
  2116. Py_ssize_t index;
  2117. PyObject* doc;
  2118. } _tuplegetterobject;
  2119. /*[clinic input]
  2120. @classmethod
  2121. _tuplegetter.__new__ as tuplegetter_new
  2122. index: Py_ssize_t
  2123. doc: object
  2124. /
  2125. [clinic start generated code]*/
  2126. static PyObject *
  2127. tuplegetter_new_impl(PyTypeObject *type, Py_ssize_t index, PyObject *doc)
  2128. /*[clinic end generated code: output=014be444ad80263f input=87c576a5bdbc0bbb]*/
  2129. {
  2130. _tuplegetterobject* self;
  2131. self = (_tuplegetterobject *)type->tp_alloc(type, 0);
  2132. if (self == NULL) {
  2133. return NULL;
  2134. }
  2135. self->index = index;
  2136. self->doc = Py_NewRef(doc);
  2137. return (PyObject *)self;
  2138. }
  2139. static PyObject *
  2140. tuplegetter_descr_get(PyObject *self, PyObject *obj, PyObject *type)
  2141. {
  2142. Py_ssize_t index = ((_tuplegetterobject*)self)->index;
  2143. PyObject *result;
  2144. if (obj == NULL) {
  2145. return Py_NewRef(self);
  2146. }
  2147. if (!PyTuple_Check(obj)) {
  2148. if (obj == Py_None) {
  2149. return Py_NewRef(self);
  2150. }
  2151. PyErr_Format(PyExc_TypeError,
  2152. "descriptor for index '%zd' for tuple subclasses "
  2153. "doesn't apply to '%s' object",
  2154. index,
  2155. Py_TYPE(obj)->tp_name);
  2156. return NULL;
  2157. }
  2158. if (!valid_index(index, PyTuple_GET_SIZE(obj))) {
  2159. PyErr_SetString(PyExc_IndexError, "tuple index out of range");
  2160. return NULL;
  2161. }
  2162. result = PyTuple_GET_ITEM(obj, index);
  2163. return Py_NewRef(result);
  2164. }
  2165. static int
  2166. tuplegetter_descr_set(PyObject *self, PyObject *obj, PyObject *value)
  2167. {
  2168. if (value == NULL) {
  2169. PyErr_SetString(PyExc_AttributeError, "can't delete attribute");
  2170. } else {
  2171. PyErr_SetString(PyExc_AttributeError, "can't set attribute");
  2172. }
  2173. return -1;
  2174. }
  2175. static int
  2176. tuplegetter_traverse(PyObject *self, visitproc visit, void *arg)
  2177. {
  2178. _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
  2179. Py_VISIT(Py_TYPE(tuplegetter));
  2180. Py_VISIT(tuplegetter->doc);
  2181. return 0;
  2182. }
  2183. static int
  2184. tuplegetter_clear(PyObject *self)
  2185. {
  2186. _tuplegetterobject *tuplegetter = (_tuplegetterobject *)self;
  2187. Py_CLEAR(tuplegetter->doc);
  2188. return 0;
  2189. }
  2190. static void
  2191. tuplegetter_dealloc(_tuplegetterobject *self)
  2192. {
  2193. PyTypeObject *tp = Py_TYPE(self);
  2194. PyObject_GC_UnTrack(self);
  2195. tuplegetter_clear((PyObject*)self);
  2196. tp->tp_free((PyObject*)self);
  2197. Py_DECREF(tp);
  2198. }
  2199. static PyObject*
  2200. tuplegetter_reduce(_tuplegetterobject *self, PyObject *Py_UNUSED(ignored))
  2201. {
  2202. return Py_BuildValue("(O(nO))", (PyObject*) Py_TYPE(self), self->index, self->doc);
  2203. }
  2204. static PyObject*
  2205. tuplegetter_repr(_tuplegetterobject *self)
  2206. {
  2207. return PyUnicode_FromFormat("%s(%zd, %R)",
  2208. _PyType_Name(Py_TYPE(self)),
  2209. self->index, self->doc);
  2210. }
  2211. static PyMemberDef tuplegetter_members[] = {
  2212. {"__doc__", T_OBJECT, offsetof(_tuplegetterobject, doc), 0},
  2213. {0}
  2214. };
  2215. static PyMethodDef tuplegetter_methods[] = {
  2216. {"__reduce__", (PyCFunction)tuplegetter_reduce, METH_NOARGS, NULL},
  2217. {NULL},
  2218. };
  2219. static PyType_Slot tuplegetter_slots[] = {
  2220. {Py_tp_dealloc, tuplegetter_dealloc},
  2221. {Py_tp_repr, tuplegetter_repr},
  2222. {Py_tp_traverse, tuplegetter_traverse},
  2223. {Py_tp_clear, tuplegetter_clear},
  2224. {Py_tp_methods, tuplegetter_methods},
  2225. {Py_tp_members, tuplegetter_members},
  2226. {Py_tp_descr_get, tuplegetter_descr_get},
  2227. {Py_tp_descr_set, tuplegetter_descr_set},
  2228. {Py_tp_new, tuplegetter_new},
  2229. {0, NULL},
  2230. };
  2231. static PyType_Spec tuplegetter_spec = {
  2232. .name = "collections._tuplegetter",
  2233. .basicsize = sizeof(_tuplegetterobject),
  2234. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  2235. Py_TPFLAGS_IMMUTABLETYPE),
  2236. .slots = tuplegetter_slots,
  2237. };
  2238. /* module level code ********************************************************/
  2239. static int
  2240. collections_traverse(PyObject *mod, visitproc visit, void *arg)
  2241. {
  2242. collections_state *state = get_module_state(mod);
  2243. Py_VISIT(state->deque_type);
  2244. Py_VISIT(state->defdict_type);
  2245. Py_VISIT(state->dequeiter_type);
  2246. Py_VISIT(state->dequereviter_type);
  2247. Py_VISIT(state->tuplegetter_type);
  2248. return 0;
  2249. }
  2250. static int
  2251. collections_clear(PyObject *mod)
  2252. {
  2253. collections_state *state = get_module_state(mod);
  2254. Py_CLEAR(state->deque_type);
  2255. Py_CLEAR(state->defdict_type);
  2256. Py_CLEAR(state->dequeiter_type);
  2257. Py_CLEAR(state->dequereviter_type);
  2258. Py_CLEAR(state->tuplegetter_type);
  2259. return 0;
  2260. }
  2261. static void
  2262. collections_free(void *module)
  2263. {
  2264. collections_clear((PyObject *)module);
  2265. }
  2266. PyDoc_STRVAR(collections_doc,
  2267. "High performance data structures.\n\
  2268. - deque: ordered collection accessible from endpoints only\n\
  2269. - defaultdict: dict subclass with a default value factory\n\
  2270. ");
  2271. static struct PyMethodDef collections_methods[] = {
  2272. _COLLECTIONS__COUNT_ELEMENTS_METHODDEF
  2273. {NULL, NULL} /* sentinel */
  2274. };
  2275. #define ADD_TYPE(MOD, SPEC, TYPE, BASE) do { \
  2276. TYPE = (PyTypeObject *)PyType_FromMetaclass(NULL, MOD, SPEC, \
  2277. (PyObject *)BASE); \
  2278. if (TYPE == NULL) { \
  2279. return -1; \
  2280. } \
  2281. if (PyModule_AddType(MOD, TYPE) < 0) { \
  2282. return -1; \
  2283. } \
  2284. } while (0)
  2285. static int
  2286. collections_exec(PyObject *module) {
  2287. collections_state *state = get_module_state(module);
  2288. ADD_TYPE(module, &deque_spec, state->deque_type, NULL);
  2289. ADD_TYPE(module, &defdict_spec, state->defdict_type, &PyDict_Type);
  2290. ADD_TYPE(module, &dequeiter_spec, state->dequeiter_type, NULL);
  2291. ADD_TYPE(module, &dequereviter_spec, state->dequereviter_type, NULL);
  2292. ADD_TYPE(module, &tuplegetter_spec, state->tuplegetter_type, NULL);
  2293. if (PyModule_AddType(module, &PyODict_Type) < 0) {
  2294. return -1;
  2295. }
  2296. return 0;
  2297. }
  2298. #undef ADD_TYPE
  2299. static struct PyModuleDef_Slot collections_slots[] = {
  2300. {Py_mod_exec, collections_exec},
  2301. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  2302. {0, NULL}
  2303. };
  2304. static struct PyModuleDef _collectionsmodule = {
  2305. .m_base = PyModuleDef_HEAD_INIT,
  2306. .m_name = "_collections",
  2307. .m_doc = collections_doc,
  2308. .m_size = sizeof(collections_state),
  2309. .m_methods = collections_methods,
  2310. .m_slots = collections_slots,
  2311. .m_traverse = collections_traverse,
  2312. .m_clear = collections_clear,
  2313. .m_free = collections_free,
  2314. };
  2315. PyMODINIT_FUNC
  2316. PyInit__collections(void)
  2317. {
  2318. return PyModuleDef_Init(&_collectionsmodule);
  2319. }