adotenv_process/lib.rs
1//! Sets values loaded by [`adotenv`] in the current process environment.
2//!
3//! [`adotenv::load`] reads `.env` files into a [`LoadedEnvironment`] but never
4//! changes the process environment. This crate adds that step: [`apply`]. It is
5//! a separate crate because changing the environment is unsafe. The
6//! environment is shared by every thread of the process, and on some platforms
7//! reading it while another thread writes it is undefined behavior. The core
8//! `adotenv` crate forbids unsafe code.
9//!
10//! ```toml
11//! [dependencies]
12//! adotenv = { version = "1", features = ["load"] }
13//! adotenv-process = "1"
14//! ```
15//!
16//! The crate has no features of its own and needs Rust 1.81 or later.
17//!
18//! # Prefer passing values explicitly
19//!
20//! Most programs do not need to change their own environment. Read values
21//! with [`LoadedEnvironment::get`], deserialize them with the `serde` feature
22//! of `adotenv`, or pass them to a child process:
23//!
24//! ```no_run
25//! use std::process::Command;
26//!
27//! use adotenv::load::load_cascade;
28//!
29//! let loaded = load_cascade("/srv/my-app", "production")?;
30//! let status = Command::new("my-server").envs(loaded.values()).status()?;
31//! # let _ = status;
32//! # Ok::<(), Box<dyn std::error::Error>>(())
33//! ```
34//!
35//! Use [`apply`] only when code you do not control reads the process
36//! environment, such as a library that calls [`std::env::var`].
37//!
38//! # Applying a loaded environment
39//!
40//! [`apply`] checks every key and value, then sets each loaded key. A loaded
41//! key replaces a variable of the same name. Other variables are kept and
42//! nothing is removed. Values are set as loaded: `${HOME}` is not expanded.
43//! The changes cannot be rolled back.
44//!
45//! The caller must guarantee that no other thread reads or writes the process
46//! environment while [`apply`] runs. In practice, call it at the start of
47//! `main`, before starting threads or an async runtime.
48//!
49//! ```
50//! use adotenv::load::load_cascade;
51//!
52//! # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-crate-{}", std::process::id()));
53//! # std::fs::create_dir_all(&dir)?;
54//! # std::fs::write(dir.join(".env"), "APP_PORT=3000\n")?;
55//! # std::fs::write(dir.join(".env.production"), "APP_PORT=8080\n")?;
56//! let loaded = load_cascade(&dir, "production")?;
57//!
58//! // SAFETY: called at startup, before any other thread exists.
59//! unsafe { adotenv_process::apply(&loaded)? };
60//! assert_eq!(std::env::var("APP_PORT")?, "8080");
61//! # std::fs::remove_dir_all(&dir)?;
62//! # Ok::<(), Box<dyn std::error::Error>>(())
63//! ```
64//!
65//! [`validate`] runs the same checks without changing anything, and is safe
66//! to call from any thread. Both return an [`ApplyError`] for the first key or
67//! value that the process environment cannot hold.
68//!
69//! `apply` takes a [`LoadedEnvironment`], and [`apply_compact`] /
70//! [`validate_compact`] provide the same checks and mutation for
71//! [`CompactValues`]. To set resolved values, resolve them with
72//! [`LoadedEnvironment::resolve_contextual`] and set them yourself.
73
74use std::{env, fmt};
75
76use adotenv::{load::LoadedEnvironment, CompactValues};
77
78#[cfg(windows)]
79const WINDOWS_VALUE_LIMIT: usize = 32_767;
80
81/// A key or value that the process environment cannot hold.
82///
83/// Returned by [`validate`], and by [`apply`] before it changes anything. It
84/// reports the first problem, in key order. These are the inputs for which
85/// [`std::env::set_var`] may panic. The error names the key but never includes
86/// the value.
87///
88/// # Examples
89///
90/// Python dotenv lets a quoted key contain `=`. With `'APP=PORT'=8080` in
91/// `.env`:
92///
93/// ```
94/// use adotenv::load::load_cascade_with;
95/// use adotenv::Dialect;
96/// use adotenv_process::{validate, ApplyError};
97///
98/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-ApplyError-{}", std::process::id()));
99/// # std::fs::create_dir_all(&dir)?;
100/// # std::fs::write(dir.join(".env"), "'APP=PORT'=8080\n")?;
101/// let loaded = load_cascade_with(&dir, "", Dialect::PYTHON_DOTENV)?;
102/// match validate(&loaded) {
103/// Err(ApplyError::InvalidKey { key }) => assert_eq!(key, "APP=PORT"),
104/// other => panic!("expected an invalid key, got {other:?}"),
105/// }
106/// # std::fs::remove_dir_all(&dir)?;
107/// # Ok::<(), Box<dyn std::error::Error>>(())
108/// ```
109#[derive(Debug, Clone, PartialEq, Eq)]
110#[non_exhaustive]
111pub enum ApplyError {
112 /// A key is empty.
113 ///
114 /// The `adotenv` loaders and [`CompactValues`] skip empty keys, so a
115 /// loaded environment or compact map does not produce this error; the
116 /// check is a safeguard.
117 EmptyKey,
118 /// A key contains NUL or `=`.
119 InvalidKey {
120 /// The key, as loaded.
121 key: String,
122 },
123 /// A value contains NUL.
124 InvalidValue {
125 /// The key whose value contains NUL.
126 key: String,
127 },
128 /// Two keys collide on a case-insensitive platform.
129 ///
130 /// Windows environment variable names are case-insensitive. This variant
131 /// is returned only on Windows.
132 DuplicateKey {
133 /// The later key in sorted order.
134 key: String,
135 },
136 /// A value is too long for the platform.
137 ///
138 /// Windows accepts at most 32,767 UTF-16 code units per value. This variant
139 /// is returned only on Windows.
140 ValueTooLong {
141 /// The key whose value is too long.
142 key: String,
143 /// The platform limit.
144 limit: usize,
145 },
146}
147
148impl fmt::Display for ApplyError {
149 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150 match self {
151 Self::EmptyKey => formatter.write_str("environment key is empty"),
152 Self::InvalidKey { key } => {
153 write!(formatter, "environment key contains NUL or '=': {key:?}")
154 }
155 Self::InvalidValue { key } => {
156 write!(formatter, "environment value for {key:?} contains NUL")
157 }
158 Self::DuplicateKey { key } => {
159 write!(
160 formatter,
161 "environment key collides case-insensitively: {key:?}"
162 )
163 }
164 Self::ValueTooLong { key, limit } => {
165 write!(
166 formatter,
167 "environment value for {key:?} exceeds {limit} UTF-16 code units"
168 )
169 }
170 }
171 }
172}
173
174impl std::error::Error for ApplyError {}
175
176/// Checks that the process environment can hold every loaded key and value.
177///
178/// Runs the checks of [`apply`] without changing anything, so it is safe to
179/// call from any thread, for example to report a bad `.env` file early. A key
180/// must not be empty and must not contain NUL or `=`. A value must not contain
181/// NUL. Keys are checked in sorted order.
182///
183/// # Errors
184///
185/// Returns the first problem found:
186///
187/// - [`ApplyError::EmptyKey`] if a key is empty.
188/// - [`ApplyError::InvalidKey`] if a key contains NUL or `=`.
189/// - [`ApplyError::InvalidValue`] if a value contains NUL.
190/// - On Windows, [`ApplyError::DuplicateKey`] if two keys differ only by case,
191/// and [`ApplyError::ValueTooLong`] if a value exceeds 32,767 UTF-16 code
192/// units.
193///
194/// # Examples
195///
196/// With `PORT=8080` and a `TOKEN` value that contains a NUL byte in `.env`:
197///
198/// ```
199/// use adotenv::load::load_cascade;
200/// use adotenv_process::{validate, ApplyError};
201///
202/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-validate-{}", std::process::id()));
203/// # std::fs::create_dir_all(&dir)?;
204/// # std::fs::write(dir.join(".env"), "PORT=8080\nTOKEN=abc\0def\n")?;
205/// let loaded = load_cascade(&dir, "")?;
206/// let error = validate(&loaded).unwrap_err();
207/// assert_eq!(error, ApplyError::InvalidValue { key: "TOKEN".to_string() });
208/// assert_eq!(error.to_string(), r#"environment value for "TOKEN" contains NUL"#);
209/// # std::fs::remove_dir_all(&dir)?;
210/// # Ok::<(), Box<dyn std::error::Error>>(())
211/// ```
212pub fn validate(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
213 validate_pairs(environment.values())
214}
215
216fn validate_pairs<'a>(pairs: impl Iterator<Item = (&'a str, &'a str)>) -> Result<(), ApplyError> {
217 #[cfg(windows)]
218 let mut seen = std::collections::BTreeSet::new();
219 for (key, value) in pairs {
220 if key.is_empty() {
221 return Err(ApplyError::EmptyKey);
222 }
223 if key.bytes().any(|byte| byte == 0 || byte == b'=') {
224 return Err(ApplyError::InvalidKey {
225 key: key.to_string(),
226 });
227 }
228 if value.as_bytes().contains(&0) {
229 return Err(ApplyError::InvalidValue {
230 key: key.to_string(),
231 });
232 }
233 #[cfg(windows)]
234 {
235 if !seen.insert(key.to_lowercase()) {
236 return Err(ApplyError::DuplicateKey {
237 key: key.to_string(),
238 });
239 }
240 if value.encode_utf16().count() > WINDOWS_VALUE_LIMIT {
241 return Err(ApplyError::ValueTooLong {
242 key: key.to_string(),
243 limit: WINDOWS_VALUE_LIMIT,
244 });
245 }
246 }
247 }
248 Ok(())
249}
250
251/// Checks that the process environment can hold every key and value in a
252/// [`CompactValues`] map.
253///
254/// Runs the same checks as [`validate`] in sorted key order without modifying
255/// the process environment.
256///
257/// # Errors
258///
259/// Returns the first [`ApplyError`] found.
260///
261/// # Examples
262///
263/// ```
264/// use adotenv::parse_values_compact;
265/// use adotenv_process::{validate_compact, ApplyError};
266///
267/// let values = parse_values_compact("PORT=8080\nTOKEN=abc\0def\n")?;
268/// assert_eq!(
269/// validate_compact(&values),
270/// Err(ApplyError::InvalidValue { key: "TOKEN".to_string() })
271/// );
272/// # Ok::<(), Box<dyn std::error::Error>>(())
273/// ```
274pub fn validate_compact(values: &CompactValues) -> Result<(), ApplyError> {
275 validate_pairs(values.iter())
276}
277
278/// Sets every loaded key to its loaded value in the current process
279/// environment.
280///
281/// First runs [`validate`], so an environment it rejects changes nothing. Then
282/// sets each key with [`std::env::set_var`], in sorted order. A loaded key
283/// replaces a variable of the same name. Other variables are kept and nothing
284/// is removed. Values are set as loaded, without expanding references such as
285/// `${HOME}`. The changes cannot be rolled back.
286///
287/// Prefer passing [`LoadedEnvironment::values`] to a child process, or reading
288/// the values directly, unless code you do not control reads the process
289/// environment. See the [crate documentation](crate).
290///
291/// # Errors
292///
293/// Returns the [`ApplyError`] from [`validate`], before changing anything.
294///
295/// # Safety
296///
297/// No other thread may read or write the process environment while `apply`
298/// runs. That includes [`std::env::var`] and C functions such as `getenv` and
299/// `setenv` called by libraries. On some platforms such concurrent access is
300/// undefined behavior. In practice, call `apply` at the start of `main`, before
301/// starting threads or an async runtime.
302///
303/// # Examples
304///
305/// With `APP_PORT=8080` and `APP_HOST=0.0.0.0` in `.env`:
306///
307/// ```
308/// use adotenv::load::load_cascade;
309/// use adotenv_process::apply;
310///
311/// # let dir = std::env::temp_dir().join(format!("adotenv-process-doc-apply-{}", std::process::id()));
312/// # std::fs::create_dir_all(&dir)?;
313/// # std::fs::write(dir.join(".env"), "APP_PORT=8080\nAPP_HOST=0.0.0.0\n")?;
314/// let loaded = load_cascade(&dir, "")?;
315///
316/// // SAFETY: called at startup, before any other thread exists.
317/// unsafe { apply(&loaded)? };
318/// assert_eq!(std::env::var("APP_PORT")?, "8080");
319/// assert_eq!(std::env::var("APP_HOST")?, "0.0.0.0");
320/// # std::fs::remove_dir_all(&dir)?;
321/// # Ok::<(), Box<dyn std::error::Error>>(())
322/// ```
323pub unsafe fn apply(environment: &LoadedEnvironment) -> Result<(), ApplyError> {
324 validate(environment)?;
325 for (key, value) in environment.values() {
326 unsafe { env::set_var(key, value) };
327 }
328 Ok(())
329}
330
331/// Sets every key and value from a [`CompactValues`] map in the current
332/// process environment.
333///
334/// First runs [`validate_compact`], so a map it rejects changes nothing. Then
335/// sets each key with [`std::env::set_var`], in sorted order.
336///
337/// # Errors
338///
339/// Returns the [`ApplyError`] from [`validate_compact`], before changing
340/// anything.
341///
342/// # Safety
343///
344/// No other thread may read or write the process environment while
345/// `apply_compact` runs. See [`apply`] for the full safety contract.
346///
347/// # Examples
348///
349/// ```
350/// use adotenv::parse_values_compact;
351/// use adotenv_process::apply_compact;
352///
353/// let values = parse_values_compact("ADOTENV_COMPACT_DOC_PORT=8080\n")?;
354/// // SAFETY: called at startup, before any other thread exists.
355/// unsafe { apply_compact(&values)? };
356/// assert_eq!(std::env::var("ADOTENV_COMPACT_DOC_PORT")?, "8080");
357/// # Ok::<(), Box<dyn std::error::Error>>(())
358/// ```
359pub unsafe fn apply_compact(values: &CompactValues) -> Result<(), ApplyError> {
360 validate_compact(values)?;
361 for (key, value) in values.iter() {
362 unsafe { env::set_var(key, value) };
363 }
364 Ok(())
365}
366
367#[cfg(test)]
368mod tests {
369 use std::{
370 fs,
371 path::PathBuf,
372 sync::{
373 atomic::{AtomicU64, Ordering},
374 Mutex,
375 },
376 };
377
378 use super::*;
379 use adotenv::load::load_cascade;
380
381 static NEXT: AtomicU64 = AtomicU64::new(0);
382 /// The process environment is global; serialize tests that touch it.
383 static ENV_LOCK: Mutex<()> = Mutex::new(());
384
385 struct TempDir(PathBuf);
386
387 impl TempDir {
388 fn new() -> Self {
389 let path = std::env::temp_dir().join(format!(
390 "adotenv-process-{}-{}",
391 std::process::id(),
392 NEXT.fetch_add(1, Ordering::Relaxed)
393 ));
394 fs::create_dir_all(&path).unwrap();
395 Self(path)
396 }
397 fn path(&self) -> &std::path::Path {
398 &self.0
399 }
400 }
401
402 impl Drop for TempDir {
403 fn drop(&mut self) {
404 let _ = fs::remove_dir_all(&self.0);
405 }
406 }
407
408 fn environment(key: &str, value: &str) -> (TempDir, LoadedEnvironment) {
409 let dir = TempDir::new();
410 fs::write(dir.path().join(".env"), format!("{key}={value}\n")).unwrap();
411 let loaded = load_cascade(dir.path(), "").unwrap();
412 (dir, loaded)
413 }
414
415 #[test]
416 fn apply_sets_loaded_values_and_can_be_removed() {
417 let _guard = ENV_LOCK.lock().unwrap();
418 let key = format!(
419 "ADOTENV_PROCESS_{}_{}",
420 std::process::id(),
421 NEXT.fetch_add(1, Ordering::Relaxed)
422 );
423 let (_dir, loaded) = environment(&key, "value");
424 unsafe { apply(&loaded).unwrap() };
425 assert_eq!(std::env::var(&key).as_deref(), Ok("value"));
426 std::env::remove_var(&key);
427 }
428
429 #[test]
430 fn validation_rejects_nul_values_before_mutation() {
431 let _guard = ENV_LOCK.lock().unwrap();
432 let key = format!(
433 "ADOTENV_PROCESS_BAD_{}_{}",
434 std::process::id(),
435 NEXT.fetch_add(1, Ordering::Relaxed)
436 );
437 let (_dir, loaded) = environment(&key, "bad\0value");
438 assert!(matches!(
439 validate(&loaded),
440 Err(ApplyError::InvalidValue { .. })
441 ));
442 assert!(matches!(
443 unsafe { apply(&loaded) },
444 Err(ApplyError::InvalidValue { .. })
445 ));
446 assert!(std::env::var_os(&key).is_none());
447 }
448
449 #[test]
450 fn validation_rejects_nul_keys_before_mutation() {
451 let _guard = ENV_LOCK.lock().unwrap();
452 let dir = TempDir::new();
453 let key = "ADOTENV_PROCESS_NUL\0KEY";
454 fs::write(dir.path().join(".env"), format!("{key}=value\n")).unwrap();
455 let loaded =
456 adotenv::load::load_files([dir.path().join(".env")], adotenv::Dialect::DOCKER_RAW)
457 .unwrap();
458 assert_eq!(loaded.get(key), Some("value"));
459 assert!(matches!(
460 validate(&loaded),
461 Err(ApplyError::InvalidKey { ref key }) if key == "ADOTENV_PROCESS_NUL\0KEY"
462 ));
463 assert!(matches!(
464 unsafe { apply(&loaded) },
465 Err(ApplyError::InvalidKey { .. })
466 ));
467 }
468
469 #[test]
470 fn all_apply_errors_have_descriptive_messages() {
471 assert_eq!(ApplyError::EmptyKey.to_string(), "environment key is empty");
472 assert_eq!(
473 ApplyError::InvalidKey { key: "A=B".into() }.to_string(),
474 "environment key contains NUL or '=': \"A=B\""
475 );
476 assert_eq!(
477 ApplyError::InvalidValue { key: "A".into() }.to_string(),
478 "environment value for \"A\" contains NUL"
479 );
480 assert_eq!(
481 ApplyError::DuplicateKey { key: "Path".into() }.to_string(),
482 "environment key collides case-insensitively: \"Path\""
483 );
484 assert_eq!(
485 ApplyError::ValueTooLong {
486 key: "A".into(),
487 limit: 32_767,
488 }
489 .to_string(),
490 "environment value for \"A\" exceeds 32767 UTF-16 code units"
491 );
492 }
493
494 #[cfg(windows)]
495 #[test]
496 fn windows_apply_rejects_duplicates_before_mutation() {
497 let _guard = ENV_LOCK.lock().unwrap();
498 let key = format!(
499 "ADOTENV_PROCESS_CASE_{}_{}",
500 std::process::id(),
501 NEXT.fetch_add(1, Ordering::Relaxed)
502 );
503 let other = key.to_ascii_lowercase();
504 let dir = TempDir::new();
505 fs::write(dir.path().join(".env"), format!("{key}=one\n{other}=two\n")).unwrap();
506 let loaded = load_cascade(dir.path(), "").unwrap();
507 assert!(std::env::var_os(&key).is_none());
508 assert!(std::env::var_os(&other).is_none());
509 assert!(matches!(
510 unsafe { apply(&loaded) },
511 Err(ApplyError::DuplicateKey { .. })
512 ));
513 assert!(std::env::var_os(&key).is_none());
514 assert!(std::env::var_os(&other).is_none());
515 }
516
517 #[cfg(windows)]
518 #[test]
519 fn windows_accepts_the_value_length_boundary() {
520 let dir = TempDir::new();
521 let value = "x".repeat(32_767);
522 fs::write(dir.path().join(".env"), format!("A={value}\n")).unwrap();
523 let loaded = load_cascade(dir.path(), "").unwrap();
524 assert!(validate(&loaded).is_ok());
525 }
526
527 #[cfg(windows)]
528 #[test]
529 fn windows_rejects_case_insensitive_duplicate_keys() {
530 let dir = TempDir::new();
531 fs::write(dir.path().join(".env"), "PATH=one\nPath=two\n").unwrap();
532 let loaded = load_cascade(dir.path(), "").unwrap();
533 assert!(matches!(
534 validate(&loaded),
535 Err(ApplyError::DuplicateKey { ref key }) if key.eq_ignore_ascii_case("path")
536 ));
537 }
538
539 #[cfg(windows)]
540 #[test]
541 fn windows_rejects_too_long_values() {
542 let dir = TempDir::new();
543 let value = "x".repeat(32_768);
544 fs::write(dir.path().join(".env"), format!("A={value}\n")).unwrap();
545 let loaded = load_cascade(dir.path(), "").unwrap();
546 assert!(matches!(
547 validate(&loaded),
548 Err(ApplyError::ValueTooLong {
549 ref key,
550 limit: 32_767
551 }) if key == "A"
552 ));
553 }
554
555 #[test]
556 fn error_messages_include_the_key() {
557 let error = ApplyError::InvalidKey { key: "A=B".into() };
558 assert!(error.to_string().contains("A=B"));
559 }
560
561 #[test]
562 fn apply_compact_sets_values_and_validates_before_mutation() {
563 let _guard = ENV_LOCK.lock().unwrap();
564 let key = format!(
565 "ADOTENV_PROCESS_COMPACT_{}_{}",
566 std::process::id(),
567 NEXT.fetch_add(1, Ordering::Relaxed)
568 );
569 let dir = TempDir::new();
570 fs::write(dir.path().join(".env"), format!("{key}=compact-val\n")).unwrap();
571 let compact = adotenv::load::load_cascade_values_compact(dir.path(), "").unwrap();
572 assert!(validate_compact(&compact).is_ok());
573 unsafe { apply_compact(&compact).unwrap() };
574 assert_eq!(std::env::var(&key).as_deref(), Ok("compact-val"));
575 std::env::remove_var(&key);
576
577 let bad_key = format!(
578 "ADOTENV_PROCESS_COMPACT_BAD_{}_{}",
579 std::process::id(),
580 NEXT.fetch_add(1, Ordering::Relaxed)
581 );
582 let good_key = format!(
583 "ADOTENV_PROCESS_COMPACT_GOOD_{}_{}",
584 std::process::id(),
585 NEXT.fetch_add(1, Ordering::Relaxed)
586 );
587 // Ensure earlier valid keys are not mutated when a later key fails validation.
588 let bad = adotenv::parse_values_compact(&format!(
589 "A_{good_key}=should-not-be-set\nZ_{bad_key}=bad\0val\n"
590 ))
591 .unwrap();
592 assert_eq!(
593 validate_compact(&bad),
594 Err(ApplyError::InvalidValue {
595 key: format!("Z_{bad_key}")
596 })
597 );
598 assert_eq!(
599 unsafe { apply_compact(&bad) },
600 Err(ApplyError::InvalidValue {
601 key: format!("Z_{bad_key}")
602 })
603 );
604 assert!(std::env::var_os(format!("A_{good_key}")).is_none());
605 assert!(std::env::var_os(format!("Z_{bad_key}")).is_none());
606
607 let nul_key = adotenv::parse_values_compact_with(
608 "ADOTENV_COMPACT_NUL\0KEY=1\n",
609 adotenv::Dialect::DOCKER_RAW,
610 )
611 .unwrap();
612 assert_eq!(
613 validate_compact(&nul_key),
614 Err(ApplyError::InvalidKey {
615 key: "ADOTENV_COMPACT_NUL\0KEY".to_string()
616 })
617 );
618
619 let eq_key = adotenv::parse_values_compact_with(
620 "'APP=PORT'=8080\n",
621 adotenv::Dialect::PYTHON_DOTENV,
622 )
623 .unwrap();
624 assert_eq!(
625 validate_compact(&eq_key),
626 Err(ApplyError::InvalidKey {
627 key: "APP=PORT".to_string()
628 })
629 );
630
631 assert!(validate_compact(&CompactValues::default()).is_ok());
632 unsafe { apply_compact(&CompactValues::default()).unwrap() };
633 }
634
635 #[cfg(windows)]
636 #[test]
637 fn windows_compact_validation_and_apply_boundary() {
638 let _guard = ENV_LOCK.lock().unwrap();
639
640 let dup = adotenv::parse_values_compact("PATH=one\nPath=two\n").unwrap();
641 assert!(matches!(
642 validate_compact(&dup),
643 Err(ApplyError::DuplicateKey { ref key }) if key.eq_ignore_ascii_case("path")
644 ));
645
646 let too_long =
647 adotenv::parse_values_compact(&format!("A={}\n", "x".repeat(32_768))).unwrap();
648 assert!(matches!(
649 validate_compact(&too_long),
650 Err(ApplyError::ValueTooLong { ref key, limit: 32_767 }) if key == "A"
651 ));
652
653 // 16,384 surrogate pairs = 32,768 UTF-16 code units (exceeds 32,767).
654 let surrogates =
655 adotenv::parse_values_compact(&format!("A={}\n", "😀".repeat(16_384))).unwrap();
656 assert!(matches!(
657 validate_compact(&surrogates),
658 Err(ApplyError::ValueTooLong { ref key, limit: 32_767 }) if key == "A"
659 ));
660
661 let key = format!(
662 "ADOTENV_PROCESS_WIN_BOUNDARY_{}_{}",
663 std::process::id(),
664 NEXT.fetch_add(1, Ordering::Relaxed)
665 );
666 let value = "x".repeat(32_767);
667 let boundary = adotenv::parse_values_compact(&format!("{key}={value}\n")).unwrap();
668 assert!(validate_compact(&boundary).is_ok());
669 unsafe { apply_compact(&boundary).unwrap() };
670 assert_eq!(std::env::var(&key).as_deref(), Ok(value.as_str()));
671 std::env::remove_var(&key);
672 }
673}