PageRenderTime 122ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

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

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