From b03963d4f6066355fb88d453f6c2a23252b8ff86 Mon Sep 17 00:00:00 2001 From: YuQing <384681@qq.com> Date: Tue, 16 Nov 2021 19:47:14 +0800 Subject: [PATCH] add function sorted_array_find and marco sorted_id_name_array_init --- src/common_define.h | 6 ++++++ src/sorted_array.c | 6 ++++++ src/sorted_array.h | 24 ++++++++++++++++++++++++ 3 files changed, 36 insertions(+) diff --git a/src/common_define.h b/src/common_define.h index 56a8e09..c6eaaf3 100644 --- a/src/common_define.h +++ b/src/common_define.h @@ -255,6 +255,12 @@ typedef struct int count; } int64_array_t; +typedef struct +{ + id_name_pair_t *elts; + int count; +} id_name_array_t; + typedef struct { void *elts; diff --git a/src/sorted_array.c b/src/sorted_array.c index 2e6137e..a23b36d 100644 --- a/src/sorted_array.c +++ b/src/sorted_array.c @@ -172,3 +172,9 @@ int sorted_array_compare_int32(const int32_t *n1, const int32_t *n2) { return *n1 - *n2; } + +int sorted_array_compare_id_name_pair(const id_name_pair_t *pair1, + const id_name_pair_t *pair2) +{ + return fc_compare_int64(pair1->id, pair2->id); +} diff --git a/src/sorted_array.h b/src/sorted_array.h index 43f111e..cad1b42 100644 --- a/src/sorted_array.h +++ b/src/sorted_array.h @@ -66,12 +66,31 @@ extern "C" { void *base, int *count, const void *elt); + /** find element from the sorted array + * parameters: + * ctx: the context for sorted array + * base: the pointer of the sorted array (the first array element) + * count: the count of the sorted array + * key: the element to find + * return: 0 for success, != 0 for error + */ + static inline void *sorted_array_find(SortedArrayContext *ctx, + void *base, const int count, const void *key) + { + return bsearch(key, base, count, ctx-> + element_size, ctx->compare_func); + } + /* comparator for 64 bits integer */ int sorted_array_compare_int64(const int64_t *n1, const int64_t *n2); /* comparator for 32 bits integer */ int sorted_array_compare_int32(const int32_t *n1, const int32_t *n2); + /* comparator for id name pair (sorted by id) */ + int sorted_array_compare_id_name_pair(const id_name_pair_t *pair1, + const id_name_pair_t *pair2); + #define sorted_i64_array_init(ctx, allow_duplication) \ sorted_array_init(ctx, sizeof(int64_t), allow_duplication, \ @@ -81,6 +100,11 @@ extern "C" { sorted_array_init(ctx, sizeof(int32_t), allow_duplication, \ (int (*)(const void *, const void *))sorted_array_compare_int32) +#define sorted_id_name_array_init(ctx, allow_duplication) \ + sorted_array_init(ctx, sizeof(id_name_pair_t), allow_duplication, \ + (int (*)(const void *, const void *)) \ + sorted_array_compare_id_name_pair) + #ifdef __cplusplus }