Module: Ecoji

Defined in:
lib/ecoji.rb,
lib/ecoji.rb,
lib/ecoji/version.rb

Defined Under Namespace

Modules: Emojis Classes: Error

Constant Summary collapse

PADDING =
0x2615
PADDING_LAST_V1 =
[0x269C, 0x1F3CD, 0x1F4D1, 0x1F64B].freeze
PADDING_LAST_V2 =
[0x1F977, 0x1F6FC, 0x1F4D1, 0x1F64B].freeze
REV_EMOJIS =
begin
  map = {}

  Emojis::V1.each_with_index do |n, ordinal|
    map[n] = { ordinal:, version: 1, padding: :none }
  end

  Emojis::V2.each_with_index do |n, ordinal|
    if map[n]
      map[n][:version] = 3
    else
      map[n] = { ordinal:, version: 2, padding: :none }
    end
  end

  map[PADDING] = { ordinal: 0, version: 3, padding: :fill }
  map[PADDING_LAST_V1[0]] = { ordinal: 0, version: 1, padding: :last }
  map[PADDING_LAST_V1[1]] = { ordinal: 1 << 8, version: 1, padding: :last }
  map[PADDING_LAST_V1[2]] = { ordinal: 2 << 8, version: 3, padding: :last }
  map[PADDING_LAST_V1[3]] = { ordinal: 3 << 8, version: 3, padding: :last }
  map[PADDING_LAST_V2[0]] = { ordinal: 0, version: 2, padding: :last }
  map[PADDING_LAST_V2[1]] = { ordinal: 1 << 8, version: 2, padding: :last }

  map
end
VERSION =
'0.1.0'

Class Method Summary collapse

Class Method Details

.decode(data, encoding: Encoding::UTF_8) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/ecoji.rb', line 63

def self.decode(data, encoding: Encoding::UTF_8)
  expected_version = 3
  chars = data.chars
  result = []

  loop do
    emojis, expected_version = read_four(chars, expected_version)
    break if emojis.empty?

    bits = (emojis[0][:ordinal] << 30) |
           (emojis[1][:ordinal] << 20) |
           (emojis[2][:ordinal] << 10) |
           emojis[3][:ordinal]
    out = [
      bits >> 32,
      0xff & (bits >> 24),
      0xff & (bits >> 16),
      0xff & (bits >> 8),
      0xff & bits
    ]

    if emojis[1][:padding] == :fill
      out = out[0...1]
    elsif emojis[2][:padding] == :fill
      out = out[0...2]
    elsif emojis[3][:padding] == :fill
      out = out[0...3]
    elsif emojis[3][:padding] == :last
      out = out[0...4]
    end

    result.concat(out)
  end

  result.pack('C*').force_encoding(encoding)
end

.encode(data, version: 2) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/ecoji.rb', line 42

def self.encode(data, version: 2)
  case version
  when 1
    emojis = Emojis::V1
    padding_last = PADDING_LAST_V1
    trim = false
  when 2
    emojis = Emojis::V2
    padding_last = PADDING_LAST_V2
    trim = true
  else
    raise Error, 'Version must be either 1 or 2'
  end

  result = []
  data.bytes.each_slice(5) do |s|
    encode_five(s, emojis, padding_last, trim) { |n| result << n }
  end
  result.pack('U*')
end