Rollup merge of #136844 - thaliaarchi:const-io-error, r=ChrisDenton

Use `const_error!` when possible

Replace usages of `io::Error::new(io::ErrorKind::Variant, "constant string")` with `io::const_error!(io::ErrorKind::Variant, "constant string")` to avoid allocations when possible. Additionally, fix `&&str` error messages in SGX and missing/misplaced trailing commas in `const_error!`.
This commit is contained in:
Matthias Krüger 2025-02-17 06:37:37 +01:00 committed by GitHub
commit c04801dbb9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 90 additions and 106 deletions

View file

@ -83,7 +83,7 @@ impl Error {
pub(crate) const UNKNOWN_THREAD_COUNT: Self = const_error!( pub(crate) const UNKNOWN_THREAD_COUNT: Self = const_error!(
ErrorKind::NotFound, ErrorKind::NotFound,
"The number of hardware threads is not known for the target platform" "The number of hardware threads is not known for the target platform",
); );
pub(crate) const UNSUPPORTED_PLATFORM: Self = pub(crate) const UNSUPPORTED_PLATFORM: Self =

View file

@ -3575,7 +3575,7 @@ impl Error for StripPrefixError {
pub fn absolute<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> { pub fn absolute<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
let path = path.as_ref(); let path = path.as_ref();
if path.as_os_str().is_empty() { if path.as_os_str().is_empty() {
Err(io::const_error!(io::ErrorKind::InvalidInput, "cannot make an empty path absolute",)) Err(io::const_error!(io::ErrorKind::InvalidInput, "cannot make an empty path absolute"))
} else { } else {
sys::path::absolute(path) sys::path::absolute(path)
} }

View file

@ -123,6 +123,6 @@ impl TryFrom<(&str, u16)> for LookupHost {
type Error = io::Error; type Error = io::Error;
fn try_from(v: (&str, u16)) -> io::Result<LookupHost> { fn try_from(v: (&str, u16)) -> io::Result<LookupHost> {
lookup(v.0, v.1).map_err(|_e| io::const_error!(io::ErrorKind::InvalidInput, &"DNS failure")) lookup(v.0, v.1).map_err(|_e| io::const_error!(io::ErrorKind::InvalidInput, "DNS failure"))
} }
} }

View file

@ -11,7 +11,7 @@ macro_rules! unimpl {
() => { () => {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::Unsupported, io::ErrorKind::Unsupported,
&"This function is not yet implemented", "This function is not yet implemented",
)); ));
}; };
} }
@ -71,7 +71,7 @@ impl TcpListener {
0, 0,
4096, 4096,
) else { ) else {
return Err(io::const_error!(io::ErrorKind::InvalidInput, &"Invalid response")); return Err(io::const_error!(io::ErrorKind::InvalidInput, "Invalid response"));
}; };
// The first four bytes should be zero upon success, and will be nonzero // The first four bytes should be zero upon success, and will be nonzero
@ -80,15 +80,15 @@ impl TcpListener {
if response[0] != 0 || valid == 0 { if response[0] != 0 || valid == 0 {
let errcode = response[1]; let errcode = response[1];
if errcode == NetError::SocketInUse as u8 { if errcode == NetError::SocketInUse as u8 {
return Err(io::const_error!(io::ErrorKind::ResourceBusy, &"Socket in use")); return Err(io::const_error!(io::ErrorKind::ResourceBusy, "Socket in use"));
} else if errcode == NetError::Invalid as u8 { } else if errcode == NetError::Invalid as u8 {
return Err(io::const_error!(io::ErrorKind::AddrNotAvailable, &"Invalid address")); return Err(io::const_error!(io::ErrorKind::AddrNotAvailable, "Invalid address"));
} else if errcode == NetError::LibraryError as u8 { } else if errcode == NetError::LibraryError as u8 {
return Err(io::const_error!(io::ErrorKind::Other, &"Library error")); return Err(io::const_error!(io::ErrorKind::Other, "Library error"));
} else { } else {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::Other, io::ErrorKind::Other,
&"Unable to connect or internal error" "Unable to connect or internal error",
)); ));
} }
} }
@ -127,15 +127,13 @@ impl TcpListener {
if receive_request.raw[0] != 0 { if receive_request.raw[0] != 0 {
// error case // error case
if receive_request.raw[1] == NetError::TimedOut as u8 { if receive_request.raw[1] == NetError::TimedOut as u8 {
return Err(io::const_error!(io::ErrorKind::TimedOut, &"accept timed out",)); return Err(io::const_error!(io::ErrorKind::TimedOut, "accept timed out"));
} else if receive_request.raw[1] == NetError::WouldBlock as u8 { } else if receive_request.raw[1] == NetError::WouldBlock as u8 {
return Err( return Err(io::const_error!(io::ErrorKind::WouldBlock, "accept would block"));
io::const_error!(io::ErrorKind::WouldBlock, &"accept would block",),
);
} else if receive_request.raw[1] == NetError::LibraryError as u8 { } else if receive_request.raw[1] == NetError::LibraryError as u8 {
return Err(io::const_error!(io::ErrorKind::Other, &"Library error")); return Err(io::const_error!(io::ErrorKind::Other, "Library error"));
} else { } else {
return Err(io::const_error!(io::ErrorKind::Other, &"library error",)); return Err(io::const_error!(io::ErrorKind::Other, "library error"));
} }
} else { } else {
// accept successful // accept successful
@ -159,7 +157,7 @@ impl TcpListener {
port, port,
) )
} else { } else {
return Err(io::const_error!(io::ErrorKind::Other, &"library error",)); return Err(io::const_error!(io::ErrorKind::Other, "library error"));
}; };
// replenish the listener // replenish the listener
@ -171,7 +169,7 @@ impl TcpListener {
Ok((TcpStream::from_listener(stream_fd, self.local.port(), port, addr), addr)) Ok((TcpStream::from_listener(stream_fd, self.local.port(), port, addr), addr))
} }
} else { } else {
Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unable to accept")) Err(io::const_error!(io::ErrorKind::InvalidInput, "Unable to accept"))
} }
} }
@ -182,13 +180,13 @@ impl TcpListener {
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
if ttl > 255 { if ttl > 255 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "TTL must be less than 256")); return Err(io::const_error!(io::ErrorKind::InvalidInput, "TTL must be less than 256"));
} }
crate::os::xous::ffi::blocking_scalar( crate::os::xous::ffi::blocking_scalar(
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdSetTtlTcp(self.fd.load(Ordering::Relaxed), ttl).into(), services::NetBlockingScalar::StdSetTtlTcp(self.fd.load(Ordering::Relaxed), ttl).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|_| ()) .map(|_| ())
} }
@ -197,7 +195,7 @@ impl TcpListener {
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdGetTtlTcp(self.fd.load(Ordering::Relaxed)).into(), services::NetBlockingScalar::StdGetTtlTcp(self.fd.load(Ordering::Relaxed)).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|res| res[0] as _)?) .map(|res| res[0] as _)?)
} }

View file

@ -12,7 +12,7 @@ macro_rules! unimpl {
() => { () => {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::Unsupported, io::ErrorKind::Unsupported,
&"This function is not yet implemented", "This function is not yet implemented",
)); ));
}; };
} }
@ -96,7 +96,7 @@ impl TcpStream {
0, 0,
4096, 4096,
) else { ) else {
return Err(io::const_error!(io::ErrorKind::InvalidInput, &"Invalid response")); return Err(io::const_error!(io::ErrorKind::InvalidInput, "Invalid response"));
}; };
// The first four bytes should be zero upon success, and will be nonzero // The first four bytes should be zero upon success, and will be nonzero
@ -106,13 +106,13 @@ impl TcpStream {
// errcode is a u8 but stuck in a u16 where the upper byte is invalid. Mask & decode accordingly. // errcode is a u8 but stuck in a u16 where the upper byte is invalid. Mask & decode accordingly.
let errcode = response[0]; let errcode = response[0];
if errcode == NetError::SocketInUse as u8 { if errcode == NetError::SocketInUse as u8 {
return Err(io::const_error!(io::ErrorKind::ResourceBusy, &"Socket in use",)); return Err(io::const_error!(io::ErrorKind::ResourceBusy, "Socket in use"));
} else if errcode == NetError::Unaddressable as u8 { } else if errcode == NetError::Unaddressable as u8 {
return Err(io::const_error!(io::ErrorKind::AddrNotAvailable, &"Invalid address",)); return Err(io::const_error!(io::ErrorKind::AddrNotAvailable, "Invalid address"));
} else { } else {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
&"Unable to connect or internal error", "Unable to connect or internal error",
)); ));
} }
} }
@ -198,7 +198,7 @@ impl TcpStream {
) else { ) else {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
&"Library failure: wrong message type or messaging error" "Library failure: wrong message type or messaging error",
)); ));
}; };
@ -212,14 +212,14 @@ impl TcpStream {
if result[0] != 0 { if result[0] != 0 {
if result[1] == 8 { if result[1] == 8 {
// timed out // timed out
return Err(io::const_error!(io::ErrorKind::TimedOut, &"Timeout",)); return Err(io::const_error!(io::ErrorKind::TimedOut, "Timeout"));
} }
if result[1] == 9 { if result[1] == 9 {
// would block // would block
return Err(io::const_error!(io::ErrorKind::WouldBlock, &"Would block",)); return Err(io::const_error!(io::ErrorKind::WouldBlock, "Would block"));
} }
} }
Err(io::const_error!(io::ErrorKind::Other, &"recv_slice failure")) Err(io::const_error!(io::ErrorKind::Other, "recv_slice failure"))
} }
} }
@ -258,20 +258,20 @@ impl TcpStream {
self.write_timeout.load(Ordering::Relaxed) as usize, self.write_timeout.load(Ordering::Relaxed) as usize,
buf_len, buf_len,
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Internal error")))?; .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Internal error")))?;
if send_request.raw[0] != 0 { if send_request.raw[0] != 0 {
if send_request.raw[4] == 8 { if send_request.raw[4] == 8 {
// timed out // timed out
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::BrokenPipe, io::ErrorKind::BrokenPipe,
&"Timeout or connection closed", "Timeout or connection closed",
)); ));
} else if send_request.raw[4] == 9 { } else if send_request.raw[4] == 9 {
// would block // would block
return Err(io::const_error!(io::ErrorKind::WouldBlock, &"Would block",)); return Err(io::const_error!(io::ErrorKind::WouldBlock, "Would block"));
} else { } else {
return Err(io::const_error!(io::ErrorKind::InvalidInput, &"Error when sending",)); return Err(io::const_error!(io::ErrorKind::InvalidInput, "Error when sending"));
} }
} }
Ok(u32::from_le_bytes([ Ok(u32::from_le_bytes([
@ -304,7 +304,7 @@ impl TcpStream {
0, 0,
0, 0,
) else { ) else {
return Err(io::const_error!(io::ErrorKind::InvalidInput, &"Internal error")); return Err(io::const_error!(io::ErrorKind::InvalidInput, "Internal error"));
}; };
let mut i = get_addr.raw.iter(); let mut i = get_addr.raw.iter();
match *i.next().unwrap() { match *i.next().unwrap() {
@ -324,7 +324,7 @@ impl TcpStream {
} }
Ok(SocketAddr::V6(SocketAddrV6::new(new_addr.into(), self.local_port, 0, 0))) Ok(SocketAddr::V6(SocketAddrV6::new(new_addr.into(), self.local_port, 0, 0)))
} }
_ => Err(io::const_error!(io::ErrorKind::InvalidInput, &"Internal error")), _ => Err(io::const_error!(io::ErrorKind::InvalidInput, "Internal error")),
} }
} }
@ -333,7 +333,7 @@ impl TcpStream {
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdTcpStreamShutdown(self.fd, how).into(), services::NetBlockingScalar::StdTcpStreamShutdown(self.fd, how).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|_| ()) .map(|_| ())
} }
@ -355,7 +355,7 @@ impl TcpStream {
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdSetNodelay(self.fd, enabled).into(), services::NetBlockingScalar::StdSetNodelay(self.fd, enabled).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|_| ()) .map(|_| ())
} }
@ -364,19 +364,19 @@ impl TcpStream {
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdGetNodelay(self.fd).into(), services::NetBlockingScalar::StdGetNodelay(self.fd).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|res| res[0] != 0)?) .map(|res| res[0] != 0)?)
} }
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
if ttl > 255 { if ttl > 255 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "TTL must be less than 256")); return Err(io::const_error!(io::ErrorKind::InvalidInput, "TTL must be less than 256"));
} }
crate::os::xous::ffi::blocking_scalar( crate::os::xous::ffi::blocking_scalar(
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdSetTtlTcp(self.fd, ttl).into(), services::NetBlockingScalar::StdSetTtlTcp(self.fd, ttl).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|_| ()) .map(|_| ())
} }
@ -385,7 +385,7 @@ impl TcpStream {
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdGetTtlTcp(self.fd).into(), services::NetBlockingScalar::StdGetTtlTcp(self.fd).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|res| res[0] as _)?) .map(|res| res[0] as _)?)
} }

View file

@ -13,7 +13,7 @@ macro_rules! unimpl {
() => { () => {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::Unsupported, io::ErrorKind::Unsupported,
&"This function is not yet implemented", "This function is not yet implemented",
)); ));
}; };
} }
@ -72,18 +72,18 @@ impl UdpSocket {
if response[0] != 0 || valid == 0 { if response[0] != 0 || valid == 0 {
let errcode = response[1]; let errcode = response[1];
if errcode == NetError::SocketInUse as u8 { if errcode == NetError::SocketInUse as u8 {
return Err(io::const_error!(io::ErrorKind::ResourceBusy, &"Socket in use")); return Err(io::const_error!(io::ErrorKind::ResourceBusy, "Socket in use"));
} else if errcode == NetError::Invalid as u8 { } else if errcode == NetError::Invalid as u8 {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
&"Port can't be 0 or invalid address" "Port can't be 0 or invalid address",
)); ));
} else if errcode == NetError::LibraryError as u8 { } else if errcode == NetError::LibraryError as u8 {
return Err(io::const_error!(io::ErrorKind::Other, &"Library error")); return Err(io::const_error!(io::ErrorKind::Other, "Library error"));
} else { } else {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::Other, io::ErrorKind::Other,
&"Unable to connect or internal error" "Unable to connect or internal error",
)); ));
} }
} }
@ -98,13 +98,13 @@ impl UdpSocket {
nonblocking: Cell::new(false), nonblocking: Cell::new(false),
}); });
} }
Err(io::const_error!(io::ErrorKind::InvalidInput, &"Invalid response")) Err(io::const_error!(io::ErrorKind::InvalidInput, "Invalid response"))
} }
pub fn peer_addr(&self) -> io::Result<SocketAddr> { pub fn peer_addr(&self) -> io::Result<SocketAddr> {
match self.remote.get() { match self.remote.get() {
Some(dest) => Ok(dest), Some(dest) => Ok(dest),
None => Err(io::const_error!(io::ErrorKind::NotConnected, &"No peer specified")), None => Err(io::const_error!(io::ErrorKind::NotConnected, "No peer specified")),
} }
} }
@ -141,13 +141,13 @@ impl UdpSocket {
if receive_request.raw[0] != 0 { if receive_request.raw[0] != 0 {
// error case // error case
if receive_request.raw[1] == NetError::TimedOut as u8 { if receive_request.raw[1] == NetError::TimedOut as u8 {
return Err(io::const_error!(io::ErrorKind::TimedOut, &"recv timed out",)); return Err(io::const_error!(io::ErrorKind::TimedOut, "recv timed out"));
} else if receive_request.raw[1] == NetError::WouldBlock as u8 { } else if receive_request.raw[1] == NetError::WouldBlock as u8 {
return Err(io::const_error!(io::ErrorKind::WouldBlock, &"recv would block",)); return Err(io::const_error!(io::ErrorKind::WouldBlock, "recv would block"));
} else if receive_request.raw[1] == NetError::LibraryError as u8 { } else if receive_request.raw[1] == NetError::LibraryError as u8 {
return Err(io::const_error!(io::ErrorKind::Other, &"Library error")); return Err(io::const_error!(io::ErrorKind::Other, "Library error"));
} else { } else {
return Err(io::const_error!(io::ErrorKind::Other, &"library error",)); return Err(io::const_error!(io::ErrorKind::Other, "library error"));
} }
} else { } else {
let rr = &receive_request.raw; let rr = &receive_request.raw;
@ -170,7 +170,7 @@ impl UdpSocket {
port, port,
) )
} else { } else {
return Err(io::const_error!(io::ErrorKind::Other, &"library error",)); return Err(io::const_error!(io::ErrorKind::Other, "library error"));
}; };
for (&s, d) in rr[22..22 + rxlen as usize].iter().zip(buf.iter_mut()) { for (&s, d) in rr[22..22 + rxlen as usize].iter().zip(buf.iter_mut()) {
*d = s; *d = s;
@ -178,7 +178,7 @@ impl UdpSocket {
Ok((rxlen as usize, addr)) Ok((rxlen as usize, addr))
} }
} else { } else {
Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unable to recv")) Err(io::const_error!(io::ErrorKind::InvalidInput, "Unable to recv"))
} }
} }
@ -208,7 +208,7 @@ impl UdpSocket {
if let Some(addr) = self.remote.get() { if let Some(addr) = self.remote.get() {
self.send_to(buf, &addr) self.send_to(buf, &addr)
} else { } else {
Err(io::const_error!(io::ErrorKind::NotConnected, &"No remote specified")) Err(io::const_error!(io::ErrorKind::NotConnected, "No remote specified"))
} }
} }
@ -281,19 +281,19 @@ impl UdpSocket {
if errcode == NetError::SocketInUse as u8 { if errcode == NetError::SocketInUse as u8 {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::ResourceBusy, io::ErrorKind::ResourceBusy,
&"Socket in use" "Socket in use",
)); ));
} else if errcode == NetError::Invalid as u8 { } else if errcode == NetError::Invalid as u8 {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
&"Socket not valid" "Socket not valid",
)); ));
} else if errcode == NetError::LibraryError as u8 { } else if errcode == NetError::LibraryError as u8 {
return Err(io::const_error!(io::ErrorKind::Other, &"Library error")); return Err(io::const_error!(io::ErrorKind::Other, "Library error"));
} else { } else {
return Err(io::const_error!( return Err(io::const_error!(
io::ErrorKind::Other, io::ErrorKind::Other,
&"Unable to connect" "Unable to connect",
)); ));
} }
} else { } else {
@ -303,16 +303,13 @@ impl UdpSocket {
} }
Err(crate::os::xous::ffi::Error::ServerQueueFull) => { Err(crate::os::xous::ffi::Error::ServerQueueFull) => {
if now.elapsed() >= write_timeout { if now.elapsed() >= write_timeout {
return Err(io::const_error!( return Err(io::const_error!(io::ErrorKind::WouldBlock, "Write timed out"));
io::ErrorKind::WouldBlock,
&"Write timed out"
));
} else { } else {
// question: do we want to do something a bit more gentle than immediately retrying? // question: do we want to do something a bit more gentle than immediately retrying?
crate::thread::yield_now(); crate::thread::yield_now();
} }
} }
_ => return Err(io::const_error!(io::ErrorKind::Other, &"Library error")), _ => return Err(io::const_error!(io::ErrorKind::Other, "Library error")),
} }
} }
} }
@ -360,13 +357,13 @@ impl UdpSocket {
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
if ttl > 255 { if ttl > 255 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "TTL must be less than 256")); return Err(io::const_error!(io::ErrorKind::InvalidInput, "TTL must be less than 256"));
} }
crate::os::xous::ffi::blocking_scalar( crate::os::xous::ffi::blocking_scalar(
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdSetTtlUdp(self.fd, ttl).into(), services::NetBlockingScalar::StdSetTtlUdp(self.fd, ttl).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|_| ()) .map(|_| ())
} }
@ -375,7 +372,7 @@ impl UdpSocket {
services::net_server(), services::net_server(),
services::NetBlockingScalar::StdGetTtlUdp(self.fd).into(), services::NetBlockingScalar::StdGetTtlUdp(self.fd).into(),
) )
.or(Err(io::const_error!(io::ErrorKind::InvalidInput, &"Unexpected return value"))) .or(Err(io::const_error!(io::ErrorKind::InvalidInput, "Unexpected return value")))
.map(|res| res[0] as _)?) .map(|res| res[0] as _)?)
} }
@ -441,7 +438,7 @@ impl UdpSocket {
impl fmt::Debug for UdpSocket { impl fmt::Debug for UdpSocket {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "UDP listening on {:?} to {:?}", self.local, self.remote.get(),) write!(f, "UDP listening on {:?} to {:?}", self.local, self.remote.get())
} }
} }

View file

@ -304,16 +304,12 @@ impl OpenOptions {
(true, false) => {} (true, false) => {}
(false, false) => { (false, false) => {
if self.truncate || self.create || self.create_new { if self.truncate || self.create || self.create_new {
return Err( return Err(io::const_error!(ErrorKind::InvalidInput, "invalid creation mode"));
io::const_error!(ErrorKind::InvalidInput, "invalid creation mode",),
);
} }
} }
(_, true) => { (_, true) => {
if self.truncate && !self.create_new { if self.truncate && !self.create_new {
return Err( return Err(io::const_error!(ErrorKind::InvalidInput, "invalid creation mode"));
io::const_error!(ErrorKind::InvalidInput, "invalid creation mode",),
);
} }
} }
} }

View file

@ -309,7 +309,7 @@ fn cstr(path: &Path) -> io::Result<CString> {
let wrapped_path = [SAFE_PREFIX, &path, &[0]].concat(); let wrapped_path = [SAFE_PREFIX, &path, &[0]].concat();
CString::from_vec_with_nul(wrapped_path).map_err(|_| { CString::from_vec_with_nul(wrapped_path).map_err(|_| {
crate::io::const_error!(io::ErrorKind::InvalidInput, "path provided contains a nul byte",) crate::io::const_error!(io::ErrorKind::InvalidInput, "path provided contains a nul byte")
}) })
} }

View file

@ -148,5 +148,5 @@ pub fn unsupported<T>() -> std_io::Result<T> {
} }
pub fn unsupported_err() -> std_io::Error { pub fn unsupported_err() -> std_io::Error {
std_io::Error::new(std_io::ErrorKind::Unsupported, "operation not supported on this platform") std_io::Error::UNSUPPORTED_PLATFORM
} }

View file

@ -107,11 +107,11 @@ pub fn getenv(_: &OsStr) -> Option<OsString> {
} }
pub unsafe fn setenv(_: &OsStr, _: &OsStr) -> io::Result<()> { pub unsafe fn setenv(_: &OsStr, _: &OsStr) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "cannot set env vars on this platform")) Err(io::const_error!(io::ErrorKind::Unsupported, "cannot set env vars on this platform"))
} }
pub unsafe fn unsetenv(_: &OsStr) -> io::Result<()> { pub unsafe fn unsetenv(_: &OsStr) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "cannot unset env vars on this platform")) Err(io::const_error!(io::ErrorKind::Unsupported, "cannot unset env vars on this platform"))
} }
pub fn temp_dir() -> PathBuf { pub fn temp_dir() -> PathBuf {

View file

@ -273,7 +273,7 @@ impl OwnedDevicePath {
io::Result::Err(const_error!( io::Result::Err(const_error!(
io::ErrorKind::NotFound, io::ErrorKind::NotFound,
"DevicePathFromText Protocol not found" "DevicePathFromText Protocol not found",
)) ))
} }

View file

@ -90,7 +90,7 @@ pub const fn unsupported<T>() -> std_io::Result<T> {
#[inline] #[inline]
pub const fn unsupported_err() -> std_io::Error { pub const fn unsupported_err() -> std_io::Error {
std_io::const_error!(std_io::ErrorKind::Unsupported, "operation not supported on UEFI",) std_io::const_error!(std_io::ErrorKind::Unsupported, "operation not supported on UEFI")
} }
pub fn decode_error_kind(code: RawOsError) -> crate::io::ErrorKind { pub fn decode_error_kind(code: RawOsError) -> crate::io::ErrorKind {

View file

@ -71,7 +71,7 @@ impl io::Read for Stdin {
}; };
if ch.len() > 1 { if ch.len() > 1 {
return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid utf-16 sequence")); return Err(io::const_error!(io::ErrorKind::InvalidData, "invalid utf-16 sequence"));
} }
match ch.pop().unwrap() { match ch.pop().unwrap() {

View file

@ -568,8 +568,7 @@ impl FileAttr {
Err(io::const_error!( Err(io::const_error!(
io::ErrorKind::Unsupported, io::ErrorKind::Unsupported,
"creation time is not available on this platform \ "creation time is not available on this platform currently",
currently",
)) ))
} }
@ -1459,11 +1458,11 @@ impl File {
Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts), Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!( Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"timestamp is too large to set as a file time" "timestamp is too large to set as a file time",
)), )),
Some(_) => Err(io::const_error!( Some(_) => Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"timestamp is too small to set as a file time" "timestamp is too small to set as a file time",
)), )),
None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }), None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
}; };

View file

@ -260,7 +260,7 @@ pub fn current_exe() -> io::Result<PathBuf> {
let exe_path = env::args().next().ok_or(io::const_error!( let exe_path = env::args().next().ok_or(io::const_error!(
ErrorKind::NotFound, ErrorKind::NotFound,
"an executable path was not found because no arguments were provided through argv" "an executable path was not found because no arguments were provided through argv",
))?; ))?;
let path = PathBuf::from(exe_path); let path = PathBuf::from(exe_path);
if path.is_absolute() { if path.is_absolute() {
@ -382,9 +382,7 @@ pub fn current_exe() -> io::Result<PathBuf> {
cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?; cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?;
argv.set_len(argv_len as usize); argv.set_len(argv_len as usize);
if argv[0].is_null() { if argv[0].is_null() {
return Err( return Err(io::const_error!(io::ErrorKind::Uncategorized, "no current exe available"));
io::const_error!(io::ErrorKind::Uncategorized, "no current exe available",),
);
} }
let argv0 = CStr::from_ptr(argv[0]).to_bytes(); let argv0 = CStr::from_ptr(argv[0]).to_bytes();
if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') { if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') {
@ -526,7 +524,7 @@ pub fn current_exe() -> io::Result<PathBuf> {
let exe_path = env::args().next().ok_or(io::const_error!( let exe_path = env::args().next().ok_or(io::const_error!(
ErrorKind::Uncategorized, ErrorKind::Uncategorized,
"an executable path was not found because no arguments were provided through argv" "an executable path was not found because no arguments were provided through argv",
))?; ))?;
let path = PathBuf::from(exe_path); let path = PathBuf::from(exe_path);

View file

@ -228,7 +228,7 @@ impl Command {
let envp = self.capture_env(); let envp = self.capture_env();
if self.saw_nul() { if self.saw_nul() {
return io::const_error!(ErrorKind::InvalidInput, "nul byte found in provided data",); return io::const_error!(ErrorKind::InvalidInput, "nul byte found in provided data");
} }
match self.setup_io(default, true) { match self.setup_io(default, true) {
@ -1228,7 +1228,7 @@ mod linux_child_ext {
.as_ref() .as_ref()
// SAFETY: The os type is a transparent wrapper, therefore we can transmute references // SAFETY: The os type is a transparent wrapper, therefore we can transmute references
.map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) }) .map(|fd| unsafe { mem::transmute::<&imp::PidFd, &os::PidFd>(fd) })
.ok_or_else(|| io::Error::new(ErrorKind::Uncategorized, "No pidfd was created.")) .ok_or_else(|| io::const_error!(ErrorKind::Uncategorized, "No pidfd was created."))
} }
fn into_pidfd(mut self) -> Result<os::PidFd, Self> { fn into_pidfd(mut self) -> Result<os::PidFd, Self> {

View file

@ -533,7 +533,7 @@ impl File {
Some(time) if let Some(ts) = time.to_wasi_timestamp() => Ok(ts), Some(time) if let Some(ts) = time.to_wasi_timestamp() => Ok(ts),
Some(_) => Err(io::const_error!( Some(_) => Err(io::const_error!(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"timestamp is too large to set as a file time" "timestamp is too large to set as a file time",
)), )),
None => Ok(0), None => Ok(0),
}; };
@ -773,8 +773,7 @@ fn open_parent(p: &Path) -> io::Result<(ManuallyDrop<WasiFd>, PathBuf)> {
} }
let msg = format!( let msg = format!(
"failed to find a pre-opened file descriptor \ "failed to find a pre-opened file descriptor \
through which {:?} could be opened", through which {p:?} could be opened",
p
); );
return Err(io::Error::new(io::ErrorKind::Uncategorized, msg)); return Err(io::Error::new(io::ErrorKind::Uncategorized, msg));
} }

View file

@ -1468,9 +1468,7 @@ pub fn link(original: &Path, link: &Path) -> io::Result<()> {
#[cfg(target_vendor = "uwp")] #[cfg(target_vendor = "uwp")]
pub fn link(_original: &Path, _link: &Path) -> io::Result<()> { pub fn link(_original: &Path, _link: &Path) -> io::Result<()> {
return Err( return Err(io::const_error!(io::ErrorKind::Unsupported, "hard link are not supported on UWP"));
io::const_error!(io::ErrorKind::Unsupported, "hard link are not supported on UWP",),
);
} }
pub fn stat(path: &Path) -> io::Result<FileAttr> { pub fn stat(path: &Path) -> io::Result<FileAttr> {

View file

@ -435,9 +435,7 @@ fn resolve_exe<'a>(
) -> io::Result<Vec<u16>> { ) -> io::Result<Vec<u16>> {
// Early return if there is no filename. // Early return if there is no filename.
if exe_path.is_empty() || path::has_trailing_slash(exe_path) { if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
return Err( return Err(io::const_error!(io::ErrorKind::InvalidInput, "program path has no file name"));
io::const_error!(io::ErrorKind::InvalidInput, "program path has no file name",),
);
} }
// Test if the file name has the `exe` extension. // Test if the file name has the `exe` extension.
// This does a case-insensitive `ends_with`. // This does a case-insensitive `ends_with`.

View file

@ -39,15 +39,15 @@ fn str_to_cdata(s: &str) -> String {
impl<T: Write> OutputFormatter for JunitFormatter<T> { impl<T: Write> OutputFormatter for JunitFormatter<T> {
fn write_discovery_start(&mut self) -> io::Result<()> { fn write_discovery_start(&mut self) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::NotFound, "Not yet implemented!")) Err(io::const_error!(io::ErrorKind::NotFound, "Not yet implemented!"))
} }
fn write_test_discovered(&mut self, _desc: &TestDesc, _test_type: &str) -> io::Result<()> { fn write_test_discovered(&mut self, _desc: &TestDesc, _test_type: &str) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::NotFound, "Not yet implemented!")) Err(io::const_error!(io::ErrorKind::NotFound, "Not yet implemented!"))
} }
fn write_discovery_finish(&mut self, _state: &ConsoleTestDiscoveryState) -> io::Result<()> { fn write_discovery_finish(&mut self, _state: &ConsoleTestDiscoveryState) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::NotFound, "Not yet implemented!")) Err(io::const_error!(io::ErrorKind::NotFound, "Not yet implemented!"))
} }
fn write_run_start( fn write_run_start(

View file

@ -20,6 +20,7 @@
#![feature(rustdoc_internals)] #![feature(rustdoc_internals)]
#![feature(file_buffered)] #![feature(file_buffered)]
#![feature(internal_output_capture)] #![feature(internal_output_capture)]
#![feature(io_const_error)]
#![feature(staged_api)] #![feature(staged_api)]
#![feature(process_exitcode_internals)] #![feature(process_exitcode_internals)]
#![feature(panic_can_unwind)] #![feature(panic_can_unwind)]

View file

@ -90,7 +90,7 @@ impl TermInfo {
get_dbpath_for_term(name) get_dbpath_for_term(name)
.ok_or_else(|| { .ok_or_else(|| {
Error::IoError(io::Error::new(io::ErrorKind::NotFound, "terminfo file not found")) Error::IoError(io::const_error!(io::ErrorKind::NotFound, "terminfo file not found"))
}) })
.and_then(|p| TermInfo::from_path(&(*p))) .and_then(|p| TermInfo::from_path(&(*p)))
} }

View file

@ -173,7 +173,7 @@ fn read_le_u32(r: &mut dyn io::Read) -> io::Result<u32> {
fn read_byte(r: &mut dyn io::Read) -> io::Result<u8> { fn read_byte(r: &mut dyn io::Read) -> io::Result<u8> {
match r.bytes().next() { match r.bytes().next() {
Some(s) => s, Some(s) => s,
None => Err(io::Error::new(io::ErrorKind::Other, "end of file")), None => Err(io::const_error!(io::ErrorKind::Other, "end of file")),
} }
} }