From f4cd3cd10428af1a248c3a8bfe7b99332f072fbf Mon Sep 17 00:00:00 2001 From: Steven Date: Thu, 22 Jan 2026 22:57:14 +0000 Subject: feat: New std library "env" for accessing the process environment --- examples/process/env.zc | 60 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 examples/process/env.zc (limited to 'examples/process/env.zc') diff --git a/examples/process/env.zc b/examples/process/env.zc new file mode 100644 index 0000000..8b30de3 --- /dev/null +++ b/examples/process/env.zc @@ -0,0 +1,60 @@ +//> cflags: -Ofast + +import "std/env.zc" + +fn main() -> int { + // ---- + // get: Retrieves the env-var as borrowed string (char *) (no alloc) + // --- + // @Example usage: On Linux (and some variants) PATH is already defined. + // --- + var path = Env::get("PATH"); + + if (path.is_some()) { + println "PATH is: {path.unwrap()}"; + } else { + println "PATH is not set"; + } + + // ---- + // set: Sets an env-var variable + // get_dup: Retrieves the env-var as caller-owned String() (heap alloc) + // --- + // @Example usage: In your terminal type "export HELLO=world" or use Env::set() + // --- + var res = Env::set("HELLO", "world"); + //=> check res against EnvRes::OK() + + var hello = Env::get_dup("HELLO"); + + if (hello.is_some()) { + var hello_str = hello.unwrap(); + defer hello_str.free(); + + println "HELLO is: {hello_str.c_str()}"; + } else { + println "HELLO is not set"; + } + + // ---- + // set_overwrite: Overwrites an exisiting env-var / creates it if it doesn't exist + // --- + Env::set_overwrite("HELLO", "world-overwritten"); + + var hello_now = Env::get("HELLO"); + + if (hello_now.is_some()) { + println "HELLO is now {hello_now.unwrap()}"; + } + + // ---- + // unset: Unsets an existing env-var + // --- + Env::unset("HELLO"); + + var hello_now2 = Env::get("HELLO"); + + if (hello_now2.is_none()) { + println "HELLO is now unset"; + } +} -- cgit v1.2.3