Use the minimum of the two string lengths for comparison
[openal-soft.git] / common / uintmap.c
blobb7a9a29c482d89ff45d9316424db49b94c4ba05c
2 #include "config.h"
4 #include "uintmap.h"
6 #include <stdlib.h>
7 #include <string.h>
10 extern inline void LockUIntMapRead(UIntMap *map);
11 extern inline void UnlockUIntMapRead(UIntMap *map);
12 extern inline void LockUIntMapWrite(UIntMap *map);
13 extern inline void UnlockUIntMapWrite(UIntMap *map);
16 void InitUIntMap(UIntMap *map, ALsizei limit)
18 map->array = NULL;
19 map->size = 0;
20 map->maxsize = 0;
21 map->limit = limit;
22 RWLockInit(&map->lock);
25 void ResetUIntMap(UIntMap *map)
27 WriteLock(&map->lock);
28 free(map->array);
29 map->array = NULL;
30 map->size = 0;
31 map->maxsize = 0;
32 WriteUnlock(&map->lock);
35 ALenum InsertUIntMapEntry(UIntMap *map, ALuint key, ALvoid *value)
37 ALsizei pos = 0;
39 WriteLock(&map->lock);
40 if(map->size > 0)
42 ALsizei low = 0;
43 ALsizei high = map->size - 1;
44 while(low < high)
46 ALsizei mid = low + (high-low)/2;
47 if(map->array[mid].key < key)
48 low = mid + 1;
49 else
50 high = mid;
52 if(map->array[low].key < key)
53 low++;
54 pos = low;
57 if(pos == map->size || map->array[pos].key != key)
59 if(map->size == map->limit)
61 WriteUnlock(&map->lock);
62 return AL_OUT_OF_MEMORY;
65 if(map->size == map->maxsize)
67 ALvoid *temp = NULL;
68 ALsizei newsize;
70 newsize = (map->maxsize ? (map->maxsize<<1) : 4);
71 if(newsize >= map->maxsize)
72 temp = realloc(map->array, newsize*sizeof(map->array[0]));
73 if(!temp)
75 WriteUnlock(&map->lock);
76 return AL_OUT_OF_MEMORY;
78 map->array = temp;
79 map->maxsize = newsize;
82 if(pos < map->size)
83 memmove(&map->array[pos+1], &map->array[pos],
84 (map->size-pos)*sizeof(map->array[0]));
85 map->size++;
87 map->array[pos].key = key;
88 map->array[pos].value = value;
89 WriteUnlock(&map->lock);
91 return AL_NO_ERROR;
94 ALvoid *RemoveUIntMapKey(UIntMap *map, ALuint key)
96 ALvoid *ptr = NULL;
97 WriteLock(&map->lock);
98 if(map->size > 0)
100 ALsizei low = 0;
101 ALsizei high = map->size - 1;
102 while(low < high)
104 ALsizei mid = low + (high-low)/2;
105 if(map->array[mid].key < key)
106 low = mid + 1;
107 else
108 high = mid;
110 if(map->array[low].key == key)
112 ptr = map->array[low].value;
113 if(low < map->size-1)
114 memmove(&map->array[low], &map->array[low+1],
115 (map->size-1-low)*sizeof(map->array[0]));
116 map->size--;
119 WriteUnlock(&map->lock);
120 return ptr;
123 ALvoid *LookupUIntMapKey(UIntMap *map, ALuint key)
125 ALvoid *ptr = NULL;
126 ReadLock(&map->lock);
127 if(map->size > 0)
129 ALsizei low = 0;
130 ALsizei high = map->size - 1;
131 while(low < high)
133 ALsizei mid = low + (high-low)/2;
134 if(map->array[mid].key < key)
135 low = mid + 1;
136 else
137 high = mid;
139 if(map->array[low].key == key)
140 ptr = map->array[low].value;
142 ReadUnlock(&map->lock);
143 return ptr;