aboutsummaryrefslogtreecommitdiff
path: root/src/references.c
blob: 84cb773b132fa1567dc6291919ca2a0dbf231a3a (plain)
  1. #include "stmd.h"
  2. #include "utf8.h"
  3. #include "references.h"
  4. static unsigned int
  5. refhash(const unsigned char *link_ref)
  6. {
  7. unsigned int hash = 0;
  8. while (*link_ref)
  9. hash = (*link_ref++) + (hash << 6) + (hash << 16) - hash;
  10. return hash;
  11. }
  12. static void reference_free(reference *ref)
  13. {
  14. free(ref->label);
  15. free(ref->url);
  16. free(ref->title);
  17. free(ref);
  18. }
  19. // normalize reference: collapse internal whitespace to single space,
  20. // remove leading/trailing whitespace, case fold
  21. static unsigned char *normalize_reference(chunk *ref)
  22. {
  23. strbuf normalized = GH_BUF_INIT;
  24. utf8proc_case_fold(&normalized, ref->data, ref->len);
  25. strbuf_trim(&normalized);
  26. strbuf_normalize_whitespace(&normalized);
  27. return strbuf_detach(&normalized);
  28. }
  29. static void add_reference(reference_map *map, reference* ref)
  30. {
  31. reference *t = ref->next = map->table[ref->hash % REFMAP_SIZE];
  32. while (t) {
  33. if (t->hash == ref->hash &&
  34. !strcmp((char *)t->label, (char *)ref->label)) {
  35. reference_free(ref);
  36. return;
  37. }
  38. t = t->next;
  39. }
  40. map->table[ref->hash % REFMAP_SIZE] = ref;
  41. }
  42. extern reference *reference_create(reference_map *map, chunk *label, chunk *url, chunk *title)
  43. {
  44. reference *ref;
  45. ref = malloc(sizeof(reference));
  46. ref->label = normalize_reference(label);
  47. ref->hash = refhash(ref->label);
  48. ref->url = clean_url(url);
  49. ref->title = clean_title(title);
  50. ref->next = NULL;
  51. add_reference(map, ref);
  52. return ref;
  53. }
  54. // Returns reference if refmap contains a reference with matching
  55. // label, otherwise NULL.
  56. reference* reference_lookup(reference_map *map, chunk *label)
  57. {
  58. reference *ref = NULL;
  59. unsigned char *norm;
  60. unsigned int hash;
  61. if (map == NULL)
  62. return NULL;
  63. norm = normalize_reference(label);
  64. hash = refhash(norm);
  65. ref = map->table[hash % REFMAP_SIZE];
  66. while (ref) {
  67. if (ref->hash == hash &&
  68. !strcmp((char *)ref->label, (char *)norm))
  69. break;
  70. ref = ref->next;
  71. }
  72. free(norm);
  73. return ref;
  74. }
  75. void reference_map_free(reference_map *map)
  76. {
  77. unsigned int i;
  78. for (i = 0; i < REFMAP_SIZE; ++i) {
  79. reference *ref = map->table[i];
  80. reference *next;
  81. while (ref) {
  82. next = ref->next;
  83. reference_free(ref);
  84. ref = next;
  85. }
  86. }
  87. free(map);
  88. }
  89. reference_map *reference_map_new(void)
  90. {
  91. reference_map *map = malloc(sizeof(reference_map));
  92. memset(map, 0x0, sizeof(reference_map));
  93. return map;
  94. }