Why can't stride be 0?

Stride is always positive. What bad would happen if it was zero for zero sized values?

Rust allows size = stride = 0; there are definitely both benefits and drawbacks. The main thing is you can no longer iterate an arbitrary buffer by incrementing a pointer until it reaches the end pointer. A bunch of low-level operations in Rust deal with this so higher-level code doesn’t need to think about it, but it does crop up from time to time.

3 Likes

Another difference between Swift and Rust is that Swift doesn't always monomorphize, so tolerating zero strides would incur an extra dynamic check on every unspecialized array iteration.

5 Likes

C++ (but not C) also enforces a minimum size of 1, and it doesn’t have any unspecialized generic code, fwiw.

What dynamic check? Is that in relation to what Jordan wrote? Could the loop be changed to always go by for i in ..< count instead of while pointer < stop { ... pointer++ }.

AFAIU for C++ it's important to maintain identity of elements, there it would be bad if &a[0] == &a[1]. Equally in Swift it would be bad for reference types to be of a stride 0, but that's impossible anyway (there are at one or two words of overhead in class bodies for ISA, etc).

Any Rust code that has to (re)allocate memory for an array of zero sized types has to special case for the zero size. An example is given in the Rustonomicon, but I'm sure you can find more in core/std's source code.

1 Like