response.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module Sphinx
  2. # Unpack internal Sphinx representation of ints, floats, strings, and arrays.
  3. # needed by Sphinx search engine.
  4. class Response
  5. # Initialize new request.
  6. def initialize(response)
  7. @response = response
  8. @position = 0
  9. @size = response.length
  10. end
  11. # Gets current stream position.
  12. def position
  13. @position
  14. end
  15. # Gets response size.
  16. def size
  17. @size
  18. end
  19. # Returns <tt>true</tt> when response stream is out.
  20. def eof?
  21. @position >= @size
  22. end
  23. # Get int from stream.
  24. def get_int
  25. raise EOFError if @position + 4 > @size
  26. value = @response[@position, 4].unpack('N*').first
  27. @position += 4
  28. return value
  29. end
  30. # Get 64-bit int from stream.
  31. def get_int64
  32. raise EOFError if @position + 8 > @size
  33. hi, lo = @response[@position, 8].unpack('N*N*')
  34. @position += 8
  35. return (hi << 32) + lo
  36. end
  37. # Get array of <tt>count</tt> ints from stream.
  38. def get_ints(count)
  39. length = 4 * count
  40. raise EOFError if @position + length > @size
  41. values = @response[@position, length].unpack('N*' * count)
  42. @position += length
  43. return values
  44. end
  45. # Get string from stream.
  46. def get_string
  47. length = get_int
  48. raise EOFError if @position + length > @size
  49. value = length > 0 ? @response[@position, length] : ''
  50. @position += length
  51. return value
  52. end
  53. # Get float from stream.
  54. def get_float
  55. raise EOFError if @position + 4 > @size
  56. uval = @response[@position, 4].unpack('N*').first;
  57. @position += 4
  58. return ([uval].pack('L')).unpack('f*').first
  59. end
  60. end
  61. end