1/* 2 * Copyright 2016, Data61 3 * Commonwealth Scientific and Industrial Research Organisation (CSIRO) 4 * ABN 41 687 119 230. 5 * 6 * This software may be distributed and modified according to the terms of 7 * the BSD 2-Clause license. Note that NO WARRANTY is provided. 8 * See "LICENSE_BSD2.txt" for details. 9 * 10 * @TAG(D61_BSD) 11 */ 12 13#include <data_struct/cvector.h> 14#include <assert.h> 15 16static void 17cvector_delete_resize(cvector_t *v) { 18 if (v->nextResize-- > 0) { 19 return; 20 } 21 // Condition to decrease v->data size: size > (c * 2) + k 22 if ((v->count + 2) * 2 < v->size) { 23 v->size = (v->count + 2); 24 v->data = krealloc(v->data, sizeof(cvector_item_t) * v->size); 25 v->nextResize = CVECTOR_RESIZE_CHECK_FREQ; 26 } 27} 28 29void 30cvector_init(cvector_t *v) 31{ 32 assert(v); 33 v->data = NULL; 34 v->size = 0; 35 v->count = 0; 36 v->nextResize = CVECTOR_RESIZE_CHECK_FREQ; 37} 38 39int 40cvector_add(cvector_t *v, cvector_item_t e) 41{ 42 assert(v); 43 if (v->size == 0) { 44 v->size = CVECTOR_INIT_SIZE; 45 v->data = kmalloc(sizeof(cvector_item_t) * v->size); 46 assert(v->data); 47 } 48 49 // Condition to increase v->data: last slot exhausted 50 if (v->size <= v->count) { 51 v->size *= 2; 52 v->data = krealloc(v->data, sizeof(cvector_item_t) * v->size); 53 assert(v->data); 54 } 55 56 v->data[v->count] = e; 57 return v->count++; 58} 59 60void 61cvector_set(cvector_t *v, uint32_t index, cvector_item_t e) 62{ 63 assert(v); 64 assert(index < v->count); 65 v->data[index] = e; 66} 67 68cvector_item_t 69cvector_get(cvector_t *v, int index) 70{ 71 assert(v); 72 assert(index < v->count); 73 return v->data[index]; 74} 75 76void 77cvector_delete(cvector_t *v, int index) 78{ 79 assert(v); 80 assert(index < v->count); 81 for(int i = index; i < (v->count - 1); i++) { 82 v->data[i] = v->data[i + 1]; 83 } 84 v->count--; 85 cvector_delete_resize(v); 86} 87 88void 89cvector_free(cvector_t *v) 90{ 91 assert(v); 92 if (v->data) kfree(v->data); 93 cvector_init(v); 94} 95 96void 97cvector_reset(cvector_t *v) 98{ 99 assert(v); 100 v->count = 0; 101} 102