authorgravatar for 72643694+mgord9518@users.noreply.github.comMathew R Gordon <72643694+mgord9518@users.noreply.github.com> 2023-07-17 04:57:41-06:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-07-17 10:57:41+00:00
logbf827d0b555df47ad2a2ea2062e2c855255c74d1
tree14ac3d27c4d09c1fe45e5167d531d7e042ae01b4
parent9abe39264724934f3d3f657912d5ac62d97c26a8
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std: Make getenv return 0-terminated slice


1 files changed, 7 insertions(+), 14 deletions(-)

lib/std/os.zig+7-14
......@@ -1908,15 +1908,16 @@ pub fn execvpeZ(
19081908
19091909/// Get an environment variable.
19101910/// See also `getenvZ`.
1911pub fn getenv(key: []const u8) ?[]const u8 {
1911pub fn getenv(key: []const u8) ?[:0]const u8 {
19121912 if (builtin.link_libc) {
1913 // Append null byte to the key to use with cstd getenv
19131914 var small_key_buf: [64]u8 = undefined;
19141915 if (key.len < small_key_buf.len) {
19151916 @memcpy(small_key_buf[0..key.len], key);
19161917 small_key_buf[key.len] = 0;
1917 const key0 = small_key_buf[0..key.len :0];
1918 return getenvZ(key0);
1918 return getenvZ(small_key_buf[0..key.len :0]);
19191919 }
1920
19201921 // Search the entire `environ` because we don't have a null terminated pointer.
19211922 var ptr = std.c.environ;
19221923 while (ptr[0]) |line| : (ptr += 1) {
......@@ -1926,11 +1927,7 @@ pub fn getenv(key: []const u8) ?[]const u8 {
19261927
19271928 if (!mem.eql(u8, this_key, key)) continue;
19281929
1929 var end_i: usize = line_i;
1930 while (line[end_i] != 0) : (end_i += 1) {}
1931 const value = line[line_i + 1 .. end_i];
1932
1933 return value;
1930 return mem.sliceTo(line + line_i + 1, 0);
19341931 }
19351932 return null;
19361933 }
......@@ -1946,18 +1943,14 @@ pub fn getenv(key: []const u8) ?[]const u8 {
19461943 const this_key = ptr[0..line_i];
19471944 if (!mem.eql(u8, key, this_key)) continue;
19481945
1949 var end_i: usize = line_i;
1950 while (ptr[end_i] != 0) : (end_i += 1) {}
1951 const this_value = ptr[line_i + 1 .. end_i];
1952
1953 return this_value;
1946 return mem.sliceTo(ptr + line_i + 1, 0);
19541947 }
19551948 return null;
19561949}
19571950
19581951/// Get an environment variable with a null-terminated name.
19591952/// See also `getenv`.
1960pub fn getenvZ(key: [*:0]const u8) ?[]const u8 {
1953pub fn getenvZ(key: [*:0]const u8) ?[:0]const u8 {
19611954 if (builtin.link_libc) {
19621955 const value = system.getenv(key) orelse return null;
19631956 return mem.sliceTo(value, 0);