darling_core/util/
over_ride.rs1use std::fmt;
2
3use syn::Lit;
4
5use crate::ast::NestedMeta;
6use crate::{FromMeta, Result};
7
8use self::Override::*;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Override<T> {
39 Inherit,
41
42 Explicit(T),
44}
45
46impl<T> Override<T> {
47 pub fn as_ref(&self) -> Override<&T> {
51 match *self {
52 Inherit => Inherit,
53 Explicit(ref val) => Explicit(val),
54 }
55 }
56
57 pub fn as_mut(&mut self) -> Override<&mut T> {
61 match *self {
62 Inherit => Inherit,
63 Explicit(ref mut val) => Explicit(val),
64 }
65 }
66
67 pub fn is_explicit(&self) -> bool {
69 match *self {
70 Inherit => false,
71 Explicit(_) => true,
72 }
73 }
74
75 pub fn explicit(self) -> Option<T> {
77 match self {
78 Inherit => None,
79 Explicit(val) => Some(val),
80 }
81 }
82
83 pub fn unwrap_or(self, optb: T) -> T {
85 match self {
86 Inherit => optb,
87 Explicit(val) => val,
88 }
89 }
90
91 pub fn unwrap_or_else<F>(self, op: F) -> T
93 where
94 F: FnOnce() -> T,
95 {
96 match self {
97 Inherit => op(),
98 Explicit(val) => val,
99 }
100 }
101}
102
103impl<T: Default> Override<T> {
104 pub fn unwrap_or_default(self) -> T {
106 match self {
107 Inherit => Default::default(),
108 Explicit(val) => val,
109 }
110 }
111}
112
113impl<T> Default for Override<T> {
114 fn default() -> Self {
115 Inherit
116 }
117}
118
119impl<T> From<Option<T>> for Override<T> {
120 fn from(v: Option<T>) -> Self {
121 match v {
122 None => Inherit,
123 Some(val) => Explicit(val),
124 }
125 }
126}
127
128impl<T: fmt::Display> fmt::Display for Override<T> {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 match *self {
131 Inherit => write!(f, "Inherit"),
132 Explicit(ref val) => write!(f, "Explicit `{}`", val),
133 }
134 }
135}
136
137impl<T: FromMeta> FromMeta for Override<T> {
140 fn from_meta(item: &syn::Meta) -> Result<Self> {
141 match item {
142 syn::Meta::Path(_) => Self::from_word(),
143 _ => FromMeta::from_meta(item).map(Explicit),
144 }
145 }
146
147 fn from_word() -> Result<Self> {
148 Ok(Inherit)
149 }
150
151 fn from_list(items: &[NestedMeta]) -> Result<Self> {
152 Ok(Explicit(FromMeta::from_list(items)?))
153 }
154
155 fn from_value(lit: &Lit) -> Result<Self> {
156 Ok(Explicit(FromMeta::from_value(lit)?))
157 }
158
159 fn from_expr(expr: &syn::Expr) -> Result<Self> {
160 Ok(Explicit(FromMeta::from_expr(expr)?))
161 }
162
163 fn from_char(value: char) -> Result<Self> {
164 Ok(Explicit(FromMeta::from_char(value)?))
165 }
166
167 fn from_string(value: &str) -> Result<Self> {
168 Ok(Explicit(FromMeta::from_string(value)?))
169 }
170
171 fn from_bool(value: bool) -> Result<Self> {
172 Ok(Explicit(FromMeta::from_bool(value)?))
173 }
174}