Merge pull request #4490 from Tetralux/fix-make-map-alloc

[runtime] `make(map[K]V)` should not allocate any capacity
This commit is contained in:
Jeroen van Rijn
2024-11-16 12:56:00 +01:00
committed by GitHub
2 changed files with 26 additions and 2 deletions
+2 -2
View File
@@ -388,7 +388,7 @@ _make_dynamic_array_len_cap :: proc(array: ^Raw_Dynamic_Array, size_of_elem, ali
//
// Note: Prefer using the procedure group `make`.
@(builtin, require_results)
make_map :: proc($T: typeid/map[$K]$E, allocator := context.allocator) -> (m: T) {
make_map :: proc($T: typeid/map[$K]$E, allocator := context.allocator, loc := #caller_location) -> (m: T) {
m.allocator = allocator
return m
}
@@ -399,7 +399,7 @@ make_map :: proc($T: typeid/map[$K]$E, allocator := context.allocator) -> (m: T)
//
// Note: Prefer using the procedure group `make`.
@(builtin, require_results)
make_map_cap :: proc($T: typeid/map[$K]$E, #any_int capacity: int = 1<<MAP_MIN_LOG2_CAPACITY, allocator := context.allocator, loc := #caller_location) -> (m: T, err: Allocator_Error) #optional_allocator_error {
make_map_cap :: proc($T: typeid/map[$K]$E, #any_int capacity: int, allocator := context.allocator, loc := #caller_location) -> (m: T, err: Allocator_Error) #optional_allocator_error {
make_map_expr_error_loc(loc, capacity)
context.allocator = allocator
+24
View File
@@ -39,4 +39,28 @@ test_temp_allocator_returns_correct_size :: proc(t: ^testing.T) {
bytes, err := mem.alloc_bytes(10, 16)
testing.expect(t, err == nil)
testing.expect(t, len(bytes) == 10)
}
@(test)
test_init_cap_map_dynarray :: proc(t: ^testing.T) {
m1 := make(map[int]string)
defer delete(m1)
testing.expect(t, cap(m1) == 0)
testing.expect(t, m1.allocator.procedure == context.allocator.procedure)
ally := context.temp_allocator
m2 := make(map[int]string, ally)
defer delete(m2)
testing.expect(t, cap(m2) == 0)
testing.expect(t, m2.allocator.procedure == ally.procedure)
d1 := make([dynamic]string)
defer delete(d1)
testing.expect(t, cap(d1) == 0)
testing.expect(t, d1.allocator.procedure == context.allocator.procedure)
d2 := make([dynamic]string, ally)
defer delete(d2)
testing.expect(t, cap(d2) == 0)
testing.expect(t, d2.allocator.procedure == ally.procedure)
}