zig icon indicating copy to clipboard operation
zig copied to clipboard

BoundedArray: add a len() function to get the length as a usize

Open jedisct1 opened this issue 2 years ago • 4 comments

The type of the active length was changed to the smallest possible type, which is nice to get a more compact representation.

However, that change introduced unexpected side effects. For example, a.len + b.len can now trigger an integer overflow.

There's also an inconsistency between functions that set the size, which all use a usize, and the way to read the size, that uses a different type. This is also inconsistent with pretty much anything else that represents a slice length.

Replace .len with len(), a function that returns the length as a usize to minimize surprise and simplify application code.

Originally suggested by @matklad

jedisct1 avatar Nov 22 '23 19:11 jedisct1

not sure this is worth is worth the complexity for the common case given that unless the whole array fits in less than 8 bytes there will be a massive amount of struct padding the usize can fit into

nektro avatar Nov 22 '23 20:11 nektro

oh the change i thought this was, it seems was made 5 months ago. my suggestion would be to make the .len field itself a usize

nektro avatar Nov 22 '23 20:11 nektro

oh the change i thought this was, it seems was made 5 months ago. my suggestion would be to make the .len field itself a usize

It used to be a usize. The change was made in #16299 .

Since the length is small, it can usually fit in 1 or 2 bytes. So, a handful bytes are frequently saved, especially when the element type is a u8.

jedisct1 avatar Nov 22 '23 22:11 jedisct1

I don't like this change. I think it's a bandage over a language design flaw and I'd rather treat the wound directly. I'd like to let this sit for the time being.

andrewrk avatar Jan 15 '24 02:01 andrewrk

This is the wrong solution to the problem. This will be resolved in one of two ways instead:

  • Reverting #16299, leaving users to do this size optimization themselves if necessary.
  • Accepting #3806

andrewrk avatar Aug 24 '24 05:08 andrewrk

I proceeded with the revert for the time being (85747b266aac8a2ff7fea4a4b18f722133544ad7).

andrewrk avatar Aug 24 '24 05:08 andrewrk