Skip to content

Commit

Permalink
chore: move toCString to utils.zig
Browse files Browse the repository at this point in the history
  • Loading branch information
Hanaasagi committed Jun 24, 2023
1 parent b9281c1 commit 648388a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
16 changes: 1 addition & 15 deletions src/loader.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const std = @import("std");
const testing = std.testing;
const parser = @import("./parser.zig");
const setenv = @import("./utils.zig").setenv;
const toCString = @import("./utils.zig").toCString;

const Error = error{
LineParseError,
Expand All @@ -13,21 +14,6 @@ pub const Options = struct {
override: bool = false,
};

// https://github.com/ziglang/zig/wiki/Zig-Newcomer-Programming-FAQs#converting-from-t-to-0t
fn toCString(str: []const u8) ![std.fs.MAX_PATH_BYTES - 1:0]u8 {
if (std.debug.runtime_safety) {
std.debug.assert(std.mem.indexOfScalar(u8, str, 0) == null);
}
var path_with_null: [std.fs.MAX_PATH_BYTES - 1:0]u8 = undefined;

if (str.len >= std.fs.MAX_PATH_BYTES) {
return error.NameTooLong;
}
@memcpy(path_with_null[0..str.len], str);
path_with_null[str.len] = 0;
return path_with_null;
}

pub const Loader = struct {
allocator: std.mem.Allocator,
parser: parser.LineParser,
Expand Down
15 changes: 15 additions & 0 deletions src/utils.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,21 @@ const testing = std.testing;
/// libc setenv
pub extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;

// https://github.com/ziglang/zig/wiki/Zig-Newcomer-Programming-FAQs#converting-from-t-to-0t
pub fn toCString(str: []const u8) ![std.fs.MAX_PATH_BYTES - 1:0]u8 {
if (std.debug.runtime_safety) {
std.debug.assert(std.mem.indexOfScalar(u8, str, 0) == null);
}
var path_with_null: [std.fs.MAX_PATH_BYTES - 1:0]u8 = undefined;

if (str.len >= std.fs.MAX_PATH_BYTES) {
return error.NameTooLong;
}
@memcpy(path_with_null[0..str.len], str);
path_with_null[str.len] = 0;
return path_with_null;
}

/// Default File name
const default_file_name = ".env";

Expand Down

0 comments on commit 648388a

Please sign in to comment.