File: symbol.rb

package info (click to toggle)
ruby-msgpack 1.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 972 kB
  • sloc: ruby: 4,789; ansic: 4,309; java: 1,809; makefile: 4
file content (26 lines) | stat: -rw-r--r-- 952 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Symbol
  # to_msgpack_ext is supposed to return a binary string.
  # The canonical way to do it for symbols would be:
  #  [to_s].pack('A*')
  # However in this instance we can take a shortcut
  if method_defined?(:name)
    alias_method :to_msgpack_ext, :name
  else
    alias_method :to_msgpack_ext, :to_s
  end

  def self.from_msgpack_ext(data)
    # from_msgpack_ext is supposed to parse a binary string.
    # The canonical way to do it for symbols would be:
    #  data.unpack1('A*').to_sym
    # However in this instance we can take a shortcut

    # We assume the string encoding is UTF-8, and let Ruby create either
    # an ASCII symbol or UTF-8 symbol.
    data.force_encoding(Encoding::UTF_8).to_sym
  rescue EncodingError
    # If somehow the string wasn't valid UTF-8 not valid ASCII, we fallback
    # to what has been the historical behavior of creating a binary symbol
    data.force_encoding(Encoding::BINARY).to_sym
  end
end