1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4use core::fmt;
5
6use use_env_key::EnvKey;
7
8#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
10pub struct EnvValue(String);
11
12impl EnvValue {
13 #[must_use]
15 pub fn new(value: impl Into<String>) -> Self {
16 Self(value.into())
17 }
18
19 #[must_use]
21 pub fn as_str(&self) -> &str {
22 &self.0
23 }
24
25 #[must_use]
27 pub fn into_string(self) -> String {
28 self.0
29 }
30}
31
32impl AsRef<str> for EnvValue {
33 fn as_ref(&self) -> &str {
34 self.as_str()
35 }
36}
37
38impl From<&str> for EnvValue {
39 fn from(value: &str) -> Self {
40 Self::new(value)
41 }
42}
43
44impl From<String> for EnvValue {
45 fn from(value: String) -> Self {
46 Self::new(value)
47 }
48}
49
50impl fmt::Display for EnvValue {
51 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
52 formatter.write_str(self.as_str())
53 }
54}
55
56#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
58pub struct EnvPair {
59 key: EnvKey,
60 value: EnvValue,
61}
62
63impl EnvPair {
64 #[must_use]
66 pub const fn new(key: EnvKey, value: EnvValue) -> Self {
67 Self { key, value }
68 }
69
70 #[must_use]
72 pub fn from_value(key: EnvKey, value: impl Into<EnvValue>) -> Self {
73 Self::new(key, value.into())
74 }
75
76 #[must_use]
78 pub const fn key(&self) -> &EnvKey {
79 &self.key
80 }
81
82 #[must_use]
84 pub const fn value(&self) -> &EnvValue {
85 &self.value
86 }
87
88 #[must_use]
90 pub fn into_parts(self) -> (EnvKey, EnvValue) {
91 (self.key, self.value)
92 }
93}
94
95impl fmt::Display for EnvPair {
96 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
97 write!(formatter, "{}={}", self.key, self.value)
98 }
99}
100
101#[cfg(test)]
102mod tests {
103 use super::{EnvPair, EnvValue};
104 use use_env_key::EnvKey;
105
106 #[test]
107 fn values_store_plain_owned_strings() {
108 let value = EnvValue::new("info");
109
110 assert_eq!(value.as_str(), "info");
111 assert_eq!(value.to_string(), "info");
112 }
113
114 #[test]
115 fn values_allow_empty_strings() {
116 let value = EnvValue::new("");
117
118 assert_eq!(value.as_str(), "");
119 }
120
121 #[test]
122 fn pairs_store_keys_and_values() {
123 let key = EnvKey::new("RUST_LOG").unwrap();
124 let value = EnvValue::new("debug");
125 let pair = EnvPair::new(key.clone(), value.clone());
126
127 assert_eq!(pair.key(), &key);
128 assert_eq!(pair.value(), &value);
129 assert_eq!(pair.to_string(), "RUST_LOG=debug");
130 }
131}