Unit CastleClassUtils

Description

Basic classes and class utilities (for streams, strings, lists and such). Many utilities for classes that are defined in the Classes unit, and some classes of our my own.

Some notes about TStream descendants :

  • I call a stream "purely sequential" (or just "sequential") if it allows only reading and/or writing of data and does not allow free "Seek" calls, in particular — it does not allow Seek to move back in a stream.

  • I call a stream "growing" if it's read-only and it's purely sequential and it's Size property may be useless. In other words, when you read a "growing" stream, you don't know when it ends, until you reach the end. You just have to read data until Read returns 0.

  • Remember that to reliably detect end of the stream when you use TStream.Read, you have to test is ReadCount = 0. Merely testing that ReadCount < less than you requested is not enough, e.g. seen for THandleStream when handle is StdIn.

Uses

Overview

Classes, Interfaces, Objects and Records

Name Description
Class TStringListCaseSens TStringList that is case sensitive.
Class EStreamNotImplemented  
Class EStreamNotImplementedWrite  
Class EStreamNotImplementedSeek  
Class EStreamNotImplementedSetSize  
Class TPeekCharStream Abstract class to read another stream, always being able to back one character.
Class TSimplePeekCharStream Read another stream, sequentially, always being able to back one character.
Class TBufferedReadStream Read another stream, sequentially, always being able to back one character, and buffering it.
Class TCastleComponent Component with small CGE extensions.
Class TCastleObjectStack Extended TObjectStack for Castle Game Engine.
Class TCastleObjectQueue Extended TObjectQueue for Castle Game Engine.
Class TCastleObjectList Extended TObjectList for Castle Game Engine.
Class TNotifyEventList  
Class TGenericCollection A generic version of TCollection.

Functions and Procedures

procedure StringsAdd(Strs: TStrings; Count: integer; itemVal: string='dummy'); overload;
procedure AddStrArrayToStrings(const StrArr: array of string; strlist: TStrings);
procedure Strings_AddSplittedString(Strings: TStrings; const S, Splitter: string);
procedure Strings_AddCastleEngineProgramHelpSuffix( Strings: TStrings; const DisplayApplicationName: string; const Version: string; WrapLines: boolean);
procedure Strings_SetText(SList: TStrings; const S: string);
procedure Strings_Trim(Strings: TStrings; MaxCount: Cardinal);
procedure StreamWriteLongWord(Stream: TStream; const Value: LongWord);
function StreamReadLongWord(Stream: TStream): LongWord;
procedure StreamWriteByte(Stream: TStream; const Value: Byte);
function StreamReadByte(Stream: TStream): Byte;
procedure WriteStr(Stream: TStream; const S: AnsiString); overload;
procedure WritelnStr(Stream: TStream; const S: AnsiString); overload;
procedure WriteStr(const S: AnsiString); overload;
procedure WritelnStr(const S: AnsiString); overload;
function StreamReadChar(Stream: TStream): char;
function StreamReadZeroEndString(Stream: TStream): string;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean; out endingChar: char): string; overload;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean): string; overload;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars; out endingChar: char): string; overload;
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars): string; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean; out endingChar: integer): string; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean): string; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars; out endingChar: integer): string; overload;
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars): string; overload;
procedure ReadGrowingStream(GrowingStream, DestStream: TStream; ResetDestStreamPosition: boolean);
function ReadGrowingStreamToString(GrowingStream: TStream): string;
procedure StreamWriteString(Stream: TStream; const s: string);
function StreamReadString(Stream: TStream): string;
function StreamToString(Stream: TStream): string;
procedure MemoryStreamLoadFromString(const Stream: TMemoryStream; const S: string; const Rewind: boolean = true); overload;
function MemoryStreamLoadFromString( const S: string; const Rewind: boolean = true): TMemoryStream; overload;
procedure CreateIfNeeded(var Component: TComponent; ComponentClass: TComponentClass; Owner: TComponent);
function DumpStackToString(const BaseFramePointer: Pointer): string;
function DumpExceptionBackTraceToString: string;

Types

TPropertySection = (...);

Constants

DefaultReadBufferSize = 1024 * 1024;

Variables

StdInStream: TStream;
StdOutStream: TStream;
StdErrStream: TStream;

Description

Functions and Procedures

procedure StringsAdd(Strs: TStrings; Count: integer; itemVal: string='dummy'); overload;

Add some strings.

procedure AddStrArrayToStrings(const StrArr: array of string; strlist: TStrings);

Add all strings from string array to TStrings instance.

procedure Strings_AddSplittedString(Strings: TStrings; const S, Splitter: string);

Splits S by Splitter, and adds each splitted part to Strings. Splitting is done by Splitter, i.e. if N is the number of occurrences of Splitter inside S, then it always adds N + 1 strings to Strings. Yes, this means that if S starts with Splitter then the first part is equal to ''. And if S ends with Splitter then the last oart is equal to ''.

procedure Strings_AddCastleEngineProgramHelpSuffix( Strings: TStrings; const DisplayApplicationName: string; const Version: string; WrapLines: boolean);

Something like SCastleEngineProgramHelpSuffix, but appends contents as a couple of lines to Strings.

procedure Strings_SetText(SList: TStrings; const S: string);

Use this instead of SList.Text := S to workaround FPC 2.0.2 bug. See [http://www.freepascal.org/mantis/view.php?id=6699]

procedure Strings_Trim(Strings: TStrings; MaxCount: Cardinal);

Make sure we don't have more than MaxCount strings on a list. Removes the last strings if necessary.

procedure StreamWriteLongWord(Stream: TStream; const Value: LongWord);
 
function StreamReadLongWord(Stream: TStream): LongWord;
 
procedure StreamWriteByte(Stream: TStream; const Value: Byte);
 
function StreamReadByte(Stream: TStream): Byte;
 
procedure WriteStr(Stream: TStream; const S: AnsiString); overload;

Write string contents, as 8-bit string (AnsiString), to stream. This isn't a procedure to encode a string within a binary stream, this only writes string contents (Length(S) bytes) into the stream. Versions with "ln" append newline. Versions without Stream parameter write to StdOutStream.

procedure WritelnStr(Stream: TStream; const S: AnsiString); overload;
 
procedure WriteStr(const S: AnsiString); overload;
 
procedure WritelnStr(const S: AnsiString); overload;
 
function StreamReadChar(Stream: TStream): char;

Read one character from stream.

Exceptions raised
EReadError
If end of stream.
function StreamReadZeroEndString(Stream: TStream): string;
 
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean; out endingChar: char): string; overload;

Read stream, until you find some character in EndingChars. Returns read contents, without final character (the one in EndingChars set).

If you use a version with BackEndingChar parameter and pass BackEndingChar = True, then the ending character will be returned back to stream (we will start reading from it next time). Note that "returning the character" is done by Seek(-1, soFromCurrent), which may not be possible on some streams. Wrap a stream in TPeekCharStream instead, and use TPeekCharStream.ReadUpto, to be able to "return back" a character reliably.

Independently from BackEndingChar, if you use a version with EndingChar parameter, it will be set to the ending character.

Exceptions raised
EReadError
If the stream will end before encountering one of EndingChars.
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean): string; overload;
 
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars; out endingChar: char): string; overload;
 
function StreamReadUpto_NotEOS(Stream: TStream; const endingChars: TSetOfChars): string; overload;
 
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean; out endingChar: integer): string; overload;

Read stream, until you find some character in EndingChars, or end of stream.

Compared to StreamReadUpto_NotEOS, this treats "end of stream" as a normal situation, and doesn't raise any exception on it. It sets EndingChar to -1 on end of stream. When EndingChar is not -1, you know you can safely cast it to normal 8-bit character.

Everything else works like with StreamReadUpto_NotEOS.

function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars; backEndingChar: boolean): string; overload;
 
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars; out endingChar: integer): string; overload;
 
function StreamReadUpto_EOS(Stream: TStream; const endingChars: TSetOfChars): string; overload;
 
procedure ReadGrowingStream(GrowingStream, DestStream: TStream; ResetDestStreamPosition: boolean);

Read a growing stream, and append it to another destination stream. A "growing stream" is a stream that we can only read sequentially, no seeks allowed, and size is unknown until we hit the end.

The only operation we do on GrowingStream is GrowingStream.Read and the only operation on DestStream is DestStream.WriteBuffer. So DestStream usually must be able to grow dynamically to accomodate any GrowingStream input size.

This procedure ends when GrowingStream ends. If ResetDestStreamPosition then at the end we do DestStream.Position := 0 (since it is usually useful and it would be easy for you to forget about it).

function ReadGrowingStreamToString(GrowingStream: TStream): string;

Read a growing stream, and returns it's contents as a string. A "growing stream" is a stream that we can only read sequentially, no seeks allowed, and size is unknown until we hit the end.

procedure StreamWriteString(Stream: TStream; const s: string);

Encode / decode a string in a binary stream. Records string length (4 bytes), then the string contents (Length(S) bytes).

function StreamReadString(Stream: TStream): string;
 
function StreamToString(Stream: TStream): string;

Convert whole Stream to a string. Changes Stream.Position to 0 and then reads Stream.Size bytes, so be sure that Stream.Size is usable.

procedure MemoryStreamLoadFromString(const Stream: TMemoryStream; const S: string; const Rewind: boolean = true); overload;

Set contents of TMemoryStream to given string. If Rewind then the position is reset to the beginning, otherwise it stays at the end.

function MemoryStreamLoadFromString( const S: string; const Rewind: boolean = true): TMemoryStream; overload;
 
procedure CreateIfNeeded(var Component: TComponent; ComponentClass: TComponentClass; Owner: TComponent);

Create Component instance, if it's Nil. If Component = nil then it will do Component := ComponentClass.Create(Owner).

function DumpStackToString(const BaseFramePointer: Pointer): string;
 
function DumpExceptionBackTraceToString: string;
 

Types

TPropertySection = (...);

Used by TCastleComponent.PropertySection.

Values
  • psBasic
  • psLayout
  • psOther

Constants

DefaultReadBufferSize = 1024 * 1024;
 

Variables

StdInStream: TStream;

Streams to read/write a standard input/output/error of the program.

Tip: to read the standard input as a text file, you can use TTextReader and StdInStream:

var
  StdInReader: TTextReader;
begin
  StdInReader := TTextReader.Create(StdInStream, false);
  try
    while not StdInReader.Eof do
      DoSomethingWithInputLine(StdInReader.Readln);
  finally FreeAndNil(StdinReader) end;
end;

The advantage of using TTextReader above, compared to using the standard Pascal Readln procedure to read from the standard Pascal Input text file, is that you can easily modify the above code to read from any stream. So, instead of the standard input, you can easily read some stream that decompresses gzip data, or downloads data from the Internet... Actually, the overloaded constructor TTextReader.Create can accept an URL, like a file://... or http://..., and will internally use the stream returned by Download function for this URL.

Notes only for Windows GUI applications:

  1. Some (or all) of the variables below may be Nil in a Windows GUI application.

    If you want to be on the safe side, then don't use these streams in the GUI application (when IsConsole = false on Windows). But (with some caveats, see below) you can sometimes use them, if they are not-nil.

  2. You can have some of the standard streams available, even in a GUI application.

    User can run a GUI program and explicitly redirect it's standard stream, e.g. cat something | my_program.exe for stdin or my_program.exe > output.txt for stdout. Actually some shells, like Cygwin's bash, always redirect some streams under the hood.

    Note that the FPC (and Delphi?) RTL may not provide the standard Input/Output/ErrOutput in this case (because IsConsole = false), but we try a little harder, regardless of the IsConsole value.

  3. Caveat: in a GUI program under Windows you cannot depend on the fact that "StdOutStream <> nil means that stdout is actually available (because user redirected stdout etc.)". A first write to the StdOutStream may cause EWriteError, so watch out for this.

    This is tested on Windows 2000 Prof, with FPC 2.0.0 and 2.1.1 (revision 4317). When no stdout is available, StdOutStream should be nil, because GetStdHandle(STD_OUTPUT_HANDLE) should return 0. However, GetStdHandle(STD_OUTPUT_HANDLE) doesn't return 0... It returns some invalid handle (no, not INVALID_HANDLE_VALUE either) that you can't write into (trying to write returns in ERROR_INVALID_HANDLE WinAPI error). It seems that there is no way for me to check whether GetStdHandle(STD_OUTPUT_HANDLE) returned valid handle (e.g. because the program's stdout was redirected, so stdout is perfectly available) or whether it returned something unusable.

    Note that GetStdHandle(STD_INPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE) work correctly, so it should be OK to check StdInStream <> nil or StdErrStream <> nil. The only problematic one is GetStdHandle(STD_OUTPUT_HANDLE).

)

StdOutStream: TStream;

Streams to read/write a standard input/output/error of the program.

Tip: to read the standard input as a text file, you can use TTextReader and StdInStream:

var
  StdInReader: TTextReader;
begin
  StdInReader := TTextReader.Create(StdInStream, false);
  try
    while not StdInReader.Eof do
      DoSomethingWithInputLine(StdInReader.Readln);
  finally FreeAndNil(StdinReader) end;
end;

The advantage of using TTextReader above, compared to using the standard Pascal Readln procedure to read from the standard Pascal Input text file, is that you can easily modify the above code to read from any stream. So, instead of the standard input, you can easily read some stream that decompresses gzip data, or downloads data from the Internet... Actually, the overloaded constructor TTextReader.Create can accept an URL, like a file://... or http://..., and will internally use the stream returned by Download function for this URL.

Notes only for Windows GUI applications:

  1. Some (or all) of the variables below may be Nil in a Windows GUI application.

    If you want to be on the safe side, then don't use these streams in the GUI application (when IsConsole = false on Windows). But (with some caveats, see below) you can sometimes use them, if they are not-nil.

  2. You can have some of the standard streams available, even in a GUI application.

    User can run a GUI program and explicitly redirect it's standard stream, e.g. cat something | my_program.exe for stdin or my_program.exe > output.txt for stdout. Actually some shells, like Cygwin's bash, always redirect some streams under the hood.

    Note that the FPC (and Delphi?) RTL may not provide the standard Input/Output/ErrOutput in this case (because IsConsole = false), but we try a little harder, regardless of the IsConsole value.

  3. Caveat: in a GUI program under Windows you cannot depend on the fact that "StdOutStream <> nil means that stdout is actually available (because user redirected stdout etc.)". A first write to the StdOutStream may cause EWriteError, so watch out for this.

    This is tested on Windows 2000 Prof, with FPC 2.0.0 and 2.1.1 (revision 4317). When no stdout is available, StdOutStream should be nil, because GetStdHandle(STD_OUTPUT_HANDLE) should return 0. However, GetStdHandle(STD_OUTPUT_HANDLE) doesn't return 0... It returns some invalid handle (no, not INVALID_HANDLE_VALUE either) that you can't write into (trying to write returns in ERROR_INVALID_HANDLE WinAPI error). It seems that there is no way for me to check whether GetStdHandle(STD_OUTPUT_HANDLE) returned valid handle (e.g. because the program's stdout was redirected, so stdout is perfectly available) or whether it returned something unusable.

    Note that GetStdHandle(STD_INPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE) work correctly, so it should be OK to check StdInStream <> nil or StdErrStream <> nil. The only problematic one is GetStdHandle(STD_OUTPUT_HANDLE).

)

StdErrStream: TStream;

Streams to read/write a standard input/output/error of the program.

Tip: to read the standard input as a text file, you can use TTextReader and StdInStream:

var
  StdInReader: TTextReader;
begin
  StdInReader := TTextReader.Create(StdInStream, false);
  try
    while not StdInReader.Eof do
      DoSomethingWithInputLine(StdInReader.Readln);
  finally FreeAndNil(StdinReader) end;
end;

The advantage of using TTextReader above, compared to using the standard Pascal Readln procedure to read from the standard Pascal Input text file, is that you can easily modify the above code to read from any stream. So, instead of the standard input, you can easily read some stream that decompresses gzip data, or downloads data from the Internet... Actually, the overloaded constructor TTextReader.Create can accept an URL, like a file://... or http://..., and will internally use the stream returned by Download function for this URL.

Notes only for Windows GUI applications:

  1. Some (or all) of the variables below may be Nil in a Windows GUI application.

    If you want to be on the safe side, then don't use these streams in the GUI application (when IsConsole = false on Windows). But (with some caveats, see below) you can sometimes use them, if they are not-nil.

  2. You can have some of the standard streams available, even in a GUI application.

    User can run a GUI program and explicitly redirect it's standard stream, e.g. cat something | my_program.exe for stdin or my_program.exe > output.txt for stdout. Actually some shells, like Cygwin's bash, always redirect some streams under the hood.

    Note that the FPC (and Delphi?) RTL may not provide the standard Input/Output/ErrOutput in this case (because IsConsole = false), but we try a little harder, regardless of the IsConsole value.

  3. Caveat: in a GUI program under Windows you cannot depend on the fact that "StdOutStream <> nil means that stdout is actually available (because user redirected stdout etc.)". A first write to the StdOutStream may cause EWriteError, so watch out for this.

    This is tested on Windows 2000 Prof, with FPC 2.0.0 and 2.1.1 (revision 4317). When no stdout is available, StdOutStream should be nil, because GetStdHandle(STD_OUTPUT_HANDLE) should return 0. However, GetStdHandle(STD_OUTPUT_HANDLE) doesn't return 0... It returns some invalid handle (no, not INVALID_HANDLE_VALUE either) that you can't write into (trying to write returns in ERROR_INVALID_HANDLE WinAPI error). It seems that there is no way for me to check whether GetStdHandle(STD_OUTPUT_HANDLE) returned valid handle (e.g. because the program's stdout was redirected, so stdout is perfectly available) or whether it returned something unusable.

    Note that GetStdHandle(STD_INPUT_HANDLE) and GetStdHandle(STD_ERROR_HANDLE) work correctly, so it should be OK to check StdInStream <> nil or StdErrStream <> nil. The only problematic one is GetStdHandle(STD_OUTPUT_HANDLE).

)


Generated by PasDoc 0.15.0.