/*
 * Copyright (c) 2020 C. Alexander Leigh, All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF ALEX LEIGH The copyright
 * notice above does not evidence any actual or intended publication of such
 * source code.
 *
 * Disclosure, copying, distribution, or transmission of this code without
 * express permission is prohibited.
 */

#include <assert.h>
#include "mecha.h"

/**
 * Initialize a new hash map.
 *
 * @author C. Alexander Leigh
 * @since mk6
 */
int mapFhash_init(struct mapShash *map, void (*destructor)(void *),
                  void (*name_destructor)(void *),
                  int (name_comparator)(const void *,
                                        const void *,
                                        size_t),
                  unsigned int buckets) {
    assert(map!=NULL);

    map->legacy = hshFvoid_raw_init(destructor, name_destructor, name_comparator, buckets);

    return 0;
}

/**
 * Free the storage related to this hash map.
 *
 * @author C. Alexander Leigh
 * @since mk6
 */
int mapFhash_free(struct mapShash *map) {
    hshFvoid_free(map->legacy);
    return 0;
}

/**
 * Set a value into the hash map. If the value already exists it is replaced. It is the responsibility of the
 * caller to arrange to store the size of the data if that is required.
 *
 * @author C. Alexander Leigh
 * @since mk6
 */
int mapFhash_set(struct mapShash *map, void *name, size_t name_len, void *data) {
    return hshFvoid_raw_add(map->legacy, name, name_len, data, 1);
}

/**
 * Get a value from the hash map.
 *
 * If a value is not found, then -1 is returned and data is unmodified.
 *
 * @author C. Alexander Leigh
 * @since mk6
 */
int mapFhash_get(void **data, struct mapShash *map, void *name, size_t name_len) {
    void *p = hshFvoid_raw_find(map->legacy, name, name_len);
    if(p!=NULL) {
        *data = p;
        return 0;
    }
    return -1;
}