1 /* MSPDebug - debugging tool for MSP430 MCUs 2 * Copyright (C) 2009, 2010 Daniel Beer 3 * 4 * This program is free software; you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation; either version 2 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 17 */ 18 19 #ifndef VECTOR_H_ 20 #define VECTOR_H_ 21 22 /* A vector is a flexible array type. It can be used to hold elements of 23 * any type. 24 * 25 * elemsize: size in bytes of each element 26 * capacity: maximum number of elements that ptr can hold 27 * size: number of elements currently held 28 */ 29 struct vector { 30 void *ptr; 31 int elemsize; 32 int capacity; 33 int size; 34 }; 35 36 /* Create and destroy vectors */ 37 void vector_init(struct vector *v, int elemsize); 38 void vector_destroy(struct vector *v); 39 40 /* Reallocate a vector to the given size. Returns 0 if successful, or -1 41 * if memory could not be allocated. 42 */ 43 int vector_realloc(struct vector *v, int capacity); 44 45 /* Append any number of elements to the end of a vector, reallocating if 46 * necessary. Returns 0 on success or -1 if memory could not be allocated. 47 */ 48 int vector_push(struct vector *v, const void *data, int count); 49 50 /* Remove the last element from a vector. */ 51 void vector_pop(struct vector *v); 52 53 /* Dereference a vector, giving an expression for the element of type t at 54 * position i in vector v. Use as follows: 55 * 56 * struct vector v; 57 * 58 * VECTOR_AT(v, 3, int) = 57; 59 * *VECTOR_PTR(v, 3, int) = 57; 60 */ 61 #define VECTOR_AT(v, i, t) (*VECTOR_PTR(v, i, t)) 62 #define VECTOR_PTR(v, i, t) \ 63 ((t *)((char *)(v).ptr + (i) * (v).elemsize)) 64 65 #endif 66