nstree 1.0.0

construct branched 'namespace strings' for nested subcomponents, often for logging
Documentation
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Actual representation of namespace paths - that is, *things that semantically contain* a
//! sequence of [`NamespaceComponent`][nsc]s, or (in the raw case) a sequence of
//! directly-display-able segments.
//!
//! [nsc]: `crate::component::NamespaceComponent`

use core::{fmt, iter};

#[cfg(any(feature = "alloc", test))]
use core::ops::Deref;

use crate::component::{self, NamespaceComponent};
use combinators::{CacheComponentsHint, Join};
pub use components_hint_iterator::{
    ComponentsSizeHintOverrideIter, IntoComponentsSizeHintOverrideIter,
};
pub use into_conversions::{IntoNamespacePath, IntoRawNamespacePath};
pub use into_into_raw_ns_path::IntoIntoRawNSPath;
pub use raw_ns_path_wrapper::RawNamespacePathWrapper;
pub use render::RenderStyle;

pub mod combinators;
mod components_hint_iterator;
mod into_conversions;
mod into_into_raw_ns_path;
mod multiplicity_recurse_impls;
mod raw_ns_path_wrapper;
mod reference_recurse_impls;
pub mod render;

/// Equivalent to `"::"`, but zero-sized.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct SingleEmptyComponent;

impl NamespacePath for SingleEmptyComponent {
    #[inline(always)]
    fn components(&self) -> impl IntoIterator<Item = NamespaceComponent<'_>> {
        // SAFETY: `""` does not contain any `"::"`
        iter::once(unsafe { NamespaceComponent::new_unchecked("") })
    }

    #[inline(always)]
    fn components_hint(&self) -> NamespaceComponentsHint {
        NamespaceComponentsHint::new(1, 0)
    }
}

impl RawNamespacePath for SingleEmptyComponent {
    #[inline(always)]
    fn raw_components(&self) -> impl IntoIterator<Item = impl fmt::Display> {
        iter::once(SingleEmptyComponent)
    }
}

impl fmt::Display for SingleEmptyComponent {
    #[inline(always)]
    fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // This is actually a completely empty component so it should write NOTHING :p
        Ok(())
    }
}

/// Namespace path - or namespace path "segment" - semantically representing a sequence of
/// `"::"`-separated namespace components. When you want to take something like this as a function
/// parameter, it's usually better to use [`IntoRawNamespacePath`] instead.
///
/// Unlike in [`NamespacePath`], such namespace components are raw [`fmt::Display`] implementors,
/// and hence do not enforce access to a continuous `&str` as the [`NamespacePath`] trait does.
///
/// To use a [`NamespacePath`] as a [`RawNamespacePath`], use [`NamespacePath::into_raw`], or the
/// [`RawNamespacePathWrapper`] struct.
///
/// To use an [`IntoNamespacePath`] as an [`IntoRawNamespacePath`], use
/// [`IntoNamespacePath::into_into_raw`] - or if you want to force the usage of the associated
/// [`NamespacePath`]'s components directly regardless, use [`IntoIntoRawNSPath`].
///
pub trait RawNamespacePath {
    /// Obtain raw, renderable single components of the namespace path. Each component *should not*
    /// contain `::`.
    ///
    /// When using multiple inner iterators to implement this function, you'll almost certainly
    /// need to use something like [`either::Either`] to enable composing the opaque types.
    #[must_use]
    fn raw_components(&self) -> impl IntoIterator<Item = impl fmt::Display>;

    /// Obtain the form of this [`RawNamespacePath`] that is "by-reference" - rather than owning.
    ///
    /// Useful for creating shared prefixes for use with [`RawNamespacePath::raw_join`]
    #[must_use]
    #[inline]
    fn raw_by_ref(&self) -> &Self {
        self
    }

    /// Connect this [`RawNamespacePath`] with a second raw namespace path, by creating a new
    /// [`RawNamespacePath`] with the first raw namespace path's "impl Display" components, and
    /// then the second raw namespace path's "impl Display" components.
    ///
    /// When you want to use a [`RawNamespacePath`] as a prefix for multiple, separate raw
    /// namespace paths, use [`RawNamespacePath::raw_by_ref`] to create a [`Copy`] path borrowing
    /// from the prefix you wish to use.
    #[must_use]
    #[inline]
    fn raw_join<O: IntoRawNamespacePath>(self, suffix: O) -> Join<Self, O::RawNSPath>
    where
        Self: Sized,
    {
        Join::new(self, suffix.into_raw_namespace_path())
    }

    /// Create a structure for rendering this raw namespace path (to a string or otherwise) in the
    /// given [`RenderStyle`].
    #[must_use]
    #[inline]
    fn raw_render(self, render_style: RenderStyle) -> render::RawNamespacePathRender<Self>
    where
        Self: Sized,
    {
        render::RawNamespacePathRender::new(self, render_style)
    }

    /// Create a [`RawNamespacePath`] that produces this path's sequence except when this path has
    /// no components, in which case it provides `fallback`'s namespace path component sequence
    /// instead.
    ///
    /// For example, this can be used to create a sort of "default" path component in case there
    /// are no path components.
    ///
    /// # Example
    /// ```rust
    /// use nstree::{RawNamespacePath, RenderStyle};
    ///
    /// // Provides a fallback indicating "unknown::location"
    /// fn with_fallback(location_pathway: impl RawNamespacePath) -> impl RawNamespacePath {
    ///     location_pathway.raw_fallback("unknown::location")
    /// }
    ///
    /// assert_eq!(
    ///     with_fallback("europe::uk::london").raw_render(RenderStyle::WithFirstSeparator).to_string(),
    ///     "::europe::uk::london"
    /// );
    /// assert_eq!(
    ///     with_fallback("").raw_render(RenderStyle::WithFirstSeparator).to_string(),
    ///     "::unknown::location"
    /// );
    /// assert_eq!(
    ///     with_fallback("::").raw_render(RenderStyle::WithFirstSeparator).to_string(),
    ///     "::"
    /// );
    /// ```
    ///
    /// # Conditional Fallbacks
    /// If you're creating a [`RawNamespacePath`] where you want to the fallback to only exist
    /// some of the time, strongly consider using [`RawNamespacePath::raw_maybe_fallback`] instead.
    ///
    /// It will provide a lower-indirection mechanism that using something like [`Option`] to wrap
    /// the second parameter.
    #[must_use]
    #[inline]
    fn raw_fallback<O: IntoRawNamespacePath>(
        self,
        fallback: O,
    ) -> combinators::Fallback<Self, O::RawNSPath>
    where
        Self: Sized,
    {
        combinators::Fallback::new(self, fallback.into_raw_namespace_path())
    }

    /// Like [`RawNamespacePath::raw_fallback`], but allows for the fallback to only exist
    /// some of the time.
    ///
    /// This is useful for type unification and provides for more efficient conditionality of the
    /// fallback that using [`RawNamespacePath::raw_fallback`] with something like an [`Option`] as
    /// a second argument.
    #[must_use]
    #[inline]
    fn raw_maybe_fallback<O: IntoRawNamespacePath>(
        self,
        maybe_fallback: Option<O>,
    ) -> combinators::MaybeFallback<Self, O::RawNSPath>
    where
        Self: Sized,
    {
        combinators::MaybeFallback::new(
            self,
            maybe_fallback.map(IntoRawNamespacePath::into_raw_namespace_path),
        )
    }
}

impl RawNamespacePath for () {
    #[inline]
    fn raw_components(&self) -> impl IntoIterator<Item = impl fmt::Display> {
        iter::empty::<NamespaceComponent<'static>>()
    }
}

impl RawNamespacePath for str {
    #[inline]
    fn raw_components(&self) -> impl IntoIterator<Item = impl fmt::Display> {
        component::get_components(self)
    }
}

#[cfg(any(feature = "alloc", test))]
impl RawNamespacePath for alloc::string::String {
    #[inline]
    fn raw_components(&self) -> impl IntoIterator<Item = impl fmt::Display> {
        self.as_str().raw_components()
    }
}

#[cfg(any(feature = "alloc", test))]
impl RawNamespacePath for alloc::borrow::Cow<'_, str> {
    #[inline]
    fn raw_components(&self) -> impl IntoIterator<Item = impl fmt::Display> {
        self.deref().raw_components()
    }
}

/// Utility structure for hints about the number - and bytelength - of [`NamespacePath`] components.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub struct NamespaceComponentsHint {
    /// Number of components in a [`NamespacePath`]
    pub component_count: usize,
    /// Total bytelength of all components in a [`NamespacePath`], *not* including any hypothetical
    /// `"::"` separators (which should not be present in the listed components anyway).
    pub total_component_length: usize,
}

impl NamespaceComponentsHint {
    /// Create a new [`NamespaceComponentsHint`]. The parameters are as-documented in the structure itself.
    #[inline]
    #[must_use]
    pub const fn new(component_count: usize, total_component_length: usize) -> Self {
        Self {
            component_count,
            total_component_length,
        }
    }

    /// Get the [`NamespaceComponentsHint`] for this [`NamespacePath`] if another [`NamespacePath`] was
    /// joined on immediately after
    #[inline]
    #[must_use]
    pub const fn with_appended(&self, other: Self) -> Self {
        Self {
            component_count: self.component_count + other.component_count,
            total_component_length: self.total_component_length + other.total_component_length,
        }
    }

    /// Get the [`NamespaceComponentsHint`] for a "path" of a single [`NamespaceComponent`]
    #[inline]
    #[must_use]
    pub const fn single(v: NamespaceComponent<'_>) -> Self {
        Self::new(1, v.len())
    }

    /// Return whether or not this has at least 1 component hinted at.
    #[inline]
    #[must_use]
    pub const fn has_components(&self) -> bool {
        self.component_count >= 1
    }

    /// Either get this value - if it has at least one [`NamespaceComponentsHint::component_count`]  - or get the
    /// component hints passed in as a second argument.
    #[inline]
    #[must_use]
    pub const fn has_components_or_else(&self, if_no_components: Self) -> Self {
        if self.has_components() {
            *self
        } else {
            if_no_components
        }
    }

    /// Get a [`NamespaceComponentsHint`] for some empty [`NamespacePath`] - specifically with zero
    /// components.
    #[inline]
    #[must_use]
    pub const fn empty() -> Self {
        Self::new(0, 0)
    }

    /// Extract a [`NamespaceComponentsHint`] directly from an iterator over
    /// [`NamespaceComponent`].
    ///
    /// This will actually, concretely obtain the information by iterating over the *entire*
    /// iterator.
    #[inline]
    #[must_use]
    pub fn count_from_iterator<'v, I: IntoIterator<Item = NamespaceComponent<'v>>>(
        iter: I,
    ) -> Self {
        iter.into_iter()
            .map(Self::single)
            .fold(Self::empty(), |hint_so_far, next_component_hint| {
                hint_so_far.with_appended(next_component_hint)
            })
    }

    /// Get the string bytes that this components-hint would suggest are needed to store a
    /// fully-rendered form of the associated [`NamespacePath`], when in the given
    /// [`RenderStyle`].
    ///
    /// Note that this is not guarunteed to be an exact upper bound in the case that an
    /// incorrect [`NamespaceComponentsHint`] has been produced by a [`NamespacePath`], but
    /// implementations should generally make quite a large effort to produce accurate values as
    /// caching of partial progress is typical.
    #[inline]
    #[must_use]
    pub const fn estimated_string_bytes(&self, render_style: RenderStyle) -> usize {
        let separator_bytes = "::".len() * render_style.separator_count(self.component_count);
        self.total_component_length + separator_bytes
    }
}

/// Namespace path - or namespace path "segment" - semantically representing a sequence of
/// `"::"`-separated namespace components, each accessible as a single `str` (or more accurately, a
/// [`NamespaceComponent`] that contains a `str`, but enforces the "no `::`" aspect).
///
/// These can be combined and manipulated.
pub trait NamespacePath {
    /// Obtain the actual components of this namespace path.
    ///
    /// If you intend to collect these into some container, consider using
    /// [`NamespacePath::components_with_size_hint`] instead, or
    /// [`NamespacePath::collect_components`].
    ///
    /// If you want to produce a string with separators, consider using
    /// [`NamespacePath::build_cache_string`], or directly using the specialised
    /// [`NamespacePath::render`] method with the appropriate [`RenderStyle::WithFirstSeparator`]
    /// and [byte calculation methods][bc] for preallocation, if using custom string types such as
    /// smallstr.
    ///
    /// [bc]: `render::NamespacePathRender::estimated_string_bytes`
    #[must_use]
    fn components(&self) -> impl IntoIterator<Item = NamespaceComponent<'_>>;

    /// Obtain the actual components of this namespace path, but more suitable for allocation by
    /// overriding the [`Iterator::size_hint`] with [`NamespacePath::components_hint`] information.
    ///
    /// Typically you'd want to use this when - for example - creating a vector of
    /// [`NamespaceComponent`], or derived values.
    ///
    /// See [`ComponentsSizeHintOverrideIter`] for the precise details.
    #[must_use]
    #[inline]
    fn components_with_size_hint(
        &self,
    ) -> IntoComponentsSizeHintOverrideIter<impl IntoIterator<Item = NamespaceComponent<'_>>> {
        IntoComponentsSizeHintOverrideIter::new(self.components(), self.components_hint())
    }

    /// Collect the [`NamespacePath::components`] into something, directly.
    ///
    /// This uses [`NamespacePath::components_with_size_hint`] for more efficient allocation - you
    /// should use it too.
    #[must_use]
    fn collect_components<'s, F: FromIterator<NamespaceComponent<'s>>>(&'s self) -> F {
        F::from_iter(self.components_with_size_hint())
    }

    /// Get (ideally completely accurate) information on the [`NamespacePath`], with respect to the
    /// number of components as well as the total byte-length of the components.
    ///
    /// By default, this can iterate directly over the components and calculate things using
    /// [`NamespaceComponentsHint::count_from_iterator`].
    ///
    /// However, when creating combinators, you're more likely to want [`NamespaceComponentsHint::with_appended`],
    /// and to work over the [`NamespacePath::components_hint`]s of the least-deep namespace path information.
    /// This enables the effective usage of caching.
    ///
    /// In general, you should work with the output of [`NamespacePath::components_hint`] unless you're making a
    /// [`NamespacePath`] that does not contain ANY internal namespace paths itself.
    #[must_use]
    fn components_hint(&self) -> NamespaceComponentsHint;

    /// Obtain a [`Copy`] form of this [`NamespacePath`] that is "by reference" - and has cached
    /// [`NamespacePath::components_hint`].
    ///
    /// This function is ideal for any case where you want to create multiple [`NamespacePath`]s
    /// with a shared prefix, in a nested fashion. Arguably, this is the entire reason for this
    /// library.
    ///
    /// # Example - Branching From Prefix
    /// ```rust
    /// use nstree::NamespacePath;
    ///
    /// // Note how this is NOT `Copy`. And yet we can use it as a prefix, by borrowing.
    /// #[derive(Debug)]
    /// enum Continent {
    ///     Africa,
    ///     // ...
    ///#     Antarctica,
    ///#     Asia,
    ///#     Europe,
    ///#     NorthAmerica,
    ///#     Oceania,
    ///#     SouthAmerica,
    /// }
    ///
    /// impl Continent {
    ///     const fn as_str(&self) -> &'static str {
    ///         match self {
    ///             Continent::Africa => "africa",
    ///#             Continent::Antarctica => "antarctica",
    ///#             Continent::Asia => "asia",
    ///#             Continent::Europe => "europe",
    ///#             Continent::NorthAmerica => "north-america",
    ///#             Continent::Oceania => "oceania",
    ///#             Continent::SouthAmerica => "south-america"
    ///             // ...
    ///         }
    ///     }
    /// }
    ///
    /// // This is a simple "forwarding to string" implementation, provided for illustrative
    /// // purposes as you may want to create types like this.
    /// impl NamespacePath for Continent {
    ///     fn components(&self) -> impl IntoIterator<Item = nstree::NamespaceComponent<'_>> {
    ///         self.as_str().components()
    ///     }
    ///
    ///     fn components_hint(&self) -> nstree::path::NamespaceComponentsHint {
    ///         self.as_str().components_hint()
    ///     }
    /// }
    ///
    /// // This will be our prefix
    /// let human_origin_continent = Continent::Africa;
    /// // We use the `by_ref_cache` function to create a `Copy` reference to the initial prefix,
    /// // that also holds cached "components hint" information.
    /// let human_origin_continent = human_origin_continent.by_ref_cache();
    ///
    /// // The prefix can now be used to create multiple paths
    /// let tunis = human_origin_continent.join("tunisia::tunis");
    /// let cairo = human_origin_continent.join(["egypt", "cairo"]);
    ///
    /// assert_eq!(tunis.collect_components::<Vec<_>>(), vec!["africa", "tunisia", "tunis"]);
    /// assert_eq!(cairo.collect_components::<Vec<_>>(), vec!["africa", "egypt", "cairo"]);
    /// ```
    #[must_use]
    #[inline]
    fn by_ref_cache(&self) -> CacheComponentsHint<&Self> {
        self.by_ref_only().cache_components_hint()
    }

    /// Obtain the form of this [`NamespacePath`] that is "by-reference" - rather than owning.
    ///
    /// Prefer [`NamespacePath::by_ref_cache`] for shared prefixes unless you have very specific
    /// reasons not to use that function - for instance if you're already calling this on something
    /// that is cached.
    #[must_use]
    #[inline]
    fn by_ref_only(&self) -> &Self {
        self
    }

    /// Connect this [`NamespacePath`] with a second namespace path, by creating a new
    /// [`NamespacePath`] with the first namespace path's components, and then the second namespace
    /// path's components.
    ///
    /// When you want to use a path as a prefix for multiple, separate paths - use
    /// [`NamespacePath::by_ref_cache`] to create a [`Copy`] path borrowing from the prefix you
    /// wish to use.
    ///
    /// # Example - Basic Usage
    /// ```rust
    /// use nstree::NamespacePath as _;
    ///
    /// let namespace_path = "::africa::tunisia".join(&["tunis"]);
    /// let namespace_path_2 = "::africa::tunisia::tunis";
    /// assert_eq!(
    ///     namespace_path.collect_components::<Vec<_>>(),
    ///     namespace_path_2.collect_components::<Vec<_>>()
    /// );
    /// ```
    ///
    /// # Example - "Branching" (& by-ref-cache)
    /// ```rust
    /// use nstree::NamespacePath as _;
    ///
    /// let prefix = String::from("europe");
    /// // This creates a reference to the string prefix and then caches it's components hint (e.g.
    /// // byte length and # of components). This is a `Copy` prefix so it can now be used for
    /// // branching.
    /// let prefix = prefix.by_ref_cache();
    ///
    /// let paris = prefix.join("france::paris");
    /// let london = prefix.join("uk::london");
    ///
    /// assert_eq!(paris.collect_components::<Vec<_>>(), vec!["europe", "france", "paris"]);
    /// assert_eq!(london.collect_components::<Vec<_>>(), vec!["europe", "uk", "london"]);
    /// ```
    #[must_use]
    #[inline]
    fn join<O: IntoNamespacePath>(self, suffix: O) -> Join<Self, O::NSPath>
    where
        Self: Sized,
    {
        Join::new(self, suffix.into_namespace_path())
    }

    /// Create a structure for [`fmt::Display`]ing this namespace path (to a string or otherwise) in the
    /// given [`RenderStyle`].
    ///
    /// While you can use this to create a local "cached" version of the [`NamespacePath`] in the
    /// form of a rendered string, for that usecase, you probably instead want
    /// [`NamespacePath::build_cache_string`] as that allows greater efficiency when obtaining
    /// certain information from the resultant structure for composition, and correctly avoids the
    /// risk of ambiguous encoding as a string.
    #[must_use]
    #[inline]
    fn render(self, render_style: RenderStyle) -> render::NamespacePathRender<Self>
    where
        Self: Sized,
    {
        render::NamespacePathRender::new(self, render_style)
    }

    /// Create a [`NamespacePath`] that produces this path's sequence except when this path has
    /// no components, in which case it provides `fallback`'s namespace path component sequence
    /// instead.
    ///
    /// For example, this can be used to create a sort of "default" path component in case there
    /// are no path components.
    ///
    /// # Example
    /// ```rust
    /// use nstree::{NamespacePath, RenderStyle};
    ///
    /// // Provides a fallback indicating "unknown::location"
    /// fn with_fallback(location_pathway: impl NamespacePath) -> impl NamespacePath {
    ///     location_pathway.fallback("unknown::location")
    /// }
    ///
    /// assert_eq!(
    ///     with_fallback("asia::taiwan").render(RenderStyle::WithFirstSeparator).to_string(),
    ///     "::asia::taiwan"
    /// );
    /// assert_eq!(
    ///     with_fallback("").render(RenderStyle::WithFirstSeparator).to_string(),
    ///     "::unknown::location"
    /// );
    /// assert_eq!(
    ///     with_fallback("::").render(RenderStyle::WithFirstSeparator).to_string(),
    ///     "::"
    /// );
    /// ```
    ///
    /// # Conditional Fallbacks
    /// If you're creating a [`NamespacePath`] where you want to the fallback to only exist
    /// some of the time, strongly consider using [`NamespacePath::maybe_fallback`] instead.
    ///
    /// It will provide a lower-indirection mechanism that using something like [`Option`] to wrap
    /// the second parameter.
    #[must_use]
    #[inline]
    fn fallback<O: IntoNamespacePath>(self, fallback: O) -> combinators::Fallback<Self, O::NSPath>
    where
        Self: Sized,
    {
        combinators::Fallback::new(self, fallback.into_namespace_path())
    }

    /// Like [`NamespacePath::fallback`], but allows for the fallback to only exist
    /// some of the time.
    ///
    /// This is useful for type unification and provides for more efficient conditionality of the
    /// fallback that using [`NamespacePath::fallback`] with something like an [`Option`] as
    /// a second argument.
    #[must_use]
    #[inline]
    fn maybe_fallback<O: IntoNamespacePath>(
        self,
        maybe_fallback: Option<O>,
    ) -> combinators::MaybeFallback<Self, O::NSPath>
    where
        Self: Sized,
    {
        combinators::MaybeFallback::new(
            self,
            maybe_fallback.map(IntoNamespacePath::into_namespace_path),
        )
    }

    /// Create a *wrapped* [`String`] holding the path, suitable for rendering (it is a path
    /// essentially rendered with the unambiguous [`RenderStyle::WithFirstSeparator`]).
    ///
    /// If you desire to render it without the prefix, you can use the standard
    /// [`NamespacePath::render`] mechanisms or just strip the prefix with [`str::strip_prefix`].
    ///
    /// The wrapping allows avoiding any re-calculation of [`NamespacePath::components_hint`], by
    /// simply using the one this namespace path creates - in nested [`NamespacePath`]
    /// implementations, this likely has significant caching.
    ///
    /// If you don't need that information, you can of course use [`CacheComponentsHint::into_inner`]
    /// to get the string. But most of what you'll want to do can probably be done with
    /// [`CacheComponentsHint::get_path`].
    ///
    /// ```rust
    /// use nstree::NamespacePath as _;
    ///
    /// assert_eq!(
    ///     ["europe", "uk", "london"].build_cache_string().into_inner(),
    ///     "::europe::uk::london"
    /// );
    ///
    /// assert_eq!(
    ///     ["::","::", "london"].build_cache_string().into_inner(),
    ///     "::::::london"
    /// );
    /// ```
    #[cfg(any(feature = "alloc", test))]
    #[must_use]
    fn build_cache_string(&self) -> CacheComponentsHint<alloc::string::String> {
        let components_hint = self.components_hint();
        // Uses unambiguous representation.
        let rendered_string = self.render(RenderStyle::WithFirstSeparator).to_string();
        // SAFETY:
        // * We extracted the components_hint from the namespace path
        // * We encoded the namespace path unambiguously into the string, so it internally has the
        //   same # of components with the same # of component bytes.
        unsafe { CacheComponentsHint::new_unchecked(rendered_string, components_hint) }
    }

    /// Eagerly cache the [`NamespacePath::components_hint`].
    ///
    /// This may seem trivial, but it's good practice to use this function anywhere you
    /// might be using a [`NamespacePath`] as some sort of prefix more than once, or if
    /// you're using some more complex [`NamespacePath`] construction with high nesting
    /// (e.g. a vector of path components).
    ///
    /// You're more likely to use this function via [`NamespacePath::by_ref_cache`], but it's
    /// useful on it's own, too.
    #[must_use]
    #[inline]
    fn cache_components_hint(self) -> CacheComponentsHint<Self>
    where
        Self: Sized,
    {
        CacheComponentsHint::new(self)
    }

    /// Wrap this as a [`RawNamespacePath`] that uses the components from
    /// [`NamespacePath::components`].
    #[must_use]
    #[inline]
    fn into_raw(self) -> RawNamespacePathWrapper<Self>
    where
        Self: Sized,
    {
        self.into()
    }
}

impl NamespacePath for () {
    #[inline(always)]
    fn components(&self) -> impl IntoIterator<Item = NamespaceComponent<'_>> {
        iter::empty()
    }

    #[inline]
    fn components_hint(&self) -> NamespaceComponentsHint {
        NamespaceComponentsHint::empty()
    }
}

/// This follows the semantics of [`component::get_components`] (along with other string-ish
/// impls).
///
/// Notably, this means that *empty strings produce **no namespace components** even in contexts
/// such as an array*. For example:
/// ```rust
/// use nstree::NamespacePath as _;
///
/// assert!(["", "", ""].collect_components::<Vec<_>>().is_empty());
/// ```
/// This may be unintuitive - you might expect this to emit 3 *empty* namespace path components.
impl NamespacePath for str {
    #[inline]
    fn components(&self) -> impl IntoIterator<Item = NamespaceComponent<'_>> {
        component::get_components(self)
    }

    #[inline]
    fn components_hint(&self) -> NamespaceComponentsHint {
        NamespaceComponentsHint::count_from_iterator(self.components())
    }
}

#[cfg(any(feature = "alloc", test))]
impl NamespacePath for alloc::string::String {
    #[inline]
    fn components(&self) -> impl IntoIterator<Item = NamespaceComponent<'_>> {
        self.as_str().components()
    }

    #[inline]
    fn components_hint(&self) -> NamespaceComponentsHint {
        self.as_str().components_hint()
    }
}

#[cfg(any(feature = "alloc", test))]
impl NamespacePath for alloc::borrow::Cow<'_, str> {
    #[inline]
    fn components(&self) -> impl IntoIterator<Item = NamespaceComponent<'_>> {
        self.deref().components()
    }

    #[inline]
    fn components_hint(&self) -> NamespaceComponentsHint {
        self.deref().components_hint()
    }
}

// nstree - nested namespace string-generating abstraction library
// Copyright (C) 2025  Matti <infomorphic-matti at protonmail dot com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
// ------
// SPDX-License-Identifier: GPL-3.0-or-later