Skip to content

Commit 97357e4

Browse files
kevinhughes27byroot
authored andcommitted
preallocate a buffer for reading from a socket
1 parent 97742e0 commit 97357e4

File tree

2 files changed

+27
-6
lines changed

2 files changed

+27
-6
lines changed

.rubocop.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,9 @@ Lint/EndAlignment:
106106
Layout/ElseAlignment:
107107
Enabled: false
108108

109+
Layout/RescueEnsureAlignment:
110+
Enabled: false
111+
109112
Naming/HeredocDelimiterNaming:
110113
Enabled: false
111114

lib/redis/connection/ruby.rb

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,30 @@ def write_timeout=(timeout)
3232
@write_timeout = (timeout if timeout && timeout > 0)
3333
end
3434

35-
def read(nbytes)
36-
result = @buffer.slice!(0, nbytes)
35+
string_capacity_support = begin
36+
String.new(capacity: 0)
37+
true # Ruby 2.4+
38+
rescue ArgumentError
39+
false # Ruby 2.3
40+
end
41+
42+
if string_capacity_support
43+
def read(nbytes)
44+
result = @buffer.slice!(0, nbytes)
3745

38-
result << _read_from_socket(nbytes - result.bytesize) while result.bytesize < nbytes
46+
buffer = String.new(capacity: nbytes, encoding: Encoding::ASCII_8BIT)
47+
result << _read_from_socket(nbytes - result.bytesize, buffer) while result.bytesize < nbytes
3948

40-
result
49+
result
50+
end
51+
else
52+
def read(nbytes)
53+
result = @buffer.slice!(0, nbytes)
54+
55+
result << _read_from_socket(nbytes - result.bytesize, "".b) while result.bytesize < nbytes
56+
57+
result
58+
end
4159
end
4260

4361
def gets
@@ -48,9 +66,9 @@ def gets
4866
@buffer.slice!(0, crlf + CRLF.bytesize)
4967
end
5068

51-
def _read_from_socket(nbytes)
69+
def _read_from_socket(nbytes, buffer = nil)
5270
loop do
53-
case chunk = read_nonblock(nbytes, exception: false)
71+
case chunk = read_nonblock(nbytes, buffer, exception: false)
5472
when :wait_readable
5573
unless wait_readable(@timeout)
5674
raise Redis::TimeoutError

0 commit comments

Comments
 (0)