Unbounded slice of many pointer vs pointer arithmetic

Why does Zig allow an unbounded slice of a many pointer, when it appears to be the same as many pointer arithmetic?

    var many_ptr: [*]const u8 = &[2]u8{1, 2};
    @compileLog(@TypeOf(many_ptr + 1)); // [*]const u8
    @compileLog(@TypeOf(many_ptr[1..])); // [*]const u8

I think bounded slicing producing e.g. *[n]u8 is justified, because the result has a length, and it implicitly converts to a []u8 slice. But why allow unbounded slice syntax for a many pointer when it doesn’t actually do any slicing?

Welcome to the forum!


Because you should be able to change the start of a multi-item pointer.
Yes, you could use pointer arithmetic for that, as you’ve described, but at least for me the slicing syntax is much more idiomatic as one also often uses it for slices and arrays.
In general you are always able to do an unbounded(or implicitly bounded) slice [start..]. Even on single-item pointers I think, though I’m currently unable to check. Disallowing this just for many-item pointers makes it both harder for the programmer and the parser.

Thanks for your reply.

It may have become an idiom in Zig, but does unbounded slicing really fit the concept of slicing if the result doesn’t have a length? Are there any other languages where slicing produces something without a length?

In general you are always able to do an unbounded(or implicitly bounded) slice [start..]. Even on single-item pointers I think,

The Zig playground (0.17.0) says it is an error:

    var i: u8 = 1;
    many_ptr = (&i)[0..]; // error: slice of single-item pointer must be bounded

Disallowing this just for many-item pointers makes it both harder for the programmer and the parser.

I agree it might well need existing code to be updated, but why is pointer arithmetic harder for the programmer or parser - it’s less tokens.

First a heads-up: You will see many-item pointers rarely when programming with Zig because you still need to somehow identify how many items you have: either via a length, which gives you a slice(ptr+len), or using a sentinel(often 0), like it is often done in C, or via having some side-channel(and even in that case a slice is mostly used).
Therefore many-item pointers are mostly used when interacting with some C-API or API that was designed with C in mind(like how argv and envp are passed to a process in posix) or when the bounds check introduced for a slice is to costly(which is rarely the case and needs precise benchmarking).
Internally a slice is basically just a many-item pointer and a length(not thinking about types, alignment and stuff):

const Slice = struct {
    ptr: [*]u8,
    len: usize,
};

For me it fits. A many-item pointer points to some location in memory where some unknown number of things are. And slicing is just creating a contiguous “subview” of some other view into memory, which may be explicitly bounded by giving it a length like a slice or array, or implicitly via some sentinel, side-channel or even nothing for a multi-item pointer.

That point was more about disallowing the [start..] syntax for many-item pointers. It would be harder to remember that you can slice single-item pointers(if the bounds are known at comptime), arrays and slices(both with an open end). But not multi-item pointers because for those you use pointer arithmetic. That’s just inconsistent and awkward.
I’m also not arguing to remove the pointer arithmetic syntax(though that could simplify the syntax a bit while not loosing that much) because it is sometimes easier to read though not by much.

I think unbounded slice makes sense for example it allows to chain multiple slicing operations like: many_ptr[offset..][0..2]

I think (many_ptr + offset)[0..2] isn’t as nice.

And because slicing offsets/ranges only work in the positive direction pointer arithmetic is still required for negative offsets.

Also sometimes generic code can be written in an agnostic way towards whether it is operating on a slice or a multi-item-pointer, if you disallow the syntax for multi-item-pointers they no longer can be sub-sliced like slices can be and you would needlessly have to special case the code.

There also could be cases where you only want to allow positive offsets which is what is guaranteed by using the subslicing syntax.

1 Like

It would be harder to remember that you can slice single-item pointers(if the bounds are known at comptime),

A slice of a single-item pointer must have compile-time bounds which evaluate to [0..0], [0..1], or [1..1]. Each of those produces *[n]T, which has a defined len.

arrays and slices(both with an open end). But not multi-item pointers because for those you use pointer arithmetic. That’s just inconsistent and awkward.

Arrays and slices have len, a many-item pointer does not. A slice expression that produces something with an unknown number of elements is inconsistent to me.

I’m also not arguing to remove the pointer arithmetic syntax(though that could simplify the syntax a bit

Well we also have pointer-pointer subtraction, so programmers would still need to be aware of that arithmetic. Having pointer-integer addition matches what the machine code is doing for many-item pointer unbounded slicing.

I think (many_ptr + offset)[0..2] isn’t as nice.

Fair point. I think it’s OK.

because slicing offsets/ranges only work in the positive direction pointer arithmetic is still required for negative offsets

Interesting point, so because unbounded slicing requires an unsigned integer, it can’t express many_ptr - offset.

generic code can be written in an agnostic way towards whether it is operating on a slice or a multi-item-pointer

OK, but practically wouldn’t that generic code need to somehow know that the many-item pointer has at least n elements? In which case, how can that code have the same interface as code that accepts a slice? Wouldn’t that tend to be bad practice to write generic code which intentionally supports using a many-item pointer without any debug checks to prevent buffer overflow?

cases where you only want to allow positive offsets which is what is guaranteed by using the subslicing syntax

That’s the same use case as many_ptr + offset, as offset must be unsigned. (many_ptr - offset requires offset to be unsigned too).

This could be specified in documentation, similar to how how for many writer or reader functions and implementations the buffer needs to have at least a specific minimum size.
In some cases even a single-item pointer or array could be passed if the bounds done by the generic code are established at comptime. Notice how all those pointer types and also arrays are often able to be coerced quite easily into one another which makes generic code quite possible. If it’s desirable is another question though the option is there.

Sometimes you know that a buffer overflow isn’t possible. So why should it generally be disallowed?

An unbounded slice of a single-item pointer is illegal. An array, yes.

Sometimes you know that a buffer overflow isn’t possible. So why should it generally be disallowed?

I was thinking about a generic function in a library. It isn’t possible for a function taking either a slice or a many-item pointer as a parameter to know that the many-item pointer can be sliced without bounds.

Perhaps there are other ways a generic function can obtain a many-item pointer through an expression when the author can know there are a certain minimum number of elements. However it is too likely that generic code would accidentally silently compile with a many-item pointer in cases when it actually should not, and there is no way for the compiler to tell the difference. And in those cases a bounded slice would often be better. So even the generic code argument for unbounded slicing falls down.

I do not see how they are similar. Writers and readers assert the size of the buffer while many-pointer can only assume the size. You can overflow it and the compiler will not help you with safety checks.

/// The compiler may or may not add safety checks
/// depending on the type of `string`.
fn substitute(string: anytype, word: []const u8) void {
    @memcpy(string[0..word.len], word);
}

test "many-pointer does not trigger safety check" {
    var array = "Runtime crashes are better than bugs. Edge cases matter.".*;
    const buffer = array[0..37];
    var ptr: [*]u8 = buffer;
    ptr += 32;

    substitute(ptr, "insects"); // does not panic. buffer overflow.

    const expected = "Runtime crashes are better than insects. Edge cases matter.";
    try std.testing.expectEqualStrings(expected, &array);
}

test "slice triggers runtime safety check" {
    var array = "Runtime crashes are better than bugs. Edge cases matter.".*;
    const buffer = array[0..37];
    var slice: []u8 = buffer;
    slice = slice[32..];

    substitute(slice, "insects"); // panics.

    const expected = "Runtime crashes are better than insects. Edge cases matter.";
    try std.testing.expectEqualStrings(expected, &array);
}

Documentation of readers and writers works in concert with safety checks. Many-pointer with safety checks has a name. It is slice.

Yes.

1 Like

I’m not advocating for using many-item pointers in many places or situations(pun intended). I was just saying that the option is there. I think one should generally use a slice when possible even when one has the length available via other means or uses a sentinel.

But if one needs the semantics, for interacting with a C API for example, or needs the performance, because one has done measurements, many-item pointers are there.

See for instance the implementation of the hashmap in the standard library.

many-item pointers are like the lower-level building block from which you can construct slice like things:

  • add a length and check it and you constructed your own slice
  • have n many-item-pointers plus a length for all of them you have something like a table (e.g. std.MultiArrayList.Slice)

They don’t need to be as safe as slices, they serve a different purpose, if you are worried about them, build a safe API with bounds checks around them and use that.

If your code just needs one length or even some static lower bound (for example enforced through logical invariants or asserts and testing) then using many-item-pointers halves the amount of needed memory compared to slices.

Especially in the case of many parallel pointers / slices, it saves you from redundantly passing / storing the same length.

Zig isn’t a theorem proving software, if the programmer knows what is going on they can decide what should and should not be possible, it is their responsibility to construct the rules of what will result in compile time, testing, or run-time error, so which errors are impossible to produce and which ones can happen through misuse and then document how the function is supposed to be used.

So write your own checks or construct the invariants such that it isn’t misused. I would rather have the opportunity to construct an incorrect program then be prevented from constructing correct ones that the compiler isn’t able to prove correct.

If you don’t like the syntax fine that is your opinion, I disagree, because I like the syntax, the ability to chain, and having this lower level building block.

It effectively allows you to refine the lower bound while leaving the upper bound undetermined until you actually have one. Basically I think in most cases code will eventually transform multi-item-pointers to something that either is a slice or is similar to one, but sometimes you need to deal with partial data where you don’t yet know (or don’t care about) the total size of the thing at the end.

If the function is never being called in a context where it could fail, then passing around an artificial upper bound that has no real use doesn’t make sense to me. You even could program such a function using exactly this unbounded syntax so you can call it in debug with a slice to have a version where the test code uses slices passed in from the caller, to ensure that all the invariants hold and then you can use multi-item-pointer for the release version that doesn’t carry around redundant bounds checks.

4 Likes

My point is that unbounded slicing of a many-item pointer is a redundant feature (due to pointer addition), and it causes a worse problem than it solves with generic code. Generic code that does unbounded slicing (and is tested with a slice or array type) is very likely not intended to work with a many-item pointer, so it would be better if Zig did not support unbounded slicing of a many-item pointer. Any generic code which is intended to work with many-item pointers can special case them, that is not a big price to pay for making plenty of bug-prone code fail to compile.

Suppose as you mentioned, you replace a slice type for a variable in your code with a many-item pointer. The generic call on it compiles, but can silently introduce undefined behaviour.

1 Like

(Devils-advocate)

So are many other things:

  • enums are just integers
  • unions is just casting in a trenchcoat
  • structs are just byte offsets
  • substraction is just addition of a negative: 1 - 1 = 1 + -1
  • slices are just a many-item pointer and a length
  • a pointer is just an integer
  • everything is just bytes
  • …

I find those things helpful and so is slicing and unbounded slicing of many-item pointers. Yes technically it’s redundant but that’s not the point. It’s consistent with how one slices other things like slices and that’s what matters to me. Zig isn’t about minimality and it shouldn’t be.

2 Likes

I don’t understand why you would make the code generic, when you aren’t intending to support it, in that case just write non-generic code and use a slice type, what do I misunderstand here?

2 Likes

A many-item pointer is slice with an infinite length.

It’s just a silly idea I had, but the semantics make sense:

fn example(ptr: [*]u8) void {
    const a: [] = ptr[10..20]; // len = 20 - 10
    const b: [*] = ptr[10..];  // which is equivalent to...
    const c: [*] = ptr[10..∞]; // len = ∞ - 10, which is still ∞
}

Since the len cannot change except when replaced by a wholly different value, the compiler can elide it completely and thus avoid having to allocate (infinite) memory to store it.

From this perspective, ptr + 10 is the weird redundant feature. More generally, pointer arithmetic is something you only need for wacky tricks like storing data behind an object (e.g. the way Fil-C stores capabilities for pointers-at-rest).

P.S. I use both forms, depending on which is more natural:

  • Slicing syntax automatically accounts for the size of the underlying object, which is more convenient for objects that are not u8.
  • Pointer arithmetic is easier to think about when dealing with low-level, type-erased buffers and such.
1 Like