From: Masatake YAMATO Date: Fri, 7 May 2021 16:50:20 +0000 (+0900) Subject: lsfd: introduce name_manager X-Git-Tag: v2.38-rc1~144^2~142 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=5179d5282499319ca4e2888ffe425b2b17869491;p=thirdparty%2Futil-linux.git lsfd: introduce name_manager Signed-off-by: Masatake YAMATO --- diff --git a/misc-utils/lsfd.c b/misc-utils/lsfd.c index 17a426f9d5..cc6adc78ff 100644 --- a/misc-utils/lsfd.c +++ b/misc-utils/lsfd.c @@ -1003,6 +1003,76 @@ int main(int argc, char *argv[]) return 0; } +struct name_manager { + struct idcache *cache; + pthread_rwlock_t rwlock; + unsigned long next_id; +}; + +struct name_manager *new_name_manager(void) +{ + struct name_manager *nm = xcalloc(1, sizeof(struct name_manager)); + nm->cache = new_idcache(); + if (!nm->cache) + err(EXIT_FAILURE, _("failed to allocate an idcache")); + + pthread_rwlock_init(&nm->rwlock, NULL); + nm->next_id = 1; /* 0 is never issued as id. */ + return nm; +} + +void free_name_manager(struct name_manager *nm) +{ + free_idcache(nm->cache); + free(nm); +} + +const char *get_name(struct name_manager *nm, unsigned long id) +{ + struct identry *e; + + pthread_rwlock_rdlock(&nm->rwlock); + e = get_id(nm->cache, id); + pthread_rwlock_unlock(&nm->rwlock); + + return e? e->name: NULL; +} + +unsigned long add_name(struct name_manager *nm, const char *name) +{ + struct identry *e = NULL, *tmp; + + pthread_rwlock_rdlock(&nm->rwlock); + for (tmp = nm->cache->ent; tmp; tmp = tmp->next) { + if (strcmp(tmp->name, name) == 0) { + e = tmp; + break; + } + } + pthread_rwlock_unlock(&nm->rwlock); + if (e) + return e->id; + + pthread_rwlock_wrlock(&nm->rwlock); + for (tmp = nm->cache->ent; tmp; tmp = tmp->next) { + if (strcmp(tmp->name, name) == 0) { + e = tmp; + break; + } + } + + if (!e) { + e = xmalloc(sizeof(struct identry)); + e->name = xstrdup(name); + e->id = nm->next_id++; + e->next = nm->cache->ent; + nm->cache->ent = e; + } + pthread_rwlock_unlock(&nm->rwlock); + + return e->id; +} + DIR *opendirf(const char *format, ...) { va_list ap; diff --git a/misc-utils/lsfd.h b/misc-utils/lsfd.h index 7862973adb..c800e38f59 100644 --- a/misc-utils/lsfd.h +++ b/misc-utils/lsfd.h @@ -148,4 +148,14 @@ struct file *make_sock(const struct file_class *class, struct file *make_unkn(const struct file_class *class, struct stat *sb, const char *name, int fd); +/* + * Name managing + */ +struct name_manager; + +struct name_manager *new_name_manager(void); +void free_name_manager(struct name_manager *nm); +const char *get_name(struct name_manager *nm, unsigned long id); +unsigned long add_name(struct name_manager *nm, const char *name); + #endif /* UTIL_LINUX_LSFD_H */