Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Factor some common io::Error constants #123732

Merged
merged 1 commit into from
Apr 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions library/std/src/io/buffered/bufreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -383,12 +383,7 @@ impl<R: ?Sized + Read> Read for BufReader<R> {
// buffer.
let mut bytes = Vec::new();
self.read_to_end(&mut bytes)?;
let string = crate::str::from_utf8(&bytes).map_err(|_| {
io::const_io_error!(
io::ErrorKind::InvalidData,
"stream did not contain valid UTF-8",
)
})?;
let string = crate::str::from_utf8(&bytes).map_err(|_| io::Error::INVALID_UTF8)?;
*buf += string;
Ok(string.len())
}
Expand Down
24 changes: 24 additions & 0 deletions library/std/src/io/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,30 @@ impl fmt::Debug for Error {
}
}

/// Common errors constants for use in std
#[allow(dead_code)]
impl Error {
pub(crate) const INVALID_UTF8: Self =
const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8");

pub(crate) const READ_EXACT_EOF: Self =
const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer");

pub(crate) const UNKNOWN_THREAD_COUNT: Self = const_io_error!(
ErrorKind::NotFound,
"The number of hardware threads is not known for the target platform"
);

pub(crate) const UNSUPPORTED_PLATFORM: Self =
const_io_error!(ErrorKind::Unsupported, "operation not supported on this platform");

pub(crate) const WRITE_ALL_EOF: Self =
const_io_error!(ErrorKind::WriteZero, "failed to write whole buffer");

pub(crate) const ZERO_TIMEOUT: Self =
const_io_error!(ErrorKind::InvalidInput, "cannot set a 0 duration timeout");
}

#[stable(feature = "rust1", since = "1.0.0")]
impl From<alloc::ffi::NulError> for Error {
/// Converts a [`alloc::ffi::NulError`] into a [`Error`].
Expand Down
28 changes: 6 additions & 22 deletions library/std/src/io/impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ use crate::alloc::Allocator;
use crate::cmp;
use crate::collections::VecDeque;
use crate::fmt;
use crate::io::{
self, BorrowedCursor, BufRead, ErrorKind, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write,
};
use crate::io::{self, BorrowedCursor, BufRead, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
use crate::mem;
use crate::str;

Expand Down Expand Up @@ -289,10 +287,7 @@ impl Read for &[u8] {
#[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
if buf.len() > self.len() {
return Err(io::const_io_error!(
ErrorKind::UnexpectedEof,
"failed to fill whole buffer"
));
return Err(io::Error::READ_EXACT_EOF);
}
let (a, b) = self.split_at(buf.len());

Expand All @@ -312,10 +307,7 @@ impl Read for &[u8] {
#[inline]
fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_>) -> io::Result<()> {
if cursor.capacity() > self.len() {
return Err(io::const_io_error!(
ErrorKind::UnexpectedEof,
"failed to fill whole buffer"
));
return Err(io::Error::READ_EXACT_EOF);
}
let (a, b) = self.split_at(cursor.capacity());

Expand All @@ -336,9 +328,7 @@ 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::const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8")
})?;
let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?;
buf.push_str(content);
let len = self.len();
*self = &self[len..];
Expand Down Expand Up @@ -399,11 +389,7 @@ impl Write for &mut [u8] {

#[inline]
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
if self.write(data)? == data.len() {
Ok(())
} else {
Err(io::const_io_error!(ErrorKind::WriteZero, "failed to write whole buffer"))
}
if self.write(data)? == data.len() { Ok(()) } else { Err(io::Error::WRITE_ALL_EOF) }
}

#[inline]
Expand Down Expand Up @@ -491,9 +477,7 @@ impl<A: Allocator> Read for VecDeque<u8, A> {
// middle of an UTF-8 character.
let len = self.len();
let content = self.make_contiguous();
let string = str::from_utf8(content).map_err(|_| {
io::const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8")
})?;
let string = str::from_utf8(content).map_err(|_| io::Error::INVALID_UTF8)?;
buf.push_str(string);
self.clear();
Ok(len)
Expand Down
28 changes: 5 additions & 23 deletions library/std/src/io/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,12 +385,7 @@ where
let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() };
let ret = f(g.buf);
if str::from_utf8(&g.buf[g.len..]).is_err() {
ret.and_then(|_| {
Err(error::const_io_error!(
ErrorKind::InvalidData,
"stream did not contain valid UTF-8"
))
})
ret.and_then(|_| Err(Error::INVALID_UTF8))
} else {
g.len = g.buf.len();
ret
Expand Down Expand Up @@ -566,11 +561,7 @@ pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [
Err(e) => return Err(e),
}
}
if !buf.is_empty() {
Err(error::const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
} else {
Ok(())
}
if !buf.is_empty() { Err(Error::READ_EXACT_EOF) } else { Ok(()) }
}

pub(crate) fn default_read_buf<F>(read: F, mut cursor: BorrowedCursor<'_>) -> Result<()>
Expand All @@ -595,10 +586,7 @@ pub(crate) fn default_read_buf_exact<R: Read + ?Sized>(
}

if cursor.written() == prev_written {
return Err(error::const_io_error!(
ErrorKind::UnexpectedEof,
"failed to fill whole buffer"
));
return Err(Error::READ_EXACT_EOF);
}
}

Expand Down Expand Up @@ -1709,10 +1697,7 @@ pub trait Write {
while !buf.is_empty() {
match self.write(buf) {
Ok(0) => {
return Err(error::const_io_error!(
ErrorKind::WriteZero,
"failed to write whole buffer",
));
return Err(Error::WRITE_ALL_EOF);
}
Ok(n) => buf = &buf[n..],
Err(ref e) if e.is_interrupted() => {}
Expand Down Expand Up @@ -1777,10 +1762,7 @@ pub trait Write {
while !bufs.is_empty() {
match self.write_vectored(bufs) {
Ok(0) => {
return Err(error::const_io_error!(
ErrorKind::WriteZero,
"failed to write whole buffer",
));
return Err(Error::WRITE_ALL_EOF);
}
Ok(n) => IoSlice::advance_slices(&mut bufs, n),
Err(ref e) if e.is_interrupted() => {}
Expand Down
5 changes: 1 addition & 4 deletions library/std/src/os/fd/owned.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,7 @@ impl BorrowedFd<'_> {
#[cfg(any(target_arch = "wasm32", target_os = "hermit"))]
#[stable(feature = "io_safety", since = "1.63.0")]
pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
Err(crate::io::const_io_error!(
crate::io::ErrorKind::Unsupported,
"operation not supported on this platform",
))
Err(crate::io::Error::UNSUPPORTED_PLATFORM)
}
}

Expand Down
11 changes: 2 additions & 9 deletions library/std/src/os/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,11 +127,7 @@ pub trait FileExt {
Err(e) => return Err(e),
}
}
if !buf.is_empty() {
Err(io::const_io_error!(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer",))
} else {
Ok(())
}
if !buf.is_empty() { Err(io::Error::READ_EXACT_EOF) } else { Ok(()) }
}

/// Writes a number of bytes starting from a given offset.
Expand Down Expand Up @@ -249,10 +245,7 @@ pub trait FileExt {
while !buf.is_empty() {
match self.write_at(buf, offset) {
Ok(0) => {
return Err(io::const_io_error!(
io::ErrorKind::WriteZero,
"failed to write whole buffer",
));
return Err(io::Error::WRITE_ALL_EOF);
}
Ok(n) => {
buf = &buf[n..];
Expand Down
11 changes: 2 additions & 9 deletions library/std/src/os/wasi/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,7 @@ pub trait FileExt {
Err(e) => return Err(e),
}
}
if !buf.is_empty() {
Err(io::const_io_error!(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer"))
} else {
Ok(())
}
if !buf.is_empty() { Err(io::Error::READ_EXACT_EOF) } else { Ok(()) }
}

/// Writes a number of bytes starting from a given offset.
Expand Down Expand Up @@ -153,10 +149,7 @@ pub trait FileExt {
while !buf.is_empty() {
match self.write_at(buf, offset) {
Ok(0) => {
return Err(io::const_io_error!(
io::ErrorKind::WriteZero,
"failed to write whole buffer",
));
return Err(io::Error::WRITE_ALL_EOF);
}
Ok(n) => {
buf = &buf[n..];
Expand Down
10 changes: 2 additions & 8 deletions library/std/src/sys/pal/hermit/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,7 @@ impl Socket {
let mut pollfd = netc::pollfd { fd: self.as_raw_fd(), events: netc::POLLOUT, revents: 0 };

if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}

let start = Instant::now();
Expand Down Expand Up @@ -245,10 +242,7 @@ impl Socket {
let timeout = match dur {
Some(dur) => {
if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}

let secs = if dur.as_secs() > netc::time_t::MAX as u64 {
Expand Down
15 changes: 3 additions & 12 deletions library/std/src/sys/pal/sgx/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,15 @@ impl TcpStream {

pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream> {
if dur == Duration::default() {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}
Self::connect(Ok(addr)) // FIXME: ignoring timeout
}

pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
match dur {
Some(dur) if dur == Duration::default() => {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}
_ => sgx_ineffective(()),
}
Expand All @@ -120,10 +114,7 @@ impl TcpStream {
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
match dur {
Some(dur) if dur == Duration::default() => {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}
_ => sgx_ineffective(()),
}
Expand Down
5 changes: 1 addition & 4 deletions library/std/src/sys/pal/solid/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ pub fn unsupported<T>() -> crate::io::Result<T> {
}

pub fn unsupported_err() -> crate::io::Error {
crate::io::const_io_error!(
crate::io::ErrorKind::Unsupported,
"operation not supported on this platform",
)
crate::io::Error::UNSUPPORTED_PLATFORM
}

#[inline]
Expand Down
10 changes: 2 additions & 8 deletions library/std/src/sys/pal/solid/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,10 +154,7 @@ impl Socket {
}

if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}

let mut timeout =
Expand Down Expand Up @@ -306,10 +303,7 @@ impl Socket {
let timeout = match dur {
Some(dur) => {
if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}

let secs = if dur.as_secs() > netc::c_long::MAX as u64 {
Expand Down
5 changes: 1 addition & 4 deletions library/std/src/sys/pal/teeos/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,7 @@ impl Drop for Thread {
// Note: Both `sched_getaffinity` and `sysconf` are available but not functional on
// teeos, so this function always returns an Error!
pub fn available_parallelism() -> io::Result<NonZero<usize>> {
Err(io::Error::new(
io::ErrorKind::NotFound,
"The number of hardware threads is not known for the target platform",
))
Err(io::Error::UNKNOWN_THREAD_COUNT)
}

fn min_stack_size(_: *const libc::pthread_attr_t) -> usize {
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sys/pal/unix/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,6 @@ mod unsupported {
}

pub fn unsupported_err() -> io::Error {
io::const_io_error!(io::ErrorKind::Unsupported, "operation not supported on this platform",)
io::Error::UNSUPPORTED_PLATFORM
}
}
10 changes: 2 additions & 8 deletions library/std/src/sys/pal/unix/net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,10 +175,7 @@ impl Socket {
let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 };

if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}

let start = Instant::now();
Expand Down Expand Up @@ -360,10 +357,7 @@ impl Socket {
let timeout = match dur {
Some(dur) => {
if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
return Err(io::Error::ZERO_TIMEOUT);
}

let secs = if dur.as_secs() > libc::time_t::MAX as u64 {
Expand Down
Loading
Loading