key_value1.c 2.3 KB

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