mie: name_map can now generate unique names when given no hints

This commit is contained in:
2025-04-11 14:12:53 +01:00
parent e379afb035
commit 7f0d8b87c5
3 changed files with 36 additions and 20 deletions

View File

@@ -31,6 +31,7 @@ struct mie_name_bucket {
struct mie_name_map {
b_btree m_entries;
size_t m_next_id;
};
extern struct mie_name_map *mie_name_map_create(void);

View File

@@ -128,27 +128,39 @@ struct mie_name *mie_name_map_put(
memset(entry, 0x0, sizeof *entry);
entry->n_base.e_type = MIE_NAME_MAP_E_NAME;
b_rope base = B_ROPE_CSTR(hint);
b_rope base = {};
if (hint) {
b_rope_init_cstr_borrowed(&base, hint);
}
char str[256];
/* first try just the hint on its own */
b_rope_to_cstr(&base, str, sizeof str);
entry->n_str = str;
entry->n_base.e_hash = base.r_v.v_cstr.hash;
b_status status = put_name(map, entry);
if (hint) {
/* first try just the hint on its own */
b_rope_to_cstr(&base, str, sizeof str);
entry->n_str = str;
entry->n_base.e_hash = base.r_v.v_cstr.hash;
b_status status = put_name(map, entry);
if (B_OK(status)) {
entry->n_str = b_strdup(str);
return entry;
if (B_OK(status)) {
entry->n_str = b_strdup(str);
return entry;
}
}
/* that name already exists, use a suffix to make the name unique. */
/* that name already exists, use a suffix to make the name unique.
* alternately, no hint was specified, so it's up to us to generate the name */
b_rope suffix = B_ROPE_UINT(0);
b_rope unique_name;
b_rope_concat(&unique_name, &base, &suffix);
for (unsigned int i = 0;; i++) {
size_t i = 0;
if (!hint || hint[0] == '\0') {
i = map->m_next_id++;
}
for (;; i++) {
suffix.r_v.v_uint = i;
b_rope_to_cstr(&unique_name, str, sizeof str);

View File

@@ -1,20 +1,23 @@
#include <mie/name.h>
#include <stdio.h>
#define NR_NAMES 6
int main(void)
{
struct mie_name_map *map = mie_name_map_create();
struct mie_name n1;
struct mie_name n2;
struct mie_name n3;
struct mie_name n[NR_NAMES] = {};
mie_name_map_put(map, &n1, "tmp");
mie_name_map_put(map, &n2, "tmp");
mie_name_map_put(map, &n3, "tmp");
mie_name_map_put(map, &n[0], "tmp");
mie_name_map_put(map, &n[1], "tmp");
mie_name_map_put(map, &n[2], "tmp");
mie_name_map_put(map, &n[3], NULL);
mie_name_map_put(map, &n[4], NULL);
mie_name_map_put(map, &n[5], NULL);
printf("%s\n", n1.n_str);
printf("%s\n", n2.n_str);
printf("%s\n", n3.n_str);
for (int i = 0; i < NR_NAMES; i++) {
printf("%s\n", n[i].n_str);
}
return 0;
}