[futurebasic] Re: [FB] Whyfor this thou behavior? (FB5 vs FB4)

Message: < previous - next > : Reply : Subscribe : Cleanse
Home   : April 2010 : Group Archive : Group : All Groups

From: Robert Purves <listrp@...>
Date: Sun, 25 Apr 2010 19:04:02 +1200
Robert Covington wrote:

>>> In FB5, instr() converts its arguments to C strings, then calls strstr() to do the heavy lifting. It therefore mis-handles strings that contain chr$( 0 ), because strstr() understands a zero byte to indicate the end of the string.
>> 
>> That's not quite accurate. In the conversion to C strings, null characters are changed to chr$( 1 ).
>> The effect is that
>>  foundPos = instr( startPos, haystack, needle )
>> fails only when haystack or needle contain both 0 and 1 characters.
> 
> Is it repairable?


Certainly. Bernie has provided a CFString method that works but is rather slow. 
Best would be a new instr() function that does a simple character search. 
That should be faster even than the existing instr().

List members are invited to write fn instr_new() in plain FB; see below.
The C translation of the winning entry -- if there is one -- would then become the new PSinstr() in build_goodies/General.c (after some minor adjustments).
The sanity tests should screen out most of the Really Buggy Horrors.

Robert P.

'----------
local fn instr_new( startPos as long, haystack as Str255, needle as Str255 )
dim as long foundPos : foundPos = 0

foundPos = instr( startPos, haystack, needle ) // your code here
end fn = foundPos


// sanity tests for instr_new()
dim as Str255 need, hay
dim as long i, j, k 
dim as long a(3)
a(0) = 0
a(1) = 1
a(2) = 10
a(3) = 255

for i = 0 to 3
need = string$( a(i), _"X" )
for j = 0 to 3
hay = string$( a(j), _"X" )
for k = 0 to 3
long if ( instr( a(k), hay, need ) != fn instr_new( a(k), hay, need ) )
print a(k), hay, need : stop
end if
next

hay = "aaaa" + hay
for k = 0 to 3
long if ( instr( a(k), hay, need ) != fn instr_new( a(k), hay, need ) )
print a(k), hay, need : stop
end if
next
next
next
'----------