Range violation instead of empty slice on a[3 .. 2]

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 21 16:24:32 PST 2015


On Saturday, November 21, 2015 18:03:05 SimonN via Digitalmars-d-learn wrote:
>      string a = "hello";
>      string b = a[3 .. 2];
>
> I expect b to become an empty slice, because 3 is >= 2 already
> after 0 increments, making the slice length 0. Instead, the code
> throws a range violation.
>
> Expressions of this kind come up, e.g., when taking slices near
> the end of arrays, like "slice = a[b.length .. $];". To make this
> robust, I need an extra check for b.length > a.length, returning
> null in this case, otherwise a[b.length .. $].
>
> What's the design reason to prefer throwing over returning an
> empty slice?

The reason is that you're providing incorrect values. How does the runtime
know that you're not just providing it garbage values? D arrays are designed
with the requirement that you provide valid indices when indexing or slicing
them, and it's considered a logic bug to provide anything other than valid
indices in a valid order. If you want your code to use indices that are
invalid or which are in an invalid order, then you're going to have to
create a wrapper.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list