Sha256: 80656682e29d0177a928fe491e8cf0640cbed0d7acf907a54874241a5d8ccea5

Contents?: true

Size: 1.85 KB

Versions: 12

Compression:

Stored size: 1.85 KB

Contents

module Riddle
  class Client
    # This class takes care of the translation of ints, strings and arrays to
    # the format required by the Sphinx service.
    class Message
      def initialize
        @message = ""
        @size_method = @message.respond_to?(:bytesize) ? :bytesize : :length
      end
      
      # Append raw data (only use if you know what you're doing)
      def append(*args)
        args.each { |arg| @message << arg }
      end
      
      # Append a string's length, then the string itself
      def append_string(str)
        string = str.respond_to?(:force_encoding) ?
          str.dup.force_encoding('ASCII-8BIT') : str
        
        @message << [string.send(@size_method)].pack('N') + string
      end
      
      # Append an integer
      def append_int(int)
        @message << [int.to_i].pack('N')
      end
      
      def append_64bit_int(int)
        @message << [int.to_i >> 32, int.to_i & 0xFFFFFFFF].pack('NN')
      end
      
      # Append a float
      def append_float(float)
        @message << [float].pack('f').unpack('L*').pack("N")
      end
      
      def append_boolean(bool)
        append_int(bool ? 1 : 0)
      end
      
      # Append multiple integers
      def append_ints(*ints)
        ints.each { |int| append_int(int) }
      end
      
      def append_64bit_ints(*ints)
        ints.each { |int| append_64bit_int(int) }
      end
      
      # Append multiple floats
      def append_floats(*floats)
        floats.each { |float| append_float(float) }
      end
      
      # Append an array of strings - first appends the length of the array,
      # then each item's length and value.
      def append_array(array)
        append_int(array.length)
        
        array.each { |item| append_string(item) }
      end
      
      # Returns the entire message
      def to_s
        @message
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
riddle-1.3.3 lib/riddle/client/message.rb
riddle-1.3.2 lib/riddle/client/message.rb
riddle-1.3.1 lib/riddle/client/message.rb
riddle-1.3.0 lib/riddle/client/message.rb
riddle-1.2.2 lib/riddle/client/message.rb
riddle-1.2.1 lib/riddle/client/message.rb
riddle-1.2.0 lib/riddle/client/message.rb
riddle-1.1.0 lib/riddle/client/message.rb
riddle-1.0.12 lib/riddle/client/message.rb
riddle-1.0.11 lib/riddle/client/message.rb
riddle-1.0.10 lib/riddle/client/message.rb
riddle-1.0.9 lib/riddle/client/message.rb