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

/External/Python/Objects/listobject.c

https://bitbucket.org/gongminmin/klayge/
C | 2336 lines | 1768 code | 202 blank | 366 comment | 528 complexity | 5e6166e38d2d11508f16b9261f1ae0a5 MD5 | raw file
Possible License(s): LGPL-2.1, Unlicense, GPL-2.0, BSD-3-Clause, MIT

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

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