Substring Record

type Substring = record

A UTF-16 string for local variables, designed for allocation-free string operations that scale linearly with the thread count.

With 8 threads, one per core, each thread keeps 0.86 to 0.99 of its single-thread speed (string: 0.07). On one thread the operations run on average 2.2 times as fast as string's (geometric mean over 271 operations, 233 at least as fast).

Case: Ascii, Invariant, Linguistic

A routine that ignores or maps case says how by a suffix. Ascii folds A to Z only, with no operating system call (ToUpperAscii, CompareAscii, ContainsAscii). Invariant uses the operating system's case table, the same under every locale (ToUpperInvariant, CompareInvariant, ContainsInvariant); its upper and lower case round trip, Linguistic's do not. Linguistic follows the default locale or a LocaleID: it ignores soft hyphens, matches decomposed and composed accents and expands the sharp s to ss (ToUpperLinguistic, CompareLinguistic, ContainsLinguistic). Without a suffix a routine compares by code unit; Replace refuses rfIgnoreCase with ESubstringCaseError.

Which to use:

  • No suffix: exact, no case conversion, the fastest: identifiers, keys, tokens, text a program writes and reads itself.
  • Ascii: A to Z folded, close to that speed (1.2 to 3.2 times its time): keywords of formats and protocols.
  • Invariant: as the operating system compares names: file names, paths, environment variables, registry keys, names programs exchange.
  • Linguistic: as a word processor treats text: words written by and for people.

Against the Ascii routines, on text that differs in case, the Invariant ones run 2.3 to 46 times slower and the Linguistic ones 4.5 to 149 times (Win64, AVX2, en-US, texts of 30 to 512 characters); the factor grows with the length the routine reads, and each routine's Note states its own. With 8 threads the routines keep 0.93 to 1.00 of their single-thread speed while each thread's data fits L2 (1 MB).

Rules of use

  • A Substring is a local variable, a parameter or a function result: never an element of an array or a container, a global, a threadvar or a field.
  • Keep a Substring in the thread that made it; hand another thread a string (ToString) or a view (Subrange).
  • Indices are 0-based: s[0] is the first character. The free functions (Pos, PosEx, LeftStr, IsDelimiter, ...), Subrange, GetSubstring and Index take 1-based positions.
  • Every index and count is range checked; a failed check raises ESubstringRangeError.
  • Conversions are explicit: Substring('text') copies a string in, ToString copies the text out. A text parameter also takes a string, a Char, a WideString or a PChar, read without a conversion; an AnsiString, UTF8String, RawByteString or ShortString argument raises ESubstringEncodingError. The compiler types a one-character literal from #$80 to #$FF as an AnsiChar, so #$E9 alone raises too: write Char(#$E9).
  • List Substr before System.SysUtils in uses. Call IntToStr, FloatToStr, StringOfChar and BoolToStr qualified: Substr.IntToStr(5).

Allocation-free loops

Reserve room before a loop with Capacity or Resize; inside it the operations take no memory. While testing, set SubstringAllocCheck to True: memory taken outside Capacity and Resize then raises ESubstringAllocError.

Loops over the characters

s[i] reads one character in place. For a loop over many characters at a string's speed, pass s.Data and s.Length to a routine that declares no Substring. Data is not terminated; ToPChar gives a terminated text.

Examples

Summing the fields of a line: the tokenizer moves a window over the text, so no field is copied.

delphi
uses Substr;

procedure Example;
var Line: Substring;
    Sum: Integer;
begin
    Line := Substring('12,30,-2,60');
    Sum := 0;
    if Line.FirstDelimitedText(',') then
        repeat
            Sum := Sum + Line.ToInteger;
        until not Line.NextDelimitedText(',');
    Assert(Sum = 100);
end;

Building a line in reserved room, checked to take no memory inside the loop.

delphi
uses Substr;

procedure Example;
var Line: Substring;
    k: Integer;
begin
    Line.Capacity := 1000;
    SubstringAllocCheck := True;
    try
        for k := 1 to 100 do
        begin
            Line.AppendInt(k);
            Line.Append(';');
        end;
    finally
        SubstringAllocCheck := False;
    end;
    Assert(Line.StartsWith('1;2;3;'));
    Assert(Line.Length = 292);
end;

Reading every character: the loop runs in a routine of its own, given Data and Length.

delphi
uses Substr;

procedure Example;

    function SumOfChars(const P: PChar; const Len: Integer): Integer;
    var j: Integer;
    begin
        Result := 0;
        for j := 0 to Len - 1 do
            Result := Result + Ord(P[j]);
    end;

var s: Substring;
begin
    s := Substring('abc');
    Assert(SumOfChars(s.Data, s.Length) = 294);
end;

Constructors

NameDescription
CreateA view of Src, as Adopt: the window covers Src's characters, which are not copied.

Properties

NameTypeDescription
CapacityIntegerThe characters the string holds without taking more memory.
DataPCharThe window's first character, not terminated: ToPChar gives a C string.
DefaultArrayWideCharThe character at Indx, 0-based.
IndexIntegerThe 1-based start of the window in the underlying text.
IsBorrowedBooleanWhether the text is another thread's long text, read where it is.
IsCachelessBooleanWhether the characters are in memory from the memory manager rather than the thread's block cache: a TSubstringList item longer than the inline storage, or what shares or grows from one.
IsExternalBooleanWhether the characters belong to another value: an adopted string, or a short Substring viewed by Subrange.
IsInlineBooleanWhether the text is held inside the variable.
LengthIntegerThe number of characters in the window, read-only.

Methods

NameDescription
AdoptViews all of Src's characters without copying them.
Append (4)Appends S after the text, in place.
AppendIntAppends the decimal digits of Value.
CheckIndexRaises ESubstringRangeError unless Indx is inside the window.
ClearMakes the string empty and releases its memory.
Compare (6)Compares Length characters of StrA from IndexA with Length characters of StrB from IndexB, ordinal.
CompareAscii (2)Compares StrA with StrB, or Length characters of each from IndexA and IndexB (0-based), by UTF-16 code unit; IgnoreCase True folds 'a'..'z' to upper case.
CompareInvariant (2)Compares StrA with StrB, or Length characters of each from IndexA and IndexB (0-based), by UTF-16 code unit; IgnoreCase True ignores case by the operating system's uppercase table, the same under every locale.
CompareLinguistic (12)Compares StrA with StrB in the sort order of the default locale or of LocaleID, with the options or IgnoreCase given.
CompareTo (2)Compares the text with strB, ordinal.
Contains (2)Whether S occurs in the text, ordinal.
ContainsAsciiWhether the text contains Value, ignoring case when IgnoreCase is True for A to Z only: A to Z and a to z match each other, every other character only itself; ordinal when it is False.
ContainsInvariantWhether the text contains Value by UTF-16 code unit; IgnoreCase True ignores case by the operating system's uppercase table, the same under every locale.
ContainsLinguistic (2)Whether the text contains Value by the rules of the default locale or of LocaleID; IgnoreCase True ignores case.
Copy (2)The whole of Str as a Substring.
CopyToCopies Count characters from SourceIndex into Destination at DestinationIndex.
CountCharThe number of occurrences of C in the window.
Create (3)A new value: Count times C, the characters of Value, or Length characters of Value from StartIndex.
DeQuotedStringQuotedString undone: for a text quoted at both ends, the text inside, every doubled QuoteChar single (a lone one dropped).
EndsWith (2)Whether the text ends with S, ordinal.
EndsWithAsciiWhether the text ends with Value, ignoring case when IgnoreCase is True for A to Z only: A to Z and a to z match each other, every other character only itself; ordinal when it is False.
EndsWithInvariantWhether the text ends with Value by UTF-16 code unit; IgnoreCase True ignores case by the operating system's uppercase table, the same under every locale.
EndsWithLinguistic (2)Whether the text ends with Value by the rules of the default locale or of LocaleID; IgnoreCase True ignores case.
Equals (5)Ordinal equality, as =; the class forms compare a Substring with any text kind, in either order.
FirstDelimitedTextThe tokenizer: puts the window on the text's first field.
FirstWordMoves the window to the first space-delimited word.
FlushThreadCacheReturns the memory the calling thread keeps for reuse to the memory manager.
Format (2)The format text with Args written into it.
GetHashCodeA hash of the window's characters, equal to the hash of a string with the same characters.
IndexOf (5)The 0-based index of the first occurrence of S at or after StartIndex.
IndexOfAny (2)The 0-based index of the first character that is one of AnyOf, from StartIndex to the end or for Count characters.
IndexOfAnyUnquoted (2)The 0-based index of the first character that is one of AnyOf outside StartQuote ... EndQuote.
IndexOfEitherThe 0-based index of the first character that is C1 or C2; -1 when there is none.
Insert (2)A copy of this string with S inserted at StartIndex; this string is unchanged.
IsDelimiterWhether the character at Index (0-based) is one of Delimiters.
IsEmptyWhether the window holds no character.
IsNullOrEmpty (6)Whether Value is empty, for every text kind.
IsNullOrWhiteSpace (6)Whether Value is empty or every character is <= ' ', for every text kind.
Join (5)The items of List with Separator between them: Join over a TSubstringList.
LastDelimiter (2)The 0-based index of the last character that is one of Delims, -1 when there is none.
LastIndexOf (7)The 0-based index of the last occurrence of S.
LastIndexOfAny (3)The 0-based index of the last character that is one of AnyOf, in the text, in [0, StartIndex], or in the Count characters that end at StartIndex.
LowerCaseAsciiMaps the window's ASCII letters to lower case, in place.
MakeUniqueGives the string its own copy of its characters, shared with no other string.
MidCount characters from StartIndex (0-based), both inside the text, else ESubstringRangeError is raised.
NextDelimitedTextThe tokenizer: moves the window to the next field.
NextWordMoves the window to the next space-delimited word.
PadLeftThe text padded on the left with PaddingChar to TotalWidth characters.
PadRightThe text padded on the right with PaddingChar to TotalWidth characters.
Parse (8)The text of a Double as FloatToStr writes it, its 15 significant digits correctly rounded, held inline.
Pos (2)The 1-based position of SubStr's first occurrence at or after OneOffset, 0 if none.
QuotedStringThe text in QuoteChar, every QuoteChar inside doubled.
Remove (2)This string without Count characters at StartIndex, or without everything from StartIndex; this string is unchanged.
Replace (3)Every non-overlapping occurrence of OldPattern replaced by NewPattern, left to right, ordinal.
ReplaceAsciiReplace's rules, with rfIgnoreCase ignoring ASCII case only: A to Z and a to z match each other, every other character, non-ASCII ones included, matches only itself.
ReplaceInvariantReplaces OldPattern by NewPattern by UTF-16 code unit: the first occurrence, or every occurrence with rfReplaceAll; rfIgnoreCase ignores case by the operating system's uppercase table, the same under every locale.
ReplaceLinguistic (2)Replaces OldPattern by NewPattern, found by the rules of the default locale or of LocaleID: the first occurrence, or every occurrence with rfReplaceAll; rfIgnoreCase ignores case.
ResizeRoom for aLen characters, keeping the first aLen characters.
Split (18)Splits the text into List at the separators: List is cleared, then each part is added.
StartsWith (2)Whether the text starts with S, ordinal.
StartsWithAsciiWhether the text starts with Value, ignoring case when IgnoreCase is True for A to Z only: A to Z and a to z match each other, every other character only itself; ordinal when it is False.
StartsWithInvariantWhether the text starts with Value by UTF-16 code unit; IgnoreCase True ignores case by the operating system's uppercase table, the same under every locale.
StartsWithLinguistic (2)Whether the text starts with Value by the rules of the default locale or of LocaleID; IgnoreCase True ignores case.
Subrange (2)Views SrcLen characters of Src from SrcIdx (1-based), copying no character.
Substring (2)The text from StartIndex (0-based) to the end, or Length characters from StartIndex.
ThreadStatsThe calling thread's counters of its memory for long texts.
ToBoolean (3)Converts the text to a Boolean.
ToDouble (3)Converts the text to a Double, correctly rounded.
ToInt64 (3)Converts the text to an Int64 as StrToInt64 does: ToInteger's rules over 64 bits.
ToInteger (3)Converts the text to an Integer.
ToLowerAscii (2)A copy with 'A'..'Z' in lower case; every other character is unchanged.
ToLowerInvariant (2)A copy in lower case by the operating system's case table, the same under every locale.
ToLowerLinguistic (4)A copy in lower case by the casing rules of the default locale or of LocaleID.
ToPCharA pointer to the text, terminated by #0, valid until the string next changes.
ToSingle (3)Converts the text to a Single, correctly rounded.
ToStringA new string with the window's characters.
ToUpperAscii (2)A copy with 'a'..'z' in upper case; every other character is unchanged.
ToUpperInvariant (2)A copy in upper case by the operating system's uppercase table, the same under every locale.
ToUpperLinguistic (4)A copy in upper case by the casing rules of the default locale or of LocaleID.
Trim (2)The text without the characters <= ' ' at both ends.
TrimLeft (3)The text without the characters <= ' ' at its start.
TrimRight (3)The text without the characters <= ' ' at its end.
UpperCaseAsciiMaps the text's ASCII letters to upper case, in place.

Operators

NameDescription
Add (5)Concatenation: a new value.
AssignAssignment: the target holds the same text.
Equal (3)s = t: ordinal equality by UTF-16 code unit, as string's; either operand may be a string.
Explicit (4)Conversion to PChar: the pointer ToPChar returns, nothing copied.
FinalizeReleases the variable's text when it goes out of scope. The compiler calls it.
GreaterThan (3)s > t: ordinal order, as string's; either operand may be a string.
GreaterThanOrEqual (3)s >= t: ordinal order, as string's; either operand may be a string.
InitializeSets a new variable to the empty text, held inline. The compiler calls it.
LessThan (3)s < t: ordinal order by UTF-16 code unit, as string's; either operand may be a string.
LessThanOrEqual (3)s <= t: ordinal order, as string's; either operand may be a string.
NotEqual (3)s <> t: ordinal inequality, as string's; either operand may be a string.

Fields

NameTypeDescription
CharsPCharThe text's characters, 0-based, read without an index check.