
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
| Unit Name | Description | |
|---|---|---|
| mormot.core.base | Framework Core Shared Types and RTL-like Functions | |
| mormot.core.os | Framework Core Low-Level Wrappers to the Operating-System API | |
| mormot.core.unicode | Framework Core Low-Level Unicode UTF-8 UTF-16 Ansi Conversion |
| Objects | Description | |
|---|---|---|
| ESynException | Generic parent class of all custom Exception types of this unit | |
| TEchoWriter | Add optional echoing of the lines to TTextWriter | |
| TTempUtf8 | A memory structure which avoids a temporary RawUtf8 allocation | |
| TTextWriter | Parent to T*Writer text processing classes, with the minimum set of methods |
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;
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 < > & "e; '
- 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
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
TTempUtf8 = record
A memory structure which avoids a temporary RawUtf8 allocation
- used by VarRecToTempUtf8/VariantToTempUtf8 and FormatUtf8/FormatShort
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()
ESynExceptionClass = class of ESynException;
Meta-class of the ESynException hierarchy
TAnsiCharToByte = array[AnsiChar] of byte;
Type of a lookup table used for fast XML/HTML conversion
TAnsiCharToWord = array[AnsiChar] of word;
Type of a lookup table used for fast two-digit chars conversion
TBaseWriterClass = class of TTextWriter;
Class of our simple TEXT format writer to a Stream
TByteToWord = array[byte] of word;
Type of a lookup table used for fast two-digit chars conversion
TChar64 = array[0..63] of AnsiChar;
Some stack-allocated zero-terminated character buffer
- as used by GetNextTChar64
TGuidShortString = string[38];
Stack-allocated ASCII string, used by GuidToShort() function
THexToDualByte = packed array[0..511] of byte;
Type of a lookup table used for fast hexadecimal conversion
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
TOnTextWriterFlush = procedure(Text: PUtf8Char; Len: PtrInt) of object;
Event signature for TTextWriter.OnFlushToStream callback
TShort4 = string[4];
Used e.g. by UInt4DigitsToShort/UInt3DigitsToShort/UInt2DigitsToShort
- such result type would avoid a string allocation on heap
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
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)
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
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
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
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
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
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
TTextWriterWriteObjectOptions = set of TTextWriterWriteObjectOption;
Options set for TTextWriter.WriteObject() method
TEXTWRITEROBJECTOPTIONS_ENUMASTEXT: array[boolean] of TTextWriterWriteObjectOptions = ( [], [woEnumSetsAsText]);
TTextWriter JSON serialization options including woEnumSetsAsText
TEXTWRITEROPTIONS_DEBUG = [woDontStoreDefault, woHumanReadable, woStoreClassName, woStorePointer, woHideSensitivePersonalInformation];
TTextWriter JSON serialization options with debugging/logging information
TEXTWRITEROPTIONS_ENUMASTEXT: array[boolean] of TTextWriterOptions = ( [], [twoEnumSetsAsTextInRecord]);
TTextWriter JSON serialization options including twoEnumSetsAsTextInRecord
TEXTWRITEROPTIONS_RESET = [twoStreamIsOwned, twoStreamIsRawByteString, twoBufferIsExternal];
TTextWriter JSON serialization options which should be preserved
- used e.g. by TTextWriter.CancelAllAsNew to reset its CustomOptions
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]
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()
| Functions or procedures | Description | |
|---|---|---|
| AddPrefixToCsv | Append some prefix to all CSV values | |
| AddToCsv | Append a Value to a CSV string | |
| Append | Append some text items to a RawUtf8 variable | |
| Append | Append one text item to a RawUtf8 variable with no code page conversion | |
| Append | Append two text items to a RawUtf8 variable with no code page conversion | |
| Append | Append one char to a RawUtf8 variable with no code page conversion | |
| Append | Append one text buffer to a RawByteString variable with no code page conversion | |
| Append | Append one text item to a RawByteString variable with no code page conversion | |
| Append | Append some text items to a RawByteString variable | |
| Append | Append one text buffer to a RawUtf8 variable with no code page conversion | |
| AppendCsvValues | Append some text lines with the supplied Values[] | |
| AppendLine | Append some text to a RawUtf8, ensuring previous text is separated with CRLF | |
| BinBitsToHexDisplayLowerShort16 | Fast conversion from up to 64-bit of binary data into lowercase hexa chars | |
| BinToHex | Fast conversion from binary data into hexa chars | |
| BinToHex | Fast conversion from binary data into hexa chars | |
| BinToHex | Fast conversion from binary data into hexa chars | |
| BinToHexDisplay | Fast conversion from binary data into hexa chars, ready to be displayed | |
| BinToHexDisplay | Fast conversion from binary data into hexa chars, ready to be displayed | |
| BinToHexDisplayFile | Fast conversion from binary data into hexa lowercase chars, ready to be used as a convenient TFileName prefix | |
| BinToHexDisplayLower | Fast conversion from binary data into lowercase hexa chars | |
| BinToHexDisplayLower | Fast conversion from binary data into lowercase hexa chars | |
| BinToHexDisplayLowerShort | Fast conversion from up to 127 bytes of binary data into lowercase hexa chars | |
| BinToHexDisplayLowerShort16 | Fast conversion from up to 64-bit of binary data into lowercase hexa chars | |
| BinToHexLower | Fast conversion from binary data into lowercase hexa chars | |
| BinToHexLower | Fast conversion from binary data into lowercase hexa chars | |
| BinToHexLower | Fast conversion from binary data into lowercase hexa chars | |
| BinToHexLower | Fast conversion from binary data into lowercase hexa chars | |
| By100ToTwoDigitString | Convert "valueunit" values into x or x.xx text with up to 2 digits | |
| ByteToHex | Append one byte as hexadecimal char pairs, into a text buffer | |
| CardinalToHex | Fast conversion from a cardinal value into hexa chars, ready to be displayed | |
| CardinalToHexLower | Fast conversion from a cardinal value into hexa chars, ready to be displayed | |
| CardinalToHexShort | Fast conversion from a cardinal value into hexa chars, ready to be displayed | |
| Char2ToByte | Fast conversion of 2 digit characters into a 0..99 value | |
| Char3ToWord | Fast conversion of 3 digit characters into a 0..9999 value | |
| Char4ToWord | Fast conversion of 4 digit characters into a 0..9999 value | |
| Chars3ToInt18 | Revert the value as encoded by TTextWriter.AddInt18ToChars3() or Int18ToChars3() | |
| ConsoleObject | A wrapper around ConsoleWrite(ObjectToJson(Value)) | |
| ConsoleShowFatalException | Could be used in the main program block of a console application to handle unexpected fatal exceptions | |
| ConsoleWrite | Write some text to the console using a given color | |
| ConsoleWrite | Write some text to the console using a given color | |
| ConsoleWriteRaw | Write some text to the console using the current color | |
| crc32cUtf8ToHex | Compute the hexadecimal representation of the crc32 checkum of a given text | |
| CsvContains | Quickly check if Value is in Csv with no temporary memory allocation | |
| CsvGuessSeparator | Recognize #9 ';' or ',' as separator in a CSV text | |
| CsvOfValue | Return a CSV list of the iterated same value | |
| CsvToInt64DynArray | Append the strings in the specified CSV text into a dynamic array of integer | |
| CsvToInt64DynArray | Convert the strings in the specified CSV text into a dynamic array of integer | |
| CsvToIntegerDynArray | Append the strings in the specified CSV text into a dynamic array of integer | |
| CsvToRawUtf8DynArray | Convert the strings in the specified CSV text into a dynamic array of UTF-8 strings | |
| CsvToRawUtf8DynArray | Add the strings in the specified CSV text into a dynamic array of UTF-8 strings | |
| CsvToRawUtf8DynArray | Add the strings in the specified CSV text into a dynamic array of UTF-8 strings | |
| Curr64ToPChar | Convert an INTEGER Curr64 (value*10000) into a string | |
| Curr64ToStr | Convert an INTEGER Curr64 (value*10000) into a string | |
| Curr64ToStr | Convert an INTEGER Curr64 (value*10000) into a string | |
| Curr64ToString | Convert a currency value from its Int64 binary representation into its numerical text equivalency | |
| CurrencyToStr | Convert a currency value into a string | |
| DefaultSynLogExceptionToStr | The default Exception handler for logging | |
| DoubleToJson | Convert a 64-bit floating-point value to its JSON text equivalency | |
| DoubleToShort | Convert a 64-bit floating-point value to its numerical text equivalency | |
| DoubleToShortNoExp | Convert a 64-bit floating-point value to its numerical text equivalency without scientific notation | |
| DoubleToStr | Convert a 64-bit floating-point value to its numerical text equivalency | |
| DoubleToStr | Convert a 64-bit floating-point value to its numerical text equivalency | |
| DoubleToString | Convert a floating-point value to its numerical text equivalency | |
| EnsureDirectoryExists | Just a wrapper around EnsureDirectoryExists(MakePath([Part])) | |
| EscapeChar | Escape as \char pair some chars from a set into a new RawUtf8 string | |
| EscapeCharBuffer | Escape as \char pair some chars from a set into a pre-allocated buffer | |
| EscapeHex | Escape as \xx hexadecimal some chars from a set into a new RawUtf8 string | |
| EscapeHexBuffer | Escape as \xx hexadecimal some chars from a set into a pre-allocated buffer | |
| ExtendedToJson | Convert a floating-point value to its JSON text equivalency | |
| ExtendedToShort | Convert a floating-point value to its numerical text equivalency | |
| ExtendedToShortNoExp | Convert a floating-point value to its numerical text equivalency without scientification notation | |
| ExtendedToStr | Convert a floating-point value to its numerical text equivalency | |
| ExtendedToStr | Convert a floating-point value to its numerical text equivalency | |
| FindCsvIndex | Return the index of a Value in a CSV string | |
| FloatStrCopy | Copy a floating-point text buffer with proper correction and validation | |
| FloatToJsonNan | Recognize if the supplied text is NAN/INF/+INF/-INF, i.e. not a number | |
| FloatToShortNan | Check if the supplied text is NAN/INF/+INF/-INF, i.e. not a number | |
| FloatToStrNan | Check if the supplied text is NAN/INF/+INF/-INF, i.e. not a number | |
| FormatBuffer | Fast Format() function replacement, tuned for direct memory buffer write | |
| FormatShort | Fast Format() function replacement, for UTF-8 content stored in ShortString | |
| FormatShort16 | Delphi don't inline "array of const" parameters fast Format() function replacement, for UTF-8 content stored in TShort16 | |
| FormatString | Fast Format() function replacement, tuned for small content | |
| FormatString | Fast Format() function replacement, tuned for small content | |
| FormatToShort | Fast Format() function replacement, for UTF-8 content stored in ShortString | |
| FormatUtf8 | Fast Format() function replacement, optimized for RawUtf8 | |
| FormatUtf8 | Fast Format() function replacement, optimized for RawUtf8 | |
| FormatVariant | Fast Format() function replacement, for UTF-8 content stored in variant | |
| GetBitCsv | Convert a set of bit into a CSV content | |
| GetCsvItem | Return n-th indexed CSV string in P, starting at Index=0 for first one | |
| GetCsvItemString | Return n-th indexed CSV string in P, starting at Index=0 for first one | |
| GetFileNameExtIndex | Extract a file extension from a file name, then compare with a comma separated list of extensions | |
| GetFirstCsvItem | Return first CSV string in the supplied UTF-8 content | |
| GetLastCsvItem | Return last CSV string in the supplied UTF-8 content | |
| GetNextItem | Return next CSV string from P | |
| GetNextItem | Return next CSV string from P | |
| GetNextItem | Return next CSV string (unquoted if needed) from P | |
| GetNextItemCardinal | Return next CSV string as unsigned integer from P, 0 if no more | |
| GetNextItemCardinalStrict | Return next CSV string as unsigned integer from P, 0 if no more | |
| GetNextItemCardinalW | Return next CSV string as unsigned integer from P, 0 if no more | |
| GetNextItemCurrency | Return next CSV string as currency from P, 0.0 if no more | |
| GetNextItemCurrency | Return next CSV string as currency from P, 0.0 if no more | |
| GetNextItemDouble | Return next CSV string as double from P, 0.0 if no more | |
| GetNextItemHexa | Return next CSV hexadecimal string as 64-bit unsigned integer from P | |
| GetNextItemHexDisplayToBin | Decode next CSV hexadecimal string from P, nil if no more or not matching BinBytes | |
| GetNextItemInt64 | Return next CSV string as 64-bit signed integer from P, 0 if no more | |
| GetNextItemInteger | Return next CSV string as signed integer from P, 0 if no more | |
| GetNextItemMultiple | Return next CSV string from P from several separator characters | |
| GetNextItemQWord | Return next CSV string as 64-bit unsigned integer from P, 0 if no more | |
| GetNextItemShortString | Return next CSV string from P, nil if no more | |
| GetNextItemString | Return next CSV string from P, nil if no more | |
| GetNextItemTrimed | Return trimmed next CSV string from P | |
| GetNextItemTrimedCRLF | Return next CRLF separated value string from P, ending #10 or #13#10 trimmed | |
| GetNextItemTrimedEscaped | Return trimmed next CSV string from P, ignoring any Escaped char | |
| GetNextTChar64 | Return next CSV string from P as a #0-ended buffer, false if no more | |
| GetUnQuoteCsvItem | Return n-th indexed CSV string (unquoted if needed) in P, starting at Index=0 for first one | |
| GuidToRawUtf8 | Convert a TGuid into 38 chars encoded { text } as RawUtf8 | |
| GuidToShort | Convert a TGuid into text | |
| GuidToShort | Convert a TGuid into text | |
| GuidToString | Convert a TGuid into into 38 chars encoded { text } as RTL string | |
| GuidToText | Append a TGuid binary content as 36 chars text | |
| HexDisplayToBin | Fast conversion from hexa chars in reverse order into a binary buffer | |
| HexDisplayToCardinal | Fast conversion from hexa chars in reverse order into a cardinal | |
| HexDisplayToInt64 | Inline gives an error under release conditions with (old?) FPC fast conversion from hexa chars in reverse order into a cardinal | |
| HexDisplayToInt64 | Fast conversion from hexa chars in reverse order into a cardinal | |
| HexToBin | Fast conversion from hexa chars into binary data | |
| HexToBin | Fast conversion from hexa chars into binary data | |
| HexToBin | Fast conversion from hexa chars into binary data | |
| HexToBinFast | Fast conversion with no validity check from hexa chars into binary data | |
| HexToChar | Internal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64 | |
| HexToChar | Fast conversion from one hexa char pair into a 8-bit AnsiChar | |
| HexToCharValid | Internal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64 | |
| HexToCharValid | Fast conversion from one hexa char pair into a 8-bit AnsiChar | |
| HexToWideChar | Fast conversion from two hexa bytes into a 16-bit UTF-16 WideChar | |
| HtmlEscape | Escape some UTF-8 text into HTML | |
| HtmlEscapeString | Escape some RTL string text into UTF-8 HTML | |
| HumanHexCompare | Fast comparison between two ToHumanHex() hexa values | |
| HumanHexCompare | Fast comparison between two ToHumanHex() hexa values | |
| HumanHexToBin | Fast conversion from ToHumanHex() hexa chars into binary data | |
| HumanHexToBin | Fast conversion from ToHumanHex() hexa chars into binary data | |
| IdemPCharAndGetNextItem | Return true if IdemPChar(source,searchUp) matches, and retrieve the value item | |
| Int18ToChars3 | Compute the value as encoded by TTextWriter.AddInt18ToChars3() method | |
| Int18ToChars3 | Compute the value as encoded by TTextWriter.AddInt18ToChars3() method | |
| Int32ToUtf8 | Fast RawUtf8 version of 32-bit IntToStr() | |
| Int32ToUtf8 | Fast RawUtf8 version of 32-bit IntToStr() | |
| Int64DynArrayToCsv | Return the corresponding CSV text from a dynamic array of 64-bit integers | |
| Int64DynArrayToCsv | Return the corresponding CSV text from a dynamic array of 64-bit integers | |
| Int64ToHex | Fast conversion from a Int64 value into hexa chars, ready to be displayed | |
| Int64ToHex | Fast conversion from a Int64 value into hexa chars, ready to be displayed | |
| Int64ToHexLower | Fast conversion from a pointer data into hexa chars, ready to be displayed | |
| Int64ToHexShort | Fast conversion from a Int64 value into hexa chars, ready to be displayed | |
| Int64ToHexShort | Fast conversion from a Int64 value into hexa chars, ready to be displayed | |
| Int64ToHexString | Fast conversion from a Int64 value into hexa chars, ready to be displayed | |
| Int64ToUtf8 | Fast RawUtf8 version of 64-bit IntToStr() | |
| Int64ToUtf8 | Delphi 2007 has trouble inlining this fast RawUtf8 version of 64-bit IntToStr() | |
| IntegerDynArrayToCsv | Return the corresponding CSV text from a dynamic array of 32-bit integer | |
| IntegerDynArrayToCsv | Return the corresponding CSV text from a dynamic array of 32-bit integer | |
| IntToString | Faster than default SysUtils.IntToStr implementation | |
| IntToString | Faster than default SysUtils.IntToStr implementation | |
| IntToString | Faster than default SysUtils.IntToStr implementation | |
| IntToThousandString | Convert an integer value into its textual representation with thousands marked | |
| IPToCardinal | Convert an IPv4 'x.x.x.x' text into its 32-bit value | |
| IPToCardinal | Convert an IPv4 'x.x.x.x' text into its 32-bit value | |
| IPToCardinal | Convert an IPv4 'x.x.x.x' text into its 32-bit value, 0 or localhost | |
| IsHex | Fast check if the supplied Hex buffer is an hexadecimal representation of a binary buffer of a given number of bytes | |
| K | Convert a count to a human readable value power-of-two metric value | |
| K | Convert a count to a human readable value power-of-two metric value | |
| KB | Delphi 2007 is buggy as hell convert a string size to a human readable value | |
| KB | Convert a size to a human readable value power-of-two metric value | |
| KB | Convert a size to a human readable value | |
| KB | Delphi 2007 is buggy as hell convert a size to a human readable value | |
| KBNoSpace | Delphi 2007 is buggy as hell convert a size to a human readable value | |
| KBU | Convert a size to a human readable value | |
| Make | Concatenate several arguments into an UTF-8 string | |
| Make | Concatenate several arguments into an UTF-8 string | |
| MakeCsv | Create a CSV text from some values | |
| MakeFileName | MakePath() variant which can handle the file extension specifically | |
| MakePath | Append some path parts into a single file name with proper path delimiters | |
| MakeString | Concatenate several arguments into a RTL string | |
| MicroSecFrom | Delphi 2007 is buggy as hell compute elapsed time into a human readable value, from a Start value | |
| MicroSecToString | Delphi 2007 is buggy as hell convert a micro seconds elapsed time into a human readable value | |
| MicroSecToString | Delphi 2007 is buggy as hell convert a micro seconds elapsed time into a human readable value | |
| MilliSecToString | Delphi 2007 is buggy as hell convert a milliseconds elapsed time into a human readable value | |
| NanoSecToString | Convert a nano seconds elapsed time into a human readable value | |
| NeedsHtmlEscape | Check if some UTF-8 text would need HTML escaping | |
| NeedsXmlEscape | Check if some UTF-8 text would need XML escaping | |
| NormalizeDirectoryExists | Just a wrapper around EnsureDirectoryExists(NormalizeFileName(MakePath([Part]))) | |
| ObjectToJson | Will serialize any TObject into its UTF-8 JSON representation | |
| ObjectToJson | Will serialize any TObject into its UTF-8 JSON representation | |
| ObjectToJsonDebug | Will serialize any TObject into its expanded UTF-8 JSON representation | |
| OctToBin | Conversion from octal C-like escape into binary data | |
| OctToBin | Conversion from octal C-like escape into binary data | |
| PointerToHex | Fast conversion from a pointer data into hexa chars, ready to be displayed | |
| PointerToHex | Fast conversion from a pointer data into hexa chars, ready to be displayed | |
| PointerToHexShort | Fast conversion from a pointer data into hexa chars, ready to be displayed | |
| Prepend | Prepend some text to a RawByteString variable with no code page conversion | |
| Prepend | Prepend some text items at the beginning of a RawByteString variable | |
| Prepend | Prepend some text items at the beginning of a RawUtf8 variable | |
| Prepend | Prepend one char to a RawByteString variable with no code page conversion | |
| RawByteStringToStream | Create a TStream from a string content | |
| RawUtf8ArrayToCsv | Return the corresponding CSV text from a dynamic array of UTF-8 strings | |
| RawUtf8ArrayToQuotedCsv | Return the corresponding CSV quoted text from a dynamic array of UTF-8 strings | |
| RawUtf8ToGuid | Convert some UTF-8 encoded text into a TGuid | |
| RawUtf8ToGuid | Convert some UTF-8 encoded text into a TGuid | |
| ReadStringFromStream | Read UTF-8 text from a TStream saved with len prefix by WriteStringToStream | |
| RenameInCsv | Change a Value within a CSV string | |
| SecToString | Delphi 2007 is buggy as hell convert a seconds elapsed time into a human readable value | |
| SetBitCsv | Retrieve the next CSV separated bit index | |
| StatusCodeToErrorMsg | Convert any HTTP_* constant to an integer error code and its English text | |
| StrCurr64 | Internal fast INTEGER Curr64 (value*10000) value to text conversion | |
| StreamChangeToRawByteString | Iterative function to retrieve the new content appended to a stream | |
| StreamToRawByteString | Read a TStream content into a String | |
| StringToConsole | Direct conversion of a RTL string into a console OEM-encoded String | |
| StringToGuid | Convert some RTL string text into a TGuid | |
| StrToCurr64 | Convert a string into its INTEGER Curr64 (value*10000) representation | |
| StrToCurrency | Convert a string into its currency representation | |
| TextToGuid | Convert some text into its TGuid binary value | |
| ToHexShort | Fast conversion for up to 256-bit of little-endian input into non-zero hexa | |
| ToUtf8 | Convert any Variant/TVarData into UTF-8 encoded String | |
| ToUtf8 | Convert any Variant into UTF-8 encoded String | |
| ToUtf8 | Fast RawUtf8 version of 32-bit IntToStr() | |
| ToUtf8 | Convert a TGuid into 36 chars encoded text as RawUtf8 | |
| ToUtf8 | Fast RawUtf8 version of 64-bit IntToStr() | |
| TrimGuid | Trim any space and '{' '-' '}' chars from input to get a 32-char TGuid hexa | |
| TrimMinDisplayHex | Trim right '0' chars in a text buffer - e.g. from BinToHexLower() | |
| UInt2DigitsToShort | Creates a 2 digits short string from a 0..99 value | |
| UInt2DigitsToShortFast | Creates a 2 digits short string from a 0..99 value | |
| UInt32ToUtf8 | Optimized conversion of a cardinal into RawUtf8 | |
| UInt32ToUtf8 | Optimized conversion of a cardinal into RawUtf8 | |
| UInt3DigitsToShort | Creates a 3 digits short string from a 0..999 value | |
| UInt3DigitsToUtf8 | Creates a 3 digits string from a 0..999 value as '000'..'999' | |
| UInt4DigitsToShort | Creates a 4 digits short string from a 0..9999 value | |
| UInt4DigitsToUtf8 | Creates a 4 digits string from a 0..9999 value as '0000'..'9999' | |
| UInt64ToUtf8 | Fast RawUtf8 version of 64-bit IntToStr(), with proper QWord support | |
| UnescapeHex | Un-escape \xx or \c encoded chars into a new RawUtf8 string | |
| UnescapeHexBuffer | Un-escape \xx or \c encoded chars from a pre-allocated buffer | |
| VariantCompAsText | Internal low-level function to compare two variants with RawUt8 conversion | |
| VariantSaveJson | Save a variant value into a JSON content | |
| VariantSaveJson | Save a variant value into a JSON content | |
| VariantToTempUtf8 | Convert any Variant into a JSON-compatible UTF-8 encoded temporary buffer | |
| VariantToText | Convert any non-null Variant into UTF-8 encoded String | |
| VariantToUtf8 | Convert any Variant into UTF-8 encoded String | |
| VariantToUtf8 | Convert any Variant into UTF-8 encoded String | |
| VariantToUtf8 | Convert any Variant into UTF-8 encoded String | |
| VarRecAs | Check if a supplied "array of const" argument is an instance of a given class | |
| VarRecAsChar | Get an open array (const Args: array of const) character argument | |
| VarRecToDouble | Convert an open array (const Args: array of const) argument to a floating point value | |
| VarRecToInlineValue | Convert an open array (const Args: array of const) argument to a value encoded as with :(...): inlined parameters in FormatUtf8(Format,Args,Params) | |
| VarRecToInt64 | Convert an open array (const Args: array of const) argument to an Int64 | |
| VarRecToTempUtf8 | Convert an open array (const Args: array of const) argument to an UTF-8 encoded text, using a specified temporary buffer | |
| VarRecToUtf8 | Convert an open array (const Args: array of const) argument to an UTF-8 encoded text | |
| VarRecToUtf8IsString | 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 | |
| WriteStringToStream | Write an UTF-8 text into a TStream with a len prefix - see ReadStringFromStream | |
| XmlEscape | Escape some UTF-8 text into XML |
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'
procedure AddToCsv(const Value: RawUtf8; var Csv: RawUtf8; const Sep: RawUtf8 = ',');
Append a Value to a CSV string
procedure Append(var Text: RawByteString; const Added: RawByteString); overload;
Append one text item to a RawByteString variable with no code page conversion
procedure Append(var Text: RawByteString; Added: pointer; AddedLen: PtrInt); overload;
Append one text buffer to a RawByteString variable with no code page conversion
procedure Append(var Text: RawUtf8; Added: pointer; AddedLen: PtrInt); overload;
Append one text buffer to a RawUtf8 variable with no code page conversion
procedure Append(var Text: RawByteString; const Args: array of const); overload;
Append some text items to a RawByteString variable
procedure Append(var Text: RawUtf8; const Added: RawByteString); overload;
Append one text item to a RawUtf8 variable with no code page conversion
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
procedure Append(var Text: RawUtf8; Added: AnsiChar); overload;
Append one char to a RawUtf8 variable with no code page conversion
procedure Append(var Text: RawUtf8; const Added1, Added2: RawByteString); overload;
Append two text items to a RawUtf8 variable with no code page conversion
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
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
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
function BinToHex(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;
Fast conversion from binary data into hexa chars
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
function BinToHex(const Bin: RawByteString): RawUtf8; overload;
Fast conversion from binary data into hexa chars
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
function BinToHexDisplay(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;
Fast conversion from binary data into hexa chars, ready to be displayed
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
function BinToHexDisplayLower(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;
Fast conversion from binary data into lowercase hexa chars
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
function BinToHexDisplayLowerShort(Bin: PAnsiChar; BinBytes: PtrInt): ShortString;
Fast conversion from up to 127 bytes of binary data into lowercase hexa chars
function BinToHexDisplayLowerShort16(Bin: Int64; BinBytes: PtrInt): TShort16;
Fast conversion from up to 64-bit of binary data into lowercase hexa chars
procedure BinToHexLower(Bin: PAnsiChar; BinBytes: PtrInt; var result: RawUtf8); overload;
Fast conversion from binary data into lowercase hexa chars
function BinToHexLower(Bin: PAnsiChar; BinBytes: PtrInt): RawUtf8; overload;
Fast conversion from binary data into lowercase hexa chars
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
function BinToHexLower(const Bin: RawByteString): RawUtf8; overload;
Fast conversion from binary data into lowercase hexa chars
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
function ByteToHex(P: PAnsiChar; Value: byte): PAnsiChar;
Append one byte as hexadecimal char pairs, into a text buffer
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()
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()
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
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
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
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
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
procedure ConsoleObject(Value: TObject; Options: TTextWriterWriteObjectOptions = [woHumanReadable]);
A wrapper around ConsoleWrite(ObjectToJson(Value))
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.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
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
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
function crc32cUtf8ToHex(const str: RawUtf8): RawUtf8;
Compute the hexadecimal representation of the crc32 checkum of a given text
- wrapper around CardinalToHex(crc32c(...))
function CsvContains(const Csv, Value: RawUtf8; Sep: AnsiChar = ','; CaseSensitive: boolean = true): boolean;
Quickly check if Value is in Csv with no temporary memory allocation
function CsvGuessSeparator(const Csv: RawUtf8): AnsiChar;
Recognize #9 ';' or ',' as separator in a CSV text
- to implement a separator-tolerant CSV parser
function CsvOfValue(const Value: RawUtf8; Count: cardinal; const Sep: RawUtf8 = ','): RawUtf8;
Return a CSV list of the iterated same value
- e.g. CsvOfValue('?',3)='?,?,?'
function CsvToInt64DynArray(Csv: PUtf8Char; Sep: AnsiChar = ','): TInt64DynArray; overload;
Convert the strings in the specified CSV text into a dynamic array of integer
procedure CsvToInt64DynArray(Csv: PUtf8Char; var List: TInt64DynArray; Sep: AnsiChar = ','); overload;
Append the strings in the specified CSV text into a dynamic array of integer
procedure CsvToIntegerDynArray(Csv: PUtf8Char; var List: TIntegerDynArray; Sep: AnsiChar = ',');
Append the strings in the specified CSV text into a dynamic array of integer
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
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
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
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^
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)
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)
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)
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)
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
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[]
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)
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)
procedure DoubleToStr(Value: Double; var result: RawUtf8); overload;
Convert a 64-bit floating-point value to its numerical text equivalency
function DoubleToStr(Value: Double): RawUtf8; overload;
Convert a 64-bit floating-point value to its numerical text equivalency
function DoubleToString(Value: Double): string;
Convert a floating-point value to its numerical text equivalency
function EnsureDirectoryExists(const Part: array of const; RaiseExceptionOnCreationFailure: ExceptionClass = nil): TFileName; overload;
Just a wrapper around EnsureDirectoryExists(MakePath([Part]))
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
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
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()
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
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[]
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)
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)
procedure ExtendedToStr(Value: TSynExtended; Precision: integer; var result: RawUtf8); overload;
Convert a floating-point value to its numerical text equivalency
function ExtendedToStr(Value: TSynExtended; Precision: integer): RawUtf8; overload;
Convert a floating-point value to its numerical text equivalency
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
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
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[]
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
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
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^
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
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
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()
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()
function FormatToShort(const Format: RawUtf8; const Args: array of const): ShortString;
Fast Format() function replacement, for UTF-8 content stored in ShortString
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
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
function FormatVariant(const Format: RawUtf8; const Args: array of const): variant;
Fast Format() function replacement, for UTF-8 content stored in variant
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
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
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
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
function GetFirstCsvItem(const Csv: RawUtf8; Sep: AnsiChar = ','): RawUtf8;
Return first CSV string in the supplied UTF-8 content
function GetLastCsvItem(const Csv: RawUtf8; Sep: AnsiChar = ','): RawUtf8;
Return last CSV string in the supplied UTF-8 content
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
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
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
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
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)
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
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
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
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
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
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
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
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
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
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
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)
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)
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
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
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
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[]
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
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
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()
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()
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
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" }function HexDisplayToBin(Hex: PAnsiChar; Bin: PByte; BinBytes: PtrInt): boolean;
Fast conversion from hexa chars in reverse order into a binary buffer
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
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
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
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)
function HexToBin(const Hex: RawUtf8): RawByteString; overload;
Fast conversion from hexa chars into binary data
function HexToBin(Hex: PAnsiChar; HexLen: PtrInt; var Bin: RawByteString): boolean; overload;
Fast conversion from hexa chars into binary data
procedure HexToBinFast(Hex: PAnsiChar; Bin: PByte; BinBytes: PtrInt);
Fast conversion with no validity check from hexa chars into binary data
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
function HexToChar(Hex: PAnsiChar; Bin: PUtf8Char; HexToBin: PByteArray): boolean; overload;
Internal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64
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)
function HexToCharValid(Hex: PAnsiChar; HexToBin: PByteArray): boolean; overload;
Internal conversion from hexa pair into a AnsiChar for PIC, ARM and x86_64
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
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
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
function HumanHexCompare(a, b: PUtf8Char): integer; overload;
Fast comparison between two ToHumanHex() hexa values
function HumanHexCompare(const a, b: RawUtf8): integer; overload;
Fast comparison between two ToHumanHex() hexa values
function HumanHexToBin(const hex: RawUtf8; var Bin: RawByteString): boolean; overload;
Fast conversion from ToHumanHex() hexa chars into binary data
function HumanHexToBin(const hex: RawUtf8): RawByteString; overload;
Fast conversion from ToHumanHex() hexa chars into binary data
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 ...
procedure Int18ToChars3(Value: cardinal; var result: RawUtf8); overload;
Compute the value as encoded by TTextWriter.AddInt18ToChars3() method
function Int18ToChars3(Value: cardinal): RawUtf8; overload;
Compute the value as encoded by TTextWriter.AddInt18ToChars3() method
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
function Int32ToUtf8(Value: PtrInt): RawUtf8; overload;
Fast RawUtf8 version of 32-bit IntToStr()
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
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
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()
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()
function Int64ToHexLower(aInt64: Int64): RawUtf8; overload;
Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally DisplayMinChars() and BinToHexDisplay()
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
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
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()
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
function Int64ToUtf8(Value: Int64): RawUtf8; overload;
Fast RawUtf8 version of 64-bit IntToStr()
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
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
function IntToString(Value: Int64): string; overload;
Faster than default SysUtils.IntToStr implementation
function IntToString(Value: cardinal): string; overload;
Faster than default SysUtils.IntToStr implementation
function IntToString(Value: integer): string; overload;
Faster than default SysUtils.IntToStr implementation
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
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
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
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
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
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
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
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
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
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
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
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
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
procedure Make(const Args: array of const; var Result: RawUtf8; const IncludeLast: RawUtf8 = ''); overload;
Concatenate several arguments into an UTF-8 string
function Make(const Args: array of const): RawUtf8; overload;
Concatenate several arguments into an UTF-8 string
function MakeCsv(const Value: array of const; EndWithComma: boolean = false; Comma: AnsiChar = ','): RawUtf8;
Create a CSV text from some values
function MakeFileName(const Part: array of const; LastIsExt: boolean = true): TFileName;
MakePath() variant which can handle the file extension specifically
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'
function MakeString(const Args: array of const): string;
Concatenate several arguments into a RTL string
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
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
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
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
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
function NeedsHtmlEscape(text: PUtf8Char; fmt: TTextWriterHtmlFormat): boolean;
Check if some UTF-8 text would need HTML escaping
function NeedsXmlEscape(text: PUtf8Char): boolean;
Check if some UTF-8 text would need XML escaping
function NormalizeDirectoryExists(const Part: array of const; RaiseExceptionOnCreationFailure: ExceptionClass = nil): TFileName; overload;
Just a wrapper around EnsureDirectoryExists(NormalizeFileName(MakePath([Part])))
procedure ObjectToJson(Value: TObject; var result: RawUtf8; Options: TTextWriterWriteObjectOptions = [woDontStoreDefault]); overload;
Will serialize any TObject into its UTF-8 JSON representation
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
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
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^
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 \
procedure PointerToHex(aPointer: pointer; var result: RawUtf8); overload;
Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
function PointerToHex(aPointer: pointer): RawUtf8; overload;
Fast conversion from a pointer data into hexa chars, ready to be displayed
- use internally BinToHexDisplay()
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
procedure Prepend(var Text: RawUtf8; const Args: array of const); overload;
Prepend some text items at the beginning of a RawUtf8 variable
procedure Prepend(var Text: RawByteString; Added: AnsiChar); overload;
Prepend one char to a RawByteString variable with no code page conversion
procedure Prepend(var Text: RawByteString; const Added: RawByteString); overload;
Prepend some text to a RawByteString variable with no code page conversion
procedure Prepend(var Text: RawByteString; const Args: array of const); overload;
Prepend some text items at the beginning of a RawByteString variable
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);
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
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
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)
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
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);
function RenameInCsv(const OldValue, NewValue: RawUtf8; var Csv: RawUtf8; const Sep: RawUtf8 = ','): boolean;
Change a Value within a CSV string
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
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
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()
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
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
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
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
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
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)^)
function StrToCurrency(P: PUtf8Char): currency;
Convert a string into its currency representation
- will call StrToCurr64()
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" }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()
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
function ToUtf8(Value: Int64): RawUtf8; overload;
Fast RawUtf8 version of 64-bit IntToStr()
function ToUtf8(Value: PtrInt): RawUtf8; overload;
Fast RawUtf8 version of 32-bit IntToStr()
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'
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'
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
function TrimMinDisplayHex(Text: PUtf8Char; TextLen: PtrInt): PtrInt;
Trim right '0' chars in a text buffer - e.g. from BinToHexLower()
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()
function UInt2DigitsToShortFast(Value: byte): TShort4;
Creates a 2 digits short string from a 0..99 value
- won't test Value>99 as UInt2DigitsToShort()
procedure UInt32ToUtf8(Value: PtrUInt; var result: RawUtf8); overload;
Optimized conversion of a cardinal into RawUtf8
function UInt32ToUtf8(Value: PtrUInt): RawUtf8; overload;
Optimized conversion of a cardinal into RawUtf8
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()
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
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()
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
procedure UInt64ToUtf8(Value: QWord; var result: RawUtf8);
Fast RawUtf8 version of 64-bit IntToStr(), with proper QWord support
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
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^
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
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
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
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
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)
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
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'
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
function VarRecAs(const aArg: TVarRec; aClass: TClass): pointer;
Check if a supplied "array of const" argument is an instance of a given class
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
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)
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
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)
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
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
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
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
function XmlEscape(const text: RawUtf8): RawUtf8;
Escape some UTF-8 text into XML
- just a wrapper around TTextWriter.AddXmlEscape() process
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
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
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
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
TSynLogExceptionToStrCustom: TSynLogExceptionToStr = nil;
Allow to customize the ESynException logging message
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
TwoDigitsHexLower: array[byte] of array[1..2] of AnsiChar;
Lowercase hexadecimal lookup table
_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
_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
_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