4 ms·
The `write` function here comes from the `Write` trait[0]. This isn't the unbuffered write API, it's just the write API. What it's writing to could be a `File`,
by Measter 5y ago
The `write` function here comes from the `Write` trait[0]. This isn't the unbuffered write API, it's just the write API. What it's writing to could be a `File`, or it could be `StdOut` or a `Vec<u8>`.
It also doesn't take a string; it takes a slice of bytes. In Rust, prefixing a string literal makes it a `&[u8]` instead of a `&str`, which is why you can just pass it straight into `write`.
Adding a length field would only make it more error-prone to use without any added benefit. Slices already know their length, and subslicing is trivial. If you have a larger slice, and you only want to write a subsection of it, you just index it. Forcing the user to pass in two lengths is just silly, and all the API implementations would do is subslice the input to that second length anyway.
You could argue that `File::open` and `File::create` should return a `BufReader<File>` and `BufWriter<File>` respectively, and I would agree that this would be reasonable as the most common use-case probably benefits from buffered IO. However, that ship's already sailed, and those functions can't be changed.
The description for the `File` type should also more explicitly state that IO is unbuffered. I'm surprised it doesn't, the docs are typically better at that sort of thing.
[0] https://doc.rust-lang.org/std/io/trait.Write.html https://doc.rust-lang.org/std/io/trait.Write.html
- BoorishBears 5y agoIt was never lost on me that the length is encoded, my very first comment mentions it's the same in Java: the number of bytes you pass in is encoded. My point isn't that every language should force that syntax ('offset' for example, doesn't make sense in languages with pointer math for example) Rather the point is that when the language doesn't follow that convention, it should buffer by default. I guess it is a blind spot in the standard library then