Class: Bagua::Tri

Inherits:
Object
  • Object
show all
Defined in:
lib/bagua/tri.rb

Overview

Provides encoding and decoding functions for trigrams.

Class Method Summary collapse

Class Method Details

.decode(grams) ⇒ Object

TODO:

Add an option to choose the encoding.

Note:

Chomps trailing null characters, as they are the result of zero padding added when the number of bits being encoded in the trigrams is not an even multiple of 3.

Decodes a string of trigrams into a UTF-8 string.



15
16
17
# File 'lib/bagua/tri.rb', line 15

def self.decode(grams)
  return to_bytes(grams).pack('C*').chomp("\000").force_encoding('utf-8')
end

.encode(str) ⇒ Object

Encodes a string into a string of trigrams representing the byte values of each character in the string.



6
7
8
# File 'lib/bagua/tri.rb', line 6

def self.encode(str)
  return from_bytes(str.unpack('C*'))
end

.from_bytes(bytes) ⇒ Object

Returns the trigram representation of the input bytes.



20
21
22
23
24
# File 'lib/bagua/tri.rb', line 20

def self.from_bytes(bytes)
  trios = Bagua::bytes_to_ntets(bytes, 3)
  grams = trios.map { |trio| gram(trio) }
  return grams.join("")
end

.to_bytes(grams) ⇒ Object

Returns the byte representation of a string of trigrams.



27
28
29
30
31
32
# File 'lib/bagua/tri.rb', line 27

def self.to_bytes(grams)
  ucodes = grams.unpack('U*')
  trios = ucodes.map { |ucode| ucode - TRI_BASE }
  bytes = Bagua::ntets_to_bytes(trios, 3)
  return bytes
end