Browse Source

Merge pull request #155 from LeSpocky/bsearch

add bsearch for arrays
tags/json-c-0.13-20171207
Eric Haszlakiewicz 10 years ago
parent
commit
a500c1f0b5
4 changed files with 49 additions and 2 deletions
  1. +8
    -2
      arraylist.c
  2. +5
    -0
      arraylist.h
  3. +17
    -0
      json_object.c
  4. +19
    -0
      json_object.h

+ 8
- 2
arraylist.c View File

@@ -91,8 +91,14 @@ array_list_add(struct array_list *arr, void *data)
void
array_list_sort(struct array_list *arr, int(*sort_fn)(const void *, const void *))
{
qsort(arr->array, arr->length, sizeof(arr->array[0]),
(int (*)(const void *, const void *))sort_fn);
qsort(arr->array, arr->length, sizeof(arr->array[0]), sort_fn);
}

void* array_list_bsearch( const void **key, struct array_list *arr,
int (*sort_fn)(const void *, const void *) )
{
return bsearch( key, arr->array, arr->length, sizeof(arr->array[0]),
sort_fn );
}

int


+ 5
- 0
arraylist.h View File

@@ -49,6 +49,11 @@ array_list_length(struct array_list *al);
extern void
array_list_sort(struct array_list *arr, int(*compar)(const void *, const void *));

extern void* array_list_bsearch( const void **key,
struct array_list *arr,
int (*sort_fn)(const void *, const void *) );


#ifdef __cplusplus
}
#endif


+ 17
- 0
json_object.c View File

@@ -889,6 +889,23 @@ void json_object_array_sort(struct json_object *jso, int(*sort_fn)(const void *,
array_list_sort(jso->o.c_array, sort_fn);
}

struct json_object* json_object_array_bsearch(
const struct json_object *key,
const struct json_object *jso,
int (*sort_fn)(const void *, const void *) )
{
struct json_object **result;

result = (struct json_object **) array_list_bsearch(
(const void **) &key, jso->o.c_array, sort_fn );

if ( result == NULL ) {
return NULL;
} else {
return *result;
}
}

int json_object_array_length(struct json_object *jso)
{
return array_list_length(jso->o.c_array);


+ 19
- 0
json_object.h View File

@@ -407,6 +407,25 @@ extern int json_object_array_length(struct json_object *obj);
*/
extern void json_object_array_sort(struct json_object *jso, int(*sort_fn)(const void *, const void *));

/** Binary search a sorted array for a specified key object.
*
* It depends on your compare function what's sufficient as a key.
* Usually you create some dummy object with the parameter compared in
* it, to identify the right item you're actually looking for.
*
* @see json_object_array_sort() for hints on the compare function.
*
* @param key a dummy json_object with the right key
* @param jso the array object we're searching
* @param sort_fn the sort/compare function
*
* @return the wanted json_object instance
*/
extern struct json_object* json_object_array_bsearch(
const struct json_object *key,
const struct json_object *jso,
int (*sort_fn)(const void *, const void *) );

/** Add an element to the end of a json_object of type json_type_array
*
* The reference count will *not* be incremented. This is to make adding


Loading…
Cancel
Save