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
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use std::{
    fmt,
    hash::{Hash, Hasher},
};

/// A Stringable is simply a value that can be converted into a String
/// This type supports heap allocated strings, string slices, and heap allocated values that support display
pub enum Stringable {
    StrVal(&'static str),
    StringVal(String),
    BoxedVal(Box<dyn std::fmt::Display>),
}

impl fmt::Display for Stringable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // This Display formatter formats the inner value.
        match self {
            Stringable::StrVal(val) => write!(f, "{}", val),
            Stringable::StringVal(val) => write!(f, "{}", val),
            Stringable::BoxedVal(val) => write!(f, "{}", val),
        }
    }
}

impl fmt::Debug for Stringable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // This Debug formatter puts single quotes around the Display formatted value.
        write!(f, "'{}'", self)
    }
}

// Allows Stringable to be made from a literal string (e.g. `"asdf".into()`)
// or other static string slices.
impl From<&'static str> for Stringable {
    fn from(input: &'static str) -> Self {
        Stringable::StrVal(input)
    }
}

// Allows Stringable to be made from a heap allocated String
impl From<String> for Stringable {
    fn from(input: String) -> Self {
        Stringable::StringVal(input)
    }
}

// Allows Stringable to be made from any trait object implementing display.
// Note: this method incurs a minimal dynamic dispatch performance penalty.
impl From<Box<dyn std::fmt::Display>> for Stringable {
    fn from(input: Box<dyn std::fmt::Display>) -> Self {
        Stringable::BoxedVal(input)
    }
}

// Allows Stringable to be made from any heap allocated type implementing display.alloc
// Note: this method incurs a minimal dynamic dispatch performance penalty.
impl<T> From<Box<T>> for Stringable
where
    T: std::fmt::Display + 'static,
{
    fn from(input: Box<T>) -> Self {
        Stringable::BoxedVal(input)
    }
}

// Allows Stringable to be made from a standard library IO error.
impl From<std::io::Error> for Stringable {
    fn from(input: std::io::Error) -> Self {
        Stringable::BoxedVal(Box::new(input))
    }
}

// Allows Stringable to be made from a standard library parse int error
impl From<std::num::ParseIntError> for Stringable {
    fn from(input: std::num::ParseIntError) -> Self {
        Stringable::BoxedVal(Box::new(input))
    }
}

// Allows Stringable to be made from a toml-rs parse error
impl From<toml::de::Error> for Stringable {
    fn from(input: toml::de::Error) -> Self {
        Stringable::BoxedVal(Box::new(input))
    }
}

// Allows Stringables to be compared to eachother.
// This allows for use in unit test comparisons, data structures, etc.
impl PartialEq for Stringable {
    fn eq(&self, other: &Stringable) -> bool {
        // Considers two values equal if they are the same variant and format to the same value.
        // This ensures compatibility with the hash definition
        match (self, other) {
            (Stringable::StrVal(left), Stringable::StrVal(right)) => left == right,
            (Stringable::StringVal(left), Stringable::StringVal(right)) => left == right,
            (Stringable::BoxedVal(left), Stringable::BoxedVal(right)) => {
                format!("{}", left) == format!("{}", right)
            }
            _ => false,
        }
    }
}
impl Eq for Stringable {}

// Allows Stringables to be hashed, which allows the use of hash-based data structures.
impl Hash for Stringable {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        // Hashes each variant with a numerical id (0u32, 1u32, 2u32) and it's inner value.
        // This ensures compatibility with the equality definition
        let id = match self {
            Stringable::StrVal(_) => 0u32,
            Stringable::StringVal(_) => 1u32,
            Stringable::BoxedVal(_) => 2u32,
        };

        id.hash(hasher);

        format!("{}", self).hash(hasher);
    }
}