Mercurial > code
comparison array.c @ 67:cff6869fbc94
Modified [p]array_find to return the index for a better usage
author | David Demelier <markand@malikania.fr> |
---|---|
date | Thu, 10 Nov 2011 18:27:04 +0100 |
parents | 9cc5d6d0563e |
children | b3ba5f5df3b9 |
comparison
equal
deleted
inserted
replaced
66:f773c76b1f3c | 67:cff6869fbc94 |
---|---|
227 * Apply the function `fn' on each object and give the optional `udata' | 227 * Apply the function `fn' on each object and give the optional `udata' |
228 * argument to the function too. | 228 * argument to the function too. |
229 */ | 229 */ |
230 | 230 |
231 void | 231 void |
232 array_map(const struct array *arr, void (*fn)(void *, void *), void *udata) | 232 array_map(const struct array *arr, array_map_fn fn, void *udata) |
233 { | 233 { |
234 int i; | 234 int i; |
235 | 235 |
236 for (i = 0; i < arr->length; ++i) | 236 for (i = 0; i < arr->length; ++i) |
237 fn((char *)arr->data + OFFSET(i), udata); | 237 fn((char *)arr->data + OFFSET(i), udata); |
238 } | 238 } |
239 | 239 |
240 /* | 240 /* |
241 * Compare each object with the user supplied function. If the `fn' function | 241 * Compare each object with the user supplied function. If the `fn' function |
242 * returns 1 then the data is returned. Optional idx argument can be set to | 242 * returns 1 then the index of the data position is returned and the parameter |
243 * indicate the data position. If the data was not found the function returns | 243 * data is filled with the array data at the correct index. If the comparison |
244 * NULL. | 244 * function nevers returns 1, array_find returns -1. |
245 */ | 245 */ |
246 | 246 |
247 void * | 247 int |
248 array_find(const struct array *arr, int (*fn)(void *, void *), int *ix, void *u) | 248 array_find(const struct array *arr, array_cmp_fn fn, void *data, void *u) |
249 { | 249 { |
250 int st, i; | 250 int st, i; |
251 void *data; | |
252 | 251 |
253 for (i = st = 0; i < arr->length && st != 1; ++i) | 252 for (i = st = 0; i < arr->length && st != 1; ++i) |
254 st = fn((char *)arr->data + OFFSET(i), u); | 253 st = fn((char *)arr->data + OFFSET(i), u); |
255 | 254 |
256 if (st) { | 255 if (st) |
257 data = (char *)arr->data + OFFSET(--i); | 256 memcpy(data, (char *)arr->data + OFFSET(--i), arr->unit); |
258 if (ix) | 257 else |
259 *ix = i; | 258 i = -1; |
260 } else | 259 |
261 data = NULL; | 260 return i; |
262 | |
263 return data; | |
264 } | 261 } |
265 | 262 |
266 /* | 263 /* |
267 * Erase every bytes and set the length to 0. | 264 * Erase every bytes and set the length to 0. |
268 */ | 265 */ |