Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Range#size returns an Union instead of an Int32 #14587

Open
hutou opened this issue May 13, 2024 · 1 comment · May be fixed by #14588
Open

Range#size returns an Union instead of an Int32 #14587

hutou opened this issue May 13, 2024 · 1 comment · May be fixed by #14588

Comments

@hutou
Copy link
Contributor

hutou commented May 13, 2024

The following snippet:

range = 1_u8..5_u8
size = range.size
p! typeof(size)

returns

typeof(size) # => (Int32 | UInt8)

instead of the expected

typeof(size) # => Int32

@straight-shoota
Copy link
Member

straight-shoota commented May 24, 2024

Quoting PR comments to bring the general discussion back here:

@straight-shoota #14588 (comment)

Hm, actually this can overflow on ranges of Int types that are bigger than Int32 🤔
Should we only cast to Int32 on smaller types?

@beta-ziliani #14588 (comment)

I'm afraid there's no good solution here. The good part of raising on overflow is that if it fits, it works. The bad part is that the failure is at runtime...

An alternative, as good or bad, is to statically fail on > Int32 types and have people do the math themselves 🤷

That's also not good because (0_u128..1_u128).size is perfectly valid 🤷

I think casting to Int32 is fine. If you use bigger number types, it will raise but that's ok. The implementation with - for Int types is just an optimization. The base implementation of Enumerable#size would iterate all the items and thus eventually overflow the counter if the difference is more than Int32 can handle.
The type of #size for all collection types is Int32 because it's meant for collections that can be feasibly represented in memory.

We'll eventually need to increase that size type in order to support bigger collections. But while Int64 should be entirely sufficient for the use case related to actual memory storage (e.g. Slice#size), Range#size is not materialized and can reach arbitrary scales (with BigInt etc.).

#size is simply not meant for this.

I think we should explain that caveat explicitly in the API docs and that's it. #size returns Int32 and if it doesn't fit, it will raise.

We should however consider adding an alternative method that unconditionally returns range.end - range.begin.
This would even be much more versatile because it would work not just with Int but any type that implements subtraction (e.g. 0_f32..1_f32, Time.utc..Time.utc).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants