Class: Codec::Tlv
Instance Method Summary
collapse
#get_length
Methods inherited from Base
#add_sub_codec, #get_sub_codecs
Constructor Details
#initialize(length, header, content) ⇒ Tlv
Returns a new instance of Tlv.
3
4
5
6
7
|
# File 'lib/codec/tlv.rb', line 3
def initialize(length,,content)
super(length,content)
@tag_codec =
@subCodecs = {}
end
|
Instance Method Details
#check_length(buf, length) ⇒ Object
9
10
11
12
13
14
15
16
17
18
19
|
# File 'lib/codec/tlv.rb', line 9
def check_length(buf,length)
raise "Length is nil" if length.nil?
if(length != 0)
if buf.length < length
raise BufferUnderflow, "Not enough data for decoding (#{length}/#{buf.length})"
end
return length
else
return buf.length
end
end
|
#decode(buffer, msg, length = nil) ⇒ Object
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# File 'lib/codec/tlv.rb', line 39
def decode(buffer, msg, length = nil)
unless length.nil?
l = check_length(buffer,length)
buffer = buffer.slice!(0...l)
end
tag = Field.new
begin
until buffer.empty?
begin
@tag_codec.decode(buffer,tag)
rescue
raise ParsingException, "Tlv Codec still remaining data but failed to decode tag when decoding field #{msg.get_id}"
end
Logger.debug { "Decoding tag #{tag.get_value.to_s}"}
sf = Field.new(tag.get_value.to_s)
subcodec = @subCodecs[tag.get_value.to_s]
if subcodec.nil?
Logger.debug { "using default codec for tag #{tag.get_value.to_s}"}
super(buffer,sf)
else
Logger.debug { "using predefined codec for tag #{tag.get_value.to_s}"}
len_field = Field.new("len")
@length_codec.decode(buffer,len_field)
subcodec.decode(buffer,sf,len_field.get_value.to_i)
end
Logger.debug { "Add field #{sf} to tlv"}
msg.add_sub_field(sf)
end
rescue BufferUnderflow => e
raise ParsingException, "Tlv Codec failed to decode field #{msg.get_id}"
val = Field.new
val.set_value("Buffer underflow when parsing tlv #{msg.get_id} [#{buffer.unpack("H*").first}]")
buffer.clear
end
unless buffer.empty? || length.nil?
Logger.warn("Remain data in a tlv buffer :[#{buffer.unpack("H*").first}]")
end
end
|
#encode(buf, field) ⇒ Object
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
# File 'lib/codec/tlv.rb', line 21
def encode(buf, field)
out = ""
fields = field.get_value
fields.each do |sf|
@tag_codec.encode(out, Field.new('*',sf.get_id))
if @subCodecs[sf.get_id]
content = ""
len = @subCodecs[sf.get_id].encode(content, sf)
@length_codec.encode(out, Field.new('*',len))
out << content
else
super(out, sf)
end
end
buf << out
return out.length
end
|