Ranges longer than size_t.max
Stewart Gordon
smjg_1998 at yahoo.com
Sat Dec 29 12:59:37 PST 2012
On 29/12/2012 01:18, Peter Alexander wrote:
> There was a discussion a while ago about the type returned by .length
> for ranges. I believe the conclusion was that it should always be size_t.
>
> My question now is what to do with really large ranges? For example, if
> we have a range of permutations of the elements in a set, when the set
> is larger than 21 the number of permutations is 21 factorial, which is
> over 2^64. As far as I see, there are three options:
They look like four to me.
> 1. Allow ranges to return BigInt for length.
> 2. Allow ranges like this but assert when .length overflows.
> 3. Allow ranges like this and just allow .length to overflow dangerously.
> 4. Do not allow ranges like this.
<snip>
5. Don't allow such ranges to define a .length property.
From the std.range documentation:
template hasLength(R)
Returns true if R has a length member that returns an integral
type. R does not have to be a range. Note that length is an optional
primitive as no range must implement it. Some ranges do not store their
length explicitly, some cannot compute it without actually exhausting
the range (e.g. socket streams), and some other ranges may be infinite.
There you go. For reasons such as this, ranges aren't required to
define a length property. As well as I/O ranges and infinite ranges,
ranges where the length is liable to be greater than ulong.max are among
those that naturally won't have this property.
If we define a length that may overflow, then sooner or later some code
will be called on it that calls hasLength on the range, finds it to be
true, and then relies on length and malfunctions because the value
returned doesn't match the actual length.
Stewart.
More information about the Digitalmars-d
mailing list