[phobos] std.array.ilength
Steve Schveighoffer
schveiguy at yahoo.com
Thu Feb 17 08:04:45 PST 2011
The unsafe situations are extreme cases (arrays of more than 2 or 4 billion elements), so the risk is equally extremely low.
As David said also, the non-release version uses an assert to protect against unsafe usage.
Consider this as unsafe as array indexing, which is verified at runtime in non-release mode, and assumed correct in released mode.
And what's wrong with to!int is that it could error even in release mode, where you don't want extra runtime checks.
-Steve
----- Original Message -----
> From:Andrei Alexandrescu <andrei at erdani.com>
> To:Discuss the phobos library for D <phobos at puremagic.com>
> Cc:
> Sent:Thursday, February 17, 2011 9:14 AM
> Subject:Re: [phobos] std.array.ilength
>
> I'm not sure I see the improvement over a cast. If anything it makes
> everything more comfy and therefore riskier.
>
> What's wrong with to!int(arr.length)? It's safe too.
>
>
> Andrei
>
> On 2/17/11 7:59 AM, David Simcha wrote:
> > Hey guys,
> >
> > Kagamin just came up with a simple but great idea to mitigate the
> > pedantic nature of 64-bit to 32-bit integer conversions in cases where
> > using size_t doesn't cut it. Examples are storing arrays of indices
> into
> > other arrays, where using size_t would be a colossal waste of space if
> > it's safe to assume none of the arrays will be billions of elements
> long.
> >
> > int ilength(T)(T[] arr) {
> > assert(arr.length <= int.max);
> > return cast(int) arr.length;
> > }
> >
> > Usage:
> >
> > int[] indices;
> > auto array = returnsArray();
> > indices ~= array.ilength;
> >
> > This cuts down on the excessive verbosity of an explicit cast that's
> > safe 99.999 % of the time and encourages sprinkling it into code even if
> > for the foreseeable future it will be compiled in 32-bit mode.
> >
> > Two questions:
> >
> > 1. Is everyone ok with me adding this as a convenience function to
> > std.array?
> > 2. int or uint? I used int only b/c that was the example on the
> > newsgroup, but I think uint makes more sense.
> >
> > --David Simcha
> > _______________________________________________
> > phobos mailing list
> > phobos at puremagic.com
> > http://lists.puremagic.com/mailman/listinfo/phobos
> _______________________________________________
> phobos mailing list
> phobos at puremagic.com
> http://lists.puremagic.com/mailman/listinfo/phobos
More information about the phobos
mailing list