Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

std: promote debug_assert to assert #98696

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions library/std/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ impl System {
new_layout: Layout,
zeroed: bool,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert!(
assert!(
new_layout.size() >= old_layout.size(),
"`new_layout.size()` must be greater than or equal to `old_layout.size()`"
);
Expand Down Expand Up @@ -246,7 +246,7 @@ unsafe impl Allocator for System {
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert!(
assert!(
new_layout.size() <= old_layout.size(),
"`new_layout.size()` must be smaller than or equal to `old_layout.size()`"
);
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/io/buffered/bufreader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,7 @@ impl<R: Read> BufRead for BufReader<R> {
// Branch using `>=` instead of the more correct `==`
// to tell the compiler that the pos..cap slice is always valid.
if self.pos >= self.cap {
debug_assert!(self.pos == self.cap);
assert!(self.pos == self.cap, "unexpected end of buffer");

let mut readbuf = ReadBuf::uninit(&mut self.buf);

Expand Down
4 changes: 2 additions & 2 deletions library/std/src/io/buffered/bufwriter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ impl<W: Write> BufWriter<W> {
// i.e., that input buffer length is less than or equal to spare capacity.
#[inline]
unsafe fn write_to_buffer_unchecked(&mut self, buf: &[u8]) {
debug_assert!(buf.len() <= self.spare_capacity());
assert!(buf.len() <= self.spare_capacity(), "unexpected write operation");
let old_len = self.buf.len();
let buf_len = buf.len();
let src = buf.as_ptr();
Expand Down Expand Up @@ -610,7 +610,7 @@ impl<W: Write> Write for BufWriter<W> {
} else {
return Ok(0);
};
debug_assert!(total_written != 0);
assert!(total_written != 0, "unexpected `total_written` value: {:?}", total_written);
for buf in iter {
if buf.len() <= self.spare_capacity() {
// SAFETY: safe by above conditional.
Expand Down
4 changes: 2 additions & 2 deletions library/std/src/io/cursor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ fn reserve_and_pad<A: Allocator>(
// realise the `reserve` it does can be eliminated. So we do it manually
// to eliminate that extra branch
let spare = vec.spare_capacity_mut();
debug_assert!(spare.len() >= diff);
assert!(spare.len() >= diff, "unexpected allocated capacity");
// Safety: we have allocated enough capacity for this.
// And we are only writing, not reading
unsafe {
Expand All @@ -444,7 +444,7 @@ unsafe fn vec_write_unchecked<A>(pos: usize, vec: &mut Vec<u8, A>, buf: &[u8]) -
where
A: Allocator,
{
debug_assert!(vec.capacity() >= pos + buf.len());
assert!(vec.capacity() >= pos + buf.len(), "unexpected write out of bound");
vec.as_mut_ptr().add(pos).copy_from(buf.as_ptr(), buf.len());
pos + buf.len()
}
Expand Down
10 changes: 5 additions & 5 deletions library/std/src/io/error/repr_bitpacked.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ impl Repr {
let p = Box::into_raw(b).cast::<u8>();
// Should only be possible if an allocator handed out a pointer with
// wrong alignment.
debug_assert_eq!(p.addr() & TAG_MASK, 0);
assert_eq!(p.addr() & TAG_MASK, 0);
// Note: We know `TAG_CUSTOM <= size_of::<Custom>()` (static_assert at
// end of file), and both the start and end of the expression must be
// valid without address space wraparound due to `Box`'s semantics.
Expand All @@ -167,7 +167,7 @@ impl Repr {
let res = Self(unsafe { NonNull::new_unchecked(tagged) }, PhantomData);
// quickly smoke-check we encoded the right thing (This generally will
// only run in libstd's tests, unless the user uses -Zbuild-std)
debug_assert!(matches!(res.data(), ErrorData::Custom(_)), "repr(custom) encoding failed");
assert!(matches!(res.data(), ErrorData::Custom(_)), "repr(custom) encoding failed");
res
}

Expand All @@ -178,7 +178,7 @@ impl Repr {
let res = Self(unsafe { NonNull::new_unchecked(ptr::invalid_mut(utagged)) }, PhantomData);
// quickly smoke-check we encoded the right thing (This generally will
// only run in libstd's tests, unless the user uses -Zbuild-std)
debug_assert!(
assert!(
matches!(res.data(), ErrorData::Os(c) if c == code),
"repr(os) encoding failed for {code}"
);
Expand All @@ -192,7 +192,7 @@ impl Repr {
let res = Self(unsafe { NonNull::new_unchecked(ptr::invalid_mut(utagged)) }, PhantomData);
// quickly smoke-check we encoded the right thing (This generally will
// only run in libstd's tests, unless the user uses -Zbuild-std)
debug_assert!(
assert!(
matches!(res.data(), ErrorData::Simple(k) if k == kind),
"repr(simple) encoding failed {:?}",
kind,
Expand Down Expand Up @@ -256,7 +256,7 @@ where
TAG_SIMPLE => {
let kind_bits = (bits >> 32) as u32;
let kind = kind_from_prim(kind_bits).unwrap_or_else(|| {
debug_assert!(false, "Invalid io::error::Repr bits: `Repr({:#018x})`", bits);
assert!(false, "Invalid io::error::Repr bits: `Repr({:#018x})`", bits);
// This means the `ptr` passed in was not valid, which violates
// the unsafe contract of `decode_repr`.
//
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/os/windows/io/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ impl IntoRawSocket for OwnedSocket {
impl FromRawSocket for OwnedSocket {
#[inline]
unsafe fn from_raw_socket(socket: RawSocket) -> Self {
debug_assert_ne!(socket, c::INVALID_SOCKET as RawSocket);
assert_ne!(socket, c::INVALID_SOCKET as RawSocket);
Self { socket }
}
}
Expand Down
16 changes: 10 additions & 6 deletions library/std/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -749,7 +749,7 @@ impl<'a> Components<'a> {
// parse a component from the left, saying how many bytes to consume to
// remove the component
fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
debug_assert!(self.front == State::Body);
assert!(self.front == State::Body, "unexpected component during parsing: {:?}", self.front);
let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
None => (0, self.path),
Some(i) => (1, &self.path[..i]),
Expand All @@ -760,7 +760,7 @@ impl<'a> Components<'a> {
// parse a component from the right, saying how many bytes to consume to
// remove the component
fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
debug_assert!(self.back == State::Body);
assert!(self.back == State::Body, "unexpected component during parsing: {:?}", self.back);
let start = self.len_before_body();
let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) {
None => (0, &self.path[start..]),
Expand Down Expand Up @@ -893,7 +893,11 @@ impl<'a> Iterator for Components<'a> {
match self.front {
State::Prefix if self.prefix_len() > 0 => {
self.front = State::StartDir;
debug_assert!(self.prefix_len() <= self.path.len());
assert!(
self.prefix_len() <= self.path.len(),
"unexpected prefix len: {:?}",
self.prefix_len()
);
let raw = &self.path[..self.prefix_len()];
self.path = &self.path[self.prefix_len()..];
return Some(Component::Prefix(PrefixComponent {
Expand All @@ -907,15 +911,15 @@ impl<'a> Iterator for Components<'a> {
State::StartDir => {
self.front = State::Body;
if self.has_physical_root {
debug_assert!(!self.path.is_empty());
assert!(!self.path.is_empty(), "unexpected path value");
self.path = &self.path[1..];
return Some(Component::RootDir);
} else if let Some(p) = self.prefix {
if p.has_implicit_root() && !p.is_verbatim() {
return Some(Component::RootDir);
}
} else if self.include_cur_dir() {
debug_assert!(!self.path.is_empty());
assert!(!self.path.is_empty(), "unexpected path value");
self.path = &self.path[1..];
return Some(Component::CurDir);
}
Expand Down Expand Up @@ -1406,7 +1410,7 @@ impl PathBuf {
fn _set_file_name(&mut self, file_name: &OsStr) {
if self.file_name().is_some() {
let popped = self.pop();
debug_assert!(popped);
assert!(popped, "unexpected error during unwrap file name");
}
self.push(file_name);
}
Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sync/mpsc/oneshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl<T> Packet<T> {
}
} else {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst) != EMPTY);
assert!(self.state.load(Ordering::SeqCst) != EMPTY, "packet state not empity");
}
} else {
// drop the signal token, since we never blocked
Expand Down
6 changes: 3 additions & 3 deletions library/std/src/sync/once_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ impl<T> OnceLock<T> {
}
self.initialize(f)?;

debug_assert!(self.is_initialized());
assert!(self.is_initialized(), "bad initialization");

// SAFETY: The inner value has been initialized
Ok(unsafe { self.get_unchecked() })
Expand Down Expand Up @@ -369,15 +369,15 @@ impl<T> OnceLock<T> {
///
/// The value must be initialized
unsafe fn get_unchecked(&self) -> &T {
debug_assert!(self.is_initialized());
assert!(self.is_initialized(), "value not initialized");
(&*self.value.get()).assume_init_ref()
}

/// # Safety
///
/// The value must be initialized
unsafe fn get_unchecked_mut(&mut self) -> &mut T {
debug_assert!(self.is_initialized());
assert!(self.is_initialized(), "value not initialized");
(&mut *self.value.get()).assume_init_mut()
}
}
Expand Down
6 changes: 3 additions & 3 deletions library/std/src/sys/itron/condvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ mod waiter_queue {
// Zeroness of `Waiter::task` indicates whether the `Waiter` is
// linked to a queue or not. This invariant is important for
// the correctness.
debug_assert_ne!(task, 0);
assert_ne!(task, 0);

Self { task, priority, prev: None, next: None }
}
Expand All @@ -182,8 +182,8 @@ mod waiter_queue {
unsafe {
let waiter = waiter_ptr.as_mut();

debug_assert!(waiter.prev.is_none());
debug_assert!(waiter.next.is_none());
assert!(waiter.prev.is_none());
assert!(waiter.next.is_none());

if let Some(head) = &mut self.head {
// Find the insertion position and insert `waiter`
Expand Down
17 changes: 10 additions & 7 deletions library/std/src/sys/itron/spin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ impl<T> SpinMutex<T> {
let _guard;
if unsafe { abi::sns_dsp() } == 0 {
let er = unsafe { abi::dis_dsp() };
debug_assert!(er >= 0);
assert!(er >= 0, "unexpected error during abi::dis_dsp(): {:?}", ret);

// Wait until the current processor acquires a lock.
while self.locked.swap(true, Ordering::Acquire) {}
Expand Down Expand Up @@ -95,11 +95,11 @@ impl<T> SpinIdOnceCell<T> {
/// Assign the content without checking if it's already initialized or
/// being initialized.
pub unsafe fn set_unchecked(&self, (id, extra): (abi::ID, T)) {
debug_assert!(self.get().is_none());
assert!(self.get().is_none());

// Assumption: A positive `abi::ID` fits in `usize`.
debug_assert!(id >= 0);
debug_assert!(usize::try_from(id).is_ok());
assert!(id >= 0, "negative `abi::ID` received: {:?}", id);
assert!(usize::try_from(id).is_ok(), "fails to conver `abi::ID` to `usize`: {:?}", id);
let id = id as usize;

unsafe { *self.extra.get() = MaybeUninit::new(extra) };
Expand All @@ -124,7 +124,7 @@ impl<T> SpinIdOnceCell<T> {

self.initialize(f)?;

debug_assert!(self.get().is_some());
assert!(self.get().is_some());

// Safety: The inner value has been initialized
Ok(unsafe { self.get_unchecked() })
Expand All @@ -139,8 +139,11 @@ impl<T> SpinIdOnceCell<T> {
let (initialized_id, initialized_extra) = f()?;

// Assumption: A positive `abi::ID` fits in `usize`.
debug_assert!(initialized_id >= 0);
debug_assert!(usize::try_from(initialized_id).is_ok());
assert!(initialized_id >= 0, "negative `abi::ID`");
assert!(
usize::try_from(initialized_id).is_ok(),
"fails to conver `abi::ID` to `usize`: {:?}"
);
let initialized_id = initialized_id as usize;

// Store the initialized contents. Use the release ordering to
Expand Down
18 changes: 15 additions & 3 deletions library/std/src/sys/itron/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,21 @@ impl Thread {
// Get the current task ID. Panicking here would cause a resource leak,
// so just abort on failure.
let current_task = task::current_task_id_aborting();
debug_assert!(usize::try_from(current_task).is_ok());
debug_assert_ne!(current_task as usize, LIFECYCLE_INIT);
debug_assert_ne!(current_task as usize, LIFECYCLE_DETACHED);
assert!(
usize::try_from(current_task).is_ok(),
"fails to convert `current_task_id` to `usize`: {:?}",
current_task
);
assert_ne!(
current_task as usize, LIFECYCLE_INIT,
"`current_task` is not in a valid state: {:?}",
current_task
);
assert_ne!(
current_task as usize, LIFECYCLE_DETACHED,
"`current_task` is not in a valid state: {:?}",
current_task
);

let current_task = current_task as usize;

Expand Down
2 changes: 1 addition & 1 deletion library/std/src/sys/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,7 +636,7 @@ impl Iterator for ReadDir {
impl Drop for Dir {
fn drop(&mut self) {
let r = unsafe { libc::closedir(self.0) };
debug_assert_eq!(r, 0);
assert!(r == 0 || r == libc::EINTR, "unexpected error during closedir: {:?}", r);
}
}

Expand Down
8 changes: 6 additions & 2 deletions library/std/src/sys/unix/locks/futex_rwlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,11 @@ impl RwLock {

// It's impossible for a reader to be waiting on a read-locked RwLock,
// except if there is also a writer waiting.
debug_assert!(!has_readers_waiting(state) || has_writers_waiting(state));
assert!(
!has_readers_waiting(state) || has_writers_waiting(state),
"invalid read state: {:?}",
state
);

// Wake up a writer if we were the last reader and there's a writer waiting.
if is_unlocked(state) && has_writers_waiting(state) {
Expand Down Expand Up @@ -161,7 +165,7 @@ impl RwLock {
pub unsafe fn write_unlock(&self) {
let state = self.state.fetch_sub(WRITE_LOCKED, Release) - WRITE_LOCKED;

debug_assert!(is_unlocked(state));
assert!(is_unlocked(state), "trying to write while the state is invalid: {:?}", state);

if has_writers_waiting(state) || has_readers_waiting(state) {
self.wake_writer_or_readers(state);
Expand Down
Loading