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
//
// Copyright (c) 2023 ZettaScale Technology
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
//
// Contributors:
//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
//
extern crate alloc;

use super::{canon::Canonizable, keyexpr};
// use crate::core::WireExpr;
use alloc::{borrow::ToOwned, boxed::Box, string::String, sync::Arc};
use core::{
    convert::TryFrom,
    fmt,
    ops::{Deref, Div},
    str::FromStr,
};

/// A [`Arc<str>`] newtype that is statically known to be a valid key expression.
///
/// See [`keyexpr`](super::borrowed::keyexpr).
#[derive(Clone, PartialEq, Eq, Hash, serde::Deserialize)]
#[serde(try_from = "String")]
pub struct OwnedKeyExpr(pub(crate) Arc<str>);
impl serde::Serialize for OwnedKeyExpr {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.0.serialize(serializer)
    }
}

impl OwnedKeyExpr {
    /// Equivalent to `<OwnedKeyExpr as TryFrom>::try_from(t)`.
    ///
    /// Will return an Err if `t` isn't a valid key expression.
    /// Note that to be considered a valid key expression, a string MUST be canon.
    ///
    /// [`OwnedKeyExpr::autocanonize`] is an alternative constructor that will canonize the passed expression before constructing it.
    pub fn new<T, E>(t: T) -> Result<Self, E>
    where
        Self: TryFrom<T, Error = E>,
    {
        Self::try_from(t)
    }

    /// Canonizes the passed value before returning it as an `OwnedKeyExpr`.
    ///
    /// Will return Err if the passed value isn't a valid key expression despite canonization.
    pub fn autocanonize<T, E>(mut t: T) -> Result<Self, E>
    where
        Self: TryFrom<T, Error = E>,
        T: Canonizable,
    {
        t.canonize();
        Self::new(t)
    }

    /// Constructs an OwnedKeyExpr without checking [`keyexpr`]'s invariants
    /// # Safety
    /// Key Expressions must follow some rules to be accepted by a Zenoh network.
    /// Messages addressed with invalid key expressions will be dropped.
    pub unsafe fn from_string_unchecked(s: String) -> Self {
        Self::from_boxed_string_unchecked(s.into_boxed_str())
    }
    /// Constructs an OwnedKeyExpr without checking [`keyexpr`]'s invariants
    /// # Safety
    /// Key Expressions must follow some rules to be accepted by a Zenoh network.
    /// Messages addressed with invalid key expressions will be dropped.
    pub unsafe fn from_boxed_string_unchecked(s: Box<str>) -> Self {
        OwnedKeyExpr(s.into())
    }
}

#[allow(clippy::suspicious_arithmetic_impl)]
impl Div<&keyexpr> for OwnedKeyExpr {
    type Output = Self;
    fn div(self, rhs: &keyexpr) -> Self::Output {
        &self / rhs
    }
}

#[allow(clippy::suspicious_arithmetic_impl)]
impl Div<&keyexpr> for &OwnedKeyExpr {
    type Output = OwnedKeyExpr;
    fn div(self, rhs: &keyexpr) -> Self::Output {
        let s: String = [self.as_str(), "/", rhs.as_str()].concat();
        OwnedKeyExpr::autocanonize(s).unwrap() // Joining 2 key expressions should always result in a canonizable string.
    }
}

#[test]
fn div() {
    let a = OwnedKeyExpr::new("a").unwrap();
    let b = OwnedKeyExpr::new("b").unwrap();
    let k = a / &b;
    assert_eq!(k.as_str(), "a/b")
}

impl fmt::Debug for OwnedKeyExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_ref().fmt(f)
    }
}

impl fmt::Display for OwnedKeyExpr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_ref().fmt(f)
    }
}

impl Deref for OwnedKeyExpr {
    type Target = keyexpr;
    fn deref(&self) -> &Self::Target {
        unsafe { keyexpr::from_str_unchecked(&self.0) }
    }
}

impl AsRef<str> for OwnedKeyExpr {
    fn as_ref(&self) -> &str {
        &self.0
    }
}
impl FromStr for OwnedKeyExpr {
    type Err = zenoh_result::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s.to_owned())
    }
}
impl TryFrom<&str> for OwnedKeyExpr {
    type Error = zenoh_result::Error;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::try_from(s.to_owned())
    }
}
impl TryFrom<String> for OwnedKeyExpr {
    type Error = zenoh_result::Error;
    fn try_from(value: String) -> Result<Self, Self::Error> {
        <&keyexpr as TryFrom<&str>>::try_from(value.as_str())?;
        Ok(Self(value.into()))
    }
}
impl<'a> From<&'a keyexpr> for OwnedKeyExpr {
    fn from(val: &'a keyexpr) -> Self {
        OwnedKeyExpr(Arc::from(val.as_str()))
    }
}
impl From<OwnedKeyExpr> for Arc<str> {
    fn from(ke: OwnedKeyExpr) -> Self {
        ke.0
    }
}
impl From<OwnedKeyExpr> for String {
    fn from(ke: OwnedKeyExpr) -> Self {
        ke.as_str().to_owned()
    }
}