# File lib/mongo/protocol/message.rb, line 138
      def self.deserialize(io, max_message_size = MAX_MESSAGE_SIZE, expected_response_to = nil)
        length, _request_id, response_to, _op_code = deserialize_header(BSON::ByteBuffer.new(io.read(16)))

        # Protection from potential DOS man-in-the-middle attacks. See
        # DRIVERS-276.
        if length > (max_message_size || MAX_MESSAGE_SIZE)
          raise Error::MaxMessageSize.new(max_message_size)
        end

        # Protection against returning the response to a previous request. See
        # RUBY-1117
        if expected_response_to && response_to != expected_response_to
          raise Error::UnexpectedResponse.new(expected_response_to, response_to)
        end

        message = Registry.get(_op_code).allocate
        buffer = BSON::ByteBuffer.new(io.read(length - 16))

        message.send(:fields).each do |field|
          if field[:multi]
            deserialize_array(message, buffer, field)
          else
            deserialize_field(message, buffer, field)
          end
        end
        message.inflate!
      end