]>
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.
15 #include "svgtiny_internal.h"
19 unsigned int size
; /* number of slots used */
20 unsigned int allocated
; /* number of slots allocated (>= size) */
21 size_t item_size
; /* size of each slot / bytes */
22 char *items
; /* array of slots */
27 * Create an empty svgtiny_list.
30 struct svgtiny_list
*svgtiny_list_create(size_t item_size
)
32 struct svgtiny_list
*list
= malloc(sizeof *list
);
37 list
->item_size
= item_size
;
44 * Return the number of objects in a list.
47 unsigned int svgtiny_list_size(struct svgtiny_list
*list
)
54 * Set the number of objects in a list. If the size is increased, the new
55 * objects are not initialized in any way.
57 * The allocation size formula is taken from Python's list:
58 * http://svn.python.org/view/python/trunk/Objects/listobject.c?view=markup
60 * Objects may have moved after this call. Use svgtiny_list_get() to get new
64 svgtiny_code
svgtiny_list_resize(struct svgtiny_list
*list
,
65 unsigned int new_size
)
67 unsigned int new_allocated
;
70 if (new_size
<= list
->allocated
) {
71 list
->size
= new_size
;
75 new_allocated
= (new_size
>> 3) + (new_size
< 9 ? 3 : 6) + new_size
;
78 new_items
= realloc(list
->items
, new_allocated
* list
->item_size
);
80 return svgtiny_OUT_OF_MEMORY
;
82 list
->size
= new_size
;
83 list
->allocated
= new_allocated
;
84 list
->items
= new_items
;
91 * Return a pointer to an object in a list.
94 void *svgtiny_list_get(struct svgtiny_list
*list
,
97 assert(i
< list
->size
);
98 return (void *) (list
->items
+ i
* list
->item_size
);
103 * Add space for one object to a list and return a pointer to it.
106 void *svgtiny_list_push(struct svgtiny_list
*list
)
109 code
= svgtiny_list_resize(list
, list
->size
+ 1);
110 if (code
!= svgtiny_OK
)
112 return svgtiny_list_get(list
, list
->size
- 1);
117 * Free an entire list.
120 void svgtiny_list_free(struct svgtiny_list
*list
)