Repository navigation
Tracking issue for Write::write_all_vectoredΒ #70436
Copy link
Copy link
Open
Labels
A-ioArea: `std::io`, `std::fs`, `std::net` and `std::path`Area: `std::io`, `std::fs`, `std::net` and `std::path`B-unstableBlocker: Implemented in the nightly compiler and unstable.Blocker: Implemented in the nightly compiler and unstable.C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFCI-libs-radarLibs issues that are tracked on the team's radar.Libs issues that are tracked on the team's radar.T-libsRelevant to the library team, which will review and decide on the PR/issue.Relevant to the library team, which will review and decide on the PR/issue.
Description
This is a tracking issue for io::Write::write_all_vectored.
Feature gate: #![feature(write_all_vectored)].
Steps:
- Implement the RFC (Add io::Write::write_all_vectoredΒ #70612).
- Stabilization PR.
Unresolved questions:
- Can we improve the API? Currently the method takes the
IoSlices as mutable slice and modifies them. This is a pretty unusual and potentially error-prone API. We could either find a way to not mutate the argument or to enforce (via the type system) the argument can't be used by the user afterwards. Or we can decide that such an unusual API is fine for this rather low level method.
Original issue:
Details
In the io::Write trait we've got the helpful write_all method, which calls write in a loop to write all bytes. However there is no such function for write_vectored. I would suggest adding a function called write_all_vectored to performance such a task.
A possible implementation. Note that bufs is a mutable slice, also see the discussion in https://github.com/rust-lang/futures-rs/pull/1741/files. On the playground: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=872e9d973bd8101e7724292f87a82869.
pub trait Write {
// ...
fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> io::Result<()> {
while !bufs.is_empty() {
match self.write_vectored(bufs) {
Ok(0) => {
return Err(Error::new(
ErrorKind::WriteZero,
"failed to write whole buffer",
));
}
Ok(n) => bufs = IoSlice::advance(mem::replace(&mut bufs, &mut []), n),
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(())
}
}Related: rust-lang/futures-rs#1741
/cc @cramertj
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
A-ioArea: `std::io`, `std::fs`, `std::net` and `std::path`Area: `std::io`, `std::fs`, `std::net` and `std::path`B-unstableBlocker: Implemented in the nightly compiler and unstable.Blocker: Implemented in the nightly compiler and unstable.C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFCI-libs-radarLibs issues that are tracked on the team's radar.Libs issues that are tracked on the team's radar.T-libsRelevant to the library team, which will review and decide on the PR/issue.Relevant to the library team, which will review and decide on the PR/issue.
Activity
cramertj commentedon Mar 26, 2020
cc @sfackler, @withoutboats
sfackler commentedon Mar 26, 2020
The main API question I have (which is more about IoSlice::advance than this I guess) is if we're okay saying that the content of the
bufsslice is unspecified after this call returns. It's probably fine, but just one "weird" affect that you may not naively expect.Thomasdezeeuw commentedon Mar 27, 2020
@sfackler I agree, but I don't know how an alternative that takes
&[IoSlice<'_>], like you would expect, would work.sfackler commentedon Mar 27, 2020
It could for example perform vectored writes when the current cursor position is at a slice boundry and switch to a normal write_all if it's in the middle of one of the slices.
Thomasdezeeuw commentedon Mar 27, 2020
But then you're missing out on the efficiency of vectored writes, if that were the case I wouldn't consider using it.
sfackler commentedon Mar 27, 2020
You are only missing out on the efficienty of vectored writes some of the time.
Thomasdezeeuw commentedon Mar 27, 2020
True, but with the implementation I provided (which I still admit isn't great) you don't miss out. I've made the point already in rust-lang/futures-rs#1741 (comment), but personally I don't its really a big deal that the provided slice is modified. In most cases I imagine the
bufsslice being build just before this call and only used in this call.cramertj commentedon Mar 27, 2020
One possibility would be to keep a fixed-size buffer of, say,
[IoSlice<'_>; 128]and copy sections of the caller's slice into that, pairing it with an index for the last-most unwrittenIoSlice. It's more complicated in that you have to re-load thatIoSliceat some clever point in order to both minimize shifting but also maximize the number ofIoSlices being offered to the underlying reader, but it prevents mutation of the original caller's slice while also allowing some fixed amount of vectored writes.I'm not necessarily advocating for this idea, as I think it might be fine to mutate the caller's slice (they can always make a clone if they don't want to deal with that), but it's an option.
Rollup merge of rust-lang#70612 - Thomasdezeeuw:issue_70436, r=LukasKβ¦
Rollup merge of rust-lang#70612 - Thomasdezeeuw:issue_70436, r=LukasKβ¦
Rollup merge of rust-lang#70612 - Thomasdezeeuw:issue_70436, r=LukasKβ¦
Rollup merge of rust-lang#70612 - Thomasdezeeuw:issue_70436, r=LukasKβ¦
[-]Add io::Write::write_all_vectored[/-][+]Tracking issue for write_all_vectored[/+]29 remaining items
Thomasdezeeuw commentedon May 13, 2022
How about an owned type that wraps
T: AsRef<[IoSlice<'_>]>(orDeref) to indicate that the write call "owns" the buffers and can modify them, but allow the buffers wrapper type to be reused (i.e. theVecinVec<IoSlice<'_>>). It makes the API a bit more conflicted, but perhaps that will resolve @joshtriplett concerns.joshtriplett commentedon May 17, 2022
@Thomasdezeeuw wrote:
That doesn't address this concern I wrote above:
What if we used a
Cow'd slice? If you never want your slice copied even in the partial write case, pass in a Cow::Owned, and give up your own ownership; if you don't want to give up ownership of your slice and allow mutating it, pass in a Cow::Borrowed.Also, we could avoid an extra syscall even in the borrowed case, if we're willing to allocate in that case, and Cow will take care of that for us.
Thomasdezeeuw commentedon May 17, 2022
@joshtriplett I'm sorry, but I don't really have the energy for this issue any more... You're comment completely misses the point of vectored I/O. If people are looking at using vectored I/O it's likely they're looking at it for performance reasons, suggesting to just allocate a new buffer so it can be used once in a system call is really quite far off this target.
It's been more than two years, the API works and has zero overhead as-is, but yes it has a gotcha. At this point either stabilise it or remove it, I'm no longer interested, this has just taken too long.
joshtriplett commentedon May 18, 2022
So, I do care very much about vectored I/O as well, and I care about the use case of being able to reuse the iovecs repeatedly, which is also something people do in C for reasons of both performance and simplicity. I'd like to be able to do that somehow in Rust, and not have to throw away and recreate the array of iovecs every time. I'm trying to brainstorm some data structure that will allow for that reuse. I was trying to favor using existing constructs and types (at the expense of incurring overhead in what I saw as the less common case of partial write), but I acknowledge that that's not ideal. I agree that Cow wasn't a great idea.
As an alternative closer to what you already proposed, perhaps it makes more sense to make a new
IoSlicesstructure that owns the iovecs as you suggested, but whose API guarantees that when the write method is done those iovecs are un-mutated? I would be happy to do that design work.Rough sketch of a solution that shouldn't need to make any copies at all:
If you have an
&IoSlices(whichwrite_all_vectoredwould get) you can callborrow_for_writewhich will mutate the slices using interior mutability, give you those slices so you canwritevthem or equivalent, and then modify them back (which hopefully we can optimize away if the IoSlices is going away). If you have a&mut IoSlicesor anIoSlices, we can provide ways to get a&mut [IoSlice], butwrite_all_vectoredwould take an&IoSlicesso it can't arbitrarily mutate the slices. (We can provide analogous types corresponding to IoSliceMut, and additionally a method that transmutes to give an&IoSlicesso that you can use the same buffer for both read and write, and also modify through it when not currently reading or writing.)That should avoid any copying, avoid any more syscalls than absolutely necessary, and overall make this exactly as efficient and capable as
writev/readvcan allow.Does something like that sound reasonable?
Lucretiel commentedon Aug 19, 2022
I wrote up a quick implementation of something similar to the proposed design. It's a pretty straightforward elaboration of
advance_slicesthat takes care to preserve the original version of the currentIoSliceand restores it each time the&[IoSlice]is advanced one step. Because only 1 buffer is ever in a mutated state at a time, it's easy to keep a copy of the original version and restore it when we're done with it. It also restores on drop to help keepio::Errorreturns clean.Then,
write_all_vectoredis basically the same as it is now, but usingBufferManagerto handle slice advancingThe only downside here is that it does require the user to provide an
&mut [IoSlice], but we can still promise at the API level (though not the type level) that the slices will be unmodified when this function returns.dead-claudia commentedon Dec 19, 2022
Can an extra method, or even option or something, be added to allow retrying the operation with data that wasn't successfully written? I'd like to tolerate some inner write errors like
EAGAIN/ErrorKind::WouldBlockwithout having to reimplementwrite_all_vectoredmanually.Thomasdezeeuw commentedon Dec 19, 2022
We don't do this for the
write_allfunction, so I don't thinkwrite_all_vectoredshould do anything different.tbottomparallel commentedon Jan 19, 2024
Would you consider an alternate signature that returns the total number of bytes written?
I am aware that it is not consistent with the signature of
write_all, but callers can implement the behavior trivially there:Unless I am missing something crucial, callers of
write_all_vectoredcannot ergonomically or efficiently do the same. To implement the behavior they would need to iterate overbufsand call.len()on eachIoSliceto sum up the total length. That's at least one extraneous pointer dereference per buffer.In contrast,
write_all_vectoredcan accumulate the total much more efficiently. The necessary information is already being returned by the underlying calls towritevand/orwrite. I would expect most of the time this will compile down to be one extraADD <reg>,<reg>instruction per underlying write call.In my experience (mostly embedded Linux) the returned count of bytes written is occasionally useful at runtime and extremely useful in unit tests. Since users cannot implement this efficiently without re-implementing
write_all_vectored, and the underlying write calls are already returning the information, it seems reasonable to havewrite_all_vectoredpass it along instead of discarding.Example:
vs
dead-claudia commentedon Jan 20, 2024
This can trivially be done via
bufs.iter().map(|s| s.len()).sum(). If yourbufshere is the top-level array itself and there's only a few entries, the compiler will likely even be able to avoid the loop.pliardb commentedon May 7, 2024
We got bitten in our codebase by a bug caused by us handling
ErrorKind::WouldBlockby retrying thewrite_all_vectored()call with the samebufsinput, despite the documentation advising against it to be fair.Still it seems that this scenario could either be 1) more explicitly disallowed through type-checking by e.g. making
bufsimmutable or 2) supported by makingbufsmutable "all the way" by making its type matchIoSlice::advance_slices()'sbufsargument (&mut &mut [IoSlice]). We went with 2) in our codebase.oxalica commentedon May 22, 2025
IoSlice::advance_slicesis stabilized since 1.81. It should be relatively easy to manually implementwrite_all_vectorednow, with special handling of EAGAIN (and EINTR).I think it's fair to keep the current signature
&mut [IoSlice]just to stay consistent withwrite_all(#70436 (comment)): both methods are shortcut methods to fully write all data at once, and treating any partial write as a non-recoverable failure (unknown length of data is sent to the underlying stream). I don't think returningusizeor taking&mut &mut [IoSlice]is useful at all for the common cases.Is it time to stabilize this?
PureWhiteWu commentedon Jun 30, 2025
Hi, is there any progress on this?
golddranks commentedon Apr 6, 2026
I think this is a weakness in
write_allthat prevents many use cases (or alternatively, in case of being used in ignorance, produces buggy networking code). I'm trying to get this misfeature ofwrite_allat least getting properly documented, since fixing it seems night impossible because of backwards compatibility.However, we shouldn't repeat mistakes just for the sake of consistency.