Skip to content

Commit 1a481c8

Browse files
committed
api for variant
1 parent afb96f7 commit 1a481c8

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
77

88
## [Unreleased]
99

10+
### Added
11+
12+
- Option-like API for `generic::Variant`
13+
1014
### Fixed
1115

1216
- Keyword sanitizing (`async`)

src/generate/generic.rs

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,3 +258,75 @@ pub enum Variant<U, T> {
258258
/// Raw bits.
259259
Res(U),
260260
}
261+
262+
use Variant::*;
263+
impl<U, T> Variant<U, T> {
264+
/// Check if the variant is expected
265+
pub fn is_expected(&self) -> bool {
266+
match self {
267+
Val(_) => true,
268+
Res(_) => false,
269+
}
270+
}
271+
272+
/// Check if the variant is not expected
273+
pub fn is_reserved(&self) -> bool {
274+
match self {
275+
Val(_) => false,
276+
Res(_) => true,
277+
}
278+
}
279+
280+
/// Moves the value `v` out of the `Variant` if it is `Val(v)`.
281+
///
282+
/// Panics if the self value equals `Res`
283+
#[inline]
284+
pub fn unwrap(self) -> T {
285+
match self {
286+
Val(v) => v,
287+
Res(_) => panic!("Unexpected variant"),
288+
}
289+
}
290+
291+
/// Returns the contained value or a default
292+
#[inline]
293+
pub fn unwrap_or(self, def: T) -> T {
294+
match self {
295+
Val(v) => v,
296+
Res(_) => def,
297+
}
298+
}
299+
300+
/// Returns the contained value or computes it from a closure
301+
#[inline]
302+
pub fn unwrap_or_else<F: FnOnce(U) -> T>(self, f: F) -> T {
303+
match self {
304+
Val(v) => v,
305+
Res(u) => f(u),
306+
}
307+
}
308+
309+
/// Unwraps a result, yielding the content of an `Val`.
310+
///
311+
/// Panics if the value is an `Res`, with a panic message including the
312+
/// passed message, and the content of the `Res`.
313+
pub fn expect(self, msg: &'static str) -> T {
314+
match self {
315+
Val(v) => v,
316+
Res(_) => panic!(msg),
317+
}
318+
}
319+
}
320+
321+
impl<U, T> Variant<U, T>
322+
where
323+
T: Into<U>
324+
{
325+
/// Get raw bits
326+
pub fn to_bits() -> U {
327+
match self {
328+
Val(v) => v.into(),
329+
Res(u) => u,
330+
}
331+
}
332+
}

0 commit comments

Comments
 (0)