export class ByteUtils {
  static toBytesFromHexString(hex: string): Uint8Array {
    if (!hex) {
      return new Uint8Array();
    }
    return new Uint8Array(hex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
  }

  static toHexString(bytes: Uint8Array): string {
    if (!bytes) {
      return '';
    }
    return bytes.reduce(
      (str, byte) => str + byte.toString(16).padStart(2, '0'),
      ''
    );
  }

  static toBytesFromString(s: string): Uint8Array {
    if (!s) {
      return new Uint8Array();
    }
    return new TextEncoder().encode(s);
  }

  static toStringFromBytes(bytes: Uint8Array): string {
    if (!bytes) {
      return '';
    }
    return new TextDecoder('utf-8').decode(bytes);
  }
}
