program Project1;
{$mode objfpc}{$H+}
uses
SysUtils;
type
generic TPreallocatedStack<T> = class
private type PT = ^T;
private
FData: PT;
FLength: SizeInt;
FSize: SizeInt;
public
constructor Create(const ASize: SizeInt);
destructor Destroy; override;
procedure Push(constref AItem: T);
function Pop: T;
end;
constructor TPreallocatedStack.Create(const ASize: SizeInt);
begin
inherited Create;
FData := GetMem(ASize * SizeOf(T));
FSize := ASize;
FLength := 0;
end;
destructor TPreallocatedStack.Destroy;
begin
Freemem(FData);
inherited Destroy;
end;
procedure TPreallocatedStack.Push(constref AItem: T);
begin
FData[FLength] := AItem;
Inc(FLength);
end;
function TPreallocatedStack.Pop: T;
begin
Dec(FLength);
Result := FData[FLength];
end;
type
TIntStack = specialize TPreallocatedStack<Integer>;
var
Stack: TIntStack;
i: Integer;
begin
Stack := TIntStack.Create(1024*1024*1024*10); // Allocates around 40 Gigabytes (10 gigs * 4 bytes per int)
try
for i:=0 to 10 do
Stack.Push(i);
for i := 0 to 3 do
WriteLn(Stack.Pop);
finally
Stack.Free;
end;
end.