1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//! References that point into `static` data

#![deny(missing_docs)]
#![deny(warnings)]
#![feature(const_fn)]
#![no_std]

use core::{mem, ops};

/// A value stored in a `static` variable
#[repr(C)]
pub struct Static<T>
where
    T: ?Sized,
{
    data: T,
}

impl<T> Static<T> {
    /// Asserts that this `value` is stored in a `static` variable
    pub const unsafe fn new(value: T) -> Self {
        Static { data: value }
    }

    /// Asserts that the reference `r` points to data stored in a `static`
    /// variable
    pub unsafe fn ref_<'a>(r: &'a T) -> &'a Static<T> {
        mem::transmute(r)
    }

    /// Asserts that the reference `r` points to data stored in a `static`
    /// variable
    pub unsafe fn ref_mut<'a>(r: &'a mut T) -> &'a mut Static<T> {
        mem::transmute(r)
    }

    /// Wraps a static reference into `Static`
    pub fn wrap(r: &'static T) -> &'static Static<T> {
        unsafe { mem::transmute(r) }
    }

    /// Wraps a mutable static reference into `Static`
    pub fn wrap_mut(r: &'static mut T) -> &'static mut Static<T> {
        unsafe { mem::transmute(r) }
    }
}

impl<T> ops::Deref for Static<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.data
    }
}

impl<T> ops::DerefMut for Static<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut self.data
    }
}