ref_slice/
lib.rs

1#![no_std]
2
3pub use self::opt_slice_mut as mut_opt_slice;
4
5#[allow(deprecated)]
6pub use self::ref_slice_mut as mut_ref_slice;
7
8/// Converts a reference to `A` into a slice of length 1 (without copying).
9#[inline]
10#[deprecated = "Similar method was added to std and stabilized in rust 1.28.0. \
11                Use `core::slice::from_ref` instead."]
12pub fn ref_slice<A>(s: &A) -> &[A] {
13    unsafe { core::slice::from_raw_parts(s, 1) }
14}
15
16/// Converts a reference to `A` into a slice of length 1 (without copying).
17#[inline]
18#[deprecated = "Similar method was added to std and stabilized in rust 1.28.0. \
19                Use `core::slice::from_mut` instead."]
20pub fn ref_slice_mut<A>(s: &mut A) -> &mut [A] {
21    unsafe { core::slice::from_raw_parts_mut(s, 1) }
22}
23
24/// Converts a reference to `Option<A>` into a slice of length 0 or 1 (without copying).
25#[inline]
26pub fn opt_slice<A>(opt: &Option<A>) -> &[A] {
27    match *opt {
28        #[allow(deprecated)]
29        Some(ref val) => ref_slice(val),
30        None => &[],
31    }
32}
33
34/// Converts a reference to `Option<A>` into a slice of length 0 or 1 (without copying).
35#[inline]
36pub fn opt_slice_mut<A>(opt: &mut Option<A>) -> &mut [A] {
37    match *opt {
38        #[allow(deprecated)]
39        Some(ref mut val) => mut_ref_slice(val),
40        None => &mut [],
41    }
42}
43
44#[cfg(test)]
45#[allow(deprecated)]
46mod tests {
47    use super::mut_opt_slice;
48    use super::mut_ref_slice;
49    use super::opt_slice;
50    use super::ref_slice;
51
52    #[test]
53    fn check() {
54        let x = &5;
55        let xs = ref_slice(x);
56
57        let result: &[i32] = &[5];
58
59        assert_eq!(result, xs);
60    }
61
62    #[test]
63    fn check_mut() {
64        let x = &mut 5;
65        let xs = mut_ref_slice(x);
66
67        let result: &mut [i32] = &mut [5];
68
69        assert_eq!(result, xs);
70    }
71
72    #[test]
73    fn check_opt() {
74        let x = &Some(42);
75        let n = &None;
76        let xs = opt_slice(x);
77        let ns = opt_slice(n);
78
79        let result_x: &[i32] = &[42];
80        let result_n: &[i32] = &[];
81
82        assert_eq!(result_x, xs);
83        assert_eq!(result_n, ns);
84    }
85
86    #[test]
87    fn check_opt_mut() {
88        let x = &mut Some(42);
89        let n = &mut None;
90        let xs = mut_opt_slice(x);
91        let ns = mut_opt_slice(n);
92
93        let result_x: &[i32] = &mut [42];
94        let result_n: &[i32] = &mut [];
95
96        assert_eq!(result_x, xs);
97        assert_eq!(result_n, ns);
98    }
99}