Module: BaseHangul

Defined in:
lib/basehangul.rb,
lib/basehangul/utils.rb,
lib/basehangul/version.rb

Overview

Binary encoder using hangul.

Defined Under Namespace

Modules: Utils, Version

Class Method Summary collapse

Class Method Details

.decode(str) ⇒ Object

Public: Decode BaseHangul string.

str - A String encoded with BaseHangul.

Returns the String decoded binary.



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/basehangul.rb', line 35

def self.decode(str)
  indices = str.each_char.map { |ch| Utils.to_index(ch) }
  binary = indices.map do |index|
    case index
    when -1         then ''
    when 0..1023    then index.to_s(2).rjust(10, '0')
    when 1024..1027 then (index - 1024).to_s(2).rjust(2, '0')
    end
  end.join
  binary = binary[0..-(binary.size % 8 + 1)]
  [binary].pack('B*')
end

.encode(bin) ⇒ Object

Public: Encode binary with BaseHangul.

bin - A String binary to encode.

Returns the String encoded hangul.



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/basehangul.rb', line 17

def self.encode(bin)
  chunks = Utils.chunks(bin.unpack('B*').first, 10)
  padding = ''
  last = chunks.last
  if last
    case last.size
    when 2       then chunks[-1] = '1' + last.rjust(10, '0')
    when 4, 6, 8 then padding = PADDING * (last.size / 2 - 1)
    end
  end
  chunks.map { |b| Utils.to_hangul(b.ljust(10, '0').to_i(2)) }.join + padding
end