Skip to content

Commit 4a2cd96

Browse files
author
Keith Derrick
committed
Add NULL-safe lookup function
New lh_table_lookup_ex() method protects itself against null pointers and invalid objects being passed in.
1 parent 74d830d commit 4a2cd96

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

linkhash.c

+14-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*
44
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
55
* Michael Clark <[email protected]>
6+
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
67
*
78
* This library is free software; you can redistribute it and/or modify
89
* it under the terms of the MIT license. See COPYING for details.
@@ -174,11 +175,21 @@ struct lh_entry* lh_table_lookup_entry(struct lh_table *t, const void *k)
174175

175176
const void* lh_table_lookup(struct lh_table *t, const void *k)
176177
{
177-
struct lh_entry *e = lh_table_lookup_entry(t, k);
178-
if(e) return e->v;
179-
return NULL;
178+
void *result;
179+
lh_table_lookup_ex(t, k, &result);
180+
return result;
180181
}
181182

183+
json_bool lh_table_lookup_ex(struct lh_table* t, const void* k, void **v)
184+
{
185+
struct lh_entry *e = lh_table_lookup_entry(t, k);
186+
if (e != NULL) {
187+
if (v != NULL) *v = (void *)e->v;
188+
return TRUE; /* key found */
189+
}
190+
if (v != NULL) *v = NULL;
191+
return FALSE; /* key not found */
192+
}
182193

183194
int lh_table_delete_entry(struct lh_table *t, struct lh_entry *e)
184195
{

linkhash.h

+12
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
*
44
* Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
55
* Michael Clark <[email protected]>
6+
* Copyright (c) 2009 Hewlett-Packard Development Company, L.P.
67
*
78
* This library is free software; you can redistribute it and/or modify
89
* it under the terms of the MIT license. See COPYING for details.
@@ -12,6 +13,8 @@
1213
#ifndef _linkhash_h_
1314
#define _linkhash_h_
1415

16+
#include "json_object.h"
17+
1518
#ifdef __cplusplus
1619
extern "C" {
1720
#endif
@@ -241,9 +244,18 @@ extern struct lh_entry* lh_table_lookup_entry(struct lh_table *t, const void *k)
241244
* @param t the table to lookup
242245
* @param k a pointer to the key to lookup
243246
* @return a pointer to the found value or NULL if it does not exist.
247+
* @deprecated Use lh_table_lookup_ex instead.
244248
*/
245249
extern const void* lh_table_lookup(struct lh_table *t, const void *k);
246250

251+
/**
252+
* Lookup a record in the table
253+
* @param t the table to lookup
254+
* @param k a pointer to the key to lookup
255+
* @param v a pointer to a where to store the found value (set to NULL if it doesn't exist).
256+
* @return whether or not the key was found
257+
*/
258+
extern json_bool lh_table_lookup_ex(struct lh_table *t, const void *k, void **v);
247259

248260
/**
249261
* Delete a record from the table.

0 commit comments

Comments
 (0)