Skip to content

Commit 9cbe994

Browse files
committed
Add more tests for io::Error packing, and fix some comments that weren't quite accurate anymore
1 parent a17a896 commit 9cbe994

File tree

3 files changed

+101
-16
lines changed

3 files changed

+101
-16
lines changed

library/std/src/io/error.rs

+4
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,9 @@ impl fmt::Debug for Error {
7676
}
7777
}
7878

79+
// Only derive debug in tests, to make sure it
80+
// doesn't accidentally get printed.
81+
#[cfg_attr(test, derive(Debug))]
7982
enum ErrorData<C> {
8083
Os(i32),
8184
Simple(ErrorKind),
@@ -98,6 +101,7 @@ enum ErrorData<C> {
98101
// if `error/repr_bitpacked.rs` is in use — for the unpacked repr it doesn't
99102
// matter at all)
100103
#[repr(align(4))]
104+
#[derive(Debug)]
101105
pub(crate) struct SimpleMessage {
102106
kind: ErrorKind,
103107
message: &'static str,

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

+31-9
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
//! a more clever manner than `rustc`'s default layout algorithm would).
77
//!
88
//! Conceptually, it stores the same data as the "unpacked" equivalent we use on
9-
//! other targets. Specifically, you can imagine it as an optimized following
10-
//! data (which is equivalent to what's stored by `repr_unpacked::Repr`, e.g.
11-
//! `super::ErrorData<Box<Custom>>`):
9+
//! other targets. Specifically, you can imagine it as an optimized version of
10+
//! the following enum (which is roughly equivalent to what's stored by
11+
//! `repr_unpacked::Repr`, e.g. `super::ErrorData<Box<Custom>>`):
1212
//!
1313
//! ```ignore (exposition-only)
1414
//! enum ErrorData {
@@ -135,7 +135,16 @@ impl Repr {
135135
// (rather than `ptr::wrapping_add`), but it's unclear this would give
136136
// any benefit, so we just use `wrapping_add` instead.
137137
let tagged = p.wrapping_add(TAG_CUSTOM).cast::<()>();
138-
// Safety: the above safety comment also means the result can't be null.
138+
// Safety: `TAG_CUSTOM + p` is the same as `TAG_CUSTOM | p`,
139+
// because `p`'s alignment means it isn't allowed to have any of the
140+
// `TAG_BITS` set (you can verify that addition and bitwise-or are the
141+
// same when the operands have no bits in common using a truth table).
142+
//
143+
// Then, `TAG_CUSTOM | p` is not zero, as that would require
144+
// `TAG_CUSTOM` and `p` both be zero, and neither is (as `p` came from a
145+
// box, and `TAG_CUSTOM` just... isn't zero -- it's `0b01`). Therefore,
146+
// `TAG_CUSTOM + p` isn't zero and so `tagged` can't be, and the
147+
// `new_unchecked` is safe.
139148
let res = Self(unsafe { NonNull::new_unchecked(tagged) });
140149
// quickly smoke-check we encoded the right thing (This generally will
141150
// only run in libstd's tests, unless the user uses -Zbuild-std)
@@ -342,12 +351,25 @@ static_assert!(@usize_eq: size_of::<NonNull<()>>(), size_of::<usize>());
342351
static_assert!(@usize_eq: size_of::<&'static SimpleMessage>(), 8);
343352
static_assert!(@usize_eq: size_of::<Box<Custom>>(), 8);
344353

345-
// And they must have >= 4 byte alignment.
346-
static_assert!(align_of::<SimpleMessage>() >= 4);
347-
static_assert!(align_of::<Custom>() >= 4);
354+
static_assert!((TAG_MASK + 1).is_power_of_two());
355+
// And they must have sufficient alignment.
356+
static_assert!(align_of::<SimpleMessage>() >= TAG_MASK + 1);
357+
static_assert!(align_of::<Custom>() >= TAG_MASK + 1);
358+
359+
static_assert!(@usize_eq: (TAG_MASK & TAG_SIMPLE_MESSAGE), TAG_SIMPLE_MESSAGE);
360+
static_assert!(@usize_eq: (TAG_MASK & TAG_CUSTOM), TAG_CUSTOM);
361+
static_assert!(@usize_eq: (TAG_MASK & TAG_OS), TAG_OS);
362+
static_assert!(@usize_eq: (TAG_MASK & TAG_SIMPLE), TAG_SIMPLE);
348363

349-
// This is obviously true (`TAG_CUSTOM` is `0b01`), but our implementation of
350-
// `Repr::new_custom` and such would be wrong if it were not, so we check.
364+
// This is obviously true (`TAG_CUSTOM` is `0b01`), but in `Repr::new_custom` we
365+
// offset a pointer by this value, and expect it to both be within the same
366+
// object, and to not wrap around the address space. See the comment in that
367+
// function for further details.
368+
//
369+
// Actually, at the moment we use `ptr::wrapping_add`, not `ptr::add`, so this
370+
// check isn't needed for that one, although the assertion that we don't
371+
// actually wrap around in that wrapping_add does simplify the safety reasoning
372+
// elsewhere considerably.
351373
static_assert!(size_of::<Custom>() >= TAG_CUSTOM);
352374

353375
// These two store a payload which is allowed to be zero, so they must be

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

+66-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
use super::{const_io_error, Custom, Error, ErrorKind, Repr};
1+
use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr};
2+
use crate::assert_matches::assert_matches;
23
use crate::error;
34
use crate::fmt;
45
use crate::mem::size_of;
@@ -69,16 +70,74 @@ fn test_const() {
6970
}
7071

7172
#[test]
72-
fn test_error_packing() {
73+
fn test_os_packing() {
7374
for code in -20i32..20i32 {
7475
let e = Error::from_raw_os_error(code);
7576
assert_eq!(e.raw_os_error(), Some(code));
77+
assert_matches!(
78+
e.repr.data(),
79+
ErrorData::Os(c) if c == code,
80+
);
7681
}
82+
}
83+
84+
#[test]
85+
fn test_errorkind_packing() {
7786
assert_eq!(Error::from(ErrorKind::NotFound).kind(), ErrorKind::NotFound);
87+
assert_eq!(Error::from(ErrorKind::PermissionDenied).kind(), ErrorKind::PermissionDenied);
7888
assert_eq!(Error::from(ErrorKind::Uncategorized).kind(), ErrorKind::Uncategorized);
79-
assert_eq!(Error::from(ErrorKind::NotFound).kind(), ErrorKind::NotFound);
80-
assert_eq!(Error::from(ErrorKind::Uncategorized).kind(), ErrorKind::Uncategorized);
81-
let dunno = const_io_error!(ErrorKind::Uncategorized, "dunno");
82-
assert_eq!(dunno.kind(), ErrorKind::Uncategorized);
83-
assert!(format!("{:?}", dunno).contains("dunno"))
89+
// Check that the innards look like like what we want.
90+
assert_matches!(
91+
Error::from(ErrorKind::OutOfMemory).repr.data(),
92+
ErrorData::Simple(ErrorKind::OutOfMemory),
93+
);
94+
}
95+
96+
#[test]
97+
fn test_simple_message_packing() {
98+
use super::{ErrorKind::*, SimpleMessage};
99+
macro_rules! check_simple_msg {
100+
($err:expr, $kind:ident, $msg:literal) => {{
101+
let e = &$err;
102+
// Check that the public api is right.
103+
assert_eq!(e.kind(), $kind);
104+
assert!(format!("{:?}", e).contains($msg));
105+
// and we got what we expected
106+
assert_matches!(
107+
e.repr.data(),
108+
ErrorData::SimpleMessage(SimpleMessage { kind: $kind, message: $msg })
109+
);
110+
}};
111+
}
112+
113+
let not_static = const_io_error!(Uncategorized, "not a constant!");
114+
check_simple_msg!(not_static, Uncategorized, "not a constant!");
115+
116+
const CONST: Error = const_io_error!(NotFound, "definitely a constant!");
117+
check_simple_msg!(CONST, NotFound, "definitely a constant!");
118+
119+
static STATIC: Error = const_io_error!(BrokenPipe, "a constant, sort of!");
120+
check_simple_msg!(STATIC, BrokenPipe, "a constant, sort of!");
121+
}
122+
123+
#[derive(Debug, PartialEq)]
124+
struct Bojji(bool);
125+
impl error::Error for Bojji {}
126+
impl fmt::Display for Bojji {
127+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128+
write!(f, "ah! {:?}", self)
129+
}
130+
}
131+
132+
#[test]
133+
fn test_custom_error_packing() {
134+
use super::Custom;
135+
let test = Error::new(ErrorKind::Uncategorized, Bojji(true));
136+
assert_matches!(
137+
test.repr.data(),
138+
ErrorData::Custom(Custom {
139+
kind: ErrorKind::Uncategorized,
140+
error,
141+
}) if error.downcast_ref::<Bojji>().as_deref() == Some(&Bojji(true)),
142+
);
84143
}

0 commit comments

Comments
 (0)