Skip to content

Instantly share code, notes, and snippets.

@khusamov
Last active May 28, 2019 08:45
Show Gist options
  • Save khusamov/ea3eced548ebd59b3ebac566286720d9 to your computer and use it in GitHub Desktop.
Save khusamov/ea3eced548ebd59b3ebac566286720d9 to your computer and use it in GitHub Desktop.
Разбиение бинарного массива по делителю. Необходим для парсинга Multipart в браузере.
// TextDecoder, TextEncoder, https://github.com/inexorabletash/text-encoding
String2Uint8Array: function(str) {
return new TextEncoder().encode(str);
},
Uint8Array2String: function(arr, encoding) {
return new TextDecoder(encoding || "utf-8").decode(arr);
}
/**
* Разбиение массива по делителю.
* Используется Buffer от feross.
* @link https://github.com/feross/buffer
* @param source
* @param splitter
* @returns {Array}
* @constructor
*/
Uint8ArraySplit(source, splitter) {
// console._log(Pir.core.data.Multipart.Uint8Array2String(sourceArray))
const result = [];
const splitterBuffer = Buffer.from(splitter);
let sourceBuffer = Buffer.from(source);
let splitterIndex;
do {
splitterIndex = sourceBuffer.indexOf(splitterBuffer);
if (splitterIndex === -1) {
result.push(sourceBuffer);
} else {
result.push(sourceBuffer.slice(0, splitterIndex));
sourceBuffer = sourceBuffer.slice(splitterIndex + splitterBuffer.length);
}
} while (splitterIndex !== -1);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment