From d35bda6429b0a3a758ddcd899e954043584f1071 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 26 Jan 2021 22:11:12 +0300 Subject: Make always-assert crate reusable --- crates/stdx/Cargo.toml | 1 + crates/stdx/src/lib.rs | 2 +- crates/stdx/src/macros.rs | 51 ----------------------------------------------- 3 files changed, 2 insertions(+), 52 deletions(-) (limited to 'crates/stdx') diff --git a/crates/stdx/Cargo.toml b/crates/stdx/Cargo.toml index c47e8d0a8..5866c0a28 100644 --- a/crates/stdx/Cargo.toml +++ b/crates/stdx/Cargo.toml @@ -11,6 +11,7 @@ doctest = false [dependencies] backtrace = { version = "0.3.44", optional = true } +always-assert = { version = "0.1.1", features = ["log"] } # Think twice before adding anything here [features] diff --git a/crates/stdx/src/lib.rs b/crates/stdx/src/lib.rs index d42817078..d26be4853 100644 --- a/crates/stdx/src/lib.rs +++ b/crates/stdx/src/lib.rs @@ -4,7 +4,7 @@ use std::{cmp::Ordering, ops, process, time::Instant}; mod macros; pub mod panic_context; -pub use crate::macros::{on_assert_failure, set_assert_hook}; +pub use always_assert::{always, never}; #[inline(always)] pub fn is_ci() -> bool { diff --git a/crates/stdx/src/macros.rs b/crates/stdx/src/macros.rs index 4f5c6100d..d91fc690c 100644 --- a/crates/stdx/src/macros.rs +++ b/crates/stdx/src/macros.rs @@ -1,9 +1,5 @@ //! Convenience macros. -use std::{ - fmt, mem, panic, - sync::atomic::{AtomicUsize, Ordering::SeqCst}, -}; #[macro_export] macro_rules! eprintln { ($($tt:tt)*) => {{ @@ -49,50 +45,3 @@ macro_rules! impl_from { )* } } - -/// A version of `assert!` macro which allows to handle an assertion failure. -/// -/// In release mode, it returns the condition and logs an error. -/// -/// ``` -/// if assert_never!(impossible) { -/// // Heh, this shouldn't have happened, but lets try to soldier on... -/// return None; -/// } -/// ``` -/// -/// Rust analyzer is a long-running process, and crashing really isn't an option. -/// -/// Shamelessly stolen from: https://www.sqlite.org/assert.html -#[macro_export] -macro_rules! assert_never { - ($cond:expr) => { $crate::assert_never!($cond, "") }; - ($cond:expr, $($fmt:tt)*) => {{ - let value = $cond; - if value { - $crate::on_assert_failure( - format_args!($($fmt)*) - ); - } - value - }}; -} - -type AssertHook = fn(&panic::Location<'_>, fmt::Arguments<'_>); -static HOOK: AtomicUsize = AtomicUsize::new(0); - -pub fn set_assert_hook(hook: AssertHook) { - HOOK.store(hook as usize, SeqCst); -} - -#[cold] -#[track_caller] -pub fn on_assert_failure(args: fmt::Arguments) { - let hook: usize = HOOK.load(SeqCst); - if hook == 0 { - panic!("\n assertion failed: {}\n", args); - } - - let hook: AssertHook = unsafe { mem::transmute::(hook) }; - hook(panic::Location::caller(), args) -} -- cgit v1.2.3