opaque_enum/lib.rs
1//! Opaque enum support.
2//!
3//! This crate exposes the [`opaque_enum`] attribute macro plus the projection
4//! trait used by generated forwarding impls. The macro lets a public type keep
5//! an enum-like authoring experience while exposing an opaque wrapper instead of
6//! public enum variants.
7//!
8//! # Example
9//!
10//! ```rust
11//! use opaque_enum::opaque_enum;
12//! use std::fmt::{self, Display, Formatter};
13//!
14//! #[opaque_enum]
15//! #[derive(Debug)]
16//! pub enum DatabaseError {
17//! ConnectionFailed(String),
18//! QueryFailed { query: String, reason: String },
19//! PermissionDenied,
20//! }
21//!
22//! #[opaque_enum]
23//! impl Display for DatabaseError {
24//! fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
25//! match self {
26//! Self::ConnectionFailed(err) => write!(f, "connection failed: {err}"),
27//! Self::QueryFailed { query, reason } => {
28//! write!(f, "query `{query}` failed: {reason}")
29//! }
30//! Self::PermissionDenied => write!(f, "permission denied"),
31//! }
32//! }
33//! }
34//!
35//! let err = DatabaseError::ConnectionFailed("timeout".to_owned());
36//! assert_eq!(err.to_string(), "connection failed: timeout");
37//! ```
38
39#![deny(missing_docs)]
40
41pub use opaque_enum_macros::opaque_enum;
42
43/// Projects an opaque wrapper receiver into the corresponding inner receiver.
44///
45/// Generated forwarding impls use this trait instead of hard-coding whether a
46/// receiver should call `as_inner`, `as_inner_mut`, or `into_inner`.
47pub trait OpaqueProject<Target> {
48 /// The projected receiver type passed to the inner implementation.
49 type Output;
50
51 /// Projects `self` into the receiver expected by the inner implementation.
52 fn project(self) -> Self::Output;
53}