PageRenderTime 69ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

https://bitbucket.org/python_mirrors/sandbox-guido
C | 2904 lines | 2256 code | 267 blank | 381 comment | 598 complexity | 5ddead3c837f8fde1d20d267a0acb453 MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD

Large files files are truncated, but you can click here to view the full file

  1. /* List object implementation */
  2. #include "Python.h"
  3. #ifdef STDC_HEADERS
  4. #include <stddef.h>
  5. #else
  6. #include <sys/types.h> /* For size_t */
  7. #endif
  8. /* Ensure ob_item has room for at least newsize elements, and set
  9. * ob_size to newsize. If newsize > ob_size on entry, the content
  10. * of the new slots at exit is undefined heap trash; it's the caller's
  11. * responsibility to overwrite them with sane values.
  12. * The number of allocated elements may grow, shrink, or stay the same.
  13. * Failure is impossible if newsize <= self.allocated on entry, although
  14. * that partly relies on an assumption that the system realloc() never
  15. * fails when passed a number of bytes <= the number of bytes last
  16. * allocated (the C standard doesn't guarantee this, but it's hard to
  17. * imagine a realloc implementation where it wouldn't be true).
  18. * Note that self->ob_item may change, and even if newsize is less
  19. * than ob_size on entry.
  20. */
  21. static int
  22. list_resize(PyListObject *self, Py_ssize_t newsize)
  23. {
  24. PyObject **items;
  25. size_t new_allocated;
  26. Py_ssize_t allocated = self->allocated;
  27. /* Bypass realloc() when a previous overallocation is large enough
  28. to accommodate the newsize. If the newsize falls lower than half
  29. the allocated size, then proceed with the realloc() to shrink the list.
  30. */
  31. if (allocated >= newsize && newsize >= (allocated >> 1)) {
  32. assert(self->ob_item != NULL || newsize == 0);
  33. Py_SIZE(self) = newsize;
  34. return 0;
  35. }
  36. /* This over-allocates proportional to the list size, making room
  37. * for additional growth. The over-allocation is mild, but is
  38. * enough to give linear-time amortized behavior over a long
  39. * sequence of appends() in the presence of a poorly-performing
  40. * system realloc().
  41. * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
  42. */
  43. new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
  44. /* check for integer overflow */
  45. if (new_allocated > PY_SIZE_MAX - newsize) {
  46. PyErr_NoMemory();
  47. return -1;
  48. } else {
  49. new_allocated += newsize;
  50. }
  51. if (newsize == 0)
  52. new_allocated = 0;
  53. items = self->ob_item;
  54. if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
  55. PyMem_RESIZE(items, PyObject *, new_allocated);
  56. else
  57. items = NULL;
  58. if (items == NULL) {
  59. PyErr_NoMemory();
  60. return -1;
  61. }
  62. self->ob_item = items;
  63. Py_SIZE(self) = newsize;
  64. self->allocated = new_allocated;
  65. return 0;
  66. }
  67. /* Debug statistic to compare allocations with reuse through the free list */
  68. #undef SHOW_ALLOC_COUNT
  69. #ifdef SHOW_ALLOC_COUNT
  70. static size_t count_alloc = 0;
  71. static size_t count_reuse = 0;
  72. static void
  73. show_alloc(void)
  74. {
  75. fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
  76. count_alloc);
  77. fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
  78. "d\n", count_reuse);
  79. fprintf(stderr, "%.2f%% reuse rate\n\n",
  80. (100.0*count_reuse/(count_alloc+count_reuse)));
  81. }
  82. #endif
  83. /* Empty list reuse scheme to save calls to malloc and free */
  84. #ifndef PyList_MAXFREELIST
  85. #define PyList_MAXFREELIST 80
  86. #endif
  87. static PyListObject *free_list[PyList_MAXFREELIST];
  88. static int numfree = 0;
  89. void
  90. PyList_Fini(void)
  91. {
  92. PyListObject *op;
  93. while (numfree) {
  94. op = free_list[--numfree];
  95. assert(PyList_CheckExact(op));
  96. PyObject_GC_Del(op);
  97. }
  98. }
  99. PyObject *
  100. PyList_New(Py_ssize_t size)
  101. {
  102. PyListObject *op;
  103. size_t nbytes;
  104. #ifdef SHOW_ALLOC_COUNT
  105. static int initialized = 0;
  106. if (!initialized) {
  107. Py_AtExit(show_alloc);
  108. initialized = 1;
  109. }
  110. #endif
  111. if (size < 0) {
  112. PyErr_BadInternalCall();
  113. return NULL;
  114. }
  115. /* Check for overflow without an actual overflow,
  116. * which can cause compiler to optimise out */
  117. if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
  118. return PyErr_NoMemory();
  119. nbytes = size * sizeof(PyObject *);
  120. if (numfree) {
  121. numfree--;
  122. op = free_list[numfree];
  123. _Py_NewReference((PyObject *)op);
  124. #ifdef SHOW_ALLOC_COUNT
  125. count_reuse++;
  126. #endif
  127. } else {
  128. op = PyObject_GC_New(PyListObject, &PyList_Type);
  129. if (op == NULL)
  130. return NULL;
  131. #ifdef SHOW_ALLOC_COUNT
  132. count_alloc++;
  133. #endif
  134. }
  135. if (size <= 0)
  136. op->ob_item = NULL;
  137. else {
  138. op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
  139. if (op->ob_item == NULL) {
  140. Py_DECREF(op);
  141. return PyErr_NoMemory();
  142. }
  143. memset(op->ob_item, 0, nbytes);
  144. }
  145. Py_SIZE(op) = size;
  146. op->allocated = size;
  147. _PyObject_GC_TRACK(op);
  148. return (PyObject *) op;
  149. }
  150. Py_ssize_t
  151. PyList_Size(PyObject *op)
  152. {
  153. if (!PyList_Check(op)) {
  154. PyErr_BadInternalCall();
  155. return -1;
  156. }
  157. else
  158. return Py_SIZE(op);
  159. }
  160. static PyObject *indexerr = NULL;
  161. PyObject *
  162. PyList_GetItem(PyObject *op, Py_ssize_t i)
  163. {
  164. if (!PyList_Check(op)) {
  165. PyErr_BadInternalCall();
  166. return NULL;
  167. }
  168. if (i < 0 || i >= Py_SIZE(op)) {
  169. if (indexerr == NULL) {
  170. indexerr = PyUnicode_FromString(
  171. "list index out of range");
  172. if (indexerr == NULL)
  173. return NULL;
  174. }
  175. PyErr_SetObject(PyExc_IndexError, indexerr);
  176. return NULL;
  177. }
  178. return ((PyListObject *)op) -> ob_item[i];
  179. }
  180. int
  181. PyList_SetItem(register PyObject *op, register Py_ssize_t i,
  182. register PyObject *newitem)
  183. {
  184. register PyObject *olditem;
  185. register PyObject **p;
  186. if (!PyList_Check(op)) {
  187. Py_XDECREF(newitem);
  188. PyErr_BadInternalCall();
  189. return -1;
  190. }
  191. if (i < 0 || i >= Py_SIZE(op)) {
  192. Py_XDECREF(newitem);
  193. PyErr_SetString(PyExc_IndexError,
  194. "list assignment index out of range");
  195. return -1;
  196. }
  197. p = ((PyListObject *)op) -> ob_item + i;
  198. olditem = *p;
  199. *p = newitem;
  200. Py_XDECREF(olditem);
  201. return 0;
  202. }
  203. static int
  204. ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
  205. {
  206. Py_ssize_t i, n = Py_SIZE(self);
  207. PyObject **items;
  208. if (v == NULL) {
  209. PyErr_BadInternalCall();
  210. return -1;
  211. }
  212. if (n == PY_SSIZE_T_MAX) {
  213. PyErr_SetString(PyExc_OverflowError,
  214. "cannot add more objects to list");
  215. return -1;
  216. }
  217. if (list_resize(self, n+1) == -1)
  218. return -1;
  219. if (where < 0) {
  220. where += n;
  221. if (where < 0)
  222. where = 0;
  223. }
  224. if (where > n)
  225. where = n;
  226. items = self->ob_item;
  227. for (i = n; --i >= where; )
  228. items[i+1] = items[i];
  229. Py_INCREF(v);
  230. items[where] = v;
  231. return 0;
  232. }
  233. int
  234. PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
  235. {
  236. if (!PyList_Check(op)) {
  237. PyErr_BadInternalCall();
  238. return -1;
  239. }
  240. return ins1((PyListObject *)op, where, newitem);
  241. }
  242. static int
  243. app1(PyListObject *self, PyObject *v)
  244. {
  245. Py_ssize_t n = PyList_GET_SIZE(self);
  246. assert (v != NULL);
  247. if (n == PY_SSIZE_T_MAX) {
  248. PyErr_SetString(PyExc_OverflowError,
  249. "cannot add more objects to list");
  250. return -1;
  251. }
  252. if (list_resize(self, n+1) == -1)
  253. return -1;
  254. Py_INCREF(v);
  255. PyList_SET_ITEM(self, n, v);
  256. return 0;
  257. }
  258. int
  259. PyList_Append(PyObject *op, PyObject *newitem)
  260. {
  261. if (PyList_Check(op) && (newitem != NULL))
  262. return app1((PyListObject *)op, newitem);
  263. PyErr_BadInternalCall();
  264. return -1;
  265. }
  266. /* Methods */
  267. static void
  268. list_dealloc(PyListObject *op)
  269. {
  270. Py_ssize_t i;
  271. PyObject_GC_UnTrack(op);
  272. Py_TRASHCAN_SAFE_BEGIN(op)
  273. if (op->ob_item != NULL) {
  274. /* Do it backwards, for Christian Tismer.
  275. There's a simple test case where somehow this reduces
  276. thrashing when a *very* large list is created and
  277. immediately deleted. */
  278. i = Py_SIZE(op);
  279. while (--i >= 0) {
  280. Py_XDECREF(op->ob_item[i]);
  281. }
  282. PyMem_FREE(op->ob_item);
  283. }
  284. if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
  285. free_list[numfree++] = op;
  286. else
  287. Py_TYPE(op)->tp_free((PyObject *)op);
  288. Py_TRASHCAN_SAFE_END(op)
  289. }
  290. static PyObject *
  291. list_repr(PyListObject *v)
  292. {
  293. Py_ssize_t i;
  294. PyObject *s, *temp;
  295. PyObject *pieces = NULL, *result = NULL;
  296. i = Py_ReprEnter((PyObject*)v);
  297. if (i != 0) {
  298. return i > 0 ? PyUnicode_FromString("[...]") : NULL;
  299. }
  300. if (Py_SIZE(v) == 0) {
  301. result = PyUnicode_FromString("[]");
  302. goto Done;
  303. }
  304. pieces = PyList_New(0);
  305. if (pieces == NULL)
  306. goto Done;
  307. /* Do repr() on each element. Note that this may mutate the list,
  308. so must refetch the list size on each iteration. */
  309. for (i = 0; i < Py_SIZE(v); ++i) {
  310. int status;
  311. if (Py_EnterRecursiveCall(" while getting the repr of a list"))
  312. goto Done;
  313. s = PyObject_Repr(v->ob_item[i]);
  314. Py_LeaveRecursiveCall();
  315. if (s == NULL)
  316. goto Done;
  317. status = PyList_Append(pieces, s);
  318. Py_DECREF(s); /* append created a new ref */
  319. if (status < 0)
  320. goto Done;
  321. }
  322. /* Add "[]" decorations to the first and last items. */
  323. assert(PyList_GET_SIZE(pieces) > 0);
  324. s = PyUnicode_FromString("[");
  325. if (s == NULL)
  326. goto Done;
  327. temp = PyList_GET_ITEM(pieces, 0);
  328. PyUnicode_AppendAndDel(&s, temp);
  329. PyList_SET_ITEM(pieces, 0, s);
  330. if (s == NULL)
  331. goto Done;
  332. s = PyUnicode_FromString("]");
  333. if (s == NULL)
  334. goto Done;
  335. temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
  336. PyUnicode_AppendAndDel(&temp, s);
  337. PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
  338. if (temp == NULL)
  339. goto Done;
  340. /* Paste them all together with ", " between. */
  341. s = PyUnicode_FromString(", ");
  342. if (s == NULL)
  343. goto Done;
  344. result = PyUnicode_Join(s, pieces);
  345. Py_DECREF(s);
  346. Done:
  347. Py_XDECREF(pieces);
  348. Py_ReprLeave((PyObject *)v);
  349. return result;
  350. }
  351. static Py_ssize_t
  352. list_length(PyListObject *a)
  353. {
  354. return Py_SIZE(a);
  355. }
  356. static int
  357. list_contains(PyListObject *a, PyObject *el)
  358. {
  359. Py_ssize_t i;
  360. int cmp;
  361. for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
  362. cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
  363. Py_EQ);
  364. return cmp;
  365. }
  366. static PyObject *
  367. list_item(PyListObject *a, Py_ssize_t i)
  368. {
  369. if (i < 0 || i >= Py_SIZE(a)) {
  370. if (indexerr == NULL) {
  371. indexerr = PyUnicode_FromString(
  372. "list index out of range");
  373. if (indexerr == NULL)
  374. return NULL;
  375. }
  376. PyErr_SetObject(PyExc_IndexError, indexerr);
  377. return NULL;
  378. }
  379. Py_INCREF(a->ob_item[i]);
  380. return a->ob_item[i];
  381. }
  382. static PyObject *
  383. list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  384. {
  385. PyListObject *np;
  386. PyObject **src, **dest;
  387. Py_ssize_t i, len;
  388. if (ilow < 0)
  389. ilow = 0;
  390. else if (ilow > Py_SIZE(a))
  391. ilow = Py_SIZE(a);
  392. if (ihigh < ilow)
  393. ihigh = ilow;
  394. else if (ihigh > Py_SIZE(a))
  395. ihigh = Py_SIZE(a);
  396. len = ihigh - ilow;
  397. np = (PyListObject *) PyList_New(len);
  398. if (np == NULL)
  399. return NULL;
  400. src = a->ob_item + ilow;
  401. dest = np->ob_item;
  402. for (i = 0; i < len; i++) {
  403. PyObject *v = src[i];
  404. Py_INCREF(v);
  405. dest[i] = v;
  406. }
  407. return (PyObject *)np;
  408. }
  409. PyObject *
  410. PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  411. {
  412. if (!PyList_Check(a)) {
  413. PyErr_BadInternalCall();
  414. return NULL;
  415. }
  416. return list_slice((PyListObject *)a, ilow, ihigh);
  417. }
  418. static PyObject *
  419. list_concat(PyListObject *a, PyObject *bb)
  420. {
  421. Py_ssize_t size;
  422. Py_ssize_t i;
  423. PyObject **src, **dest;
  424. PyListObject *np;
  425. if (!PyList_Check(bb)) {
  426. PyErr_Format(PyExc_TypeError,
  427. "can only concatenate list (not \"%.200s\") to list",
  428. bb->ob_type->tp_name);
  429. return NULL;
  430. }
  431. #define b ((PyListObject *)bb)
  432. size = Py_SIZE(a) + Py_SIZE(b);
  433. if (size < 0)
  434. return PyErr_NoMemory();
  435. np = (PyListObject *) PyList_New(size);
  436. if (np == NULL) {
  437. return NULL;
  438. }
  439. src = a->ob_item;
  440. dest = np->ob_item;
  441. for (i = 0; i < Py_SIZE(a); i++) {
  442. PyObject *v = src[i];
  443. Py_INCREF(v);
  444. dest[i] = v;
  445. }
  446. src = b->ob_item;
  447. dest = np->ob_item + Py_SIZE(a);
  448. for (i = 0; i < Py_SIZE(b); i++) {
  449. PyObject *v = src[i];
  450. Py_INCREF(v);
  451. dest[i] = v;
  452. }
  453. return (PyObject *)np;
  454. #undef b
  455. }
  456. static PyObject *
  457. list_repeat(PyListObject *a, Py_ssize_t n)
  458. {
  459. Py_ssize_t i, j;
  460. Py_ssize_t size;
  461. PyListObject *np;
  462. PyObject **p, **items;
  463. PyObject *elem;
  464. if (n < 0)
  465. n = 0;
  466. size = Py_SIZE(a) * n;
  467. if (n && size/n != Py_SIZE(a))
  468. return PyErr_NoMemory();
  469. if (size == 0)
  470. return PyList_New(0);
  471. np = (PyListObject *) PyList_New(size);
  472. if (np == NULL)
  473. return NULL;
  474. items = np->ob_item;
  475. if (Py_SIZE(a) == 1) {
  476. elem = a->ob_item[0];
  477. for (i = 0; i < n; i++) {
  478. items[i] = elem;
  479. Py_INCREF(elem);
  480. }
  481. return (PyObject *) np;
  482. }
  483. p = np->ob_item;
  484. items = a->ob_item;
  485. for (i = 0; i < n; i++) {
  486. for (j = 0; j < Py_SIZE(a); j++) {
  487. *p = items[j];
  488. Py_INCREF(*p);
  489. p++;
  490. }
  491. }
  492. return (PyObject *) np;
  493. }
  494. static int
  495. list_clear(PyListObject *a)
  496. {
  497. Py_ssize_t i;
  498. PyObject **item = a->ob_item;
  499. if (item != NULL) {
  500. /* Because XDECREF can recursively invoke operations on
  501. this list, we make it empty first. */
  502. i = Py_SIZE(a);
  503. Py_SIZE(a) = 0;
  504. a->ob_item = NULL;
  505. a->allocated = 0;
  506. while (--i >= 0) {
  507. Py_XDECREF(item[i]);
  508. }
  509. PyMem_FREE(item);
  510. }
  511. /* Never fails; the return value can be ignored.
  512. Note that there is no guarantee that the list is actually empty
  513. at this point, because XDECREF may have populated it again! */
  514. return 0;
  515. }
  516. /* a[ilow:ihigh] = v if v != NULL.
  517. * del a[ilow:ihigh] if v == NULL.
  518. *
  519. * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
  520. * guaranteed the call cannot fail.
  521. */
  522. static int
  523. list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  524. {
  525. /* Because [X]DECREF can recursively invoke list operations on
  526. this list, we must postpone all [X]DECREF activity until
  527. after the list is back in its canonical shape. Therefore
  528. we must allocate an additional array, 'recycle', into which
  529. we temporarily copy the items that are deleted from the
  530. list. :-( */
  531. PyObject *recycle_on_stack[8];
  532. PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
  533. PyObject **item;
  534. PyObject **vitem = NULL;
  535. PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
  536. Py_ssize_t n; /* # of elements in replacement list */
  537. Py_ssize_t norig; /* # of elements in list getting replaced */
  538. Py_ssize_t d; /* Change in size */
  539. Py_ssize_t k;
  540. size_t s;
  541. int result = -1; /* guilty until proved innocent */
  542. #define b ((PyListObject *)v)
  543. if (v == NULL)
  544. n = 0;
  545. else {
  546. if (a == b) {
  547. /* Special case "a[i:j] = a" -- copy b first */
  548. v = list_slice(b, 0, Py_SIZE(b));
  549. if (v == NULL)
  550. return result;
  551. result = list_ass_slice(a, ilow, ihigh, v);
  552. Py_DECREF(v);
  553. return result;
  554. }
  555. v_as_SF = PySequence_Fast(v, "can only assign an iterable");
  556. if(v_as_SF == NULL)
  557. goto Error;
  558. n = PySequence_Fast_GET_SIZE(v_as_SF);
  559. vitem = PySequence_Fast_ITEMS(v_as_SF);
  560. }
  561. if (ilow < 0)
  562. ilow = 0;
  563. else if (ilow > Py_SIZE(a))
  564. ilow = Py_SIZE(a);
  565. if (ihigh < ilow)
  566. ihigh = ilow;
  567. else if (ihigh > Py_SIZE(a))
  568. ihigh = Py_SIZE(a);
  569. norig = ihigh - ilow;
  570. assert(norig >= 0);
  571. d = n - norig;
  572. if (Py_SIZE(a) + d == 0) {
  573. Py_XDECREF(v_as_SF);
  574. return list_clear(a);
  575. }
  576. item = a->ob_item;
  577. /* recycle the items that we are about to remove */
  578. s = norig * sizeof(PyObject *);
  579. if (s > sizeof(recycle_on_stack)) {
  580. recycle = (PyObject **)PyMem_MALLOC(s);
  581. if (recycle == NULL) {
  582. PyErr_NoMemory();
  583. goto Error;
  584. }
  585. }
  586. memcpy(recycle, &item[ilow], s);
  587. if (d < 0) { /* Delete -d items */
  588. memmove(&item[ihigh+d], &item[ihigh],
  589. (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
  590. list_resize(a, Py_SIZE(a) + d);
  591. item = a->ob_item;
  592. }
  593. else if (d > 0) { /* Insert d items */
  594. k = Py_SIZE(a);
  595. if (list_resize(a, k+d) < 0)
  596. goto Error;
  597. item = a->ob_item;
  598. memmove(&item[ihigh+d], &item[ihigh],
  599. (k - ihigh)*sizeof(PyObject *));
  600. }
  601. for (k = 0; k < n; k++, ilow++) {
  602. PyObject *w = vitem[k];
  603. Py_XINCREF(w);
  604. item[ilow] = w;
  605. }
  606. for (k = norig - 1; k >= 0; --k)
  607. Py_XDECREF(recycle[k]);
  608. result = 0;
  609. Error:
  610. if (recycle != recycle_on_stack)
  611. PyMem_FREE(recycle);
  612. Py_XDECREF(v_as_SF);
  613. return result;
  614. #undef b
  615. }
  616. int
  617. PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  618. {
  619. if (!PyList_Check(a)) {
  620. PyErr_BadInternalCall();
  621. return -1;
  622. }
  623. return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  624. }
  625. static PyObject *
  626. list_inplace_repeat(PyListObject *self, Py_ssize_t n)
  627. {
  628. PyObject **items;
  629. Py_ssize_t size, i, j, p;
  630. size = PyList_GET_SIZE(self);
  631. if (size == 0 || n == 1) {
  632. Py_INCREF(self);
  633. return (PyObject *)self;
  634. }
  635. if (n < 1) {
  636. (void)list_clear(self);
  637. Py_INCREF(self);
  638. return (PyObject *)self;
  639. }
  640. if (size > PY_SSIZE_T_MAX / n) {
  641. return PyErr_NoMemory();
  642. }
  643. if (list_resize(self, size*n) == -1)
  644. return NULL;
  645. p = size;
  646. items = self->ob_item;
  647. for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
  648. for (j = 0; j < size; j++) {
  649. PyObject *o = items[j];
  650. Py_INCREF(o);
  651. items[p++] = o;
  652. }
  653. }
  654. Py_INCREF(self);
  655. return (PyObject *)self;
  656. }
  657. static int
  658. list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
  659. {
  660. PyObject *old_value;
  661. if (i < 0 || i >= Py_SIZE(a)) {
  662. PyErr_SetString(PyExc_IndexError,
  663. "list assignment index out of range");
  664. return -1;
  665. }
  666. if (v == NULL)
  667. return list_ass_slice(a, i, i+1, v);
  668. Py_INCREF(v);
  669. old_value = a->ob_item[i];
  670. a->ob_item[i] = v;
  671. Py_DECREF(old_value);
  672. return 0;
  673. }
  674. static PyObject *
  675. listinsert(PyListObject *self, PyObject *args)
  676. {
  677. Py_ssize_t i;
  678. PyObject *v;
  679. if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
  680. return NULL;
  681. if (ins1(self, i, v) == 0)
  682. Py_RETURN_NONE;
  683. return NULL;
  684. }
  685. static PyObject *
  686. listclear(PyListObject *self)
  687. {
  688. list_clear(self);
  689. Py_RETURN_NONE;
  690. }
  691. static PyObject *
  692. listcopy(PyListObject *self)
  693. {
  694. return list_slice(self, 0, Py_SIZE(self));
  695. }
  696. static PyObject *
  697. listappend(PyListObject *self, PyObject *v)
  698. {
  699. if (app1(self, v) == 0)
  700. Py_RETURN_NONE;
  701. return NULL;
  702. }
  703. static PyObject *
  704. listextend(PyListObject *self, PyObject *b)
  705. {
  706. PyObject *it; /* iter(v) */
  707. Py_ssize_t m; /* size of self */
  708. Py_ssize_t n; /* guess for size of b */
  709. Py_ssize_t mn; /* m + n */
  710. Py_ssize_t i;
  711. PyObject *(*iternext)(PyObject *);
  712. /* Special cases:
  713. 1) lists and tuples which can use PySequence_Fast ops
  714. 2) extending self to self requires making a copy first
  715. */
  716. if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
  717. PyObject **src, **dest;
  718. b = PySequence_Fast(b, "argument must be iterable");
  719. if (!b)
  720. return NULL;
  721. n = PySequence_Fast_GET_SIZE(b);
  722. if (n == 0) {
  723. /* short circuit when b is empty */
  724. Py_DECREF(b);
  725. Py_RETURN_NONE;
  726. }
  727. m = Py_SIZE(self);
  728. if (list_resize(self, m + n) == -1) {
  729. Py_DECREF(b);
  730. return NULL;
  731. }
  732. /* note that we may still have self == b here for the
  733. * situation a.extend(a), but the following code works
  734. * in that case too. Just make sure to resize self
  735. * before calling PySequence_Fast_ITEMS.
  736. */
  737. /* populate the end of self with b's items */
  738. src = PySequence_Fast_ITEMS(b);
  739. dest = self->ob_item + m;
  740. for (i = 0; i < n; i++) {
  741. PyObject *o = src[i];
  742. Py_INCREF(o);
  743. dest[i] = o;
  744. }
  745. Py_DECREF(b);
  746. Py_RETURN_NONE;
  747. }
  748. it = PyObject_GetIter(b);
  749. if (it == NULL)
  750. return NULL;
  751. iternext = *it->ob_type->tp_iternext;
  752. /* Guess a result list size. */
  753. n = _PyObject_LengthHint(b, 8);
  754. if (n == -1) {
  755. Py_DECREF(it);
  756. return NULL;
  757. }
  758. m = Py_SIZE(self);
  759. mn = m + n;
  760. if (mn >= m) {
  761. /* Make room. */
  762. if (list_resize(self, mn) == -1)
  763. goto error;
  764. /* Make the list sane again. */
  765. Py_SIZE(self) = m;
  766. }
  767. /* Else m + n overflowed; on the chance that n lied, and there really
  768. * is enough room, ignore it. If n was telling the truth, we'll
  769. * eventually run out of memory during the loop.
  770. */
  771. /* Run iterator to exhaustion. */
  772. for (;;) {
  773. PyObject *item = iternext(it);
  774. if (item == NULL) {
  775. if (PyErr_Occurred()) {
  776. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  777. PyErr_Clear();
  778. else
  779. goto error;
  780. }
  781. break;
  782. }
  783. if (Py_SIZE(self) < self->allocated) {
  784. /* steals ref */
  785. PyList_SET_ITEM(self, Py_SIZE(self), item);
  786. ++Py_SIZE(self);
  787. }
  788. else {
  789. int status = app1(self, item);
  790. Py_DECREF(item); /* append creates a new ref */
  791. if (status < 0)
  792. goto error;
  793. }
  794. }
  795. /* Cut back result list if initial guess was too large. */
  796. if (Py_SIZE(self) < self->allocated)
  797. list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
  798. Py_DECREF(it);
  799. Py_RETURN_NONE;
  800. error:
  801. Py_DECREF(it);
  802. return NULL;
  803. }
  804. PyObject *
  805. _PyList_Extend(PyListObject *self, PyObject *b)
  806. {
  807. return listextend(self, b);
  808. }
  809. static PyObject *
  810. list_inplace_concat(PyListObject *self, PyObject *other)
  811. {
  812. PyObject *result;
  813. result = listextend(self, other);
  814. if (result == NULL)
  815. return result;
  816. Py_DECREF(result);
  817. Py_INCREF(self);
  818. return (PyObject *)self;
  819. }
  820. static PyObject *
  821. listpop(PyListObject *self, PyObject *args)
  822. {
  823. Py_ssize_t i = -1;
  824. PyObject *v;
  825. int status;
  826. if (!PyArg_ParseTuple(args, "|n:pop", &i))
  827. return NULL;
  828. if (Py_SIZE(self) == 0) {
  829. /* Special-case most common failure cause */
  830. PyErr_SetString(PyExc_IndexError, "pop from empty list");
  831. return NULL;
  832. }
  833. if (i < 0)
  834. i += Py_SIZE(self);
  835. if (i < 0 || i >= Py_SIZE(self)) {
  836. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  837. return NULL;
  838. }
  839. v = self->ob_item[i];
  840. if (i == Py_SIZE(self) - 1) {
  841. status = list_resize(self, Py_SIZE(self) - 1);
  842. assert(status >= 0);
  843. return v; /* and v now owns the reference the list had */
  844. }
  845. Py_INCREF(v);
  846. status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
  847. assert(status >= 0);
  848. /* Use status, so that in a release build compilers don't
  849. * complain about the unused name.
  850. */
  851. (void) status;
  852. return v;
  853. }
  854. /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
  855. static void
  856. reverse_slice(PyObject **lo, PyObject **hi)
  857. {
  858. assert(lo && hi);
  859. --hi;
  860. while (lo < hi) {
  861. PyObject *t = *lo;
  862. *lo = *hi;
  863. *hi = t;
  864. ++lo;
  865. --hi;
  866. }
  867. }
  868. /* Lots of code for an adaptive, stable, natural mergesort. There are many
  869. * pieces to this algorithm; read listsort.txt for overviews and details.
  870. */
  871. /* A sortslice contains a pointer to an array of keys and a pointer to
  872. * an array of corresponding values. In other words, keys[i]
  873. * corresponds with values[i]. If values == NULL, then the keys are
  874. * also the values.
  875. *
  876. * Several convenience routines are provided here, so that keys and
  877. * values are always moved in sync.
  878. */
  879. typedef struct {
  880. PyObject **keys;
  881. PyObject **values;
  882. } sortslice;
  883. Py_LOCAL_INLINE(void)
  884. sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
  885. {
  886. s1->keys[i] = s2->keys[j];
  887. if (s1->values != NULL)
  888. s1->values[i] = s2->values[j];
  889. }
  890. Py_LOCAL_INLINE(void)
  891. sortslice_copy_incr(sortslice *dst, sortslice *src)
  892. {
  893. *dst->keys++ = *src->keys++;
  894. if (dst->values != NULL)
  895. *dst->values++ = *src->values++;
  896. }
  897. Py_LOCAL_INLINE(void)
  898. sortslice_copy_decr(sortslice *dst, sortslice *src)
  899. {
  900. *dst->keys-- = *src->keys--;
  901. if (dst->values != NULL)
  902. *dst->values-- = *src->values--;
  903. }
  904. Py_LOCAL_INLINE(void)
  905. sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
  906. Py_ssize_t n)
  907. {
  908. memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
  909. if (s1->values != NULL)
  910. memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
  911. }
  912. Py_LOCAL_INLINE(void)
  913. sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
  914. Py_ssize_t n)
  915. {
  916. memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
  917. if (s1->values != NULL)
  918. memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
  919. }
  920. Py_LOCAL_INLINE(void)
  921. sortslice_advance(sortslice *slice, Py_ssize_t n)
  922. {
  923. slice->keys += n;
  924. if (slice->values != NULL)
  925. slice->values += n;
  926. }
  927. /* Comparison function: PyObject_RichCompareBool with Py_LT.
  928. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  929. */
  930. #define ISLT(X, Y) (PyObject_RichCompareBool(X, Y, Py_LT))
  931. /* Compare X to Y via "<". Goto "fail" if the comparison raises an
  932. error. Else "k" is set to true iff X<Y, and an "if (k)" block is
  933. started. It makes more sense in context <wink>. X and Y are PyObject*s.
  934. */
  935. #define IFLT(X, Y) if ((k = ISLT(X, Y)) < 0) goto fail; \
  936. if (k)
  937. /* binarysort is the best method for sorting small arrays: it does
  938. few compares, but can do data movement quadratic in the number of
  939. elements.
  940. [lo, hi) is a contiguous slice of a list, and is sorted via
  941. binary insertion. This sort is stable.
  942. On entry, must have lo <= start <= hi, and that [lo, start) is already
  943. sorted (pass start == lo if you don't know!).
  944. If islt() complains return -1, else 0.
  945. Even in case of error, the output slice will be some permutation of
  946. the input (nothing is lost or duplicated).
  947. */
  948. static int
  949. binarysort(sortslice lo, PyObject **hi, PyObject **start)
  950. {
  951. register Py_ssize_t k;
  952. register PyObject **l, **p, **r;
  953. register PyObject *pivot;
  954. assert(lo.keys <= start && start <= hi);
  955. /* assert [lo, start) is sorted */
  956. if (lo.keys == start)
  957. ++start;
  958. for (; start < hi; ++start) {
  959. /* set l to where *start belongs */
  960. l = lo.keys;
  961. r = start;
  962. pivot = *r;
  963. /* Invariants:
  964. * pivot >= all in [lo, l).
  965. * pivot < all in [r, start).
  966. * The second is vacuously true at the start.
  967. */
  968. assert(l < r);
  969. do {
  970. p = l + ((r - l) >> 1);
  971. IFLT(pivot, *p)
  972. r = p;
  973. else
  974. l = p+1;
  975. } while (l < r);
  976. assert(l == r);
  977. /* The invariants still hold, so pivot >= all in [lo, l) and
  978. pivot < all in [l, start), so pivot belongs at l. Note
  979. that if there are elements equal to pivot, l points to the
  980. first slot after them -- that's why this sort is stable.
  981. Slide over to make room.
  982. Caution: using memmove is much slower under MSVC 5;
  983. we're not usually moving many slots. */
  984. for (p = start; p > l; --p)
  985. *p = *(p-1);
  986. *l = pivot;
  987. if (lo.values != NULL) {
  988. Py_ssize_t offset = lo.values - lo.keys;
  989. p = start + offset;
  990. pivot = *p;
  991. l += offset;
  992. for (p = start + offset; p > l; --p)
  993. *p = *(p-1);
  994. *l = pivot;
  995. }
  996. }
  997. return 0;
  998. fail:
  999. return -1;
  1000. }
  1001. /*
  1002. Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
  1003. is required on entry. "A run" is the longest ascending sequence, with
  1004. lo[0] <= lo[1] <= lo[2] <= ...
  1005. or the longest descending sequence, with
  1006. lo[0] > lo[1] > lo[2] > ...
  1007. Boolean *descending is set to 0 in the former case, or to 1 in the latter.
  1008. For its intended use in a stable mergesort, the strictness of the defn of
  1009. "descending" is needed so that the caller can safely reverse a descending
  1010. sequence without violating stability (strict > ensures there are no equal
  1011. elements to get out of order).
  1012. Returns -1 in case of error.
  1013. */
  1014. static Py_ssize_t
  1015. count_run(PyObject **lo, PyObject **hi, int *descending)
  1016. {
  1017. Py_ssize_t k;
  1018. Py_ssize_t n;
  1019. assert(lo < hi);
  1020. *descending = 0;
  1021. ++lo;
  1022. if (lo == hi)
  1023. return 1;
  1024. n = 2;
  1025. IFLT(*lo, *(lo-1)) {
  1026. *descending = 1;
  1027. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1028. IFLT(*lo, *(lo-1))
  1029. ;
  1030. else
  1031. break;
  1032. }
  1033. }
  1034. else {
  1035. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1036. IFLT(*lo, *(lo-1))
  1037. break;
  1038. }
  1039. }
  1040. return n;
  1041. fail:
  1042. return -1;
  1043. }
  1044. /*
  1045. Locate the proper position of key in a sorted vector; if the vector contains
  1046. an element equal to key, return the position immediately to the left of
  1047. the leftmost equal element. [gallop_right() does the same except returns
  1048. the position to the right of the rightmost equal element (if any).]
  1049. "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
  1050. "hint" is an index at which to begin the search, 0 <= hint < n. The closer
  1051. hint is to the final result, the faster this runs.
  1052. The return value is the int k in 0..n such that
  1053. a[k-1] < key <= a[k]
  1054. pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
  1055. key belongs at index k; or, IOW, the first k elements of a should precede
  1056. key, and the last n-k should follow key.
  1057. Returns -1 on error. See listsort.txt for info on the method.
  1058. */
  1059. static Py_ssize_t
  1060. gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
  1061. {
  1062. Py_ssize_t ofs;
  1063. Py_ssize_t lastofs;
  1064. Py_ssize_t k;
  1065. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1066. a += hint;
  1067. lastofs = 0;
  1068. ofs = 1;
  1069. IFLT(*a, key) {
  1070. /* a[hint] < key -- gallop right, until
  1071. * a[hint + lastofs] < key <= a[hint + ofs]
  1072. */
  1073. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1074. while (ofs < maxofs) {
  1075. IFLT(a[ofs], key) {
  1076. lastofs = ofs;
  1077. ofs = (ofs << 1) + 1;
  1078. if (ofs <= 0) /* int overflow */
  1079. ofs = maxofs;
  1080. }
  1081. else /* key <= a[hint + ofs] */
  1082. break;
  1083. }
  1084. if (ofs > maxofs)
  1085. ofs = maxofs;
  1086. /* Translate back to offsets relative to &a[0]. */
  1087. lastofs += hint;
  1088. ofs += hint;
  1089. }
  1090. else {
  1091. /* key <= a[hint] -- gallop left, until
  1092. * a[hint - ofs] < key <= a[hint - lastofs]
  1093. */
  1094. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1095. while (ofs < maxofs) {
  1096. IFLT(*(a-ofs), key)
  1097. break;
  1098. /* key <= a[hint - ofs] */
  1099. lastofs = ofs;
  1100. ofs = (ofs << 1) + 1;
  1101. if (ofs <= 0) /* int overflow */
  1102. ofs = maxofs;
  1103. }
  1104. if (ofs > maxofs)
  1105. ofs = maxofs;
  1106. /* Translate back to positive offsets relative to &a[0]. */
  1107. k = lastofs;
  1108. lastofs = hint - ofs;
  1109. ofs = hint - k;
  1110. }
  1111. a -= hint;
  1112. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1113. /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
  1114. * right of lastofs but no farther right than ofs. Do a binary
  1115. * search, with invariant a[lastofs-1] < key <= a[ofs].
  1116. */
  1117. ++lastofs;
  1118. while (lastofs < ofs) {
  1119. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1120. IFLT(a[m], key)
  1121. lastofs = m+1; /* a[m] < key */
  1122. else
  1123. ofs = m; /* key <= a[m] */
  1124. }
  1125. assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
  1126. return ofs;
  1127. fail:
  1128. return -1;
  1129. }
  1130. /*
  1131. Exactly like gallop_left(), except that if key already exists in a[0:n],
  1132. finds the position immediately to the right of the rightmost equal value.
  1133. The return value is the int k in 0..n such that
  1134. a[k-1] <= key < a[k]
  1135. or -1 if error.
  1136. The code duplication is massive, but this is enough different given that
  1137. we're sticking to "<" comparisons that it's much harder to follow if
  1138. written as one routine with yet another "left or right?" flag.
  1139. */
  1140. static Py_ssize_t
  1141. gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint)
  1142. {
  1143. Py_ssize_t ofs;
  1144. Py_ssize_t lastofs;
  1145. Py_ssize_t k;
  1146. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1147. a += hint;
  1148. lastofs = 0;
  1149. ofs = 1;
  1150. IFLT(key, *a) {
  1151. /* key < a[hint] -- gallop left, until
  1152. * a[hint - ofs] <= key < a[hint - lastofs]
  1153. */
  1154. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1155. while (ofs < maxofs) {
  1156. IFLT(key, *(a-ofs)) {
  1157. lastofs = ofs;
  1158. ofs = (ofs << 1) + 1;
  1159. if (ofs <= 0) /* int overflow */
  1160. ofs = maxofs;
  1161. }
  1162. else /* a[hint - ofs] <= key */
  1163. break;
  1164. }
  1165. if (ofs > maxofs)
  1166. ofs = maxofs;
  1167. /* Translate back to positive offsets relative to &a[0]. */
  1168. k = lastofs;
  1169. lastofs = hint - ofs;
  1170. ofs = hint - k;
  1171. }
  1172. else {
  1173. /* a[hint] <= key -- gallop right, until
  1174. * a[hint + lastofs] <= key < a[hint + ofs]
  1175. */
  1176. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1177. while (ofs < maxofs) {
  1178. IFLT(key, a[ofs])
  1179. break;
  1180. /* a[hint + ofs] <= key */
  1181. lastofs = ofs;
  1182. ofs = (ofs << 1) + 1;
  1183. if (ofs <= 0) /* int overflow */
  1184. ofs = maxofs;
  1185. }
  1186. if (ofs > maxofs)
  1187. ofs = maxofs;
  1188. /* Translate back to offsets relative to &a[0]. */
  1189. lastofs += hint;
  1190. ofs += hint;
  1191. }
  1192. a -= hint;
  1193. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1194. /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
  1195. * right of lastofs but no farther right than ofs. Do a binary
  1196. * search, with invariant a[lastofs-1] <= key < a[ofs].
  1197. */
  1198. ++lastofs;
  1199. while (lastofs < ofs) {
  1200. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1201. IFLT(key, a[m])
  1202. ofs = m; /* key < a[m] */
  1203. else
  1204. lastofs = m+1; /* a[m] <= key */
  1205. }
  1206. assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
  1207. return ofs;
  1208. fail:
  1209. return -1;
  1210. }
  1211. /* The maximum number of entries in a MergeState's pending-runs stack.
  1212. * This is enough to sort arrays of size up to about
  1213. * 32 * phi ** MAX_MERGE_PENDING
  1214. * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
  1215. * with 2**64 elements.
  1216. */
  1217. #define MAX_MERGE_PENDING 85
  1218. /* When we get into galloping mode, we stay there until both runs win less
  1219. * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
  1220. */
  1221. #define MIN_GALLOP 7
  1222. /* Avoid malloc for small temp arrays. */
  1223. #define MERGESTATE_TEMP_SIZE 256
  1224. /* One MergeState exists on the stack per invocation of mergesort. It's just
  1225. * a convenient way to pass state around among the helper functions.
  1226. */
  1227. struct s_slice {
  1228. sortslice base;
  1229. Py_ssize_t len;
  1230. };
  1231. typedef struct s_MergeState {
  1232. /* This controls when we get *into* galloping mode. It's initialized
  1233. * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
  1234. * random data, and lower for highly structured data.
  1235. */
  1236. Py_ssize_t min_gallop;
  1237. /* 'a' is temp storage to help with merges. It contains room for
  1238. * alloced entries.
  1239. */
  1240. sortslice a; /* may point to temparray below */
  1241. Py_ssize_t alloced;
  1242. /* A stack of n pending runs yet to be merged. Run #i starts at
  1243. * address base[i] and extends for len[i] elements. It's always
  1244. * true (so long as the indices are in bounds) that
  1245. *
  1246. * pending[i].base + pending[i].len == pending[i+1].base
  1247. *
  1248. * so we could cut the storage for this, but it's a minor amount,
  1249. * and keeping all the info explicit simplifies the code.
  1250. */
  1251. int n;
  1252. struct s_slice pending[MAX_MERGE_PENDING];
  1253. /* 'a' points to this when possible, rather than muck with malloc. */
  1254. PyObject *temparray[MERGESTATE_TEMP_SIZE];
  1255. } MergeState;
  1256. /* Conceptually a MergeState's constructor. */
  1257. static void
  1258. merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
  1259. {
  1260. assert(ms != NULL);
  1261. if (has_keyfunc) {
  1262. /* The temporary space for merging will need at most half the list
  1263. * size rounded up. Use the minimum possible space so we can use the
  1264. * rest of temparray for other things. In particular, if there is
  1265. * enough extra space, listsort() will use it to store the keys.
  1266. */
  1267. ms->alloced = (list_size + 1) / 2;
  1268. /* ms->alloced describes how many keys will be stored at
  1269. ms->temparray, but we also need to store the values. Hence,
  1270. ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
  1271. if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
  1272. ms->alloced = MERGESTATE_TEMP_SIZE / 2;
  1273. ms->a.values = &ms->temparray[ms->alloced];
  1274. }
  1275. else {
  1276. ms->alloced = MERGESTATE_TEMP_SIZE;
  1277. ms->a.values = NULL;
  1278. }
  1279. ms->a.keys = ms->temparray;
  1280. ms->n = 0;
  1281. ms->min_gallop = MIN_GALLOP;
  1282. }
  1283. /* Free all the temp memory owned by the MergeState. This must be called
  1284. * when you're done with a MergeState, and may be called before then if
  1285. * you want to free the temp memory early.
  1286. */
  1287. static void
  1288. merge_freemem(MergeState *ms)
  1289. {
  1290. assert(ms != NULL);
  1291. if (ms->a.keys != ms->temparray)
  1292. PyMem_Free(ms->a.keys);
  1293. }
  1294. /* Ensure enough temp memory for 'need' array slots is available.
  1295. * Returns 0 on success and -1 if the memory can't be gotten.
  1296. */
  1297. static int
  1298. merge_getmem(MergeState *ms, Py_ssize_t need)
  1299. {
  1300. int multiplier;
  1301. assert(ms != NULL);
  1302. if (need <= ms->alloced)
  1303. return 0;
  1304. multiplier = ms->a.values != NULL ? 2 : 1;
  1305. /* Don't realloc! That can cost cycles to copy the old data, but
  1306. * we don't care what's in the block.
  1307. */
  1308. merge_freemem(ms);
  1309. if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
  1310. PyErr_NoMemory();
  1311. return -1;
  1312. }
  1313. ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
  1314. * sizeof(PyObject *));
  1315. if (ms->a.keys != NULL) {
  1316. ms->alloced = need;
  1317. if (ms->a.values != NULL)
  1318. ms->a.values = &ms->a.keys[need];
  1319. return 0;
  1320. }
  1321. PyErr_NoMemory();
  1322. return -1;
  1323. }
  1324. #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
  1325. merge_getmem(MS, NEED))
  1326. /* Merge the na elements starting at ssa with the nb elements starting at
  1327. * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
  1328. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
  1329. * should have na <= nb. See listsort.txt for more info. Return 0 if
  1330. * successful, -1 if error.
  1331. */
  1332. static Py_ssize_t
  1333. merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
  1334. sortslice ssb, Py_ssize_t nb)
  1335. {
  1336. Py_ssize_t k;
  1337. sortslice dest;
  1338. int result = -1; /* guilty until proved innocent */
  1339. Py_ssize_t min_gallop;
  1340. assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
  1341. assert(ssa.keys + na == ssb.keys);
  1342. if (MERGE_GETMEM(ms, na) < 0)
  1343. return -1;
  1344. sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
  1345. dest = ssa;
  1346. ssa = ms->a;
  1347. sortslice_copy_incr(&dest, &ssb);
  1348. --nb;
  1349. if (nb == 0)
  1350. goto Succeed;
  1351. if (na == 1)
  1352. goto CopyB;
  1353. min_gallop = ms->min_gallop;
  1354. for (;;) {
  1355. Py_ssize_t acount = 0; /* # of times A won in a row */
  1356. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1357. /* Do the straightforward thing until (if ever) one run
  1358. * appears to win consistently.
  1359. */
  1360. for (;;) {
  1361. assert(na > 1 && nb > 0);
  1362. k = ISLT(ssb.keys[0], ssa.keys[0]);
  1363. if (k) {
  1364. if (k < 0)
  1365. goto Fail;
  1366. sortslice_copy_incr(&dest, &ssb);
  1367. ++bcount;
  1368. acount = 0;
  1369. --nb;
  1370. if (nb == 0)
  1371. goto Succeed;
  1372. if (bcount >= min_gallop)
  1373. break;
  1374. }
  1375. else {
  1376. sortslice_copy_incr(&dest, &ssa);
  1377. ++acount;
  1378. bcount = 0;
  1379. --na;
  1380. if (na == 1)
  1381. goto CopyB;
  1382. if (acount >= min_gallop)
  1383. break;
  1384. }
  1385. }
  1386. /* One run is winning so consistently that galloping may
  1387. * be a huge win. So try that, and continue galloping until
  1388. * (if ever) neither run appears to be winning consistently
  1389. * anymore.
  1390. */
  1391. ++min_gallop;
  1392. do {
  1393. assert(na > 1 && nb > 0);
  1394. min_gallop -= min_gallop > 1;
  1395. ms->min_gallop = min_gallop;
  1396. k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
  1397. acount = k;
  1398. if (k) {
  1399. if (k < 0)
  1400. goto Fail;
  1401. sortslice_memcpy(&dest, 0, &ssa, 0, k);
  1402. sortslice_advance(&dest, k);
  1403. sortslice_advance(&ssa, k);
  1404. na -= k;
  1405. if (na == 1)
  1406. goto CopyB;
  1407. /* na==0 is impossible now if the comparison
  1408. * function is consistent, but we can't assume
  1409. * that it is.
  1410. */
  1411. if (na == 0)
  1412. goto Succeed;
  1413. }
  1414. sortslice_copy_incr(&dest, &ssb);
  1415. --nb;
  1416. if (nb == 0)
  1417. goto Succeed;
  1418. k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
  1419. bcount = k;
  1420. if (k) {
  1421. if (k < 0)
  1422. goto Fail;
  1423. sortslice_memmove(&dest, 0, &ssb, 0, k);
  1424. sortslice_advance(&dest, k);
  1425. sortslice_advance(&ssb, k);
  1426. nb -= k;
  1427. if (nb == 0)
  1428. goto Succeed;
  1429. }
  1430. sortslice_copy_incr(&dest, &ssa);
  1431. --na;
  1432. if (na == 1)
  1433. goto CopyB;
  1434. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1435. ++min_gallop; /* penalize it for leaving galloping mode */
  1436. ms->min_gallop = min_gallop;
  1437. }
  1438. Succeed:
  1439. result = 0;
  1440. Fail:
  1441. if (na)
  1442. sortslice_memcpy(&dest, 0, &ssa, 0, na);
  1443. return result;
  1444. CopyB:
  1445. assert(na == 1 && nb > 0);
  1446. /* The last element of ssa belongs at the end of the merge. */
  1447. sortslice_memmove(&dest, 0, &ssb, 0, nb);
  1448. sortslice_copy(&dest, nb, &ssa, 0);
  1449. return 0;
  1450. }
  1451. /* Merge the na elements starting at pa with the nb elements starting at
  1452. * ssb.keys = ssa.keys + na in a stable way, in-place. na and nb must be > 0.
  1453. * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
  1454. * should have na >= nb. See listsort.txt for more info. Return 0 if
  1455. * successful, -1 if error.
  1456. */
  1457. static Py_ssize_t
  1458. merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
  1459. sortslice ssb, Py_ssize_t nb)
  1460. {
  1461. Py_ssize_t k;
  1462. sortslice dest, basea, baseb;
  1463. int result = -1; /* guilty until proved innocent */
  1464. Py_ssize_t min_gallop;
  1465. assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
  1466. assert(ssa.keys + na == ssb.keys);
  1467. if (MERGE_GETMEM(ms, nb) < 0)
  1468. return -1;
  1469. dest = ssb;
  1470. sortslice_advance(&dest, nb-1);
  1471. sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
  1472. basea = ssa;
  1473. baseb = ms->a;
  1474. ssb.keys = ms->a.keys + nb - 1;
  1475. if (ssb.values != NULL)
  1476. ssb.values = ms->a.values + nb - 1;
  1477. sortslice_advance(&ssa, na - 1);
  1478. sortslice_copy_decr(&dest, &ssa);
  1479. --na;
  1480. if (na == 0)
  1481. goto Succeed;
  1482. if (nb == 1)
  1483. goto CopyA;
  1484. min_gallop = ms->min_gallop;
  1485. for (;;) {
  1486. Py_ssize_t acount = 0; /* # of times A won in a row */
  1487. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1488. /* Do the straightforward thing until (if ever) one run
  1489. * appears to win consistently.
  1490. */
  1491. for (;;) {
  1492. assert(na > 0 && nb > 1);
  1493. k = ISLT(ssb.keys[0], ssa.keys[0]);
  1494. if (k) {
  1495. if (k < 0)
  1496. goto Fail;
  1497. sortslice_copy_decr(&dest, &ssa);
  1498. ++acount;
  1499. bcount = 0;
  1500. --na;
  1501. if (na == 0)
  1502. goto Succeed;
  1503. if (acount >= min_gallop)
  1504. break;
  1505. }
  1506. else {
  1507. sortslice_copy_decr(&dest, &ssb);
  1508. ++bcount;
  1509. acount = 0;
  1510. --nb;
  1511. if (nb == 1)
  1512. goto CopyA;
  1513. if (bcount >= min_gallop)
  1514. break;
  1515. }
  1516. }
  1517. /* One run is winning so consistently that galloping may
  1518. * be a huge win. So try that, and continue galloping until
  1519. * (if ever) neither run appears to be winning consistently
  1520. * anymore.
  1521. */
  1522. ++min_gallop;
  1523. do {
  1524. assert(na > 0 && nb > 1);
  1525. min_gallop -= min_gallop > 1;
  1526. ms->min_gallop = min_gallop;
  1527. k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
  1528. if (k < 0)
  1529. goto Fail;
  1530. k = na - k;
  1531. acount = k;
  1532. if (k) {
  1533. sortslice_advance(&dest, -k);
  1534. sortslice_advance(&ssa, -k);
  1535. sortslice_memmove(&dest, 1, &ssa, 1, k);
  1536. na -= k;
  1537. if (na == 0)
  1538. goto Succeed;
  1539. }
  1540. sortslice_copy_decr(&dest, &ssb);
  1541. --nb;
  1542. if (nb == 1)
  1543. goto CopyA;
  1544. k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
  1545. if (k < 0)
  1546. goto Fail;
  1547. k = nb - k;
  1548. bcount = k;
  1549. if (k) {
  1550. sortslice_advance(&dest, -k);
  1551. sortslice_advance(&ssb, -k);
  1552. sortslice_memcpy(&dest, 1, &ssb, 1, k);
  1553. nb -= k;
  1554. if (nb == 1)
  1555. goto CopyA;
  1556. /* nb==0 is impossible now if the comparison
  1557. * function is consistent, but we can't assume
  1558. * that it is.
  1559. */
  1560. if (nb == 0)
  1561. goto Succeed;
  1562. }
  1563. sortslice_copy_decr(&dest, &ssa);
  1564. --na;
  1565. if (na == 0)
  1566. goto Succeed;
  1567. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1568. ++min_gallop; /* penalize it for leaving galloping mode */
  1569. ms->min_gallop = min_gallop;
  1570. }
  1571. Succeed:
  1572. result = 0;
  1573. Fail:
  1574. if (nb)
  1575. sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
  1576. return result;
  1577. CopyA:
  1578. assert(nb == 1 && na > 0);
  1579. /* The first element of ssb belongs at the front of the merge. */
  1580. sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
  1581. sortslice_advance(&dest, -na);
  1582. sortslice_advance(&ssa, -na);
  1583. sortslice_copy(&dest, 0, &ssb, 0);
  1584. return 0;
  1585. }
  1586. /* Merge the two runs at stack indices i and i+1.
  1587. * Returns 0 on success, -1 on error.
  1588. */
  1589. static Py_ssize_t
  1590. merge_at(MergeState *ms, Py_ssize_t i)
  1591. {
  1592. sortslice ssa, ssb;
  1593. Py_ssize_t na, nb;
  1594. Py_ssize_t k;
  1595. assert(ms != NULL);
  1596. assert(ms->n >= 2);
  1597. assert(i >= 0);
  1598. assert(i == ms->n - 2 || i == ms->n - 3);
  1599. ssa = ms->pending[i].base;
  1600. na = ms->pending[i].len;
  1601. ssb = ms->pending[i+1].base;
  1602. nb = ms->pending[i+1].len;
  1603. assert(na > 0 && nb > 0);
  1604. assert(ssa.keys + na == ssb.keys);
  1605. /* Record the length of the combined runs; if i is the 3rd-last
  1606. * run now, also slide over the last run (which isn't involved
  1607. * in this merge). The current run i+1 goes away in any case.
  1608. */
  1609. ms->pending[i].len = na + nb;
  1610. if (i == ms->n - 3)
  1611. ms->pending[i+1] = ms->pending[i+2];
  1612. --ms->n;
  1613. /* Where does b start in a? Elements in a before that can be
  1614. * ignored (already in place).
  1615. */
  1616. k = gallo

Large files files are truncated, but you can click here to view the full file