Est-ce une technique d'encodage?
Question
Poursuivez vers le post de ruakh ici , je veux savoir si l'extrait suivant appartient à Type d'encodage TLV ou KLV :
interface
const
Lex_0: string[length('(EOF)')] ='(EOF)';
Lex_1: string[length('(Error)')] ='(Error)';
LexTable : array[0..114] of ^String = (
@Lex_0,
@Lex_1
)
La solution
Votre exemple de code ne fonctionnera pas, car vous mélangez shortstring const
et pointer
de string
- comme Rob l'a déclaré dans son commentaire.
Et votre code n'a rien à voir avec l'encodage KLV ou TLV.
Voici peut-être un exemple d'encodage TLV (je ne montre que l'encodage de chaîne, mais vous pouvez ajouter d'autres types):
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;
J'ai utilisé WideString
ici car il peut stocker en toute sécurité tout contenu Unicode, même sur la version antérieure à Delphi 2009 du compilateur.
Vous pouvez utiliser un enregistrement au lieu de mon arithmétique de pointeur:
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;
Un encodage similaire peut être utilisé pour KLV, mais en ajoutant une clé entière dans l'en-tête.
Autres conseils
Pour autant que je sache, cela ne définit que deux constantes (Lex_0
et Lex_1
dans ce cas) et les met dans un tableau appelé LexTable
, ce n'est pas du tout un encodage.
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)'
alors le tableau LexTable
de pointeurs vers la chaîne est créé et les adresses des deux constantes sont placées dans le tableau.