From 8793fac19f6e15f780cfccdf84e30f0d03e9588d Mon Sep 17 00:00:00 2001
From: Eric Wong <e@80x24.org>
Date: Mon, 4 Jan 2016 11:22:56 +0000
Subject: [PATCH] stringio: binmode sets encoding to ASCII-8BIT

This should match the behavior of IO#binmode as far
as treating content as ASCII-8BIT (binary).
---
 ext/stringio/stringio.c        | 13 ++++++++++++-
 test/stringio/test_stringio.rb |  7 +++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/ext/stringio/stringio.c b/ext/stringio/stringio.c
index 23c4356..6bc3bff 100644
--- a/ext/stringio/stringio.c
+++ b/ext/stringio/stringio.c
@@ -493,7 +493,18 @@ strio_set_lineno(VALUE self, VALUE lineno)
     return lineno;
 }
 
-#define strio_binmode strio_self
+static VALUE
+strio_binmode(VALUE self)
+{
+  struct StringIO *ptr = StringIO(self);
+  rb_encoding *enc = rb_ascii8bit_encoding();
+
+  ptr->enc = enc;
+  if (WRITABLE(self)) {
+      rb_enc_associate(ptr->string, enc);
+  }
+  return self;
+}
 
 #define strio_fcntl strio_unimpl
 
diff --git a/test/stringio/test_stringio.rb b/test/stringio/test_stringio.rb
index 77a9872..71de29c 100644
--- a/test/stringio/test_stringio.rb
+++ b/test/stringio/test_stringio.rb
@@ -665,4 +665,11 @@ def test_each_line_limit_0
     assert_raise(ArgumentError, "[ruby-dev:43392]") { StringIO.new.each_line(0){} }
     assert_raise(ArgumentError, "[ruby-dev:43392]") { StringIO.new.each_line("a",0){} }
   end
+
+  def test_binmode
+    s = StringIO.new
+    s.set_encoding('utf-8')
+    assert_same s, s.binmode
+    assert_equal Encoding::ASCII_8BIT, s.external_encoding
+  end
 end
-- 
EW

