All files / utils encodingUtils.ts

54.54% Statements 6/11
25% Branches 2/8
50% Functions 1/2
54.54% Lines 6/11

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 341x                   1x 1x       1x 1x                 1x                
import iconv from 'iconv-lite';
 
export type TextEncoding = 'utf-8' | 'ascii' | 'utf16le' | 'base64' | 'hex' | 'latin1' | 'binary';
 
/**
 * Encodes text to a buffer using the specified encoding
 * @param text The text to encode
 * @param encoding The encoding to use (defaults to utf-8)
 * @returns ArrayBuffer containing the encoded data
 */
export function encodeText(text: string, encoding: TextEncoding = 'utf-8'): ArrayBuffer {
  Iif (encoding === 'base64' || encoding === 'hex') {
    return Buffer.from(text).toString(encoding) as any;
  }
  
  const buffer = iconv.encode(text, encoding);
  return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
}
 
/**
 * Decodes a buffer to text using the specified encoding
 * @param buffer The buffer to decode
 * @param encoding The encoding to use (defaults to utf-8)
 * @returns The decoded text
 */
export function decodeText(buffer: ArrayBuffer, encoding: TextEncoding = 'utf-8'): string {
  const nodeBuffer = Buffer.from(buffer);
  
  Iif (encoding === 'base64' || encoding === 'hex') {
    return Buffer.from(nodeBuffer.toString(), encoding).toString();
  }
  
  return iconv.decode(nodeBuffer, encoding);
}