ranvier_core/never.rs
1//! # Never: Serde-Compatible Uninhabited Type
2//!
3//! A replacement for `std::convert::Infallible` that satisfies
4//! Axon's `Serialize + DeserializeOwned` bounds.
5//!
6//! Use `Never` as the error type for pipelines that cannot fail,
7//! or as any generic parameter that should be uninhabited.
8//!
9//! # Example
10//!
11//! ```rust
12//! use ranvier_core::Never;
13//!
14//! // Never can be used as the error type in Axon type aliases:
15//! // type InfallibleAxon<In, Out, Res = ()> = Axon<In, Out, Never, Res>;
16//! ```
17
18use serde::{Deserialize, Deserializer, Serialize, Serializer};
19use std::convert::Infallible;
20use std::fmt;
21
22/// An uninhabited type that implements `Serialize + DeserializeOwned`.
23///
24/// This type has no variants and can never be constructed at runtime,
25/// making it semantically identical to `std::convert::Infallible`.
26/// Unlike `Infallible`, `Never` satisfies the `Serialize + DeserializeOwned`
27/// bounds required by `Axon<In, Out, E, Res>`.
28///
29/// # When to Use
30///
31/// - As the error type for infallible pipelines: `Axon<In, Out, Never, Res>`
32/// - Anywhere an uninhabited type is needed with serde compatibility
33///
34/// # Guarantees
35///
36/// - Cannot be constructed (no variants)
37/// - Serialization: unreachable (no value exists to serialize)
38/// - Deserialization: always fails with a descriptive error
39/// - Converts freely from `std::convert::Infallible`
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
41pub enum Never {}
42
43impl Serialize for Never {
44 fn serialize<S: Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
45 match *self {}
46 }
47}
48
49impl<'de> Deserialize<'de> for Never {
50 fn deserialize<D: Deserializer<'de>>(_deserializer: D) -> Result<Self, D::Error> {
51 Err(serde::de::Error::custom(
52 "Never type cannot be deserialized (uninhabited)",
53 ))
54 }
55}
56
57impl fmt::Display for Never {
58 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 match *self {}
60 }
61}
62
63impl std::error::Error for Never {}
64
65impl From<Infallible> for Never {
66 fn from(x: Infallible) -> Self {
67 match x {}
68 }
69}
70
71#[cfg(test)]
72mod tests {
73 use super::*;
74
75 #[test]
76 fn never_serialize_json_schema() {
77 // Never cannot be instantiated, so we only verify deserialization fails gracefully
78 let result: Result<Never, _> = serde_json::from_str("null");
79 assert!(result.is_err());
80 assert!(result
81 .unwrap_err()
82 .to_string()
83 .contains("cannot be deserialized"));
84 }
85
86 #[test]
87 fn never_deser_any_value_fails() {
88 let result: Result<Never, _> = serde_json::from_str("42");
89 assert!(result.is_err());
90 }
91
92 #[test]
93 fn never_is_send_sync() {
94 fn assert_send_sync<T: Send + Sync>() {}
95 assert_send_sync::<Never>();
96 }
97}