]>
Commit | Line | Data |
---|---|---|
91b6eb11 | 1 | /* Increase the size of a dynamic array. |
04277e02 | 2 | Copyright (C) 2017-2019 Free Software Foundation, Inc. |
91b6eb11 FW |
3 | This file is part of the GNU C Library. |
4 | ||
5 | The GNU C Library is free software; you can redistribute it and/or | |
6 | modify it under the terms of the GNU Lesser General Public | |
7 | License as published by the Free Software Foundation; either | |
8 | version 2.1 of the License, or (at your option) any later version. | |
9 | ||
10 | The GNU C Library is distributed in the hope that it will be useful, | |
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
13 | Lesser General Public License for more details. | |
14 | ||
15 | You should have received a copy of the GNU Lesser General Public | |
16 | License along with the GNU C Library; if not, see | |
5a82c748 | 17 | <https://www.gnu.org/licenses/>. */ |
91b6eb11 FW |
18 | |
19 | #include <dynarray.h> | |
5898f454 | 20 | #include <errno.h> |
91b6eb11 FW |
21 | #include <stdlib.h> |
22 | #include <string.h> | |
23 | ||
24 | bool | |
25 | __libc_dynarray_resize (struct dynarray_header *list, size_t size, | |
26 | void *scratch, size_t element_size) | |
27 | { | |
28 | /* The existing allocation provides sufficient room. */ | |
29 | if (size <= list->allocated) | |
30 | { | |
31 | list->used = size; | |
32 | return true; | |
33 | } | |
34 | ||
35 | /* Otherwise, use size as the new allocation size. The caller is | |
36 | expected to provide the final size of the array, so there is no | |
37 | over-allocation here. */ | |
38 | ||
39 | size_t new_size_bytes; | |
0253580a | 40 | if (__builtin_mul_overflow (size, element_size, &new_size_bytes)) |
5898f454 FW |
41 | { |
42 | /* Overflow. */ | |
43 | __set_errno (ENOMEM); | |
44 | return false; | |
45 | } | |
91b6eb11 FW |
46 | void *new_array; |
47 | if (list->array == scratch) | |
48 | { | |
49 | /* The previous array was not heap-allocated. */ | |
50 | new_array = malloc (new_size_bytes); | |
51 | if (new_array != NULL && list->array != NULL) | |
52 | memcpy (new_array, list->array, list->used * element_size); | |
53 | } | |
54 | else | |
55 | new_array = realloc (list->array, new_size_bytes); | |
56 | if (new_array == NULL) | |
57 | return false; | |
58 | list->array = new_array; | |
59 | list->allocated = size; | |
60 | list->used = size; | |
61 | return true; | |
62 | } | |
63 | libc_hidden_def (__libc_dynarray_resize) |