FictionTools/z88dk/ext/uthash/tests/lru_cache/cache.c
/** Inserts a given <key, value> pair into the cache

    @param cache
    The cache object

    @param key
    The key that identifies <value>

    @param data
    Data associated with <key>

    @return EINVAL if cache is NULL, ENOMEM if malloc fails, 0 otherwise
*/
Inserts a given  pair into the cache
Inserts a given pair into the cache
int foo_cache_insert(struct foo_cache *cache, char *key, void *data)
{
	struct foo_cache_entry *entry = NULL;
	struct foo_cache_entry *tmp_entry = NULL;
	size_t key_len = 0;
	int rv;
	if (!cache || !data)
		return EINVAL;
	if ((entry = malloc(sizeof(*entry))) == NULL)
		return ENOMEM;
	if ((rv = pthread_rwlock_wrlock(&(cache->cache_lock))) != 0)
		goto err_out;
	entry->key = key;
	entry->data = data;
	key_len = strnlen(entry->key, KEY_MAX_LENGTH);
	HASH_ADD_KEYPTR(hh, cache->entries, entry->key, key_len, entry);
	if (HASH_COUNT(cache->entries) >= cache->max_entries) {
		HASH_ITER(hh, cache->entries, entry, tmp_entry) {
			HASH_DELETE(hh, cache->entries, entry);
			if (cache->free_cb)
				cache->free_cb(entry->data);
			else
				free(entry->data);
			free(entry);
			break;
		}
	}
	rv = pthread_rwlock_unlock(&(cache->cache_lock));
	return rv;
err_out:
	if (entry)
		free(entry);
	(void)pthread_rwlock_unlock(&(cache->cache_lock));
	return rv;
}
int foo_cache_insert ( struct foo_cache * cache , char * key , void * data ) { struct foo_cache_entry * entry = NULL ; struct foo_cache_entry * tmp_entry = NULL ; size_t key_len = 0 ; int rv ; if ( ! cache || ! data ) return EINVAL ; if ( ( entry = malloc ( sizeof ( * entry ) ) ) == NULL ) return ENOMEM ; if ( ( rv = pthread_rwlock_wrlock ( & ( cache -> cache_lock ) ) ) != 0 ) goto err_out ; entry -> key = key ; entry -> data = data ; key_len = strnlen ( entry -> key , KEY_MAX_LENGTH ) ; HASH_ADD_KEYPTR ( hh , cache -> entries , entry -> key , key_len , entry ) ; if ( HASH_COUNT ( cache -> entries ) >= cache -> max_entries ) { HASH_ITER ( hh , cache -> entries , entry , tmp_entry ) { HASH_DELETE ( hh , cache -> entries , entry ) ; if ( cache -> free_cb ) cache -> free_cb ( entry -> data ) ; else free ( entry -> data ) ; free ( entry ) ; break ; } } rv = pthread_rwlock_unlock ( & ( cache -> cache_lock ) ) ; return rv ; err_out : if ( entry ) free ( entry ) ; ( void ) pthread_rwlock_unlock ( & ( cache -> cache_lock ) ) ; return rv ; }
Inserts a given <key, value> pair into the cache
Inserts a given <key value > pair into the cache
/* free(key->key) if data has been copied */