How to design a TLV decoder?

"Trustin Lee (이희승)" trustin at gmail.com
Mon Mar 29 10:07:54 EDT 2010


Hi,

You could define TLV decoder interface:

    interface TLVDecoder {
        TLV decode(ChannelBuffer buf);
    }

A decoder could look like:

    public class Type1TLVDecoder {
        public TLV decode(ChannelBuffer buf) {
            buf.markReaderIndex();
            try {
                if (buf.readUnsignedByte() == 1) {
                     // decode
                     // ...
                     return new Type1TLV(...);
                }
            } finally {
                buf.resetReaderIndex();
            }
            return null;
        }
    }

and your decoder could iterate all known TLVDecoder implementations
until one of them returns a TLV.  If all TLVDecoders return null even
after enough bytes were read, it means corrupt data or unknown message type.

HTH,
Trustin

hezjing wrote:
> Hi
> 
> I want to encode and decode a message which contains a list of
> Type-Length-Value (TLV).
> 
> So I have a class representing a message, and different classes for the
> TLVs.
> For example,
> 
> class Message {
>     List<TLV> typeLenthValues;
> }
> 
> interface TLV {
>     int getType();
>     int getLength();
>     byte[] getValue();
> }
> 
> class NameTLV implements TLV {
>     void setFirstName() { ... }
>     void setLastName() { ... }
> }
> 
> class AddressTLV implements TLV {
>     void setPostCode() { ... }
>     void setStreet() { ... }
> }
> 
> 
> The encoding is straight-forward, I'm able to create one generic encoder
> that handle all the different TLVs.
> 
> Unfortunately I'm not able to create a generic decoder to decode the raw
> bytes into specific TLV.
> For example the following is the code snippet from my decoder,
> 
> class decoder {
>     public TLV decode(...) {
>         TLV tlv = null;
>         if (type == 0) {
>             tlv = decodeName();
>         } else if (type == 1) {
>             tlv = decodeAddress();
>         } else if (type == ...) {
>         ...
>         } else if (type == 80) {
>             tlv = decodeX();
>         }
>     }
> }
> 
> 
> I don't like the code where I have to code each of the TLV, and there are
> more TLVs introduced in the future!
> 
> Do you have any idea of how to create a decoder like this?
> 
> 
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> netty-users mailing list
> netty-users at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/netty-users

-- 
what we call human nature in actuality is human habit
http://gleamynode.net/


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 260 bytes
Desc: OpenPGP digital signature
Url : http://lists.jboss.org/pipermail/netty-users/attachments/20100329/2ed31559/attachment-0001.bin 


More information about the netty-users mailing list