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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![allow(unknown_lints)]
#![allow(clippy::manual_let_else)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(rust_2021_compatibility)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
#![forbid(unsafe_code)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! ENV is a hash-like accessor for environment variables.
//!
//! This module implements the [`ENV`] singleton object from Ruby Core.
//!
//! In Artichoke, the environment variable store is modeled as a hash map of
//! byte vector keys and values, e.g. `HashMap<Vec<u8>, Vec<u8>>`. Backends are
//! expected to convert their internals to this representation in their public
//! APIs. For this reason, all APIs exposed by ENV backends in this crate are
//! fallible.
//!
//! You can use this object in your application by accessing it directly. As a
//! Core API, it is globally available:
//!
//! ```ruby
//! ENV["PATH"]
//! ENV["PS1"] = 'artichoke> '
//! ```
//!
//! There are two `ENV` implementations in this crate:
//!
//! - [`Memory`], enabled by default, implements an `ENV` store and accessor on
//!   top of a Rust [`HashMap`]. This backend does not query or modify the host
//!   system.
//! - [`System`], enabled when the **system-env** feature is activated, is a
//!   proxy for the system environment and uses platform-specific APIs defined
//!   in the [Rust Standard Library].
//!
//! # Examples
//!
//! Using the in-memory backend allows safely manipulating an emulated environment:
//!
//! ```
//! # use spinoso_env::Memory;
//! # fn example() -> Result<(), spinoso_env::Error> {
//! let mut env = Memory::new();
//! // This does not alter the behavior of the host Rust process.
//! env.put(b"PATH", None)?;
//! // `Memory` backends start out empty.
//! assert_eq!(env.get(b"HOME")?, None);
//! # Ok(())
//! # }
//! # example().unwrap()
//! ```
//!
//! System backends inherit and mutate the environment from the current Rust
//! process:
//!
//! ```
//! # #[cfg(feature = "system-env")]
//! # use spinoso_env::System;
//! # #[cfg(feature = "system-env")]
//! const ENV: System = System::new();
//! # #[cfg(feature = "system-env")]
//! # fn example() -> Result<(), spinoso_env::Error> {
//! ENV.put(b"RUBY", Some(b"Artichoke"))?;
//! assert!(ENV.get(b"PATH")?.is_some());
//! # Ok(())
//! # }
//! # #[cfg(feature = "system-env")]
//! # example().unwrap()
//! ```
//!
//! # Crate features
//!
//! This crate requires [`std`], the Rust Standard Library.
//!
//! All features are enabled by default:
//!
//! - **system-env** - Enable an `ENV` backend that accesses the host system's
//!   environment variables via the [`std::env`] module.
//!
#![cfg_attr(
    not(feature = "system-env"),
    doc = "[`System`]: https://artichoke.github.io/artichoke/spinoso_env/struct.System.html"
)]
//! [`ENV`]: https://ruby-doc.org/core-3.1.2/ENV.html
//! [`HashMap`]: std::collections::HashMap
//! [Rust Standard Library]: std
//! [`std::env`]: module@std::env

// Ensure code blocks in `README.md` compile
#[cfg(all(doctest, feature = "system-env"))]
#[doc = include_str!("../README.md")]
mod readme {}

use core::fmt;
use std::borrow::Cow;
use std::error;

#[cfg(feature = "system-env")]
use scolapasta_path::ConvertBytesError;
use scolapasta_string_escape::format_debug_escape_into;

mod env;

pub use env::memory::Memory;
#[cfg(feature = "system-env")]
pub use env::system::System;

/// Sum type of all errors possibly returned from [`get`], [`put`], and
/// [`to_map`].
///
/// These APIs can return errors under several conditions:
///
/// - An environment variable name is not convertible to a [platform string].
/// - An environment variable value is not convertible to a [platform string].
/// - An environment variable name contains a NUL byte.
/// - An environment variable name contains an `=` byte.
/// - An environment variable value contains a NUL byte.
///
/// Ruby represents these error conditions with different exception types.
///
/// [`get`]: Memory::get
/// [`put`]: Memory::put
/// [`to_map`]: Memory::to_map
/// [platform string]: std::ffi::OsString
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Error {
    /// Error that indicates an argument parsing or value logic error occurred.
    ///
    /// See [`ArgumentError`].
    Argument(ArgumentError),
    /// Error that indicates the access to the underlying platform APIs failed.
    ///
    /// This error type corresponds to the `EINVAL` syscall error.
    ///
    /// See [`InvalidError`].
    Invalid(InvalidError),
}

#[cfg(feature = "system-env")]
impl From<ConvertBytesError> for Error {
    fn from(err: ConvertBytesError) -> Self {
        Self::Argument(err.into())
    }
}

impl From<ArgumentError> for Error {
    #[inline]
    fn from(err: ArgumentError) -> Self {
        Self::Argument(err)
    }
}

impl From<InvalidError> for Error {
    #[inline]
    fn from(err: InvalidError) -> Self {
        Self::Invalid(err)
    }
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ENV error")
    }
}

impl error::Error for Error {
    #[inline]
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Self::Argument(ref err) => Some(err),
            Self::Invalid(ref err) => Some(err),
        }
    }
}

/// Error that indicates an argument parsing or value logic error occurred.
///
/// Argument errors have an associated message.
///
/// This error corresponds to the [Ruby `ArgumentError` Exception class].
///
/// # Examples
///
/// ```
/// # use spinoso_env::ArgumentError;
/// let err = ArgumentError::new();
/// assert_eq!(err.message(), "ArgumentError");
///
/// let err = ArgumentError::with_message("bad environment variable name: contains null byte");
/// assert_eq!(
///     err.message(),
///     "bad environment variable name: contains null byte"
/// );
/// ```
///
/// [Ruby `ArgumentError` Exception class]: https://ruby-doc.org/core-3.1.2/ArgumentError.html
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct ArgumentError(&'static str);

impl From<&'static str> for ArgumentError {
    #[inline]
    fn from(message: &'static str) -> Self {
        Self::with_message(message)
    }
}

#[cfg(feature = "system-env")]
impl From<ConvertBytesError> for ArgumentError {
    fn from(_err: ConvertBytesError) -> Self {
        Self::with_message("bytes could not be converted to a platform string")
    }
}

impl Default for ArgumentError {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for ArgumentError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())
    }
}

impl error::Error for ArgumentError {}

impl ArgumentError {
    /// Construct a new, default argument error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::ArgumentError;
    /// const ERR: ArgumentError = ArgumentError::new();
    /// assert_eq!(ERR.message(), "ArgumentError");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self("ArgumentError")
    }

    /// Construct a new, argument error with a message.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::ArgumentError;
    /// const ERR: ArgumentError =
    ///     ArgumentError::with_message("bad environment variable name: contains null byte");
    /// assert_eq!(
    ///     ERR.message(),
    ///     "bad environment variable name: contains null byte"
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub const fn with_message(message: &'static str) -> Self {
        Self(message)
    }

    /// Retrieve the exception message associated with this argument error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::ArgumentError;
    /// let err = ArgumentError::new();
    /// assert_eq!(err.message(), "ArgumentError");
    ///
    /// let err = ArgumentError::with_message("bad environment variable name: contains null byte");
    /// assert_eq!(
    ///     err.message(),
    ///     "bad environment variable name: contains null byte"
    /// );
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        self.0
    }
}

/// Error that indicates the underlying platform API returned an error.
///
/// This error is typically returned by the operating system and corresponds to
/// `EINVAL`.
///
/// # Examples
///
/// ```
/// # use spinoso_env::InvalidError;
/// let err = InvalidError::new();
/// assert_eq!(err.message(), b"Errno::EINVAL");
///
/// let err = InvalidError::with_message("Invalid argument - setenv()");
/// assert_eq!(err.message(), b"Invalid argument - setenv()");
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct InvalidError(Cow<'static, [u8]>);

impl fmt::Display for InvalidError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        format_debug_escape_into(f, self.message())
    }
}

impl error::Error for InvalidError {}

impl From<&'static str> for InvalidError {
    #[inline]
    fn from(message: &'static str) -> Self {
        Self::with_message(message)
    }
}

impl From<&'static [u8]> for InvalidError {
    #[inline]
    fn from(message: &'static [u8]) -> Self {
        Self(Cow::Borrowed(message))
    }
}

impl From<Vec<u8>> for InvalidError {
    #[inline]
    fn from(message: Vec<u8>) -> Self {
        Self(Cow::Owned(message))
    }
}

impl InvalidError {
    /// Construct a new, default invalid error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::InvalidError;
    /// const ERR: InvalidError = InvalidError::new();
    /// assert_eq!(ERR.message(), b"Errno::EINVAL");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        const MESSAGE: &[u8] = b"Errno::EINVAL";

        Self(Cow::Borrowed(MESSAGE))
    }

    /// Construct a new, invalid error with a message.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::InvalidError;
    /// const ERR: InvalidError = InvalidError::with_message("Invalid argument - setenv()");
    /// assert_eq!(ERR.message(), b"Invalid argument - setenv()");
    /// ```
    #[inline]
    #[must_use]
    pub const fn with_message(message: &'static str) -> Self {
        Self(Cow::Borrowed(message.as_bytes()))
    }

    /// Retrieve the exception message associated with this invalid error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::InvalidError;
    /// let err = InvalidError::new();
    /// assert_eq!(err.message(), b"Errno::EINVAL");
    /// ```
    #[inline]
    #[must_use]
    pub fn message(&self) -> &[u8] {
        &self.0
    }

    /// Consume this error and return the inner message.
    ///
    /// This method allows taking ownership of this error's message without an
    /// allocation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_env::InvalidError;
    /// # use std::borrow::Cow;
    /// let err = InvalidError::new();
    /// assert_eq!(err.into_message(), Cow::Borrowed(b"Errno::EINVAL"));
    /// ```
    #[inline]
    #[must_use]
    pub fn into_message(self) -> Cow<'static, [u8]> {
        self.0
    }
}