Sha256: 3510dbd2c1b97dd96257b0ccf455ae05e9cd0e5d2fb94e0eb334af2076d96a70

Contents?: true

Size: 1.4 KB

Versions: 2

Compression:

Stored size: 1.4 KB

Contents

##
# DNSSD::TextRecord is a Hash wrapper that can encode its contents for DNSSD.

class DNSSD::TextRecord

  ##
  # Creates a new TextRecord, decoding an encoded +text_record+ if given.

  def initialize(text_record = nil)
    @records = {}

    return unless text_record

    text_record = text_record.dup

    until text_record.empty? do
      size = text_record.slice! 0
      next if size.zero?

      raise ArgumentError, 'ran out of data in text record' if
        text_record.length < size

      entry = text_record.slice! 0, size

      raise ArgumentError, 'key not found' unless entry =~ /^[^=]/

      key, value = entry.split '=', 2

      next unless key

      @records[key] = value
    end
  end

  def [](key)
    @records[key]
  end

  def []=(key, value)
    @records[key] = value
  end

  ##
  # Encodes this TextRecord.  A key value pair must be less than 255 bytes in
  # length.  Keys longer than 14 bytes may not be compatible with all
  # clients.

  def encode
    @records.sort.map do |key, value|
      key = key.to_s

      raise DNSSD::Error, "empty key" if key.empty?
      raise DNSSD::Error, "key '#{key}' contains =" if key =~ /=/

      record = value ? [key, value.to_s].join('=') : key

      raise DNSSD::Error, "key value pair at '#{key}' too large to encode" if
        record.length > 255

      "#{record.length.chr}#{record}"
    end.join ''
  end

  def to_hash
    @records.dup
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dnssd-1.2 lib/dnssd/text_record.rb
dnssd-1.1.0 lib/dnssd/text_record.rb