Class: Nesser::Packer

Inherits:
Object
  • Object
show all
Defined in:
lib/nesser/packets/packer.rb

Instance Method Summary collapse

Constructor Details

#initializePacker

Returns a new instance of Packer.



22
23
24
25
# File 'lib/nesser/packets/packer.rb', line 22

def initialize()
  @data = ''
  @segment_cache = {}
end

Instance Method Details

#getObject



131
132
133
# File 'lib/nesser/packets/packer.rb', line 131

def get()
  return @data
end

#pack(format, *data) ⇒ Object



32
33
34
# File 'lib/nesser/packets/packer.rb', line 32

def pack(format, *data)
  @data += data.pack(format)
end

#pack_name(name, dry_run: false, compress: true) ⇒ Object



86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/nesser/packets/packer.rb', line 86

def pack_name(name, dry_run:false, compress:true)
  length = 0
  validate!(name)

  # `name` becomes nil at the end, unless there's a comma on the end, in
  # which case it's a 0-length string
  while name and name.length() > 0
    if compress && @segment_cache[name]
      # User a pointer if we've already done this
      if not dry_run
        @data += [0xc000 | @segment_cache[name]].pack("n")
      end

      # If we use break here, we get a bad NUL terminator
      return length + 2
    end

    # Log where we put this segment
    if not dry_run
      @segment_cache[name] = @data.length
    end

    # Get the next label
    segment, name = name.split(/\./, 2)

    # Encode it into the string
    if not dry_run
      @data += [segment.length(), segment].pack("Ca*")
    end
    length += 1 + segment.length()
  end

  # Always be null terminating
  if not dry_run
    @data += "\0"
  end
  length += 1

  return length
end