Files
MycLib/Src/Data/Myc.Data.Records.pas
T
2025-12-09 12:59:36 +01:00

74 lines
1.9 KiB
ObjectPascal

unit Myc.Data.Records;
interface
uses
System.SysUtils,
System.Generics.Collections,
Myc.Data.Keyword,
Myc.Data.Value;
type
// Runtime implementation for generic records using linear search (optimized for small record sizes)
TDynamicRecord = class(TInterfacedObject, IKeywordMapping<TDataValue>)
private
FFields: TArray<TPair<IKeyword, TDataValue>>;
// IKeywordMapping implementation
function GetItems(Idx: Integer): TPair<IKeyword, TDataValue>;
function GetFields(const Key: IKeyword): TDataValue;
function GetCount: Integer;
public
constructor Create(const AFields: TArray<TPair<IKeyword, TDataValue>>);
function IndexOf(const Key: IKeyword): Integer;
end;
implementation
{ TDynamicRecord }
constructor TDynamicRecord.Create(const AFields: TArray<TPair<IKeyword, TDataValue>>);
begin
inherited Create;
FFields := AFields;
end;
function TDynamicRecord.GetCount: Integer;
begin
Result := Length(FFields);
end;
function TDynamicRecord.GetFields(const Key: IKeyword): TDataValue;
var
idx: Integer;
begin
idx := IndexOf(Key);
if idx < 0 then
raise EArgumentException.CreateFmt('Field "%s" not found in dynamic record.', [Key.Name]);
Result := FFields[idx].Value;
end;
function TDynamicRecord.GetItems(Idx: Integer): TPair<IKeyword, TDataValue>;
begin
Result := FFields[Idx];
end;
function TDynamicRecord.IndexOf(const Key: IKeyword): Integer;
var
i: Integer;
begin
// Linear search (O(n)). Fast enough for typical records.
// Keyword comparison is integer-based (Idx), so this is efficient.
for i := 0 to High(FFields) do
begin
if FFields[i].Key.Idx = Key.Idx then
begin
Result := i;
exit;
end;
end;
Result := -1;
end;
end.