Skip to content

♻️ Refactor ResponseReader #435

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions lib/net/imap/response_reader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,34 @@ def initialize(client, sock)
end

def read_response_buffer
buff = String.new
@buff = String.new
catch :eof do
while true
read_line(buff)
break unless /\{(\d+)\}\r\n\z/n =~ buff
read_literal(buff, $1.to_i)
read_line
break unless (@literal_size = get_literal_size)
read_literal
end
end
buff
ensure
@buff = nil
end

private

def read_line(buff)
attr_reader :buff, :literal_size

def get_literal_size = /\{(\d+)\}\r\n\z/n =~ buff && $1.to_i

def read_line
buff << (@sock.gets(CRLF) or throw :eof)
end

def read_literal(buff, literal_size)
def read_literal
literal = String.new(capacity: literal_size)
buff << (@sock.read(literal_size, literal) or throw :eof)
ensure
@literal_size = nil
end

end
Expand Down
3 changes: 3 additions & 0 deletions test/net/imap/test_response_reader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@ def literal(str) = "{#{str.bytesize}}\r\n#{str}"
long_line = "tag ok #{aaaaaaaaa} #{aaaaaaaaa}\r\n"
literal_aaaa = "* fake #{literal aaaaaaaaa}\r\n"
literal_crlf = "tag ok #{literal many_crlfs} #{literal many_crlfs}\r\n"
zero_literal = "tag ok #{literal ""} #{literal ""}\r\n"
illegal_crs = "tag ok #{many_crs} #{many_crs}\r\n"
illegal_lfs = "tag ok #{literal "\r"}\n#{literal "\r"}\n\r\n"
io = StringIO.new([
simple,
long_line,
literal_aaaa,
literal_crlf,
zero_literal,
illegal_crs,
illegal_lfs,
simple,
Expand All @@ -40,6 +42,7 @@ def literal(str) = "{#{str.bytesize}}\r\n#{str}"
assert_equal long_line, rcvr.read_response_buffer.to_str
assert_equal literal_aaaa, rcvr.read_response_buffer.to_str
assert_equal literal_crlf, rcvr.read_response_buffer.to_str
assert_equal zero_literal, rcvr.read_response_buffer.to_str
assert_equal illegal_crs, rcvr.read_response_buffer.to_str
assert_equal illegal_lfs, rcvr.read_response_buffer.to_str
assert_equal simple, rcvr.read_response_buffer.to_str
Expand Down