1use std::marker::{PhantomData};
2
3pub trait Toggle<T> {
4 fn as_ref(&self) -> Option<&T>;
5 fn as_mut(&mut self) -> Option<&mut T>;
6}
7
8pub type Disabled<T> = Disable<T>;
9pub type Enabled<T> = Enable<T>;
10
11pub struct Disable<T> {
12 _marker: PhantomData<T>,
13}
14
15impl<T> Disable<T> {
16 #[inline]
17 pub fn new() -> Disable<T> {
18 Disable{_marker: PhantomData}
19 }
20}
21
22impl<T> Toggle<T> for Disable<T> {
23 #[inline]
24 fn as_ref(&self) -> Option<&T> {
25 None
26 }
27
28 #[inline]
29 fn as_mut(&mut self) -> Option<&mut T> {
30 None
31 }
32}
33
34impl<T> Clone for Disable<T> where T: Clone {
35 fn clone(&self) -> Disable<T> {
36 Disable{_marker: PhantomData}
37 }
38}
39
40impl<T> Copy for Disable<T> where T: Copy {
41}
42
43pub struct Enable<T> {
44 value: T,
45}
46
47impl<T> Enable<T> {
48 #[inline]
49 pub fn new(value: T) -> Enable<T> {
50 Enable{value: value}
51 }
52}
53
54impl<T> Toggle<T> for Enable<T> {
55 #[inline]
56 fn as_ref(&self) -> Option<&T> {
57 Some(&self.value)
58 }
59
60 #[inline]
61 fn as_mut(&mut self) -> Option<&mut T> {
62 Some(&mut self.value)
63 }
64}
65
66impl<T> Clone for Enable<T> where T: Clone {
67 fn clone(&self) -> Enable<T> {
68 Enable{value: self.value.clone()}
69 }
70}
71
72impl<T> Copy for Enable<T> where T: Copy {
73}
74
75#[cfg(test)]
76mod tests {
77
78 use super::{Toggle, Disable, Enable};
79
80 struct Hello<Tg> where Tg: Toggle<String> {
81 t: Tg,
82 }
83
84 #[test]
85 fn test_disable() {
86 let hello = Hello{t: Disable::new()};
87 assert!(hello.t.as_ref().is_none());
88 }
89
90 #[test]
91 fn test_disable_mut() {
92 let mut hello = Hello{t: Disable::new()};
93 assert!(hello.t.as_mut().is_none());
94 }
95
96 #[test]
97 fn test_enable() {
98 let hello = Hello{t: Enable::new(format!("Hello, world!"))};
99 assert!(hello.t.as_ref().is_some());
100 }
101
102 #[test]
103 fn test_enable_mut() {
104 let mut hello = Hello{t: Enable::new(format!("Hello, world!"))};
105 *hello.t.as_mut().unwrap() = format!("Goodbye, cruel world!");
106 assert_eq!("Goodbye, cruel world!", hello.t.as_ref().unwrap());
107 }
108
109}