未验证 提交 a42e62fa 编写于 作者: D Dylan DPC 提交者: GitHub

Rollup merge of #83353 - m-ou-se:io-error-avoid-alloc, r=nagisa

Add internal io::Error::new_const to avoid allocations.

This makes it possible to have a io::Error containing a message with zero allocations, and uses that everywhere to avoid the *three* allocations involved in `io::Error::new(kind, "message")`.

The function signature isn't perfect, because it needs a reference to the `&str`. So for now, this is just a `pub(crate)` function. Later, we'll be able to use `fn new_const<MSG: &'static str>(kind: ErrorKind)` to make that a bit better. (Then we'll also be able to use some ZST trickery if that would result in more efficient code.)

See https://github.com/rust-lang/rust/issues/83352
...@@ -1036,7 +1036,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...@@ -1036,7 +1036,7 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
impl From<NulError> for io::Error { impl From<NulError> for io::Error {
/// Converts a [`NulError`] into a [`io::Error`]. /// Converts a [`NulError`] into a [`io::Error`].
fn from(_: NulError) -> io::Error { fn from(_: NulError) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, "data provided contains a nul byte") io::Error::new_const(io::ErrorKind::InvalidInput, &"data provided contains a nul byte")
} }
} }
......
...@@ -2188,7 +2188,10 @@ fn create_dir_all(&self, path: &Path) -> io::Result<()> { ...@@ -2188,7 +2188,10 @@ fn create_dir_all(&self, path: &Path) -> io::Result<()> {
match path.parent() { match path.parent() {
Some(p) => self.create_dir_all(p)?, Some(p) => self.create_dir_all(p)?,
None => { None => {
return Err(io::Error::new(io::ErrorKind::Other, "failed to create whole tree")); return Err(io::Error::new_const(
io::ErrorKind::Other,
&"failed to create whole tree",
));
} }
} }
match self.inner.mkdir(path) { match self.inner.mkdir(path) {
......
...@@ -164,9 +164,9 @@ fn drop(&mut self) { ...@@ -164,9 +164,9 @@ fn drop(&mut self) {
match r { match r {
Ok(0) => { Ok(0) => {
return Err(Error::new( return Err(Error::new_const(
ErrorKind::WriteZero, ErrorKind::WriteZero,
"failed to write the buffered data", &"failed to write the buffered data",
)); ));
} }
Ok(n) => guard.consume(n), Ok(n) => guard.consume(n),
......
...@@ -229,9 +229,9 @@ fn seek(&mut self, style: SeekFrom) -> io::Result<u64> { ...@@ -229,9 +229,9 @@ fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
self.pos = n; self.pos = n;
Ok(self.pos) Ok(self.pos)
} }
None => Err(Error::new( None => Err(Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"invalid seek to a negative or overflowing position", &"invalid seek to a negative or overflowing position",
)), )),
} }
} }
...@@ -328,9 +328,9 @@ fn slice_write_vectored( ...@@ -328,9 +328,9 @@ fn slice_write_vectored(
// Resizing write implementation // Resizing write implementation
fn vec_write(pos_mut: &mut u64, vec: &mut Vec<u8>, buf: &[u8]) -> io::Result<usize> { fn vec_write(pos_mut: &mut u64, vec: &mut Vec<u8>, buf: &[u8]) -> io::Result<usize> {
let pos: usize = (*pos_mut).try_into().map_err(|_| { let pos: usize = (*pos_mut).try_into().map_err(|_| {
Error::new( Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"cursor position exceeds maximum possible vector length", &"cursor position exceeds maximum possible vector length",
) )
})?; })?;
// Make sure the internal buffer is as least as big as where we // Make sure the internal buffer is as least as big as where we
......
...@@ -69,6 +69,8 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ...@@ -69,6 +69,8 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
enum Repr { enum Repr {
Os(i32), Os(i32),
Simple(ErrorKind), Simple(ErrorKind),
// &str is a fat pointer, but &&str is a thin pointer.
SimpleMessage(ErrorKind, &'static &'static str),
Custom(Box<Custom>), Custom(Box<Custom>),
} }
...@@ -259,6 +261,18 @@ fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error { ...@@ -259,6 +261,18 @@ fn _new(kind: ErrorKind, error: Box<dyn error::Error + Send + Sync>) -> Error {
Error { repr: Repr::Custom(Box::new(Custom { kind, error })) } Error { repr: Repr::Custom(Box::new(Custom { kind, error })) }
} }
/// Creates a new I/O error from a known kind of error as well as a
/// constant message.
///
/// This function does not allocate.
///
/// This function should maybe change to
/// `new_const<const MSG: &'static str>(kind: ErrorKind)`
/// in the future, when const generics allow that.
pub(crate) const fn new_const(kind: ErrorKind, message: &'static &'static str) -> Error {
Self { repr: Repr::SimpleMessage(kind, message) }
}
/// Returns an error representing the last OS error which occurred. /// Returns an error representing the last OS error which occurred.
/// ///
/// This function reads the value of `errno` for the target platform (e.g. /// This function reads the value of `errno` for the target platform (e.g.
...@@ -342,6 +356,7 @@ pub fn raw_os_error(&self) -> Option<i32> { ...@@ -342,6 +356,7 @@ pub fn raw_os_error(&self) -> Option<i32> {
Repr::Os(i) => Some(i), Repr::Os(i) => Some(i),
Repr::Custom(..) => None, Repr::Custom(..) => None,
Repr::Simple(..) => None, Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
} }
} }
...@@ -377,6 +392,7 @@ pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> { ...@@ -377,6 +392,7 @@ pub fn get_ref(&self) -> Option<&(dyn error::Error + Send + Sync + 'static)> {
match self.repr { match self.repr {
Repr::Os(..) => None, Repr::Os(..) => None,
Repr::Simple(..) => None, Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref c) => Some(&*c.error), Repr::Custom(ref c) => Some(&*c.error),
} }
} }
...@@ -448,6 +464,7 @@ pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'stat ...@@ -448,6 +464,7 @@ pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error + Send + Sync + 'stat
match self.repr { match self.repr {
Repr::Os(..) => None, Repr::Os(..) => None,
Repr::Simple(..) => None, Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref mut c) => Some(&mut *c.error), Repr::Custom(ref mut c) => Some(&mut *c.error),
} }
} }
...@@ -484,6 +501,7 @@ pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> { ...@@ -484,6 +501,7 @@ pub fn into_inner(self) -> Option<Box<dyn error::Error + Send + Sync>> {
match self.repr { match self.repr {
Repr::Os(..) => None, Repr::Os(..) => None,
Repr::Simple(..) => None, Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(c) => Some(c.error), Repr::Custom(c) => Some(c.error),
} }
} }
...@@ -512,6 +530,7 @@ pub fn kind(&self) -> ErrorKind { ...@@ -512,6 +530,7 @@ pub fn kind(&self) -> ErrorKind {
Repr::Os(code) => sys::decode_error_kind(code), Repr::Os(code) => sys::decode_error_kind(code),
Repr::Custom(ref c) => c.kind, Repr::Custom(ref c) => c.kind,
Repr::Simple(kind) => kind, Repr::Simple(kind) => kind,
Repr::SimpleMessage(kind, _) => kind,
} }
} }
} }
...@@ -527,6 +546,9 @@ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { ...@@ -527,6 +546,9 @@ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
.finish(), .finish(),
Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt), Repr::Custom(ref c) => fmt::Debug::fmt(&c, fmt),
Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(), Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
Repr::SimpleMessage(kind, &message) => {
fmt.debug_struct("Error").field("kind", &kind).field("message", &message).finish()
}
} }
} }
} }
...@@ -541,6 +563,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { ...@@ -541,6 +563,7 @@ fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
} }
Repr::Custom(ref c) => c.error.fmt(fmt), Repr::Custom(ref c) => c.error.fmt(fmt),
Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()), Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
Repr::SimpleMessage(_, &msg) => msg.fmt(fmt),
} }
} }
} }
...@@ -551,6 +574,7 @@ impl error::Error for Error { ...@@ -551,6 +574,7 @@ impl error::Error for Error {
fn description(&self) -> &str { fn description(&self) -> &str {
match self.repr { match self.repr {
Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(), Repr::Os(..) | Repr::Simple(..) => self.kind().as_str(),
Repr::SimpleMessage(_, &msg) => msg,
Repr::Custom(ref c) => c.error.description(), Repr::Custom(ref c) => c.error.description(),
} }
} }
...@@ -560,6 +584,7 @@ fn cause(&self) -> Option<&dyn error::Error> { ...@@ -560,6 +584,7 @@ fn cause(&self) -> Option<&dyn error::Error> {
match self.repr { match self.repr {
Repr::Os(..) => None, Repr::Os(..) => None,
Repr::Simple(..) => None, Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref c) => c.error.cause(), Repr::Custom(ref c) => c.error.cause(),
} }
} }
...@@ -568,6 +593,7 @@ fn source(&self) -> Option<&(dyn error::Error + 'static)> { ...@@ -568,6 +593,7 @@ fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self.repr { match self.repr {
Repr::Os(..) => None, Repr::Os(..) => None,
Repr::Simple(..) => None, Repr::Simple(..) => None,
Repr::SimpleMessage(..) => None,
Repr::Custom(ref c) => c.error.source(), Repr::Custom(ref c) => c.error.source(),
} }
} }
......
use super::{Custom, Error, ErrorKind, Repr}; use super::{Custom, Error, ErrorKind, Repr};
use crate::error; use crate::error;
use crate::fmt; use crate::fmt;
use crate::mem::size_of;
use crate::sys::decode_error_kind; use crate::sys::decode_error_kind;
use crate::sys::os::error_string; use crate::sys::os::error_string;
#[test]
fn test_size() {
assert!(size_of::<Error>() <= size_of::<[usize; 2]>());
}
#[test] #[test]
fn test_debug_error() { fn test_debug_error() {
let code = 6; let code = 6;
...@@ -51,3 +57,13 @@ impl error::Error for TestError {} ...@@ -51,3 +57,13 @@ impl error::Error for TestError {}
let extracted = err.into_inner().unwrap(); let extracted = err.into_inner().unwrap();
extracted.downcast::<TestError>().unwrap(); extracted.downcast::<TestError>().unwrap();
} }
#[test]
fn test_const() {
const E: Error = Error::new_const(ErrorKind::NotFound, &"hello");
assert_eq!(E.kind(), ErrorKind::NotFound);
assert_eq!(E.to_string(), "hello");
assert!(format!("{:?}", E).contains("\"hello\""));
assert!(format!("{:?}", E).contains("NotFound"));
}
...@@ -263,7 +263,7 @@ unsafe fn initializer(&self) -> Initializer { ...@@ -263,7 +263,7 @@ unsafe fn initializer(&self) -> Initializer {
#[inline] #[inline]
fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
if buf.len() > self.len() { if buf.len() > self.len() {
return Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")); return Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"));
} }
let (a, b) = self.split_at(buf.len()); let (a, b) = self.split_at(buf.len());
...@@ -345,7 +345,7 @@ fn write_all(&mut self, data: &[u8]) -> io::Result<()> { ...@@ -345,7 +345,7 @@ fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
if self.write(data)? == data.len() { if self.write(data)? == data.len() {
Ok(()) Ok(())
} else { } else {
Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer")) Err(Error::new_const(ErrorKind::WriteZero, &"failed to write whole buffer"))
} }
} }
......
...@@ -333,7 +333,7 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize> ...@@ -333,7 +333,7 @@ fn append_to_string<F>(buf: &mut String, f: F) -> Result<usize>
let ret = f(g.buf); let ret = f(g.buf);
if str::from_utf8(&g.buf[g.len..]).is_err() { if str::from_utf8(&g.buf[g.len..]).is_err() {
ret.and_then(|_| { ret.and_then(|_| {
Err(Error::new(ErrorKind::InvalidData, "stream did not contain valid UTF-8")) Err(Error::new_const(ErrorKind::InvalidData, &"stream did not contain valid UTF-8"))
}) })
} else { } else {
g.len = g.buf.len(); g.len = g.buf.len();
...@@ -429,7 +429,7 @@ pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [ ...@@ -429,7 +429,7 @@ pub(crate) fn default_read_exact<R: Read + ?Sized>(this: &mut R, mut buf: &mut [
} }
} }
if !buf.is_empty() { if !buf.is_empty() {
Err(Error::new(ErrorKind::UnexpectedEof, "failed to fill whole buffer")) Err(Error::new_const(ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
} else { } else {
Ok(()) Ok(())
} }
...@@ -1437,7 +1437,10 @@ fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { ...@@ -1437,7 +1437,10 @@ fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
while !buf.is_empty() { while !buf.is_empty() {
match self.write(buf) { match self.write(buf) {
Ok(0) => { Ok(0) => {
return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer")); return Err(Error::new_const(
ErrorKind::WriteZero,
&"failed to write whole buffer",
));
} }
Ok(n) => buf = &buf[n..], Ok(n) => buf = &buf[n..],
Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
...@@ -1502,7 +1505,10 @@ fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> { ...@@ -1502,7 +1505,10 @@ fn write_all_vectored(&mut self, mut bufs: &mut [IoSlice<'_>]) -> Result<()> {
while !bufs.is_empty() { while !bufs.is_empty() {
match self.write_vectored(bufs) { match self.write_vectored(bufs) {
Ok(0) => { Ok(0) => {
return Err(Error::new(ErrorKind::WriteZero, "failed to write whole buffer")); return Err(Error::new_const(
ErrorKind::WriteZero,
&"failed to write whole buffer",
));
} }
Ok(n) => bufs = IoSlice::advance(bufs, n), Ok(n) => bufs = IoSlice::advance(bufs, n),
Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
...@@ -1576,7 +1582,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result { ...@@ -1576,7 +1582,7 @@ fn write_str(&mut self, s: &str) -> fmt::Result {
if output.error.is_err() { if output.error.is_err() {
output.error output.error
} else { } else {
Err(Error::new(ErrorKind::Other, "formatter error")) Err(Error::new_const(ErrorKind::Other, &"formatter error"))
} }
} }
} }
......
...@@ -152,12 +152,12 @@ fn take_eof() { ...@@ -152,12 +152,12 @@ fn take_eof() {
impl Read for R { impl Read for R {
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> { fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(io::ErrorKind::Other, "")) Err(io::Error::new_const(io::ErrorKind::Other, &""))
} }
} }
impl BufRead for R { impl BufRead for R {
fn fill_buf(&mut self) -> io::Result<&[u8]> { fn fill_buf(&mut self) -> io::Result<&[u8]> {
Err(io::Error::new(io::ErrorKind::Other, "")) Err(io::Error::new_const(io::ErrorKind::Other, &""))
} }
fn consume(&mut self, _amt: usize) {} fn consume(&mut self, _amt: usize) {}
} }
......
...@@ -88,6 +88,6 @@ fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T> ...@@ -88,6 +88,6 @@ fn each_addr<A: ToSocketAddrs, F, T>(addr: A, mut f: F) -> io::Result<T>
} }
} }
Err(last_err.unwrap_or_else(|| { Err(last_err.unwrap_or_else(|| {
Error::new(ErrorKind::InvalidInput, "could not resolve to any addresses") Error::new_const(ErrorKind::InvalidInput, &"could not resolve to any addresses")
})) }))
} }
...@@ -173,7 +173,7 @@ pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { ...@@ -173,7 +173,7 @@ pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> { pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
match addr.to_socket_addrs()?.next() { match addr.to_socket_addrs()?.next() {
Some(addr) => self.0.send_to(buf, &addr), Some(addr) => self.0.send_to(buf, &addr),
None => Err(Error::new(ErrorKind::InvalidInput, "no addresses to send data to")), None => Err(Error::new_const(ErrorKind::InvalidInput, &"no addresses to send data to")),
} }
} }
......
...@@ -46,7 +46,7 @@ pub fn duplicate(&self) -> io::Result<FileDesc> { ...@@ -46,7 +46,7 @@ pub fn duplicate(&self) -> io::Result<FileDesc> {
self.duplicate_path(&[]) self.duplicate_path(&[])
} }
pub fn duplicate_path(&self, _path: &[u8]) -> io::Result<FileDesc> { pub fn duplicate_path(&self, _path: &[u8]) -> io::Result<FileDesc> {
Err(io::Error::new(ErrorKind::Other, "duplicate isn't supported")) Err(io::Error::new_const(ErrorKind::Other, &"duplicate isn't supported"))
} }
pub fn nonblocking(&self) -> io::Result<bool> { pub fn nonblocking(&self) -> io::Result<bool> {
...@@ -54,11 +54,11 @@ pub fn nonblocking(&self) -> io::Result<bool> { ...@@ -54,11 +54,11 @@ pub fn nonblocking(&self) -> io::Result<bool> {
} }
pub fn set_cloexec(&self) -> io::Result<()> { pub fn set_cloexec(&self) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "cloexec isn't supported")) Err(io::Error::new_const(ErrorKind::Other, &"cloexec isn't supported"))
} }
pub fn set_nonblocking(&self, _nonblocking: bool) -> io::Result<()> { pub fn set_nonblocking(&self, _nonblocking: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "nonblocking isn't supported")) Err(io::Error::new_const(ErrorKind::Other, &"nonblocking isn't supported"))
} }
} }
......
...@@ -226,7 +226,7 @@ fn get_access_mode(&self) -> io::Result<i32> { ...@@ -226,7 +226,7 @@ fn get_access_mode(&self) -> io::Result<i32> {
(false, _, true) => Ok(O_WRONLY | O_APPEND), (false, _, true) => Ok(O_WRONLY | O_APPEND),
(true, _, true) => Ok(O_RDWR | O_APPEND), (true, _, true) => Ok(O_RDWR | O_APPEND),
(false, false, false) => { (false, false, false) => {
Err(io::Error::new(ErrorKind::InvalidInput, "invalid access mode")) Err(io::Error::new_const(ErrorKind::InvalidInput, &"invalid access mode"))
} }
} }
} }
...@@ -236,12 +236,18 @@ fn get_creation_mode(&self) -> io::Result<i32> { ...@@ -236,12 +236,18 @@ fn get_creation_mode(&self) -> io::Result<i32> {
(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(io::Error::new(ErrorKind::InvalidInput, "invalid creation mode")); return Err(io::Error::new_const(
ErrorKind::InvalidInput,
&"invalid creation mode",
));
} }
} }
(_, true) => { (_, true) => {
if self.truncate && !self.create_new { if self.truncate && !self.create_new {
return Err(io::Error::new(ErrorKind::InvalidInput, "invalid creation mode")); return Err(io::Error::new_const(
ErrorKind::InvalidInput,
&"invalid creation mode",
));
} }
} }
} }
......
...@@ -55,7 +55,10 @@ pub fn unsupported<T>() -> crate::io::Result<T> { ...@@ -55,7 +55,10 @@ pub fn unsupported<T>() -> crate::io::Result<T> {
} }
pub fn unsupported_err() -> crate::io::Error { pub fn unsupported_err() -> crate::io::Error {
crate::io::Error::new(crate::io::ErrorKind::Other, "operation not supported on HermitCore yet") crate::io::Error::new_const(
crate::io::ErrorKind::Other,
&"operation not supported on HermitCore yet",
)
} }
// This enum is used as the storage for a bunch of types which can't actually // This enum is used as the storage for a bunch of types which can't actually
......
...@@ -14,7 +14,10 @@ ...@@ -14,7 +14,10 @@
/// if not, starts it. /// if not, starts it.
pub fn init() -> io::Result<()> { pub fn init() -> io::Result<()> {
if abi::network_init() < 0 { if abi::network_init() < 0 {
return Err(io::Error::new(ErrorKind::Other, "Unable to initialize network interface")); return Err(io::Error::new_const(
ErrorKind::Other,
&"Unable to initialize network interface",
));
} }
Ok(()) Ok(())
...@@ -47,9 +50,10 @@ pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> { ...@@ -47,9 +50,10 @@ pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
match abi::tcpstream::connect(addr.ip().to_string().as_bytes(), addr.port(), None) { match abi::tcpstream::connect(addr.ip().to_string().as_bytes(), addr.port(), None) {
Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))), Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))),
_ => { _ => Err(io::Error::new_const(
Err(io::Error::new(ErrorKind::Other, "Unable to initiate a connection on a socket")) ErrorKind::Other,
} &"Unable to initiate a connection on a socket",
)),
} }
} }
...@@ -60,15 +64,16 @@ pub fn connect_timeout(saddr: &SocketAddr, duration: Duration) -> io::Result<Tcp ...@@ -60,15 +64,16 @@ pub fn connect_timeout(saddr: &SocketAddr, duration: Duration) -> io::Result<Tcp
Some(duration.as_millis() as u64), Some(duration.as_millis() as u64),
) { ) {
Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))), Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))),
_ => { _ => Err(io::Error::new_const(
Err(io::Error::new(ErrorKind::Other, "Unable to initiate a connection on a socket")) ErrorKind::Other,
} &"Unable to initiate a connection on a socket",
)),
} }
} }
pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> { pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
abi::tcpstream::set_read_timeout(*self.0.as_inner(), duration.map(|d| d.as_millis() as u64)) abi::tcpstream::set_read_timeout(*self.0.as_inner(), duration.map(|d| d.as_millis() as u64))
.map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"Unable to set timeout value"))
} }
pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> { pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
...@@ -76,26 +81,28 @@ pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> { ...@@ -76,26 +81,28 @@ pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
*self.0.as_inner(), *self.0.as_inner(),
duration.map(|d| d.as_millis() as u64), duration.map(|d| d.as_millis() as u64),
) )
.map_err(|_| io::Error::new(ErrorKind::Other, "Unable to set timeout value")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"Unable to set timeout value"))
} }
pub fn read_timeout(&self) -> io::Result<Option<Duration>> { pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
let duration = abi::tcpstream::get_read_timeout(*self.0.as_inner()) let duration = abi::tcpstream::get_read_timeout(*self.0.as_inner()).map_err(|_| {
.map_err(|_| io::Error::new(ErrorKind::Other, "Unable to determine timeout value"))?; io::Error::new_const(ErrorKind::Other, &"Unable to determine timeout value")
})?;
Ok(duration.map(|d| Duration::from_millis(d))) Ok(duration.map(|d| Duration::from_millis(d)))
} }
pub fn write_timeout(&self) -> io::Result<Option<Duration>> { pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
let duration = abi::tcpstream::get_write_timeout(*self.0.as_inner()) let duration = abi::tcpstream::get_write_timeout(*self.0.as_inner()).map_err(|_| {
.map_err(|_| io::Error::new(ErrorKind::Other, "Unable to determine timeout value"))?; io::Error::new_const(ErrorKind::Other, &"Unable to determine timeout value")
})?;
Ok(duration.map(|d| Duration::from_millis(d))) Ok(duration.map(|d| Duration::from_millis(d)))
} }
pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
abi::tcpstream::peek(*self.0.as_inner(), buf) abi::tcpstream::peek(*self.0.as_inner(), buf)
.map_err(|_| io::Error::new(ErrorKind::Other, "set_nodelay failed")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"set_nodelay failed"))
} }
pub fn read(&self, buffer: &mut [u8]) -> io::Result<usize> { pub fn read(&self, buffer: &mut [u8]) -> io::Result<usize> {
...@@ -107,7 +114,7 @@ pub fn read_vectored(&self, ioslice: &mut [IoSliceMut<'_>]) -> io::Result<usize> ...@@ -107,7 +114,7 @@ pub fn read_vectored(&self, ioslice: &mut [IoSliceMut<'_>]) -> io::Result<usize>
for i in ioslice.iter_mut() { for i in ioslice.iter_mut() {
let ret = abi::tcpstream::read(*self.0.as_inner(), &mut i[0..]) let ret = abi::tcpstream::read(*self.0.as_inner(), &mut i[0..])
.map_err(|_| io::Error::new(ErrorKind::Other, "Unable to read on socket"))?; .map_err(|_| io::Error::new_const(ErrorKind::Other, &"Unable to read on socket"))?;
if ret != 0 { if ret != 0 {
size += ret; size += ret;
...@@ -130,8 +137,9 @@ pub fn write_vectored(&self, ioslice: &[IoSlice<'_>]) -> io::Result<usize> { ...@@ -130,8 +137,9 @@ pub fn write_vectored(&self, ioslice: &[IoSlice<'_>]) -> io::Result<usize> {
let mut size: usize = 0; let mut size: usize = 0;
for i in ioslice.iter() { for i in ioslice.iter() {
size += abi::tcpstream::write(*self.0.as_inner(), i) size += abi::tcpstream::write(*self.0.as_inner(), i).map_err(|_| {
.map_err(|_| io::Error::new(ErrorKind::Other, "Unable to write on socket"))?; io::Error::new_const(ErrorKind::Other, &"Unable to write on socket")
})?;
} }
Ok(size) Ok(size)
...@@ -144,13 +152,13 @@ pub fn is_write_vectored(&self) -> bool { ...@@ -144,13 +152,13 @@ pub fn is_write_vectored(&self) -> bool {
pub fn peer_addr(&self) -> io::Result<SocketAddr> { pub fn peer_addr(&self) -> io::Result<SocketAddr> {
let (ipaddr, port) = abi::tcpstream::peer_addr(*self.0.as_inner()) let (ipaddr, port) = abi::tcpstream::peer_addr(*self.0.as_inner())
.map_err(|_| io::Error::new(ErrorKind::Other, "peer_addr failed"))?; .map_err(|_| io::Error::new_const(ErrorKind::Other, &"peer_addr failed"))?;
let saddr = match ipaddr { let saddr = match ipaddr {
Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port), Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port),
Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port),
_ => { _ => {
return Err(io::Error::new(ErrorKind::Other, "peer_addr failed")); return Err(io::Error::new_const(ErrorKind::Other, &"peer_addr failed"));
} }
}; };
...@@ -158,12 +166,12 @@ pub fn peer_addr(&self) -> io::Result<SocketAddr> { ...@@ -158,12 +166,12 @@ pub fn peer_addr(&self) -> io::Result<SocketAddr> {
} }
pub fn socket_addr(&self) -> io::Result<SocketAddr> { pub fn socket_addr(&self) -> io::Result<SocketAddr> {
Err(io::Error::new(ErrorKind::Other, "socket_addr isn't supported")) Err(io::Error::new_const(ErrorKind::Other, &"socket_addr isn't supported"))
} }
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
abi::tcpstream::shutdown(*self.0.as_inner(), how as i32) abi::tcpstream::shutdown(*self.0.as_inner(), how as i32)
.map_err(|_| io::Error::new(ErrorKind::Other, "unable to shutdown socket")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to shutdown socket"))
} }
pub fn duplicate(&self) -> io::Result<TcpStream> { pub fn duplicate(&self) -> io::Result<TcpStream> {
...@@ -172,31 +180,31 @@ pub fn duplicate(&self) -> io::Result<TcpStream> { ...@@ -172,31 +180,31 @@ pub fn duplicate(&self) -> io::Result<TcpStream> {
pub fn set_nodelay(&self, mode: bool) -> io::Result<()> { pub fn set_nodelay(&self, mode: bool) -> io::Result<()> {
abi::tcpstream::set_nodelay(*self.0.as_inner(), mode) abi::tcpstream::set_nodelay(*self.0.as_inner(), mode)
.map_err(|_| io::Error::new(ErrorKind::Other, "set_nodelay failed")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"set_nodelay failed"))
} }
pub fn nodelay(&self) -> io::Result<bool> { pub fn nodelay(&self) -> io::Result<bool> {
abi::tcpstream::nodelay(*self.0.as_inner()) abi::tcpstream::nodelay(*self.0.as_inner())
.map_err(|_| io::Error::new(ErrorKind::Other, "nodelay failed")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"nodelay failed"))
} }
pub fn set_ttl(&self, tll: u32) -> io::Result<()> { pub fn set_ttl(&self, tll: u32) -> io::Result<()> {
abi::tcpstream::set_tll(*self.0.as_inner(), tll) abi::tcpstream::set_tll(*self.0.as_inner(), tll)
.map_err(|_| io::Error::new(ErrorKind::Other, "unable to set TTL")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to set TTL"))
} }
pub fn ttl(&self) -> io::Result<u32> { pub fn ttl(&self) -> io::Result<u32> {
abi::tcpstream::get_tll(*self.0.as_inner()) abi::tcpstream::get_tll(*self.0.as_inner())
.map_err(|_| io::Error::new(ErrorKind::Other, "unable to get TTL")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to get TTL"))
} }
pub fn take_error(&self) -> io::Result<Option<io::Error>> { pub fn take_error(&self) -> io::Result<Option<io::Error>> {
Err(io::Error::new(ErrorKind::Other, "take_error isn't supported")) Err(io::Error::new_const(ErrorKind::Other, &"take_error isn't supported"))
} }
pub fn set_nonblocking(&self, mode: bool) -> io::Result<()> { pub fn set_nonblocking(&self, mode: bool) -> io::Result<()> {
abi::tcpstream::set_nonblocking(*self.0.as_inner(), mode) abi::tcpstream::set_nonblocking(*self.0.as_inner(), mode)
.map_err(|_| io::Error::new(ErrorKind::Other, "unable to set blocking mode")) .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to set blocking mode"))
} }
} }
...@@ -222,12 +230,12 @@ pub fn socket_addr(&self) -> io::Result<SocketAddr> { ...@@ -222,12 +230,12 @@ pub fn socket_addr(&self) -> io::Result<SocketAddr> {
pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
let (handle, ipaddr, port) = abi::tcplistener::accept(self.0.port()) let (handle, ipaddr, port) = abi::tcplistener::accept(self.0.port())
.map_err(|_| io::Error::new(ErrorKind::Other, "accept failed"))?; .map_err(|_| io::Error::new_const(ErrorKind::Other, &"accept failed"))?;
let saddr = match ipaddr { let saddr = match ipaddr {
Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port), Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port),
Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port), Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port),
_ => { _ => {
return Err(io::Error::new(ErrorKind::Other, "accept failed")); return Err(io::Error::new_const(ErrorKind::Other, &"accept failed"));
} }
}; };
...@@ -239,27 +247,27 @@ pub fn duplicate(&self) -> io::Result<TcpListener> { ...@@ -239,27 +247,27 @@ pub fn duplicate(&self) -> io::Result<TcpListener> {
} }
pub fn set_ttl(&self, _: u32) -> io::Result<()> { pub fn set_ttl(&self, _: u32) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn ttl(&self) -> io::Result<u32> { pub fn ttl(&self) -> io::Result<u32> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_only_v6(&self, _: bool) -> io::Result<()> { pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn only_v6(&self) -> io::Result<bool> { pub fn only_v6(&self) -> io::Result<bool> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn take_error(&self) -> io::Result<Option<io::Error>> { pub fn take_error(&self) -> io::Result<Option<io::Error>> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
} }
...@@ -273,127 +281,127 @@ fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result { ...@@ -273,127 +281,127 @@ fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
impl UdpSocket { impl UdpSocket {
pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> { pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn peer_addr(&self) -> io::Result<SocketAddr> { pub fn peer_addr(&self) -> io::Result<SocketAddr> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn socket_addr(&self) -> io::Result<SocketAddr> { pub fn socket_addr(&self) -> io::Result<SocketAddr> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> { pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> { pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> { pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn duplicate(&self) -> io::Result<UdpSocket> { pub fn duplicate(&self) -> io::Result<UdpSocket> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> { pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> { pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn read_timeout(&self) -> io::Result<Option<Duration>> { pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn write_timeout(&self) -> io::Result<Option<Duration>> { pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_broadcast(&self, _: bool) -> io::Result<()> { pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn broadcast(&self) -> io::Result<bool> { pub fn broadcast(&self) -> io::Result<bool> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> { pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn multicast_loop_v4(&self) -> io::Result<bool> { pub fn multicast_loop_v4(&self) -> io::Result<bool> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> { pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn multicast_ttl_v4(&self) -> io::Result<u32> { pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> { pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn multicast_loop_v6(&self) -> io::Result<bool> { pub fn multicast_loop_v6(&self) -> io::Result<bool> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> { pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> { pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_ttl(&self, _: u32) -> io::Result<()> { pub fn set_ttl(&self, _: u32) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn ttl(&self) -> io::Result<u32> { pub fn ttl(&self) -> io::Result<u32> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn take_error(&self) -> io::Result<Option<io::Error>> { pub fn take_error(&self) -> io::Result<Option<io::Error>> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> { pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> { pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn send(&self, _: &[u8]) -> io::Result<usize> { pub fn send(&self, _: &[u8]) -> io::Result<usize> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
Err(io::Error::new(ErrorKind::Other, "not supported")) Err(io::Error::new_const(ErrorKind::Other, &"not supported"))
} }
} }
......
...@@ -40,7 +40,7 @@ fn write(&mut self, data: &[u8]) -> io::Result<usize> { ...@@ -40,7 +40,7 @@ fn write(&mut self, data: &[u8]) -> io::Result<usize> {
unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) } unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) }
if len < 0 { if len < 0 {
Err(io::Error::new(io::ErrorKind::Other, "Stdout is not able to print")) Err(io::Error::new_const(io::ErrorKind::Other, &"Stdout is not able to print"))
} else { } else {
Ok(len as usize) Ok(len as usize)
} }
...@@ -52,7 +52,7 @@ fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> { ...@@ -52,7 +52,7 @@ fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> {
unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) } unsafe { len = abi::write(1, data.as_ptr() as *const u8, data.len()) }
if len < 0 { if len < 0 {
Err(io::Error::new(io::ErrorKind::Other, "Stdout is not able to print")) Err(io::Error::new_const(io::ErrorKind::Other, &"Stdout is not able to print"))
} else { } else {
Ok(len as usize) Ok(len as usize)
} }
...@@ -81,7 +81,7 @@ fn write(&mut self, data: &[u8]) -> io::Result<usize> { ...@@ -81,7 +81,7 @@ fn write(&mut self, data: &[u8]) -> io::Result<usize> {
unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) } unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) }
if len < 0 { if len < 0 {
Err(io::Error::new(io::ErrorKind::Other, "Stderr is not able to print")) Err(io::Error::new_const(io::ErrorKind::Other, &"Stderr is not able to print"))
} else { } else {
Ok(len as usize) Ok(len as usize)
} }
...@@ -93,7 +93,7 @@ fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> { ...@@ -93,7 +93,7 @@ fn write_vectored(&mut self, data: &[IoSlice<'_>]) -> io::Result<usize> {
unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) } unsafe { len = abi::write(2, data.as_ptr() as *const u8, data.len()) }
if len < 0 { if len < 0 {
Err(io::Error::new(io::ErrorKind::Other, "Stderr is not able to print")) Err(io::Error::new_const(io::ErrorKind::Other, &"Stderr is not able to print"))
} else { } else {
Ok(len as usize) Ok(len as usize)
} }
......
...@@ -37,7 +37,7 @@ pub unsafe fn new_with_coreid( ...@@ -37,7 +37,7 @@ pub unsafe fn new_with_coreid(
// The thread failed to start and as a result p was not consumed. Therefore, it is // The thread failed to start and as a result p was not consumed. Therefore, it is
// safe to reconstruct the box so that it gets deallocated. // safe to reconstruct the box so that it gets deallocated.
drop(Box::from_raw(p)); drop(Box::from_raw(p));
Err(io::Error::new(io::ErrorKind::Other, "Unable to create thread!")) Err(io::Error::new_const(io::ErrorKind::Other, &"Unable to create thread!"))
} else { } else {
Ok(Thread { tid: tid }) Ok(Thread { tid: tid })
}; };
......
...@@ -50,7 +50,7 @@ pub fn unsupported<T>() -> crate::io::Result<T> { ...@@ -50,7 +50,7 @@ pub fn unsupported<T>() -> crate::io::Result<T> {
} }
pub fn unsupported_err() -> crate::io::Error { pub fn unsupported_err() -> crate::io::Error {
crate::io::Error::new(ErrorKind::Other, "operation not supported on SGX yet") crate::io::Error::new_const(ErrorKind::Other, &"operation not supported on SGX yet")
} }
/// This function is used to implement various functions that doesn't exist, /// This function is used to implement various functions that doesn't exist,
...@@ -61,9 +61,9 @@ pub fn unsupported_err() -> crate::io::Error { ...@@ -61,9 +61,9 @@ pub fn unsupported_err() -> crate::io::Error {
pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> { pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> {
static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false); static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false);
if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) { if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) {
Err(crate::io::Error::new( Err(crate::io::Error::new_const(
ErrorKind::Other, ErrorKind::Other,
"operation can't be trusted to have any effect on SGX", &"operation can't be trusted to have any effect on SGX",
)) ))
} else { } else {
Ok(v) Ok(v)
......
...@@ -97,9 +97,9 @@ pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> { ...@@ -97,9 +97,9 @@ pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream> { pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream> {
if dur == Duration::default() { if dur == Duration::default() {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
Self::connect(Ok(addr)) // FIXME: ignoring timeout Self::connect(Ok(addr)) // FIXME: ignoring timeout
...@@ -108,9 +108,9 @@ pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream ...@@ -108,9 +108,9 @@ pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
match dur { match dur {
Some(dur) if dur == Duration::default() => { Some(dur) if dur == Duration::default() => {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
_ => sgx_ineffective(()), _ => sgx_ineffective(()),
...@@ -120,9 +120,9 @@ pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> { ...@@ -120,9 +120,9 @@ pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> { pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
match dur { match dur {
Some(dur) if dur == Duration::default() => { Some(dur) if dur == Duration::default() => {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
_ => sgx_ineffective(()), _ => sgx_ineffective(()),
......
...@@ -96,7 +96,7 @@ pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> { ...@@ -96,7 +96,7 @@ pub fn ftruncate64(fd: c_int, size: u64) -> io::Result<()> {
Some(f) => cvt_r(|| f(fd, size as i64)).map(drop), Some(f) => cvt_r(|| f(fd, size as i64)).map(drop),
None => { None => {
if size > i32::MAX as u64 { if size > i32::MAX as u64 {
Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot truncate >2GB")) Err(io::Error::new_const(io::ErrorKind::InvalidInput, &"cannot truncate >2GB"))
} else { } else {
cvt_r(|| ftruncate(fd, size as i32)).map(drop) cvt_r(|| ftruncate(fd, size as i32)).map(drop)
} }
...@@ -123,7 +123,7 @@ pub unsafe fn cvt_pread64( ...@@ -123,7 +123,7 @@ pub unsafe fn cvt_pread64(
if let Ok(o) = offset.try_into() { if let Ok(o) = offset.try_into() {
cvt(pread(fd, buf, count, o)) cvt(pread(fd, buf, count, o))
} else { } else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot pread >2GB")) Err(io::Error::new_const(io::ErrorKind::InvalidInput, &"cannot pread >2GB"))
} }
}) })
} }
...@@ -141,7 +141,7 @@ pub unsafe fn cvt_pwrite64( ...@@ -141,7 +141,7 @@ pub unsafe fn cvt_pwrite64(
if let Ok(o) = offset.try_into() { if let Ok(o) = offset.try_into() {
cvt(pwrite(fd, buf, count, o)) cvt(pwrite(fd, buf, count, o))
} else { } else {
Err(io::Error::new(io::ErrorKind::InvalidInput, "cannot pwrite >2GB")) Err(io::Error::new_const(io::ErrorKind::InvalidInput, &"cannot pwrite >2GB"))
} }
}) })
} }
......
...@@ -109,7 +109,7 @@ fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> { ...@@ -109,7 +109,7 @@ fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
} }
} }
if !buf.is_empty() { if !buf.is_empty() {
Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")) Err(io::Error::new_const(io::ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
} else { } else {
Ok(()) Ok(())
} }
...@@ -191,9 +191,9 @@ fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> { ...@@ -191,9 +191,9 @@ fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
while !buf.is_empty() { while !buf.is_empty() {
match self.write_at(buf, offset) { match self.write_at(buf, offset) {
Ok(0) => { Ok(0) => {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::WriteZero, io::ErrorKind::WriteZero,
"failed to write whole buffer", &"failed to write whole buffer",
)); ));
} }
Ok(n) => { Ok(n) => {
......
...@@ -29,16 +29,16 @@ pub(super) unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, ...@@ -29,16 +29,16 @@ pub(super) unsafe fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un,
let bytes = path.as_os_str().as_bytes(); let bytes = path.as_os_str().as_bytes();
if bytes.contains(&0) { if bytes.contains(&0) {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"paths may not contain interior null bytes", &"paths may not contain interior null bytes",
)); ));
} }
if bytes.len() >= addr.sun_path.len() { if bytes.len() >= addr.sun_path.len() {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"path must be shorter than SUN_LEN", &"path must be shorter than SUN_LEN",
)); ));
} }
for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) { for (dst, src) in addr.sun_path.iter_mut().zip(bytes.iter()) {
...@@ -118,9 +118,9 @@ pub(super) fn from_parts( ...@@ -118,9 +118,9 @@ pub(super) fn from_parts(
// linux returns zero bytes of address // linux returns zero bytes of address
len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address len = sun_path_offset(&addr) as libc::socklen_t; // i.e., zero-length address
} else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t { } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"file descriptor did not correspond to a Unix socket", &"file descriptor did not correspond to a Unix socket",
)); ));
} }
......
...@@ -357,17 +357,17 @@ pub fn created(&self) -> io::Result<SystemTime> { ...@@ -357,17 +357,17 @@ pub fn created(&self) -> io::Result<SystemTime> {
tv_nsec: ext.stx_btime.tv_nsec as _, tv_nsec: ext.stx_btime.tv_nsec as _,
})) }))
} else { } else {
Err(io::Error::new( Err(io::Error::new_const(
io::ErrorKind::Other, io::ErrorKind::Other,
"creation time is not available for the filesystem", &"creation time is not available for the filesystem",
)) ))
}; };
} }
} }
Err(io::Error::new( Err(io::Error::new_const(
io::ErrorKind::Other, io::ErrorKind::Other,
"creation time is not available on this platform \ &"creation time is not available on this platform \
currently", currently",
)) ))
} }
...@@ -1156,9 +1156,9 @@ fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> ...@@ -1156,9 +1156,9 @@ fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)>
let reader = File::open(from)?; let reader = File::open(from)?;
let metadata = reader.metadata()?; let metadata = reader.metadata()?;
if !metadata.is_file() { if !metadata.is_file() {
return Err(Error::new( return Err(Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"the source path is not an existing regular file", &"the source path is not an existing regular file",
)); ));
} }
Ok((reader, metadata)) Ok((reader, metadata))
......
macro_rules! unimpl { macro_rules! unimpl {
() => { () => {
return Err(io::Error::new(io::ErrorKind::Other, "No networking available on L4Re.")); return Err(io::Error::new_const(io::ErrorKind::Other, &"No networking available on L4Re."));
}; };
} }
......
...@@ -139,9 +139,9 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul ...@@ -139,9 +139,9 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul
let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 }; let mut pollfd = libc::pollfd { fd: self.0.raw(), events: libc::POLLOUT, revents: 0 };
if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
...@@ -150,7 +150,7 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul ...@@ -150,7 +150,7 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul
loop { loop {
let elapsed = start.elapsed(); let elapsed = start.elapsed();
if elapsed >= timeout { if elapsed >= timeout {
return Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")); return Err(io::Error::new_const(io::ErrorKind::TimedOut, &"connection timed out"));
} }
let timeout = timeout - elapsed; let timeout = timeout - elapsed;
...@@ -177,7 +177,10 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul ...@@ -177,7 +177,10 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul
// for POLLHUP rather than read readiness // for POLLHUP rather than read readiness
if pollfd.revents & libc::POLLHUP != 0 { if pollfd.revents & libc::POLLHUP != 0 {
let e = self.take_error()?.unwrap_or_else(|| { let e = self.take_error()?.unwrap_or_else(|| {
io::Error::new(io::ErrorKind::Other, "no error set after POLLHUP") io::Error::new_const(
io::ErrorKind::Other,
&"no error set after POLLHUP",
)
}); });
return Err(e); return Err(e);
} }
...@@ -318,9 +321,9 @@ pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Resul ...@@ -318,9 +321,9 @@ pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Resul
let timeout = match dur { let timeout = match dur {
Some(dur) => { Some(dur) => {
if dur.as_secs() == 0 && dur.subsec_nanos() == 0 { if dur.as_secs() == 0 && dur.subsec_nanos() == 0 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
......
...@@ -287,9 +287,9 @@ fn sysctl() -> io::Result<PathBuf> { ...@@ -287,9 +287,9 @@ fn sysctl() -> io::Result<PathBuf> {
0, 0,
))?; ))?;
if path_len <= 1 { if path_len <= 1 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::Other, io::ErrorKind::Other,
"KERN_PROC_PATHNAME sysctl returned zero-length string", &"KERN_PROC_PATHNAME sysctl returned zero-length string",
)); ));
} }
let mut path: Vec<u8> = Vec::with_capacity(path_len); let mut path: Vec<u8> = Vec::with_capacity(path_len);
...@@ -310,9 +310,9 @@ fn procfs() -> io::Result<PathBuf> { ...@@ -310,9 +310,9 @@ fn procfs() -> io::Result<PathBuf> {
if curproc_exe.is_file() { if curproc_exe.is_file() {
return crate::fs::read_link(curproc_exe); return crate::fs::read_link(curproc_exe);
} }
Err(io::Error::new( Err(io::Error::new_const(
io::ErrorKind::Other, io::ErrorKind::Other,
"/proc/curproc/exe doesn't point to regular file.", &"/proc/curproc/exe doesn't point to regular file.",
)) ))
} }
sysctl().or_else(|_| procfs()) sysctl().or_else(|_| procfs())
...@@ -329,7 +329,7 @@ pub fn current_exe() -> io::Result<PathBuf> { ...@@ -329,7 +329,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(io::Error::new(io::ErrorKind::Other, "no current exe available")); return Err(io::Error::new_const(io::ErrorKind::Other, &"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'/') {
...@@ -343,9 +343,9 @@ pub fn current_exe() -> io::Result<PathBuf> { ...@@ -343,9 +343,9 @@ pub fn current_exe() -> io::Result<PathBuf> {
#[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))] #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))]
pub fn current_exe() -> io::Result<PathBuf> { pub fn current_exe() -> io::Result<PathBuf> {
match crate::fs::read_link("/proc/self/exe") { match crate::fs::read_link("/proc/self/exe") {
Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::Error::new( Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::Error::new_const(
io::ErrorKind::Other, io::ErrorKind::Other,
"no /proc/self/exe available. Is /proc mounted?", &"no /proc/self/exe available. Is /proc mounted?",
)), )),
other => other, other => other,
} }
...@@ -431,7 +431,7 @@ fn _get_next_image_info( ...@@ -431,7 +431,7 @@ fn _get_next_image_info(
_get_next_image_info(0, &mut cookie, &mut info, mem::size_of::<image_info>() as i32); _get_next_image_info(0, &mut cookie, &mut info, mem::size_of::<image_info>() as i32);
if result != 0 { if result != 0 {
use crate::io::ErrorKind; use crate::io::ErrorKind;
Err(io::Error::new(ErrorKind::Other, "Error getting executable path")) Err(io::Error::new_const(ErrorKind::Other, &"Error getting executable path"))
} else { } else {
let name = CStr::from_ptr(info.name.as_ptr()).to_bytes(); let name = CStr::from_ptr(info.name.as_ptr()).to_bytes();
Ok(PathBuf::from(OsStr::from_bytes(name))) Ok(PathBuf::from(OsStr::from_bytes(name)))
...@@ -447,7 +447,7 @@ pub fn current_exe() -> io::Result<PathBuf> { ...@@ -447,7 +447,7 @@ pub fn current_exe() -> io::Result<PathBuf> {
#[cfg(any(target_os = "fuchsia", target_os = "l4re"))] #[cfg(any(target_os = "fuchsia", target_os = "l4re"))]
pub fn current_exe() -> io::Result<PathBuf> { pub fn current_exe() -> io::Result<PathBuf> {
use crate::io::ErrorKind; use crate::io::ErrorKind;
Err(io::Error::new(ErrorKind::Other, "Not yet implemented!")) Err(io::Error::new_const(ErrorKind::Other, &"Not yet implemented!"))
} }
#[cfg(target_os = "vxworks")] #[cfg(target_os = "vxworks")]
......
...@@ -22,9 +22,9 @@ pub fn spawn( ...@@ -22,9 +22,9 @@ pub fn spawn(
let envp = self.capture_env(); let envp = self.capture_env();
if self.saw_nul() { if self.saw_nul() {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"nul byte found in provided data", &"nul byte found in provided data",
)); ));
} }
...@@ -37,7 +37,10 @@ pub fn spawn( ...@@ -37,7 +37,10 @@ pub fn spawn(
pub fn exec(&mut self, default: Stdio) -> io::Error { pub fn exec(&mut self, default: Stdio) -> io::Error {
if self.saw_nul() { if self.saw_nul() {
return io::Error::new(io::ErrorKind::InvalidInput, "nul byte found in provided data"); return io::Error::new_const(
io::ErrorKind::InvalidInput,
&"nul byte found in provided data",
);
} }
match self.setup_io(default, true) { match self.setup_io(default, true) {
...@@ -182,9 +185,9 @@ pub fn wait(&mut self) -> io::Result<ExitStatus> { ...@@ -182,9 +185,9 @@ pub fn wait(&mut self) -> io::Result<ExitStatus> {
))?; ))?;
} }
if actual != 1 { if actual != 1 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
"Failed to get exit status of process", &"Failed to get exit status of process",
)); ));
} }
Ok(ExitStatus(proc_info.return_code)) Ok(ExitStatus(proc_info.return_code))
...@@ -220,9 +223,9 @@ pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> { ...@@ -220,9 +223,9 @@ pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
))?; ))?;
} }
if actual != 1 { if actual != 1 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
"Failed to get exit status of process", &"Failed to get exit status of process",
)); ));
} }
Ok(Some(ExitStatus(proc_info.return_code))) Ok(Some(ExitStatus(proc_info.return_code)))
......
...@@ -28,7 +28,10 @@ pub fn spawn( ...@@ -28,7 +28,10 @@ pub fn spawn(
let envp = self.capture_env(); let envp = self.capture_env();
if self.saw_nul() { if self.saw_nul() {
return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")); return Err(io::Error::new_const(
ErrorKind::InvalidInput,
&"nul byte found in provided data",
));
} }
let (ours, theirs) = self.setup_io(default, needs_stdin)?; let (ours, theirs) = self.setup_io(default, needs_stdin)?;
...@@ -118,7 +121,10 @@ pub fn exec(&mut self, default: Stdio) -> io::Error { ...@@ -118,7 +121,10 @@ pub fn exec(&mut self, default: Stdio) -> io::Error {
let envp = self.capture_env(); let envp = self.capture_env();
if self.saw_nul() { if self.saw_nul() {
return io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"); return io::Error::new_const(
ErrorKind::InvalidInput,
&"nul byte found in provided data",
);
} }
match self.setup_io(default, true) { match self.setup_io(default, true) {
...@@ -442,9 +448,9 @@ pub fn kill(&mut self) -> io::Result<()> { ...@@ -442,9 +448,9 @@ pub fn kill(&mut self) -> io::Result<()> {
// and used for another process, and we probably shouldn't be killing // and used for another process, and we probably shouldn't be killing
// random processes, so just return an error. // random processes, so just return an error.
if self.status.is_some() { if self.status.is_some() {
Err(Error::new( Err(Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"invalid argument: can't kill an exited process", &"invalid argument: can't kill an exited process",
)) ))
} else { } else {
cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop) cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
......
...@@ -18,7 +18,7 @@ pub fn unsupported<T>() -> std_io::Result<T> { ...@@ -18,7 +18,7 @@ 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::Other, "operation not supported on this platform") std_io::Error::new_const(std_io::ErrorKind::Other, &"operation not supported on this platform")
} }
pub fn decode_error_kind(_code: i32) -> crate::io::ErrorKind { pub fn decode_error_kind(_code: i32) -> crate::io::ErrorKind {
......
...@@ -80,11 +80,11 @@ pub fn getenv(_: &OsStr) -> io::Result<Option<OsString>> { ...@@ -80,11 +80,11 @@ pub fn getenv(_: &OsStr) -> io::Result<Option<OsString>> {
} }
pub fn setenv(_: &OsStr, _: &OsStr) -> io::Result<()> { pub fn setenv(_: &OsStr, _: &OsStr) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Other, "cannot set env vars on this platform")) Err(io::Error::new_const(io::ErrorKind::Other, &"cannot set env vars on this platform"))
} }
pub fn unsetenv(_: &OsStr) -> io::Result<()> { pub fn unsetenv(_: &OsStr) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Other, "cannot unset env vars on this platform")) Err(io::Error::new_const(io::ErrorKind::Other, &"cannot unset env vars on this platform"))
} }
pub fn temp_dir() -> PathBuf { pub fn temp_dir() -> PathBuf {
......
...@@ -22,7 +22,10 @@ pub fn spawn( ...@@ -22,7 +22,10 @@ pub fn spawn(
let envp = self.capture_env(); let envp = self.capture_env();
if self.saw_nul() { if self.saw_nul() {
return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")); return Err(io::Error::new_const(
ErrorKind::InvalidInput,
&"nul byte found in provided data",
));
} }
let (ours, theirs) = self.setup_io(default, needs_stdin)?; let (ours, theirs) = self.setup_io(default, needs_stdin)?;
let mut p = Process { pid: 0, status: None }; let mut p = Process { pid: 0, status: None };
...@@ -134,9 +137,9 @@ pub fn kill(&mut self) -> io::Result<()> { ...@@ -134,9 +137,9 @@ pub fn kill(&mut self) -> io::Result<()> {
// and used for another process, and we probably shouldn't be killing // and used for another process, and we probably shouldn't be killing
// random processes, so just return an error. // random processes, so just return an error.
if self.status.is_some() { if self.status.is_some() {
Err(Error::new( Err(Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"invalid argument: can't kill an exited process", &"invalid argument: can't kill an exited process",
)) ))
} else { } else {
cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop) cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
......
...@@ -85,7 +85,7 @@ fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> { ...@@ -85,7 +85,7 @@ fn read_exact_at(&self, mut buf: &mut [u8], mut offset: u64) -> io::Result<()> {
} }
} }
if !buf.is_empty() { if !buf.is_empty() {
Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")) Err(io::Error::new_const(io::ErrorKind::UnexpectedEof, &"failed to fill whole buffer"))
} else { } else {
Ok(()) Ok(())
} }
...@@ -151,9 +151,9 @@ fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> { ...@@ -151,9 +151,9 @@ fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> io::Result<()> {
while !buf.is_empty() { while !buf.is_empty() {
match self.write_at(buf, offset) { match self.write_at(buf, offset) {
Ok(0) => { Ok(0) => {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::WriteZero, io::ErrorKind::WriteZero,
"failed to write whole buffer", &"failed to write whole buffer",
)); ));
} }
Ok(n) => { Ok(n) => {
...@@ -532,5 +532,5 @@ pub fn symlink_path<P: AsRef<Path>, U: AsRef<Path>>(old_path: P, new_path: U) -> ...@@ -532,5 +532,5 @@ pub fn symlink_path<P: AsRef<Path>, U: AsRef<Path>>(old_path: P, new_path: U) ->
} }
fn osstr2str(f: &OsStr) -> io::Result<&str> { fn osstr2str(f: &OsStr) -> io::Result<&str> {
f.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "input must be utf-8")) f.to_str().ok_or_else(|| io::Error::new_const(io::ErrorKind::Other, &"input must be utf-8"))
} }
...@@ -670,7 +670,7 @@ pub fn __wasilibc_find_relpath( ...@@ -670,7 +670,7 @@ pub fn __wasilibc_find_relpath(
} }
pub fn osstr2str(f: &OsStr) -> io::Result<&str> { pub fn osstr2str(f: &OsStr) -> io::Result<&str> {
f.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::Other, "input must be utf-8")) f.to_str().ok_or_else(|| io::Error::new_const(io::ErrorKind::Other, &"input must be utf-8"))
} }
pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
......
...@@ -513,9 +513,9 @@ fn readlink(&self) -> io::Result<PathBuf> { ...@@ -513,9 +513,9 @@ fn readlink(&self) -> io::Result<PathBuf> {
) )
} }
_ => { _ => {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::Other, io::ErrorKind::Other,
"Unsupported reparse point type", &"Unsupported reparse point type",
)); ));
} }
}; };
...@@ -802,7 +802,7 @@ pub fn link(original: &Path, link: &Path) -> io::Result<()> { ...@@ -802,7 +802,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(io::Error::new(io::ErrorKind::Other, "hard link are not supported on UWP")); return Err(io::Error::new_const(io::ErrorKind::Other, &"hard link are not supported on UWP"));
} }
pub fn stat(path: &Path) -> io::Result<FileAttr> { pub fn stat(path: &Path) -> io::Result<FileAttr> {
......
...@@ -130,9 +130,9 @@ pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> { ...@@ -130,9 +130,9 @@ pub fn to_u16s<S: AsRef<OsStr>>(s: S) -> crate::io::Result<Vec<u16>> {
fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> { fn inner(s: &OsStr) -> crate::io::Result<Vec<u16>> {
let mut maybe_result: Vec<u16> = s.encode_wide().collect(); let mut maybe_result: Vec<u16> = s.encode_wide().collect();
if unrolled_find_u16s(0, &maybe_result).is_some() { if unrolled_find_u16s(0, &maybe_result).is_some() {
return Err(crate::io::Error::new( return Err(crate::io::Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"strings passed to WinAPI cannot contain NULs", &"strings passed to WinAPI cannot contain NULs",
)); ));
} }
maybe_result.push(0); maybe_result.push(0);
......
...@@ -136,9 +136,9 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul ...@@ -136,9 +136,9 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul
} }
if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 { if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
...@@ -164,7 +164,7 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul ...@@ -164,7 +164,7 @@ pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Resul
unsafe { cvt(c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout))? }; unsafe { cvt(c::select(1, ptr::null_mut(), &mut writefds, &mut errorfds, &timeout))? };
match n { match n {
0 => Err(io::Error::new(io::ErrorKind::TimedOut, "connection timed out")), 0 => Err(io::Error::new_const(io::ErrorKind::TimedOut, &"connection timed out")),
_ => { _ => {
if writefds.fd_count != 1 { if writefds.fd_count != 1 {
if let Some(e) = self.take_error()? { if let Some(e) = self.take_error()? {
...@@ -339,9 +339,9 @@ pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()> ...@@ -339,9 +339,9 @@ pub fn set_timeout(&self, dur: Option<Duration>, kind: c_int) -> io::Result<()>
Some(dur) => { Some(dur) => {
let timeout = sys::dur2timeout(dur); let timeout = sys::dur2timeout(dur);
if timeout == 0 { if timeout == 0 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout", &"cannot set a 0 duration timeout",
)); ));
} }
timeout timeout
...@@ -370,7 +370,7 @@ fn set_no_inherit(&self) -> io::Result<()> { ...@@ -370,7 +370,7 @@ fn set_no_inherit(&self) -> io::Result<()> {
#[cfg(target_vendor = "uwp")] #[cfg(target_vendor = "uwp")]
fn set_no_inherit(&self) -> io::Result<()> { fn set_no_inherit(&self) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Other, "Unavailable on UWP")) Err(io::Error::new_const(io::ErrorKind::Other, &"Unavailable on UWP"))
} }
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
......
...@@ -62,7 +62,7 @@ fn as_ref(&self) -> &OsStr { ...@@ -62,7 +62,7 @@ fn as_ref(&self) -> &OsStr {
fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> { fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
if str.as_ref().encode_wide().any(|b| b == 0) { if str.as_ref().encode_wide().any(|b| b == 0) {
Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data")) Err(io::Error::new_const(ErrorKind::InvalidInput, &"nul byte found in provided data"))
} else { } else {
Ok(str) Ok(str)
} }
......
...@@ -68,9 +68,9 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> { ...@@ -68,9 +68,9 @@ fn write(handle_id: c::DWORD, data: &[u8]) -> io::Result<usize> {
let utf8 = match str::from_utf8(&data[..len]) { let utf8 = match str::from_utf8(&data[..len]) {
Ok(s) => s, Ok(s) => s,
Err(ref e) if e.valid_up_to() == 0 => { Err(ref e) if e.valid_up_to() == 0 => {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
"Windows stdio in console mode does not support writing non-UTF-8 byte sequences", &"Windows stdio in console mode does not support writing non-UTF-8 byte sequences",
)); ));
} }
Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(), Err(e) => str::from_utf8(&data[..e.valid_up_to()]).unwrap(),
...@@ -149,9 +149,9 @@ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { ...@@ -149,9 +149,9 @@ fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if buf.len() == 0 { if buf.len() == 0 {
return Ok(0); return Ok(0);
} else if buf.len() < 4 { } else if buf.len() < 4 {
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
"Windows stdin in console mode does not support a buffer too small to \ &"Windows stdin in console mode does not support a buffer too small to \
guarantee holding one arbitrary UTF-8 character (4 bytes)", guarantee holding one arbitrary UTF-8 character (4 bytes)",
)); ));
} }
...@@ -243,9 +243,9 @@ fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> { ...@@ -243,9 +243,9 @@ fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
} }
Err(_) => { Err(_) => {
// We can't really do any better than forget all data and return an error. // We can't really do any better than forget all data and return an error.
return Err(io::Error::new( return Err(io::Error::new_const(
io::ErrorKind::InvalidData, io::ErrorKind::InvalidData,
"Windows stdin in console mode does not support non-UTF-16 input; \ &"Windows stdin in console mode does not support non-UTF-16 input; \
encountered unpaired surrogate", encountered unpaired surrogate",
)); ));
} }
......
...@@ -9,9 +9,9 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> { ...@@ -9,9 +9,9 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
let metadata = reader.metadata()?; let metadata = reader.metadata()?;
if !metadata.is_file() { if !metadata.is_file() {
return Err(Error::new( return Err(Error::new_const(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"the source path is not an existing regular file", &"the source path is not an existing regular file",
)); ));
} }
......
...@@ -108,7 +108,7 @@ pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result ...@@ -108,7 +108,7 @@ pub fn sockaddr_to_addr(storage: &c::sockaddr_storage, len: usize) -> io::Result
*(storage as *const _ as *const c::sockaddr_in6) *(storage as *const _ as *const c::sockaddr_in6)
}))) })))
} }
_ => Err(Error::new(ErrorKind::InvalidInput, "invalid argument")), _ => Err(Error::new_const(ErrorKind::InvalidInput, &"invalid argument")),
} }
} }
...@@ -171,7 +171,7 @@ fn try_from(s: &str) -> io::Result<LookupHost> { ...@@ -171,7 +171,7 @@ fn try_from(s: &str) -> io::Result<LookupHost> {
($e:expr, $msg:expr) => { ($e:expr, $msg:expr) => {
match $e { match $e {
Some(r) => r, Some(r) => r,
None => return Err(io::Error::new(io::ErrorKind::InvalidInput, $msg)), None => return Err(io::Error::new_const(io::ErrorKind::InvalidInput, &$msg)),
} }
}; };
} }
......
...@@ -64,7 +64,7 @@ struct SYSTEM_INFO { ...@@ -64,7 +64,7 @@ struct SYSTEM_INFO {
sysinfo.dwNumberOfProcessors as usize sysinfo.dwNumberOfProcessors as usize
}; };
match res { match res {
0 => Err(io::Error::new(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")), 0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }), cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
} }
} }
...@@ -81,7 +81,7 @@ struct SYSTEM_INFO { ...@@ -81,7 +81,7 @@ struct SYSTEM_INFO {
fn available_concurrency_internal() -> io::Result<NonZeroUsize> { fn available_concurrency_internal() -> io::Result<NonZeroUsize> {
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } { match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
-1 => Err(io::Error::last_os_error()), -1 => Err(io::Error::last_os_error()),
0 => Err(io::Error::new(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")), 0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }), cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }),
} }
} }
...@@ -114,7 +114,7 @@ fn available_concurrency_internal() -> io::Result<NonZeroUsize> { ...@@ -114,7 +114,7 @@ fn available_concurrency_internal() -> io::Result<NonZeroUsize> {
if res == -1 { if res == -1 {
return Err(io::Error::last_os_error()); return Err(io::Error::last_os_error());
} else if cpus == 0 { } else if cpus == 0 {
return Err(io::Error::new(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")); return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
} }
} }
Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }) Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
...@@ -142,7 +142,7 @@ fn available_concurrency_internal() -> io::Result<NonZeroUsize> { ...@@ -142,7 +142,7 @@ fn available_concurrency_internal() -> io::Result<NonZeroUsize> {
if res == -1 { if res == -1 {
return Err(io::Error::last_os_error()); return Err(io::Error::last_os_error());
} else if cpus == 0 { } else if cpus == 0 {
return Err(io::Error::new(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")); return Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"));
} }
Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) }) Ok(unsafe { NonZeroUsize::new_unchecked(cpus as usize) })
...@@ -150,7 +150,7 @@ fn available_concurrency_internal() -> io::Result<NonZeroUsize> { ...@@ -150,7 +150,7 @@ fn available_concurrency_internal() -> io::Result<NonZeroUsize> {
} else { } else {
// FIXME: implement on vxWorks, Redox, HermitCore, Haiku, l4re // FIXME: implement on vxWorks, Redox, HermitCore, Haiku, l4re
fn available_concurrency_internal() -> io::Result<NonZeroUsize> { fn available_concurrency_internal() -> io::Result<NonZeroUsize> {
Err(io::Error::new(io::ErrorKind::NotFound, "The number of hardware threads is not known for the target platform")) Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform"))
} }
} }
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册