Class: Codec::Packed

Inherits:
Base
  • Object
show all
Defined in:
lib/codec/packed.rb

Instance Method Summary collapse

Methods inherited from Base

#add_sub_codec, #get_sub_codecs

Constructor Details

#initialize(length, isNumeric = true, isLeftPadded = false, isFPadded = false) ⇒ Packed

Returns a new instance of Packed.



3
4
5
6
7
8
# File 'lib/codec/packed.rb', line 3

def initialize(length, isNumeric = true, isLeftPadded=false, isFPadded = false)
  @length = length
  @isNum = isNumeric
  @fPad = isFPadded
  @lPad = isLeftPadded
end

Instance Method Details

#check_length(buf, length) ⇒ Object

No more required encode return the field length for upper codec layer def get_length(field)

if @length > 0
  return @length 
else
  return field.get_value.to_s.length
end

end



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/codec/packed.rb', line 19

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(buf, f, length = nil) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/codec/packed.rb', line 31

def decode(buf,f, length = nil)
  length ||= @length
  l = check_length(buf,(length + 1) / 2)
  val = buf.slice!(0...l).unpack("H*").first
  # remove padding if odd length
  ( @lPad ? val.chop! : val.slice!(0) ) if @length.odd? || length.odd?
  val = val.to_i if @isNum
  f.set_value(val)   
end

#encode(buf, field) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/codec/packed.rb', line 41

def encode(buf, field)
  out = field.get_value.to_s
  Logger.debug{ "Encode packed #{out} on #{@length} [#{@isNum}|#{@fPad}|#{@lPad}]" }
  padding = (@fPad ? "F" : "0")
  if @length > 0
    out = (@lPad ? out.ljust(@length,padding) : out.rjust(@length,padding))
    raise TooLongDataException if out.length > @length
  end
  l = out.length
  # handle padding if odd length
  (@lPad ? out << padding : out.prepend(padding) )if out.length.odd?
  Logger.debug{ "before packing : #{out}" }
  out = [out].pack("H*")
  buf << out
  return l
end