THRIFT-1632. rb: ruby: data corruption in thrift_native implementation of MemoryBufferTransport

This patch fixes a subtle bug whereby the read buffer was being resized but the method continued to read from the original, unresized buffer but at the wrong location.



git-svn-id: https://svn.apache.org/repos/asf/thrift/trunk@1355198 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/lib/rb/ext/memory_buffer.c b/lib/rb/ext/memory_buffer.c
index bd1bac8..319b073 100644
--- a/lib/rb/ext/memory_buffer.c
+++ b/lib/rb/ext/memory_buffer.c
@@ -93,25 +93,26 @@
   int index;
   VALUE buf = GET_BUF(self);
 
+  index = FIX2INT(rb_ivar_get(self, index_ivar_id));
   while (i < size) {
-    index = FIX2INT(rb_ivar_get(self, index_ivar_id));
     if (index >= RSTRING_LEN(buf)) {
       rb_raise(rb_eEOFError, "Not enough bytes remain in memory buffer");
     }
     char byte = RSTRING_PTR(buf)[index++];
 
-    if (index >= GARBAGE_BUFFER_SIZE) {
-      rb_ivar_set(self, buf_ivar_id, rb_funcall(buf, slice_method_id, 2, INT2FIX(index), INT2FIX(RSTRING_LEN(buf) - 1)));
-      index = 0;
-    }
-    rb_ivar_set(self, index_ivar_id, INT2FIX(index));
-
     if (i >= RSTRING_LEN(buffer_value)) {
       rb_raise(rb_eIndexError, "index %d out of string", i);
     }
     ((char*)RSTRING_PTR(buffer_value))[i] = byte;
     i++;
   }
+
+  if (index >= GARBAGE_BUFFER_SIZE) {
+    rb_ivar_set(self, buf_ivar_id, rb_funcall(buf, slice_method_id, 2, INT2FIX(index), INT2FIX(RSTRING_LEN(buf) - 1)));
+    index = 0;
+  }
+  rb_ivar_set(self, index_ivar_id, INT2FIX(index));
+
   return INT2FIX(i);
 }