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
// License: see LICENSE file at root directory of `master` branch

//! # Read-only container

use core::{
    fmt::{self, Display, Formatter},
    ops::Deref,
};

/// # Read-only container
///
/// The key of this container is [`Deref`][core:Deref] implementation. It allows you to access public fields and immutable functions of `T`. In
/// case `T` has mutable functions, those are not accessible.
///
/// By design, the struct has no functions.
///
/// [core:Deref]: https://doc.rust-lang.org/core/ops/trait.Deref.html
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Clone)]
pub struct ReadOnly<T> {
    data: T,
}

impl<T> Deref for ReadOnly<T> {

    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.data
    }

}

impl<T> Display for ReadOnly<T> where T: Display {

    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        self.data.fmt(f)
    }

}

impl<T> From<T> for ReadOnly<T> {

    fn from(data: T) -> Self {
        new(data)
    }

}

/// # Makes new read-only version of some value
pub const fn new<T>(some: T) -> ReadOnly<T> {
    ReadOnly {
        data: some,
    }
}