PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/Objects/listobject.c

https://bitbucket.org/mirror/python-trunk/
C | 3017 lines | 2351 code | 275 blank | 391 comment | 582 complexity | cab64ed5783d7a12af7f1c23af9cf228 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. nbytes = size * sizeof(PyObject *);
  116. /* Check for overflow without an actual overflow,
  117. * which can cause compiler to optimise out */
  118. if (size > PY_SIZE_MAX / sizeof(PyObject *))
  119. return PyErr_NoMemory();
  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. rc = Py_ReprEnter((PyObject*)op);
  293. if (rc != 0) {
  294. if (rc < 0)
  295. return rc;
  296. Py_BEGIN_ALLOW_THREADS
  297. fprintf(fp, "[...]");
  298. Py_END_ALLOW_THREADS
  299. return 0;
  300. }
  301. Py_BEGIN_ALLOW_THREADS
  302. fprintf(fp, "[");
  303. Py_END_ALLOW_THREADS
  304. for (i = 0; i < Py_SIZE(op); i++) {
  305. if (i > 0) {
  306. Py_BEGIN_ALLOW_THREADS
  307. fprintf(fp, ", ");
  308. Py_END_ALLOW_THREADS
  309. }
  310. if (PyObject_Print(op->ob_item[i], fp, 0) != 0) {
  311. Py_ReprLeave((PyObject *)op);
  312. return -1;
  313. }
  314. }
  315. Py_BEGIN_ALLOW_THREADS
  316. fprintf(fp, "]");
  317. Py_END_ALLOW_THREADS
  318. Py_ReprLeave((PyObject *)op);
  319. return 0;
  320. }
  321. static PyObject *
  322. list_repr(PyListObject *v)
  323. {
  324. Py_ssize_t i;
  325. PyObject *s, *temp;
  326. PyObject *pieces = NULL, *result = NULL;
  327. i = Py_ReprEnter((PyObject*)v);
  328. if (i != 0) {
  329. return i > 0 ? PyString_FromString("[...]") : NULL;
  330. }
  331. if (Py_SIZE(v) == 0) {
  332. result = PyString_FromString("[]");
  333. goto Done;
  334. }
  335. pieces = PyList_New(0);
  336. if (pieces == NULL)
  337. goto Done;
  338. /* Do repr() on each element. Note that this may mutate the list,
  339. so must refetch the list size on each iteration. */
  340. for (i = 0; i < Py_SIZE(v); ++i) {
  341. int status;
  342. if (Py_EnterRecursiveCall(" while getting the repr of a list"))
  343. goto Done;
  344. s = PyObject_Repr(v->ob_item[i]);
  345. Py_LeaveRecursiveCall();
  346. if (s == NULL)
  347. goto Done;
  348. status = PyList_Append(pieces, s);
  349. Py_DECREF(s); /* append created a new ref */
  350. if (status < 0)
  351. goto Done;
  352. }
  353. /* Add "[]" decorations to the first and last items. */
  354. assert(PyList_GET_SIZE(pieces) > 0);
  355. s = PyString_FromString("[");
  356. if (s == NULL)
  357. goto Done;
  358. temp = PyList_GET_ITEM(pieces, 0);
  359. PyString_ConcatAndDel(&s, temp);
  360. PyList_SET_ITEM(pieces, 0, s);
  361. if (s == NULL)
  362. goto Done;
  363. s = PyString_FromString("]");
  364. if (s == NULL)
  365. goto Done;
  366. temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
  367. PyString_ConcatAndDel(&temp, s);
  368. PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
  369. if (temp == NULL)
  370. goto Done;
  371. /* Paste them all together with ", " between. */
  372. s = PyString_FromString(", ");
  373. if (s == NULL)
  374. goto Done;
  375. result = _PyString_Join(s, pieces);
  376. Py_DECREF(s);
  377. Done:
  378. Py_XDECREF(pieces);
  379. Py_ReprLeave((PyObject *)v);
  380. return result;
  381. }
  382. static Py_ssize_t
  383. list_length(PyListObject *a)
  384. {
  385. return Py_SIZE(a);
  386. }
  387. static int
  388. list_contains(PyListObject *a, PyObject *el)
  389. {
  390. Py_ssize_t i;
  391. int cmp;
  392. for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
  393. cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
  394. Py_EQ);
  395. return cmp;
  396. }
  397. static PyObject *
  398. list_item(PyListObject *a, Py_ssize_t i)
  399. {
  400. if (i < 0 || i >= Py_SIZE(a)) {
  401. if (indexerr == NULL)
  402. indexerr = PyString_FromString(
  403. "list index out of range");
  404. PyErr_SetObject(PyExc_IndexError, indexerr);
  405. return NULL;
  406. }
  407. Py_INCREF(a->ob_item[i]);
  408. return a->ob_item[i];
  409. }
  410. static PyObject *
  411. list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  412. {
  413. PyListObject *np;
  414. PyObject **src, **dest;
  415. Py_ssize_t i, len;
  416. if (ilow < 0)
  417. ilow = 0;
  418. else if (ilow > Py_SIZE(a))
  419. ilow = Py_SIZE(a);
  420. if (ihigh < ilow)
  421. ihigh = ilow;
  422. else if (ihigh > Py_SIZE(a))
  423. ihigh = Py_SIZE(a);
  424. len = ihigh - ilow;
  425. np = (PyListObject *) PyList_New(len);
  426. if (np == NULL)
  427. return NULL;
  428. src = a->ob_item + ilow;
  429. dest = np->ob_item;
  430. for (i = 0; i < len; i++) {
  431. PyObject *v = src[i];
  432. Py_INCREF(v);
  433. dest[i] = v;
  434. }
  435. return (PyObject *)np;
  436. }
  437. PyObject *
  438. PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
  439. {
  440. if (!PyList_Check(a)) {
  441. PyErr_BadInternalCall();
  442. return NULL;
  443. }
  444. return list_slice((PyListObject *)a, ilow, ihigh);
  445. }
  446. static PyObject *
  447. list_concat(PyListObject *a, PyObject *bb)
  448. {
  449. Py_ssize_t size;
  450. Py_ssize_t i;
  451. PyObject **src, **dest;
  452. PyListObject *np;
  453. if (!PyList_Check(bb)) {
  454. PyErr_Format(PyExc_TypeError,
  455. "can only concatenate list (not \"%.200s\") to list",
  456. bb->ob_type->tp_name);
  457. return NULL;
  458. }
  459. #define b ((PyListObject *)bb)
  460. size = Py_SIZE(a) + Py_SIZE(b);
  461. if (size < 0)
  462. return PyErr_NoMemory();
  463. np = (PyListObject *) PyList_New(size);
  464. if (np == NULL) {
  465. return NULL;
  466. }
  467. src = a->ob_item;
  468. dest = np->ob_item;
  469. for (i = 0; i < Py_SIZE(a); i++) {
  470. PyObject *v = src[i];
  471. Py_INCREF(v);
  472. dest[i] = v;
  473. }
  474. src = b->ob_item;
  475. dest = np->ob_item + Py_SIZE(a);
  476. for (i = 0; i < Py_SIZE(b); i++) {
  477. PyObject *v = src[i];
  478. Py_INCREF(v);
  479. dest[i] = v;
  480. }
  481. return (PyObject *)np;
  482. #undef b
  483. }
  484. static PyObject *
  485. list_repeat(PyListObject *a, Py_ssize_t n)
  486. {
  487. Py_ssize_t i, j;
  488. Py_ssize_t size;
  489. PyListObject *np;
  490. PyObject **p, **items;
  491. PyObject *elem;
  492. if (n < 0)
  493. n = 0;
  494. size = Py_SIZE(a) * n;
  495. if (n && size/n != Py_SIZE(a))
  496. return PyErr_NoMemory();
  497. if (size == 0)
  498. return PyList_New(0);
  499. np = (PyListObject *) PyList_New(size);
  500. if (np == NULL)
  501. return NULL;
  502. items = np->ob_item;
  503. if (Py_SIZE(a) == 1) {
  504. elem = a->ob_item[0];
  505. for (i = 0; i < n; i++) {
  506. items[i] = elem;
  507. Py_INCREF(elem);
  508. }
  509. return (PyObject *) np;
  510. }
  511. p = np->ob_item;
  512. items = a->ob_item;
  513. for (i = 0; i < n; i++) {
  514. for (j = 0; j < Py_SIZE(a); j++) {
  515. *p = items[j];
  516. Py_INCREF(*p);
  517. p++;
  518. }
  519. }
  520. return (PyObject *) np;
  521. }
  522. static int
  523. list_clear(PyListObject *a)
  524. {
  525. Py_ssize_t i;
  526. PyObject **item = a->ob_item;
  527. if (item != NULL) {
  528. /* Because XDECREF can recursively invoke operations on
  529. this list, we make it empty first. */
  530. i = Py_SIZE(a);
  531. Py_SIZE(a) = 0;
  532. a->ob_item = NULL;
  533. a->allocated = 0;
  534. while (--i >= 0) {
  535. Py_XDECREF(item[i]);
  536. }
  537. PyMem_FREE(item);
  538. }
  539. /* Never fails; the return value can be ignored.
  540. Note that there is no guarantee that the list is actually empty
  541. at this point, because XDECREF may have populated it again! */
  542. return 0;
  543. }
  544. /* a[ilow:ihigh] = v if v != NULL.
  545. * del a[ilow:ihigh] if v == NULL.
  546. *
  547. * Special speed gimmick: when v is NULL and ihigh - ilow <= 8, it's
  548. * guaranteed the call cannot fail.
  549. */
  550. static int
  551. list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  552. {
  553. /* Because [X]DECREF can recursively invoke list operations on
  554. this list, we must postpone all [X]DECREF activity until
  555. after the list is back in its canonical shape. Therefore
  556. we must allocate an additional array, 'recycle', into which
  557. we temporarily copy the items that are deleted from the
  558. list. :-( */
  559. PyObject *recycle_on_stack[8];
  560. PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
  561. PyObject **item;
  562. PyObject **vitem = NULL;
  563. PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
  564. Py_ssize_t n; /* # of elements in replacement list */
  565. Py_ssize_t norig; /* # of elements in list getting replaced */
  566. Py_ssize_t d; /* Change in size */
  567. Py_ssize_t k;
  568. size_t s;
  569. int result = -1; /* guilty until proved innocent */
  570. #define b ((PyListObject *)v)
  571. if (v == NULL)
  572. n = 0;
  573. else {
  574. if (a == b) {
  575. /* Special case "a[i:j] = a" -- copy b first */
  576. v = list_slice(b, 0, Py_SIZE(b));
  577. if (v == NULL)
  578. return result;
  579. result = list_ass_slice(a, ilow, ihigh, v);
  580. Py_DECREF(v);
  581. return result;
  582. }
  583. v_as_SF = PySequence_Fast(v, "can only assign an iterable");
  584. if(v_as_SF == NULL)
  585. goto Error;
  586. n = PySequence_Fast_GET_SIZE(v_as_SF);
  587. vitem = PySequence_Fast_ITEMS(v_as_SF);
  588. }
  589. if (ilow < 0)
  590. ilow = 0;
  591. else if (ilow > Py_SIZE(a))
  592. ilow = Py_SIZE(a);
  593. if (ihigh < ilow)
  594. ihigh = ilow;
  595. else if (ihigh > Py_SIZE(a))
  596. ihigh = Py_SIZE(a);
  597. norig = ihigh - ilow;
  598. assert(norig >= 0);
  599. d = n - norig;
  600. if (Py_SIZE(a) + d == 0) {
  601. Py_XDECREF(v_as_SF);
  602. return list_clear(a);
  603. }
  604. item = a->ob_item;
  605. /* recycle the items that we are about to remove */
  606. s = norig * sizeof(PyObject *);
  607. if (s > sizeof(recycle_on_stack)) {
  608. recycle = (PyObject **)PyMem_MALLOC(s);
  609. if (recycle == NULL) {
  610. PyErr_NoMemory();
  611. goto Error;
  612. }
  613. }
  614. memcpy(recycle, &item[ilow], s);
  615. if (d < 0) { /* Delete -d items */
  616. memmove(&item[ihigh+d], &item[ihigh],
  617. (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
  618. list_resize(a, Py_SIZE(a) + d);
  619. item = a->ob_item;
  620. }
  621. else if (d > 0) { /* Insert d items */
  622. k = Py_SIZE(a);
  623. if (list_resize(a, k+d) < 0)
  624. goto Error;
  625. item = a->ob_item;
  626. memmove(&item[ihigh+d], &item[ihigh],
  627. (k - ihigh)*sizeof(PyObject *));
  628. }
  629. for (k = 0; k < n; k++, ilow++) {
  630. PyObject *w = vitem[k];
  631. Py_XINCREF(w);
  632. item[ilow] = w;
  633. }
  634. for (k = norig - 1; k >= 0; --k)
  635. Py_XDECREF(recycle[k]);
  636. result = 0;
  637. Error:
  638. if (recycle != recycle_on_stack)
  639. PyMem_FREE(recycle);
  640. Py_XDECREF(v_as_SF);
  641. return result;
  642. #undef b
  643. }
  644. int
  645. PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
  646. {
  647. if (!PyList_Check(a)) {
  648. PyErr_BadInternalCall();
  649. return -1;
  650. }
  651. return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
  652. }
  653. static PyObject *
  654. list_inplace_repeat(PyListObject *self, Py_ssize_t n)
  655. {
  656. PyObject **items;
  657. Py_ssize_t size, i, j, p;
  658. size = PyList_GET_SIZE(self);
  659. if (size == 0 || n == 1) {
  660. Py_INCREF(self);
  661. return (PyObject *)self;
  662. }
  663. if (n < 1) {
  664. (void)list_clear(self);
  665. Py_INCREF(self);
  666. return (PyObject *)self;
  667. }
  668. if (size > PY_SSIZE_T_MAX / n) {
  669. return PyErr_NoMemory();
  670. }
  671. if (list_resize(self, size*n) == -1)
  672. return NULL;
  673. p = size;
  674. items = self->ob_item;
  675. for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
  676. for (j = 0; j < size; j++) {
  677. PyObject *o = items[j];
  678. Py_INCREF(o);
  679. items[p++] = o;
  680. }
  681. }
  682. Py_INCREF(self);
  683. return (PyObject *)self;
  684. }
  685. static int
  686. list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
  687. {
  688. PyObject *old_value;
  689. if (i < 0 || i >= Py_SIZE(a)) {
  690. PyErr_SetString(PyExc_IndexError,
  691. "list assignment index out of range");
  692. return -1;
  693. }
  694. if (v == NULL)
  695. return list_ass_slice(a, i, i+1, v);
  696. Py_INCREF(v);
  697. old_value = a->ob_item[i];
  698. a->ob_item[i] = v;
  699. Py_DECREF(old_value);
  700. return 0;
  701. }
  702. static PyObject *
  703. listinsert(PyListObject *self, PyObject *args)
  704. {
  705. Py_ssize_t i;
  706. PyObject *v;
  707. if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
  708. return NULL;
  709. if (ins1(self, i, v) == 0)
  710. Py_RETURN_NONE;
  711. return NULL;
  712. }
  713. static PyObject *
  714. listappend(PyListObject *self, PyObject *v)
  715. {
  716. if (app1(self, v) == 0)
  717. Py_RETURN_NONE;
  718. return NULL;
  719. }
  720. static PyObject *
  721. listextend(PyListObject *self, PyObject *b)
  722. {
  723. PyObject *it; /* iter(v) */
  724. Py_ssize_t m; /* size of self */
  725. Py_ssize_t n; /* guess for size of b */
  726. Py_ssize_t mn; /* m + n */
  727. Py_ssize_t i;
  728. PyObject *(*iternext)(PyObject *);
  729. /* Special cases:
  730. 1) lists and tuples which can use PySequence_Fast ops
  731. 2) extending self to self requires making a copy first
  732. */
  733. if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
  734. PyObject **src, **dest;
  735. b = PySequence_Fast(b, "argument must be iterable");
  736. if (!b)
  737. return NULL;
  738. n = PySequence_Fast_GET_SIZE(b);
  739. if (n == 0) {
  740. /* short circuit when b is empty */
  741. Py_DECREF(b);
  742. Py_RETURN_NONE;
  743. }
  744. m = Py_SIZE(self);
  745. if (list_resize(self, m + n) == -1) {
  746. Py_DECREF(b);
  747. return NULL;
  748. }
  749. /* note that we may still have self == b here for the
  750. * situation a.extend(a), but the following code works
  751. * in that case too. Just make sure to resize self
  752. * before calling PySequence_Fast_ITEMS.
  753. */
  754. /* populate the end of self with b's items */
  755. src = PySequence_Fast_ITEMS(b);
  756. dest = self->ob_item + m;
  757. for (i = 0; i < n; i++) {
  758. PyObject *o = src[i];
  759. Py_INCREF(o);
  760. dest[i] = o;
  761. }
  762. Py_DECREF(b);
  763. Py_RETURN_NONE;
  764. }
  765. it = PyObject_GetIter(b);
  766. if (it == NULL)
  767. return NULL;
  768. iternext = *it->ob_type->tp_iternext;
  769. /* Guess a result list size. */
  770. n = _PyObject_LengthHint(b, 8);
  771. if (n == -1) {
  772. Py_DECREF(it);
  773. return NULL;
  774. }
  775. m = Py_SIZE(self);
  776. mn = m + n;
  777. if (mn >= m) {
  778. /* Make room. */
  779. if (list_resize(self, mn) == -1)
  780. goto error;
  781. /* Make the list sane again. */
  782. Py_SIZE(self) = m;
  783. }
  784. /* Else m + n overflowed; on the chance that n lied, and there really
  785. * is enough room, ignore it. If n was telling the truth, we'll
  786. * eventually run out of memory during the loop.
  787. */
  788. /* Run iterator to exhaustion. */
  789. for (;;) {
  790. PyObject *item = iternext(it);
  791. if (item == NULL) {
  792. if (PyErr_Occurred()) {
  793. if (PyErr_ExceptionMatches(PyExc_StopIteration))
  794. PyErr_Clear();
  795. else
  796. goto error;
  797. }
  798. break;
  799. }
  800. if (Py_SIZE(self) < self->allocated) {
  801. /* steals ref */
  802. PyList_SET_ITEM(self, Py_SIZE(self), item);
  803. ++Py_SIZE(self);
  804. }
  805. else {
  806. int status = app1(self, item);
  807. Py_DECREF(item); /* append creates a new ref */
  808. if (status < 0)
  809. goto error;
  810. }
  811. }
  812. /* Cut back result list if initial guess was too large. */
  813. if (Py_SIZE(self) < self->allocated)
  814. list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
  815. Py_DECREF(it);
  816. Py_RETURN_NONE;
  817. error:
  818. Py_DECREF(it);
  819. return NULL;
  820. }
  821. PyObject *
  822. _PyList_Extend(PyListObject *self, PyObject *b)
  823. {
  824. return listextend(self, b);
  825. }
  826. static PyObject *
  827. list_inplace_concat(PyListObject *self, PyObject *other)
  828. {
  829. PyObject *result;
  830. result = listextend(self, other);
  831. if (result == NULL)
  832. return result;
  833. Py_DECREF(result);
  834. Py_INCREF(self);
  835. return (PyObject *)self;
  836. }
  837. static PyObject *
  838. listpop(PyListObject *self, PyObject *args)
  839. {
  840. Py_ssize_t i = -1;
  841. PyObject *v;
  842. int status;
  843. if (!PyArg_ParseTuple(args, "|n:pop", &i))
  844. return NULL;
  845. if (Py_SIZE(self) == 0) {
  846. /* Special-case most common failure cause */
  847. PyErr_SetString(PyExc_IndexError, "pop from empty list");
  848. return NULL;
  849. }
  850. if (i < 0)
  851. i += Py_SIZE(self);
  852. if (i < 0 || i >= Py_SIZE(self)) {
  853. PyErr_SetString(PyExc_IndexError, "pop index out of range");
  854. return NULL;
  855. }
  856. v = self->ob_item[i];
  857. if (i == Py_SIZE(self) - 1) {
  858. status = list_resize(self, Py_SIZE(self) - 1);
  859. assert(status >= 0);
  860. return v; /* and v now owns the reference the list had */
  861. }
  862. Py_INCREF(v);
  863. status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
  864. assert(status >= 0);
  865. /* Use status, so that in a release build compilers don't
  866. * complain about the unused name.
  867. */
  868. (void) status;
  869. return v;
  870. }
  871. /* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
  872. static void
  873. reverse_slice(PyObject **lo, PyObject **hi)
  874. {
  875. assert(lo && hi);
  876. --hi;
  877. while (lo < hi) {
  878. PyObject *t = *lo;
  879. *lo = *hi;
  880. *hi = t;
  881. ++lo;
  882. --hi;
  883. }
  884. }
  885. /* Lots of code for an adaptive, stable, natural mergesort. There are many
  886. * pieces to this algorithm; read listsort.txt for overviews and details.
  887. */
  888. /* Comparison function. Takes care of calling a user-supplied
  889. * comparison function (any callable Python object), which must not be
  890. * NULL (use the ISLT macro if you don't know, or call PyObject_RichCompareBool
  891. * with Py_LT if you know it's NULL).
  892. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  893. */
  894. static int
  895. islt(PyObject *x, PyObject *y, PyObject *compare)
  896. {
  897. PyObject *res;
  898. PyObject *args;
  899. Py_ssize_t i;
  900. assert(compare != NULL);
  901. /* Call the user's comparison function and translate the 3-way
  902. * result into true or false (or error).
  903. */
  904. args = PyTuple_New(2);
  905. if (args == NULL)
  906. return -1;
  907. Py_INCREF(x);
  908. Py_INCREF(y);
  909. PyTuple_SET_ITEM(args, 0, x);
  910. PyTuple_SET_ITEM(args, 1, y);
  911. res = PyObject_Call(compare, args, NULL);
  912. Py_DECREF(args);
  913. if (res == NULL)
  914. return -1;
  915. if (!PyInt_Check(res)) {
  916. PyErr_Format(PyExc_TypeError,
  917. "comparison function must return int, not %.200s",
  918. res->ob_type->tp_name);
  919. Py_DECREF(res);
  920. return -1;
  921. }
  922. i = PyInt_AsLong(res);
  923. Py_DECREF(res);
  924. return i < 0;
  925. }
  926. /* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
  927. * islt. This avoids a layer of function call in the usual case, and
  928. * sorting does many comparisons.
  929. * Returns -1 on error, 1 if x < y, 0 if x >= y.
  930. */
  931. #define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
  932. PyObject_RichCompareBool(X, Y, Py_LT) : \
  933. islt(X, Y, COMPARE))
  934. /* Compare X to Y via "<". Goto "fail" if the comparison raises an
  935. error. Else "k" is set to true iff X<Y, and an "if (k)" block is
  936. started. It makes more sense in context <wink>. X and Y are PyObject*s.
  937. */
  938. #define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
  939. if (k)
  940. /* binarysort is the best method for sorting small arrays: it does
  941. few compares, but can do data movement quadratic in the number of
  942. elements.
  943. [lo, hi) is a contiguous slice of a list, and is sorted via
  944. binary insertion. This sort is stable.
  945. On entry, must have lo <= start <= hi, and that [lo, start) is already
  946. sorted (pass start == lo if you don't know!).
  947. If islt() complains return -1, else 0.
  948. Even in case of error, the output slice will be some permutation of
  949. the input (nothing is lost or duplicated).
  950. */
  951. static int
  952. binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
  953. /* compare -- comparison function object, or NULL for default */
  954. {
  955. register Py_ssize_t k;
  956. register PyObject **l, **p, **r;
  957. register PyObject *pivot;
  958. assert(lo <= start && start <= hi);
  959. /* assert [lo, start) is sorted */
  960. if (lo == start)
  961. ++start;
  962. for (; start < hi; ++start) {
  963. /* set l to where *start belongs */
  964. l = lo;
  965. r = start;
  966. pivot = *r;
  967. /* Invariants:
  968. * pivot >= all in [lo, l).
  969. * pivot < all in [r, start).
  970. * The second is vacuously true at the start.
  971. */
  972. assert(l < r);
  973. do {
  974. p = l + ((r - l) >> 1);
  975. IFLT(pivot, *p)
  976. r = p;
  977. else
  978. l = p+1;
  979. } while (l < r);
  980. assert(l == r);
  981. /* The invariants still hold, so pivot >= all in [lo, l) and
  982. pivot < all in [l, start), so pivot belongs at l. Note
  983. that if there are elements equal to pivot, l points to the
  984. first slot after them -- that's why this sort is stable.
  985. Slide over to make room.
  986. Caution: using memmove is much slower under MSVC 5;
  987. we're not usually moving many slots. */
  988. for (p = start; p > l; --p)
  989. *p = *(p-1);
  990. *l = pivot;
  991. }
  992. return 0;
  993. fail:
  994. return -1;
  995. }
  996. /*
  997. Return the length of the run beginning at lo, in the slice [lo, hi). lo < hi
  998. is required on entry. "A run" is the longest ascending sequence, with
  999. lo[0] <= lo[1] <= lo[2] <= ...
  1000. or the longest descending sequence, with
  1001. lo[0] > lo[1] > lo[2] > ...
  1002. Boolean *descending is set to 0 in the former case, or to 1 in the latter.
  1003. For its intended use in a stable mergesort, the strictness of the defn of
  1004. "descending" is needed so that the caller can safely reverse a descending
  1005. sequence without violating stability (strict > ensures there are no equal
  1006. elements to get out of order).
  1007. Returns -1 in case of error.
  1008. */
  1009. static Py_ssize_t
  1010. count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
  1011. {
  1012. Py_ssize_t k;
  1013. Py_ssize_t n;
  1014. assert(lo < hi);
  1015. *descending = 0;
  1016. ++lo;
  1017. if (lo == hi)
  1018. return 1;
  1019. n = 2;
  1020. IFLT(*lo, *(lo-1)) {
  1021. *descending = 1;
  1022. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1023. IFLT(*lo, *(lo-1))
  1024. ;
  1025. else
  1026. break;
  1027. }
  1028. }
  1029. else {
  1030. for (lo = lo+1; lo < hi; ++lo, ++n) {
  1031. IFLT(*lo, *(lo-1))
  1032. break;
  1033. }
  1034. }
  1035. return n;
  1036. fail:
  1037. return -1;
  1038. }
  1039. /*
  1040. Locate the proper position of key in a sorted vector; if the vector contains
  1041. an element equal to key, return the position immediately to the left of
  1042. the leftmost equal element. [gallop_right() does the same except returns
  1043. the position to the right of the rightmost equal element (if any).]
  1044. "a" is a sorted vector with n elements, starting at a[0]. n must be > 0.
  1045. "hint" is an index at which to begin the search, 0 <= hint < n. The closer
  1046. hint is to the final result, the faster this runs.
  1047. The return value is the int k in 0..n such that
  1048. a[k-1] < key <= a[k]
  1049. pretending that *(a-1) is minus infinity and a[n] is plus infinity. IOW,
  1050. key belongs at index k; or, IOW, the first k elements of a should precede
  1051. key, and the last n-k should follow key.
  1052. Returns -1 on error. See listsort.txt for info on the method.
  1053. */
  1054. static Py_ssize_t
  1055. gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
  1056. {
  1057. Py_ssize_t ofs;
  1058. Py_ssize_t lastofs;
  1059. Py_ssize_t k;
  1060. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1061. a += hint;
  1062. lastofs = 0;
  1063. ofs = 1;
  1064. IFLT(*a, key) {
  1065. /* a[hint] < key -- gallop right, until
  1066. * a[hint + lastofs] < key <= a[hint + ofs]
  1067. */
  1068. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1069. while (ofs < maxofs) {
  1070. IFLT(a[ofs], key) {
  1071. lastofs = ofs;
  1072. ofs = (ofs << 1) + 1;
  1073. if (ofs <= 0) /* int overflow */
  1074. ofs = maxofs;
  1075. }
  1076. else /* key <= a[hint + ofs] */
  1077. break;
  1078. }
  1079. if (ofs > maxofs)
  1080. ofs = maxofs;
  1081. /* Translate back to offsets relative to &a[0]. */
  1082. lastofs += hint;
  1083. ofs += hint;
  1084. }
  1085. else {
  1086. /* key <= a[hint] -- gallop left, until
  1087. * a[hint - ofs] < key <= a[hint - lastofs]
  1088. */
  1089. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1090. while (ofs < maxofs) {
  1091. IFLT(*(a-ofs), key)
  1092. break;
  1093. /* key <= a[hint - ofs] */
  1094. lastofs = ofs;
  1095. ofs = (ofs << 1) + 1;
  1096. if (ofs <= 0) /* int overflow */
  1097. ofs = maxofs;
  1098. }
  1099. if (ofs > maxofs)
  1100. ofs = maxofs;
  1101. /* Translate back to positive offsets relative to &a[0]. */
  1102. k = lastofs;
  1103. lastofs = hint - ofs;
  1104. ofs = hint - k;
  1105. }
  1106. a -= hint;
  1107. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1108. /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
  1109. * right of lastofs but no farther right than ofs. Do a binary
  1110. * search, with invariant a[lastofs-1] < key <= a[ofs].
  1111. */
  1112. ++lastofs;
  1113. while (lastofs < ofs) {
  1114. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1115. IFLT(a[m], key)
  1116. lastofs = m+1; /* a[m] < key */
  1117. else
  1118. ofs = m; /* key <= a[m] */
  1119. }
  1120. assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
  1121. return ofs;
  1122. fail:
  1123. return -1;
  1124. }
  1125. /*
  1126. Exactly like gallop_left(), except that if key already exists in a[0:n],
  1127. finds the position immediately to the right of the rightmost equal value.
  1128. The return value is the int k in 0..n such that
  1129. a[k-1] <= key < a[k]
  1130. or -1 if error.
  1131. The code duplication is massive, but this is enough different given that
  1132. we're sticking to "<" comparisons that it's much harder to follow if
  1133. written as one routine with yet another "left or right?" flag.
  1134. */
  1135. static Py_ssize_t
  1136. gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
  1137. {
  1138. Py_ssize_t ofs;
  1139. Py_ssize_t lastofs;
  1140. Py_ssize_t k;
  1141. assert(key && a && n > 0 && hint >= 0 && hint < n);
  1142. a += hint;
  1143. lastofs = 0;
  1144. ofs = 1;
  1145. IFLT(key, *a) {
  1146. /* key < a[hint] -- gallop left, until
  1147. * a[hint - ofs] <= key < a[hint - lastofs]
  1148. */
  1149. const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
  1150. while (ofs < maxofs) {
  1151. IFLT(key, *(a-ofs)) {
  1152. lastofs = ofs;
  1153. ofs = (ofs << 1) + 1;
  1154. if (ofs <= 0) /* int overflow */
  1155. ofs = maxofs;
  1156. }
  1157. else /* a[hint - ofs] <= key */
  1158. break;
  1159. }
  1160. if (ofs > maxofs)
  1161. ofs = maxofs;
  1162. /* Translate back to positive offsets relative to &a[0]. */
  1163. k = lastofs;
  1164. lastofs = hint - ofs;
  1165. ofs = hint - k;
  1166. }
  1167. else {
  1168. /* a[hint] <= key -- gallop right, until
  1169. * a[hint + lastofs] <= key < a[hint + ofs]
  1170. */
  1171. const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
  1172. while (ofs < maxofs) {
  1173. IFLT(key, a[ofs])
  1174. break;
  1175. /* a[hint + ofs] <= key */
  1176. lastofs = ofs;
  1177. ofs = (ofs << 1) + 1;
  1178. if (ofs <= 0) /* int overflow */
  1179. ofs = maxofs;
  1180. }
  1181. if (ofs > maxofs)
  1182. ofs = maxofs;
  1183. /* Translate back to offsets relative to &a[0]. */
  1184. lastofs += hint;
  1185. ofs += hint;
  1186. }
  1187. a -= hint;
  1188. assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
  1189. /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
  1190. * right of lastofs but no farther right than ofs. Do a binary
  1191. * search, with invariant a[lastofs-1] <= key < a[ofs].
  1192. */
  1193. ++lastofs;
  1194. while (lastofs < ofs) {
  1195. Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
  1196. IFLT(key, a[m])
  1197. ofs = m; /* key < a[m] */
  1198. else
  1199. lastofs = m+1; /* a[m] <= key */
  1200. }
  1201. assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
  1202. return ofs;
  1203. fail:
  1204. return -1;
  1205. }
  1206. /* The maximum number of entries in a MergeState's pending-runs stack.
  1207. * This is enough to sort arrays of size up to about
  1208. * 32 * phi ** MAX_MERGE_PENDING
  1209. * where phi ~= 1.618. 85 is ridiculouslylarge enough, good for an array
  1210. * with 2**64 elements.
  1211. */
  1212. #define MAX_MERGE_PENDING 85
  1213. /* When we get into galloping mode, we stay there until both runs win less
  1214. * often than MIN_GALLOP consecutive times. See listsort.txt for more info.
  1215. */
  1216. #define MIN_GALLOP 7
  1217. /* Avoid malloc for small temp arrays. */
  1218. #define MERGESTATE_TEMP_SIZE 256
  1219. /* One MergeState exists on the stack per invocation of mergesort. It's just
  1220. * a convenient way to pass state around among the helper functions.
  1221. */
  1222. struct s_slice {
  1223. PyObject **base;
  1224. Py_ssize_t len;
  1225. };
  1226. typedef struct s_MergeState {
  1227. /* The user-supplied comparison function. or NULL if none given. */
  1228. PyObject *compare;
  1229. /* This controls when we get *into* galloping mode. It's initialized
  1230. * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
  1231. * random data, and lower for highly structured data.
  1232. */
  1233. Py_ssize_t min_gallop;
  1234. /* 'a' is temp storage to help with merges. It contains room for
  1235. * alloced entries.
  1236. */
  1237. PyObject **a; /* may point to temparray below */
  1238. Py_ssize_t alloced;
  1239. /* A stack of n pending runs yet to be merged. Run #i starts at
  1240. * address base[i] and extends for len[i] elements. It's always
  1241. * true (so long as the indices are in bounds) that
  1242. *
  1243. * pending[i].base + pending[i].len == pending[i+1].base
  1244. *
  1245. * so we could cut the storage for this, but it's a minor amount,
  1246. * and keeping all the info explicit simplifies the code.
  1247. */
  1248. int n;
  1249. struct s_slice pending[MAX_MERGE_PENDING];
  1250. /* 'a' points to this when possible, rather than muck with malloc. */
  1251. PyObject *temparray[MERGESTATE_TEMP_SIZE];
  1252. } MergeState;
  1253. /* Conceptually a MergeState's constructor. */
  1254. static void
  1255. merge_init(MergeState *ms, PyObject *compare)
  1256. {
  1257. assert(ms != NULL);
  1258. ms->compare = compare;
  1259. ms->a = ms->temparray;
  1260. ms->alloced = MERGESTATE_TEMP_SIZE;
  1261. ms->n = 0;
  1262. ms->min_gallop = MIN_GALLOP;
  1263. }
  1264. /* Free all the temp memory owned by the MergeState. This must be called
  1265. * when you're done with a MergeState, and may be called before then if
  1266. * you want to free the temp memory early.
  1267. */
  1268. static void
  1269. merge_freemem(MergeState *ms)
  1270. {
  1271. assert(ms != NULL);
  1272. if (ms->a != ms->temparray)
  1273. PyMem_Free(ms->a);
  1274. ms->a = ms->temparray;
  1275. ms->alloced = MERGESTATE_TEMP_SIZE;
  1276. }
  1277. /* Ensure enough temp memory for 'need' array slots is available.
  1278. * Returns 0 on success and -1 if the memory can't be gotten.
  1279. */
  1280. static int
  1281. merge_getmem(MergeState *ms, Py_ssize_t need)
  1282. {
  1283. assert(ms != NULL);
  1284. if (need <= ms->alloced)
  1285. return 0;
  1286. /* Don't realloc! That can cost cycles to copy the old data, but
  1287. * we don't care what's in the block.
  1288. */
  1289. merge_freemem(ms);
  1290. if (need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
  1291. PyErr_NoMemory();
  1292. return -1;
  1293. }
  1294. ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
  1295. if (ms->a) {
  1296. ms->alloced = need;
  1297. return 0;
  1298. }
  1299. PyErr_NoMemory();
  1300. merge_freemem(ms); /* reset to sane state */
  1301. return -1;
  1302. }
  1303. #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
  1304. merge_getmem(MS, NEED))
  1305. /* Merge the na elements starting at pa with the nb elements starting at pb
  1306. * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
  1307. * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
  1308. * merge, and should have na <= nb. See listsort.txt for more info.
  1309. * Return 0 if successful, -1 if error.
  1310. */
  1311. static Py_ssize_t
  1312. merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
  1313. PyObject **pb, Py_ssize_t nb)
  1314. {
  1315. Py_ssize_t k;
  1316. PyObject *compare;
  1317. PyObject **dest;
  1318. int result = -1; /* guilty until proved innocent */
  1319. Py_ssize_t min_gallop;
  1320. assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
  1321. if (MERGE_GETMEM(ms, na) < 0)
  1322. return -1;
  1323. memcpy(ms->a, pa, na * sizeof(PyObject*));
  1324. dest = pa;
  1325. pa = ms->a;
  1326. *dest++ = *pb++;
  1327. --nb;
  1328. if (nb == 0)
  1329. goto Succeed;
  1330. if (na == 1)
  1331. goto CopyB;
  1332. min_gallop = ms->min_gallop;
  1333. compare = ms->compare;
  1334. for (;;) {
  1335. Py_ssize_t acount = 0; /* # of times A won in a row */
  1336. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1337. /* Do the straightforward thing until (if ever) one run
  1338. * appears to win consistently.
  1339. */
  1340. for (;;) {
  1341. assert(na > 1 && nb > 0);
  1342. k = ISLT(*pb, *pa, compare);
  1343. if (k) {
  1344. if (k < 0)
  1345. goto Fail;
  1346. *dest++ = *pb++;
  1347. ++bcount;
  1348. acount = 0;
  1349. --nb;
  1350. if (nb == 0)
  1351. goto Succeed;
  1352. if (bcount >= min_gallop)
  1353. break;
  1354. }
  1355. else {
  1356. *dest++ = *pa++;
  1357. ++acount;
  1358. bcount = 0;
  1359. --na;
  1360. if (na == 1)
  1361. goto CopyB;
  1362. if (acount >= min_gallop)
  1363. break;
  1364. }
  1365. }
  1366. /* One run is winning so consistently that galloping may
  1367. * be a huge win. So try that, and continue galloping until
  1368. * (if ever) neither run appears to be winning consistently
  1369. * anymore.
  1370. */
  1371. ++min_gallop;
  1372. do {
  1373. assert(na > 1 && nb > 0);
  1374. min_gallop -= min_gallop > 1;
  1375. ms->min_gallop = min_gallop;
  1376. k = gallop_right(*pb, pa, na, 0, compare);
  1377. acount = k;
  1378. if (k) {
  1379. if (k < 0)
  1380. goto Fail;
  1381. memcpy(dest, pa, k * sizeof(PyObject *));
  1382. dest += k;
  1383. pa += k;
  1384. na -= k;
  1385. if (na == 1)
  1386. goto CopyB;
  1387. /* na==0 is impossible now if the comparison
  1388. * function is consistent, but we can't assume
  1389. * that it is.
  1390. */
  1391. if (na == 0)
  1392. goto Succeed;
  1393. }
  1394. *dest++ = *pb++;
  1395. --nb;
  1396. if (nb == 0)
  1397. goto Succeed;
  1398. k = gallop_left(*pa, pb, nb, 0, compare);
  1399. bcount = k;
  1400. if (k) {
  1401. if (k < 0)
  1402. goto Fail;
  1403. memmove(dest, pb, k * sizeof(PyObject *));
  1404. dest += k;
  1405. pb += k;
  1406. nb -= k;
  1407. if (nb == 0)
  1408. goto Succeed;
  1409. }
  1410. *dest++ = *pa++;
  1411. --na;
  1412. if (na == 1)
  1413. goto CopyB;
  1414. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1415. ++min_gallop; /* penalize it for leaving galloping mode */
  1416. ms->min_gallop = min_gallop;
  1417. }
  1418. Succeed:
  1419. result = 0;
  1420. Fail:
  1421. if (na)
  1422. memcpy(dest, pa, na * sizeof(PyObject*));
  1423. return result;
  1424. CopyB:
  1425. assert(na == 1 && nb > 0);
  1426. /* The last element of pa belongs at the end of the merge. */
  1427. memmove(dest, pb, nb * sizeof(PyObject *));
  1428. dest[nb] = *pa;
  1429. return 0;
  1430. }
  1431. /* Merge the na elements starting at pa with the nb elements starting at pb
  1432. * in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
  1433. * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
  1434. * merge, and should have na >= nb. See listsort.txt for more info.
  1435. * Return 0 if successful, -1 if error.
  1436. */
  1437. static Py_ssize_t
  1438. merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
  1439. {
  1440. Py_ssize_t k;
  1441. PyObject *compare;
  1442. PyObject **dest;
  1443. int result = -1; /* guilty until proved innocent */
  1444. PyObject **basea;
  1445. PyObject **baseb;
  1446. Py_ssize_t min_gallop;
  1447. assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
  1448. if (MERGE_GETMEM(ms, nb) < 0)
  1449. return -1;
  1450. dest = pb + nb - 1;
  1451. memcpy(ms->a, pb, nb * sizeof(PyObject*));
  1452. basea = pa;
  1453. baseb = ms->a;
  1454. pb = ms->a + nb - 1;
  1455. pa += na - 1;
  1456. *dest-- = *pa--;
  1457. --na;
  1458. if (na == 0)
  1459. goto Succeed;
  1460. if (nb == 1)
  1461. goto CopyA;
  1462. min_gallop = ms->min_gallop;
  1463. compare = ms->compare;
  1464. for (;;) {
  1465. Py_ssize_t acount = 0; /* # of times A won in a row */
  1466. Py_ssize_t bcount = 0; /* # of times B won in a row */
  1467. /* Do the straightforward thing until (if ever) one run
  1468. * appears to win consistently.
  1469. */
  1470. for (;;) {
  1471. assert(na > 0 && nb > 1);
  1472. k = ISLT(*pb, *pa, compare);
  1473. if (k) {
  1474. if (k < 0)
  1475. goto Fail;
  1476. *dest-- = *pa--;
  1477. ++acount;
  1478. bcount = 0;
  1479. --na;
  1480. if (na == 0)
  1481. goto Succeed;
  1482. if (acount >= min_gallop)
  1483. break;
  1484. }
  1485. else {
  1486. *dest-- = *pb--;
  1487. ++bcount;
  1488. acount = 0;
  1489. --nb;
  1490. if (nb == 1)
  1491. goto CopyA;
  1492. if (bcount >= min_gallop)
  1493. break;
  1494. }
  1495. }
  1496. /* One run is winning so consistently that galloping may
  1497. * be a huge win. So try that, and continue galloping until
  1498. * (if ever) neither run appears to be winning consistently
  1499. * anymore.
  1500. */
  1501. ++min_gallop;
  1502. do {
  1503. assert(na > 0 && nb > 1);
  1504. min_gallop -= min_gallop > 1;
  1505. ms->min_gallop = min_gallop;
  1506. k = gallop_right(*pb, basea, na, na-1, compare);
  1507. if (k < 0)
  1508. goto Fail;
  1509. k = na - k;
  1510. acount = k;
  1511. if (k) {
  1512. dest -= k;
  1513. pa -= k;
  1514. memmove(dest+1, pa+1, k * sizeof(PyObject *));
  1515. na -= k;
  1516. if (na == 0)
  1517. goto Succeed;
  1518. }
  1519. *dest-- = *pb--;
  1520. --nb;
  1521. if (nb == 1)
  1522. goto CopyA;
  1523. k = gallop_left(*pa, baseb, nb, nb-1, compare);
  1524. if (k < 0)
  1525. goto Fail;
  1526. k = nb - k;
  1527. bcount = k;
  1528. if (k) {
  1529. dest -= k;
  1530. pb -= k;
  1531. memcpy(dest+1, pb+1, k * sizeof(PyObject *));
  1532. nb -= k;
  1533. if (nb == 1)
  1534. goto CopyA;
  1535. /* nb==0 is impossible now if the comparison
  1536. * function is consistent, but we can't assume
  1537. * that it is.
  1538. */
  1539. if (nb == 0)
  1540. goto Succeed;
  1541. }
  1542. *dest-- = *pa--;
  1543. --na;
  1544. if (na == 0)
  1545. goto Succeed;
  1546. } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
  1547. ++min_gallop; /* penalize it for leaving galloping mode */
  1548. ms->min_gallop = min_gallop;
  1549. }
  1550. Succeed:
  1551. result = 0;
  1552. Fail:
  1553. if (nb)
  1554. memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
  1555. return result;
  1556. CopyA:
  1557. assert(nb == 1 && na > 0);
  1558. /* The first element of pb belongs at the front of the merge. */
  1559. dest -= na;
  1560. pa -= na;
  1561. memmove(dest+1, pa+1, na * sizeof(PyObject *));
  1562. *dest = *pb;
  1563. return 0;
  1564. }
  1565. /* Merge the two runs at stack indices i and i+1.
  1566. * Returns 0 on success, -1 on error.
  1567. */
  1568. static Py_ssize_t
  1569. merge_at(MergeState *ms, Py_ssize_t i)
  1570. {
  1571. PyObject **pa, **pb;
  1572. Py_ssize_t na, nb;
  1573. Py_ssize_t k;
  1574. PyObject *compare;
  1575. assert(ms != NULL);
  1576. assert(ms->n >= 2);
  1577. assert(i >= 0);
  1578. assert(i == ms->n - 2 || i == ms->n - 3);
  1579. pa = ms->pending[i].base;
  1580. na = ms->pending[i].len;
  1581. pb = ms->pending[i+1].base;
  1582. nb = ms->pending[i+1].len;
  1583. assert(na > 0 && nb > 0);
  1584. assert(pa + na == pb);
  1585. /* Record the length of the combined runs; if i is the 3rd-last
  1586. * run now, also slide over the last run (which isn't involved
  1587. * in this merge). The current run i+1 goes away in any case.
  1588. */
  1589. ms->pending[i].len = na + nb;
  1590. if (i == ms->n - 3)
  1591. ms->pending[i+1] = ms->pending[i+2];
  1592. --ms->n;
  1593. /* Where does b start in a? Elements in a before that can be
  1594. * ignored (already in place).
  1595. */
  1596. compare = ms->compare;
  1597. k = gallop_right(*pb, pa, na, 0, compare);
  1598. if (k < 0)
  1599. return -1;
  1600. pa += k;
  1601. na -= k;
  1602. if (na == 0)
  1603. return 0;
  1604. /* Where does a end in b? Elements in b after that can be
  1605. * ignored (already in place).
  1606. */
  1607. nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
  1608. if (nb <= 0)
  1609. return nb;
  1610. /* Merge what remains of the runs, using a temp array with
  1611. * min(na, nb) elements.
  1612. */
  1613. if (na <= nb)
  1614. return merge_lo(ms, pa, na, pb, nb);
  1615. else
  1616. return merge_hi(ms, pa, na, pb, nb);
  1617. }
  1618. /* Examine the stack of runs waiting to be merged, merging adjacent runs
  1619. * until the stack invariants are re-established:
  1620. *
  1621. * 1. len[-3] > len[-2] + len[-1]
  1622. * 2. len[-2] > len[-1]
  1623. *
  1624. * See listsort.txt for more info.
  1625. *
  1626. * Returns 0 on success, -1 on error.
  1627. */
  1628. static int
  1629. merge_collapse(MergeState *ms)
  1630. {
  1631. struct s_slice *p = ms->pending;
  1632. assert(ms);
  1633. while (ms->n > 1) {
  1634. Py_ssize_t n = ms->n - 2;
  1635. if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
  1636. if (p[n-1].len < p[n+1].len)
  1637. --n;
  1638. if (merge_at(ms, n) < 0)
  1639. return -1;
  1640. }
  1641. else if (p[n].len <= p[n+1].len) {
  1642. if (merge_at(ms, n) < 0)
  1643. return -1;
  1644. }
  1645. else
  1646. break;
  1647. }
  1648. return 0;
  1649. }
  1650. /* Regardless of invariants, merge all runs on the stack until only one
  1651. * remains. This is used at the end of the mergesort.
  1652. *
  1653. * Returns 0 on success, -1 on error.
  1654. */
  1655. static int
  1656. merge_force_collapse(MergeState *ms)
  1657. {
  1658. struct s_slice *p = ms->pending;
  1659. assert(ms);
  1660. while (ms->n > 1) {
  1661. Py_ssize_t n = ms->n - 2;
  1662. if (n > 0 && p[n-1].len < p[n+1].len)
  1663. --n;
  1664. if (merge_at(ms, n) < 0)
  1665. return -1;
  1666. }
  1667. return 0;
  1668. }
  1669. /* Compute a good value for the minimum run length; natural runs shorter
  1670. * than this are boosted artificially via binary insertion.
  1671. *
  1672. * If n < 64, return n (it's too small to bother with fancy stuff).
  1673. * Else if n is an exact power of 2, return 32.
  1674. * Else return an int k, 32 <= k <= 64, such that n/k is close to, but
  1675. * strictly less than, an exact power of 2.
  1676. *
  1677. * See listsort.txt for more info.
  1678. */
  1679. static Py_ssize_t
  1680. merge_compute_minrun(Py_ssize_t n)
  1681. {
  1682. Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
  1683. assert(n >= 0);
  1684. while (n >= 64) {
  1685. r |= n & 1;
  1686. n >>= 1;
  1687. }
  1688. return n + r;
  1689. }
  1690. /* Special wrapper to support stable sorting using the decorate-sort-undecorate
  1691. pattern. Holds a key which is used for comparisons and the original record
  1692. which is returned during the undecorate phase. By exposing only the key
  1693. during comparisons, the underlying sort stability characteristics are left
  1694. unchanged. Also, if a custom comparison function is used, it will only see
  1695. the key instead of a full record. */
  1696. typedef struct {
  1697. PyObject_HEAD
  1698. PyObject *key;
  1699. PyObject *value;
  1700. } sortwrapperobject;
  1701. PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
  1702. static PyObject *
  1703. sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
  1704. static void
  1705. sortwrapper_dealloc(sortwrapperobject *);
  1706. static PyTypeObject sortwrapper_type = {
  1707. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1708. "sortwrapper", /* tp_name */
  1709. sizeof(sortwrapperobject), /* tp_basicsize */
  1710. 0, /* tp_itemsize */
  1711. /* methods */
  1712. (destructor)sortwrapper_dealloc, /* tp_dealloc */
  1713. 0, /* tp_print */
  1714. 0, /* tp_getattr */
  1715. 0, /* tp_setattr */
  1716. 0, /* tp_compare */
  1717. 0, /* tp_repr */
  1718. 0, /* tp_as_number */
  1719. 0, /* tp_as_sequence */
  1720. 0, /* tp_as_mapping */
  1721. 0, /* tp_hash */
  1722. 0, /* tp_call */
  1723. 0, /* tp_str */
  1724. PyObject_GenericGetAttr, /* tp_getattro */
  1725. 0, /* tp_setattro */
  1726. 0, /* tp_as_buffer */
  1727. Py_TPFLAGS_DEFAULT |
  1728. Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
  1729. sortwrapper_doc, /* tp_doc */
  1730. 0, /* tp_traverse */
  1731. 0, /* tp_clear */
  1732. (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
  1733. };
  1734. static PyObject *
  1735. sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
  1736. {
  1737. if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
  1738. PyErr_SetString(PyExc_TypeError,
  1739. "expected a sortwrapperobject");
  1740. return NULL;
  1741. }
  1742. return PyObject_RichCompare(a->key, b->key, op);
  1743. }
  1744. static void
  1745. sortwrapper_dealloc(sortwrapperobject *so)
  1746. {
  1747. Py_XDECREF(so->key);
  1748. Py_XDECREF(so->value);
  1749. PyObject_Del(so);
  1750. }
  1751. /* Returns a new reference to a sortwrapper.
  1752. Consumes the references to the two underlying objects. */
  1753. static PyObject *
  1754. build_sortwrapper(PyObject *key, PyObject *value)
  1755. {
  1756. sortwrapperobject *so;
  1757. so = PyObject_New(sortwrapperobject, &sortwrapper_type);
  1758. if (so == NULL)
  1759. return NULL;
  1760. so->key = key;
  1761. so->value = value;
  1762. return (PyObject *)so;
  1763. }
  1764. /* Returns a new reference to the value underlying the wrapper. */
  1765. static PyObject *
  1766. sortwrapper_getvalue(PyObject *so)
  1767. {
  1768. PyObject *value;
  1769. if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
  1770. PyErr_SetString(PyExc_TypeError,
  1771. "expected a sortwrapperobject");
  1772. return NULL;
  1773. }
  1774. value = ((sortwrapperobject *)so)->value;
  1775. Py_INCREF(value);
  1776. return value;
  1777. }
  1778. /* Wrapper for user specified cmp functions in combination with a
  1779. specified key function. Makes sure the cmp function is presented
  1780. with the actual key instead of the sortwrapper */
  1781. typedef struct {
  1782. PyObject_HEAD
  1783. PyObject *func;
  1784. } cmpwrapperobject;
  1785. static void
  1786. cmpwrapper_dealloc(cmpwrapperobject *co)
  1787. {
  1788. Py_XDECREF(co->func);
  1789. PyObject_Del(co);
  1790. }
  1791. static PyObject *
  1792. cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
  1793. {
  1794. PyObject *x, *y, *xx, *yy;
  1795. if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
  1796. return NULL;
  1797. if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
  1798. !PyObject_TypeCheck(y, &sortwrapper_type)) {
  1799. PyErr_SetString(PyExc_TypeError,
  1800. "expected a sortwrapperobject");
  1801. return NULL;
  1802. }
  1803. xx = ((sortwrapperobject *)x)->key;
  1804. yy = ((sortwrapperobject *)y)->key;
  1805. return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
  1806. }
  1807. PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
  1808. static PyTypeObject cmpwrapper_type = {
  1809. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1810. "cmpwrapper", /* tp_name */
  1811. sizeof(cmpwrapperobject), /* tp_basicsize */
  1812. 0, /* tp_itemsize */
  1813. /* methods */
  1814. (destructor)cmpwrapper_dealloc, /* tp_dealloc */
  1815. 0, /* tp_print */
  1816. 0, /* tp_getattr */
  1817. 0, /* tp_setattr */
  1818. 0, /* tp_compare */
  1819. 0, /* tp_repr */
  1820. 0, /* tp_as_number */
  1821. 0, /* tp_as_sequence */
  1822. 0, /* tp_as_mapping */
  1823. 0, /* tp_hash */
  1824. (ternaryfunc)cmpwrapper_call, /* tp_call */
  1825. 0, /* tp_str */
  1826. PyObject_GenericGetAttr, /* tp_getattro */
  1827. 0, /* tp_setattro */
  1828. 0, /* tp_as_buffer */
  1829. Py_TPFLAGS_DEFAULT, /* tp_flags */
  1830. cmpwrapper_doc, /* tp_doc */
  1831. };
  1832. static PyObject *
  1833. build_cmpwrapper(PyObject *cmpfunc)
  1834. {
  1835. cmpwrapperobject *co;
  1836. co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
  1837. if (co == NULL)
  1838. return NULL;
  1839. Py_INCREF(cmpfunc);
  1840. co->func = cmpfunc;
  1841. return (PyObject *)co;
  1842. }
  1843. /* An adaptive, stable, natural mergesort. See listsort.txt.
  1844. * Returns Py_None on success, NULL on error. Even in case of error, the
  1845. * list will be some permutation of its input state (nothing is lost or
  1846. * duplicated).
  1847. */
  1848. static PyObject *
  1849. listsort(PyListObject *self, PyObject *args, PyObject *kwds)
  1850. {
  1851. MergeState ms;
  1852. PyObject **lo, **hi;
  1853. Py_ssize_t nremaining;
  1854. Py_ssize_t minrun;
  1855. Py_ssize_t saved_ob_size, saved_allocated;
  1856. PyObject **saved_ob_item;
  1857. PyObject **final_ob_item;
  1858. PyObject *compare = NULL;
  1859. PyObject *result = NULL; /* guilty until proved innocent */
  1860. int reverse = 0;
  1861. PyObject *keyfunc = NULL;
  1862. Py_ssize_t i;
  1863. PyObject *key, *value, *kvpair;
  1864. static char *kwlist[] = {"cmp", "key", "reverse", 0};
  1865. assert(self != NULL);
  1866. assert (PyList_Check(self));
  1867. if (args != NULL) {
  1868. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
  1869. kwlist, &compare, &keyfunc, &reverse))
  1870. return NULL;
  1871. }
  1872. if (compare == Py_None)
  1873. compare = NULL;
  1874. if (compare != NULL &&
  1875. PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
  1876. return NULL;
  1877. if (keyfunc == Py_None)
  1878. keyfunc = NULL;
  1879. if (compare != NULL && keyfunc != NULL) {
  1880. compare = build_cmpwrapper(compare);
  1881. if (compare == NULL)
  1882. return NULL;
  1883. } else
  1884. Py_XINCREF(compare);
  1885. /* The list is temporarily made empty, so that mutations performed
  1886. * by comparison functions can't affect the slice of memory we're
  1887. * sorting (allowing mutations during sorting is a core-dump
  1888. * factory, since ob_item may change).
  1889. */
  1890. saved_ob_size = Py_SIZE(self);
  1891. saved_ob_item = self->ob_item;
  1892. saved_allocated = self->allocated;
  1893. Py_SIZE(self) = 0;
  1894. self->ob_item = NULL;
  1895. self->allocated = -1; /* any operation will reset it to >= 0 */
  1896. i

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