logo.png
mORMot2 API Reference

mormot.core.text.pas unit

Purpose: Framework Core Low-Level Text Processing
- this unit is a part of the Open Source Synopse mORMot framework 2, licensed under a MPL/GPL/LGPL three license - see LICENSE.md

1.1. Units used in the mormot.core.text unit

Unit NameDescription
mormot.core.baseFramework Core Shared Types and RTL-like Functions
mormot.core.osFramework Core Low-Level Wrappers to the Operating-System API
mormot.core.unicodeFramework Core Low-Level Unicode UTF-8 UTF-16 Ansi Conversion

1.2. mormot.core.text class hierarchy

TObjectTTextWriterTEchoWriterExceptionESynException
mormot.core.text class hierarchy

1.3. Objects implemented in the mormot.core.text unit

ObjectsDescription
ESynExceptionGeneric parent class of all custom Exception types of this unit
TEchoWriterAdd optional echoing of the lines to TTextWriter
TTempUtf8A memory structure which avoids a temporary RawUtf8 allocation
TTextWriterParent to T*Writer text processing classes, with the minimum set of methods

1.3.1. TTextWriter

TTextWriter = class(TObject)

Parent to T*Writer text processing classes, with the minimum set of methods
- use an internal buffer, so much faster than naive string+string
- see TTextDateWriter in mormot.core.datetime for date/time methods
- see TJsonWriter in mormot.core.json for proper JSON support
- see TResultsWriter in mormot.db.core for SQL resultset export
- see TOrmWriter in mormot.orm.core for ORM oriented serialization
- note: mORMot 1.18 TTextWriter.RegisterCustomJSONSerializerFromText() are moved into Rtti.RegisterFromText() as other similar methods


B: PUtf8Char;

Direct access to the low-level current position in the buffer
- you should not use this field directly


BEnd: PUtf8Char;

Direct access to the low-level last position in the buffer
- you should not use this field directly
- points in fact to 16 bytes before the buffer ending


constructor Create(aStream: TStream; aBuf: pointer; aBufSize: integer); overload;

The data will be written to the specified Stream
- aStream may be nil: in this case, it MUST be set before using any Add*() method
- will use an external buffer (which may be allocated on stack)


constructor Create(aStream: TStream; aBufSize: integer = 8192); overload;

The data will be written to the specified Stream
- aStream may be nil: in this case, it MUST be set before using any Add*() method
- default internal buffer size if 8192


constructor CreateOwnedFileStream(const aFileName: TFileName; aBufSize: integer = 16384);

The data will be written to an external file
- you should call explicitly FlushFinal or FlushToStream to write any pending data to the file


constructor CreateOwnedStream(var aStackBuf: TTextWriterStackBuffer; NoSharedStream: boolean = false); overload;

The data will be written to an internal TRawByteStringStream
- will use the stack-allocated TTextWriterStackBuffer


constructor CreateOwnedStream(var aStackBuf: TTextWriterStackBuffer; aBufSize: integer; NoSharedStream: boolean = false); overload;

The data will be written to an internal TRawByteStringStream
- will use the stack-allocated TTextWriterStackBuffer if possible


constructor CreateOwnedStream(aBufSize: integer = 4096; NoSharedStream: boolean = false); overload;

The data will be written to an internal TRawByteStringStream
- default internal buffer size if 4096 (enough for most JSON objects)
- consider using a stack-allocated buffer and the overloaded method


constructor CreateOwnedStream(aBuf: pointer; aBufSize: integer; NoSharedStream: boolean = false); overload;

The data will be written to an internal TRawByteStringStream
- will use an external buffer (which may be allocated on stack)


destructor Destroy; override;

Release all internal structures
- e.g. free fStream if the instance was owned by this class


function AddJsonReformat(Json: PUtf8Char; Format: TTextWriterJsonFormat; EndOfObject: PUtf8Char): PUtf8Char; virtual;

This class implementation will raise an exception
- use overriden TJsonWriter version instead!


function AddPrepare(Len: PtrInt): pointer;

Prepare direct access to the internal output buffer
- return nil if Len is too big to fit in the current buffer size
- return the position to write text, and increase the instance position


function LastChar: AnsiChar;

Return the last char appended
- returns #0 if no char has been written yet, or the buffer has been just flushed: so this method is to be handled only in some particular usecases


function PendingBytes: PtrUInt;

How many bytes are currently in the internal buffer and not on disk/stream
- see TextLength for the total number of bytes, on both stream and memory


function Text: RawUtf8;

Write pending data, then retrieve the whole text as a UTF-8 string


procedure Add(Value: PtrInt); overload;

Append a 32-bit signed integer Value as text


procedure Add(Value: Int64); overload;

Already implemented by Add(Value: PtrInt) method on CPU64 append a 64-bit signed integer Value as text


procedure Add(const c1, c2: AnsiChar); overload;

Append two chars to the buffer


procedure Add(P: PUtf8Char; Escape: TTextWriterKind); overload; virtual;

Write some #0 ended UTF-8 text, according to the specified format
- use overriden TJsonWriter version instead!


procedure Add(Value: PGuid; QuotedChar: AnsiChar = #0); overload;

Append a GUID value, encoded as text without any {}
- will store e.g. '3F2504E0-4F89-11D3-9A0C-0305E82C3301'


procedure Add(Value: boolean); overload;

URW1111 append a boolean Value as text
- write either 'true' or 'false'


procedure Add(const c: AnsiChar); overload;

Append one ASCII char to the buffer


procedure Add(P: PUtf8Char; Len: PtrInt; Escape: TTextWriterKind); overload; virtual;

Write some #0 ended UTF-8 text, according to the specified format
- use overriden TJsonWriter version instead!


procedure Add(const Format: RawUtf8; const Values: array of const; Escape: TTextWriterKind = twNone; WriteObjectOptions: TTextWriterWriteObjectOptions = [woFullExpand]); overload; virtual;

Append strings or integers with a specified format
- this class implementation will raise an exception for twJsonEscape, and simply call FormatUtf8() over a temp RawUtf8 for twNone/twOnSameLine
- use faster and more complete overriden TJsonWriter.Add instead!


procedure Add(Value: Extended; precision: integer; noexp: boolean = false); overload;

Append a floating-point Value as a String
- write "Infinity", "-Infinity", and "NaN" for corresponding IEEE values
- noexp=true will call ExtendedToShortNoExp() to avoid any scientific notation in the resulting text


procedure Add2(Value: PtrUInt);

Append an integer Value as fixed-length 2 digits text with comma


procedure Add3(Value: cardinal);

Append an integer Value as fixed-length 3 digits text without any comma


procedure Add4(Value: PtrUInt);

Append an integer Value as fixed-length 4 digits text with comma


procedure AddB(Value: PtrUInt);

URW1111 append an Unsigned integer <= 255 < 999 Value as a String


procedure AddBinToHex(Bin: pointer; BinBytes: PtrInt; LowerHex: boolean = false);

Append some binary data as hexadecimal text conversion


procedure AddBinToHexDisplay(Bin: pointer; BinBytes: PtrInt);

Fast conversion from binary data into hexa chars, ready to be displayed
- using this function with Bin^ as an integer value will serialize it in big-endian order (most-significant byte first), as used by humans
- up to the internal buffer bytes may be converted


procedure AddBinToHexDisplayLower(Bin: pointer; BinBytes: PtrInt; QuotedChar: AnsiChar = #0);

Fast conversion from binary data into MSB hexa chars
- up to the internal buffer bytes may be converted


procedure AddBinToHexDisplayMinChars(Bin: pointer; BinBytes: PtrInt; QuotedChar: AnsiChar = #0);

Append a Value as significant hexadecimal text
- expects BinBytes to be > 0
- append its minimal chars, i.e. excluding highest bytes containing 0
- use GetNextItemHexa() to decode such a text value


procedure AddBinToHexDisplayQuoted(Bin: pointer; BinBytes: PtrInt);

Fast conversion from binary data into quoted MSB lowercase hexa chars
- up to the internal buffer bytes may be converted


procedure AddBinToHexMinChars(Bin: pointer; BinBytes: PtrInt; LowerHex: boolean = false);

Append some binary data as hexadecimal text conversion
- append its minimal chars, i.e. excluding last bytes containing 0


procedure AddByteToHex(Value: PtrUInt);

Write a byte as two hexa chars


procedure AddByteToHexLower(Value: PtrUInt);

Write a byte as two hexa chars


procedure AddChars(aChar: AnsiChar; aCount: PtrInt);

Write the same character multiple times


procedure AddClassName(aClass: TClass);

Append the class name of an Object instance as text


procedure AddComma;

Append one comma (',') character
- to be called after a regular Add(), within the 16 bytes buffer overhead


procedure AddCR;

Append CR+LF (#13#10) chars
- this method won't call TEchoWriter.EchoAdd() registered events - use TEchoWriter.AddEndOfLine() method instead
- TEchoWriter.AddEndOfLine() will append either CR+LF (#13#10) or only LF (#10) depending on its internal options


procedure AddCRAndIndent; virtual;

Append CR+LF (#13#10) chars and #9 indentation
- indentation depth is defined by the HumanReadableLevel value


procedure AddCsvDouble(const Doubles: array of double);

Append an array of doubles as CSV


procedure AddCsvInteger(const Integers: array of integer);

Append an array of integers as CSV


procedure AddCurr(const Value: currency);

Append a Currency value
- just an inlined wrapper around AddCurr64(PInt64(@Value))


procedure AddCurr64(Value: PInt64);

Append a Currency from its Int64 in-memory representation
- expects a PInt64 to avoid ambiguity with the AddCurr() method


procedure AddDirect(const c1, c2: AnsiChar); overload;

Append one ASCII char to the buffer with no buffer check
- to be called after a regular Add(), within the 16 bytes buffer overhead


procedure AddDirect(const c: AnsiChar); overload;

Append one ASCII char to the buffer with no buffer check
- to be called after a regular Add(), within the 16 bytes buffer overhead


procedure AddDouble(Value: double; noexp: boolean = false);

Append a floating-point Value as a String
- write "Infinity", "-Infinity", and "NaN" for corresponding IEEE values
- noexp=true will call ExtendedToShortNoExp() to avoid any scientific notation in the resulting text


procedure AddFieldName(const FieldName: RawUtf8);

Append a RawUtf8 property name, as '"FieldName":'
- FieldName content should not need any JSON escape (e.g. no " within)
- if twoForceJsonExtended is defined in CustomOptions, it would append 'PropName:' without the double quotes
- is a wrapper around AddProp()


procedure AddFloatStr(P: PUtf8Char);

Append a floating-point text buffer
- will correct on the fly '.5' -> '0.5' and '-.5' -> '-0.5'
- is used when the input comes from a third-party source with no regular output, e.g. a database driver


procedure AddHtmlEscape(Text: PUtf8Char; TextLen: PtrInt; Fmt: TTextWriterHtmlFormat = hfAnyWhere); overload;

Append some UTF-8 chars, escaping all HTML special chars as expected


procedure AddHtmlEscape(Text: PUtf8Char; Fmt: TTextWriterHtmlFormat = hfAnyWhere); overload;

Append some UTF-8 chars, escaping all HTML special chars as expected


procedure AddHtmlEscapeString(const Text: string; Fmt: TTextWriterHtmlFormat = hfAnyWhere);

Append some RTL string chars, escaping all HTML special chars as expected


procedure AddHtmlEscapeUtf8(const Text: RawUtf8; Fmt: TTextWriterHtmlFormat = hfAnyWhere);

Append some UTF-8 chars, escaping all HTML special chars as expected


procedure AddHtmlEscapeW(Text: PWideChar; Fmt: TTextWriterHtmlFormat = hfAnyWhere); overload;

Append some UTF-16 chars, escaping all HTML special chars as expected


procedure AddInstanceName(Instance: TObject; SepChar: AnsiChar);

Append an Instance name and pointer, as '"TObjectList(00425E68)"'+SepChar
- append "void" if Instance = nil


procedure AddInstancePointer(Instance: TObject; SepChar: AnsiChar; IncludeUnitName, IncludePointer: boolean);

Append an Instance name and pointer, as 'TObjectList(00425E68)'+SepChar


procedure AddInt18ToChars3(Value: cardinal);

Write a Int18 value (0..262143) as 3 chars
- this encoding is faster than Base64, and has spaces on the left side
- use function Chars3ToInt18() to decode the textual content


procedure AddLine(const Text: ShortString);

Append a line of text with CR+LF at the end


procedure AddMicroSec(MicroSec: cardinal);

Append a time period, specified in micro seconds, in 00.000.000 TSynLog format


procedure AddNoJsonEscape(P: PAnsiChar; Len: PtrInt; CodePage: cardinal); overload;

Append some Ansi text as UTF-8 chars to the buffer
- don't escapes chars according to the JSON RFC


procedure AddNoJsonEscape(P: pointer; Len: PtrInt); overload;

Append some UTF-8 chars to the buffer - inlined for small content
- don't escapes chars according to the JSON RFC


procedure AddNoJsonEscape(P: pointer); overload;

Append some UTF-8 chars to the buffer
- input length is calculated from zero-ended char
- don't escapes chars according to the JSON RFC


procedure AddNoJsonEscapeBig(P: pointer; Len: PtrInt);

Append some UTF-8 chars to the buffer
- don't escapes chars according to the JSON RFC
- called by inlined AddNoJsonEscape() if Len >= fTempBufSize


procedure AddNoJsonEscapeString(const s: string);

Append some UTF-8 encoded chars to the buffer, from a RTL string type
- don't escapes chars according to the JSON RFC
- if s is a UnicodeString, will convert UTF-16 into UTF-8


procedure AddNoJsonEscapeUtf8(const text: RawByteString);

Append some UTF-8 chars to the buffer
- don't escapes chars according to the JSON RFC


procedure AddNoJsonEscapeW(WideChar: PWord; WideCharCount: integer);

Append some unicode chars to the buffer
- WideCharCount is the unicode chars count, not the byte size; if it is 0, then it will convert until an ending #0 (fastest way)
- don't escapes chars according to the JSON RFC
- will convert the Unicode chars into UTF-8


procedure AddNull;

Append 'null' as text


procedure AddObjArrayJson(const aObjArray; aOptions: TTextWriterWriteObjectOptions = [woDontStoreDefault]);

Append a T*ObjArray dynamic array as a JSON array
- for proper serialization on Delphi 7-2009, use Rtti.RegisterObjArray()


procedure AddOnce(const c: AnsiChar); overload;

Append one ASCII char to the buffer, if not already there as LastChar


procedure AddOnSameLine(P: PUtf8Char); overload;

Append some chars to the buffer in one line
- P should be ended with a #0
- will write #1..#31 chars as spaces (so content will stay on the same line)


procedure AddOnSameLine(P: PUtf8Char; Len: PtrInt); overload;

Append some chars to the buffer in one line
- will write #0..#31 chars as spaces (so content will stay on the same line)


procedure AddOnSameLineString(const Text: string);

Append some RTL string to the buffer in one line
- will write #0..#31 chars as spaces (so content will stay on the same line)


procedure AddOnSameLineW(P: PWord; Len: PtrInt);

Append some wide chars to the buffer in one line
- will write #0..#31 chars as spaces (so content will stay on the same line)


procedure AddPointer(P: PtrUInt; QuotedChar: AnsiChar = #0);

Add the pointer into significant hexa chars, ready to be displayed
- append its minimal chars i.e. excluding highest bytes containing 0


procedure AddProp(PropName: PUtf8Char); overload;

Append a property name, as '"PropName":'
- just a wrapper around AddProp(PropName, StrLen(PropName))


procedure AddProp(PropName: PUtf8Char; PropNameLen: PtrInt); overload;

Append a property name, as '"PropName":'
- PropName content should not need any JSON escape (e.g. no " within, and only ASCII 7-bit characters)
- if twoForceJsonExtended is defined in CustomOptions, it would append 'PropName:' without the double quotes


procedure AddPropInt64(const PropName: ShortString; Value: Int64; WithQuote: AnsiChar = #0);

Append a JSON field name, followed by a number value and a comma (',')


procedure AddPropName(const PropName: ShortString);

Append a ShortString property name, as '"PropName":'
- PropName content should not need any JSON escape (e.g. no " within, and only ASCII 7-bit characters)
- if twoForceJsonExtended is defined in CustomOptions, it would append 'PropName:' without the double quotes
- is a wrapper around AddProp()


procedure AddQ(Value: QWord);

Append an Unsigned 64-bit integer Value as a String


procedure AddQHex(Value: Qword; QuotedChar: AnsiChar = '"');

URW1147 on Delphi XE2 append an Unsigned 64-bit integer Value as a quoted hexadecimal String


procedure AddQuotedFieldName(FieldName: PUtf8Char; FieldNameLen: PtrInt; const VoidPlaceHolder: RawUtf8 = ''); overload;

Append a RawUtf8 property name, as '"FieldName"
- FieldName content should not need any JSON escape (e.g. no " within)


procedure AddQuotedFieldName(const FieldName: RawUtf8; const VoidPlaceHolder: RawUtf8 = ''); overload;

Append a RawUtf8 property name, as '"FieldName"
- FieldName content should not need any JSON escape (e.g. no " within)


procedure AddQuotedStr(Text: PUtf8Char; TextLen: PtrUInt; Quote: AnsiChar; TextMaxLen: PtrInt = 0);

Append some UTF-8 chars, quoting all " chars
- same algorithm than AddString(QuotedStr()) - without memory allocation, and with an optional maximum text length (truncated with ending '...')
- this function implements what is specified in the official SQLite3 documentation: "A string constant is formed by enclosing the string in single quotes ('). A single quote within the string can be encoded by putting two single quotes in a row - as in Pascal."


procedure AddRawJson(const json: RawJson);

Append some UTF-8 content to the buffer, with no JSON escape
- if supplied json is '', will write 'null' so that valid JSON is written
- redirect to AddNoJsonEscape() otherwise


procedure AddReplace(Text: PUtf8Char; Orig, Replaced: AnsiChar);

Append some UTF-8 chars, replacing a given character with another


procedure AddShort(Text: PUtf8Char; TextLen: PtrInt); overload;

Append a ShortString - or at least a small buffer < 256 chars


procedure AddShort(const Text: ShortString); overload;

Append a ShortString


procedure AddShorter(const Short8: TShort8);

Append a TShort8 - Text should be not '', and up to 8 chars long
- this method is aggressively inlined, so may be preferred to AddShort() for appending simple UTF-8 constant text


procedure AddSingle(Value: single; noexp: boolean = false);

Append a floating-point Value as a String
- write "Infinity", "-Infinity", and "NaN" for corresponding IEEE values
- noexp=true will call ExtendedToShortNoExp() to avoid any scientific notation in the resulting text


procedure AddSpaced(Text: PUtf8Char; TextLen, Width: PtrInt); overload;

Append some text with left-filled spaces up to Width characters count
- if the value too big to fit, will truncate up to the first Width chars


procedure AddSpaced(const Text: RawUtf8; Width: PtrInt; SepChar: AnsiChar = #0); overload;

Append some text with left-filled spaces up to Width characters count


procedure AddSpaced(Value: QWord; Width: PtrInt; SepChar: AnsiChar = #0); overload;

Append some number with left-filled spaces up to Width characters count
- if the value too big to fit in Width, will append K(Value) abbreviation


procedure AddString(const Text: RawUtf8);

Append an UTF-8 String, with no JSON escaping


procedure AddStringCopy(const Text: RawUtf8; start, len: PtrInt);

Append a sub-part of an UTF-8 String
- emulates AddString(copy(Text,start,len))


procedure AddStrings(const Text: RawUtf8; count: PtrInt); overload;

Append an UTF-8 string several times


procedure AddStrings(const Text: array of RawUtf8); overload;

Append several UTF-8 strings


procedure AddTrimLeftLowerCase(Text: PShortString);

Append after trim first lowercase chars ('otDone' will add 'Done' e.g.)


procedure AddTrimSpaces(P: PUtf8Char); overload;

Append a #0-terminated UTF-8 buffer excluding any space or control char
- this won't escape the text as expected by JSON


procedure AddTrimSpaces(const Text: RawUtf8); overload;

Append a UTF-8 String excluding any space or control char
- this won't escape the text as expected by JSON


procedure AddTypedJson(Value: pointer; TypeInfo: pointer; WriteOptions: TTextWriterWriteObjectOptions = []); virtual;

This class implementation will raise an exception
- use overriden TJsonWriter version instead!
- TypeInfo is a PRttiInfo instance - but not available in this early unit


procedure AddU(Value: PtrUInt);

Append an Unsigned 32-bit integer Value as a String


procedure AddUHex(Value: cardinal; QuotedChar: AnsiChar = '"');

Append an Unsigned 32-bit integer Value as a quoted hexadecimal String


procedure AddUrlNameNormalize(U: PUtf8Char; L: PtrInt);

Append an URI-decoded domain name, also normalizing dual // into /
- only parameters - i.e. after '?' - may have ' ' replaced by '+'


procedure AddVarData(Value: PVarData; HtmlEscape: boolean);

Append a variant content as UTF-8 text
- with optional HTML escape (via a TTempUtf8) but no JSON serialization


procedure AddVariant(const Value: variant; Escape: TTextWriterKind = twJsonEscape; WriteOptions: TTextWriterWriteObjectOptions = []); virtual;

This class implementation will raise an exception
- use overriden TJsonWriter version instead!


procedure AddXmlEscape(Text: PUtf8Char);

Append some chars, escaping all XML special chars as expected
- i.e. < > & " ' as &lt; &gt; &amp; &quote; &apos;
- and all control chars (i.e. #1..#31) as &#..;
- see @http://www.w3.org/TR/xml/#syntax


procedure CancelAll;

Rewind the Stream to the position when Create() was called
- note that this does not clear the Stream content itself, just move back its writing position to its initial place


procedure CancelAllAsNew;

Same as CancelAll, and also reset the CustomOptions


procedure CancelAllWith(var temp: TTextWriterStackBuffer);

Same as CancelAll, and also use a new local TTextWriterStackBuffer


procedure CancelLastChar(aCharToCancel: AnsiChar); overload;

The last char appended is canceled, if match the supplied one
- only one char cancelation is allowed at the same position: don't call CancelLastChar/CancelLastComma more than once without appending text inbetween


procedure CancelLastChar; overload;

The last char appended is canceled
- only one char cancelation is allowed at the same position: don't call CancelLastChar/CancelLastComma more than once without appending text inbetween


procedure CancelLastComma(aReplaceChar: AnsiChar); overload;

The last char appended is canceled if it was a ',' and replaced
- only one char cancelation is allowed at the same position: don't call CancelLastChar/CancelLastComma more than once without appending text inbetween


procedure CancelLastComma; overload;

The last char appended is canceled if it was a ','
- only one char cancelation is allowed at the same position: don't call CancelLastChar/CancelLastComma more than once without appending text inbetween


procedure FlushFinal;

Write pending data to the Stream, without automatic buffer resizal
- will append the internal memory buffer to the Stream
- in short, FlushToStream may be called during the adding process, and FlushFinal at the end of the process, just before using the resulting Stream
- if you don't call FlushToStream or FlushFinal, some pending characters may not be copied to the Stream: you should call it before using the Stream


procedure FlushToStream; virtual;

Write pending data to the Stream, with automatic buffer resizal
- you should not have to call FlushToStream in most cases, but FlushFinal at the end of the process, just before using the resulting Stream
- FlushToStream may be used to force immediate writing of the internal memory buffer to the destination Stream
- you can set FlushToStreamNoAutoResize=true or call FlushFinal if you do not want the automatic memory buffer resizal to take place


procedure ForceContent(const text: RawUtf8);

Set the internal stream content with the supplied UTF-8 text


class procedure SetDefaultEnumTrim(aShouldTrimEnumsAsText: boolean);

Allow to override the default (JSON) serialization of enumerations and sets as text, which would write the whole identifier (e.g. 'sllError')
- calling SetDefaultEnumTrim(true) would force the enumerations to be trimmed for any lower case char, e.g. sllError -> 'Error'
- this is global to the current process, and should be use mainly for compatibility purposes for the whole process
- you may change the default behavior by setting twoTrimLeftEnumSets in the TTextWriter.CustomOptions property of a given serializer
- note that unserialization process would recognize both formats


procedure SetText(var result: RawUtf8; reformat: TTextWriterJsonFormat = jsonCompact);

Write pending data, then retrieve the whole text as a UTF-8 string


procedure WrBase64(P: PAnsiChar; Len: PtrUInt; withMagic: boolean); virtual;

Write some data Base64 encoded
- use overriden TJsonWriter version instead!


procedure WriteObject(Value: TObject; WriteOptions: TTextWriterWriteObjectOptions = [woDontStoreDefault]); virtual;

Serialize as JSON the given object
- use overriden TJsonWriter version instead!


property CustomOptions: TTextWriterOptions read fCustomOptions write fCustomOptions;

Global options to customize this TTextWriter instance process
- allows to override e.g. AddRecordJson() and AddDynArrayJson() behavior


property HumanReadableLevel: integer read fHumanReadableLevel write fHumanReadableLevel;

Low-level access to the current indentation level


property OnFlushToStream: TOnTextWriterFlush read fOnFlushToStream write fOnFlushToStream;

Optional event called before FlushToStream method process
- used e.g. by TEchoWriter to perform proper content echoing


property Stream: TStream read fStream write SetStream;

The internal TStream used for storage
- you should call the FlushFinal (or FlushToStream) methods before using this TStream content, to flush all pending characters
- if the TStream instance has not been specified when calling the TTextWriter constructor, it can be forced via this property, before any writing


property TextLength: PtrUInt read GetTextLength;

Count of added bytes to the stream
- see PendingBytes for the number of bytes currently in the memory buffer or WrittenBytes for the number of bytes already written to disk/stream


property WrittenBytes: PtrUInt read fTotalFileSize;

How many bytes were currently written on disk/stream
- excluding the bytes in the internal buffer (see PendingBytes)
- see TextLength for the total number of bytes, on both stream and memory


1.3.2. TEchoWriter

TEchoWriter = class(TObject)

Add optional echoing of the lines to TTextWriter
- as used e.g. by TSynLog writer for log optional redirection
- is defined as a nested class to reduce plain TTextWriter scope, and better follow the SOLID principles


constructor Create(Owner: TTextWriter); reintroduce;

Prepare for the echoing process


destructor Destroy; override;

End the echoing process


procedure AddEndOfLine(aLevel: TSynLogLevel = sllNone);

Mark an end of line, ready to be "echoed" to registered listeners
- append a LF (#10) char or CR+LF (#13#10) chars to the buffer, depending on the EndOfLineCRLF property value (default is LF, to minimize storage)
- any callback registered via EchoAdd() will monitor this line in the current thread, or calling EchoPendingExecute from a background thread
- used e.g. by TSynLog for console output, as stated by Level parameter


procedure EchoAdd(const aEcho: TOnTextWriterEcho);

Add a callback to echo each line written by this class
- this class expects AddEndOfLine to mark the end of each line


procedure EchoPendingExecute;

Run all pending EchoPendingExecuteBackground notifications
- should be executed from a background thread


procedure EchoRemove(const aEcho: TOnTextWriterEcho);

Remove a callback to echo each line written by this class
- event should have been previously registered by a EchoAdd() call


procedure EchoReset;

Reset the internal buffer used for echoing content


procedure FlushToStream(Text: PUtf8Char; Len: PtrInt);

Should be called from TTextWriter.FlushToStream
- write pending data to the Stream, with automatic buffer resizal and echoing
- this overriden method will handle proper echoing


property EchoPendingExecuteBackground: boolean read fEchoPendingExecuteBackground write fEchoPendingExecuteBackground;

If EchoPendingExecute is about to be executed in the background


property EndOfLineCRLF: boolean read GetEndOfLineCRLF write SetEndOfLineCRLF;

Define how AddEndOfLine method stores its line feed characters
- by default (FALSE), it will append a LF (#10) char to the buffer
- you can set this property to TRUE, so that CR+LF (#13#10) chars will be appended instead
- is just a wrapper around twoEndOfLineCRLF item in CustomOptions


property Writer: TTextWriter read fWriter;

The associated TTextWriter instance


1.3.3. TTempUtf8

TTempUtf8 = record

A memory structure which avoids a temporary RawUtf8 allocation
- used by VarRecToTempUtf8/VariantToTempUtf8 and FormatUtf8/FormatShort


1.3.4. ESynException

ESynException = class(Exception)

Generic parent class of all custom Exception types of this unit
- all our classes inheriting from ESynException are serializable, so you could use ObjectToJsonDebug(any ESynException) to retrieve some extended information


constructor CreateLastOSError(const Format: RawUtf8; const Args: array of const; const Trailer: ShortString = 'OSError');

Constructor appending some FormatUtf8() content to the GetLastError
- message will contain GetLastError value followed by the formatted text
- expect % as delimiter, so is less error prone than %s %d %g
- will handle vtPointer/vtClass/vtObject/vtVariant kind of arguments, appending class name for any class or object, the hexa value for a pointer, or the JSON representation of any supplied TDocVariant


constructor CreateU(const Msg: RawUtf8);

Constructor will accept RawUtf8 instead of string as message text


constructor CreateUtf8(const Format: RawUtf8; const Args: array of const); virtual;

Constructor which will use FormatUtf8() instead of Format()
- expect % as delimiter, so is less error prone than %s %d %g
- will handle vtPointer/vtClass/vtObject/vtVariant kind of arguments, appending class name for any class or object, the hexa value for a pointer, or the JSON representation of any supplied TDocVariant


function CustomLog(WR: TTextWriter; const Context: TSynLogExceptionContext): boolean; virtual;

Can be used to customize how the exception is logged
- this default implementation will call the TSynLogExceptionToStrCustom global callback, if defined, or a default handler internal to this unit
- override this method to provide a custom logging content
- should return TRUE if Context.EAddr and Stack trace is not to be written (i.e. as for any TSynLogExceptionToStr callback)


class procedure RaiseUtf8(const Format: RawUtf8; const Args: array of const);

A wrapper function around raise CreateUtf8()


property Message;

The Exception Message string, as defined in parent Exception class


property MessageUtf8: RawUtf8 read fMessageUtf8;

The Exception Message UTF-8 text, as generated by CreateUtf8()


property RaisedAt: pointer read fRaisedAt write fRaisedAt;

The code location when this exception was triggered
- populated by mormot.core.log unit, during interception - so may be nil
- you can use TDebugFile.FindLocation(ESynException) class function to guess the corresponding source code line
- will be serialized as "Address": hexadecimal and source code location, using TDebugFile .map/.dbg/.mab information, by JSON WriteObject when woStorePointer option is defined - e.g. with ObjectToJsonDebug()


1.4. Types implemented in the mormot.core.text unit

1.4.1. ESynExceptionClass

ESynExceptionClass = class of ESynException;

Meta-class of the ESynException hierarchy


1.4.2. TAnsiCharToByte

TAnsiCharToByte = array[AnsiChar] of byte;

Type of a lookup table used for fast XML/HTML conversion


1.4.3. TAnsiCharToWord

TAnsiCharToWord = array[AnsiChar] of word;

Type of a lookup table used for fast two-digit chars conversion


1.4.4. TBaseWriterClass

TBaseWriterClass = class of TTextWriter;

Class of our simple TEXT format writer to a Stream


1.4.5. TByteToWord

TByteToWord = array[byte] of word;

Type of a lookup table used for fast two-digit chars conversion


1.4.6. TChar64

TChar64 = array[0..63] of AnsiChar;

Some stack-allocated zero-terminated character buffer
- as used by GetNextTChar64


1.4.7. TGuidShortString

TGuidShortString = string[38];

Stack-allocated ASCII string, used by GuidToShort() function


1.4.8. THexToDualByte

THexToDualByte = packed array[0..511] of byte;

Type of a lookup table used for fast hexadecimal conversion


1.4.9. TOnTextWriterEcho

TOnTextWriterEcho = function(Sender: TEchoWriter; Level: TSynLogLevel; const Text: RawUtf8): boolean of object;

Callback used to echo each line of TEchoWriter class
- should return TRUE on success, FALSE if the log was not echoed: but TSynLog will continue logging, even if this event returned FALSE


1.4.10. TOnTextWriterFlush

TOnTextWriterFlush = procedure(Text: PUtf8Char; Len: PtrInt) of object;

Event signature for TTextWriter.OnFlushToStream callback


1.4.11. TShort4

TShort4 = string[4];

Used e.g. by UInt4DigitsToShort/UInt3DigitsToShort/UInt2DigitsToShort
- such result type would avoid a string allocation on heap


1.4.12. TSynLogExceptionToStr

TSynLogExceptionToStr = function(WR: TTextWriter; const Context: TSynLogExceptionContext): boolean;

Global hook callback to customize exceptions logged by TSynLog
- should return TRUE if all needed information has been logged by the event handler
- should return FALSE if Context.EAddr and Stack trace is to be appended


1.4.13. TTextWriterHtmlFormat

TTextWriterHtmlFormat = ( hfNone, hfAnyWhere, hfOutsideAttributes, hfWithinAttributes );

The potential places were TJsonWriter.AddHtmlEscape should process proper HTML string escaping, unless hfNone is used

  < > & "  ->   < > & "e;

by default (hfAnyWhere)

  < > &  ->   < > &

outside HTML attributes (hfOutsideAttributes)

  & "  ->   & "e;

within HTML attributes (hfWithinAttributes)


1.4.14. TTextWriterJsonFormat

TTextWriterJsonFormat = ( jsonCompact, jsonHumanReadable, jsonUnquotedPropName, jsonUnquotedPropNameCompact, jsonEscapeUnicode, jsonNoEscapeUnicode );

The available JSON format, for TTextWriter.AddJsonReformat() and its JsonBufferReformat() and JsonReformat() wrappers
- jsonCompact is the default machine-friendly single-line layout
- jsonHumanReadable will add line feeds and indentation, for a more human-friendly result
- jsonUnquotedPropName will emit the jsonHumanReadable layout, but with all property names being quoted only if necessary: this format could be used e.g. for configuration files - this format, similar to the one used in the MongoDB extended syntax, is not JSON compatible: do not use it e.g. with AJAX clients, but is would be handled as expected by all our units as valid JSON input, without previous correction
- jsonUnquotedPropNameCompact will emit single-line layout with unquoted property names, which is the smallest data output within mORMot instances
- by default we rely on UTF-8 encoding (which is mandatory in the RFC 8259) but you can use jsonEscapeUnicode to produce pure 7-bit ASCII output, with \u#### escape of non-ASCII chars, e.g. as default python json.dumps
- jsonNoEscapeUnicode will search for any \u#### pattern and generate pure UTF-8 output instead
- those features are not implemented in this unit, but in mormot.core.json


1.4.15. TTextWriterKind

TTextWriterKind = ( twNone, twJsonEscape, twOnSameLine );

Defines how text is to be added into TTextWriter / TJsonWriter
- twNone will write the supplied text with no escaping
- twJsonEscape will properly escape " and \ as expected by JSON
- twOnSameLine will convert any line feeds or control chars into spaces


1.4.16. TTextWriterOption

TTextWriterOption = ( twoStreamIsOwned, twoStreamIsRawByteString, twoFlushToStreamNoAutoResize, twoEnumSetsAsTextInRecord, twoEnumSetsAsBooleanInRecord, twoFullSetsAsStar, twoTrimLeftEnumSets, twoForceJsonExtended, twoForceJsonStandard, twoEndOfLineCRLF, twoBufferIsExternal, twoIgnoreDefaultInRecord, twoDateTimeWithZ, twoNonExpandedArrays, twoNoSharedStream, twoNoWriteToStreamException );

Available global options for a TTextWriter / TTextWriter instance
- TTextWriter.WriteObject() method behavior would be set via their own TTextWriterWriteObjectOptions, and work in conjunction with those settings
- twoStreamIsOwned would be set if the associated TStream is owned by the TTextWriter instance - as a TRawByteStringStream if twoStreamIsRawByteString
- twoFlushToStreamNoAutoResize would forbid FlushToStream to resize the internal memory buffer when it appears undersized - FlushFinal will set it before calling a last FlushToStream
- by default, custom serializers set via TRttiJson.RegisterCustomSerializer() would let AddRecordJson() and AddDynArrayJson() write enumerates and sets as integer numbers, unless twoEnumSetsAsTextInRecord or twoEnumSetsAsBooleanInRecord (exclusively) are set - for Mustache data context, twoEnumSetsAsBooleanInRecord will return a JSON object with "setname":true/false fields
- variants and nested objects would be serialized with their default JSON serialization options, unless twoForceJsonExtended or twoForceJsonStandard is defined
- when enumerates and sets are serialized as text into JSON, you may force the identifiers to be left-trimed for all their lowercase characters (e.g. sllError -> 'Error') by setting twoTrimLeftEnumSets: this option may default to the deprecated global TTextWriter.SetDefaultEnumTrim setting
- twoEndOfLineCRLF would reflect the TEchoWriter.EndOfLineCRLF property
- twoBufferIsExternal would be set if the temporary buffer is not handled by the instance, but specified at constructor, maybe from the stack
- twoIgnoreDefaultInRecord will force custom record serialization to avoid writing the fields with default values, i.e. enable soWriteIgnoreDefault when published properties are serialized
- twoDateTimeWithZ appends an ending 'Z' to TDateTime/TDateTimeMS values
- twoNonExpandedArrays will force the 'non expanded' optimized JSON layout for array of records or classes, ignoring other formatting options:

 {"fieldCount":2,"values":["f1","f2","1v1",1v2,"2v1",2v2...],"rowCount":20}

- twoNoSharedStream will force to create a new stream for each instance
- twoNoWriteToStreamException let TTextWriter.WriteToStream silently fail


1.4.17. TTextWriterOptions

TTextWriterOptions = set of TTextWriterOption;

Options set for a TTextWriter / TTextWriter instance
- allows to override e.g. AddRecordJson() and AddDynArrayJson() behavior; or set global process customization for a TTextWriter


1.4.18. TTextWriterStackBuffer

TTextWriterStackBuffer = array[0..8191] of AnsiChar;

May be used to allocate on stack a 8KB work buffer for a TTextWriter
- via the TTextWriter.CreateOwnedStream overloaded constructor


1.4.19. TTextWriterWriteObjectOption

TTextWriterWriteObjectOption = ( woHumanReadable, woDontStoreDefault, woFullExpand, woStoreClassName, woStorePointer, woStoreStoredFalse, woHumanReadableFullSetsAsStar, woHumanReadableEnumSetAsComment, woEnumSetsAsText, woDateTimeWithMagic, woDateTimeWithZSuffix, woTimeLogAsText, woIDAsIDstr, woRawBlobAsBase64, woHideSensitivePersonalInformation, woObjectListWontStoreClassName, woDontStoreInherited, woInt64AsHex, woDontStoreVoid, woPersistentLock );

Available options for TTextWriter.WriteObject() method
- woHumanReadable will add some line feeds and indentation to the content, to make it more friendly to the human eye
- woDontStoreDefault (which is set by default for WriteObject method) will avoid serializing properties including a default value (JsonToObject function will set the default values, so it may help saving some bandwidth or storage)
- woFullExpand will generate a debugger-friendly layout, including instance class name, sets/enumerates as text, and reference pointer - as used by TSynLog and ObjectToJsonFull()
- woStoreClassName will add a "ClassName":"TMyClass" field
- woStorePointer will add a "Address":"0431298A" field, and .map/.dbg/.mab source code line number corresponding to ESynException.RaisedAt
- woStoreStoredFalse will write the 'stored false' properties, even if they are marked as such (used e.g. to persist all settings on file, but disallow the sensitive - password - fields be logged)
- woHumanReadableFullSetsAsStar will store an human-readable set with all its enumerates items set to be stored as ["*"]
- woHumanReadableEnumSetAsComment will add a comment at the end of the line, containing all available values of the enumaration or set, e.g:

 "Enum": "Destroying", // Idle,Started,Finished,Destroying

- woEnumSetsAsText will store sets and enumerables as text (is also included in woFullExpand or woHumanReadable)
- woDateTimeWithMagic will append the JSON_SQLDATE_MAGIC_C (i.e. U+FFF1) before the ISO-8601 encoded TDateTime value
- woDateTimeWithZSuffix will append the Z suffix to the ISO-8601 encoded TDateTime value, to identify the content as strict UTC value
- TTimeLog would be serialized as Int64, unless woTimeLogAsText is defined
- since TOrm.ID could be huge Int64 numbers, they may be truncated on client side, e.g. to 53-bit range in JavaScript: you could define woIDAsIDstr to append an additional "ID_str":"##########" field
- by default, RawBlob properties are serialized as null, unless woRawBlobAsBase64 is defined or a custom serialization is used (e.g. TOrm)
- if woHideSensitivePersonalInformation is set, rcfSpi types (e.g. the TSynPersistentWithPassword.Password field) will be serialized as "***" to prevent security issues (e.g. in log)
- by default, TObjectList will set the woStoreClassName for its nested objects, unless woObjectListWontStoreClassName is defined
- all inherited properties would be serialized, unless woDontStoreInherited is defined, and only the topmost class level properties would be serialized
- woInt64AsHex will force Int64/QWord to be written as hexadecimal string - see j2oAllowInt64Hex reverse option fot Json2Object
- woDontStoreVoid will avoid serializing numeric properties equal to 0 and string properties equal to '' (replace both deprecated woDontStore0 and woDontStoreEmptyString flags)
- woPersistentLock paranoid setting will call TSynPersistentLock.Lock/Unlock during serialization


1.4.20. TTextWriterWriteObjectOptions

TTextWriterWriteObjectOptions = set of TTextWriterWriteObjectOption;

Options set for TTextWriter.WriteObject() method


1.5. Constants implemented in the mormot.core.text unit

1.5.1. TEXTWRITEROBJECTOPTIONS_ENUMASTEXT

TEXTWRITEROBJECTOPTIONS_ENUMASTEXT: array[boolean] of TTextWriterWriteObjectOptions = ( [], [woEnumSetsAsText]);

TTextWriter JSON serialization options including woEnumSetsAsText


1.5.2. TEXTWRITEROPTIONS_DEBUG

TEXTWRITEROPTIONS_DEBUG = [woDontStoreDefault, woHumanReadable, woStoreClassName, woStorePointer, woHideSensitivePersonalInformation];

TTextWriter JSON serialization options with debugging/logging information


1.5.3. TEXTWRITEROPTIONS_ENUMASTEXT

TEXTWRITEROPTIONS_ENUMASTEXT: array[boolean] of TTextWriterOptions = ( [], [twoEnumSetsAsTextInRecord]);

TTextWriter JSON serialization options including twoEnumSetsAsTextInRecord


1.5.4. TEXTWRITEROPTIONS_RESET

TEXTWRITEROPTIONS_RESET = [twoStreamIsOwned, twoStreamIsRawByteString, twoBufferIsExternal];

TTextWriter JSON serialization options which should be preserved
- used e.g. by TTextWriter.CancelAllAsNew to reset its CustomOptions


1.5.5. TEXTWRITEROPTIONS_SETASTEXT

TEXTWRITEROPTIONS_SETASTEXT: array[boolean] of TTextWriterOptions = ( [twoFullSetsAsStar], [twoFullSetsAsStar, twoEnumSetsAsTextInRecord]);

TTextWriter JSON serialization options focusing of sets support
- as used e.g. by TJsonWriter.AddRecordJson/AddDynArrayJson and TDynArray.SaveJson methods, and SaveJson/RecordSaveJson functions
- to be used as TEXTWRITEROPTIONS_TEXTSET[EnumSetsAsText]


1.5.6. vtNotString

vtNotString = [vtBoolean, vtInteger, vtInt64, vtCurrency, vtExtended, vtVariant];

Which TVarRec.VType are numbers, i.e. don't need to be quoted
- vtVariant is a number by default, unless detected e.g. by VariantToUtf8()


1.6. Functions or procedures implemented in the mormot.core.text unit

Functions or proceduresDescription
AddPrefixToCsvAppend some prefix to all CSV values
AddToCsvAppend a Value to a CSV string
AppendAppend some text items to a RawUtf8 variable
AppendAppend one text item to a RawUtf8 variable with no code page conversion
AppendAppend two text items to a RawUtf8 variable with no code page conversion
AppendAppend one char to a RawUtf8 variable with no code page conversion
AppendAppend one text buffer to a RawByteString variable with no code page conversion
AppendAppend one text item to a RawByteString variable with no code page conversion
AppendAppend some text items to a RawByteString variable
AppendAppend one text buffer to a RawUtf8 variable with no code page conversion
AppendCsvValuesAppend some text lines with the supplied Values[]
AppendLineAppend some text to a RawUtf8, ensuring previous text is separated with CRLF
BinBitsToHexDisplayLowerShort16Fast conversion from up to 64-bit of binary data into lowercase hexa chars
BinToHexFast conversion from binary data into hexa chars
BinToHexFast conversion from binary data into hexa chars
BinToHexFast conversion from binary data into hexa chars
BinToHexDisplayFast conversion from binary data into hexa chars, ready to be displayed
BinToHexDisplayFast conversion from binary data into hexa chars, ready to be displayed
BinToHexDisplayFileFast conversion from binary data into hexa lowercase chars, ready to be used as a convenient TFileName prefix
BinToHexDisplayLowerFast conversion from binary data into lowercase hexa chars
BinToHexDisplayLowerFast conversion from binary data into lowercase hexa chars
BinToHexDisplayLowerShortFast conversion from up to 127 bytes of binary data into lowercase hexa chars
BinToHexDisplayLowerShort16Fast conversion from up to 64-bit of binary data into lowercase hexa chars
BinToHexLowerFast conversion from binary data into lowercase hexa chars
BinToHexLowerFast conversion from binary data into lowercase hexa chars
BinToHexLowerFast conversion from binary data into lowercase hexa chars
BinToHexLowerFast conversion from binary data into lowercase hexa chars
By100ToTwoDigitStringConvert "valueunit" values into x or x.xx text with up to 2 digits
ByteToHexAppend one byte as hexadecimal char pairs, into a text buffer
CardinalToHexFast conversion from a cardinal value into hexa chars, ready to be displayed
CardinalToHexLowerFast conversion from a cardinal value into hexa chars, ready to be displayed
CardinalToHexShortFast conversion from a cardinal value into hexa chars, ready to be displayed
Char2ToByteFast conversion of 2 digit characters into a 0..99 value
Char3ToWordFast conversion of 3 digit characters into a 0..9999 value
Char4ToWordFast conversion of 4 digit characters into a 0..9999 value
Chars3ToInt18Revert the value as encoded by TTextWriter.AddInt18ToChars3() or Int18ToChars3()
ConsoleObjectA wrapper around ConsoleWrite(ObjectToJson(Value))
ConsoleShowFatalExceptionCould be used in the main program block of a console application to handle unexpected fatal exceptions
ConsoleWriteWrite some text to the console using a given color
ConsoleWriteWrite some text to the console using a given color
ConsoleWriteRawWrite some text to the console using the current color
crc32cUtf8ToHexCompute the hexadecimal representation of the crc32 checkum of a given text
CsvContainsQuickly check if Value is in Csv with no temporary memory allocation
CsvGuessSeparatorRecognize #9 ';' or ',' as separator in a CSV text
CsvOfValueReturn a CSV list of the iterated same value
CsvToInt64DynArrayAppend the strings in the specified CSV text into a dynamic array of integer
CsvToInt64DynArrayConvert the strings in the specified CSV text into a dynamic array of integer
CsvToIntegerDynArrayAppend the strings in the specified CSV text into a dynamic array of integer
CsvToRawUtf8DynArrayConvert the strings in the specified CSV text into a dynamic array of UTF-8 strings
CsvToRawUtf8DynArrayAdd the strings in the specified CSV text into a dynamic array of UTF-8 strings
CsvToRawUtf8DynArrayAdd the strings in the specified CSV text into a dynamic array of UTF-8 strings
Curr64ToPCharConvert an INTEGER Curr64 (value*10000) into a string
Curr64ToStrConvert an INTEGER Curr64 (value*10000) into a string
Curr64ToStrConvert an INTEGER Curr64 (value*10000) into a string
Curr64ToStringConvert a currency value from its Int64 binary representation into its numerical text equivalency
CurrencyToStrConvert a currency value into a string
DefaultSynLogExceptionToStrThe default Exception handler for logging
DoubleToJsonConvert a 64-bit floating-point value to its JSON text equivalency
DoubleToShortConvert a 64-bit floating-point value to its numerical text equivalency
DoubleToShortNoExpConvert a 64-bit floating-point value to its numerical text equivalency without scientific notation
DoubleToStrConvert a 64-bit floating-point value to its numerical text equivalency
DoubleToStrConvert a 64-bit floating-point value to its numerical text equivalency
DoubleToStringConvert a floating-point value to its numerical text equivalency
EnsureDirectoryExistsJust a wrapper around EnsureDirectoryExists(MakePath([Part]))
EscapeCharEscape as \char pair some chars from a set into a new RawUtf8 string
EscapeCharBufferEscape as \char pair some chars from a set into a pre-allocated buffer
EscapeHexEscape as \xx hexadecimal some chars from a set into a new RawUtf8 string
EscapeHexBufferEscape as \xx hexadecimal some chars from a set into a pre-allocated buffer
ExtendedToJsonConvert a floating-point value to its JSON text equivalency
ExtendedToShortConvert a floating-point value to its numerical text equivalency
ExtendedToShortNoExpConvert a floating-point value to its numerical text equivalency without scientification notation
ExtendedToStrConvert a floating-point value to its numerical text equivalency
ExtendedToStrConvert a floating-point value to its numerical text equivalency
FindCsvIndexReturn the index of a Value in a CSV string
FloatStrCopyCopy a floating-point text buffer with proper correction and validation
FloatToJsonNanRecognize if the supplied text is NAN/INF/+INF/-INF, i.e. not a number
FloatToShortNanCheck if the supplied text is NAN/INF/+INF/-INF, i.e. not a number
FloatToStrNanCheck if the supplied text is NAN/INF/+INF/-INF, i.e. not a number
FormatBufferFast Format() function replacement, tuned for direct memory buffer write
FormatShortFast Format() function replacement, for UTF-8 content stored in ShortString
FormatShort16Delphi don't inline "array of const" parameters fast Format() function replacement, for UTF-8 content stored in TShort16
FormatStringFast Format() function replacement, tuned for small content
FormatStringFast Format() function replacement, tuned for small content
FormatToShortFast Format() function replacement, for UTF-8 content stored in ShortString
FormatUtf8Fast Format() function replacement, optimized for RawUtf8
FormatUtf8Fast Format() function replacement, optimized for RawUtf8
FormatVariantFast Format() function replacement, for UTF-8 content stored in variant
GetBitCsvConvert a set of bit into a CSV content
GetCsvItemReturn n-th indexed CSV string in P, starting at Index=0 for first one
GetCsvItemStringReturn n-th indexed CSV string in P, starting at Index=0 for first one
GetFileNameExtIndexExtract a file extension from a file name, then compare with a comma separated list of extensions
GetFirstCsvItemReturn first CSV string in the supplied UTF-8 content
GetLastCsvItemReturn last CSV string in the supplied UTF-8 content
GetNextItemReturn next CSV string from P
GetNextItemReturn next CSV string from P
GetNextItemReturn next CSV string (unquoted if needed) from P
GetNextItemCardinalReturn next CSV string as unsigned integer from P, 0 if no more
GetNextItemCardinalStrictReturn next CSV string as unsigned integer from P, 0 if no more
GetNextItemCardinalWReturn next CSV string as unsigned integer from P, 0 if no more
GetNextItemCurrencyReturn next CSV string as currency from P, 0.0 if no more
GetNextItemCurrencyReturn next CSV string as currency from P, 0.0 if no more
GetNextItemDoubleReturn next CSV string as double from P, 0.0 if no more
GetNextItemHexaReturn next CSV hexadecimal string as 64-bit unsigned integer from P
GetNextItemHexDisplayToBinDecode next CSV hexadecimal string from P, nil if no more or not matching BinBytes
GetNextItemInt64Return next CSV string as 64-bit signed integer from P, 0 if no more
GetNextItemIntegerReturn next CSV string as signed integer from P, 0 if no more
GetNextItemMultipleReturn next CSV string from P from several separator characters
GetNextItemQWordReturn next CSV string as 64-bit unsigned integer from P, 0 if no more
GetNextItemShortStringReturn next CSV string from P, nil if no more
GetNextItemStringReturn next CSV string from P, nil if no more
GetNextItemTrimedReturn trimmed next CSV string from P
GetNextItemTrimedCRLFReturn next CRLF separated value string from P, ending #10 or #13#10 trimmed
GetNextItemTrimedEscapedReturn trimmed next CSV string from P, ignoring any Escaped char
GetNextTChar64Return next CSV string from P as a #0-ended buffer, false if no more
GetUnQuoteCsvItemReturn n-th indexed CSV string (unquoted if needed) in P, starting at Index=0 for first one
GuidToRawUtf8Convert a TGuid into 38 chars encoded { text } as RawUtf8
GuidToShortConvert a TGuid into text
GuidToShortConvert a TGuid into text
GuidToStringConvert a TGuid into into 38 chars encoded { text } as RTL string
GuidToTextAppend a TGuid binary content as 36 chars text
HexDisplayToBinFast conversion from hexa chars in reverse order into a binary buffer
HexDisplayToCardinalFast conversion from hexa chars in reverse order into a cardinal
HexDisplayToInt64Inline gives an error under release conditions with (old?) FPC fast conversion from hexa chars in reverse order into a cardinal
HexDisplayToInt64Fast conversion from hexa chars in reverse order into a cardinal
HexToBinFast conversion from hexa chars into binary data
HexToBinFast conversion from hexa chars into binary data
HexToBinFast conversion from hexa chars into binary data
HexToBinFastFast conversion with no validity check from hexa chars into binary data
HexToCharInternal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64
HexToCharFast conversion from one hexa char pair into a 8-bit AnsiChar
HexToCharValidInternal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64
HexToCharValidFast conversion from one hexa char pair into a 8-bit AnsiChar
HexToWideCharFast conversion from two hexa bytes into a 16-bit UTF-16 WideChar
HtmlEscapeEscape some UTF-8 text into HTML
HtmlEscapeStringEscape some RTL string text into UTF-8 HTML
HumanHexCompareFast comparison between two ToHumanHex() hexa values
HumanHexCompareFast comparison between two ToHumanHex() hexa values
HumanHexToBinFast conversion from ToHumanHex() hexa chars into binary data
HumanHexToBinFast conversion from ToHumanHex() hexa chars into binary data
IdemPCharAndGetNextItemReturn true if IdemPChar(source,searchUp) matches, and retrieve the value item
Int18ToChars3Compute the value as encoded by TTextWriter.AddInt18ToChars3() method
Int18ToChars3Compute the value as encoded by TTextWriter.AddInt18ToChars3() method
Int32ToUtf8Fast RawUtf8 version of 32-bit IntToStr()
Int32ToUtf8Fast RawUtf8 version of 32-bit IntToStr()
Int64DynArrayToCsvReturn the corresponding CSV text from a dynamic array of 64-bit integers
Int64DynArrayToCsvReturn the corresponding CSV text from a dynamic array of 64-bit integers
Int64ToHexFast conversion from a Int64 value into hexa chars, ready to be displayed
Int64ToHexFast conversion from a Int64 value into hexa chars, ready to be displayed
Int64ToHexLowerFast conversion from a pointer data into hexa chars, ready to be displayed
Int64ToHexShortFast conversion from a Int64 value into hexa chars, ready to be displayed
Int64ToHexShortFast conversion from a Int64 value into hexa chars, ready to be displayed
Int64ToHexStringFast conversion from a Int64 value into hexa chars, ready to be displayed
Int64ToUtf8Fast RawUtf8 version of 64-bit IntToStr()
Int64ToUtf8Delphi 2007 has trouble inlining this fast RawUtf8 version of 64-bit IntToStr()
IntegerDynArrayToCsvReturn the corresponding CSV text from a dynamic array of 32-bit integer
IntegerDynArrayToCsvReturn the corresponding CSV text from a dynamic array of 32-bit integer
IntToStringFaster than default SysUtils.IntToStr implementation
IntToStringFaster than default SysUtils.IntToStr implementation
IntToStringFaster than default SysUtils.IntToStr implementation
IntToThousandStringConvert an integer value into its textual representation with thousands marked
IPToCardinalConvert an IPv4 'x.x.x.x' text into its 32-bit value
IPToCardinalConvert an IPv4 'x.x.x.x' text into its 32-bit value
IPToCardinalConvert an IPv4 'x.x.x.x' text into its 32-bit value, 0 or localhost
IsHexFast check if the supplied Hex buffer is an hexadecimal representation of a binary buffer of a given number of bytes
KConvert a count to a human readable value power-of-two metric value
KConvert a count to a human readable value power-of-two metric value
KBDelphi 2007 is buggy as hell convert a string size to a human readable value
KBConvert a size to a human readable value power-of-two metric value
KBConvert a size to a human readable value
KBDelphi 2007 is buggy as hell convert a size to a human readable value
KBNoSpaceDelphi 2007 is buggy as hell convert a size to a human readable value
KBUConvert a size to a human readable value
MakeConcatenate several arguments into an UTF-8 string
MakeConcatenate several arguments into an UTF-8 string
MakeCsvCreate a CSV text from some values
MakeFileNameMakePath() variant which can handle the file extension specifically
MakePathAppend some path parts into a single file name with proper path delimiters
MakeStringConcatenate several arguments into a RTL string
MicroSecFromDelphi 2007 is buggy as hell compute elapsed time into a human readable value, from a Start value
MicroSecToStringDelphi 2007 is buggy as hell convert a micro seconds elapsed time into a human readable value
MicroSecToStringDelphi 2007 is buggy as hell convert a micro seconds elapsed time into a human readable value
MilliSecToStringDelphi 2007 is buggy as hell convert a milliseconds elapsed time into a human readable value
NanoSecToStringConvert a nano seconds elapsed time into a human readable value
NeedsHtmlEscapeCheck if some UTF-8 text would need HTML escaping
NeedsXmlEscapeCheck if some UTF-8 text would need XML escaping
NormalizeDirectoryExistsJust a wrapper around EnsureDirectoryExists(NormalizeFileName(MakePath([Part])))
ObjectToJsonWill serialize any TObject into its UTF-8 JSON representation
ObjectToJsonWill serialize any TObject into its UTF-8 JSON representation
ObjectToJsonDebugWill serialize any TObject into its expanded UTF-8 JSON representation
OctToBinConversion from octal C-like escape into binary data
OctToBinConversion from octal C-like escape into binary data
PointerToHexFast conversion from a pointer data into hexa chars, ready to be displayed
PointerToHexFast conversion from a pointer data into hexa chars, ready to be displayed
PointerToHexShortFast conversion from a pointer data into hexa chars, ready to be displayed
PrependPrepend some text to a RawByteString variable with no code page conversion
PrependPrepend some text items at the beginning of a RawByteString variable
PrependPrepend some text items at the beginning of a RawUtf8 variable
PrependPrepend one char to a RawByteString variable with no code page conversion
RawByteStringToStreamCreate a TStream from a string content
RawUtf8ArrayToCsvReturn the corresponding CSV text from a dynamic array of UTF-8 strings
RawUtf8ArrayToQuotedCsvReturn the corresponding CSV quoted text from a dynamic array of UTF-8 strings
RawUtf8ToGuidConvert some UTF-8 encoded text into a TGuid
RawUtf8ToGuidConvert some UTF-8 encoded text into a TGuid
ReadStringFromStreamRead UTF-8 text from a TStream saved with len prefix by WriteStringToStream
RenameInCsvChange a Value within a CSV string
SecToStringDelphi 2007 is buggy as hell convert a seconds elapsed time into a human readable value
SetBitCsvRetrieve the next CSV separated bit index
StatusCodeToErrorMsgConvert any HTTP_* constant to an integer error code and its English text
StrCurr64Internal fast INTEGER Curr64 (value*10000) value to text conversion
StreamChangeToRawByteStringIterative function to retrieve the new content appended to a stream
StreamToRawByteStringRead a TStream content into a String
StringToConsoleDirect conversion of a RTL string into a console OEM-encoded String
StringToGuidConvert some RTL string text into a TGuid
StrToCurr64Convert a string into its INTEGER Curr64 (value*10000) representation
StrToCurrencyConvert a string into its currency representation
TextToGuidConvert some text into its TGuid binary value
ToHexShortFast conversion for up to 256-bit of little-endian input into non-zero hexa
ToUtf8Convert any Variant/TVarData into UTF-8 encoded String
ToUtf8Convert any Variant into UTF-8 encoded String
ToUtf8Fast RawUtf8 version of 32-bit IntToStr()
ToUtf8Convert a TGuid into 36 chars encoded text as RawUtf8
ToUtf8Fast RawUtf8 version of 64-bit IntToStr()
TrimGuidTrim any space and '{' '-' '}' chars from input to get a 32-char TGuid hexa
TrimMinDisplayHexTrim right '0' chars in a text buffer - e.g. from BinToHexLower()
UInt2DigitsToShortCreates a 2 digits short string from a 0..99 value
UInt2DigitsToShortFastCreates a 2 digits short string from a 0..99 value
UInt32ToUtf8Optimized conversion of a cardinal into RawUtf8
UInt32ToUtf8Optimized conversion of a cardinal into RawUtf8
UInt3DigitsToShortCreates a 3 digits short string from a 0..999 value
UInt3DigitsToUtf8Creates a 3 digits string from a 0..999 value as '000'..'999'
UInt4DigitsToShortCreates a 4 digits short string from a 0..9999 value
UInt4DigitsToUtf8Creates a 4 digits string from a 0..9999 value as '0000'..'9999'
UInt64ToUtf8Fast RawUtf8 version of 64-bit IntToStr(), with proper QWord support
UnescapeHexUn-escape \xx or \c encoded chars into a new RawUtf8 string
UnescapeHexBufferUn-escape \xx or \c encoded chars from a pre-allocated buffer
VariantCompAsTextInternal low-level function to compare two variants with RawUt8 conversion
VariantSaveJsonSave a variant value into a JSON content
VariantSaveJsonSave a variant value into a JSON content
VariantToTempUtf8Convert any Variant into a JSON-compatible UTF-8 encoded temporary buffer
VariantToTextConvert any non-null Variant into UTF-8 encoded String
VariantToUtf8Convert any Variant into UTF-8 encoded String
VariantToUtf8Convert any Variant into UTF-8 encoded String
VariantToUtf8Convert any Variant into UTF-8 encoded String
VarRecAsCheck if a supplied "array of const" argument is an instance of a given class
VarRecAsCharGet an open array (const Args: array of const) character argument
VarRecToDoubleConvert an open array (const Args: array of const) argument to a floating point value
VarRecToInlineValueConvert an open array (const Args: array of const) argument to a value encoded as with :(...): inlined parameters in FormatUtf8(Format,Args,Params)
VarRecToInt64Convert an open array (const Args: array of const) argument to an Int64
VarRecToTempUtf8Convert an open array (const Args: array of const) argument to an UTF-8 encoded text, using a specified temporary buffer
VarRecToUtf8Convert an open array (const Args: array of const) argument to an UTF-8 encoded text
VarRecToUtf8IsStringConvert an open array (const Args: array of const) argument to an UTF-8 encoded text, returning FALSE if the argument was not a string value
WriteStringToStreamWrite an UTF-8 text into a TStream with a len prefix - see ReadStringFromStream
XmlEscapeEscape some UTF-8 text into XML

1.6.1. AddPrefixToCsv

function AddPrefixToCsv(Csv: PUtf8Char; const Prefix: RawUtf8; Sep: AnsiChar = ','): RawUtf8;

Append some prefix to all CSV values

 AddPrefixToCsv('One,Two,Three','Pre')='PreOne,PreTwo,PreThree'

1.6.2. AddToCsv

procedure AddToCsv(const Value: RawUtf8; var Csv: RawUtf8; const Sep: RawUtf8 = ',');

Append a Value to a CSV string


1.6.3. Append

procedure Append(var Text: RawByteString; const Added: RawByteString); overload;

Append one text item to a RawByteString variable with no code page conversion


1.6.4. Append

procedure Append(var Text: RawByteString; Added: pointer; AddedLen: PtrInt); overload;

Append one text buffer to a RawByteString variable with no code page conversion


1.6.5. Append

procedure Append(var Text: RawUtf8; Added: pointer; AddedLen: PtrInt); overload;

Append one text buffer to a RawUtf8 variable with no code page conversion


1.6.6. Append

procedure Append(var Text: RawByteString; const Args: array of const); overload;

Append some text items to a RawByteString variable


1.6.7. Append

procedure Append(var Text: RawUtf8; const Added: RawByteString); overload;

Append one text item to a RawUtf8 variable with no code page conversion


1.6.8. Append

procedure Append(var Text: RawUtf8; const Args: array of const); overload;

Append some text items to a RawUtf8 variable
- see also AppendLine() below if you need a separator


1.6.9. Append

procedure Append(var Text: RawUtf8; Added: AnsiChar); overload;

Append one char to a RawUtf8 variable with no code page conversion


1.6.10. Append

procedure Append(var Text: RawUtf8; const Added1, Added2: RawByteString); overload;

Append two text items to a RawUtf8 variable with no code page conversion


1.6.11. AppendCsvValues

procedure AppendCsvValues(const Csv: string; const Values: array of string; var result: string; const AppendBefore: string = #13#10);

Append some text lines with the supplied Values[]
- if any Values[] item is '', no line is added
- otherwise, appends 'Caption: Value', with Caption taken from CSV


1.6.12. AppendLine

procedure AppendLine(var Text: RawUtf8; const Args: array of const; const Separator: shortstring = #13#10);

Append some text to a RawUtf8, ensuring previous text is separated with CRLF
- could be used e.g. to update HTTP headers


1.6.13. BinBitsToHexDisplayLowerShort16

procedure BinBitsToHexDisplayLowerShort16(Bin: Int64; BinBits: PtrInt; var Result: TShort16);

Fast conversion from up to 64-bit of binary data into lowercase hexa chars
- warning: here binary size is in bits (typically 1..64), not bytes


1.6.14. BinToHex

function BinToHex(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;

Fast conversion from binary data into hexa chars


1.6.15. BinToHex

procedure BinToHex(Bin, Hex: PAnsiChar; BinBytes: PtrInt); overload;

Fast conversion from binary data into hexa chars
- BinBytes contain the bytes count to be converted: Hex^ must contain enough space for at least BinBytes*2 chars
- using this function with BinBytes^ as an integer value will encode it in low-endian order (less-signignifican byte first): don't use it for display


1.6.16. BinToHex

function BinToHex(const Bin: RawByteString): RawUtf8; overload;

Fast conversion from binary data into hexa chars


1.6.17. BinToHexDisplay

procedure BinToHexDisplay(Bin, Hex: PAnsiChar; BinBytes: PtrInt); overload;

Fast conversion from binary data into hexa chars, ready to be displayed
- BinBytes contain the bytes count to be converted: Hex^ must contain enough space for at least BinBytes*2 chars
- using this function with Bin^ as an integer value will encode it in big-endian order (most-signignifican byte first): use it for display


1.6.18. BinToHexDisplay

function BinToHexDisplay(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;

Fast conversion from binary data into hexa chars, ready to be displayed


1.6.19. BinToHexDisplayFile

function BinToHexDisplayFile(Bin: PAnsiChar; BinBytes: PtrInt): TFileName;

Fast conversion from binary data into hexa lowercase chars, ready to be used as a convenient TFileName prefix


1.6.20. BinToHexDisplayLower

function BinToHexDisplayLower(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;

Fast conversion from binary data into lowercase hexa chars


1.6.21. BinToHexDisplayLower

procedure BinToHexDisplayLower(Bin, Hex: PAnsiChar; BinBytes: PtrInt); overload;

Fast conversion from binary data into lowercase hexa chars
- BinBytes contain the bytes count to be converted: Hex^ must contain enough space for at least BinBytes*2 chars
- using this function with Bin^ as an integer value will encode it in big-endian order (most-signignifican byte first): use it for display


1.6.22. BinToHexDisplayLowerShort

function BinToHexDisplayLowerShort(Bin: PAnsiChar; BinBytes: PtrInt): ShortString;

Fast conversion from up to 127 bytes of binary data into lowercase hexa chars


1.6.23. BinToHexDisplayLowerShort16

function BinToHexDisplayLowerShort16(Bin: Int64; BinBytes: PtrInt): TShort16;

Fast conversion from up to 64-bit of binary data into lowercase hexa chars


1.6.24. BinToHexLower

procedure BinToHexLower(Bin: PAnsiChar; BinBytes: PtrInt; var result: RawUtf8); overload;

Fast conversion from binary data into lowercase hexa chars


1.6.25. BinToHexLower

function BinToHexLower(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;

Fast conversion from binary data into lowercase hexa chars


1.6.26. BinToHexLower

procedure BinToHexLower(Bin, Hex: PAnsiChar; BinBytes: PtrInt); overload;

Fast conversion from binary data into lowercase hexa chars
- BinBytes contain the bytes count to be converted: Hex^ must contain enough space for at least BinBytes*2 chars
- using this function with BinBytes^ as an integer value will encode it in low-endian order (less-signignifican byte first): don't use it for display


1.6.27. BinToHexLower

function BinToHexLower(const Bin: RawByteString): RawUtf8; overload;

Fast conversion from binary data into lowercase hexa chars


1.6.28. By100ToTwoDigitString

procedure By100ToTwoDigitString(value: cardinal; const valueunit: ShortString; var result: TShort16);

Convert "valueunit" values into x or x.xx text with up to 2 digits
- supplied value should be the actual unit value * 100


1.6.29. ByteToHex

function ByteToHex(P: PAnsiChar; Value: byte): PAnsiChar;

Append one byte as hexadecimal char pairs, into a text buffer


1.6.30. CardinalToHex

function CardinalToHex(aCardinal: cardinal): RawUtf8;

Fast conversion from a cardinal value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- reverse function of HexDisplayToCardinal()


1.6.31. CardinalToHexLower

function CardinalToHexLower(aCardinal: cardinal): RawUtf8;

Fast conversion from a cardinal value into hexa chars, ready to be displayed
- use internally BinToHexDisplayLower()
- reverse function of HexDisplayToCardinal()


1.6.32. CardinalToHexShort

function CardinalToHexShort(aCardinal: cardinal): TShort16;

Fast conversion from a cardinal value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- such result type would avoid a string allocation on heap


1.6.33. Char2ToByte

function Char2ToByte(P: PUtf8Char; out Value: cardinal; ConvertHexToBinTab: PByteArray): boolean;

Fast conversion of 2 digit characters into a 0..99 value
- returns FALSE on success, TRUE if P^ is not correct


1.6.34. Char3ToWord

function Char3ToWord(P: PUtf8Char; out Value: cardinal; ConvertHexToBinTab: PByteArray): boolean;

Fast conversion of 3 digit characters into a 0..9999 value
- returns FALSE on success, TRUE if P^ is not correct


1.6.35. Char4ToWord

function Char4ToWord(P: PUtf8Char; out Value: cardinal; ConvertHexToBinTab: PByteArray): boolean;

Fast conversion of 4 digit characters into a 0..9999 value
- returns FALSE on success, TRUE if P^ is not correct


1.6.36. Chars3ToInt18

function Chars3ToInt18(P: pointer): cardinal;

Revert the value as encoded by TTextWriter.AddInt18ToChars3() or Int18ToChars3()
- no range check is performed: you should ensure that the incoming text follows the expected 3-chars layout


1.6.37. ConsoleObject

procedure ConsoleObject(Value: TObject; Options: TTextWriterWriteObjectOptions = [woHumanReadable]);

A wrapper around ConsoleWrite(ObjectToJson(Value))


1.6.38. ConsoleShowFatalException

procedure ConsoleShowFatalException(E: Exception; WaitForEnterKey: boolean = true);

Could be used in the main program block of a console application to handle unexpected fatal exceptions
- WaitForEnterKey=true won't do anything on POSIX (to avoid locking a daemon)
- typical use may be:

begin
  try
    ... // main console process
  except
    on E: Exception do
      ConsoleShowFatalException(E);
  end;
end.

1.6.39. ConsoleWrite

procedure ConsoleWrite(const Fmt: RawUtf8; const Args: array of const; Color: TConsoleColor = ccLightGray; NoLineFeed: boolean = false); overload;

Write some text to the console using a given color
- redirect to mormot.core.os ConsoleWrite() with proper thread safety


1.6.40. ConsoleWrite

procedure ConsoleWrite(const Args: array of const; Color: TConsoleColor = ccLightGray; NoLineFeed: boolean = false); overload;

Write some text to the console using a given color
- redirect to mormot.core.os ConsoleWrite() with proper thread safety


1.6.41. ConsoleWriteRaw

procedure ConsoleWriteRaw(const Args: array of const; NoLineFeed: boolean = false); overload;

Write some text to the console using the current color
- similar to writeln() but redirect to ConsoleWrite() with proper thread safety


1.6.42. crc32cUtf8ToHex

function crc32cUtf8ToHex(const str: RawUtf8): RawUtf8;

Compute the hexadecimal representation of the crc32 checkum of a given text
- wrapper around CardinalToHex(crc32c(...))


1.6.43. CsvContains

function CsvContains(const Csv, Value: RawUtf8; Sep: AnsiChar = ','; CaseSensitive: boolean = true): boolean;

Quickly check if Value is in Csv with no temporary memory allocation


1.6.44. CsvGuessSeparator

function CsvGuessSeparator(const Csv: RawUtf8): AnsiChar;

Recognize #9 ';' or ',' as separator in a CSV text
- to implement a separator-tolerant CSV parser


1.6.45. CsvOfValue

function CsvOfValue(const Value: RawUtf8; Count: cardinal; const Sep: RawUtf8 = ','): RawUtf8;

Return a CSV list of the iterated same value
- e.g. CsvOfValue('?',3)='?,?,?'


1.6.46. CsvToInt64DynArray

function CsvToInt64DynArray(Csv: PUtf8Char; Sep: AnsiChar = ','): TInt64DynArray; overload;

Convert the strings in the specified CSV text into a dynamic array of integer


1.6.47. CsvToInt64DynArray

procedure CsvToInt64DynArray(Csv: PUtf8Char; var List: TInt64DynArray; Sep: AnsiChar = ','); overload;

Append the strings in the specified CSV text into a dynamic array of integer


1.6.48. CsvToIntegerDynArray

procedure CsvToIntegerDynArray(Csv: PUtf8Char; var List: TIntegerDynArray; Sep: AnsiChar = ',');

Append the strings in the specified CSV text into a dynamic array of integer


1.6.49. CsvToRawUtf8DynArray

procedure CsvToRawUtf8DynArray(const Csv, Sep, SepEnd: RawUtf8; var List: TRawUtf8DynArray); overload;

Add the strings in the specified CSV text into a dynamic array of UTF-8 strings
- warning: will add the strings, so List := nil may be needed before call


1.6.50. CsvToRawUtf8DynArray

procedure CsvToRawUtf8DynArray(Csv: PUtf8Char; var List: TRawUtf8DynArray; Sep: AnsiChar = ','; TrimItems: boolean = false; AddVoidItems: boolean = false; Quote: AnsiChar = #0); overload;

Add the strings in the specified CSV text into a dynamic array of UTF-8 strings
- warning: will add the strings, so List := nil may be needed before call


1.6.51. CsvToRawUtf8DynArray

function CsvToRawUtf8DynArray(const Csv: RawUtf8; const Sep: RawUtf8 = ','; const SepEnd: RawUtf8 = ''): TRawUtf8DynArray; overload;

Convert the strings in the specified CSV text into a dynamic array of UTF-8 strings


1.6.52. Curr64ToPChar

function Curr64ToPChar(const Value: Int64; Dest: PUtf8Char): PtrInt;

Convert an INTEGER Curr64 (value*10000) into a string
- this type is compatible with currency memory mapping with PInt64(@Curr)^
- fast conversion, using only integer operations
- decimals are joined by 2 (no decimal, 2 decimals, 4 decimals)
- return the number of chars written to Dest^


1.6.53. Curr64ToStr

function Curr64ToStr(const Value: Int64): RawUtf8; overload;

Convert an INTEGER Curr64 (value*10000) into a string
- this type is compatible with currency memory mapping with PInt64(@Curr)^
- fast conversion, using only integer operations
- decimals are joined by 2 (no decimal, 2 decimals, 4 decimals)


1.6.54. Curr64ToStr

procedure Curr64ToStr(const Value: Int64; var result: RawUtf8); overload;

Convert an INTEGER Curr64 (value*10000) into a string
- this type is compatible with currency memory mapping with PInt64(@Curr)^
- fast conversion, using only integer operations
- decimals are joined by 2 (no decimal, 2 decimals, 4 decimals)


1.6.55. Curr64ToString

function Curr64ToString(Value: Int64): string;

Convert a currency value from its Int64 binary representation into its numerical text equivalency
- decimals are joined by 2 (no decimal, 2 decimals, 4 decimals)


1.6.56. CurrencyToStr

function CurrencyToStr(const Value: currency): RawUtf8;

Convert a currency value into a string
- fast conversion, using only integer operations
- decimals are joined by 2 (no decimal, 2 decimals, 4 decimals)


1.6.57. DefaultSynLogExceptionToStr

function DefaultSynLogExceptionToStr(WR: TTextWriter; const Context: TSynLogExceptionContext): boolean;

The default Exception handler for logging
- defined here to be called e.g. by ESynException.CustomLog() as default


1.6.58. DoubleToJson

function DoubleToJson(tmp: PShortString; Value: double; NoExp: boolean): PShortString;

Convert a 64-bit floating-point value to its JSON text equivalency
- on Delphi Win32, calls FloatToText() in ffGeneral mode
- on other platforms, i.e. Delphi Win64 and all FPC targets, will use our own faster Fabian Loitsch's Grisu algorithm
- returns the number as text (stored into tmp variable), or "Infinity", "-Infinity", and "NaN" for corresponding IEEE special values
- result is a PShortString either over tmp, or JSON_NAN[]


1.6.59. DoubleToShort

function DoubleToShort(S: PShortString; const Value: double): integer;

Convert a 64-bit floating-point value to its numerical text equivalency
- on Delphi Win32, calls FloatToText() in ffGeneral mode
- on other platforms, i.e. Delphi Win64 and all FPC targets, will use our own faster Fabian Loitsch's Grisu algorithm implementation
- returns the count of chars stored into S, i.e. length(S)


1.6.60. DoubleToShortNoExp

function DoubleToShortNoExp(S: PShortString; const Value: double): integer;

Convert a 64-bit floating-point value to its numerical text equivalency without scientific notation
- on Delphi Win32, calls FloatToText() in ffGeneral mode
- on other platforms, i.e. Delphi Win64 and all FPC targets, will use our own faster Fabian Loitsch's Grisu algorithm implementation
- returns the count of chars stored into S, i.e. length(S)


1.6.61. DoubleToStr

procedure DoubleToStr(Value: Double; var result: RawUtf8); overload;

Convert a 64-bit floating-point value to its numerical text equivalency


1.6.62. DoubleToStr

function DoubleToStr(Value: Double): RawUtf8; overload;

Convert a 64-bit floating-point value to its numerical text equivalency


1.6.63. DoubleToString

function DoubleToString(Value: Double): string;

Convert a floating-point value to its numerical text equivalency


1.6.64. EnsureDirectoryExists

function EnsureDirectoryExists(const Part: array of const; RaiseExceptionOnCreationFailure: ExceptionClass = nil): TFileName; overload;

Just a wrapper around EnsureDirectoryExists(MakePath([Part]))


1.6.65. EscapeChar

function EscapeChar(const src: RawUtf8; const toescape: TSynAnsicharSet; escape: AnsiChar = '\'): RawUtf8;

Escape as \char pair some chars from a set into a new RawUtf8 string
- by definition, escape should be part of the toescape set


1.6.66. EscapeCharBuffer

function EscapeCharBuffer(src, dest: PUtf8Char; srclen: integer; const toescape: TSynAnsicharSet; escape: AnsiChar = '\'): PUtf8Char;

Escape as \char pair some chars from a set into a pre-allocated buffer
- dest^ should have at least srclen * 2 bytes, for \char pairs
- by definition, escape should be part of the toescape set


1.6.67. EscapeHex

function EscapeHex(const src: RawUtf8; const toescape: TSynAnsicharSet; escape: AnsiChar = '\'): RawUtf8;

Escape as \xx hexadecimal some chars from a set into a new RawUtf8 string
- as used e.g. by LdapEscape()


1.6.68. EscapeHexBuffer

function EscapeHexBuffer(src, dest: PUtf8Char; srclen: integer; const toescape: TSynAnsicharSet; escape: AnsiChar = '\'): PUtf8Char;

Escape as \xx hexadecimal some chars from a set into a pre-allocated buffer
- dest^ should have at least srclen * 3 bytes, for \## trios


1.6.69. ExtendedToJson

function ExtendedToJson(tmp: PShortString; Value: TSynExtended; Precision: integer; NoExp: boolean): PShortString;

Convert a floating-point value to its JSON text equivalency
- depending on the platform, it may either call str() or FloatToText() in ffGeneral mode (the shortest possible decimal string using fixed or scientific format)
- returns the number as text (stored into tmp variable), or "Infinity", "-Infinity", and "NaN" for corresponding IEEE special values
- result is a PShortString either over tmp, or JSON_NAN[]


1.6.70. ExtendedToShort

function ExtendedToShort(S: PShortString; Value: TSynExtended; Precision: integer): integer;

Convert a floating-point value to its numerical text equivalency
- on Delphi Win32, calls FloatToText() in ffGeneral mode; on FPC uses str()
- DOUBLE_PRECISION will redirect to DoubleToShort() and its faster Fabian Loitsch's Grisu algorithm if available
- returns the count of chars stored into S, i.e. length(S)


1.6.71. ExtendedToShortNoExp

function ExtendedToShortNoExp(S: PShortString; Value: TSynExtended; Precision: integer): integer;

Convert a floating-point value to its numerical text equivalency without scientification notation
- DOUBLE_PRECISION will redirect to DoubleToShortNoExp() and its faster Fabian Loitsch's Grisu algorithm if available - or calls str(Value:0:precision,S)
- returns the count of chars stored into S, i.e. length(S)


1.6.72. ExtendedToStr

procedure ExtendedToStr(Value: TSynExtended; Precision: integer; var result: RawUtf8); overload;

Convert a floating-point value to its numerical text equivalency


1.6.73. ExtendedToStr

function ExtendedToStr(Value: TSynExtended; Precision: integer): RawUtf8; overload;

Convert a floating-point value to its numerical text equivalency


1.6.74. FindCsvIndex

function FindCsvIndex(Csv: PUtf8Char; const Value: RawUtf8; Sep: AnsiChar = ','; CaseSensitive: boolean = true; TrimValue: boolean = false): integer;

Return the index of a Value in a CSV string
- start at Index=0 for first one
- return -1 if specified Value was not found in CSV items


1.6.75. FloatStrCopy

function FloatStrCopy(s, d: PUtf8Char): PUtf8Char;

Copy a floating-point text buffer with proper correction and validation
- will correct on the fly '.5' -> '0.5' and '-.5' -> '-0.5'
- will end not only on #0 but on any char not matching 1[.2[e[-]3]] pattern
- is used when the input comes from a third-party source with no regular output, e.g. a database driver, via TTextWriter.AddFloatStr


1.6.76. FloatToJsonNan

function FloatToJsonNan(s: PShortString): PShortString;

Recognize if the supplied text is NAN/INF/+INF/-INF, i.e. not a number
- returns the number as text (stored into tmp variable), or "Infinity", "-Infinity", and "NaN" for corresponding IEEE special values
- result is a PShortString either over tmp, or JSON_NAN[]


1.6.77. FloatToShortNan

function FloatToShortNan(const s: ShortString): TFloatNan;

Check if the supplied text is NAN/INF/+INF/-INF, i.e. not a number
- as returned by ExtendedToShort/DoubleToShort textual conversion
- such values do appear as IEEE floating points, but are not defined in JSON


1.6.78. FloatToStrNan

function FloatToStrNan(const s: RawUtf8): TFloatNan;

Check if the supplied text is NAN/INF/+INF/-INF, i.e. not a number
- as returned e.g. by ExtendedToStr/DoubleToStr textual conversion
- such values do appear as IEEE floating points, but are not defined in JSON


1.6.79. FormatBuffer

function FormatBuffer(const Format: RawUtf8; const Args: array of const; Dest: pointer; DestLen: PtrInt): PtrInt;

Fast Format() function replacement, tuned for direct memory buffer write
- use the same single token % (and implementation) than FormatUtf8()
- returns the number of UTF-8 bytes appended to Dest^


1.6.80. FormatShort

procedure FormatShort(const Format: RawUtf8; const Args: array of const; var result: ShortString);

Fast Format() function replacement, for UTF-8 content stored in ShortString
- use the same single token % (and implementation) than FormatUtf8()
- ShortString allows fast stack allocation, so is perfect for small content
- truncate result if the text size exceeds 255 bytes


1.6.81. FormatShort16

procedure FormatShort16(const Format: RawUtf8; const Args: array of const; var result: TShort16);

Delphi don't inline "array of const" parameters fast Format() function replacement, for UTF-8 content stored in TShort16
- truncate result if the text size exceeds 16 bytes


1.6.82. FormatString

procedure FormatString(const Format: RawUtf8; const Args: array of const; out result: string); overload;

Fast Format() function replacement, tuned for small content
- use the same single token % (and implementation) than FormatUtf8()


1.6.83. FormatString

function FormatString(const Format: RawUtf8; const Args: array of const): string; overload;

Fast Format() function replacement, tuned for small content
- use the same single token % (and implementation) than FormatUtf8()


1.6.84. FormatToShort

function FormatToShort(const Format: RawUtf8; const Args: array of const): ShortString;

Fast Format() function replacement, for UTF-8 content stored in ShortString


1.6.85. FormatUtf8

procedure FormatUtf8(const Format: RawUtf8; const Args: array of const; out result: RawUtf8); overload;

Fast Format() function replacement, optimized for RawUtf8
- overloaded function, which avoid a temporary RawUtf8 instance on stack


1.6.86. FormatUtf8

function FormatUtf8(const Format: RawUtf8; const Args: array of const): RawUtf8; overload;

Fast Format() function replacement, optimized for RawUtf8
- only supported token is %, which will be written in the resulting string according to each Args[] supplied items - so you will never get any exception as with the SysUtils.Format() when a specifier is incorrect
- resulting string has no length limit and uses fast concatenation
- there is no escape char, so to output a '%' character, you need to use '%' as place-holder, and specify '%' as value in the Args array
- note that, due to a Delphi compiler limitation, cardinal values should be type-casted to Int64() (otherwise the integer mapped value will be converted)
- any supplied TObject instance will be written as their class name
- see FormatSql() and FormatJson() from mormot.core.json for ? placeholders


1.6.87. FormatVariant

function FormatVariant(const Format: RawUtf8; const Args: array of const): variant;

Fast Format() function replacement, for UTF-8 content stored in variant


1.6.88. GetBitCsv

function GetBitCsv(const Bits; BitsCount: integer): RawUtf8;

Convert a set of bit into a CSV content
- each bit is stored as BitIndex+1, and separated by a ','
- several bits set to one can be regrouped via 'first-last,' syntax
- ',0' is always appended at the end of the CSV chunk to mark its end


1.6.89. GetCsvItem

function GetCsvItem(P: PUtf8Char; Index: PtrUInt; Sep: AnsiChar = ','): RawUtf8; overload;

Return n-th indexed CSV string in P, starting at Index=0 for first one


1.6.90. GetCsvItemString

function GetCsvItemString(P: PChar; Index: PtrUInt; Sep: Char = ','): string;

Return n-th indexed CSV string in P, starting at Index=0 for first one
- this function return the RTL string type of the compiler, and therefore can be used with ready to be displayed text


1.6.91. GetFileNameExtIndex

function GetFileNameExtIndex(const FileName, CsvExt: TFileName): integer;

Extract a file extension from a file name, then compare with a comma separated list of extensions
- e.g. GetFileNameExtIndex('test.log','exe,log,map')=1
- will return -1 if no file extension match
- will return any matching extension, starting count at 0
- extension match is case-insensitive


1.6.92. GetFirstCsvItem

function GetFirstCsvItem(const Csv: RawUtf8; Sep: AnsiChar = ','): RawUtf8;

Return first CSV string in the supplied UTF-8 content


1.6.93. GetLastCsvItem

function GetLastCsvItem(const Csv: RawUtf8; Sep: AnsiChar = ','): RawUtf8;

Return last CSV string in the supplied UTF-8 content


1.6.94. GetNextItem

procedure GetNextItem(var P: PUtf8Char; Sep, Quote: AnsiChar; var result: RawUtf8); overload;

Return next CSV string (unquoted if needed) from P
- P=nil after call when end of text is reached


1.6.95. GetNextItem

function GetNextItem(var P: PUtf8Char; Sep: AnsiChar = ','): RawUtf8; overload;

Return next CSV string from P
- P=nil after call when end of text is reached


1.6.96. GetNextItem

procedure GetNextItem(var P: PUtf8Char; Sep: AnsiChar; var result: RawUtf8); overload;

Return next CSV string from P
- P=nil after call when end of text is reached


1.6.97. GetNextItemCardinal

function GetNextItemCardinal(var P: PUtf8Char; Sep: AnsiChar = ','): PtrUInt;

Return next CSV string as unsigned integer from P, 0 if no more
- if Sep is #0, it won't be searched for


1.6.98. GetNextItemCardinalStrict

function GetNextItemCardinalStrict(var P: PUtf8Char): PtrUInt;

Return next CSV string as unsigned integer from P, 0 if no more
- P^ will point to the first non digit character (the item separator, e.g. ',' for CSV)


1.6.99. GetNextItemCardinalW

function GetNextItemCardinalW(var P: PWideChar; Sep: WideChar = ','): PtrUInt;

Return next CSV string as unsigned integer from P, 0 if no more
- this version expects P^ to point to an Unicode char array


1.6.100. GetNextItemCurrency

function GetNextItemCurrency(var P: PUtf8Char; Sep: AnsiChar = ','): currency; overload;

Return next CSV string as currency from P, 0.0 if no more
- if Sep is #0, will return all characters until next whitespace char


1.6.101. GetNextItemCurrency

procedure GetNextItemCurrency(var P: PUtf8Char; out result: currency; Sep: AnsiChar = ','); overload;

Return next CSV string as currency from P, 0.0 if no more
- if Sep is #0, will return all characters until next whitespace char


1.6.102. GetNextItemDouble

function GetNextItemDouble(var P: PUtf8Char; Sep: AnsiChar = ','): double;

Return next CSV string as double from P, 0.0 if no more
- if Sep is #0, will return all characters until next whitespace char


1.6.103. GetNextItemHexa

function GetNextItemHexa(var P: PUtf8Char; Sep: AnsiChar = ','): QWord;

Return next CSV hexadecimal string as 64-bit unsigned integer from P
- returns 0 if no valid hexadecimal text is available in P
- if Sep is #0, it won't be searched for
- will first fill the 64-bit value with 0, then decode each two hexadecimal characters available in P
- could be used to decode TTextWriter.AddBinToHexDisplayMinChars() output


1.6.104. GetNextItemHexDisplayToBin

function GetNextItemHexDisplayToBin(var P: PUtf8Char; Bin: PByte; BinBytes: PtrInt; Sep: AnsiChar = ','): boolean;

Decode next CSV hexadecimal string from P, nil if no more or not matching BinBytes
- Bin is filled with 0 if the supplied CSV content is invalid
- if Sep is #0, it will read the hexadecimal chars until a whitespace is reached


1.6.105. GetNextItemInt64

function GetNextItemInt64(var P: PUtf8Char; Sep: AnsiChar = ','): Int64;

Return next CSV string as 64-bit signed integer from P, 0 if no more
- if Sep is #0, it won't be searched for


1.6.106. GetNextItemInteger

function GetNextItemInteger(var P: PUtf8Char; Sep: AnsiChar = ','): PtrInt;

Return next CSV string as signed integer from P, 0 if no more
- if Sep is #0, it won't be searched for


1.6.107. GetNextItemMultiple

function GetNextItemMultiple(var P: PUtf8Char; const Sep: RawUtf8; var Next: RawUtf8): AnsiChar; overload;

Return next CSV string from P from several separator characters
- P=nil after call when end of text is reached
- returns the character which ended the result string, i.e. #0 or one of Sep


1.6.108. GetNextItemQWord

function GetNextItemQWord(var P: PUtf8Char; Sep: AnsiChar = ','): QWord;

Return next CSV string as 64-bit unsigned integer from P, 0 if no more
- if Sep is #0, it won't be searched for


1.6.109. GetNextItemShortString

procedure GetNextItemShortString(var P: PUtf8Char; Dest: PShortString; Sep: AnsiChar = ',');

Return next CSV string from P, nil if no more
- output text would be trimmed from any left or right space
- will always append a trailing #0 - excluded from Dest length (0..254)


1.6.110. GetNextItemString

function GetNextItemString(var P: PChar; Sep: Char = ','): string;

Return next CSV string from P, nil if no more
- this function returns the RTL string type of the compiler, and therefore can be used with ready to be displayed text (e.g. for the UI)


1.6.111. GetNextItemTrimed

procedure GetNextItemTrimed(var P: PUtf8Char; Sep: AnsiChar; var result: RawUtf8);

Return trimmed next CSV string from P
- P=nil after call when end of text is reached


1.6.112. GetNextItemTrimedCRLF

procedure GetNextItemTrimedCRLF(var P: PUtf8Char; var result: RawUtf8);

Return next CRLF separated value string from P, ending #10 or #13#10 trimmed
- any kind of line feed (CRLF or LF) will be handled, on all operating systems
- as used e.g. by TSynNameValue.InitFromCsv and TDocVariantData.InitFromPairs
- P=nil after call when end of text is reached


1.6.113. GetNextItemTrimedEscaped

procedure GetNextItemTrimedEscaped(var P: PUtf8Char; Sep, Esc: AnsiChar; var result: RawUtf8);

Return trimmed next CSV string from P, ignoring any Escaped char
- P=nil after call when end of text is reached


1.6.114. GetNextTChar64

function GetNextTChar64(var P: PUtf8Char; Sep: AnsiChar; out Buf: TChar64): PtrInt;

Return next CSV string from P as a #0-ended buffer, false if no more
- if Sep is #0, will copy all characters until next whitespace char
- returns the number of bytes stored into Buf[]


1.6.115. GetUnQuoteCsvItem

function GetUnQuoteCsvItem(P: PUtf8Char; Index: PtrUInt; Sep: AnsiChar = ','; Quote: AnsiChar = ''''): RawUtf8; overload;

Return n-th indexed CSV string (unquoted if needed) in P, starting at Index=0 for first one


1.6.116. GuidToRawUtf8

function GuidToRawUtf8(const guid: TGuid): RawUtf8;

Convert a TGuid into 38 chars encoded { text } as RawUtf8
- will return e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {})
- if you do not need the embracing { }, use ToUtf8() overloaded function


1.6.117. GuidToShort

function GuidToShort(const guid: TGuid): TGuidShortString; overload;

Convert a TGuid into text
- will return e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {})
- using a ShortString will allow fast allocation on the stack, so is preferred e.g. when providing a Guid to a ESynException.CreateUtf8()


1.6.118. GuidToShort

procedure GuidToShort(const guid: TGuid; out dest: TGuidShortString); overload;

Convert a TGuid into text
- will return e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {})
- using a ShortString will allow fast allocation on the stack, so is preferred e.g. when providing a Guid to a ESynException.CreateUtf8()


1.6.119. GuidToString

function GuidToString(const guid: TGuid): string;

Convert a TGuid into into 38 chars encoded { text } as RTL string
- will return e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {})
- this version is faster than the one supplied by SysUtils


1.6.120. GuidToText

function GuidToText(P: PUtf8Char; guid: PByteArray): PUtf8Char;

Append a TGuid binary content as 36 chars text
- will store e.g. '3F2504E0-4F89-11D3-9A0C-0305E82C3301' (without any {})
- this will be the format used for JSON encoding, e.g.

 { "UID": "C9A646D3-9C61-4CB7-BFCD-EE2522C8F633" }

1.6.121. HexDisplayToBin

function HexDisplayToBin(Hex: PAnsiChar; Bin: PByte; BinBytes: PtrInt): boolean;

Fast conversion from hexa chars in reverse order into a binary buffer


1.6.122. HexDisplayToCardinal

function HexDisplayToCardinal(Hex: PAnsiChar; out aValue: cardinal): boolean;

Fast conversion from hexa chars in reverse order into a cardinal
- reverse function of CardinalToHex()
- returns false and set aValue=0 if Hex is not a valid hexadecimal 32-bit unsigned integer
- returns true and set aValue with the decoded number, on success


1.6.123. HexDisplayToInt64

function HexDisplayToInt64(const Hex: RawByteString): Int64; overload;

Fast conversion from hexa chars in reverse order into a cardinal
- reverse function of Int64ToHex()
- returns 0 if the supplied text buffer is not a valid hexadecimal 64-bit signed integer


1.6.124. HexDisplayToInt64

function HexDisplayToInt64(Hex: PAnsiChar; out aValue: Int64): boolean; overload;

Inline gives an error under release conditions with (old?) FPC fast conversion from hexa chars in reverse order into a cardinal
- reverse function of Int64ToHex()
- returns false and set aValue=0 if Hex is not a valid hexadecimal 64-bit signed integer
- returns true and set aValue with the decoded number, on success


1.6.125. HexToBin

function HexToBin(Hex: PAnsiChar; Bin: PByte; BinBytes: PtrInt): boolean; overload;

Fast conversion from hexa chars into binary data
- BinBytes contain the bytes count to be converted: Hex^ must contain at least BinBytes*2 chars to be converted, and Bin^ enough space
- if Bin=nil, no output data is written, but the Hex^ format is checked
- return false if any invalid (non hexa) char is found in Hex^
- using this function with Bin^ as an integer value will decode in big-endian order (most-signignifican byte first)


1.6.126. HexToBin

function HexToBin(const Hex: RawUtf8): RawByteString; overload;

Fast conversion from hexa chars into binary data


1.6.127. HexToBin

function HexToBin(Hex: PAnsiChar; HexLen: PtrInt; var Bin: RawByteString): boolean; overload;

Fast conversion from hexa chars into binary data


1.6.128. HexToBinFast

procedure HexToBinFast(Hex: PAnsiChar; Bin: PByte; BinBytes: PtrInt);

Fast conversion with no validity check from hexa chars into binary data


1.6.129. HexToChar

function HexToChar(Hex: PAnsiChar; Bin: PUtf8Char): boolean; overload;

Fast conversion from one hexa char pair into a 8-bit AnsiChar
- return false if any invalid (non hexa) char is found in Hex^
- similar to HexToBin(Hex,Bin,1) but with Bin<>nil
- use HexToCharValid if you want to check a hexadecimal char content


1.6.130. HexToChar

function HexToChar(Hex: PAnsiChar; Bin: PUtf8Char; HexToBin: PByteArray): boolean; overload;

Internal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64


1.6.131. HexToCharValid

function HexToCharValid(Hex: PAnsiChar): boolean; overload;

Fast conversion from one hexa char pair into a 8-bit AnsiChar
- return false if any invalid (non hexa) char is found in Hex^
- similar to HexToBin(Hex,nil,1)


1.6.132. HexToCharValid

function HexToCharValid(Hex: PAnsiChar; HexToBin: PByteArray): boolean; overload;

Internal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64


1.6.133. HexToWideChar

function HexToWideChar(Hex: PUtf8Char): cardinal;

Fast conversion from two hexa bytes into a 16-bit UTF-16 WideChar
- as used by JsonUnicodeEscapeToUtf8() for \u#### chars unescape
- similar to HexDisplayToBin(Hex,@wordvar,2)
- returns 0 on malformated input


1.6.134. HtmlEscape

function HtmlEscape(const text: RawUtf8; fmt: TTextWriterHtmlFormat = hfAnyWhere): RawUtf8;

Escape some UTF-8 text into HTML
- just a wrapper around TTextWriter.AddHtmlEscape() process, replacing < > & " chars depending on the HTML layer


1.6.135. HtmlEscapeString

function HtmlEscapeString(const text: string; fmt: TTextWriterHtmlFormat = hfAnyWhere): RawUtf8;

Escape some RTL string text into UTF-8 HTML
- just a wrapper around TTextWriter.AddHtmlEscapeString() process, replacing < > & " chars depending on the HTML layer


1.6.136. HumanHexCompare

function HumanHexCompare(a, b: PUtf8Char): integer; overload;

Fast comparison between two ToHumanHex() hexa values


1.6.137. HumanHexCompare

function HumanHexCompare(const a, b: RawUtf8): integer; overload;

Fast comparison between two ToHumanHex() hexa values


1.6.138. HumanHexToBin

function HumanHexToBin(const hex: RawUtf8; var Bin: RawByteString): boolean; overload;

Fast conversion from ToHumanHex() hexa chars into binary data


1.6.139. HumanHexToBin

function HumanHexToBin(const hex: RawUtf8): RawByteString; overload;

Fast conversion from ToHumanHex() hexa chars into binary data


1.6.140. IdemPCharAndGetNextItem

function IdemPCharAndGetNextItem(var source: PUtf8Char; const searchUp: RawUtf8; var Item: RawUtf8; Sep: AnsiChar = #13): boolean;

Return true if IdemPChar(source,searchUp) matches, and retrieve the value item
- typical use may be:

 if IdemPCharAndGetNextItem(P,
   'CONTENT-DISPOSITION: FORM-DATA; NAME="',Name,'"') then ...

1.6.141. Int18ToChars3

procedure Int18ToChars3(Value: cardinal; var result: RawUtf8); overload;

Compute the value as encoded by TTextWriter.AddInt18ToChars3() method


1.6.142. Int18ToChars3

function Int18ToChars3(Value: cardinal): RawUtf8; overload;

Compute the value as encoded by TTextWriter.AddInt18ToChars3() method


1.6.143. Int32ToUtf8

procedure Int32ToUtf8(Value: PtrInt; var result: RawUtf8); overload;

Fast RawUtf8 version of 32-bit IntToStr()
- result as var parameter saves a local assignment and a try..finally


1.6.144. Int32ToUtf8

function Int32ToUtf8(Value: PtrInt): RawUtf8; overload;

Fast RawUtf8 version of 32-bit IntToStr()


1.6.145. Int64DynArrayToCsv

function Int64DynArrayToCsv(Values: PInt64Array; ValuesCount: integer; const Prefix: RawUtf8 = ''; const Suffix: RawUtf8 = ''; InlinedValue: boolean = false; SepChar: AnsiChar = ','): RawUtf8; overload;

Return the corresponding CSV text from a dynamic array of 64-bit integers
- you can set some custom Prefix and Suffix text


1.6.146. Int64DynArrayToCsv

function Int64DynArrayToCsv(const Values: TInt64DynArray; const Prefix: RawUtf8 = ''; const Suffix: RawUtf8 = ''; InlinedValue: boolean = false; SepChar: AnsiChar = ','): RawUtf8; overload;

Return the corresponding CSV text from a dynamic array of 64-bit integers
- you can set some custom Prefix and Suffix text


1.6.147. Int64ToHex

procedure Int64ToHex(aInt64: Int64; var result: RawUtf8); overload;

Fast conversion from a Int64 value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- reverse function of HexDisplayToInt64()


1.6.148. Int64ToHex

function Int64ToHex(aInt64: Int64): RawUtf8; overload;

Fast conversion from a Int64 value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- reverse function of HexDisplayToInt64()


1.6.149. Int64ToHexLower

function Int64ToHexLower(aInt64: Int64): RawUtf8; overload;

Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally DisplayMinChars() and BinToHexDisplay()


1.6.150. Int64ToHexShort

procedure Int64ToHexShort(aInt64: Int64; out result: TShort16); overload;

Fast conversion from a Int64 value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- such result type would avoid a string allocation on heap


1.6.151. Int64ToHexShort

function Int64ToHexShort(aInt64: Int64): TShort16; overload;

Fast conversion from a Int64 value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- such result type would avoid a string allocation on heap


1.6.152. Int64ToHexString

function Int64ToHexString(aInt64: Int64): string;

Fast conversion from a Int64 value into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
- reverse function of HexDisplayToInt64()


1.6.153. Int64ToUtf8

procedure Int64ToUtf8(Value: Int64; var result: RawUtf8); overload;

Delphi 2007 has trouble inlining this fast RawUtf8 version of 64-bit IntToStr()
- result as var parameter saves a local assignment and a try..finally


1.6.154. Int64ToUtf8

function Int64ToUtf8(Value: Int64): RawUtf8; overload;

Fast RawUtf8 version of 64-bit IntToStr()


1.6.155. IntegerDynArrayToCsv

function IntegerDynArrayToCsv(Values: PIntegerArray; ValuesCount: integer; const Prefix: RawUtf8 = ''; const Suffix: RawUtf8 = ''; InlinedValue: boolean = false; SepChar: AnsiChar = ','): RawUtf8; overload;

Return the corresponding CSV text from a dynamic array of 32-bit integer
- you can set some custom Prefix and Suffix text


1.6.156. IntegerDynArrayToCsv

function IntegerDynArrayToCsv(const Values: TIntegerDynArray; const Prefix: RawUtf8 = ''; const Suffix: RawUtf8 = ''; InlinedValue: boolean = false; SepChar: AnsiChar = ','): RawUtf8; overload;

Return the corresponding CSV text from a dynamic array of 32-bit integer
- you can set some custom Prefix and Suffix text


1.6.157. IntToString

function IntToString(Value: Int64): string; overload;

Faster than default SysUtils.IntToStr implementation


1.6.158. IntToString

function IntToString(Value: cardinal): string; overload;

Faster than default SysUtils.IntToStr implementation


1.6.159. IntToString

function IntToString(Value: integer): string; overload;

Faster than default SysUtils.IntToStr implementation


1.6.160. IntToThousandString

function IntToThousandString(Value: integer; const ThousandSep: TShort4 = ','): ShortString;

Convert an integer value into its textual representation with thousands marked
- ThousandSep is the character used to separate thousands in numbers with more than three digits to the left of the decimal separator


1.6.161. IPToCardinal

function IPToCardinal(const aIP: RawUtf8): cardinal; overload;

Convert an IPv4 'x.x.x.x' text into its 32-bit value, 0 or localhost
- result is in little endian order, not network order: 1.2.3.4 becomes $04030201
- returns <> 0 value if the text was a valid IPv4 text, 0 on parsing error
- '' or '127.0.0.1' will also return 0


1.6.162. IPToCardinal

function IPToCardinal(const aIP: RawUtf8; out aValue: cardinal): boolean; overload;

Convert an IPv4 'x.x.x.x' text into its 32-bit value
- result is in little endian order, not network order: 1.2.3.4 becomes $04030201
- returns TRUE if the text was a valid IPv4 text, unserialized as 32-bit aValue
- returns FALSE on parsing error, also setting aValue=0
- '' or '127.0.0.1' will also return false


1.6.163. IPToCardinal

function IPToCardinal(aIP: PUtf8Char; out aValue: cardinal): boolean; overload;

Convert an IPv4 'x.x.x.x' text into its 32-bit value
- result is in little endian order, not network order: 1.2.3.4 becomes $04030201
- returns TRUE if the text was a valid IPv4 text, unserialized as 32-bit aValue
- returns FALSE on parsing error, also setting aValue=0
- '' or '127.0.0.1' will also return false


1.6.164. IsHex

function IsHex(const Hex: RawByteString; BinBytes: PtrInt): boolean;

Fast check if the supplied Hex buffer is an hexadecimal representation of a binary buffer of a given number of bytes


1.6.165. K

function K(value: Int64): TShort16; overload;

Convert a count to a human readable value power-of-two metric value
- append E, P, T, G, M, K symbol, with one fractional digit


1.6.166. K

procedure K(value: Int64; out result: TShort16); overload;

Convert a count to a human readable value power-of-two metric value
- append E, P, T, G, M, K symbol, with one fractional digit


1.6.167. KB

function KB(bytes: Int64): TShort16; overload;

Convert a size to a human readable value
- append EB, PB, TB, GB, MB, KB or B symbol with preceding space
- for EB, PB, TB, GB, MB and KB, add one fractional digit


1.6.168. KB

function KB(bytes: Int64; nospace: boolean): TShort16; overload;

Delphi 2007 is buggy as hell convert a size to a human readable value
- append EB, PB, TB, GB, MB, KB or B symbol with or without preceding space
- for EB, PB, TB, GB, MB and KB, add one fractional digit


1.6.169. KB

function KB(const buffer: RawByteString): TShort16; overload;

Delphi 2007 is buggy as hell convert a string size to a human readable value
- append EB, PB, TB, GB, MB, KB or B symbol
- for EB, PB, TB, GB, MB and KB, add one fractional digit


1.6.170. KB

procedure KB(bytes: Int64; out result: TShort16; nospace: boolean); overload;

Convert a size to a human readable value power-of-two metric value
- append EB, PB, TB, GB, MB, KB or B symbol with or without preceding space
- for EB, PB, TB, GB, MB and KB, add one fractional digit


1.6.171. KBNoSpace

function KBNoSpace(bytes: Int64): TShort16;

Delphi 2007 is buggy as hell convert a size to a human readable value
- append EB, PB, TB, GB, MB, KB or B symbol without preceding space
- for EB, PB, TB, GB, MB and KB, add one fractional digit


1.6.172. KBU

procedure KBU(bytes: Int64; var result: RawUtf8);

Convert a size to a human readable value
- append EB, PB, TB, GB, MB, KB or B symbol
- for EB, PB, TB, GB, MB and KB, add one fractional digit


1.6.173. Make

procedure Make(const Args: array of const; var Result: RawUtf8; const IncludeLast: RawUtf8 = ''); overload;

Concatenate several arguments into an UTF-8 string


1.6.174. Make

function Make(const Args: array of const): RawUtf8; overload;

Concatenate several arguments into an UTF-8 string


1.6.175. MakeCsv

function MakeCsv(const Value: array of const; EndWithComma: boolean = false; Comma: AnsiChar = ','): RawUtf8;

Create a CSV text from some values


1.6.176. MakeFileName

function MakeFileName(const Part: array of const; LastIsExt: boolean = true): TFileName;

MakePath() variant which can handle the file extension specifically


1.6.177. MakePath

function MakePath(const Part: array of const; EndWithDelim: boolean = false; Delim: AnsiChar = PathDelim): TFileName;

Append some path parts into a single file name with proper path delimiters
- set EndWithDelim=true if you want to create e.g. a full folder name
- similar to os.path.join() in the Python RTL
- e.g. on Windows: MakePath(['abc', 1, 'toto.json']) = 'abc\1\toto.json'


1.6.178. MakeString

function MakeString(const Args: array of const): string;

Concatenate several arguments into a RTL string


1.6.179. MicroSecFrom

function MicroSecFrom(Start: QWord): TShort16;

Delphi 2007 is buggy as hell compute elapsed time into a human readable value, from a Start value
- will get current QueryPerformanceMicroSeconds() and compute against Start
- append 'us', 'ms', 's', 'm', 'h' and 'd' symbol for the given value range, with two fractional digits


1.6.180. MicroSecToString

procedure MicroSecToString(Micro: QWord; out result: TShort16); overload;

Delphi 2007 is buggy as hell convert a micro seconds elapsed time into a human readable value
- append 'us', 'ms', 's', 'm', 'h' and 'd' symbol for the given value range, with two fractional digits


1.6.181. MicroSecToString

function MicroSecToString(Micro: QWord): TShort16; overload;

Delphi 2007 is buggy as hell convert a micro seconds elapsed time into a human readable value
- append 'us', 'ms', 's', 'm', 'h' and 'd' symbol for the given value range, with two fractional digits


1.6.182. MilliSecToString

function MilliSecToString(MS: QWord): TShort16;

Delphi 2007 is buggy as hell convert a milliseconds elapsed time into a human readable value
- append 'ms', 's', 'm', 'h' and 'd' symbol for the given value range, with two fractional digits


1.6.183. NanoSecToString

procedure NanoSecToString(Nano: QWord; out result: TShort16);

Convert a nano seconds elapsed time into a human readable value
- append 'ns', 'us', 'ms', 's', 'm', 'h' and 'd' symbol for the given value range, with two fractional digits


1.6.184. NeedsHtmlEscape

function NeedsHtmlEscape(text: PUtf8Char; fmt: TTextWriterHtmlFormat): boolean;

Check if some UTF-8 text would need HTML escaping


1.6.185. NeedsXmlEscape

function NeedsXmlEscape(text: PUtf8Char): boolean;

Check if some UTF-8 text would need XML escaping


1.6.186. NormalizeDirectoryExists

function NormalizeDirectoryExists(const Part: array of const; RaiseExceptionOnCreationFailure: ExceptionClass = nil): TFileName; overload;

Just a wrapper around EnsureDirectoryExists(NormalizeFileName(MakePath([Part])))


1.6.187. ObjectToJson

procedure ObjectToJson(Value: TObject; var result: RawUtf8; Options: TTextWriterWriteObjectOptions = [woDontStoreDefault]); overload;

Will serialize any TObject into its UTF-8 JSON representation


1.6.188. ObjectToJson

function ObjectToJson(Value: TObject; Options: TTextWriterWriteObjectOptions = [woDontStoreDefault]): RawUtf8; overload;

Will serialize any TObject into its UTF-8 JSON representation
- serialize as JSON the published integer, Int64, floating point values, TDateTime (stored as ISO 8601 text), string, variant and enumerate (e.g. boolean) properties of the object (and its parents)
- would set twoForceJsonStandard to force standard (non-extended) JSON
- the enumerates properties are stored with their integer index value
- will write also the properties published in the parent classes
- nested properties are serialized as nested JSON objects
- any TCollection property will also be serialized as JSON arrays
- you can add some custom serializers for ANY class, via mormot.core.json.pas TRttiJson.RegisterCustomSerializer() class method
- call internally TTextWriter.WriteObject() method from DefaultJsonWriter


1.6.189. ObjectToJsonDebug

function ObjectToJsonDebug(Value: TObject): RawUtf8;

Will serialize any TObject into its expanded UTF-8 JSON representation
- includes TEXTWRITEROPTIONS_DEBUG debugger-friendly information, similar to TSynLog, i.e. class name and sets/enumerates as text
- redirect to ObjectToJson() with the proper TTextWriterWriteObjectOptions, since our JSON serialization detects and serialize Exception.Message


1.6.190. OctToBin

function OctToBin(Oct: PAnsiChar; Bin: PByte): PtrInt; overload;

Conversion from octal C-like escape into binary data
- \xxx is converted into a single xxx byte from octal, and \\ into \
- will stop the conversion when Oct^=#0 or when invalid \xxx is reached
- returns the number of bytes written to Bin^


1.6.191. OctToBin

function OctToBin(const Oct: RawUtf8): RawByteString; overload;

Conversion from octal C-like escape into binary data
- \xxx is converted into a single xxx byte from octal, and \\ into \


1.6.192. PointerToHex

procedure PointerToHex(aPointer: pointer; var result: RawUtf8); overload;

Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally BinToHexDisplay()


1.6.193. PointerToHex

function PointerToHex(aPointer: pointer): RawUtf8; overload;

Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally BinToHexDisplay()


1.6.194. PointerToHexShort

function PointerToHexShort(aPointer: pointer): TShort16; overload;

Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally DisplayMinChars() and BinToHexDisplay()
- such result type would avoid a string allocation on heap


1.6.195. Prepend

procedure Prepend(var Text: RawUtf8; const Args: array of const); overload;

Prepend some text items at the beginning of a RawUtf8 variable


1.6.196. Prepend

procedure Prepend(var Text: RawByteString; Added: AnsiChar); overload;

Prepend one char to a RawByteString variable with no code page conversion


1.6.197. Prepend

procedure Prepend(var Text: RawByteString; const Added: RawByteString); overload;

Prepend some text to a RawByteString variable with no code page conversion


1.6.198. Prepend

procedure Prepend(var Text: RawByteString; const Args: array of const); overload;

Prepend some text items at the beginning of a RawByteString variable


1.6.199. RawByteStringToStream

function RawByteStringToStream(const aString: RawByteString): TStream;

Create a TStream from a string content
- uses RawByteString for byte storage, whatever the codepage is
- in fact, the returned TStream is a TRawByteString instance, since this function is just a wrapper around:

 result := TRawByteStringStream.Create(aString);

1.6.200. RawUtf8ArrayToCsv

function RawUtf8ArrayToCsv(const Values: array of RawUtf8; const Sep: RawUtf8 = ','; HighValues: integer = -1; Reverse: boolean = false): RawUtf8;

Return the corresponding CSV text from a dynamic array of UTF-8 strings


1.6.201. RawUtf8ArrayToQuotedCsv

function RawUtf8ArrayToQuotedCsv(const Values: array of RawUtf8; const Sep: RawUtf8 = ','; Quote: AnsiChar = ''''): RawUtf8;

Return the corresponding CSV quoted text from a dynamic array of UTF-8 strings
- apply QuoteStr() function to each Values[] item


1.6.202. RawUtf8ToGuid

function RawUtf8ToGuid(const text: RawByteString; out guid: TGuid): boolean; overload;

Convert some UTF-8 encoded text into a TGuid
- expect e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {}) or '3F2504E0-4F89-11D3-9A0C-0305E82C3301' (without the {}) or even '3F2504E04F8911D39A0C0305E82C3301' following TGuid order (not HexToBin)


1.6.203. RawUtf8ToGuid

function RawUtf8ToGuid(const text: RawByteString): TGuid; overload;

Convert some UTF-8 encoded text into a TGuid
- expect e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {}) or '3F2504E0-4F89-11D3-9A0C-0305E82C3301' (without the {}) or even '3F2504E04F8911D39A0C0305E82C3301' following TGuid order (not HexToBin)
- return {00000000-0000-0000-0000-000000000000} if the supplied text buffer is not a valid TGuid


1.6.204. ReadStringFromStream

function ReadStringFromStream(S: TStream; MaxAllowedSize: integer = 255): RawUtf8;

Read UTF-8 text from a TStream saved with len prefix by WriteStringToStream
- format is Length(integer):Text - use StreamToRawByteString for raw data
- will return '' if there is no such text in the stream
- you can set a MaxAllowedSize value, if you know how long the size should be
- it will read from the current position in S: so if you just write into S, it could be a good idea to rewind it before call, e.g.:

  WriteStringToStream(Stream,aUtf8Text);
  Stream.Seek(0,soBeginning);
  str := ReadStringFromStream(Stream);

1.6.205. RenameInCsv

function RenameInCsv(const OldValue, NewValue: RawUtf8; var Csv: RawUtf8; const Sep: RawUtf8 = ','): boolean;

Change a Value within a CSV string


1.6.206. SecToString

function SecToString(S: QWord): TShort16;

Delphi 2007 is buggy as hell convert a seconds elapsed time into a human readable value
- append 's', 'm', 'h' and 'd' symbol for the given value range, with two fractional digits


1.6.207. SetBitCsv

procedure SetBitCsv(var Bits; BitsCount: integer; var P: PUtf8Char);

Retrieve the next CSV separated bit index
- each bit was stored as BitIndex+1, i.e. 0 to mark end of CSV chunk
- several bits set to one can be regrouped via 'first-last,' syntax


1.6.208. StatusCodeToErrorMsg

function StatusCodeToErrorMsg(Code: integer): RawUtf8;

Convert any HTTP_* constant to an integer error code and its English text
- returns e.g. 'HTTP Error 404 - Not Found', calling StatusCodeToText()


1.6.209. StrCurr64

function StrCurr64(P: PAnsiChar; const Value: Int64): PAnsiChar;

Internal fast INTEGER Curr64 (value*10000) value to text conversion
- expect the last available temporary char position in P
- return the last written char position (write in reverse order in P^)
- will return 0 for Value=0, or a string representation with always 4 decimals (e.g. 1->'0.0001' 500->'0.0500' 25000->'2.5000' 30000->'3.0000')
- is called by Curr64ToPChar() and Curr64ToStr() functions


1.6.210. StreamChangeToRawByteString

function StreamChangeToRawByteString( aStream: TStream; var aPosition: Int64): RawByteString;

Iterative function to retrieve the new content appended to a stream
- aPosition should be set to 0 before the initial call


1.6.211. StreamToRawByteString

function StreamToRawByteString(aStream: TStream; aSize: Int64 = -1; aCodePage: integer = CP_RAWBYTESTRING): RawByteString;

Read a TStream content into a String
- it will read binary or text content from the current position until the end (using TStream.Size)
- uses RawByteString for byte storage, whatever the codepage is


1.6.212. StringToConsole

function StringToConsole(const S: string): RawByteString;

Direct conversion of a RTL string into a console OEM-encoded String
- under Windows, will use the CP_OEMCP encoding
- under Linux, will expect the console to be defined with UTF-8 encoding


1.6.213. StringToGuid

function StringToGuid(const text: string): TGuid;

Convert some RTL string text into a TGuid
- expect e.g. '{3F2504E0-4F89-11D3-9A0C-0305E82C3301}' (with the {})
- return {00000000-0000-0000-0000-000000000000} if the supplied text buffer is not a valid TGuid


1.6.214. StrToCurr64

function StrToCurr64(P: PUtf8Char; NoDecimal: PBoolean = nil): Int64;

Convert a string into its INTEGER Curr64 (value*10000) representation
- this type is compatible with currency memory mapping with PInt64(@Curr)^
- fast conversion, using only integer operations
- if NoDecimal is defined, will be set to TRUE if there is no decimal, AND the returned value will be an Int64 (not a PInt64(@Curr)^)


1.6.215. StrToCurrency

function StrToCurrency(P: PUtf8Char): currency;

Convert a string into its currency representation
- will call StrToCurr64()


1.6.216. TextToGuid

function TextToGuid(P: PUtf8Char; Guid: PByteArray): PUtf8Char;

Convert some text into its TGuid binary value
- expect e.g. '3F2504E0-4F89-11D3-9A0C-0305E82C3301' (without any {}) but will ignore internal '-' so '3F2504E04F8911D39A0C0305E82C3301' is also fine
- note: TGuid binary order does not follow plain HexToBin or HexDisplayToBin
- return nil if the supplied text buffer is not a valid TGuid
- this will be the format used for JSON encoding, e.g.

 { "Uid": "C9A646D3-9C61-4CB7-BFCD-EE2522C8F633" }

1.6.217. ToHexShort

function ToHexShort(P: pointer; Len: PtrInt): TShort64;

Fast conversion for up to 256-bit of little-endian input into non-zero hexa
- Len should be <= 32 bytes, to fit in a TShort64 result
- use internally DisplayMinChars() and BinToHexDisplay()


1.6.218. ToUtf8

function ToUtf8(const guid: TGuid): RawUtf8; overload;

Convert a TGuid into 36 chars encoded text as RawUtf8
- will return e.g. '3F2504E0-4F89-11D3-9A0C-0305E82C3301' (without the {})
- if you need the embracing { }, use GuidToRawUtf8() function instead


1.6.219. ToUtf8

function ToUtf8(Value: Int64): RawUtf8; overload;

Fast RawUtf8 version of 64-bit IntToStr()


1.6.220. ToUtf8

function ToUtf8(Value: PtrInt): RawUtf8; overload;

Fast RawUtf8 version of 32-bit IntToStr()


1.6.221. ToUtf8

function ToUtf8(const V: TVarData): RawUtf8; overload;

Convert any Variant/TVarData into UTF-8 encoded String
- use VariantSaveJson() instead if you need a conversion to JSON with custom parameters
- note: null will be returned as 'null'


1.6.222. ToUtf8

function ToUtf8(const V: Variant): RawUtf8; overload;

Convert any Variant into UTF-8 encoded String
- use VariantSaveJson() instead if you need a conversion to JSON with custom parameters
- note: null will be returned as 'null'


1.6.223. TrimGuid

function TrimGuid(var text: RawUtf8): boolean;

Trim any space and '{' '-' '}' chars from input to get a 32-char TGuid hexa
- change in-place the text into lowercase hexadecimal
- returns true if resulting text is a 128-bit cleaned hexa, false otherwise


1.6.224. TrimMinDisplayHex

function TrimMinDisplayHex(Text: PUtf8Char; TextLen: PtrInt): PtrInt;

Trim right '0' chars in a text buffer - e.g. from BinToHexLower()


1.6.225. UInt2DigitsToShort

function UInt2DigitsToShort(Value: byte): TShort4;

Creates a 2 digits short string from a 0..99 value
- using TShort4 as returned string would avoid a string allocation on heap
- could be used e.g. as parameter to FormatUtf8()


1.6.226. UInt2DigitsToShortFast

function UInt2DigitsToShortFast(Value: byte): TShort4;

Creates a 2 digits short string from a 0..99 value
- won't test Value>99 as UInt2DigitsToShort()


1.6.227. UInt32ToUtf8

procedure UInt32ToUtf8(Value: PtrUInt; var result: RawUtf8); overload;

Optimized conversion of a cardinal into RawUtf8


1.6.228. UInt32ToUtf8

function UInt32ToUtf8(Value: PtrUInt): RawUtf8; overload;

Optimized conversion of a cardinal into RawUtf8


1.6.229. UInt3DigitsToShort

function UInt3DigitsToShort(Value: cardinal): TShort4;

Creates a 3 digits short string from a 0..999 value
- using TShort4 as returned string would avoid a string allocation on heap
- could be used e.g. as parameter to FormatUtf8()


1.6.230. UInt3DigitsToUtf8

function UInt3DigitsToUtf8(Value: cardinal): RawUtf8;

Creates a 3 digits string from a 0..999 value as '000'..'999'
- consider using UInt3DigitsToShort() to avoid temporary memory allocation, e.g. when used as FormatUtf8() parameter


1.6.231. UInt4DigitsToShort

function UInt4DigitsToShort(Value: cardinal): TShort4;

Creates a 4 digits short string from a 0..9999 value
- using TShort4 as returned string would avoid a string allocation on heap
- could be used e.g. as parameter to FormatUtf8()


1.6.232. UInt4DigitsToUtf8

function UInt4DigitsToUtf8(Value: cardinal): RawUtf8;

Creates a 4 digits string from a 0..9999 value as '0000'..'9999'
- consider using UInt4DigitsToShort() to avoid temporary memory allocation, e.g. when used as FormatUtf8() parameter


1.6.233. UInt64ToUtf8

procedure UInt64ToUtf8(Value: QWord; var result: RawUtf8);

Fast RawUtf8 version of 64-bit IntToStr(), with proper QWord support


1.6.234. UnescapeHex

function UnescapeHex(const src: RawUtf8; escape: AnsiChar = '\'): RawUtf8;

Un-escape \xx or \c encoded chars into a new RawUtf8 string
- any CR/LF after \ will also be ignored


1.6.235. UnescapeHexBuffer

function UnescapeHexBuffer(src, dest: PUtf8Char; escape: AnsiChar = '\'): PUtf8Char;

Un-escape \xx or \c encoded chars from a pre-allocated buffer
- any CR/LF after \ will also be ignored
- dest^ should have at least the same length than src^


1.6.236. VariantCompAsText

function VariantCompAsText(A, B: PVarData; caseInsensitive: boolean): integer;

Internal low-level function to compare two variants with RawUt8 conversion
- as used e.g. by FastVarDataComp() for complex or diverse VType


1.6.237. VariantSaveJson

procedure VariantSaveJson(const Value: variant; Escape: TTextWriterKind; var result: RawUtf8); overload;

Save a variant value into a JSON content
- just a wrapper around the _VariantSaveJson procedure redirection


1.6.238. VariantSaveJson

function VariantSaveJson(const Value: variant; Escape: TTextWriterKind = twJsonEscape): RawUtf8; overload;

Save a variant value into a JSON content
- just a wrapper around the _VariantSaveJson procedure redirection


1.6.239. VariantToTempUtf8

procedure VariantToTempUtf8(const V: variant; var Res: TTempUtf8; var wasString: boolean);

Convert any Variant into a JSON-compatible UTF-8 encoded temporary buffer
- this function would allocate a RawUtf8 in Res.TempRawUtf8 only if needed, but use the supplied Res.Temp[] buffer for numbers to text conversion - caller should ensure to make RawUtf8(Res.TempRawUtf8) := '' once done with it
- wasString is set if the V value was a text
- empty and null variants will be stored as 'null' text - as expected by JSON
- booleans will be stored as 'true' or 'false' - as expected by JSON
- custom variant types (e.g. TDocVariant) will be stored as JSON


1.6.240. VariantToText

function VariantToText(const V: Variant; var Text: RawUtf8): boolean; overload;

Convert any non-null Variant into UTF-8 encoded String
- empty and null variants will return false (usable e.g. for mustache data)


1.6.241. VariantToUtf8

function VariantToUtf8(const V: Variant; var Text: RawUtf8): boolean; overload;

Convert any Variant into UTF-8 encoded String
- use VariantSaveJson() instead if you need a conversion to JSON with custom parameters
- returns TRUE if the V value was a text, FALSE if was not (e.g. a number)
- empty and null variants will be stored as 'null' text - as expected by JSON
- custom variant types (e.g. TDocVariant) will be stored as JSON


1.6.242. VariantToUtf8

function VariantToUtf8(const V: Variant): RawUtf8; overload;

Convert any Variant into UTF-8 encoded String
- use VariantSaveJson() instead if you need a conversion to JSON with custom parameters
- note: null will be returned as 'null'


1.6.243. VariantToUtf8

procedure VariantToUtf8(const V: Variant; var result: RawUtf8; var wasString: boolean); overload;

Convert any Variant into UTF-8 encoded String
- use VariantSaveJson() instead if you need a conversion to JSON with custom parameters
- wasString is set if the V value was a text
- empty and null variants will be stored as 'null' text - as expected by JSON
- custom variant types (e.g. TDocVariant) will be stored as JSON


1.6.244. VarRecAs

function VarRecAs(const aArg: TVarRec; aClass: TClass): pointer;

Check if a supplied "array of const" argument is an instance of a given class


1.6.245. VarRecAsChar

function VarRecAsChar(const V: TVarRec): integer;

Get an open array (const Args: array of const) character argument
- only handle varChar and varWideChar kind of arguments


1.6.246. VarRecToDouble

function VarRecToDouble(const V: TVarRec; out value: double): boolean;

Convert an open array (const Args: array of const) argument to a floating point value
- returns TRUE and set Value if the supplied argument is a number (e.g. vtInteger, vtInt64, vtCurrency or vtExtended)
- returns FALSE if the argument is not a number
- note that, due to a Delphi compiler limitation, cardinal values should be type-casted to Int64() (otherwise the integer mapped value will be converted)


1.6.247. VarRecToInlineValue

procedure VarRecToInlineValue(const V: TVarRec; var result: RawUtf8);

Convert an open array (const Args: array of const) argument to a value encoded as with :(...): inlined parameters in FormatUtf8(Format,Args,Params)
- note that, due to a Delphi compiler limitation, cardinal values should be type-casted to Int64() (otherwise the integer mapped value will be converted)
- any supplied TObject instance will be written as their class name


1.6.248. VarRecToInt64

function VarRecToInt64(const V: TVarRec; out value: Int64): boolean;

Convert an open array (const Args: array of const) argument to an Int64
- returns TRUE and set Value if the supplied argument is a vtInteger, vtInt64 or vtBoolean
- returns FALSE if the argument is not an integer
- note that, due to a Delphi compiler limitation, cardinal values should be type-casted to Int64() (otherwise the integer mapped value will be converted)


1.6.249. VarRecToTempUtf8

function VarRecToTempUtf8(const V: TVarRec; var Res: TTempUtf8; wasString: PBoolean = nil): PtrInt;

Convert an open array (const Args: array of const) argument to an UTF-8 encoded text, using a specified temporary buffer
- this function would allocate a RawUtf8 in Res.TempRawUtf8 only if needed, but use the supplied Res.Temp[] buffer for numbers to text conversion - caller should ensure to make RawUtf8(Res.TempRawUtf8) := '' once done with it
- it would return the number of UTF-8 bytes, i.e. Res.Len
- note that, due to a Delphi compiler limitation, cardinal values should be type-casted to Int64() (otherwise the integer mapped value will be converted)
- any supplied TObject instance will be written as their class name


1.6.250. VarRecToUtf8

procedure VarRecToUtf8(const V: TVarRec; var result: RawUtf8; wasString: PBoolean = nil);

Convert an open array (const Args: array of const) argument to an UTF-8 encoded text
- note that, due to a Delphi compiler limitation, cardinal values should be type-casted to Int64() (otherwise the integer mapped value will be converted)
- any supplied TObject instance will be written as their class name


1.6.251. VarRecToUtf8IsString

function VarRecToUtf8IsString(const V: TVarRec; var value: RawUtf8): boolean;

Convert an open array (const Args: array of const) argument to an UTF-8 encoded text, returning FALSE if the argument was not a string value


1.6.252. WriteStringToStream

function WriteStringToStream(S: TStream; const Text: RawUtf8): boolean;

Write an UTF-8 text into a TStream with a len prefix - see ReadStringFromStream
- format is Length(integer):Text - use RawByteStringToStream for raw data


1.6.253. XmlEscape

function XmlEscape(const text: RawUtf8): RawUtf8;

Escape some UTF-8 text into XML
- just a wrapper around TTextWriter.AddXmlEscape() process


1.7. Variables implemented in the mormot.core.text unit

1.7.1. BinaryVariantLoadAsJson

BinaryVariantLoadAsJson: procedure(var Value: variant; Json: PUtf8Char; TryCustomVariant: pointer);

Unserialize a JSON content into a variant
- is properly implemented by mormot.core.json.pas: if this unit is not included in the project, this function is nil
- used by mormot.core.data.pas RTTI_BINARYLOAD[tkVariant]() for complex types


1.7.2. ConvertHexToBin

ConvertHexToBin: THexToDualByte;

A conversion table from hexa chars into binary data
- [0..255] range maps the 0..15 binary, [256..511] maps 0..15 binary shl 4
- returns 255 for any character out of 0..9,A..Z,a..z range
- used e.g. by HexToBin() function
- is defined globally, since may be used from an inlined function


1.7.3. DefaultJsonWriter

DefaultJsonWriter: TBaseWriterClass = TTextWriter;

Contains the default JSON serialization class for the framework
- used internally by ObjectToJson/VariantSaveJson to avoid circular references
- will be set to TJsonWriter by mormot.core.json; default TTextWriter would raise an exception on any JSON processing attempt


1.7.4. SmallUInt32Utf8

SmallUInt32Utf8: array[0..999] of RawUtf8;

Naive but efficient cache to avoid string memory allocation for 0..999 small numbers by Int32ToUtf8/UInt32ToUtf8
- use around 16KB of heap (since each item consumes 16 bytes), but increase overall performance and reduce memory allocation (and fragmentation), especially during multi-threaded execution
- noticeable when RawUtf8 strings are used as array indexes (e.g. in mormot.db.nosql.bson)
- less noticeable without any allocation: StrInt32() is faster on a buffer
- is defined globally, since may be used from an inlined function


1.7.5. TSynLogExceptionToStrCustom

TSynLogExceptionToStrCustom: TSynLogExceptionToStr = nil;

Allow to customize the ESynException logging message


1.7.6. TwoDigitsHex

TwoDigitsHex: array[byte] of array[1..2] of AnsiChar;

Fast lookup table for converting hexadecimal numbers from 0 to 15 into their ASCII equivalence
- is local for better code generation


1.7.7. TwoDigitsHexLower

TwoDigitsHexLower: array[byte] of array[1..2] of AnsiChar;

Lowercase hexadecimal lookup table


1.7.8. _Iso8601ToDateTime

_Iso8601ToDateTime: function(const iso: RawByteString): TDateTime;

Date/Time conversion from ISO-8601 text
- is implemented by Iso8601ToDateTime() from mormot.core.datetime.pas: if this unit is not included in the project, this function is nil
- used by TRttiProp.SetValue() for TDateTime properties with a getter


1.7.9. _VariantSaveJson

_VariantSaveJson: procedure(const Value: variant; Escape: TTextWriterKind; var result: RawUtf8);

Save a variant value into a JSON content
- is implemented by mormot.core.json.pas and mormot.core.variants.pas: will raise an exception if none of these units is included in the project
- follows the TTextWriter.AddVariant() and VariantLoadJson() format
- is able to handle simple and custom variant types, for instance:

  VariantSaveJson(1.5)='1.5'
  VariantSaveJson('test')='"test"'
  o := _Json('{ BSON: [ "test", 5.05, 1986 ] }');
  VariantSaveJson(o)='{"BSON":["test",5.05,1986]}'
  o := _Obj(['name','John','doc',_Obj(['one',1,'two',_Arr(['one',2])])]);
  VariantSaveJson(o)='{"name":"John","doc":{"one":1,"two":["one",2]}}'

- note that before Delphi 2009, any varString value is expected to be a RawUtf8 instance - which does make sense in the mORMot area


1.7.10. _VariantToUtf8DateTimeToIso8601

_VariantToUtf8DateTimeToIso8601: procedure(DT: TDateTime; FirstChar: AnsiChar; var result: RawUtf8; WithMS: boolean);

Write a TDateTime into strict ISO-8601 date and/or time text
- is implemented by DateTimeToIso8601TextVar from mormot.core.datetime.pas: if this unit is not included in the project, an ESynException is raised
- used by VariantToUtf8() for TDateTime conversion