loadIntoTempFile function
For memory efficiency, we write to a temp file as soon as we can.
Implementation
PFile? loadIntoTempFile(dynamic file, {String? name, int? size}) {
assert(_tmpDir != null);
name ??= puid();
var tmpFile = name.contains("/") ? File(name) : _tmpDir!.file(name);
var ready = SafeCompleter();
if (!tmpFile.existsSync()) {
if (file == null) return null;
if (file is Uint8List || file is List<int>) {
var uints =
file is Uint8List ? file : Uint8List.fromList(file as List<int>);
/// Only write if it doesn't exists.
final buffer = uints.buffer;
tmpFile.writeAsBytesSync(
buffer.asUint8List(uints.offsetInBytes, uints.lengthInBytes),
flush: true);
ready.complete();
} else if (file is Stream) {
assert(
size != null, "If you provide a stream, you must provide a length");
assert(file is Stream<List<int>> || file is Stream<int>);
var _fileStream = file is Stream<List<int>>
? file
: (file as Stream<int>).chunked(PFile.defaultChunkSize);
_fileStream.toList().then((bytes) {
tmpFile.writeAsBytesSync(bytes.expand((_) => _).toList(), flush: true);
ready.complete();
});
} else {
return null;
}
} else {
ready.complete();
}
return NativePFile(tmpFile);
}