graph.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #include "graph.h"
  2. /**
  3. * Extern inline functions.
  4. */
  5. size_t LSUP_graph_size(LSUP_Graph *gr);
  6. size_t LSUP_graph_capacity(LSUP_Graph *gr);
  7. int
  8. LSUP_graph_init(
  9. LSUP_Graph *gr, size_t capacity, const LSUP_Term *uri,
  10. LSUP_store_type store_type)
  11. {
  12. if (uri->type != LSUP_TERM_URI)
  13. return -1;
  14. gr->uri = uri;
  15. gr->keys = LSUP_keyset_new(capacity, .75);
  16. switch (store_type ) {
  17. case LSUP_STORE_MEM:
  18. gr->idx = LSUP_index_new(gr->keys->capacity);
  19. break;
  20. case LSUP_STORE_MDB:
  21. // TODO
  22. default:
  23. return -1;
  24. }
  25. return 0;
  26. }
  27. LSUP_Graph *
  28. LSUP_graph_new(
  29. size_t capacity, const LSUP_Term *uri,
  30. LSUP_store_type store_type)
  31. {
  32. LSUP_Graph *gr;
  33. CRITICAL(gr = malloc(sizeof(LSUP_Graph)));
  34. LSUP_graph_init(gr, capacity, uri, store_type);
  35. return gr;
  36. }
  37. int
  38. LSUP_graph_add(LSUP_Graph *gr, LSUP_Triple data[], size_t data_size)
  39. {
  40. // TODO Decouple this and build interface for memory and MDB integration.
  41. // Resize all at once if needed.
  42. if (gr->keys->capacity < gr->keys->free_i + data_size)
  43. LSUP_keyset_resize(gr->keys, gr->keys->free_i + data_size);
  44. LSUP_SerTerm **sterms = malloc(
  45. sizeof(LSUP_SerTerm) * 3 * LSUP_keyset_size(gr->keys));
  46. for (size_t i = 0; i < data_size; i++) {
  47. LSUP_term_serialize(data[i].s, sterms[i]);
  48. LSUP_term_serialize(data[i].p, sterms[i] + 1);
  49. LSUP_term_serialize(data[i].o, sterms[i] + 2);
  50. LSUP_Key sk = LSUP_sterm_to_key(sterms[i]);
  51. LSUP_Key pk = LSUP_sterm_to_key(sterms[i] + 1);
  52. LSUP_Key ok = LSUP_sterm_to_key(sterms[i] + 2);
  53. // Add terms to index.
  54. LSUP_index_add_pair(gr->idx, sk, sterms[i]);
  55. LSUP_index_add_pair(gr->idx, pk, sterms[i] + 1);
  56. LSUP_index_add_pair(gr->idx, ok, sterms[i] + 2);
  57. // Add triple.
  58. LSUP_TripleKey trp = {sk, pk, ok};
  59. LSUP_keyset_add(gr->keys, &trp, LSUP_KS_CHECK_DUP);
  60. }
  61. return 0;
  62. }
  63. bool
  64. LSUP_graph_contains(const LSUP_Graph *gr, const LSUP_Triple *spo)
  65. {
  66. LSUP_Key sk = LSUP_term_to_key(spo->s);
  67. LSUP_Key pk = LSUP_term_to_key(spo->p);
  68. LSUP_Key ok = LSUP_term_to_key(spo->o);
  69. LSUP_TripleKey spok = {sk, pk, ok};
  70. return LSUP_keyset_contains(gr->keys, &spok);
  71. }
  72. void
  73. LSUP_graph_free(LSUP_Graph *gr)
  74. {
  75. if(LIKELY(gr != NULL)) {
  76. LSUP_keyset_free(gr->keys);
  77. LSUP_index_free(gr->idx);
  78. free(gr);
  79. }
  80. }