perf(fs): improve `FileHandle.read` performance

pull/1950/head
amrbashir 9 months ago
parent 8c67d44aef
commit b0e8033364
No known key found for this signature in database
GPG Key ID: BBD7A47A2003FF33

@ -31,5 +31,6 @@
},
"engines": {
"pnpm": "^9.0.0"
}
},
"packageManager": "pnpm@9.12.1+sha512.e5a7e52a4183a02d5931057f7a0dbff9d5e9ce3161e33fa68ae392125b79282a8a8a470a51dfc8a0ed86221442eb2fb57019b0990ed24fab519bf0e1bc5ccfc4"
}

File diff suppressed because one or more lines are too long

@ -243,6 +243,25 @@ function parseFileInfo(r: UnparsedFileInfo): FileInfo {
}
}
// https://mstn.github.io/2018/06/08/fixed-size-arrays-in-typescript/
type FixedSizeArray<T, N extends number> = ReadonlyArray<T> & {
length: N
}
// https://gist.github.com/zapthedingbat/38ebfbedd98396624e5b5f2ff462611d
/** Converts a big-endian eight byte array to number */
function fromBytes(buffer: FixedSizeArray<number, 8>): number {
const bytes = new Uint8ClampedArray(buffer)
const size = bytes.byteLength
let x = 0
for (let i = 0; i < size; i++) {
const byte = bytes[i]
x *= 0x100
x += byte
}
return x
}
/**
* The Tauri abstraction for reading and writing files.
*
@ -285,12 +304,20 @@ class FileHandle extends Resource {
return 0
}
const [data, nread] = await invoke<[number[], number]>('plugin:fs|read', {
const data = await invoke<ArrayBuffer | number[]>('plugin:fs|read', {
rid: this.rid,
len: buffer.byteLength
})
buffer.set(data)
// Rust side will never return an empty array for this command and
// ensure there is at least 8 elements there.
//
// This is an optimization to include the number of read bytes (as bigendian bytes)
// at the end of returned array to avoid serialization overhead of separate values.
const nread = fromBytes(data.slice(-8) as FixedSizeArray<number, 8>)
const bytes = data instanceof ArrayBuffer ? new Uint8Array(data) : data
buffer.set(bytes.slice(0, bytes.length - 8))
return nread === 0 ? null : nread
}

@ -301,13 +301,20 @@ pub async fn read_dir<R: Runtime>(
pub async fn read<R: Runtime>(
webview: Webview<R>,
rid: ResourceId,
len: u32,
) -> CommandResult<(Vec<u8>, usize)> {
let mut data = vec![0; len as usize];
len: usize,
) -> CommandResult<tauri::ipc::Response> {
let mut data = vec![0; len];
let file = webview.resources_table().get::<StdFileResource>(rid)?;
let nread = StdFileResource::with_lock(&file, |mut file| file.read(&mut data))
.map_err(|e| format!("faied to read bytes from file with error: {e}"))?;
Ok((data, nread))
// This is an optimization to include the number of read bytes (as bigendian bytes)
// at the end of returned vector so we can use `tauri::ipc::Response`
// and avoid serialization overhead of separate values.
let nread = nread.to_be_bytes();
data.extend(nread);
Ok(tauri::ipc::Response::new(data))
}
#[tauri::command]

Loading…
Cancel
Save