key_value1.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. /*!
  2. \file key_value1.c
  3. \brief Key_Value management.
  4. (C) 2001-2008 by the GRASS Development Team
  5. This program is free software under the
  6. GNU General Public License (>=v2).
  7. Read the file COPYING that comes with GRASS
  8. for details.
  9. \author CERL
  10. */
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include <grass/gis.h>
  14. /*!
  15. \brief Allocate and initialize Key_Value structure
  16. \return poiter to allocated Key_Value structure
  17. */
  18. struct Key_Value *G_create_key_value(void)
  19. {
  20. struct Key_Value *kv = G_malloc(sizeof(struct Key_Value));
  21. kv->nitems = 0;
  22. kv->nalloc = 0;
  23. kv->key = NULL;
  24. kv->value = NULL;
  25. return kv;
  26. }
  27. /*!
  28. \brief Set value for given key
  29. \param[in] key key to be set up
  30. \param[in] value value for given key
  31. \param[in,out] kv Key_value structure to be modified
  32. */
  33. void G_set_key_value(const char *key, const char *value, struct Key_Value *kv)
  34. {
  35. int n;
  36. if (!key)
  37. return;
  38. for (n = 0; n < kv->nitems; n++)
  39. if (strcmp(key, kv->key[n]) == 0)
  40. break;
  41. if (n == kv->nitems) {
  42. if (n >= kv->nalloc) {
  43. size_t size;
  44. if (kv->nalloc <= 0)
  45. kv->nalloc = 8;
  46. else
  47. kv->nalloc *= 2;
  48. size = kv->nalloc * sizeof(char *);
  49. kv->key = G_realloc(kv->key, size);
  50. kv->value = G_realloc(kv->value, size);
  51. }
  52. kv->key[n] = G_store(key);
  53. kv->value[n] = G_store(value);
  54. kv->nitems++;
  55. return;
  56. }
  57. if (kv->value[n])
  58. G_free(kv->value[n]);
  59. kv->value[n] = value ? G_store(value) : NULL;
  60. }
  61. /*!
  62. \brief Find given key
  63. \param[in] key key to be found
  64. \param[in] kv Key_value structure
  65. \return poiter to value of key
  66. \return NULL if no key found
  67. */
  68. const char *G_find_key_value(const char *key, const struct Key_Value *kv)
  69. {
  70. int n;
  71. if (!kv)
  72. return NULL;
  73. for (n = 0; n < kv->nitems; n++)
  74. if (strcmp(key, kv->key[n]) == 0)
  75. return kv->value[n][0] ? kv->value[n] : NULL;
  76. return NULL;
  77. }
  78. /*!
  79. \brief Free allocated Key_Value structure
  80. \param[in] kv Key_Value structure
  81. \return
  82. */
  83. void G_free_key_value(struct Key_Value *kv)
  84. {
  85. int n;
  86. if (!kv)
  87. return;
  88. for (n = 0; n < kv->nitems; n++) {
  89. G_free(kv->key[n]);
  90. G_free(kv->value[n]);
  91. }
  92. G_free(kv->key);
  93. G_free(kv->value);
  94. kv->nitems = 0; /* just for safe measure */
  95. kv->nalloc = 0;
  96. G_free(kv);
  97. }