zenoh_keyexpr/key_expr/
owned.rs

1//
2// Copyright (c) 2023 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13//
14extern crate alloc;
15
16// use crate::core::WireExpr;
17use alloc::{borrow::ToOwned, boxed::Box, string::String, sync::Arc};
18use core::{
19    convert::TryFrom,
20    fmt,
21    ops::{Deref, Div},
22    str::FromStr,
23};
24
25use super::{canon::Canonize, keyexpr, nonwild_keyexpr};
26
27/// A [`Arc<str>`] newtype that is statically known to be a valid key expression.
28///
29/// See [`keyexpr`](super::borrowed::keyexpr).
30#[derive(Clone, PartialEq, Eq, Hash, serde::Deserialize)]
31#[cfg_attr(feature = "std", derive(schemars::JsonSchema))]
32#[serde(try_from = "String")]
33pub struct OwnedKeyExpr(pub(crate) Arc<str>);
34impl serde::Serialize for OwnedKeyExpr {
35    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
36    where
37        S: serde::Serializer,
38    {
39        self.0.serialize(serializer)
40    }
41}
42
43impl OwnedKeyExpr {
44    /// Equivalent to `<OwnedKeyExpr as TryFrom>::try_from(t)`.
45    ///
46    /// Will return an Err if `t` isn't a valid key expression.
47    /// Note that to be considered a valid key expression, a string MUST be canon.
48    ///
49    /// [`OwnedKeyExpr::autocanonize`] is an alternative constructor that will canonize the passed expression before constructing it.
50    pub fn new<T, E>(t: T) -> Result<Self, E>
51    where
52        Self: TryFrom<T, Error = E>,
53    {
54        Self::try_from(t)
55    }
56
57    /// Canonizes the passed value before returning it as an `OwnedKeyExpr`.
58    ///
59    /// Will return Err if the passed value isn't a valid key expression despite canonization.
60    pub fn autocanonize<T, E>(mut t: T) -> Result<Self, E>
61    where
62        Self: TryFrom<T, Error = E>,
63        T: Canonize,
64    {
65        t.canonize();
66        Self::new(t)
67    }
68
69    /// Constructs an OwnedKeyExpr without checking [`keyexpr`]'s invariants
70    /// # Safety
71    /// Key Expressions must follow some rules to be accepted by a Zenoh network.
72    /// Messages addressed with invalid key expressions will be dropped.
73    pub unsafe fn from_string_unchecked(s: String) -> Self {
74        Self::from_boxed_str_unchecked(s.into_boxed_str())
75    }
76    /// Constructs an OwnedKeyExpr without checking [`keyexpr`]'s invariants
77    /// # Safety
78    /// Key Expressions must follow some rules to be accepted by a Zenoh network.
79    /// Messages addressed with invalid key expressions will be dropped.
80    pub unsafe fn from_boxed_str_unchecked(s: Box<str>) -> Self {
81        OwnedKeyExpr(s.into())
82    }
83}
84
85#[allow(clippy::suspicious_arithmetic_impl)]
86impl Div<&keyexpr> for OwnedKeyExpr {
87    type Output = Self;
88    fn div(self, rhs: &keyexpr) -> Self::Output {
89        &self / rhs
90    }
91}
92
93#[allow(clippy::suspicious_arithmetic_impl)]
94impl Div<&keyexpr> for &OwnedKeyExpr {
95    type Output = OwnedKeyExpr;
96    fn div(self, rhs: &keyexpr) -> Self::Output {
97        let s: String = [self.as_str(), "/", rhs.as_str()].concat();
98        OwnedKeyExpr::autocanonize(s).unwrap() // Joining 2 key expressions should always result in a canonizable string.
99    }
100}
101
102#[test]
103fn div() {
104    let a = OwnedKeyExpr::new("a").unwrap();
105    let b = OwnedKeyExpr::new("b").unwrap();
106    let k = a / &b;
107    assert_eq!(k.as_str(), "a/b")
108}
109
110impl fmt::Debug for OwnedKeyExpr {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        self.as_ref().fmt(f)
113    }
114}
115
116impl fmt::Display for OwnedKeyExpr {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        self.as_ref().fmt(f)
119    }
120}
121
122impl Deref for OwnedKeyExpr {
123    type Target = keyexpr;
124    fn deref(&self) -> &Self::Target {
125        unsafe { keyexpr::from_str_unchecked(&self.0) }
126    }
127}
128
129impl AsRef<str> for OwnedKeyExpr {
130    fn as_ref(&self) -> &str {
131        &self.0
132    }
133}
134impl FromStr for OwnedKeyExpr {
135    type Err = zenoh_result::Error;
136    fn from_str(s: &str) -> Result<Self, Self::Err> {
137        Self::try_from(s.to_owned())
138    }
139}
140impl TryFrom<&str> for OwnedKeyExpr {
141    type Error = zenoh_result::Error;
142    fn try_from(s: &str) -> Result<Self, Self::Error> {
143        Self::try_from(s.to_owned())
144    }
145}
146impl TryFrom<String> for OwnedKeyExpr {
147    type Error = zenoh_result::Error;
148    fn try_from(value: String) -> Result<Self, Self::Error> {
149        <&keyexpr as TryFrom<&str>>::try_from(value.as_str())?;
150        Ok(Self(value.into()))
151    }
152}
153impl<'a> From<&'a keyexpr> for OwnedKeyExpr {
154    fn from(val: &'a keyexpr) -> Self {
155        OwnedKeyExpr(Arc::from(val.as_str()))
156    }
157}
158impl From<OwnedKeyExpr> for Arc<str> {
159    fn from(ke: OwnedKeyExpr) -> Self {
160        ke.0
161    }
162}
163impl From<OwnedKeyExpr> for String {
164    fn from(ke: OwnedKeyExpr) -> Self {
165        ke.as_str().to_owned()
166    }
167}
168
169/// A [`Arc<str>`] newtype that is statically known to be a valid nonwild key expression.
170///
171/// See [`nonwild_keyexpr`](super::borrowed::nonwild_keyexpr).
172#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Deserialize)]
173#[cfg_attr(feature = "std", derive(schemars::JsonSchema))]
174#[serde(try_from = "String")]
175pub struct OwnedNonWildKeyExpr(pub(crate) Arc<str>);
176impl serde::Serialize for OwnedNonWildKeyExpr {
177    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
178    where
179        S: serde::Serializer,
180    {
181        self.0.serialize(serializer)
182    }
183}
184
185impl TryFrom<String> for OwnedNonWildKeyExpr {
186    type Error = zenoh_result::Error;
187    fn try_from(value: String) -> Result<Self, Self::Error> {
188        let ke = <&keyexpr as TryFrom<&str>>::try_from(value.as_str())?;
189        <&nonwild_keyexpr as TryFrom<&keyexpr>>::try_from(ke)?;
190        Ok(Self(value.into()))
191    }
192}
193impl<'a> From<&'a nonwild_keyexpr> for OwnedNonWildKeyExpr {
194    fn from(val: &'a nonwild_keyexpr) -> Self {
195        OwnedNonWildKeyExpr(Arc::from(val.as_str()))
196    }
197}
198
199impl Deref for OwnedNonWildKeyExpr {
200    type Target = nonwild_keyexpr;
201    fn deref(&self) -> &Self::Target {
202        unsafe { nonwild_keyexpr::from_str_unchecked(&self.0) }
203    }
204}
205
206#[allow(clippy::suspicious_arithmetic_impl)]
207impl Div<&keyexpr> for &OwnedNonWildKeyExpr {
208    type Output = OwnedKeyExpr;
209    fn div(self, rhs: &keyexpr) -> Self::Output {
210        let s: String = [self.as_str(), "/", rhs.as_str()].concat();
211        OwnedKeyExpr::autocanonize(s).unwrap() // Joining 2 key expressions should always result in a canonizable string.
212    }
213}
214
215#[allow(clippy::suspicious_arithmetic_impl)]
216impl Div<&nonwild_keyexpr> for &OwnedNonWildKeyExpr {
217    type Output = OwnedKeyExpr;
218    fn div(self, rhs: &nonwild_keyexpr) -> Self::Output {
219        let s: String = [self.as_str(), "/", rhs.as_str()].concat();
220        s.try_into().unwrap() // Joining 2 non wild key expressions should always result in a non wild string.
221    }
222}