Skip to content

Instantly share code, notes, and snippets.

@hn3000
Last active March 13, 2021 12:54
Show Gist options
  • Save hn3000/100460d1e239f22bf3862f1a8f8cfd92 to your computer and use it in GitHub Desktop.
Save hn3000/100460d1e239f22bf3862f1a8f8cfd92 to your computer and use it in GitHub Desktop.
Bug or feature?
# async write! to file
Demonstrates unexpected behaviour in rust async_std -- writing two small strings with
separate write! invocations to the same file leads to an infinite loop writing out
broken fragments of the second string.
Running this will create two files:
- file1 contains `>aaaaaa<[bbbbbb]`
- file2 starts with `>aaaaaa<[bbbbbb` and grows as long as there's free space on your disk
make sure you have Ctrl-C ready before trying this.
We're not sure if this is a bug or if we're just holding it wrong.
[package]
name = "weird_async_write_behaviour"
version = "1.0.0"
authors = ["@hn3000", "@rkarp"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
async-std = "1.9.0"
use async_std::fs::OpenOptions;
use async_std::io;
use async_std::io::prelude::WriteExt;
fn main() -> std::io::Result<()> {
async_std::task::block_on(async_main())
}
async fn async_main() -> std::io::Result<()> {
maybe_write_entry("file1", ">aaaaaa<", "[bbbbbb]").await?; // works fine
maybe_write_entry("file2", ">aaaaaa<", "[bbbbbbb]").await?; // does not -- endless loop, fills file2 with fragments of the second write
Ok(())
}
async fn maybe_write_entry(filename: &str, a: &str, b: &str) -> io::Result<()> {
println!("About to write: ({} {})", a, b);
let mut file = OpenOptions::new()
.append(true)
// .write(true) // also happens with write, write+truncate
// .truncate(true)
.create(true)
.open(filename).await?;
write!(
&mut file,
"{}",
a,
).await?;
write!(
&mut file,
"{}",
b,
).await?;
println!("Done wrote: ({} {})", a, b);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment