All files / Sources/IO/Core/BinaryHelper index.js

40% Statements 6/15
14.28% Branches 1/7
100% Functions 2/2
40% Lines 6/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49              2x 2x             2x   2x 2x 2x                                                          
/**
 * Converts a binary buffer in an ArrayBuffer to a string.
 *
 * Note this does not take encoding into consideration, so don't
 * expect proper Unicode or any other encoding.
 */
function arrayBufferToString(arrayBuffer) {
  const decoder = new TextDecoder('latin1');
  return decoder.decode(arrayBuffer);
}
 
/**
 * Extracts binary data out of a file ArrayBuffer given a prefix/suffix.
 */
function extractBinary(arrayBuffer, prefixRegex, suffixRegex = null) {
  const str = arrayBufferToString(arrayBuffer);
 
  const prefixMatch = prefixRegex.exec(str);
  if (!prefixMatch) {
    return { text: str };
  }
 
  const dataStartIndex = prefixMatch.index + prefixMatch[0].length;
  const strFirstHalf = str.substring(0, dataStartIndex);
  let retVal = null;
 
  const suffixMatch = suffixRegex ? suffixRegex.exec(str) : null;
  if (suffixMatch) {
    const strSecondHalf = str.substr(suffixMatch.index);
    retVal = {
      text: strFirstHalf + strSecondHalf,
      binaryBuffer: arrayBuffer.slice(dataStartIndex, suffixMatch.index),
    };
  } else {
    // no suffix, so just take all the data starting from dataStartIndex
    retVal = {
      text: strFirstHalf,
      binaryBuffer: arrayBuffer.slice(dataStartIndex),
    };
  }
 
  return retVal;
}
 
export default {
  arrayBufferToString,
  extractBinary,
};