THRIFT-3483 Incorrect empty binary handling introduced by THRIFT-3359
Client: C++, Node.js
Patch: Nobuaki Sukegawa

This closes #737
diff --git a/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp b/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp
index f1370bb..9569188 100644
--- a/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp
+++ b/lib/cpp/src/thrift/protocol/TJSONProtocol.cpp
@@ -801,9 +801,11 @@
   uint32_t len = static_cast<uint32_t>(tmp.length());
   str.clear();
   // Ignore padding
-  uint32_t bound = len >= 2 ? len - 2 : 0;
-  for (uint32_t i = len - 1; i >= bound && b[i] == '='; --i) {
-    --len;
+  if (len >= 2)  {
+    uint32_t bound = len - 2;
+    for (uint32_t i = len - 1; i >= bound && b[i] == '='; --i) {
+      --len;
+    }
   }
   while (len >= 4) {
     base64_decode(b, 4);
diff --git a/lib/nodejs/lib/thrift/binary_protocol.js b/lib/nodejs/lib/thrift/binary_protocol.js
index 25e5634..6d3918e 100644
--- a/lib/nodejs/lib/thrift/binary_protocol.js
+++ b/lib/nodejs/lib/thrift/binary_protocol.js
@@ -276,7 +276,7 @@
 TBinaryProtocol.prototype.readBinary = function() {
   var len = this.readI32();
   if (len === 0) {
-    return new Buffer();
+    return new Buffer(0);
   }
 
   if (len < 0) {
diff --git a/lib/nodejs/lib/thrift/compact_protocol.js b/lib/nodejs/lib/thrift/compact_protocol.js
index deecf48..b0e9148 100644
--- a/lib/nodejs/lib/thrift/compact_protocol.js
+++ b/lib/nodejs/lib/thrift/compact_protocol.js
@@ -761,7 +761,7 @@
 TCompactProtocol.prototype.readBinary = function() {
   var size = this.readVarint32();
   if (size === 0) {
-    return new Buffer();
+    return new Buffer(0);
   }
 
   if (size < 0) {
diff --git a/test/cpp/src/TestClient.cpp b/test/cpp/src/TestClient.cpp
index a6773d4..0ad789d 100644
--- a/test/cpp/src/TestClient.cpp
+++ b/test/cpp/src/TestClient.cpp
@@ -463,6 +463,20 @@
     /**
      * BINARY TEST
      */
+    printf("testBinary(empty)\n");
+    try {
+      string bin_result;
+      testClient.testBinary(bin_result, string());
+      if (!bin_result.empty()) {
+        printf("*** FAILED ***\n");
+        printf("invalid length: %lu\n", static_cast<long unsigned int>(bin_result.size()));
+        return_code |= ERR_BASETYPES;
+      }
+    } catch (exception& ex) {
+      printf("}\n*** FAILED ***\n");
+      printf("%s\n", ex.what());
+      return_code |= ERR_BASETYPES;
+    }
     printf("testBinary([-128..127]) = {");
     const char bin_data[256]
         = {-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114,