]>
gitweb.michael.orlitzky.com - libsvgtiny.git/blob - src/svgtiny_list.c
2 * This file is part of Libsvgtiny
3 * Licensed under the MIT License,
4 * http://opensource.org/licenses/mit-license.php
5 * Copyright 2008 James Bursa <james@semichrome.net>
9 * A svgtiny_list is a managed array of objects. It grows in chunks to reduce
10 * calls to realloc(), but keeps wasted space low.
16 #include "svgtiny_internal.h"
20 unsigned int size
; /* number of slots used */
21 unsigned int allocated
; /* number of slots allocated (>= size) */
22 size_t item_size
; /* size of each slot / bytes */
23 char *items
; /* array of slots */
28 * Create an empty svgtiny_list.
31 struct svgtiny_list
*svgtiny_list_create(size_t item_size
)
33 struct svgtiny_list
*list
= malloc(sizeof *list
);
38 list
->item_size
= item_size
;
45 * Return the number of objects in a list.
48 unsigned int svgtiny_list_size(struct svgtiny_list
*list
)
55 * Set the number of objects in a list. If the size is increased, the new
56 * objects are not initialized in any way.
58 * The allocation size formula is taken from Python's list:
59 * http://svn.python.org/view/python/trunk/Objects/listobject.c?view=markup
61 * Objects may have moved after this call. Use svgtiny_list_get() to get new
65 svgtiny_code
svgtiny_list_resize(struct svgtiny_list
*list
,
66 unsigned int new_size
)
68 unsigned int new_allocated
;
71 if (new_size
<= list
->allocated
) {
72 list
->size
= new_size
;
76 new_allocated
= (new_size
>> 3) + (new_size
< 9 ? 3 : 6) + new_size
;
79 new_items
= realloc(list
->items
, new_allocated
* list
->item_size
);
81 return svgtiny_OUT_OF_MEMORY
;
83 list
->size
= new_size
;
84 list
->allocated
= new_allocated
;
85 list
->items
= new_items
;
92 * Return a pointer to an object in a list.
95 void *svgtiny_list_get(struct svgtiny_list
*list
,
98 assert(i
< list
->size
);
99 return (void *) (list
->items
+ i
* list
->item_size
);
104 * Add space for one object to a list and return a pointer to it.
107 void *svgtiny_list_push(struct svgtiny_list
*list
)
110 code
= svgtiny_list_resize(list
, list
->size
+ 1);
111 if (code
!= svgtiny_OK
)
113 return svgtiny_list_get(list
, list
->size
- 1);
118 * Free an entire list.
121 void svgtiny_list_free(struct svgtiny_list
*list
)