Class: CoCoGe::CodeGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/co_co_ge/code_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(symbols:, bits: nil, length: nil, separator: nil, parts_per_word: nil) ⇒ CodeGenerator

Returns a new instance of CodeGenerator.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/co_co_ge/code_generator.rb', line 4

def initialize(symbols:, bits: nil, length: nil, separator: nil, parts_per_word: nil)
  @symbols        = symbols.to_a.uniq
  @separator      = separator.to_s
  @parts_per_word = parts_per_word

  check_arguments

  !!bits ^ !!length or raise ArgumentError,
    "either bits or length parameter is required"
  if bits
    @bits = bits
    @length = (Math.log(1 << @bits) / Math.log(@symbols.size)).floor
  else
    @length = length
    @bits = (Math.log(@symbols.size ** @length) / Math.log(2)).floor
  end
end

Instance Attribute Details

#bitsObject (readonly)

Returns the value of attribute bits.



24
25
26
# File 'lib/co_co_ge/code_generator.rb', line 24

def bits
  @bits
end

#lengthObject (readonly)

Returns the value of attribute length.



26
27
28
# File 'lib/co_co_ge/code_generator.rb', line 26

def length
  @length
end

#parts_per_wordObject (readonly)

Returns the value of attribute parts_per_word.



30
31
32
# File 'lib/co_co_ge/code_generator.rb', line 30

def parts_per_word
  @parts_per_word
end

#separatorObject (readonly)

Returns the value of attribute separator.



28
29
30
# File 'lib/co_co_ge/code_generator.rb', line 28

def separator
  @separator
end

#symbolsObject (readonly)

Returns the value of attribute symbols.



22
23
24
# File 'lib/co_co_ge/code_generator.rb', line 22

def symbols
  @symbols
end

Instance Method Details

#capacityObject



32
33
34
# File 'lib/co_co_ge/code_generator.rb', line 32

def capacity
  @symbols.size ** @length
end

#duration(count:, attempts_per_second:) ⇒ Object



36
37
38
# File 'lib/co_co_ge/code_generator.rb', line 36

def duration(count:, attempts_per_second:)
  Tins::Duration.new(capacity / count / attempts_per_second)
end

#generate(bytes: generate_bytes) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/co_co_ge/code_generator.rb', line 40

def generate(bytes: generate_bytes)
  parts = symbolize(bytes: bytes)
  if @parts_per_word
    parts = parts.each_slice(@parts_per_word).map { |p| p.join }
  end
  parts.join(@separator)
end

#parse(code, pack_format: nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/co_co_ge/code_generator.rb', line 48

def parse(code, pack_format: nil)
  code = code.delete(@separator)
  bytes = []
  loop do
    code.empty? and break
    number = parse_next_symbol(code) or return
    bytes << number
  end
  bytes
end

#symbolize(bytes: generate_bytes) ⇒ Object



59
60
61
# File 'lib/co_co_ge/code_generator.rb', line 59

def symbolize(bytes: generate_bytes)
  bytes.map { |b| @symbols[b % @symbols.size] }
end