From 071ad5d96168b3575d5b0ea2daeed6938ce5b9c4 Mon Sep 17 00:00:00 2001
From: cremno <cremno@mail.ru>
Date: Tue, 22 Oct 2013 13:45:57 +0200
Subject: [PATCH 1/2] MRI: changes to mkxp's Marshal::load monkey patch

- force string encoding to UTF-8 only when it's ASCII-8BIT (force only valid UTF-8 strings in future?)

- support original Marshal::load proc (2nd arg)
---
 binding-mri/filesystem-binding.cpp | 22 ++++++++++++++--------
 1 file changed, 14 insertions(+), 8 deletions(-)

diff --git a/binding-mri/filesystem-binding.cpp b/binding-mri/filesystem-binding.cpp
index 92c9f79..1944f58 100644
--- a/binding-mri/filesystem-binding.cpp
+++ b/binding-mri/filesystem-binding.cpp
@@ -159,14 +159,19 @@ RB_METHOD(kernelSaveData)
 
 static VALUE stringForceUTF8(VALUE arg)
 {
-	if (rb_type(arg) != RUBY_T_STRING)
-		return arg;
-
-	rb_enc_associate(arg, rb_utf8_encoding());
+	if (rb_type(arg) == RUBY_T_STRING && ENCODING_IS_ASCII8BIT(arg))
+		rb_enc_associate_index(arg, rb_utf8_encindex());
 
 	return arg;
 }
 
+static VALUE marshal_load_custom_proc(VALUE arg, VALUE proc)
+{
+	VALUE obj = stringForceUTF8(arg);
+	obj = rb_funcall2(proc, rb_intern("call"), 1, &obj);
+	return obj;
+}
+
 RB_METHOD(_marshalLoad)
 {
 	RB_UNUSED_PARAM;
@@ -175,10 +180,11 @@ RB_METHOD(_marshalLoad)
 
 	rb_get_args(argc, argv, "o|o", &port, &proc, RB_ARG_END);
 
-	if (rb_type(proc) != RUBY_T_NIL)
-		rb_raise(rb_eNotImpError, "MKXP: Marshal with custom proc not (yet) implemented");
-
-	VALUE utf8Proc = rb_proc_new(RUBY_METHOD_FUNC(stringForceUTF8), Qnil);
+	VALUE utf8Proc;
+	if (NIL_P(proc))
+		utf8Proc = rb_proc_new(RUBY_METHOD_FUNC(stringForceUTF8), Qnil);
+	else
+		utf8Proc = rb_proc_new(RUBY_METHOD_FUNC(marshal_load_custom_proc), proc);
 
 	VALUE marsh = rb_const_get(rb_cObject, rb_intern("Marshal"));
 
-- 
2.43.0


From 8c45a5b11e7109aca3e0ee5ad4104685b0dd18a7 Mon Sep 17 00:00:00 2001
From: cremno <cremno@mail.ru>
Date: Tue, 22 Oct 2013 15:24:55 +0200
Subject: [PATCH 2/2] follow-up: style adjustments (see GH-2)

---
 binding-mri/filesystem-binding.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/binding-mri/filesystem-binding.cpp b/binding-mri/filesystem-binding.cpp
index 1944f58..7294b4d 100644
--- a/binding-mri/filesystem-binding.cpp
+++ b/binding-mri/filesystem-binding.cpp
@@ -165,10 +165,11 @@ static VALUE stringForceUTF8(VALUE arg)
 	return arg;
 }
 
-static VALUE marshal_load_custom_proc(VALUE arg, VALUE proc)
+static VALUE customProc(VALUE arg, VALUE proc)
 {
 	VALUE obj = stringForceUTF8(arg);
 	obj = rb_funcall2(proc, rb_intern("call"), 1, &obj);
+
 	return obj;
 }
 
@@ -184,7 +185,7 @@ RB_METHOD(_marshalLoad)
 	if (NIL_P(proc))
 		utf8Proc = rb_proc_new(RUBY_METHOD_FUNC(stringForceUTF8), Qnil);
 	else
-		utf8Proc = rb_proc_new(RUBY_METHOD_FUNC(marshal_load_custom_proc), proc);
+		utf8Proc = rb_proc_new(RUBY_METHOD_FUNC(customProc), proc);
 
 	VALUE marsh = rb_const_get(rb_cObject, rb_intern("Marshal"));
 
-- 
2.43.0