Commit bf827d0b55

Mathew R Gordon <72643694+mgord9518@users.noreply.github.com>
2023-07-17 12:57:41
std: Make getenv return 0-terminated slice
1 parent 9abe392
Changed files (1)
lib
std
lib/std/os.zig
@@ -1908,15 +1908,16 @@ pub fn execvpeZ(
 
 /// Get an environment variable.
 /// See also `getenvZ`.
-pub fn getenv(key: []const u8) ?[]const u8 {
+pub fn getenv(key: []const u8) ?[:0]const u8 {
     if (builtin.link_libc) {
+        // Append null byte to the key to use with cstd getenv
         var small_key_buf: [64]u8 = undefined;
         if (key.len < small_key_buf.len) {
             @memcpy(small_key_buf[0..key.len], key);
             small_key_buf[key.len] = 0;
-            const key0 = small_key_buf[0..key.len :0];
-            return getenvZ(key0);
+            return getenvZ(small_key_buf[0..key.len :0]);
         }
+
         // Search the entire `environ` because we don't have a null terminated pointer.
         var ptr = std.c.environ;
         while (ptr[0]) |line| : (ptr += 1) {
@@ -1926,11 +1927,7 @@ pub fn getenv(key: []const u8) ?[]const u8 {
 
             if (!mem.eql(u8, this_key, key)) continue;
 
-            var end_i: usize = line_i;
-            while (line[end_i] != 0) : (end_i += 1) {}
-            const value = line[line_i + 1 .. end_i];
-
-            return value;
+            return mem.sliceTo(line + line_i + 1, 0);
         }
         return null;
     }
@@ -1946,18 +1943,14 @@ pub fn getenv(key: []const u8) ?[]const u8 {
         const this_key = ptr[0..line_i];
         if (!mem.eql(u8, key, this_key)) continue;
 
-        var end_i: usize = line_i;
-        while (ptr[end_i] != 0) : (end_i += 1) {}
-        const this_value = ptr[line_i + 1 .. end_i];
-
-        return this_value;
+        return mem.sliceTo(ptr + line_i + 1, 0);
     }
     return null;
 }
 
 /// Get an environment variable with a null-terminated name.
 /// See also `getenv`.
-pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
+pub fn getenvZ(key: [*:0]const u8) ?[:0]const u8 {
     if (builtin.link_libc) {
         const value = system.getenv(key) orelse return null;
         return mem.sliceTo(value, 0);