From 66d149e92ff1baddfdfd4b6a88ca9bcea6fc6195 Mon Sep 17 00:00:00 2001 From: dcodeIO Date: Fri, 9 Jun 2017 11:32:35 +0200 Subject: [PATCH] Ported utf8 chunking mechanism to base64 as well, fixes #800 --- lib/base64/index.js | 28 +++++++++++++++++++--------- lib/base64/package.json | 2 +- package.json | 2 +- 3 files changed, 21 insertions(+), 11 deletions(-) diff --git a/lib/base64/index.js b/lib/base64/index.js index 001344f77..6146f5430 100644 --- a/lib/base64/index.js +++ b/lib/base64/index.js @@ -40,7 +40,8 @@ for (var i = 0; i < 64;) * @returns {string} Base64 encoded string */ base64.encode = function encode(buffer, start, end) { - var string = []; // alt: new Array(Math.ceil((end - start) / 3) * 4); + var parts = null, + chunk = []; var i = 0, // output index j = 0, // goto index t; // temporary @@ -48,29 +49,38 @@ base64.encode = function encode(buffer, start, end) { var b = buffer[start++]; switch (j) { case 0: - string[i++] = b64[b >> 2]; + chunk[i++] = b64[b >> 2]; t = (b & 3) << 4; j = 1; break; case 1: - string[i++] = b64[t | b >> 4]; + chunk[i++] = b64[t | b >> 4]; t = (b & 15) << 2; j = 2; break; case 2: - string[i++] = b64[t | b >> 6]; - string[i++] = b64[b & 63]; + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; j = 0; break; } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } } if (j) { - string[i++] = b64[t]; - string[i ] = 61; + chunk[i++] = b64[t]; + chunk[i++] = 61; if (j === 1) - string[i + 1] = 61; + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); } - return String.fromCharCode.apply(String, string); + return String.fromCharCode.apply(String, chunk.slice(0, i)); }; var invalidEncoding = "invalid encoding"; diff --git a/lib/base64/package.json b/lib/base64/package.json index 7eba6d44e..f119811bc 100644 --- a/lib/base64/package.json +++ b/lib/base64/package.json @@ -1,7 +1,7 @@ { "name": "@protobufjs/base64", "description": "A minimal base64 implementation for number arrays.", - "version": "1.1.1", + "version": "1.1.2", "author": "Daniel Wirtz ", "repository": { "type": "git", diff --git a/package.json b/package.json index d4f9b6069..fd1d8d80e 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "dependencies": { "long": "^3.2.0", "@protobufjs/aspromise": "^1.1.2", - "@protobufjs/base64": "^1.1.1", + "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.3", "@protobufjs/eventemitter": "^1.1.0", "@protobufjs/fetch": "^1.1.0",