È una tecnica di codifica?
Soluzione
Il tuo codice di esempio non funzionerà, poiché stai mescolando shortstring const
e pointer
di string
- Come ha affermato Rob nel suo commento.
E il tuo codice non ha nulla a che fare con KLV né codifica TLV.
Qui può essere un campione di codifica TLV (mostro solo la codifica delle stringhe, ma puoi aggiungere altri tipi):
type
TTLVType = (tlvUnknown, tlvString, tlvInteger);
function EncodeToTLV(const aString: WideString): TBytes;
var Len: integer;
begin
Len := length(aString)*2;
SetLength(result,Len+sizeof(TTLVType)+sizeof(integer));
Result[0] := ord(tlvString); // Type
PInteger(@Result[sizeof(TTLVType)])^ := Len; // Length
move(pointer(aString)^,Result[sizeof(TTLVType)+sizeof(integer)],Len); // Value
end;
function DecodeStringFromTLV(const aValue: TBytes): WideString;
begin
if (length(aValue)<3) or (aValue[0]<>ord(tlvString)) or
(PInteger(@aValue[sizeof(TTLVType)])^<>length(aValue)-sizeof(TTLVType)-sizeof(integer)) then
raise EXception.Create('Invalid input format');
SetString(result,PWideChar(@Result[sizeof(TTLVType)+sizeof(integer)]),PInteger(@aValue[sizeof(TTLVType)])^ div 2);
end;
ero solito WideString
Qui perché può archiviare in sicurezza qualsiasi contenuto Unicode, anche sulla versione pre-Delfi 2009 del compilatore.
Puoi usare un record invece del mio puntatore aritmetico:
type
TTLVHeader = packed record
ContentType: TTLVType;
ContentLength: integer;
Content: array[0..1000] of byte; // but real length will vary
end;
PTLVHeader = ^TTLVHeader;
function EncodeToTLV(const aString: WideString): TBytes;
var Len: integer;
begin
Len := length(aString)*2;
SetLength(result,Len+sizeof(TTLVType)+sizeof(integer));
with PTLVHeader(result)^ do
begin
ContentType := tlvString;
ContentLength := Len;
move(pointer(aString)^,Content,Len);
end;
end;
Una codifica simile può essere utilizzata per KLV, ma aggiungendo una chiave interi nell'intestazione.
Altri suggerimenti
Per quanto ne so, questo definisce solo due costanti (Lex_0
e Lex_1
in questo caso) e li mette in un array chiamato LexTable
, questo non è affatto codifica.
Lex_0: string // declares a string constant by the name of Lex_0
[length('(EOF)')] // specifies the length of the string, this is equivalent to [5] in this case
='(EOF)' // sets the constant to '(EOF)'
poi il LexTable
Viene creata una matrice di puntatori alla stringa e gli indirizzi delle due costanti vengono inseriti nell'array.