Re: Copying string slices before calling subroutines?



On Fri, 04 May 2007 23:27:57 +0100, Simon Wright wrote:

My reworking begins

function Index
(Source : String;
Pattern : String;
Going : Ada.Strings.Direction := Ada.Strings.Forward;
Mapping : Ada.Strings.Maps.Character_Mapping
:= Ada.Strings.Maps.Identity) return Natural
is
Cur_Index : Natural;
Potential_Match : Boolean;
use Ada.Strings;
use Ada.Strings.Maps;
begin
if Pattern = "" then
raise Pattern_Error;
end if;

-- Forwards case

if Going = Forward then
for J in 1 .. Source'Length - Pattern'Length + 1 loop
Cur_Index := Source'First + J - 1;
Potential_Match := True;
for K in Pattern'Range loop
if Pattern (K) /=
Value (Mapping, Source (Cur_Index + K - 1)) then
Potential_Match := False;
exit;
end if;
end loop;
if Potential_Match then
return Cur_Index;
end if;
end loop;

which calls Ada.Strings.Maps.Value rather more often than I suppose it
could.

You can save remapping of Source, just there is no need to do it in advance
and allocate a full copy of Source. Instead of that, you make a ring buffer
of mod Pattern'Length where you store Value (Mapping, Source (i)). Once you
advance the main string index you "rotate" the buffer.

Then Pattern'Length = 1 should be a special case, as well as identity
mapping. Though, I don't know how efficient the latter could be.

--
Regards,
Dmitry A. Kazakov
http://www.dmitry-kazakov.de
.



Relevant Pages