From 0aaf274211d4b4877b266bc1ad406db4fd8160ab Mon Sep 17 00:00:00 2001 From: Samuel Williams Date: Sun, 2 Feb 2020 00:24:13 +1300 Subject: [PATCH] Ensure that binary buffer is used at all times. --- lib/openssl/buffering.rb | 31 +++++++++++++++++++++++++++---- test/test_buffering.rb | 9 ++++++++- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/lib/openssl/buffering.rb b/lib/openssl/buffering.rb index 5d0ed3b6f..a5f4241bf 100644 --- a/lib/openssl/buffering.rb +++ b/lib/openssl/buffering.rb @@ -22,6 +22,29 @@ module OpenSSL::Buffering include Enumerable + # A buffer which will retain binary encoding. + class Buffer < String + BINARY = Encoding::BINARY + + def initialize + super + + force_encoding(BINARY) + end + + def << string + if string.encoding == BINARY + super(string) + else + super(string.b) + end + + return self + end + + alias concat << + end + ## # The "sync mode" of the SSLSocket. # @@ -40,7 +63,7 @@ module OpenSSL::Buffering def initialize(*) super @eof = false - @rbuffer = String.new + @rbuffer = Buffer.new @sync = @io.sync end @@ -312,7 +335,7 @@ def eof? # buffer is flushed to the underlying socket. def do_write(s) - @wbuffer = String.new unless defined? @wbuffer + @wbuffer = Buffer.new unless defined? @wbuffer @wbuffer << s @wbuffer.force_encoding(Encoding::BINARY) @sync ||= false @@ -398,7 +421,7 @@ def <<(s) # See IO#puts for full details. def puts(*args) - s = String.new + s = Buffer.new if args.empty? s << "\n" end @@ -416,7 +439,7 @@ def puts(*args) # See IO#print for full details. def print(*args) - s = String.new + s = Buffer.new args.each{ |arg| s << arg.to_s } do_write(s) nil diff --git a/test/test_buffering.rb b/test/test_buffering.rb index 5f2ba9d4e..7575c5b4f 100644 --- a/test/test_buffering.rb +++ b/test/test_buffering.rb @@ -10,7 +10,7 @@ class IO attr_accessor :sync def initialize - @io = String.new + @io = Buffer.new def @io.sync true end @@ -41,6 +41,13 @@ def setup @io = IO.new end + def test_encoding + @io.write '😊' + @io.flush + + assert_equal @io.string.encoding, Encoding::BINARY + end + def test_flush @io.write 'a'