env_posix.odin 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. //+private
  2. //+build darwin, netbsd, freebsd, openbsd
  3. package os2
  4. import "base:runtime"
  5. import "core:strings"
  6. import "core:sys/posix"
  7. _lookup_env :: proc(key: string, allocator: runtime.Allocator) -> (value: string, found: bool) {
  8. if key == "" {
  9. return
  10. }
  11. TEMP_ALLOCATOR_GUARD()
  12. ckey := strings.clone_to_cstring(key, temp_allocator())
  13. cval := posix.getenv(ckey)
  14. if cval == nil {
  15. return
  16. }
  17. found = true
  18. value = strings.clone(string(cval), allocator) // NOTE(laytan): what if allocation fails?
  19. return
  20. }
  21. _set_env :: proc(key, value: string) -> (ok: bool) {
  22. TEMP_ALLOCATOR_GUARD()
  23. ckey := strings.clone_to_cstring(key, temp_allocator())
  24. cval := strings.clone_to_cstring(key, temp_allocator())
  25. ok = posix.setenv(ckey, cval, true) == .OK
  26. return
  27. }
  28. _unset_env :: proc(key: string) -> (ok: bool) {
  29. TEMP_ALLOCATOR_GUARD()
  30. ckey := strings.clone_to_cstring(key, temp_allocator())
  31. ok = posix.unsetenv(ckey) == .OK
  32. return
  33. }
  34. // NOTE(laytan): clearing the env is weird, why would you ever do that?
  35. _clear_env :: proc() {
  36. for i, entry := 0, posix.environ[0]; entry != nil; i, entry = i+1, posix.environ[i] {
  37. key := strings.truncate_to_byte(string(entry), '=')
  38. _unset_env(key)
  39. }
  40. }
  41. _environ :: proc(allocator: runtime.Allocator) -> (environ: []string) {
  42. n := 0
  43. for entry := posix.environ[0]; entry != nil; n, entry = n+1, posix.environ[n] {}
  44. err: runtime.Allocator_Error
  45. if environ, err = make([]string, n, allocator); err != nil {
  46. // NOTE(laytan): is the environment empty or did allocation fail, how does the user know?
  47. return
  48. }
  49. for i, entry := 0, posix.environ[0]; entry != nil; i, entry = i+1, posix.environ[i] {
  50. if environ[i], err = strings.clone(string(entry), allocator); err != nil {
  51. // NOTE(laytan): is the entire environment returned or did allocation fail, how does the user know?
  52. return
  53. }
  54. }
  55. return
  56. }