refactor and func -> proc rename
This commit is contained in:
@@ -3,7 +3,13 @@ import "@std/arraylist"
|
||||
import "@std/hashmap"
|
||||
import "@std/testing"
|
||||
|
||||
StringId :: alias usize
|
||||
# cross-cutting concern, hence global singleton (owned by main.hon)
|
||||
strings StringPool = undefined
|
||||
|
||||
InternError :: enum { out_of_space }
|
||||
|
||||
StringId :: alias u32
|
||||
NoId :: maxval!(StringId)
|
||||
|
||||
StringPool :: struct {
|
||||
ids hashmap.StringHashMap(StringId) # string → id
|
||||
@@ -11,7 +17,7 @@ StringPool :: struct {
|
||||
allocator mem.Allocator
|
||||
}
|
||||
|
||||
init func(allocator mem.Allocator) StringPool {
|
||||
init proc(allocator mem.Allocator) StringPool {
|
||||
return StringPool{
|
||||
ids = hashmap.init(allocator),
|
||||
strings = arraylist.init(allocator),
|
||||
@@ -19,7 +25,7 @@ init func(allocator mem.Allocator) StringPool {
|
||||
}
|
||||
}
|
||||
|
||||
deinit func(pool @mut StringPool) void {
|
||||
deinit proc(pool @mut StringPool) void {
|
||||
hashmap.deinit(&pool.ids)
|
||||
for pool.strings.items |str| {
|
||||
mem.free(pool.allocator, str)
|
||||
@@ -27,10 +33,12 @@ deinit func(pool @mut StringPool) void {
|
||||
arraylist.deinit(&pool.strings)
|
||||
}
|
||||
|
||||
intern func(pool @mut StringPool, str []u8) StringId ! mem.AllocError {
|
||||
intern proc(pool @mut StringPool, str []u8) StringId ! (mem.AllocError | InternError) {
|
||||
if hashmap.get(&pool.ids, str) |id| return id
|
||||
|
||||
id :: pool.strings.items.len
|
||||
if (pool.strings.items.len >= usize(NoId)) return .out_of_space
|
||||
id StringId :: StringId(pool.strings.items.len)
|
||||
|
||||
owned_str []mut u8 :: try mem.alloc(u8, pool.allocator, str.len)
|
||||
errdefer mem.free(pool.allocator, owned_str)
|
||||
memcopy!(owned_str, str)
|
||||
@@ -48,12 +56,12 @@ intern func(pool @mut StringPool, str []u8) StringId ! mem.AllocError {
|
||||
return id
|
||||
}
|
||||
|
||||
get_str func(pool @StringPool, id StringId) ?[]u8 {
|
||||
if (id >= pool.strings.items.len) return null
|
||||
return pool.strings.items[id]
|
||||
get_str proc(pool @StringPool, id StringId) ?[]u8 {
|
||||
if (usize(id) >= pool.strings.items.len) return null
|
||||
return pool.strings.items[usize(id)]
|
||||
}
|
||||
|
||||
get_id func(pool @StringPool, str []u8) ?StringId {
|
||||
get_id proc(pool @StringPool, str []u8) ?StringId {
|
||||
return hashmap.get(&pool.ids, str)
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user