encode method

Uint8List? encode(
  1. DVAssetEncoding encoding,
  2. Uint8List bytes, {
  3. int? level,
})

bytes encoded with encoding at level (the highest by default), or null when that is not smaller than bytes.

Implementation

Uint8List? encode(DVAssetEncoding encoding, Uint8List bytes, {int? level}) {
  if (bytes.length < 2) return null;
  final int codec = _codecFor(encoding);
  final ffi.Pointer<ffi.Uint8> input = pkgffi.malloc<ffi.Uint8>(bytes.length);
  // One byte short of the input: an encoding that does not fit is one that
  // saves nothing.
  final int capacity = bytes.length - 1;
  final ffi.Pointer<ffi.Uint8> output = pkgffi.malloc<ffi.Uint8>(capacity);
  try {
    input.asTypedList(bytes.length).setAll(0, bytes);
    final int written = _encode(
        codec, level ?? _highestLevel(encoding), input, bytes.length, output, capacity);
    if (written == -2) return null;
    if (written < 0) {
      throw StateError('${encoding.token} encoding failed ($written)');
    }
    return Uint8List.fromList(output.asTypedList(written));
  } finally {
    pkgffi.malloc.free(input);
    pkgffi.malloc.free(output);
  }
}