Class: Paquito::SingleBytePrefixVersionWithStringBypass

Inherits:
SingleBytePrefixVersion show all
Defined in:
lib/paquito/single_byte_prefix_version_with_string_bypass.rb

Constant Summary collapse

UTF8_VERSION =
255
BINARY_VERSION =
254
ASCII_VERSION =
253

Instance Method Summary collapse

Constructor Details

#initialize(current_version, coders, string_coder = nil) ⇒ SingleBytePrefixVersionWithStringBypass

Returns a new instance of SingleBytePrefixVersionWithStringBypass.



9
10
11
12
# File 'lib/paquito/single_byte_prefix_version_with_string_bypass.rb', line 9

def initialize(current_version, coders, string_coder = nil)
  super(current_version, coders)
  @string_coder = string_coder
end

Instance Method Details

#dump(object) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/paquito/single_byte_prefix_version_with_string_bypass.rb', line 14

def dump(object)
  if object.class == String # We don't want to match subclasses
    case object.encoding
    when Encoding::UTF_8
      UTF8_VERSION.chr(Encoding::BINARY) << (@string_coder ? @string_coder.dump(object) : object.b)
    when Encoding::BINARY
      BINARY_VERSION.chr(Encoding::BINARY) << (@string_coder ? @string_coder.dump(object) : object)
    when Encoding::US_ASCII
      ASCII_VERSION.chr(Encoding::BINARY) << (@string_coder ? @string_coder.dump(object) : object)
    else
      super
    end
  else
    super
  end
end

#load(payload) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/paquito/single_byte_prefix_version_with_string_bypass.rb', line 31

def load(payload)
  payload_version = payload.getbyte(0)
  unless payload_version
    raise UnsupportedCodec, "Missing version byte."
  end

  case payload_version
  when UTF8_VERSION
    string = payload.byteslice(1..-1).force_encoding(Encoding::UTF_8)
    @string_coder ? @string_coder.load(string) : string
  when BINARY_VERSION
    string = payload.byteslice(1..-1).force_encoding(Encoding::BINARY)
    @string_coder ? @string_coder.load(string) : string
  when ASCII_VERSION
    string = payload.byteslice(1..-1).force_encoding(Encoding::US_ASCII)
    @string_coder ? @string_coder.load(string) : string
  else
    coder = @coders.fetch(payload_version) do
      raise UnsupportedCodec, "Unsupported packer version #{payload_version}"
    end
    coder.load(payload.byteslice(1..-1))
  end
end