Method: Tamper::ExistencePack#encode

Defined in:
lib/tamper/existence_pack.rb

#encode(guid) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/tamper/existence_pack.rb', line 18

def encode(guid)
  guid_diff  = guid.to_i - @last_guid
  guid_diff += 1 if @current_chunk.empty? && @output.empty? && guid.to_i > 0

  if guid_diff == 1 || guid.to_i == 0  # guid is 1 step forward
    @current_chunk << '1'
    @run_counter += 1

  elsif guid_diff <= 0  # somehow we went backwards or didn't change guid on iteration
    raise ArgumentError, "Error: data was not sorted by GUID (got #{@last_guid}, then #{guid})!"

  elsif guid_diff > 40  # big gap, encode with skip control char
    dump_keep(@current_chunk, @run_counter)

    @output += control_code(:skip, guid_diff - 1)
    @current_chunk = '1'
    @run_counter   = 1

  else # skips < 40 should just be encoded as '0'
    if @run_counter > 40    # first check if a run came before this 0; if so dump it
      dump_keep(@current_chunk, @run_counter)
      @current_chunk = ''
      @run_counter = 0
    end

    @current_chunk += ('0' * (guid_diff - 1))
    @current_chunk << '1'
    @run_counter = 1
  end

  @last_guid = guid.to_i
end