Class: Async::Redis::Protocol::RESP

Inherits:
IO::Protocol::Line
  • Object
show all
Defined in:
lib/async/redis/protocol/resp.rb

Instance Method Summary collapse

Constructor Details

#initialize(stream) ⇒ RESP

Returns a new instance of RESP.



36
37
38
# File 'lib/async/redis/protocol/resp.rb', line 36

def initialize(stream)
	super(stream, CRLF)
end

Instance Method Details

#closed?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/async/redis/protocol/resp.rb', line 40

def closed?
	@stream.closed?
end

#read_data(length) ⇒ Object



70
71
72
73
74
75
76
77
# File 'lib/async/redis/protocol/resp.rb', line 70

def read_data(length)
	buffer = @stream.read(length) or @stream.eof!
	
	# Eat trailing whitespace because length does not include the CRLF:
	@stream.read(2) or @stream.eof!
	
	return buffer
end

#read_objectObject Also known as: read_response



79
80
81
82
83
84
85
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
# File 'lib/async/redis/protocol/resp.rb', line 79

def read_object
	line = read_line
	token = line.slice!(0, 1)
	
	case token
	when '$'
		length = line.to_i
		
		if length == -1
			return nil
		else
			return read_data(length)
		end
	when '*'
		count = line.to_i
		
		# Null array (https://redis.io/topics/protocol#resp-arrays):
		return nil if count == -1
		
		array = Array.new(count) {read_object}
		
		return array
	when ':'
		return line.to_i
	
	when '-'
		raise ServerError.new(line)
	
	when '+'
		return line
	
	else
		@stream.flush
		
		raise NotImplementedError, "Implementation for token #{token} missing"
	end
	
	# TODO: If an exception (e.g. Async::TimeoutError) propagates out of this function, perhaps @stream should be closed? Otherwise it might be in a weird state.
end

#write_object(object) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/async/redis/protocol/resp.rb', line 57

def write_object(object)
	case object
	when String
		write_lines("$#{object.bytesize}", object)
	when Array
		write_array(object)
	when Integer
		write_lines(":#{object}")
	else
		write_object(object.to_redis)
	end
end

#write_request(arguments) ⇒ Object

The redis server doesn’t want actual objects (e.g. integers) but only bulk strings. So, we inline it for performance.



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/async/redis/protocol/resp.rb', line 45

def write_request(arguments)
	write_lines("*#{arguments.count}")
	
	arguments.each do |argument|
		string = argument.to_s
		
		write_lines("$#{string.bytesize}", string)
	end
	
	@stream.flush
end