[fpc-devel] Aligned dynamic arrays

Anthony Walter sysrpl at gmail.com
Thu Mar 28 23:40:48 CET 2019


Here is a brief follow up. I am working on other projects at the moment,
but I am confident this a simple solution. Please tell me if this somehow
will not fit you needs.

Create a new type that is compatible with Array<T> where Array<T> = type
array of T.
Define implcit conversions between the to types and similar methods
Create a Push and Pop methods, well as a read write Length property and two
indexers.
Indexer named Reference is default and provides a memory reference to Tn
Indexer named Item is available and provides a copy of Tn

So we would have ...

  TAlignedArray = record<T>
    type TReference = ^T;
    type TValue = T;
    FPage: Pointer;
    FLength: Integer;
    procedure SetLength(Value: Integer);
    function GetReference(Index: Integer): TReference;
    function GetItem(Index: Integer): TValue;
    procedure SetItem(Index: Integer; const Value: TValue);
  public
    procedure Push(const Item: TValue);
    procedure Pop: TValue;
    property Length: Integer read FLength write SetLength;
    property Reference[Index: Integer]: TValue read GetReference; default;
    property Item[Index: Integer]: TValue read GetValue write SetValue;

Examples usages:

type
  TVertexArray = TAlignedArray<TVec3>;

// and later

var
  Vertices: TVertexArray;
begin
  Vertices.Length = 1000; // okay, request a page aligned memory
  Vertices[0].X := X; // okay, we are working with references
  Vertices.Item[1] := Vec3(X, Y, Z); // okay, we are setting a value
  Vertices.Length = 0; // clean up


When the vertex array need to grow, it uses the POSIX posix_memalign (or
the _aligned_malloc on Windows) to request a 4 KB aligned and sized page
adequate to contain all the items. The newish allocate and release
mechanisms can further be used to simply the management of the
TAlignedArray<T> type.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20190328/67dcdaae/attachment.html>


More information about the fpc-devel mailing list