Skip to main content

nu_protocol/engine/
env_name.rs

1//! Environment variable name handling with global case-insensitivity.
2//!
3//! This module defines `EnvName`, a wrapper around `String` that handles case sensitivity
4//! for environment variable names. All environment variables are now case-insensitive for lookup
5//! but case-preserving for storage across all platforms.
6//!
7//! ## Case Sensitivity Rules
8//!
9//! - **All platforms**: All environment variable names are case-insensitive but case-preserving.
10//!   This means `PATH`, `Path`, and `path` refer to the same variable, and so do `HOME` and `home`.
11//!
12//! This ensures that:
13//! - `$env.PATH`, `$env.path`, `$env.Path` all work on any platform
14//! - `$env.HOME`, `$env.home` all refer to the same variable
15//! - Case is preserved when storing the variable name
16//! - Existing scripts may need updates if they relied on case sensitivity
17
18use serde::{Deserialize, Serialize};
19use std::hash::{Hash, Hasher};
20
21/// A `String` that's case-insensitive for all environment variable names, used for environment variable names.
22#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
23#[debug("{_0:?}")]
24pub struct EnvName(pub(crate) String);
25
26/// All environment variables are case-insensitive on all platforms
27pub fn env_var_eq(a: &str, b: &str) -> bool {
28    a.eq_ignore_ascii_case(b)
29}
30
31impl<T: Into<String>> From<T> for EnvName {
32    fn from(name: T) -> Self {
33        EnvName(name.into())
34    }
35}
36
37impl AsRef<str> for EnvName {
38    fn as_ref(&self) -> &str {
39        &self.0
40    }
41}
42
43impl PartialEq<Self> for EnvName {
44    fn eq(&self, other: &Self) -> bool {
45        env_var_eq(&self.0, &other.0)
46    }
47}
48
49impl Eq for EnvName {}
50
51impl Hash for EnvName {
52    fn hash<H: Hasher>(&self, state: &mut H) {
53        // All environment variables are hashed case-insensitively on all platforms
54        self.hash_case_insensitive(state);
55    }
56}
57
58impl EnvName {
59    /// Get the inner string
60    pub fn into_string(self) -> String {
61        self.0
62    }
63
64    /// Get a reference to the inner string
65    pub fn as_str(&self) -> &str {
66        &self.0
67    }
68
69    /// Hash the name case-insensitively by uppercasing each byte
70    fn hash_case_insensitive<H: Hasher>(&self, state: &mut H) {
71        for &b in self.0.as_bytes() {
72            b.to_ascii_uppercase().hash(state);
73        }
74    }
75}
76
77#[test]
78fn test_env_name_case_insensitive() {
79    // On all platforms, all environment variables are case-insensitive
80    let strings1 = [
81        EnvName::from("abc"),
82        EnvName::from("Abc"),
83        EnvName::from("aBc"),
84        EnvName::from("abC"),
85        EnvName::from("ABc"),
86        EnvName::from("aBC"),
87        EnvName::from("AbC"),
88        EnvName::from("ABC"),
89    ];
90    let strings2 = [
91        EnvName::from("xyz"),
92        EnvName::from("Xyz"),
93        EnvName::from("xYz"),
94        EnvName::from("xyZ"),
95        EnvName::from("XYz"),
96        EnvName::from("xYZ"),
97        EnvName::from("XyZ"),
98        EnvName::from("XYZ"),
99    ];
100    // All the strings in `strings1` compare equal to each other and hash the same.
101    for s1 in &strings1 {
102        for also_s1 in &strings1 {
103            assert_eq!(s1, also_s1);
104            let mut hash_set = std::collections::HashSet::new();
105            hash_set.insert(s1);
106            hash_set.insert(also_s1);
107            assert_eq!(hash_set.len(), 1);
108        }
109    }
110    // Same for `strings2`.
111    for s2 in &strings2 {
112        for also_s2 in &strings2 {
113            assert_eq!(s2, also_s2);
114            let mut hash_set = std::collections::HashSet::new();
115            hash_set.insert(s2);
116            hash_set.insert(also_s2);
117            assert_eq!(hash_set.len(), 1);
118        }
119    }
120    // But nothing in `strings1` compares equal to anything in `strings2`. We also assert that
121    // their hashes are distinct. In theory they could collide, but using DefaultHasher here (which
122    // is initialized with the zero key) should prevent that from happening randomly.
123    for s1 in &strings1 {
124        for s2 in &strings2 {
125            assert_ne!(s1, s2);
126            let mut hasher1 = std::hash::DefaultHasher::new();
127            s1.hash(&mut hasher1);
128            let mut hasher2 = std::hash::DefaultHasher::new();
129            s2.hash(&mut hasher2);
130            assert_ne!(hasher1.finish(), hasher2.finish());
131        }
132    }
133}