use opfs::persistent::{DirectoryHandle, app_specific_dir};
use opfs::{
CreateWritableOptions, GetFileHandleOptions,
WriteParams, WriteCommandType,
DirectoryHandle as _, FileHandle as _, WritableFileStream as _
};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir: DirectoryHandle = app_specific_dir().await?;
let options = GetFileHandleOptions { create: true };
let mut file = dir.get_file_handle_with_options("example.txt", &options).await?;
let write_options = CreateWritableOptions { keep_existing_data: false };
let mut writer = file.create_writable_with_options(&write_options).await?;
writer.write_at_cursor_pos(b"Hello, World! This is a test file.".to_vec()).await?;
writer.close().await?;
println!("Full file content: {:?}", String::from_utf8(file.read().await?)?);
println!("First 5 bytes: {:?}", String::from_utf8(file.read_range(0..5).await?)?);
println!("From byte 7 to end: {:?}", String::from_utf8(file.read_range(7..).await?)?);
println!("Bytes 7-12 inclusive: {:?}", String::from_utf8(file.read_range(7..=12).await?)?);
println!("Everything: {:?}", String::from_utf8(file.read_range(..).await?)?);
let mut writer = file.create_writable_with_options(&CreateWritableOptions {
keep_existing_data: true
}).await?;
let params = WriteParams {
command_type: WriteCommandType::Write,
data: Some(b"RUST".to_vec()),
position: Some(7),
size: None,
};
writer.write_with_params(¶ms).await?;
let params = WriteParams {
command_type: WriteCommandType::Truncate,
data: None,
position: None,
size: Some(20),
};
writer.write_with_params(¶ms).await?;
let params = WriteParams {
command_type: WriteCommandType::Seek,
data: None,
position: Some(15),
size: None,
};
writer.write_with_params(¶ms).await?;
writer.write_at_cursor_pos(b"!!!".to_vec()).await?;
writer.close().await?;
println!("Final file content: {:?}", String::from_utf8(file.read().await?)?);
println!("File size: {} bytes", file.size().await?);
Ok(())
}