Add bring-your-own-buffer versions of os.lookup_env and os.get_env

And make `core:terminal` use it so that `core:log` can be imported with `-default-to-nil-allocator`,
in which the actual allocator is set up in `main()`.

Windows was tricky because of the utf-8 <> utf-16 conversion, so we use some temporary stack buffers for that purpose,
limiting the non-allocating version there to 512 utf-16 characters each for the key and environment value.

In general the value is (obviously) limited to the size of the supplied buffer, and a `.Buffer_Full` error is returned
if that buffer is insufficient. If the key is not found, the procedure returns `.Env_Var_Not_Found`.

TODO:
- Factor out buffer-backed utf8 + utf16 conversion to `core:sys/util` to more easily apply this pattern.
- Add similar `lookup_env` and `get_env` procedures to `core:os/os2`.

Fixes #5336
This commit is contained in:
Jeroen van Rijn
2025-06-16 20:12:26 +02:00
parent 1bd48df41f
commit 1a2f83f123
10 changed files with 266 additions and 30 deletions
+30 -2
View File
@@ -946,7 +946,7 @@ access :: proc(path: string, mask: int) -> (bool, Error) {
}
@(require_results)
lookup_env :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
lookup_env_alloc :: proc(key: string, allocator := context.allocator) -> (value: string, found: bool) {
runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD(ignore = context.temp_allocator == allocator)
path_str := strings.clone_to_cstring(key, context.temp_allocator)
// NOTE(tetra): Lifetime of 'cstr' is unclear, but _unix_free(cstr) segfaults.
@@ -958,11 +958,39 @@ lookup_env :: proc(key: string, allocator := context.allocator) -> (value: strin
}
@(require_results)
get_env :: proc(key: string, allocator := context.allocator) -> (value: string) {
lookup_env_buffer :: proc(buf: []u8, key: string) -> (value: string, err: Error) {
if len(key) + 1 > len(buf) {
return "", .Buffer_Full
} else {
copy(buf, key)
}
if value = string(_unix_getenv(cstring(raw_data(buf)))); value == "" {
return "", .Env_Var_Not_Found
} else {
if len(value) > len(buf) {
return "", .Buffer_Full
} else {
copy(buf, value)
return string(buf[:len(value)]), nil
}
}
}
lookup_env :: proc{lookup_env_alloc, lookup_env_buffer}
@(require_results)
get_env_alloc :: proc(key: string, allocator := context.allocator) -> (value: string) {
value, _ = lookup_env(key, allocator)
return
}
@(require_results)
get_env_buf :: proc(buf: []u8, key: string) -> (value: string) {
value, _ = lookup_env(buf, key)
return
}
get_env :: proc{get_env_alloc, get_env_buf}
set_env :: proc(key, value: string) -> Error {
runtime.DEFAULT_TEMP_ALLOCATOR_TEMP_GUARD()
key_cstring := strings.clone_to_cstring(key, context.temp_allocator)