Skip to content
/ rust Public
forked from rust-lang/rust

Commit 293c0c6

Browse files
authored
Rollup merge of rust-lang#133449 - joboet:io_const_error, r=tgross35
std: expose `const_io_error!` as `const_error!` ACP: rust-lang/libs-team#205 Tracking issue: rust-lang#133448 Probably best reviewed commit-by-commit, the first one does the API change, the second does the mass-rename.
2 parents 6935c94 + 57d5c6a commit 293c0c6

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+248
-264
lines changed

library/std/src/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3020,7 +3020,7 @@ impl DirBuilder {
30203020
match path.parent() {
30213021
Some(p) => self.create_dir_all(p)?,
30223022
None => {
3023-
return Err(io::const_io_error!(
3023+
return Err(io::const_error!(
30243024
io::ErrorKind::Uncategorized,
30253025
"failed to create whole tree",
30263026
));

library/std/src/io/buffered/bufreader/buffer.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ impl Buffer {
4141
match Box::try_new_uninit_slice(capacity) {
4242
Ok(buf) => Ok(Self { buf, pos: 0, filled: 0, initialized: 0 }),
4343
Err(_) => {
44-
Err(io::const_io_error!(ErrorKind::OutOfMemory, "failed to allocate read buffer"))
44+
Err(io::const_error!(ErrorKind::OutOfMemory, "failed to allocate read buffer"))
4545
}
4646
}
4747
}

library/std/src/io/buffered/bufwriter.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ impl<W: Write> BufWriter<W> {
9696

9797
pub(crate) fn try_new_buffer() -> io::Result<Vec<u8>> {
9898
Vec::try_with_capacity(DEFAULT_BUF_SIZE).map_err(|_| {
99-
io::const_io_error!(ErrorKind::OutOfMemory, "failed to allocate write buffer")
99+
io::const_error!(ErrorKind::OutOfMemory, "failed to allocate write buffer")
100100
})
101101
}
102102

@@ -238,7 +238,7 @@ impl<W: ?Sized + Write> BufWriter<W> {
238238

239239
match r {
240240
Ok(0) => {
241-
return Err(io::const_io_error!(
241+
return Err(io::const_error!(
242242
ErrorKind::WriteZero,
243243
"failed to write the buffered data",
244244
));

library/std/src/io/cursor.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ where
304304
self.pos = n;
305305
Ok(self.pos)
306306
}
307-
None => Err(io::const_io_error!(
307+
None => Err(io::const_error!(
308308
ErrorKind::InvalidInput,
309309
"invalid seek to a negative or overflowing position",
310310
)),
@@ -446,7 +446,7 @@ fn reserve_and_pad<A: Allocator>(
446446
buf_len: usize,
447447
) -> io::Result<usize> {
448448
let pos: usize = (*pos_mut).try_into().map_err(|_| {
449-
io::const_io_error!(
449+
io::const_error!(
450450
ErrorKind::InvalidInput,
451451
"cursor position exceeds maximum possible vector length",
452452
)

library/std/src/io/error.rs

+40-27
Original file line numberDiff line numberDiff line change
@@ -76,31 +76,31 @@ impl fmt::Debug for Error {
7676
#[allow(dead_code)]
7777
impl Error {
7878
pub(crate) const INVALID_UTF8: Self =
79-
const_io_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8");
79+
const_error!(ErrorKind::InvalidData, "stream did not contain valid UTF-8");
8080

8181
pub(crate) const READ_EXACT_EOF: Self =
82-
const_io_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer");
82+
const_error!(ErrorKind::UnexpectedEof, "failed to fill whole buffer");
8383

84-
pub(crate) const UNKNOWN_THREAD_COUNT: Self = const_io_error!(
84+
pub(crate) const UNKNOWN_THREAD_COUNT: Self = const_error!(
8585
ErrorKind::NotFound,
8686
"The number of hardware threads is not known for the target platform"
8787
);
8888

8989
pub(crate) const UNSUPPORTED_PLATFORM: Self =
90-
const_io_error!(ErrorKind::Unsupported, "operation not supported on this platform");
90+
const_error!(ErrorKind::Unsupported, "operation not supported on this platform");
9191

9292
pub(crate) const WRITE_ALL_EOF: Self =
93-
const_io_error!(ErrorKind::WriteZero, "failed to write whole buffer");
93+
const_error!(ErrorKind::WriteZero, "failed to write whole buffer");
9494

9595
pub(crate) const ZERO_TIMEOUT: Self =
96-
const_io_error!(ErrorKind::InvalidInput, "cannot set a 0 duration timeout");
96+
const_error!(ErrorKind::InvalidInput, "cannot set a 0 duration timeout");
9797
}
9898

9999
#[stable(feature = "rust1", since = "1.0.0")]
100100
impl From<alloc::ffi::NulError> for Error {
101101
/// Converts a [`alloc::ffi::NulError`] into a [`Error`].
102102
fn from(_: alloc::ffi::NulError) -> Error {
103-
const_io_error!(ErrorKind::InvalidInput, "data provided contains a nul byte")
103+
const_error!(ErrorKind::InvalidInput, "data provided contains a nul byte")
104104
}
105105
}
106106

@@ -151,27 +151,38 @@ pub type RawOsError = sys::RawOsError;
151151
// (For the sake of being explicit: the alignment requirement here only matters
152152
// if `error/repr_bitpacked.rs` is in use — for the unpacked repr it doesn't
153153
// matter at all)
154+
#[doc(hidden)]
155+
#[unstable(feature = "io_const_error_internals", issue = "none")]
154156
#[repr(align(4))]
155157
#[derive(Debug)]
156-
pub(crate) struct SimpleMessage {
157-
kind: ErrorKind,
158-
message: &'static str,
159-
}
160-
161-
impl SimpleMessage {
162-
pub(crate) const fn new(kind: ErrorKind, message: &'static str) -> Self {
163-
Self { kind, message }
164-
}
158+
pub struct SimpleMessage {
159+
pub kind: ErrorKind,
160+
pub message: &'static str,
165161
}
166162

167-
/// Creates and returns an `io::Error` for a given `ErrorKind` and constant
168-
/// message. This doesn't allocate.
169-
pub(crate) macro const_io_error($kind:expr, $message:expr $(,)?) {
170-
$crate::io::error::Error::from_static_message({
171-
const MESSAGE_DATA: $crate::io::error::SimpleMessage =
172-
$crate::io::error::SimpleMessage::new($kind, $message);
173-
&MESSAGE_DATA
174-
})
163+
/// Creates a new I/O error from a known kind of error and a string literal.
164+
///
165+
/// Contrary to [`Error::new`], this macro does not allocate and can be used in
166+
/// `const` contexts.
167+
///
168+
/// # Example
169+
/// ```
170+
/// #![feature(io_const_error)]
171+
/// use std::io::{const_error, Error, ErrorKind};
172+
///
173+
/// const FAIL: Error = const_error!(ErrorKind::Unsupported, "tried something that never works");
174+
///
175+
/// fn not_here() -> Result<(), Error> {
176+
/// Err(FAIL)
177+
/// }
178+
/// ```
179+
#[rustc_macro_transparency = "semitransparent"]
180+
#[unstable(feature = "io_const_error", issue = "133448")]
181+
#[allow_internal_unstable(hint_must_use, io_const_error_internals)]
182+
pub macro const_error($kind:expr, $message:expr $(,)?) {
183+
$crate::hint::must_use($crate::io::Error::from_static_message(
184+
const { &$crate::io::SimpleMessage { kind: $kind, message: $message } },
185+
))
175186
}
176187

177188
// As with `SimpleMessage`: `#[repr(align(4))]` here is just because
@@ -592,13 +603,15 @@ impl Error {
592603
///
593604
/// This function does not allocate.
594605
///
595-
/// You should not use this directly, and instead use the `const_io_error!`
596-
/// macro: `io::const_io_error!(ErrorKind::Something, "some_message")`.
606+
/// You should not use this directly, and instead use the `const_error!`
607+
/// macro: `io::const_error!(ErrorKind::Something, "some_message")`.
597608
///
598609
/// This function should maybe change to `from_static_message<const MSG: &'static
599610
/// str>(kind: ErrorKind)` in the future, when const generics allow that.
600611
#[inline]
601-
pub(crate) const fn from_static_message(msg: &'static SimpleMessage) -> Error {
612+
#[doc(hidden)]
613+
#[unstable(feature = "io_const_error_internals", issue = "none")]
614+
pub const fn from_static_message(msg: &'static SimpleMessage) -> Error {
602615
Self { repr: Repr::new_simple_message(msg) }
603616
}
604617

library/std/src/io/error/tests.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage, const_io_error};
1+
use super::{Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage, const_error};
22
use crate::assert_matches::assert_matches;
33
use crate::mem::size_of;
44
use crate::sys::decode_error_kind;
@@ -60,7 +60,7 @@ fn test_downcasting() {
6060

6161
#[test]
6262
fn test_const() {
63-
const E: Error = const_io_error!(ErrorKind::NotFound, "hello");
63+
const E: Error = const_error!(ErrorKind::NotFound, "hello");
6464

6565
assert_eq!(E.kind(), ErrorKind::NotFound);
6666
assert_eq!(E.to_string(), "hello");
@@ -110,13 +110,13 @@ fn test_simple_message_packing() {
110110
}};
111111
}
112112

113-
let not_static = const_io_error!(Uncategorized, "not a constant!");
113+
let not_static = const_error!(Uncategorized, "not a constant!");
114114
check_simple_msg!(not_static, Uncategorized, "not a constant!");
115115

116-
const CONST: Error = const_io_error!(NotFound, "definitely a constant!");
116+
const CONST: Error = const_error!(NotFound, "definitely a constant!");
117117
check_simple_msg!(CONST, NotFound, "definitely a constant!");
118118

119-
static STATIC: Error = const_io_error!(BrokenPipe, "a constant, sort of!");
119+
static STATIC: Error = const_error!(BrokenPipe, "a constant, sort of!");
120120
check_simple_msg!(STATIC, BrokenPipe, "a constant, sort of!");
121121
}
122122

library/std/src/io/mod.rs

+5-2
Original file line numberDiff line numberDiff line change
@@ -301,12 +301,15 @@ mod tests;
301301
pub use core::io::{BorrowedBuf, BorrowedCursor};
302302
use core::slice::memchr;
303303

304-
pub(crate) use error::const_io_error;
305-
306304
#[stable(feature = "bufwriter_into_parts", since = "1.56.0")]
307305
pub use self::buffered::WriterPanicked;
308306
#[unstable(feature = "raw_os_error_ty", issue = "107792")]
309307
pub use self::error::RawOsError;
308+
#[doc(hidden)]
309+
#[unstable(feature = "io_const_error_internals", issue = "none")]
310+
pub use self::error::SimpleMessage;
311+
#[unstable(feature = "io_const_error", issue = "133448")]
312+
pub use self::error::const_error;
310313
#[stable(feature = "is_terminal", since = "1.70.0")]
311314
pub use self::stdio::IsTerminal;
312315
pub(crate) use self::stdio::attempt_print_to_stderr;

library/std/src/io/tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -225,12 +225,12 @@ fn take_eof() {
225225

226226
impl Read for R {
227227
fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
228-
Err(io::const_io_error!(io::ErrorKind::Other, ""))
228+
Err(io::const_error!(io::ErrorKind::Other, ""))
229229
}
230230
}
231231
impl BufRead for R {
232232
fn fill_buf(&mut self) -> io::Result<&[u8]> {
233-
Err(io::const_io_error!(io::ErrorKind::Other, ""))
233+
Err(io::const_error!(io::ErrorKind::Other, ""))
234234
}
235235
fn consume(&mut self, _amt: usize) {}
236236
}

library/std/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,7 @@
340340
#![feature(fmt_internals)]
341341
#![feature(hasher_prefixfree_extras)]
342342
#![feature(hashmap_internals)]
343+
#![feature(hint_must_use)]
343344
#![feature(ip)]
344345
#![feature(lazy_get)]
345346
#![feature(maybe_uninit_slice)]
@@ -410,6 +411,7 @@
410411
// Only for const-ness:
411412
// tidy-alphabetical-start
412413
#![feature(const_collections_with_hasher)]
414+
#![feature(io_const_error)]
413415
#![feature(thread_local_internals)]
414416
// tidy-alphabetical-end
415417
//

library/std/src/net/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,6 @@ where
8484
}
8585
}
8686
Err(last_err.unwrap_or_else(|| {
87-
io::const_io_error!(ErrorKind::InvalidInput, "could not resolve to any addresses")
87+
io::const_error!(ErrorKind::InvalidInput, "could not resolve to any addresses")
8888
}))
8989
}

library/std/src/net/udp.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -203,9 +203,7 @@ impl UdpSocket {
203203
pub fn send_to<A: ToSocketAddrs>(&self, buf: &[u8], addr: A) -> io::Result<usize> {
204204
match addr.to_socket_addrs()?.next() {
205205
Some(addr) => self.0.send_to(buf, &addr),
206-
None => {
207-
Err(io::const_io_error!(ErrorKind::InvalidInput, "no addresses to send data to"))
208-
}
206+
None => Err(io::const_error!(ErrorKind::InvalidInput, "no addresses to send data to")),
209207
}
210208
}
211209

library/std/src/os/unix/net/addr.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@ pub(super) fn sockaddr_un(path: &Path) -> io::Result<(libc::sockaddr_un, libc::s
3030
let bytes = path.as_os_str().as_bytes();
3131

3232
if bytes.contains(&0) {
33-
return Err(io::const_io_error!(
33+
return Err(io::const_error!(
3434
io::ErrorKind::InvalidInput,
3535
"paths must not contain interior null bytes",
3636
));
3737
}
3838

3939
if bytes.len() >= addr.sun_path.len() {
40-
return Err(io::const_io_error!(
40+
return Err(io::const_error!(
4141
io::ErrorKind::InvalidInput,
4242
"path must be shorter than SUN_LEN",
4343
));
@@ -119,7 +119,7 @@ impl SocketAddr {
119119
// linux returns zero bytes of address
120120
len = SUN_PATH_OFFSET as libc::socklen_t; // i.e., zero-length address
121121
} else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t {
122-
return Err(io::const_io_error!(
122+
return Err(io::const_error!(
123123
io::ErrorKind::InvalidInput,
124124
"file descriptor did not correspond to a Unix socket",
125125
));
@@ -273,7 +273,7 @@ impl linux_ext::addr::SocketAddrExt for SocketAddr {
273273
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
274274

275275
if name.len() + 1 > addr.sun_path.len() {
276-
return Err(io::const_io_error!(
276+
return Err(io::const_error!(
277277
io::ErrorKind::InvalidInput,
278278
"abstract socket name must be shorter than SUN_LEN",
279279
));

library/std/src/os/wasi/fs.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ impl FileExt for fs::File {
261261
a if a == wasi::ADVICE_DONTNEED.raw() => wasi::ADVICE_DONTNEED,
262262
a if a == wasi::ADVICE_NOREUSE.raw() => wasi::ADVICE_NOREUSE,
263263
_ => {
264-
return Err(io::const_io_error!(
264+
return Err(io::const_error!(
265265
io::ErrorKind::InvalidInput,
266266
"invalid parameter 'advice'",
267267
));
@@ -560,6 +560,5 @@ pub fn symlink_path<P: AsRef<Path>, U: AsRef<Path>>(old_path: P, new_path: U) ->
560560
}
561561

562562
fn osstr2str(f: &OsStr) -> io::Result<&str> {
563-
f.to_str()
564-
.ok_or_else(|| io::const_io_error!(io::ErrorKind::Uncategorized, "input must be utf-8"))
563+
f.to_str().ok_or_else(|| io::const_error!(io::ErrorKind::Uncategorized, "input must be utf-8"))
565564
}

library/std/src/os/windows/io/socket.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ impl OwnedSocket {
101101

102102
#[cfg(target_vendor = "uwp")]
103103
pub(crate) fn set_no_inherit(&self) -> io::Result<()> {
104-
Err(io::const_io_error!(io::ErrorKind::Unsupported, "Unavailable on UWP"))
104+
Err(io::const_error!(io::ErrorKind::Unsupported, "Unavailable on UWP"))
105105
}
106106
}
107107

library/std/src/path.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3581,7 +3581,7 @@ impl Error for StripPrefixError {
35813581
pub fn absolute<P: AsRef<Path>>(path: P) -> io::Result<PathBuf> {
35823582
let path = path.as_ref();
35833583
if path.as_os_str().is_empty() {
3584-
Err(io::const_io_error!(io::ErrorKind::InvalidInput, "cannot make an empty path absolute",))
3584+
Err(io::const_error!(io::ErrorKind::InvalidInput, "cannot make an empty path absolute",))
35853585
} else {
35863586
sys::path::absolute(path)
35873587
}

library/std/src/sys/pal/common/small_c_string.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ const MAX_STACK_ALLOCATION: usize = 384;
1111
const MAX_STACK_ALLOCATION: usize = 32;
1212

1313
const NUL_ERR: io::Error =
14-
io::const_io_error!(io::ErrorKind::InvalidInput, "file name contained an unexpected NUL byte");
14+
io::const_error!(io::ErrorKind::InvalidInput, "file name contained an unexpected NUL byte");
1515

1616
#[inline]
1717
pub fn run_path_with_cstr<T>(path: &Path, f: &dyn Fn(&CStr) -> io::Result<T>) -> io::Result<T> {

library/std/src/sys/pal/hermit/fs.rs

+7-9
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ impl OpenOptions {
294294
(false, _, true) => Ok(O_WRONLY | O_APPEND),
295295
(true, _, true) => Ok(O_RDWR | O_APPEND),
296296
(false, false, false) => {
297-
Err(io::const_io_error!(ErrorKind::InvalidInput, "invalid access mode"))
297+
Err(io::const_error!(ErrorKind::InvalidInput, "invalid access mode"))
298298
}
299299
}
300300
}
@@ -304,18 +304,16 @@ impl OpenOptions {
304304
(true, false) => {}
305305
(false, false) => {
306306
if self.truncate || self.create || self.create_new {
307-
return Err(io::const_io_error!(
308-
ErrorKind::InvalidInput,
309-
"invalid creation mode",
310-
));
307+
return Err(
308+
io::const_error!(ErrorKind::InvalidInput, "invalid creation mode",),
309+
);
311310
}
312311
}
313312
(_, true) => {
314313
if self.truncate && !self.create_new {
315-
return Err(io::const_io_error!(
316-
ErrorKind::InvalidInput,
317-
"invalid creation mode",
318-
));
314+
return Err(
315+
io::const_error!(ErrorKind::InvalidInput, "invalid creation mode",),
316+
);
319317
}
320318
}
321319
}

library/std/src/sys/pal/hermit/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ pub fn unsupported<T>() -> crate::io::Result<T> {
4242
}
4343

4444
pub fn unsupported_err() -> crate::io::Error {
45-
crate::io::const_io_error!(
45+
crate::io::const_error!(
4646
crate::io::ErrorKind::Unsupported,
4747
"operation not supported on HermitCore yet",
4848
)

0 commit comments

Comments
 (0)