Method: Sixword.encode_iter

Defined in:
lib/sixword.rb

.encode_iter(byte_string, options = {}) {|String| ... } ⇒ Enumerator?

Encode a string of bytes in six-word encoding (full API). This is the relatively low level method that supports all the major options. See the various other top-level methods for convenience helpers.

Parameters:

  • byte_string (String)

    A byte string to encode

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :pad (Boolean) — default: false

    Whether to use the custom padding scheme established by this library. If false, then byte_string length must be a multiple of 8.

  • :words_per_slice (Integer) — default: 1

    The number of words to yield together in each iteration. By default, yield only a single word at a time. You can yield up to 6 words together, which will be joined by a space ‘ ` character.

Yields:

  • (String)

    A String word (or String of space separated words, if :words_per_slice is given)

Returns:

  • (Enumerator, nil)

    If no block is given, return an Enumerator

Raises:

  • Sixword::InputError on incorrectly padded inputs

  • ArgumentError on bad argument types



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/sixword.rb', line 159

def self.encode_iter(byte_string, options={})
  options = {words_per_slice: 1, pad: false}.merge(options)
  words_per_slice = options.fetch(:words_per_slice)
  pad = options.fetch(:pad)

  unless byte_string
    raise ArgumentError.new("byte_string is falsy")
  end

  unless block_given?
    return to_enum(__method__, byte_string, options)
  end

  if !pad && byte_string.bytesize % 8 != 0
    raise InputError.new(
      "Must pad bytes to multiple of 8 or use pad_encode")
  end

  unless (1..6).include?(words_per_slice)
    raise ArgumentError.new("words_per_slice must be in 1..6")
  end

  byte_string.each_byte.each_slice(8) do |slice|
    # figure out whether we need padding
    padding = nil
    if pad && slice.length < 8
      padding = 8 - slice.length
      padding.times do
        slice << 0
      end
    end

    # encode the data
    encoded = Lib.encode_64_bits(slice)

    # add padding information as needed
    if padding
      encoded[-1] << padding.to_s
    end

    encoded.each_slice(words_per_slice) do |encoded_slice|
      yield encoded_slice.join(' ')
    end
  end
end