1#![deny(missing_docs)]
5
6use std::backtrace::Backtrace;
14use std::backtrace::BacktraceStatus;
15use std::borrow::Cow;
16use std::convert::Infallible;
17use std::env;
18use std::error::Error;
19use std::fmt;
20use std::fmt::Debug;
21use std::fmt::Display;
22use std::fmt::Formatter;
23use std::io;
24use std::num::TryFromIntError;
25use std::ops::Deref;
26use std::sync::Arc;
27use std::sync::LazyLock;
28
29#[derive(Debug, Clone)]
31pub struct ErrString(Cow<'static, str>);
32
33#[expect(
34 clippy::fallible_impl_from,
35 reason = "intentionally panic in debug mode when VORTEX_PANIC_ON_ERR is set"
36)]
37impl<T> From<T> for ErrString
38where
39 T: Into<Cow<'static, str>>,
40{
41 #[expect(
42 clippy::panic,
43 reason = "intentionally panic in debug mode when VORTEX_PANIC_ON_ERR is set"
44 )]
45 fn from(msg: T) -> Self {
46 if panic_on_err() {
47 panic!("{}\nBacktrace:\n{}", msg.into(), Backtrace::capture());
48 } else {
49 Self(msg.into())
50 }
51 }
52}
53
54fn panic_on_err() -> bool {
55 static PANIC_ON_ERR: LazyLock<bool> =
56 LazyLock::new(|| env::var("VORTEX_PANIC_ON_ERR").is_ok_and(|v| v == "1"));
57 *PANIC_ON_ERR
58}
59
60impl AsRef<str> for ErrString {
61 fn as_ref(&self) -> &str {
62 &self.0
63 }
64}
65
66impl Deref for ErrString {
67 type Target = str;
68
69 fn deref(&self) -> &Self::Target {
70 &self.0
71 }
72}
73
74impl Display for ErrString {
75 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
76 Display::fmt(&self.0, f)
77 }
78}
79
80#[derive(Clone)]
90pub struct VortexError(Arc<ErrorInner>);
91
92const _: () = assert!(size_of::<VortexError>() == size_of::<usize>());
93const _: () = assert!(size_of::<VortexResult<()>>() == size_of::<usize>());
94
95struct ErrorInner {
96 message: Option<ErrString>,
98 origin: Origin,
99}
100
101enum Origin {
103 Own {
105 source: Option<Box<dyn Error + Send + Sync + 'static>>,
106 backtrace: Backtrace,
107 },
108 Context(VortexError),
113}
114
115impl VortexError {
116 pub fn new<T: Into<ErrString>>(message: T) -> Self {
118 Self::from_parts(Some(message.into()), None)
119 }
120
121 pub fn external<E>(source: E) -> Self
126 where
127 E: Into<Box<dyn Error + Send + Sync + 'static>>,
128 {
129 Self::from_parts(None, Some(source.into()))
130 }
131
132 fn from_parts(
133 message: Option<ErrString>,
134 source: Option<Box<dyn Error + Send + Sync + 'static>>,
135 ) -> Self {
136 Self(Arc::new(ErrorInner {
137 message,
138 origin: Origin::Own {
139 source,
140 backtrace: Backtrace::capture(),
141 },
142 }))
143 }
144
145 pub fn with_context<T: Into<ErrString>>(mut self, msg: T) -> Self {
147 let msg: ErrString = msg.into();
148 let message = ErrString(Cow::Owned(format!("{msg}:\n {}", self.message_body())));
151 if let Some(inner) = Arc::get_mut(&mut self.0) {
152 inner.message = Some(message);
153 return self;
154 }
155 Self(Arc::new(ErrorInner {
156 message: Some(message),
157 origin: Origin::Context(self),
158 }))
159 }
160
161 fn message_body(&self) -> Cow<'_, str> {
163 match (&self.0.message, self.source_ref()) {
164 (Some(message), _) => Cow::Borrowed(message.as_ref()),
165 (None, Some(source)) => Cow::Owned(source.to_string()),
166 (None, None) => Cow::Borrowed(""),
167 }
168 }
169
170 fn source_ref(&self) -> Option<&(dyn Error + Send + Sync + 'static)> {
171 match &self.0.origin {
172 Origin::Own { source, .. } => source.as_deref(),
173 Origin::Context(error) => error.source_ref(),
174 }
175 }
176
177 fn backtrace(&self) -> &Backtrace {
178 match &self.0.origin {
179 Origin::Own { backtrace, .. } => backtrace,
180 Origin::Context(error) => error.backtrace(),
181 }
182 }
183}
184
185impl Display for VortexError {
186 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
187 match (&self.0.message, self.source_ref()) {
188 (Some(message), _) => Display::fmt(message, f)?,
189 (None, Some(source)) => Display::fmt(source, f)?,
190 (None, None) => {}
191 }
192 let backtrace = self.backtrace();
193 if backtrace.status() == BacktraceStatus::Captured {
194 write!(f, "\nBacktrace:\n{backtrace}")?;
195 }
196 Ok(())
197 }
198}
199
200impl Debug for VortexError {
201 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
202 write!(f, "{self}")
203 }
204}
205
206impl Error for VortexError {
207 fn source(&self) -> Option<&(dyn Error + 'static)> {
208 self.source_ref()
209 .map(|source| source as &(dyn Error + 'static))
210 }
211}
212
213pub type VortexResult<T> = Result<T, VortexError>;
215
216pub type SharedVortexResult<T> = Result<T, Arc<VortexError>>;
218
219impl From<Arc<VortexError>> for VortexError {
220 fn from(value: Arc<VortexError>) -> Self {
221 Arc::try_unwrap(value).unwrap_or_else(|value| (*value).clone())
222 }
223}
224
225impl From<&Arc<VortexError>> for VortexError {
226 fn from(value: &Arc<VortexError>) -> Self {
227 (**value).clone()
228 }
229}
230
231pub trait VortexExpect {
233 type Output;
235
236 fn vortex_expect(self, msg: &'static str) -> Self::Output;
245}
246
247impl<T, E> VortexExpect for Result<T, E>
248where
249 E: Into<VortexError>,
250{
251 type Output = T;
252
253 #[allow(clippy::inline_always)]
254 #[inline(always)]
255 fn vortex_expect(self, msg: &'static str) -> Self::Output {
256 match self {
257 Ok(value) => value,
258 Err(err) => __private::result_expect_failed(err, msg),
259 }
260 }
261}
262
263impl<T> VortexExpect for Option<T> {
264 type Output = T;
265
266 #[allow(clippy::inline_always)]
267 #[inline(always)]
268 fn vortex_expect(self, msg: &'static str) -> Self::Output {
269 match self {
270 Some(value) => value,
271 None => __private::option_expect_failed(msg),
272 }
273 }
274}
275
276#[macro_export]
285macro_rules! vortex_err {
286 (Context: $msg:literal, $err:expr) => {
287 $crate::__private::context($msg, $err)
288 };
289 (External: $err:expr $(,)?) => {
290 $crate::__private::external($err)
291 };
292 ($fmt:literal $(, $arg:expr)* $(,)?) => {
293 $crate::__private::fmt_err(&format_args!($fmt $(, $arg)*))
294 };
295 ($err:expr $(,)?) => {
296 $crate::__private::fmt_err(&format_args!("{}", $err))
297 };
298}
299
300#[macro_export]
302macro_rules! vortex_bail {
303 ($($tt:tt)+) => {
304 return Err($crate::vortex_err!($($tt)+))
305 };
306}
307
308#[macro_export]
313macro_rules! vortex_ensure {
314 ($cond:expr) => {
315 $crate::vortex_ensure!($cond, "{}", stringify!($cond));
316 };
317 ($cond:expr, $($tt:tt)*) => {
318 if !$cond {
319 $crate::vortex_bail!($($tt)*);
320 }
321 };
322}
323
324#[macro_export]
358macro_rules! vortex_ensure_eq {
359 ($left:expr, $right:expr $(,)?) => {
360 match (&$left, &$right) {
361 (left_val, right_val) => {
362 if *left_val != *right_val {
363 $crate::vortex_bail!(
364 "`{} == {}`\n left: {}\n right: {}",
365 stringify!($left),
366 stringify!($right),
367 left_val,
368 right_val
369 );
370 }
371 }
372 }
373 };
374 ($left:expr, $right:expr, $fmt:literal $(, $arg:expr)* $(,)?) => {
375 match (&$left, &$right) {
376 (left_val, right_val) => {
377 if *left_val != *right_val {
378 $crate::vortex_bail!(
379 "{}\n left: {}\n right: {}",
380 format_args!($fmt $(, $arg)*),
381 left_val,
382 right_val
383 );
384 }
385 }
386 }
387 };
388}
389
390#[macro_export]
396macro_rules! vortex_panic {
397 (Context: $msg:literal, $err:expr) => {{
398 $crate::vortex_panic!($crate::vortex_err!(Context: $msg, $err))
399 }};
400 ($fmt:literal $(, $arg:expr)* $(,)?) => {
402 $crate::vortex_panic!($crate::vortex_err!($fmt $(, $arg)*))
403 };
404 ($err:expr, $fmt:literal $(, $arg:expr)* $(,)?) => {
405 $crate::__private::panic_err_ctx($err, &format_args!($fmt $(, $arg)*))
406 };
407 ($err:expr) => {
408 $crate::__private::panic_err($err)
409 };
410}
411
412impl From<Infallible> for VortexError {
413 fn from(_: Infallible) -> Self {
414 unreachable!()
415 }
416}
417
418impl From<arrow_schema::ArrowError> for VortexError {
419 fn from(value: arrow_schema::ArrowError) -> Self {
420 VortexError::external(value)
421 }
422}
423
424#[cfg(feature = "flatbuffers")]
425impl From<flatbuffers::InvalidFlatbuffer> for VortexError {
426 fn from(value: flatbuffers::InvalidFlatbuffer) -> Self {
427 VortexError::external(value)
428 }
429}
430
431impl From<io::Error> for VortexError {
432 fn from(value: io::Error) -> Self {
433 VortexError::external(value)
434 }
435}
436
437#[cfg(feature = "object_store")]
438impl From<object_store::Error> for VortexError {
439 fn from(value: object_store::Error) -> Self {
440 VortexError::external(value)
441 }
442}
443
444impl From<jiff::Error> for VortexError {
445 fn from(value: jiff::Error) -> Self {
446 VortexError::external(value)
447 }
448}
449
450#[cfg(feature = "tokio")]
451impl From<tokio::task::JoinError> for VortexError {
452 fn from(value: tokio::task::JoinError) -> Self {
453 if value.is_panic() {
454 std::panic::resume_unwind(value.into_panic())
455 } else {
456 VortexError::external(value)
457 }
458 }
459}
460
461impl From<TryFromIntError> for VortexError {
462 fn from(value: TryFromIntError) -> Self {
463 VortexError::external(value)
464 }
465}
466
467impl From<prost::EncodeError> for VortexError {
468 fn from(value: prost::EncodeError) -> Self {
469 VortexError::external(value)
470 }
471}
472
473impl From<prost::DecodeError> for VortexError {
474 fn from(value: prost::DecodeError) -> Self {
475 VortexError::external(value)
476 }
477}
478
479impl From<prost::UnknownEnumValue> for VortexError {
480 fn from(value: prost::UnknownEnumValue) -> Self {
481 VortexError::external(value)
482 }
483}
484
485#[doc(hidden)]
492#[expect(
493 clippy::panic,
494 reason = "cold handlers for vortex_panic!/vortex_expect intentionally panic"
495)]
496pub mod __private {
497
498 use std::error::Error;
499 use std::fmt::Arguments;
500
501 use crate::VortexError;
502
503 #[doc(hidden)]
504 #[inline]
505 #[cold]
506 #[must_use]
507 pub const fn must_use(error: VortexError) -> VortexError {
508 error
509 }
510
511 #[doc(hidden)]
512 #[cold]
513 #[inline(never)]
514 #[must_use]
515 pub fn fmt_err(args: &Arguments<'_>) -> VortexError {
516 VortexError::new(args.to_string())
517 }
518
519 #[doc(hidden)]
520 #[cold]
521 #[inline(never)]
522 #[must_use]
523 pub fn context(msg: &'static str, err: VortexError) -> VortexError {
524 err.with_context(msg)
525 }
526
527 #[doc(hidden)]
528 #[cold]
529 #[inline(never)]
530 #[must_use]
531 pub fn external(err: impl Into<Box<dyn Error + Send + Sync + 'static>>) -> VortexError {
532 VortexError::external(err)
533 }
534
535 #[doc(hidden)]
536 #[cold]
537 #[inline(never)]
538 pub fn panic_err(err: VortexError) -> ! {
539 panic!("{err}")
540 }
541
542 #[doc(hidden)]
543 #[cold]
544 #[inline(never)]
545 pub fn panic_err_ctx(err: VortexError, args: &Arguments<'_>) -> ! {
546 panic!("{}", err.with_context(args.to_string()))
547 }
548
549 #[doc(hidden)]
550 #[cold]
551 #[inline(never)]
552 pub fn result_expect_failed(err: impl Into<VortexError>, msg: &'static str) -> ! {
553 panic!("{}", err.into().with_context(msg))
554 }
555
556 #[doc(hidden)]
557 #[cold]
558 #[inline(never)]
559 pub fn option_expect_failed(msg: &'static str) -> ! {
560 panic!("{}", VortexError::new(msg))
561 }
562}