util.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2002-2005 Roman Zippel <zippel@linux-m68k.org>
  4. * Copyright (C) 2002-2005 Sam Ravnborg <sam@ravnborg.org>
  5. */
  6. #include <stdarg.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <hash.h>
  10. #include <hashtable.h>
  11. #include <xalloc.h>
  12. #include "lkc.h"
  13. /* hash table of all parsed Kconfig files */
  14. static HASHTABLE_DEFINE(file_hashtable, 1U << 11);
  15. struct file {
  16. struct hlist_node node;
  17. char name[];
  18. };
  19. /* file already present in list? If not add it */
  20. const char *file_lookup(const char *name)
  21. {
  22. struct file *file;
  23. size_t len;
  24. int hash = hash_str(name);
  25. hash_for_each_possible(file_hashtable, file, node, hash)
  26. if (!strcmp(name, file->name))
  27. return file->name;
  28. len = strlen(name);
  29. file = xmalloc(sizeof(*file) + len + 1);
  30. memset(file, 0, sizeof(*file));
  31. memcpy(file->name, name, len);
  32. file->name[len] = '\0';
  33. hash_add(file_hashtable, &file->node, hash);
  34. str_printf(&autoconf_cmd, "\t%s \\\n", name);
  35. return file->name;
  36. }
  37. /* Allocate initial growable string */
  38. struct gstr str_new(void)
  39. {
  40. struct gstr gs;
  41. gs.s = xmalloc(sizeof(char) * 64);
  42. gs.len = 64;
  43. gs.max_width = 0;
  44. strcpy(gs.s, "\0");
  45. return gs;
  46. }
  47. /* Free storage for growable string */
  48. void str_free(struct gstr *gs)
  49. {
  50. free(gs->s);
  51. gs->s = NULL;
  52. gs->len = 0;
  53. }
  54. /* Append to growable string */
  55. void str_append(struct gstr *gs, const char *s)
  56. {
  57. size_t l;
  58. if (s) {
  59. l = strlen(gs->s) + strlen(s) + 1;
  60. if (l > gs->len) {
  61. gs->s = xrealloc(gs->s, l);
  62. gs->len = l;
  63. }
  64. strcat(gs->s, s);
  65. }
  66. }
  67. /* Append printf formatted string to growable string */
  68. void str_printf(struct gstr *gs, const char *fmt, ...)
  69. {
  70. va_list ap;
  71. char s[10000]; /* big enough... */
  72. va_start(ap, fmt);
  73. vsnprintf(s, sizeof(s), fmt, ap);
  74. str_append(gs, s);
  75. va_end(ap);
  76. }
  77. /* Retrieve value of growable string */
  78. char *str_get(const struct gstr *gs)
  79. {
  80. return gs->s;
  81. }