hex2Bin method

Uint8List hex2Bin(
  1. String hexString
)

Implementation

Uint8List hex2Bin(String hexString) {
  // Convert the hex string to a Dart string
  final hexPointer = hexString.toNativeUtf8().cast<ffi.Char>();

  // Allocate memory for the binary data
  final binMaxLen = hexString.length ~/ 2;
  final binPointer = calloc<ffi.Uint8>(binMaxLen);
  final binLen = calloc<ffi.Size>();

  // Call sodium_hex2bin to perform the conversion
  final result = sodium_hex2bin(
    binPointer.cast<ffi.UnsignedChar>(),
    binMaxLen,
    hexPointer,
    hexString.length,
    ffi.nullptr,
    binLen,
    ffi.nullptr,
  );

  List<int> output = [];
  if (result == 0) {
    final binData = binPointer.asTypedList(binLen.value);

    // Clone the original list
    output = List.from(binData);
  } else {
    debugPrint('[Lazysodium] Conversion hex2Bin failed.');
  }

  // Free allocated memory
  calloc.free(binPointer);
  calloc.free(binLen);
  calloc.free(hexPointer);

  if (result == 0) {
    return Uint8List.fromList(output);
  }
  return Uint8List(0);
}