Welcome to little lamb

Code » limb » release » tree

[release] / src / liblimb / hmap.h / hmap_set.c

/* This file is part of limb                           https://lila.oss/limb
 * Copyright (C) 2023 Olivier Brunel                          jjk@jjacky.com */
/* SPDX-License-Identifier: GPL-2.0-only */
#include <errno.h>
#include "hmap.h"

int
hmap_set(u32 key, void *data, hmap *hmap)
{
    struct item *it;

    it = lookup(key, hmap);
    if (!it->key) {
        /* should we grow? */
        if (1 + hmap->sa.len > hmap->sa.a - hmap->sa.a / 4) {
            if (!grow(2 * hmap->sa.len, hmap))
                return (errno = ENOMEM, 0);
            /* find possibly new location after growth */
            it = lookup(key, hmap);
        }
        ++hmap->sa.len;
    }

    it->key = key;
    memcpy(it->data, data, DLEN(hmap));

    return 1;
}