Cthulhu  0.2.10
Cthulhu compiler collection
optimal.c
Go to the documentation of this file.
1 // SPDX-License-Identifier: LGPL-3.0-only
2 
3 #include "std/map.h"
4 
5 #include "arena/arena.h"
6 
7 #include <stdint.h>
8 
9 static const size_t kSizeAnchors[] = {
10  10, 100, 1000,
11  10000, 50000, 100000,
12  250000, 500000, 750000, 1000000
13 };
14 
15 #define TOTAL_SIZE_ANCHORS (sizeof(kSizeAnchors) / sizeof(size_t))
16 
18 static size_t bucket_for_size(size_t size)
19 {
20  switch (size)
21  {
22  case 10:
23  return 5;
24  case 100:
25  return 31;
26  case 1000:
27  return 2203;
28  case 10000:
29  return 21701;
30 
31  case 50000:
32  case 100000:
33  case 250000:
34  case 500000:
35  return 216091;
36 
37  case 750000:
38  case 1000000:
39  return 756839;
40 
41  default:
42  return 2203;
43  }
44 }
45 
46 static size_t signed_abs(size_t lhs, size_t rhs)
47 {
48  if (rhs > lhs)
49  {
50  return rhs - lhs;
51  }
52  return lhs - rhs;
53 }
54 
55 static size_t nearest_const(size_t size)
56 {
57  size_t num = 0;
58  size_t distance = SIZE_MAX;
59 
60  for (size_t i = 0; i < TOTAL_SIZE_ANCHORS; i++)
61  {
62  size_t d = signed_abs(size, kSizeAnchors[i]);
63  if (d < distance)
64  {
65  distance = d;
66  num = kSizeAnchors[i];
67  }
68  else
69  {
70  break;
71  }
72  }
73 
74  return num;
75 }
76 
77 static size_t select_best_size(size_t size)
78 {
79  size_t near = nearest_const(size);
80  size_t bucket = bucket_for_size(near);
81  return bucket;
82 }
83 
85 map_t *map_optimal(size_t size, hash_info_t info, arena_t *arena)
86 {
87  size_t bucket = select_best_size(size);
88  return map_new(bucket, info, arena);
89 }
CT_NODISCARD size_t size
Definition: scan.h:128
#define STA_DECL
sal2 annotation on function implementations to copy annotations from the declaration
STA_DECL map_t * map_optimal(size_t size, hash_info_t info, arena_t *arena)
create a new map with an optimal size
Definition: optimal.c:85
CT_NODISCARD CT_STD_API map_t * map_new(size_t size, hash_info_t info, arena_t *arena)
create a new map on the heap
Definition: map.c:113
#define TOTAL_SIZE_ANCHORS
Definition: optimal.c:15
an allocator object
Definition: arena.h:86
information for using a type in a hashset or hashmap
Definition: typeinfo.h:39
an unordered hash map
Definition: map.h:38