Yesterday I came to know about representing information using TLV format.
If you were to write a portable BER TLV encoder/decoder in ANSI C, what data structure would you use (*)?
Would something like the follwoing do?
struct TlvElement
{
int nTag;
int nLength;
unsigned char *pValue; // Byte array
TlvElement *pNext;
};
(*) Unfortunately I can’t use C++ and STL for this.
From the wiki article:
So, I’d change the
nTagandnLengthto some fixed-length type.int‘s size is platform specific and this could cause you some troubles. Fix their sizes for your protocol and useint8_t,int16_torint32_t, etc. FornLength, you may even use unsigned.As the value could be any type, I’d use
void*forpValue, instead ofunsigned char*.How you will use this data structure? How you want to have access to the different TLVs?
My point is – do you need linked list? Or, will linked list be the best option for your case/application/purposes/etc?
What I’m trying to say is, that you may remove the
pNextelement and just treat the TLVs as elements of a (dynamically growing) array. This one really depends on your needs.Most probably, as you’re implementing TLVs, you’ll need to send them through some connection, right? If so, you need to think about some protocol. I’d do something like this – send the total numbers of TLVs at the very beginning and I would NOT use linked-list, but a dynamic array.
You should be careful sending such data structure through the network – the
pNextpointers will not be valid, they must be reset on the other side of the connection.You also need to carefully send the data, but I guess you know these things. I just wanted to mention them.
EDIT I see you have some troubles understanding what does nested TLV mean.
A nested TLV is just a TLV element, which has value of a type TLV. And this has nothing to do with the “container” of TLVs – dynamic array or linked list.
Here’s an untested example, just to get the idea. I’d do this like this:
NOTE: once again, this is not tested code, but I guess you get the idea. Hope that helps.