rustr/result.rs
1//! Safe unwrap for R ffi
2//!
3use ::traits::*;
4
5use std::result::Result::{self, Ok, Err};
6use std::option::Option::{self, Some, None};
7
8
9impl<T: Empty, E> Gettable for Result<T, E> {
10 type Res=T;
11 /// Safely unwraps a Result, yielding the content of an `Ok`.
12 ///
13 /// # Examples
14 ///
15 /// ```txt
16 /// let x: Rresult<u32, &str> = Ok(2);
17 /// assert_eq!(x.unwrap(), 2);
18 /// ```
19 ///
20 /// ```txt
21 /// let x: Rresult<u32, &str> = Err("emergency failure");
22 /// x.get();
23 /// ```
24 #[inline]
25 fn get(self) -> T {
26 match self {
27 Ok(t) => t,
28 Err(_) => T::empty(),
29 // panic!("called `Rresult::unwrap()` on an `Err` value: {:?}", e)
30 }
31 }
32}
33
34impl<T, E: Empty> ErrGettable for Result<T, E> {
35 type Res=E;
36 /// Safely unwraps a Result, yielding the content of an `Err`.
37 ///
38 /// # Examples
39 ///
40 /// ```txt
41 /// let x: Rresult<u32, &str> = Ok(2);
42 /// x.get_err();
43 /// ```
44 ///
45 /// ```txt
46 /// let x: Rresult<u32, &str> = Err("emergency failure");
47 /// assert_eq!(x.get_err(), "emergency failure");
48 /// ```
49 #[inline]
50 fn get_err(self) -> E {
51 match self {
52 Ok(_) => E::empty(),
53 Err(e) => e,
54 }
55 }
56}
57
58
59impl<T: Empty> Gettable for Option<T> {
60 type Res=T;
61 /// Moves the value `v` out of the `Roption<T>` if it is `Some(v)`.
62 ///
63 /// # Panics
64 ///
65 /// Panics if the self value equals `None`.
66 ///
67 /// # Safety note
68 ///
69 /// In general, because this function may panic, its use is discouraged.
70 /// Instead, prefer to use pattern matching and handle the `None`
71 /// case explicitly.
72 ///
73 /// # Examples
74 ///
75 /// ```txt
76 /// let x = Some("air");
77 /// assert_eq!(x.get(), "air");
78 /// ```
79 ///
80 /// ```txt
81 /// let x: Roption<&str> = None;
82 /// assert_eq!(x.get(), "air"); // fails
83 /// ```
84 #[inline]
85 fn get(self) -> T {
86 match self {
87 Some(val) => val,
88 None => T::empty(),
89 }
90 }
91}