zenoh_protocol/core/
whatami.rs

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
//
// 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>
//
use alloc::string::String;
use core::{convert::TryFrom, fmt, num::NonZeroU8, ops::BitOr, str::FromStr};

use const_format::formatcp;
use zenoh_result::{bail, ZError};

#[repr(u8)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WhatAmI {
    Router = 0b001,
    #[default]
    Peer = 0b010,
    Client = 0b100,
}

impl WhatAmI {
    const STR_R: &'static str = "router";
    const STR_P: &'static str = "peer";
    const STR_C: &'static str = "client";

    const U8_R: u8 = Self::Router as u8;
    const U8_P: u8 = Self::Peer as u8;
    const U8_C: u8 = Self::Client as u8;

    pub const fn to_str(self) -> &'static str {
        match self {
            Self::Router => Self::STR_R,
            Self::Peer => Self::STR_P,
            Self::Client => Self::STR_C,
        }
    }

    #[cfg(feature = "test")]
    pub fn rand() -> Self {
        use rand::prelude::SliceRandom;
        let mut rng = rand::thread_rng();

        *[Self::Router, Self::Peer, Self::Client]
            .choose(&mut rng)
            .unwrap()
    }
}

impl TryFrom<u8> for WhatAmI {
    type Error = ();

    fn try_from(v: u8) -> Result<Self, Self::Error> {
        match v {
            Self::U8_R => Ok(Self::Router),
            Self::U8_P => Ok(Self::Peer),
            Self::U8_C => Ok(Self::Client),
            _ => Err(()),
        }
    }
}

impl FromStr for WhatAmI {
    type Err = ZError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            Self::STR_R => Ok(Self::Router),
            Self::STR_P => Ok(Self::Peer),
            Self::STR_C => Ok(Self::Client),
            _ => bail!(
                "{s} is not a valid WhatAmI value. Valid values are: {}, {}, {}.",
                Self::STR_R,
                Self::STR_P,
                Self::STR_C
            ),
        }
    }
}

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

impl From<WhatAmI> for u8 {
    fn from(w: WhatAmI) -> Self {
        w as u8
    }
}

#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WhatAmIMatcher(NonZeroU8);

impl WhatAmIMatcher {
    // We use the 7th bit for detecting whether the WhatAmIMatcher is non-zero
    const U8_0: u8 = 1 << 7;
    const U8_R: u8 = Self::U8_0 | WhatAmI::U8_R;
    const U8_P: u8 = Self::U8_0 | WhatAmI::U8_P;
    const U8_C: u8 = Self::U8_0 | WhatAmI::U8_C;
    const U8_R_P: u8 = Self::U8_0 | WhatAmI::U8_R | WhatAmI::U8_P;
    const U8_P_C: u8 = Self::U8_0 | WhatAmI::U8_P | WhatAmI::U8_C;
    const U8_R_C: u8 = Self::U8_0 | WhatAmI::U8_R | WhatAmI::U8_C;
    const U8_R_P_C: u8 = Self::U8_0 | WhatAmI::U8_R | WhatAmI::U8_P | WhatAmI::U8_C;

    pub const fn empty() -> Self {
        Self(unsafe { NonZeroU8::new_unchecked(Self::U8_0) })
    }

    pub const fn router(self) -> Self {
        Self(unsafe { NonZeroU8::new_unchecked(self.0.get() | Self::U8_R) })
    }

    pub const fn peer(self) -> Self {
        Self(unsafe { NonZeroU8::new_unchecked(self.0.get() | Self::U8_P) })
    }

    pub const fn client(self) -> Self {
        Self(unsafe { NonZeroU8::new_unchecked(self.0.get() | Self::U8_C) })
    }

    pub const fn is_empty(&self) -> bool {
        self.0.get() == Self::U8_0
    }

    pub const fn matches(&self, w: WhatAmI) -> bool {
        (self.0.get() & w as u8) != 0
    }

    pub const fn to_str(self) -> &'static str {
        match self.0.get() {
            Self::U8_0 => "",
            Self::U8_R => WhatAmI::STR_R,
            Self::U8_P => WhatAmI::STR_P,
            Self::U8_C => WhatAmI::STR_C,
            Self::U8_R_P => formatcp!("{}|{}", WhatAmI::STR_R, WhatAmI::STR_P),
            Self::U8_R_C => formatcp!("{}|{}", WhatAmI::STR_R, WhatAmI::STR_C),
            Self::U8_P_C => formatcp!("{}|{}", WhatAmI::STR_P, WhatAmI::STR_C),
            Self::U8_R_P_C => formatcp!("{}|{}|{}", WhatAmI::STR_R, WhatAmI::STR_P, WhatAmI::STR_C),

            _ => unreachable!(),
        }
    }

    #[cfg(feature = "test")]
    pub fn rand() -> Self {
        use rand::Rng;

        let mut rng = rand::thread_rng();
        let mut waim = WhatAmIMatcher::empty();
        if rng.gen_bool(0.5) {
            waim = waim.router();
        }
        if rng.gen_bool(0.5) {
            waim = waim.peer();
        }
        if rng.gen_bool(0.5) {
            waim = waim.client();
        }
        waim
    }
}

impl TryFrom<u8> for WhatAmIMatcher {
    type Error = ();

    fn try_from(v: u8) -> Result<Self, Self::Error> {
        const MIN: u8 = 0;
        const MAX: u8 = WhatAmI::U8_R | WhatAmI::U8_P | WhatAmI::U8_C;

        if (MIN..=MAX).contains(&v) {
            Ok(WhatAmIMatcher(unsafe {
                NonZeroU8::new_unchecked(Self::U8_0 | v)
            }))
        } else {
            Err(())
        }
    }
}

impl FromStr for WhatAmIMatcher {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut inner = 0;
        for s in s.split('|') {
            match s.trim() {
                "" => {}
                WhatAmI::STR_R => inner |= WhatAmI::U8_R,
                WhatAmI::STR_P => inner |= WhatAmI::U8_P,
                WhatAmI::STR_C => inner |= WhatAmI::U8_C,
                _ => return Err(()),
            }
        }
        Self::try_from(inner)
    }
}

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

impl From<WhatAmIMatcher> for u8 {
    fn from(w: WhatAmIMatcher) -> u8 {
        w.0.get()
    }
}

impl<T> BitOr<T> for WhatAmIMatcher
where
    NonZeroU8: BitOr<T, Output = NonZeroU8>,
{
    type Output = Self;

    fn bitor(self, rhs: T) -> Self::Output {
        WhatAmIMatcher(self.0 | rhs)
    }
}

impl BitOr<WhatAmI> for WhatAmIMatcher {
    type Output = Self;

    fn bitor(self, rhs: WhatAmI) -> Self::Output {
        self | rhs as u8
    }
}

impl BitOr for WhatAmIMatcher {
    type Output = Self;

    fn bitor(self, rhs: Self) -> Self::Output {
        self | rhs.0
    }
}

impl BitOr for WhatAmI {
    type Output = WhatAmIMatcher;

    fn bitor(self, rhs: Self) -> Self::Output {
        WhatAmIMatcher(unsafe {
            NonZeroU8::new_unchecked(self as u8 | rhs as u8 | WhatAmIMatcher::U8_0)
        })
    }
}

impl From<WhatAmI> for WhatAmIMatcher {
    fn from(w: WhatAmI) -> Self {
        WhatAmIMatcher(unsafe { NonZeroU8::new_unchecked(w as u8 | WhatAmIMatcher::U8_0) })
    }
}

// Serde
impl serde::Serialize for WhatAmI {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.to_str())
    }
}

pub struct WhatAmIVisitor;

impl<'de> serde::de::Visitor<'de> for WhatAmIVisitor {
    type Value = WhatAmI;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "either '{}', '{}' or '{}'",
            WhatAmI::STR_R,
            WhatAmI::STR_P,
            WhatAmI::STR_C
        )
    }
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        v.parse().map_err(|_| {
            serde::de::Error::unknown_variant(v, &[WhatAmI::STR_R, WhatAmI::STR_P, WhatAmI::STR_C])
        })
    }
    fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        self.visit_str(v)
    }
    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        self.visit_str(&v)
    }
}

impl<'de> serde::Deserialize<'de> for WhatAmI {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(WhatAmIVisitor)
    }
}

impl serde::Serialize for WhatAmIMatcher {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.to_str())
    }
}

pub struct WhatAmIMatcherVisitor;
impl<'de> serde::de::Visitor<'de> for WhatAmIMatcherVisitor {
    type Value = WhatAmIMatcher;
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "a list of whatami variants ('{}', '{}', '{}')",
            WhatAmI::STR_R,
            WhatAmI::STR_P,
            WhatAmI::STR_C
        )
    }

    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::SeqAccess<'de>,
    {
        let mut inner = 0;

        while let Some(s) = seq.next_element::<String>()? {
            match s.as_str() {
                WhatAmI::STR_R => inner |= WhatAmI::U8_R,
                WhatAmI::STR_P => inner |= WhatAmI::U8_P,
                WhatAmI::STR_C => inner |= WhatAmI::U8_C,
                _ => {
                    return Err(serde::de::Error::invalid_value(
                        serde::de::Unexpected::Str(&s),
                        &formatcp!(
                            "one of ('{}', '{}', '{}')",
                            WhatAmI::STR_R,
                            WhatAmI::STR_P,
                            WhatAmI::STR_C
                        ),
                    ))
                }
            }
        }

        Ok(WhatAmIMatcher::try_from(inner)
            .expect("`WhatAmIMatcher` should be valid by construction"))
    }
}

impl<'de> serde::Deserialize<'de> for WhatAmIMatcher {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_seq(WhatAmIMatcherVisitor)
    }
}