Skip to content
Snippets Groups Projects
Commit b5e9f50d authored by Marek Vavruša's avatar Marek Vavruša
Browse files

generic/pack: support for lookup

parent b0e7e071
No related merge requests found
...@@ -129,24 +129,37 @@ static inline int pack_obj_push(pack_t *pack, const uint8_t *obj, pack_objlen_t ...@@ -129,24 +129,37 @@ static inline int pack_obj_push(pack_t *pack, const uint8_t *obj, pack_objlen_t
return 0; return 0;
} }
/** Returns a pointer to packed object.
* @return pointer to packed object or NULL
*/
static inline uint8_t *pack_obj_find(pack_t *pack, const uint8_t *obj, pack_objlen_t len)
{
uint8_t *endp = pack_tail(*pack);
uint8_t *it = pack_head(*pack);
while (it != endp) {
uint8_t *val = pack_obj_val(it);
if (pack_obj_len(it) == len && memcmp(obj, val, len) == 0) {
return it;
}
it = pack_obj_next(it);
}
return NULL;
}
/** Delete object from the pack /** Delete object from the pack
* @return 0 on success, negative number on failure * @return 0 on success, negative number on failure
*/ */
static inline int pack_obj_del(pack_t *pack, const uint8_t *obj, pack_objlen_t len) static inline int pack_obj_del(pack_t *pack, const uint8_t *obj, pack_objlen_t len)
{ {
uint8_t *endp = pack_tail(*pack); uint8_t *endp = pack_tail(*pack);
uint8_t *it = pack_head(*pack); uint8_t *it = pack_obj_find(pack, obj, len);
while (it != endp) { if (it) {
uint8_t *val = pack_obj_val(it); size_t packed_len = len + sizeof(len);
if (pack_obj_len(it) == len && memcmp(obj, val, len) == 0) { memmove(it, it + packed_len, endp - it - packed_len);
size_t packed_len = len + sizeof(len); pack->len -= packed_len;
memmove(it, it + packed_len, endp - it - packed_len); return 0;
pack->len -= packed_len; }
return 0; return -1;
}
it = pack_obj_next(it);
}
return -1;
} }
#ifdef __cplusplus #ifdef __cplusplus
......
...@@ -49,6 +49,12 @@ static void test_pack_std(void **state) ...@@ -49,6 +49,12 @@ static void test_pack_std(void **state)
count += 1; count += 1;
} }
/* Find */
it = pack_obj_find(&pack, U8("de"), 2);
assert_non_null(it);
it = pack_obj_find(&pack, U8("ed"), 2);
assert_null(it);
/* Delete */ /* Delete */
assert_int_not_equal(pack_obj_del(&pack, U8("be"), 2), 0); assert_int_not_equal(pack_obj_del(&pack, U8("be"), 2), 0);
assert_int_equal(pack_obj_del(&pack, U8("de"), 2), 0); assert_int_equal(pack_obj_del(&pack, U8("de"), 2), 0);
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment