Skip to content

Commit 0cf82e5

Browse files
committed
api for variant
1 parent 27e3d3f commit 0cf82e5

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-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
## [v0.16.1] - 2019-08-17
1115

1216
### Fixed

src/generate/generic.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,63 @@ pub enum Variant<U, T> {
227227
///Raw bits
228228
Res(U),
229229
}
230+
231+
use Variant::*;
232+
impl<U, T> Variant<U, T> {
233+
/// Check if the variant is expected
234+
pub fn is_value(&self) -> bool {
235+
match self {
236+
Val(_) => true,
237+
Res(_) => false,
238+
}
239+
}
240+
/// Check if the variant is not expected
241+
pub fn is_reserved(&self) -> bool {
242+
match self {
243+
Val(_) => false,
244+
Res(_) => true,
245+
}
246+
}
247+
248+
/// Returns the contained value or a default
249+
#[inline]
250+
pub fn unwrap_or(self, def: T) -> T {
251+
match self {
252+
Val(v) => v,
253+
Res(_) => def,
254+
}
255+
}
256+
257+
/// Returns the contained value or computes it from a closure
258+
#[inline]
259+
pub fn unwrap_or_else<F: FnOnce(U) -> T>(self, f: F) -> T {
260+
match self {
261+
Val(v) => v,
262+
Res(u) => f(u),
263+
}
264+
}
265+
}
266+
267+
impl<U, T> Variant<U, T> where U: core::fmt::Debug {
268+
/// Moves the value `v` out of the `Variant` if it is `Val(v)`.
269+
///
270+
/// Panics if the self value equals `Res`
271+
#[inline]
272+
pub fn unwrap(self) -> T {
273+
match self {
274+
Val(v) => v,
275+
Res(u) => panic!("Unexpected variant: {:?}", u),
276+
}
277+
}
278+
279+
/// Unwraps a result, yielding the content of an `Val`.
280+
///
281+
/// Panics if the value is an `Res`, with a panic message including the
282+
/// passed message, and the content of the `Res`.
283+
pub fn expect(self, msg: &str) -> T {
284+
match self {
285+
Val(v) => v,
286+
Res(u) => panic!("{}: {:?}", msg, u),
287+
}
288+
}
289+
}

0 commit comments

Comments
 (0)