aboutsummaryrefslogtreecommitdiff
path: root/src/libsok/sok-cache.c
blob: 748614e325305d4e845bf32ed09bfbf512a0f304 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdbool.h> // bool
#include <stdint.h> // uint64_t
#include <stdlib.h> // bsearch(), qsort()
#include "sok.h"

#define UNUSED(a) ((void) (a))
#define GROW_SIZE (4096 / sizeof(uint64_t))

static uint64_t
hash_ctx(
  const sok_ctx_t * const ctx
) {
  UNUSED(ctx);
  // TODO
  return 0;
}

static int
u64_cmp(
  const void * const ap, 
  const void * const bp
) {
  const uint64_t a = *((uint64_t*) ap),
                 b = *((uint64_t*) bp);

  return (a > b) ? -1 : ((a == b) ? 0 : 1);
}

static bool
sok_cache_grow(
  sok_cache_t * const cache
) {
  // calculate new capacity
  const size_t new_capacity = cache->capacity + GROW_SIZE;
  if (new_capacity < cache->capacity) {
    return false;
  }

  // reallocate memory
  uint64_t * const vals = realloc(cache->vals, new_capacity);
  if (!vals) {
    return false;
  }

  // update data
  cache->vals = vals;
  cache->capacity = new_capacity;

  // return success
  return true;
}

static bool
sok_cache_has_hash(
  const sok_cache_t * const cache,
  const uint64_t hash
) {
  return !!bsearch(
    &hash,
    cache->vals,
    cache->num_vals,
    sizeof(uint64_t),
    u64_cmp
  );
}

bool
sok_cache_has(
  const sok_cache_t * const cache,
  const sok_ctx_t * const ctx
) {
  return sok_cache_has_hash(cache, hash_ctx(ctx));
}

bool
sok_cache_add(
  sok_cache_t * const cache,
  const sok_ctx_t * const ctx
) {
  // hash context
  const uint64_t hash = hash_ctx(ctx);

  // check for duplicates
  if (sok_cache_has_hash(cache, hash)) {
    return true;
  }

  // check capacity
  if (cache->num_vals >= cache->capacity) {
    // grow cache
    if (!sok_cache_grow(cache)) {
      // return failure
      return false;
    }
  }

  // append hash, sort values
  cache->vals[cache->num_vals++] = hash_ctx(ctx);
  qsort(cache->vals, cache->num_vals, sizeof(uint64_t), u64_cmp);

  // return success
  return true;
}

bool
sok_cache_init(
  sok_cache_t * const cache,
  const size_t capacity
) {
  // alloc memory, check for error
  uint64_t * const vals = malloc(sizeof(uint64_t) * capacity);
  if (!vals) {
    // return failure
    return false;
  }

  // populate cache
  cache->vals = vals;
  cache->num_vals = 0;
  cache->capacity = capacity;

  // return success
  return true;
}

void
sok_cache_fini(
  sok_cache_t * const cache
) {
  if (cache->vals) {
    // free memory
    free(cache->vals);
    cache->vals = NULL;
  }
}