Class: Codec::Headerlength

Inherits:
Prefixedlength show all
Defined in:
lib/codec/prefix.rb

Direct Known Subclasses

Headerfulllength

Instance Attribute Summary

Attributes inherited from Base

#id

Instance Method Summary collapse

Methods inherited from Prefixedlength

#build_field

Methods inherited from Base

#add_sub_codec, #build_field, #decode_with_length, #encode_with_length, #eval_length, #get_sub_codecs

Constructor Details

#initialize(id, header, content, length_path) ⇒ Headerlength

Returns a new instance of Headerlength.



54
55
56
57
58
# File 'lib/codec/prefix.rb', line 54

def initialize(id,header,content,length_path)
  @path = length_path # length attribute contain the path for length field in header
  @separator = @path.slice!(0).chr # first character contain the separator
  super(id,header,content)
end

Instance Method Details

#decode(buffer) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/codec/prefix.rb', line 70

def decode(buffer)
  f = Field.new
  f.set_id(@id)
  head, buf = @length_codec.decode(buffer)
  head.set_id(@length_codec.id)
  f.add_sub_field(head)
  len = get_length(head)
  if len == 0
    return f,buf
  else
     len -= (buffer.length - buf.length) if @header_length_include
    val,remain = @value_codec.decode_with_length(buf,len)
     val.set_id(@value_codec.id)
	  f.add_sub_field(val)
     return f,remain
  end
end

#encode(field) ⇒ Object

Raises:



88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/codec/prefix.rb', line 88

def encode(field)
  # encode content
  content_field = field.get_sub_field(@value_codec.id)
  length, content = @value_codec.encode_with_length(content_field)
  head_field = field.get_sub_field(@length_codec.id)
  raise EncodingException, "Missing header for encoding #{@id}" if head_field.empty?
  # update length field in header if length !=0
  head_field.set_value(length,@path,@separator) if length !=0
  # encode header
  header =  @length_codec.encode(head_field)
  return header + content
end

#get_length(header_field) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/codec/prefix.rb', line 60

def get_length(header_field)
   return header_field.get_value.to_i if @path.length == 0 # Handle simple numeric header field
	length_field = header_field.get_deep_field(@path,@separator)
	if length_field.nil?
	  return 0
	else
	  length_field.get_value.to_i
	end
end