Question

Furhter to ruakh's post here, I want to ascertain wether the following snippet falls into the TLV or KLV encoding type :

interface

const
  Lex_0: string[length('(EOF)')] ='(EOF)';
  Lex_1: string[length('(Error)')] ='(Error)';

  LexTable : array[0..114] of ^String = (
  @Lex_0,
  @Lex_1
  )
Was it helpful?

Solution

Your sample code won't work, as you are mixing shortstring const and pointer of string - as Rob stated in his comment.

And your code has nothing to do with KLV nor TLV encoding.

Here may be a sample of TLV encoding (I show only string encoding, but you can add other 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;

I used WideString here because it can safely store any Unicode content, even on pre-Delphi 2009 version of the compiler.

You may use a record instead of my pointer arithmetic:

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;

A similar encoding may be used for KLV, but adding an integer key in the header.

OTHER TIPS

As far as I can tell, this only defines two constants (Lex_0 and Lex_1 in this case) and puts them into an array called LexTable, this is no encoding at all.

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)'

then the LexTable array of pointers to string is created and addresses of the two constants are put in the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top