CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
Ardupilot

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: Ardupilot/ardupilot
Path: blob/master/libraries/AP_Common/AP_ExpandingArray.cpp
Views: 1798
1
/*
2
This program is free software: you can redistribute it and/or modify
3
it under the terms of the GNU General Public License as published by
4
the Free Software Foundation, either version 3 of the License, or
5
(at your option) any later version.
6
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
11
12
You should have received a copy of the GNU General Public License
13
along with this program. If not, see <http://www.gnu.org/licenses/>.
14
*/
15
16
#include "AP_ExpandingArray.h"
17
#include <AP_HAL/AP_HAL.h>
18
19
#ifndef HAL_BOOTLOADER_BUILD
20
21
extern const AP_HAL::HAL& hal;
22
23
AP_ExpandingArrayGeneric::~AP_ExpandingArrayGeneric(void)
24
{
25
// free chunks
26
for (uint16_t i=0; i<chunk_count; i++) {
27
free(chunk_ptrs[i]);
28
}
29
// free chunks_ptrs array
30
free(chunk_ptrs);
31
}
32
33
// expand the array by specified number of chunks, returns true on success
34
bool AP_ExpandingArrayGeneric::expand(uint16_t num_chunks)
35
{
36
// expand chunk_ptrs array if necessary
37
if (chunk_count + num_chunks >= chunk_count_max) {
38
uint16_t chunk_ptr_size = chunk_count + num_chunks + chunk_ptr_increment;
39
if (hal.util->available_memory() < 100U + (chunk_ptr_size * sizeof(chunk_ptr_t))) {
40
// fail if reallocating would leave less than 100 bytes of memory free
41
return false;
42
}
43
chunk_ptr_t *chunk_ptrs_new = (chunk_ptr_t*)hal.util->std_realloc((void*)chunk_ptrs, chunk_ptr_size * sizeof(chunk_ptr_t));
44
if (chunk_ptrs_new == nullptr) {
45
return false;
46
}
47
48
// use new pointers array
49
chunk_ptrs = chunk_ptrs_new;
50
chunk_count_max = chunk_ptr_size;
51
}
52
53
// allocate new chunks
54
for (uint16_t i = 0; i < num_chunks; i++) {
55
if (hal.util->available_memory() < 100U + (chunk_size * elem_size)) {
56
// fail if reallocating would leave less than 100 bytes of memory free
57
return false;
58
}
59
uint8_t *new_chunk = (uint8_t *)calloc(chunk_size, elem_size);
60
if (new_chunk == nullptr) {
61
// failed to allocate new chunk
62
return false;
63
}
64
chunk_ptrs[chunk_count] = new_chunk;
65
chunk_count++;
66
}
67
return true;
68
}
69
70
// expand to hold at least num_items
71
bool AP_ExpandingArrayGeneric::expand_to_hold(uint16_t num_items)
72
{
73
// check if already big enough
74
if (num_items <= max_items()) {
75
return true;
76
}
77
uint16_t chunks_required = ((num_items - max_items()) / chunk_size) + 1;
78
return expand(chunks_required);
79
}
80
81
#endif // HAL_BOOTLOADER_BUILD
82
83