Path: blob/master/libraries/AP_Common/AP_ExpandingArray.cpp
9354 views
/*1This program is free software: you can redistribute it and/or modify2it under the terms of the GNU General Public License as published by3the Free Software Foundation, either version 3 of the License, or4(at your option) any later version.56This program is distributed in the hope that it will be useful,7but WITHOUT ANY WARRANTY; without even the implied warranty of8MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the9GNU General Public License for more details.1011You should have received a copy of the GNU General Public License12along with this program. If not, see <http://www.gnu.org/licenses/>.13*/1415#include "AP_ExpandingArray.h"16#include <AP_HAL/AP_HAL.h>1718#ifndef HAL_BOOTLOADER_BUILD1920extern const AP_HAL::HAL& hal;2122AP_ExpandingArrayGeneric::~AP_ExpandingArrayGeneric(void)23{24// free chunks25for (uint16_t i=0; i<chunk_count; i++) {26free(chunk_ptrs[i]);27}28// free chunks_ptrs array29free(chunk_ptrs);30}3132// expand the array by specified number of chunks, returns true on success33bool AP_ExpandingArrayGeneric::expand(uint16_t num_chunks)34{35// expand chunk_ptrs array if necessary36if (chunk_count + num_chunks >= chunk_count_max) {37uint16_t chunk_ptr_size = chunk_count + num_chunks + chunk_ptr_increment;38if (hal.util->available_memory() < 100U + (chunk_ptr_size * sizeof(chunk_ptr_t))) {39// fail if reallocating would leave less than 100 bytes of memory free40return false;41}42chunk_ptr_t *chunk_ptrs_new = (chunk_ptr_t*)mem_realloc((void*)chunk_ptrs,43chunk_count_max * sizeof(chunk_ptr_t),44chunk_ptr_size * sizeof(chunk_ptr_t));4546if (chunk_ptrs_new == nullptr) {47return false;48}4950// use new pointers array51chunk_ptrs = chunk_ptrs_new;52chunk_count_max = chunk_ptr_size;53}5455// allocate new chunks56for (uint16_t i = 0; i < num_chunks; i++) {57if (hal.util->available_memory() < 100U + (chunk_size * elem_size)) {58// fail if reallocating would leave less than 100 bytes of memory free59return false;60}61uint8_t *new_chunk = (uint8_t *)calloc(chunk_size, elem_size);62if (new_chunk == nullptr) {63// failed to allocate new chunk64return false;65}66chunk_ptrs[chunk_count] = new_chunk;67chunk_count++;68}69return true;70}7172// expand to hold at least num_items73bool AP_ExpandingArrayGeneric::expand_to_hold(uint16_t num_items)74{75// check if already big enough76if (num_items <= max_items()) {77return true;78}79uint16_t chunks_required = ((num_items - max_items()) / chunk_size) + 1;80return expand(chunks_required);81}8283#endif // HAL_BOOTLOADER_BUILD848586