diff options
| author | Benoît du Garreau <bdgdlm@outlook.com> | 2024-03-13 15:09:39 +0100 |
|---|---|---|
| committer | Benoît du Garreau <bdgdlm@outlook.com> | 2024-04-12 09:43:39 +0200 |
| commit | b07c1f7f4d46f083725a03f85a3c6cd3447267ae (patch) | |
| tree | f17e2ec4615f2852c01f09a4468943b692260f12 /library/std/src | |
| parent | 6475796a813f2153d3bfc92c6089ed0f0c1c5b46 (diff) | |
| download | rust-b07c1f7f4d46f083725a03f85a3c6cd3447267ae.tar.gz rust-b07c1f7f4d46f083725a03f85a3c6cd3447267ae.zip | |
Improve several `Read` implementations
Diffstat (limited to 'library/std/src')
| -rw-r--r-- | library/std/src/io/cursor.rs | 21 | ||||
| -rw-r--r-- | library/std/src/io/impls.rs | 4 | ||||
| -rw-r--r-- | library/std/src/process.rs | 4 |
3 files changed, 28 insertions, 1 deletions
diff --git a/library/std/src/io/cursor.rs b/library/std/src/io/cursor.rs index 49dde828c1f..c4e97fc45ff 100644 --- a/library/std/src/io/cursor.rs +++ b/library/std/src/io/cursor.rs @@ -364,6 +364,27 @@ where self.pos += n as u64; Ok(()) } + + fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { + let content = self.remaining_slice(); + let len = content.len(); + buf.try_reserve(len)?; + buf.extend_from_slice(content); + self.pos += len as u64; + + Ok(len) + } + + fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { + let content = + crate::str::from_utf8(self.remaining_slice()).map_err(|_| io::Error::INVALID_UTF8)?; + let len = content.len(); + buf.try_reserve(len)?; + buf.push_str(content); + self.pos += len as u64; + + Ok(len) + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/io/impls.rs b/library/std/src/io/impls.rs index dd7e0725176..9f9ee4af5c8 100644 --- a/library/std/src/io/impls.rs +++ b/library/std/src/io/impls.rs @@ -329,8 +329,9 @@ impl Read for &[u8] { #[inline] fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?; - buf.push_str(content); let len = self.len(); + buf.try_reserve(len)?; + buf.push_str(content); *self = &self[len..]; Ok(len) } @@ -478,6 +479,7 @@ impl<A: Allocator> Read for VecDeque<u8, A> { let len = self.len(); let content = self.make_contiguous(); let string = str::from_utf8(content).map_err(|_| io::Error::INVALID_UTF8)?; + buf.try_reserve(len)?; buf.push_str(string); self.clear(); Ok(len) diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 69cc61b30ef..ab282135d1a 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -486,6 +486,10 @@ impl Read for ChildStderr { fn is_read_vectored(&self) -> bool { self.inner.is_read_vectored() } + + fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { + self.inner.read_to_end(buf) + } } impl AsInner<AnonPipe> for ChildStderr { |
