PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

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

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