How to create a static map?

I need a static mapping from strings to an enum. Something like this:

Thing :: enum {
  Thing_A,
  Thing_B,
  Thing_C,
}

names :: map[string]Thing{
  "thing a" = Thing_A,
  "thing b" = Thing_B,
  "thing c" = Thing_C,
}

which :: proc(n: string) -> Thing {
  return names[n]
}

The compiler complains about implicit allocations. There are no allocations, this thing can be completely in read-only memory. Do I have to build with #+feature dynamic-literals? Are there other ways to build fast mappings from strings to things?

I guess I can implement which as a switch on string literals. Will that be optimized in any way, or is it going to be a sequence of ifs?

map[string]Thing is just short-hand for make(map[string]Thing, context.allocator). Any function that takes an allocator is a hint that there will be an allocation happening, which in your case there is. And yes you will need to build with #+feature dynamic-literals if you want to do what you are doing as this is an opt in feature to make you acknowledge that you are implicitly allocating memory.

The best solution if you want no allocations is to make a switch statement. If you build with optimizations then it should be optimized into a jump table, although you would need to look at the assembly to confirm, as this is up to LLVM.

2 Likes

As an alternative, you can try the following (if that’s okay):

package main

import "core:fmt"

Thing :: enum {
  A,
  B,
  C,
}

Pair :: struct {
  key: string,
  value: Thing,
}

pairs :: [len(Thing)]Pair {
  {key = "thing a", value = Thing.A},
  {key = "thing b", value = Thing.B},
  {key = "thing c", value = Thing.C},
}

which :: proc(name: string) -> Thing {
  res: Thing
  for p in pairs {
    if p.key == name do res = p.value
  }
  return res
}

main :: proc() {
  name := "thing a"
  fmt.println("looking for name:", name)
  fmt.println("The result is:", which(name))
}

If I remember correctly, LLVM does have some tricks to optimize a switch on strings (e.g. jump table based on length). I’d just use the switch statement until (and unless) it becomes a problem (in which case you might want something custom anyway).

1 Like

@Nave55 The hope was that the compiler could bake a pre-built map into the executable. Unfortunately doesn’t work for variables even with @rodata, and constants have different semantics.

@mechodin That’s linear search. I’d like something faster.

@SaiMoen I guess I’ll stick to that. In fact it is not clear if a hash map would have any advantage over an optimized switch, even if baked into read-only data segment.