PageRenderTime 80ms CodeModel.GetById 39ms RepoModel.GetById 1ms app.codeStats 1ms

/Objects/listobject.c

https://bitbucket.org/python_mirrors/sandbox-tkdoc
C | 2965 lines | 2308 code | 275 blank | 382 comment | 610 complexity | c6bef17fff584e38e3ed070440443f00 MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause

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

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

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