View mode: basic / threaded / horizontal-split · Log in · Help
March 30, 2005
array length is an unsigned value
Here is trap for young players ...

int find(dchar[] ToScan, dchar[] ToFind)
{
 for( int lPos = 0; lPos <= (ToScan.length - ToFind.length); lPos++)
   {
       if (ToScan[lPos .. lPos + ToFind.length] == ToFind)
           return lPos;
   }
   return -1;
}


See the bug? Neither did I until I tested it with ...

 assert( find("xxx", "abcdef") == -1);

The problem is that the expression ("xxx".length - "abcdef".length) is
*not* a negative number. And thus it failed to exit the 'for' loop cleanly;
instead it crashed with an ArrayBoundsError! 

So now I've got ...

int find(dchar[] ToScan, dchar[] ToFind)
{
   if (ToScan.length == 0)
       return -1;

   if (ToFind.length == 0)
       return -1;

   if (ToFind.length > ToScan.length)
       return -1;

   for( int lPos = 0; lPos <= (ToScan.length - ToFind.length); lPos++)
   {
       if (ToScan[lPos .. lPos + ToFind.length] == ToFind)
           return lPos;
   }
   return -1;
}

Oh well, live and learn.

-- 
Derek Parnell
Melbourne, Australia
http://www.dsource.org/projects/build/
http://www.prowiki.org/wiki4d/wiki.cgi?FrontPage
30/03/2005 10:34:52 AM
Top | Discussion index | About this forum | D home