unit DynArray;
interface
TDynArray =
class
private
FDataPointer: Pointer;
FElementSize: Integer;
FDataSize: Integer;
function GetValue(
Index: Integer): Integer;
procedure SetValue(
Index: Integer;
const Value: Integer);
procedure CopyData(Destination: Pointer; Size: Integer);
public
constructor Create(InitialLength: Integer);
destructor Destroy;
override;
property Value[
Index: Integer]: Integer
read GetValue
write SetValue;
procedure SetLength(NewLength: Integer);
end;
const
ElementSize = sizeof(Integer);
implementation
{ TDynArray }
procedure TDynArray.CopyData(Destination: Pointer; Size: Integer);
begin
CopyMemory(Destination, FDataPointer, Size);
end;
constructor TDynArray.Create(InitialLength: Integer);
begin
FElementSize := ElementSize;
FDataPointer :=
nil;
FDataSize := 0;
SetLength(InitialLength);
end;
destructor TDynArray.Destroy;
begin
SetLength(0);
end;
function TDynArray.GetValue(
Index: Integer): Integer;
begin
if Index > Pred(FDataSize)
then
//irgendeine Exception oder sowas auslösen
Result := Integer(Pointer(Integer(FDataPointer) +
Index * FElementSize)^);
end;
procedure TDynArray.SetLength(NewLength: Integer);
var
NewData: Pointer;
begin
if NewLength <> 0
then
FreeMem(FDataPointer, FDataSize * FElementSize);
GetMem(NewData, NewLength * FElementSize);
if FDataSize <> 0
then
CopyData(NewData, FDataSize * FElementSize);
FreeMem(FDataPointer, FDataSize * FElementSize);
FDataPointer := NewData;
end;
procedure TDynArray.SetValue(
Index: Integer;
const Value: Integer);
begin
if Index > Pred(FDataSize)
then
//irgendeine Exception oder sowas auslösen
Integer(Pointer(Integer(FDataPointer) +
Index * FElementSize)^) := Value;
end;
end.