From c40f70711ae121894ce0f3e657bf1b7d25a0cb4a Mon Sep 17 00:00:00 2001 From: Grant Gardner Date: Mon, 1 Jul 2024 00:25:45 +1000 Subject: [PATCH] Add SSLSocket#readbyte Companion to getbyte but raise EOFError Similar to https://github.com/ruby/openssl/pull/438 --- lib/openssl/buffering.rb | 6 ++++++ test/openssl/test_pair.rb | 21 +++++++++++++++++++++ test/openssl/test_ssl.rb | 13 +++++++++++++ test/openssl/ut_eof.rb | 4 ++++ 4 files changed, 44 insertions(+) diff --git a/lib/openssl/buffering.rb b/lib/openssl/buffering.rb index d0b4b1803..85f593af0 100644 --- a/lib/openssl/buffering.rb +++ b/lib/openssl/buffering.rb @@ -107,6 +107,12 @@ def getbyte read(1)&.ord end + # Get the next 8bit byte. Raises EOFError on EOF + def readbyte + raise EOFError if eof? + getbyte + end + ## # Reads _size_ bytes from the stream. If _buf_ is provided it must # reference a string which will receive the data. diff --git a/test/openssl/test_pair.rb b/test/openssl/test_pair.rb index 66e36a7ab..10942191d 100644 --- a/test/openssl/test_pair.rb +++ b/test/openssl/test_pair.rb @@ -101,6 +101,27 @@ def test_getc } end + def test_getbyte + ssl_pair {|s1, s2| + s1 << "a" + assert_equal(97, s2.getbyte) + } + end + + def test_readbyte + ssl_pair {|s1, s2| + s1 << "b" + assert_equal(98, s2.readbyte) + } + end + + def test_readbyte_eof + ssl_pair {|s1, s2| + s2.close + assert_raise(EOFError) { s1.readbyte } + } + end + def test_gets ssl_pair {|s1, s2| s1 << "abc\n\n$def123ghi" diff --git a/test/openssl/test_ssl.rb b/test/openssl/test_ssl.rb index 1471b0cb3..f011e881e 100644 --- a/test/openssl/test_ssl.rb +++ b/test/openssl/test_ssl.rb @@ -248,6 +248,19 @@ def test_getbyte } end + def test_readbyte + start_server { |port| + server_connect(port) { |ssl| + str = +("x" * 100 + "\n") + ssl.syswrite(str) + newstr = str.bytesize.times.map { |i| + ssl.readbyte + }.pack("C*") + assert_equal(str, newstr) + } + } + end + def test_sync_close start_server do |port| begin diff --git a/test/openssl/ut_eof.rb b/test/openssl/ut_eof.rb index 7b18f43a7..06aa632a6 100644 --- a/test/openssl/ut_eof.rb +++ b/test/openssl/ut_eof.rb @@ -8,6 +8,10 @@ def test_getbyte_eof open_file("") {|f| assert_nil f.getbyte } end + def test_readbyte_eof + open_file("") {|f| assert_raise(EOFError) { f.readbyte } } + end + def test_eof_0 open_file("") {|f| assert_equal("", f.read(0))