Skip to main content

nu_protocol/
casing.rs

1use nu_utils::IgnoreCaseExt;
2use serde::{Deserialize, Serialize};
3use std::cmp::Ordering;
4
5#[derive(
6    Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, Serialize, Deserialize,
7)]
8pub enum Casing {
9    #[default]
10    Sensitive,
11    Insensitive,
12}
13
14pub(crate) mod private {
15    pub trait Seal {}
16}
17
18pub trait CaseSensitivity: private::Seal + 'static {
19    fn eq(lhs: &str, rhs: &str) -> bool;
20
21    fn cmp(lhs: &str, rhs: &str) -> Ordering;
22}
23
24pub struct CaseSensitive;
25pub struct CaseInsensitive;
26
27impl private::Seal for CaseSensitive {}
28impl private::Seal for CaseInsensitive {}
29
30impl CaseSensitivity for CaseSensitive {
31    #[inline]
32    fn eq(lhs: &str, rhs: &str) -> bool {
33        lhs == rhs
34    }
35
36    #[inline]
37    fn cmp(lhs: &str, rhs: &str) -> Ordering {
38        lhs.cmp(rhs)
39    }
40}
41
42impl CaseSensitivity for CaseInsensitive {
43    #[inline]
44    fn eq(lhs: &str, rhs: &str) -> bool {
45        lhs.eq_ignore_case(rhs)
46    }
47
48    #[inline]
49    fn cmp(lhs: &str, rhs: &str) -> Ordering {
50        lhs.cmp_ignore_case(rhs)
51    }
52}
53
54/// Wraps `Self` in a type that affects the case sensitivity of operations
55///
56/// Using methods of [`CaseSensitivity`] in `Wrapper` implementations are not mandotary.
57/// They are provided mostly for convenience and to have a common implementation for comparisons
58pub trait WrapCased {
59    /// Wrapper type generic over case sensitivity.
60    type Wrapper<S: CaseSensitivity>;
61
62    fn case_sensitive(self) -> Self::Wrapper<CaseSensitive>;
63    fn case_insensitive(self) -> Self::Wrapper<CaseInsensitive>;
64}