Parcourir la Source

Finally get how to convert strings!!

So it seems that `std.mem.trim` (and likely other functions) don't work
correctly on C strings, or don't work correctly if passed on and coerced
weirdly.

But what helps is converting to a regular zig string/slice using
`std.mem.sliceTo(c_string, 0)`.  It even makes sense, given that `0` is
the nul byte at the end of a c string.  Huh.

Oh, and we run Go thingy now!!
Luna Stadler 4 ans auparavant
Parent
commit
c431dadccc
1 fichiers modifiés avec 30 ajouts et 3 suppressions
  1. 30 3
      zig/sdl/hello_sdl.zig

+ 30 - 3
zig/sdl/hello_sdl.zig

@ -151,19 +151,46 @@ pub fn main() !void {
151 151
    }
152 152
}
153 153
154
fn runCommand(cmd: []const u8, allocator: *std.mem.Allocator) ?[*:0]u8 {
155
    const argv = &[_][]const u8{ "/usr/bin/qalc", "-terse", cmd };
154
fn runCommand(raw_cmd: []const u8, allocator: *std.mem.Allocator) ?[*:0]u8 {
155
    const cmd = std.mem.trim(u8, std.mem.sliceTo(raw_cmd, 0), &std.ascii.spaces);
156
    const argv = if (std.mem.startsWith(u8, cmd, "go "))
157
        &[_][]const u8{ "go", "doc", cmd[3..] }
158
    else
159
        &[_][]const u8{ "/usr/bin/qalc", "-terse", cmd };
160
    for (argv) |arg| {
161
        std.debug.print("'{s}' ", .{arg});
162
    }
156 163
    const result = std.ChildProcess.exec(.{ .allocator = allocator, .argv = argv }) catch |err| return "oopsie";
157 164
    const buf = allocator.allocSentinel(u8, 100, 0) catch |err| return "alloc";
158
    std.mem.copy(u8, buf, result.stdout);
165
    std.mem.copy(u8, buf, result.stdout[0..std.math.min(100, result.stdout.len)]);
159 166
    var i: usize = result.stdout.len;
160 167
    while (i < buf.len) : (i += 1) {
161 168
        buf[i] = ' ';
162 169
    }
163 170
    buf[buf.len - 1] = 0;
171
    std.debug.print("stderr: '{s}'\n", .{result.stderr});
164 172
    defer {
165 173
        allocator.free(result.stdout);
166 174
        allocator.free(result.stderr);
167 175
    }
168 176
    return buf;
169 177
}
178
179
// tests
180
181
test "trim []const u8" {
182
    const untrimmed: []const u8 = "   hey there   ";
183
    const trimmed = std.mem.trim(u8, untrimmed, &std.ascii.spaces);
184
    try std.testing.expect(trimmed.len < untrimmed.len);
185
    try std.testing.expect(trimmed.len == 9);
186
    try std.testing.expect(std.mem.eql(u8, trimmed, "hey there"));
187
}
188
189
test "trim [*:0]const u8" {
190
    const untrimmed: [*:0]const u8 = "   hey there   ";
191
    const to_trim: [*:0]const u8 = " ";
192
    const trimmed = std.mem.trim(u8, std.mem.sliceTo(untrimmed, 0), std.mem.sliceTo(to_trim, 0));
193
    try std.testing.expect(std.mem.len(trimmed) < std.mem.len(untrimmed));
194
    try std.testing.expect(trimmed.len == 9);
195
    try std.testing.expect(std.mem.eql(u8, trimmed, "hey there"));
196
}