#copy and modify "string" in []u8 buffer with length

1 messages · Page 1 of 1 (latest)

zenith veldt
#

I'm learning Zig, coming from C# and TypeScript, but still have dusty C knowledge from the old days.
To get started, I want to write a small program that changes a few characters in a text file. This is read in line by line, each line being read into the same 1024 character buffer. For conversion I use a second buffer, in which the text line is copied character by character, changing some characters.
I have written the following function for this:

fn convLine(in_line: []const u8, out_line: []u8) !void { for (in_line, 0..) |_, i| { out_line[i] = switch (in_line[i]) { ',' => ';', '.' => ',', else => in_line[i], }; } //outline.len = in_line.len; // doesnt work }

The problem is that out_line.len is always the buffer size. Is the 0 termination byte not copied? Do I think too C-ish?

wispy light
#

The reason you get that error is because each function parameter is essentially declared as if it was like this:

const in_line: []const u8;
const out_line: []u8;

Thus, you cannot mutate the actual values themselves.

#

If you wanted this function to update the caller's slice that they passed, then you'd have to take *[]u8.
However, a generally less invasive approach is to simply return a usize, the number of bytes/elements that were written.

#

And then the caller is expected to do const part = my_buffer[0..return_value];.

#

If this was C, it would let you do that line you wrote, but it still wouldn't update the callsite.

#

You'd be mutating a function-local copy of the slice value in C, which would be a useless assignment in this case.

wispy light
wispy light
#

...or whathaveyou.

zenith veldt
#

I Don't actually get an error, when I print out out_line after invoking convLine(), there are always 1024 characters printed, the actual converted line followed by a lot of garbage.

#

const in_line: []const u8; const out_line: []u8;
is ok, because buffer addresses are const, just content is not in case of out_line

#

I think returning a subslice would be best, thank you

wispy light