Skip to content

Commit 59a828f

Browse files
authored
Merge pull request #100 from graup/fix-uiny8array
Fix uint8array check
2 parents 9fee62e + 5e339a3 commit 59a828f

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

binary/utils.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,11 +1051,6 @@ jspb.utils.byteSourceToUint8Array = function(data) {
10511051
return /** @type {!Uint8Array} */(new Uint8Array(data));
10521052
}
10531053

1054-
if (typeof Buffer != 'undefined' && data.constructor === Buffer) {
1055-
return /** @type {!Uint8Array} */ (
1056-
new Uint8Array(/** @type {?} */ (data)));
1057-
}
1058-
10591054
if (data.constructor === Array) {
10601055
data = /** @type {!Array<number>} */(data);
10611056
return /** @type {!Uint8Array} */(new Uint8Array(data));
@@ -1066,6 +1061,15 @@ jspb.utils.byteSourceToUint8Array = function(data) {
10661061
return goog.crypt.base64.decodeStringToUint8Array(data);
10671062
}
10681063

1064+
if (data instanceof Uint8Array) {
1065+
// Support types like nodejs Buffer and other subclasses of Uint8Array.
1066+
data = /** @type {!Uint8Array} */ (data);
1067+
// Make a shallow copy to ensure we only ever deal with Uint8Array
1068+
// exactly to ensure monomorphism.
1069+
return /** @type {!Uint8Array} */ (
1070+
new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
1071+
}
1072+
10691073
goog.asserts.fail('Type not convertible to Uint8Array.');
10701074
return /** @type {!Uint8Array} */(new Uint8Array(0));
10711075
};

binary/utils_test.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -719,7 +719,6 @@ describe('binaryUtilsTest', function() {
719719
var sourceBytes = new Uint8Array(sourceData);
720720
var sourceBuffer = sourceBytes.buffer;
721721
var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
722-
var sourceString = goog.crypt.byteArrayToString(sourceData);
723722

724723
function check(result) {
725724
expect(result.constructor).toEqual(Uint8Array);
@@ -740,5 +739,8 @@ describe('binaryUtilsTest', function() {
740739

741740
// Converting base64-encoded strings into Uint8Arrays should work.
742741
check(convert(sourceBase64));
742+
743+
// Existing Uint8Array into Uint8Arrays should work.
744+
check(convert(sourceUint8Array));
743745
});
744746
});

0 commit comments

Comments
 (0)