1 #include "targetcache.h"
2 #include "target.h"
3 #include "stringmap.h"
4 #include "ml_macros.h"
5 #include <stdint.h>
6 #include <string.h>
7 #include <stdio.h>
8 #include <gc/gc.h>
9 #include <cache.h>
10 
11 static target_t **Cache;
12 static size_t CacheSize = 1;
13 
targetcache_init()14 void targetcache_init() {
15 	size_t InitialSize = cache_target_count();
16 	while (CacheSize < InitialSize) CacheSize *= 2;
17 	Cache = (target_t **)GC_MALLOC_IGNORE_OFF_PAGE(CacheSize * sizeof(target_t *));
18 }
19 
targetcache_index(size_t Index)20 target_id_slot targetcache_index(size_t Index) {
21 	if (Index >= CacheSize) {
22 		size_t NewCacheSize = CacheSize;
23 		do NewCacheSize *= 2; while (Index >= NewCacheSize);
24 		Cache = (target_t **)GC_REALLOC(Cache, NewCacheSize * sizeof(target_t *));
25 		CacheSize = NewCacheSize;
26 	}
27 	target_t *Target = Cache[Index];
28 	const char *Id = Target ? Target->Id : cache_target_index_to_id(Index);
29 	return (target_id_slot){Cache + Index, Id};
30 }
31 
targetcache_insert(const char * Id)32 target_index_slot targetcache_insert(const char *Id) {
33 	size_t Index = cache_target_id_to_index(Id);
34 	if (Index >= CacheSize) {
35 		size_t NewCacheSize = CacheSize * 2;
36 		do NewCacheSize *= 2; while (Index >= NewCacheSize);
37 		Cache = (target_t **)GC_REALLOC(Cache, NewCacheSize * sizeof(target_t *));
38 		CacheSize = NewCacheSize;
39 	}
40 	return (target_index_slot){Cache + Index, Index};
41 }
42 
targetcache_search(const char * Id)43 target_index_slot targetcache_search(const char *Id) {
44 	size_t Index = cache_target_id_to_index_existing(Id);
45 	if (Index == INVALID_TARGET) return (target_index_slot){NULL, Index};
46 	if (Index >= CacheSize) {
47 		size_t NewCacheSize = CacheSize * 2;
48 		do NewCacheSize *= 2; while (Index >= NewCacheSize);
49 		Cache = (target_t **)GC_REALLOC(Cache, NewCacheSize * sizeof(target_t *));
50 		CacheSize = NewCacheSize;
51 	}
52 	return (target_index_slot){Cache + Index, Index};
53 }
54