Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/libraries/AP_Common/AP_ExpandingArray.cpp
Views: 1798
/*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*)hal.util->std_realloc((void*)chunk_ptrs, chunk_ptr_size * sizeof(chunk_ptr_t));43if (chunk_ptrs_new == nullptr) {44return false;45}4647// use new pointers array48chunk_ptrs = chunk_ptrs_new;49chunk_count_max = chunk_ptr_size;50}5152// allocate new chunks53for (uint16_t i = 0; i < num_chunks; i++) {54if (hal.util->available_memory() < 100U + (chunk_size * elem_size)) {55// fail if reallocating would leave less than 100 bytes of memory free56return false;57}58uint8_t *new_chunk = (uint8_t *)calloc(chunk_size, elem_size);59if (new_chunk == nullptr) {60// failed to allocate new chunk61return false;62}63chunk_ptrs[chunk_count] = new_chunk;64chunk_count++;65}66return true;67}6869// expand to hold at least num_items70bool AP_ExpandingArrayGeneric::expand_to_hold(uint16_t num_items)71{72// check if already big enough73if (num_items <= max_items()) {74return true;75}76uint16_t chunks_required = ((num_items - max_items()) / chunk_size) + 1;77return expand(chunks_required);78}7980#endif // HAL_BOOTLOADER_BUILD818283