Skip to content

Commit

Permalink
preallocate a buffer for reading from a socket
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinhughes27 authored and byroot committed Aug 11, 2021
1 parent 97742e0 commit 97357e4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
3 changes: 3 additions & 0 deletions .rubocop.yml
Expand Up @@ -106,6 +106,9 @@ Lint/EndAlignment:
Layout/ElseAlignment:
Enabled: false

Layout/RescueEnsureAlignment:
Enabled: false

Naming/HeredocDelimiterNaming:
Enabled: false

Expand Down
30 changes: 24 additions & 6 deletions lib/redis/connection/ruby.rb
Expand Up @@ -32,12 +32,30 @@ def write_timeout=(timeout)
@write_timeout = (timeout if timeout && timeout > 0)
end

def read(nbytes)
result = @buffer.slice!(0, nbytes)
string_capacity_support = begin
String.new(capacity: 0)
true # Ruby 2.4+
rescue ArgumentError
false # Ruby 2.3
end

if string_capacity_support
def read(nbytes)
result = @buffer.slice!(0, nbytes)

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

result
result
end
else
def read(nbytes)
result = @buffer.slice!(0, nbytes)

result << _read_from_socket(nbytes - result.bytesize, "".b) while result.bytesize < nbytes

result
end
end

def gets
Expand All @@ -48,9 +66,9 @@ def gets
@buffer.slice!(0, crlf + CRLF.bytesize)
end

def _read_from_socket(nbytes)
def _read_from_socket(nbytes, buffer = nil)
loop do
case chunk = read_nonblock(nbytes, exception: false)
case chunk = read_nonblock(nbytes, buffer, exception: false)
when :wait_readable
unless wait_readable(@timeout)
raise Redis::TimeoutError
Expand Down

0 comments on commit 97357e4

Please sign in to comment.