Class: Codec::Headerlength

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

Instance Method Summary collapse

Methods inherited from Base

#add_sub_codec, #get_sub_codecs

Constructor Details

#initialize(header, header_id, content, content_id, length_path, total_length = false) ⇒ Headerlength

Returns a new instance of Headerlength.



42
43
44
45
46
47
48
49
# File 'lib/codec/prefix.rb', line 42

def initialize(header,header_id,content,content_id,length_path,total_length = false)
  @header_id = header_id
  @content_id = content_id
  @path = length_path # length attribute contain the path for length field in header
  @separator = @path.slice!(0).chr # first character contain the separator
  @total_length = total_length # indicate that length in header is equal to (header + content) length
  super(header,content)
end

Instance Method Details

#decode(buffer, f, length = nil) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/codec/prefix.rb', line 61

def decode(buffer, f, length=nil)
   f.set_value("") # reinit field value
   buffer = buffer.slice!(0...length) if length && length > 0
   initial_len = buffer.size
   head = Field.new(@header_id)
   content = Field.new(@content_id)
  @length_codec.decode(buffer,head)
   h_len = initial_len - buffer.size
  f.add_sub_field(head)
  len = get_length(head)
  if len > 0
     len -= h_len if @total_length
    @value_codec.decode(buffer, content, len)
	  f.add_sub_field(content)
  end
end

#encode(buf, field) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/codec/prefix.rb', line 78

def encode(buf, field)
  # encode content
  content_buf = ""
  length = 0
  content = field.get_sub_field(@content_id)
  length  = @value_codec.encode(content_buf, content) unless content.nil?
  head = field.get_sub_field(@header_id)
  raise EncodingException.new "Missing header for encoding #{@id}" if head.empty?
  # update length field in header if length !=0
  head.set_value(length,@path,@separator) if length !=0
  # encode header
  head_buf =  ""
  h_len = @length_codec.encode(head_buf,head)
  # TODO : optimize computation for header length 
  if length != 0 && @total_length # re-encode header with total length
    length = head_buf.length + content_buf.length
    head.set_value(length,@path,@separator)
    head_buf = ""
    @length_codec.encode(head_buf,head)
  end
  buf << head_buf
  buf << content_buf
  return head_buf.length + content_buf.length
end

#get_length(header_field) ⇒ Object



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

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