1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 ******************************************************************************/
19 #define LOG_TAG "bt_osi_array"
25 #include "osi/include/allocator.h"
26 #include "osi/include/array.h"
27 #include "osi/include/log.h"
34 uint8_t internal_storage[];
37 static bool grow(array_t *array);
39 static const size_t INTERNAL_ELEMENTS = 16;
41 array_t *array_new(size_t element_size) {
42 assert(element_size > 0);
44 array_t *array = osi_calloc(sizeof(array_t) + element_size * INTERNAL_ELEMENTS);
46 LOG_ERROR("%s unable to allocate memory for array with elements of size %zu.", __func__, element_size);
50 array->element_size = element_size;
51 array->capacity = INTERNAL_ELEMENTS;
52 array->data = array->internal_storage;
56 void array_free(array_t *array) {
60 if (array->data != array->internal_storage)
66 void *array_ptr(const array_t *array) {
67 return array_at(array, 0);
70 void *array_at(const array_t *array, size_t index) {
71 assert(array != NULL);
72 assert(index < array->length);
73 return array->data + (index * array->element_size);
76 size_t array_length(const array_t *array) {
77 assert(array != NULL);
81 bool array_append_value(array_t *array, uint32_t value) {
82 return array_append_ptr(array, &value);
85 bool array_append_ptr(array_t *array, void *data) {
86 assert(array != NULL);
89 if (array->length == array->capacity && !grow(array)) {
90 LOG_ERROR("%s unable to grow array past current capacity of %zu elements of size %zu.", __func__, array->capacity, array->element_size);
95 memcpy(array_at(array, array->length - 1), data, array->element_size);
99 static bool grow(array_t *array) {
100 const size_t new_capacity = array->capacity + (array->capacity / 2);
101 const bool is_moving = (array->data == array->internal_storage);
103 void *new_data = realloc(is_moving ? NULL : array->data, new_capacity * array->element_size);
108 memcpy(new_data, array->internal_storage, array->length * array->element_size);
110 array->data = new_data;
111 array->capacity = new_capacity;