intern.odin 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package strings
  2. import "core:mem"
  3. Intern_Entry :: struct {
  4. len: int,
  5. str: [1]byte, // string is allocated inline with the entry to keep allocations simple
  6. }
  7. Intern :: struct {
  8. allocator: mem.Allocator,
  9. entries: map[string]^Intern_Entry,
  10. }
  11. intern_init :: proc(m: ^Intern, allocator := context.allocator, map_allocator := context.allocator) {
  12. m.allocator = allocator
  13. m.entries = make(map[string]^Intern_Entry, 16, map_allocator)
  14. }
  15. intern_destroy :: proc(m: ^Intern) {
  16. for _, value in m.entries {
  17. free(value, m.allocator)
  18. }
  19. delete(m.entries)
  20. }
  21. intern_get :: proc(m: ^Intern, text: string) -> string {
  22. entry := _intern_get_entry(m, text)
  23. #no_bounds_check return string(entry.str[:entry.len])
  24. }
  25. intern_get_cstring :: proc(m: ^Intern, text: string) -> cstring {
  26. entry := _intern_get_entry(m, text)
  27. return cstring(&entry.str[0])
  28. }
  29. _intern_get_entry :: proc(m: ^Intern, text: string) -> ^Intern_Entry #no_bounds_check {
  30. if prev, ok := m.entries[text]; ok {
  31. return prev
  32. }
  33. if m.allocator.procedure == nil {
  34. m.allocator = context.allocator
  35. }
  36. entry_size := int(offset_of(Intern_Entry, str)) + len(text) + 1
  37. new_entry := (^Intern_Entry)(mem.alloc(entry_size, align_of(Intern_Entry), m.allocator))
  38. new_entry.len = len(text)
  39. copy(new_entry.str[:new_entry.len], text)
  40. new_entry.str[new_entry.len] = 0
  41. key := string(new_entry.str[:new_entry.len])
  42. m.entries[key] = new_entry
  43. return new_entry
  44. }