Copy valid slice from zero-terminated u8 array slice

Is there a function like the following in the standard library?

return blk: {
    const eos_index = mem.indexOfSentinel(u8, 0, @ptrCast(&raw_name));
    if (eos_index <= 0) break :blk null;
    const _result = try allocator.alloc(u8, eos_index);
    @memcpy(_result, raw_name[0..eos_index]);
    break :blk _result;

Usually what I do is use std.mem.sliceTo() to get a slice of the given buffer, then allocator.dupe() it to make a copy that I own. There is also allocator.dupeZ(), I belive it appends a zero to the end and returns a sentinel terminated slice but I don’t think I’ve used it myself so I could be mistaken on that.


It feels better than writing it by myself, thanks :wink:

What’s wrong with using code that you wrote?

1 Like

8 lines vs 1 line; Which is more readable?

return try allocator.dupe(u8, std.mem.span(&raw_name));

My question was:

“What’s wrong with using code that you wrote?”


“What’s wrong with using the code that you wrote?”

1 Like

Safe bet that everyone here wants to use code that they wrote, that’s why we’re on a programming forum. :slight_smile:

Some reasons I prefer to use a standard library implementation of something, if it exists:

  • Maintenance burden. Code which I write, I have to look at, test, remember what it was for, and so on.
  • Reuse. I know that the next time I have to do the same thing, I can just use std again. Don’t have to copy-paste, make the implementation I used the first time public, toss it in a utility library, it’s just there.
  • Edge cases. Did I mention tests? Because if I write it, I write tests for it, and I want those to be robust for all expected inputs. Often this is more work than writing the code was to begin with. If it’s in std, I take it for granted that it has complete coverage.
  • Intent. It’s both easier for me to understand, and easier for other people who know Zig. If I forget what it was for, there’s documentation (which, again, I didn’t have to write) and I know where to find it.
  • Improvement. Maybe the testing suite didn’t catch every possible edge case and a bug is discovered. Zig’s still a moving target, maybe some language change made the original implementation invalid, so it needs to be updated. Maybe someone spotted a better way to do the same thing. I benefit from all of these things.

Lets me get back to doing what I wanted to be doing: using code I wrote.


My point was that there is nothing wrong with that code.
But there is a better alternative.

I think there’s a small misunderstanding here.

@Validark was asking about why they mentioned it felt better to use code written by someone else other than their own code more generally speaking. I don’t think he was talking about that specific code example.

Yes, I misunderstood the question.
Thanks @AndrewCodeDev for making that clear to me.

1 Like