Safe interval pointer [Was: Re: Perfect hashing for string switch]

BCS none at anon.com
Thu Jan 28 20:49:19 PST 2010


Hello bearophile,

> Matti Niemenmaa:
> 
>> Your test6 is invalid: it reads beyond the bounds of the given array.
>> For example with input "th", it will check whether the third
>> character is 'i'; but the length of the array is only 2, so it
>> shouldn't be doing that.
>> 
> Shame on me, I am sorry -.- Thank you. I will try to improve the code
> later.
> 
> The good thing is that D2 allows me to implement something to catch
> that kind of out-of-range pointer errors at run-time (D1 is not good
> enough here). 

Things I'd use in place of that:

/////
char[] str, int at = 0;
...
switch(str[at]) { ... }
...
at++;

or

/////
char[] str;
...
switch(str[0]) { ... }
...
str = str[1..$];

A good compiler should be able to convert the first to about the same as 
what your type should compile to. A really good compiler should be able to 
const propagate at and remove the variable and (if you start by switching 
on the length) fold out even the bounds checks.

The second has the same optimization potential but for some reason I think 
it would be expecting more of a compiler to get it optimized that well.

--

<IXOYE><






More information about the Digitalmars-d mailing list