* Return a freshly allocated List with room for at least min_size cells. * * Since empty non-NIL lists are invalid, new_list() sets the initial length * to min_size, effectively marking that number of cells as valid; the caller * is responsible for filling in their data. */
| 85 | * is responsible for filling in their data. |
| 86 | */ |
| 87 | static List * |
| 88 | new_list(NodeTag type, int min_size) |
| 89 | { |
| 90 | List *newlist; |
| 91 | int max_size; |
| 92 | |
| 93 | Assert(min_size > 0); |
| 94 | |
| 95 | /* |
| 96 | * We allocate all the requested cells, and possibly some more, as part of |
| 97 | * the same palloc request as the List header. This is a big win for the |
| 98 | * typical case of short fixed-length lists. It can lose if we allocate a |
| 99 | * moderately long list and then it gets extended; we'll be wasting more |
| 100 | * initial_elements[] space than if we'd made the header small. However, |
| 101 | * rounding up the request as we do in the normal code path provides some |
| 102 | * defense against small extensions. |
| 103 | */ |
| 104 | |
| 105 | #ifndef DEBUG_LIST_MEMORY_USAGE |
| 106 | |
| 107 | /* |
| 108 | * Normally, we set up a list with some extra cells, to allow it to grow |
| 109 | * without a repalloc. Prefer cell counts chosen to make the total |
| 110 | * allocation a power-of-2, since palloc would round it up to that anyway. |
| 111 | * (That stops being true for very large allocations, but very long lists |
| 112 | * are infrequent, so it doesn't seem worth special logic for such cases.) |
| 113 | * |
| 114 | * The minimum allocation is 8 ListCell units, providing either 4 or 5 |
| 115 | * available ListCells depending on the machine's word width. Counting |
| 116 | * palloc's overhead, this uses the same amount of space as a one-cell |
| 117 | * list did in the old implementation, and less space for any longer list. |
| 118 | * |
| 119 | * We needn't worry about integer overflow; no caller passes min_size |
| 120 | * that's more than twice the size of an existing list, so the size limits |
| 121 | * within palloc will ensure that we don't overflow here. |
| 122 | */ |
| 123 | max_size = pg_nextpower2_32(Max(8, min_size + LIST_HEADER_OVERHEAD)); |
| 124 | max_size -= LIST_HEADER_OVERHEAD; |
| 125 | #else |
| 126 | |
| 127 | /* |
| 128 | * For debugging, don't allow any extra space. This forces any cell |
| 129 | * addition to go through enlarge_list() and thus move the existing data. |
| 130 | */ |
| 131 | max_size = min_size; |
| 132 | #endif |
| 133 | |
| 134 | newlist = (List *) palloc(offsetof(List, initial_elements) + |
| 135 | max_size * sizeof(ListCell)); |
| 136 | newlist->type = type; |
| 137 | newlist->length = min_size; |
| 138 | newlist->max_length = max_size; |
| 139 | newlist->elements = newlist->initial_elements; |
| 140 | |
| 141 | return newlist; |
| 142 | } |
| 143 | |
| 144 | /* |
no test coverage detected