lang-lib 1.3.0

A lightweight, high-performance localization library for Rust. Loads TOML language files, supports runtime locale switching, configurable paths, and automatic fallback chains.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
use std::borrow::Cow;
use std::collections::HashSet;
use std::sync::{Arc, Mutex, OnceLock, PoisonError};

use arc_swap::{ArcSwap, Guard};
use rustc_hash::FxHashMap;

use crate::error::LangError;
use crate::intern::intern;
use crate::loader;
#[cfg(feature = "registry")]
use crate::{
    change::{ChangeKind, LangChangeEvent},
    registry::emit,
};

// ---------------------------------------------------------------------------
// Internal state
// ---------------------------------------------------------------------------
//
// Translation values use a different storage strategy depending on whether
// the `hot-reload` feature is enabled:
//
// - **Default builds** store values as `&'static str` references handed out
//   by the leak-based interner. Hit-path returns are
//   `Cow::Borrowed(&'static str)` — pure pointer copies, no atomics, no
//   allocation. Memory is never reclaimed; this is correct because the
//   default build cannot reload locale files at runtime, so the interner
//   cannot grow after startup.
//
// - **`hot-reload` builds** store values as `Arc<str>`. Hit-path returns are
//   `Cow::Owned(arc.to_string())` — one allocation per call, but reloading
//   a locale drops the old `Arc<str>` instances cleanly (no leak). The
//   `Lang::translate_arc` opt-in returns `Arc<str>` directly for callers
//   that want zero-allocation reads under hot-reload at the cost of
//   refcount contention under same-key high concurrency.

/// Value-storage type used inside the per-locale map.
///
/// `&'static str` in default builds (interner-backed, zero-alloc returns);
/// `Arc<str>` in `hot-reload` builds (reclaims on reload).
#[cfg(not(feature = "hot-reload"))]
pub(crate) type StoredValue = &'static str;

/// Value-storage type used inside the per-locale map.
///
/// `&'static str` in default builds (interner-backed, zero-alloc returns);
/// `Arc<str>` in `hot-reload` builds (reclaims on reload).
#[cfg(feature = "hot-reload")]
pub(crate) type StoredValue = Arc<str>;

type LocaleMap = FxHashMap<&'static str, StoredValue>;

struct LangState {
    path: &'static str,
    active: &'static str,
    fallbacks: Arc<[&'static str]>,
    locales: FxHashMap<&'static str, Arc<LocaleMap>>,
}

impl LangState {
    fn initial() -> Self {
        Self {
            path: "locales",
            active: "en",
            fallbacks: Arc::from(["en"].as_slice()),
            locales: FxHashMap::default(),
        }
    }
}

impl Clone for LangState {
    fn clone(&self) -> Self {
        Self {
            path: self.path,
            active: self.active,
            fallbacks: Arc::clone(&self.fallbacks),
            locales: self.locales.clone(),
        }
    }
}

static STATE: OnceLock<ArcSwap<LangState>> = OnceLock::new();
static WRITE_LOCK: Mutex<()> = Mutex::new(());

fn state() -> &'static ArcSwap<LangState> {
    STATE.get_or_init(|| ArcSwap::new(Arc::new(LangState::initial())))
}

fn snapshot() -> Guard<Arc<LangState>> {
    state().load()
}

fn with_write<F>(mutate: F)
where
    F: FnOnce(&mut LangState),
{
    let _guard = WRITE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);
    let current = state().load_full();
    let mut next = (*current).clone();
    mutate(&mut next);
    state().store(Arc::new(next));
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// The main entry point for configuring and querying the localization system.
///
/// `Lang` manages process-global state behind a lock-free [`arc_swap::ArcSwap`]
/// snapshot. Configure it once during startup, load the locales your
/// application needs, and then use [`t!`](crate::t) or [`Lang::translate`]
/// wherever translated text is needed.
///
/// Concurrent calls to [`Lang::translate`] do not contend on any lock. Write
/// operations (`set_*`, [`Lang::load`], [`Lang::unload`]) briefly serialize
/// against each other but never block readers.
pub struct Lang;

/// A lightweight, request-scoped translation helper.
///
/// `Translator` stores an interned locale identifier and forwards lookups to
/// the global [`Lang`] store without mutating the process-wide active locale.
/// This makes it a good fit for web handlers, jobs, and other code paths
/// where locale is part of the input rather than part of global application
/// state.
///
/// Cloning a `Translator` is cheap — the locale is held as a `&'static str`,
/// so the operation is a pointer copy and no allocation occurs.
///
/// # Examples
///
/// ```rust,no_run
/// use lang_lib::{Lang, Translator};
///
/// Lang::load_from("en", "tests/fixtures/locales").unwrap();
/// let translator = Translator::new("en");
///
/// let title = translator.translate_with_fallback("welcome", "Welcome");
/// assert_eq!(title, "Welcome");
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Translator {
    locale: &'static str,
}

impl Translator {
    /// Creates a translator bound to a specific locale.
    #[must_use]
    pub fn new(locale: impl AsRef<str>) -> Self {
        Self {
            locale: intern(locale.as_ref()),
        }
    }

    /// Returns the locale used by this translator.
    #[must_use]
    pub fn locale(&self) -> &'static str {
        self.locale
    }

    /// Translates a key using this translator's locale.
    ///
    /// The returned value borrows directly into the interned translation
    /// store on the hit path and into `key` on the complete-miss path. Both
    /// outcomes are zero-allocation.
    #[must_use]
    pub fn translate<'a>(&self, key: &'a str) -> Cow<'a, str> {
        Lang::translate(key, Some(self.locale), None)
    }

    /// Translates a key using this translator's locale and an inline fallback.
    ///
    /// The returned value borrows directly into the interned translation
    /// store on the hit path, into `fallback` when the lookup misses, and
    /// into `key` only if no fallback resolves either. All three outcomes
    /// are zero-allocation.
    #[must_use]
    pub fn translate_with_fallback<'a>(&self, key: &'a str, fallback: &'a str) -> Cow<'a, str> {
        Lang::translate(key, Some(self.locale), Some(fallback))
    }

    /// Translates a key, returning the value as an `Arc<str>`.
    ///
    /// Available when the `hot-reload` feature is enabled. Forwards to
    /// [`Lang::translate_arc`] with this translator's locale. See that
    /// method's documentation for the contention trade-off.
    #[cfg(feature = "hot-reload")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hot-reload")))]
    #[must_use]
    pub fn translate_arc(&self, key: &str) -> Arc<str> {
        Lang::translate_arc(key, Some(self.locale), None)
    }

    /// Translates a key with an inline fallback, returning the value as an
    /// `Arc<str>`.
    ///
    /// Available when the `hot-reload` feature is enabled. Forwards to
    /// [`Lang::translate_arc`] with this translator's locale.
    #[cfg(feature = "hot-reload")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hot-reload")))]
    #[must_use]
    pub fn translate_arc_with_fallback(&self, key: &str, fallback: &str) -> Arc<str> {
        Lang::translate_arc(key, Some(self.locale), Some(fallback))
    }
}

impl Lang {
    /// Sets the directory where language files are looked up.
    ///
    /// Defaults to `"locales"`. Call this before the first [`Lang::load`] if
    /// your project stores files elsewhere.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    /// Lang::set_path("assets/lang");
    /// ```
    pub fn set_path(path: impl AsRef<str>) {
        let interned = intern(path.as_ref());
        with_write(|state| state.path = interned);
    }

    /// Returns the current language file path.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::set_path("assets/locales");
    /// assert_eq!(Lang::path(), "assets/locales");
    /// ```
    #[must_use]
    pub fn path() -> &'static str {
        snapshot().path
    }

    /// Sets the active locale used when no locale is specified in `t!`.
    ///
    /// The locale does not need to be loaded before calling this, but
    /// translations will be empty until it is.
    ///
    /// This method is a good fit for single-user applications, CLIs, and
    /// startup-time configuration. In request-driven servers, prefer passing
    /// an explicit locale to [`Lang::translate`] or [`t!`](crate::t) so one
    /// request does not change another request's active locale.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    /// Lang::set_locale("es");
    /// ```
    pub fn set_locale(locale: impl AsRef<str>) {
        let interned = intern(locale.as_ref());
        with_write(|state| state.active = interned);
    }

    /// Returns the currently active locale.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::set_locale("fr");
    /// assert_eq!(Lang::locale(), "fr");
    /// ```
    #[must_use]
    pub fn locale() -> &'static str {
        snapshot().active
    }

    /// Sets the fallback locale chain.
    ///
    /// When a key is not found in the requested locale, each fallback is
    /// checked in order. The last resort is the inline `fallback:` argument
    /// in `t!`, and if that is absent, the key itself is returned.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    /// Lang::set_fallbacks(vec!["en".to_string()]);
    /// ```
    #[allow(clippy::needless_pass_by_value, reason = "preserves 1.0.x signature")]
    pub fn set_fallbacks(chain: Vec<String>) {
        let interned: Vec<&'static str> = chain.iter().map(|s| intern(s)).collect();
        let arc: Arc<[&'static str]> = Arc::from(interned);
        with_write(|state| state.fallbacks = Arc::clone(&arc));
    }

    /// Loads a locale from disk.
    ///
    /// Reads `{path}/{locale}.toml` and stores all translations in memory.
    /// Calling this a second time for the same locale replaces the existing
    /// translations with a fresh load from disk.
    ///
    /// Locale names must be single file stems such as `en`, `en-US`, or
    /// `pt_BR`. Path separators and relative path components are rejected.
    ///
    /// # Errors
    ///
    /// Returns [`LangError::Io`] if the file cannot be read, or
    /// [`LangError::Parse`] if the TOML is invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    /// Lang::set_path("locales");
    /// Lang::load("en").unwrap();
    /// Lang::load("es").unwrap();
    /// ```
    pub fn load(locale: impl AsRef<str>) -> Result<(), LangError> {
        let locale = locale.as_ref();
        let path = snapshot().path;
        let map = loader::load_file(path, locale)?;
        let interned_locale = intern(locale);
        let arc_map: Arc<LocaleMap> = Arc::new(map);
        #[cfg(feature = "registry")]
        let was_present = snapshot().locales.contains_key(interned_locale);
        with_write(|state| {
            let _ = state.locales.insert(interned_locale, Arc::clone(&arc_map));
        });
        #[cfg(feature = "registry")]
        emit(LangChangeEvent {
            locale: interned_locale,
            kind: if was_present {
                ChangeKind::Reloaded
            } else {
                ChangeKind::Loaded
            },
        });
        Ok(())
    }

    /// Loads a locale from a specific path, ignoring the global path setting.
    ///
    /// Useful when a project stores one locale separately from the others.
    /// Locale names follow the same validation rules as [`Lang::load`].
    ///
    /// # Errors
    ///
    /// Returns [`LangError::Io`] or [`LangError::Parse`] on failure.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::load_from("en", "tests/fixtures/locales").unwrap();
    /// ```
    pub fn load_from(locale: impl AsRef<str>, path: &str) -> Result<(), LangError> {
        let locale = locale.as_ref();
        let map = loader::load_file(path, locale)?;
        let interned_locale = intern(locale);
        let arc_map: Arc<LocaleMap> = Arc::new(map);
        #[cfg(feature = "registry")]
        let was_present = snapshot().locales.contains_key(interned_locale);
        with_write(|state| {
            let _ = state.locales.insert(interned_locale, Arc::clone(&arc_map));
        });
        #[cfg(feature = "registry")]
        emit(LangChangeEvent {
            locale: interned_locale,
            kind: if was_present {
                ChangeKind::Reloaded
            } else {
                ChangeKind::Loaded
            },
        });
        Ok(())
    }

    /// Returns `true` if the locale has been loaded.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::load_from("en", "tests/fixtures/locales").unwrap();
    /// assert!(Lang::is_loaded("en"));
    /// ```
    #[must_use]
    pub fn is_loaded(locale: &str) -> bool {
        snapshot().locales.contains_key(locale)
    }

    /// Returns a sorted list of all loaded locale identifiers.
    ///
    /// Sorting keeps diagnostics and tests deterministic.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::load_from("es", "tests/fixtures/locales").unwrap();
    /// Lang::load_from("en", "tests/fixtures/locales").unwrap();
    /// assert_eq!(Lang::loaded(), vec!["en", "es"]);
    /// ```
    #[must_use]
    pub fn loaded() -> Vec<&'static str> {
        let mut locales: Vec<&'static str> = snapshot().locales.keys().copied().collect();
        locales.sort_unstable();
        locales
    }

    /// Unloads a locale and removes it from the lookup table.
    ///
    /// Unloading a locale does not change the active locale or fallback chain.
    /// If either of those still references the removed locale, translation
    /// will simply skip it.
    ///
    /// Note: in `1.1.x`, translation strings are interned into a process-wide
    /// pool, so unloading a locale removes it from the lookup table but does
    /// not reclaim the interned bytes themselves. The `1.2.x` hot-reload
    /// milestone revisits this so long-running reloaders do not grow the
    /// interner without bound.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::load_from("en", "tests/fixtures/locales").unwrap();
    /// Lang::unload("en");
    /// assert!(!Lang::is_loaded("en"));
    /// ```
    pub fn unload(locale: &str) {
        #[cfg(feature = "registry")]
        let was_present = snapshot().locales.contains_key(locale);
        with_write(|state| {
            let _ = state.locales.remove(locale);
        });
        #[cfg(feature = "registry")]
        if was_present {
            emit(LangChangeEvent {
                locale: intern(locale),
                kind: ChangeKind::Unloaded,
            });
        }
    }

    /// Creates a request-scoped [`Translator`] for the provided locale.
    ///
    /// This is a convenience wrapper around [`Translator::new`]. It is most
    /// useful in server code where locale is resolved per request and passed
    /// through the handler stack.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// let translator = Lang::translator("es");
    /// assert_eq!(translator.locale(), "es");
    /// ```
    #[must_use]
    pub fn translator(locale: impl AsRef<str>) -> Translator {
        Translator::new(locale)
    }

    /// Registers a handler that fires whenever the translation store
    /// changes.
    ///
    /// Handlers fire inline on the thread that produced the change (the
    /// writer, or the watcher thread when `hot-reload` is enabled). The
    /// dispatch is lock-free and panic-isolating; a panic in one handler
    /// does not stop sibling handlers.
    ///
    /// Returns a [`registry_io::HandlerId`] that can be passed to
    /// [`Lang::off_change`] to deregister the handler.
    ///
    /// Available when the `registry` feature is enabled.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "registry")]
    /// # fn demo() {
    /// use lang_lib::Lang;
    ///
    /// let id = Lang::on_change(|event| {
    ///     println!("{:?} on {}", event.kind, event.locale);
    /// });
    /// let _ = Lang::off_change(id);
    /// # }
    /// ```
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    pub fn on_change<F>(handler: F) -> registry_io::HandlerId
    where
        F: Fn(&LangChangeEvent) + Send + Sync + 'static,
    {
        crate::registry::registry().register(handler)
    }

    /// Deregisters a change-event handler previously installed via
    /// [`Lang::on_change`].
    ///
    /// Returns `true` if a handler with the given id was removed.
    ///
    /// Available when the `registry` feature is enabled.
    #[cfg(feature = "registry")]
    #[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
    #[must_use = "off_change returns whether a handler was actually removed"]
    pub fn off_change(id: registry_io::HandlerId) -> bool {
        crate::registry::registry().unregister(id)
    }

    /// Starts watching the given directory for `<locale>.toml` changes.
    ///
    /// File modifications, atomic-rename writes, and creates are detected
    /// and debounced into a single per-file reload. Each successful reload
    /// fires a [`crate::LangChangeEvent`] through the shared registry
    /// (`registry` feature is implied by `hot-reload`).
    ///
    /// Only one watcher may be active per process. Call [`Lang::unwatch`]
    /// before starting a new one.
    ///
    /// Available when the `hot-reload` feature is enabled.
    ///
    /// # Errors
    ///
    /// Returns [`crate::WatchError::Io`] if the watcher cannot subscribe
    /// to filesystem events, or [`crate::WatchError::AlreadyRunning`] if
    /// a watcher is already active.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "hot-reload")]
    /// # fn demo() -> Result<(), lang_lib::WatchError> {
    /// use lang_lib::Lang;
    /// Lang::watch("locales")?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "hot-reload")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hot-reload")))]
    pub fn watch(dir: impl AsRef<std::path::Path>) -> Result<(), crate::WatchError> {
        crate::watch::start(dir.as_ref().to_path_buf())
    }

    /// Stops the active filesystem watcher, if any.
    ///
    /// Idempotent: calling [`Lang::unwatch`] when no watcher is running is
    /// a no-op.
    ///
    /// Available when the `hot-reload` feature is enabled.
    #[cfg(feature = "hot-reload")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hot-reload")))]
    pub fn unwatch() {
        crate::watch::stop();
    }

    /// Translates a key.
    ///
    /// Lookup order:
    /// 1. The requested locale (or active locale if `None`)
    /// 2. Each locale in the fallback chain, in order
    /// 3. The inline `fallback` string if provided
    /// 4. The key itself (never returns an empty string)
    ///
    /// The hot path is lock-free and zero-allocation: a hit returns
    /// [`Cow::Borrowed`] backed by the interned translation store; a miss
    /// with an inline fallback returns [`Cow::Borrowed`] of the user-supplied
    /// fallback; a complete miss returns [`Cow::Borrowed`] of the key.
    /// The returned value derefs to `&str` and works transparently with
    /// `format!`, `println!`, and equality against `&str`.
    ///
    /// This is the function called by the [`t!`](crate::t) macro. Prefer
    /// using the macro directly in application code.
    ///
    /// In concurrent server code, passing `Some(locale)` is usually the safest
    /// policy because it avoids mutating the process-wide active locale.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use lang_lib::Lang;
    ///
    /// Lang::load_from("en", "tests/fixtures/locales").unwrap();
    /// let text = Lang::translate("welcome", Some("en"), Some("Welcome"));
    /// assert_eq!(text, "Welcome");
    /// ```
    #[must_use]
    pub fn translate<'a>(
        key: &'a str,
        locale: Option<&'a str>,
        fallback: Option<&'a str>,
    ) -> Cow<'a, str> {
        let state = snapshot();
        let target: &str = locale.unwrap_or(state.active);

        if let Some(map) = state.locales.get(target) {
            if let Some(val) = map.get(key) {
                return stored_to_cow(val);
            }
        }

        let mut seen = HashSet::with_capacity(state.fallbacks.len());
        for &fb_locale in state.fallbacks.iter() {
            if fb_locale == target || !seen.insert(fb_locale) {
                continue;
            }
            if let Some(map) = state.locales.get(fb_locale) {
                if let Some(val) = map.get(key) {
                    return stored_to_cow(val);
                }
            }
        }

        if let Some(fb) = fallback {
            return Cow::Borrowed(fb);
        }

        Cow::Borrowed(key)
    }

    /// Translates a key, returning the value as an `Arc<str>`.
    ///
    /// Available when the `hot-reload` feature is enabled. The hit path is
    /// zero-allocation (a refcount bump on the existing `Arc<str>`); the
    /// miss paths allocate a fresh `Arc<str>` from the caller-supplied
    /// fallback or key.
    ///
    /// Use this when you want to avoid the per-call `String` allocation
    /// imposed by `Lang::translate` in `hot-reload` builds. Be aware that
    /// high concurrency on the same translation key can produce refcount
    /// cache-line contention; if you suspect this is biting you, measure
    /// and switch back to [`Lang::translate`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # #[cfg(feature = "hot-reload")]
    /// # fn demo() {
    /// use lang_lib::Lang;
    ///
    /// let value = Lang::translate_arc("greeting", Some("en"), None);
    /// println!("{value}");
    /// # }
    /// ```
    #[cfg(feature = "hot-reload")]
    #[cfg_attr(docsrs, doc(cfg(feature = "hot-reload")))]
    #[must_use]
    pub fn translate_arc(key: &str, locale: Option<&str>, fallback: Option<&str>) -> Arc<str> {
        let state = snapshot();
        let target: &str = locale.unwrap_or(state.active);

        if let Some(map) = state.locales.get(target) {
            if let Some(val) = map.get(key) {
                return Arc::clone(val);
            }
        }

        let mut seen = HashSet::with_capacity(state.fallbacks.len());
        for &fb_locale in state.fallbacks.iter() {
            if fb_locale == target || !seen.insert(fb_locale) {
                continue;
            }
            if let Some(map) = state.locales.get(fb_locale) {
                if let Some(val) = map.get(key) {
                    return Arc::clone(val);
                }
            }
        }

        Arc::from(fallback.unwrap_or(key))
    }
}

/// Coerces the per-feature `StoredValue` into a `Cow<'a, str>`.
///
/// Default build: pure pointer copy — the borrow's `'static` lifetime
/// coerces to `'a` via covariance. Zero allocation.
///
/// `hot-reload` build: allocates a new `String` from the `Arc<str>`'s
/// bytes. Avoids touching the `Arc`'s refcount, so there is no contention
/// when the same key is read from many threads simultaneously.
#[cfg(not(feature = "hot-reload"))]
#[inline]
fn stored_to_cow<'a>(val: &StoredValue) -> Cow<'a, str> {
    Cow::Borrowed(*val)
}

#[cfg(feature = "hot-reload")]
#[inline]
fn stored_to_cow<'a>(val: &StoredValue) -> Cow<'a, str> {
    Cow::Owned(val.as_ref().to_owned())
}