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
//
// Copyright (c) 2022 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 super::ZInt;
use zenoh_core::{bail, zresult::ZError};

#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WhatAmI {
    Router = 1,
    Peer = 1 << 1,
    Client = 1 << 2,
}

impl std::str::FromStr for WhatAmI {
    type Err = ZError;

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

impl WhatAmI {
    pub fn to_str(self) -> &'static str {
        match self {
            WhatAmI::Router => "router",
            WhatAmI::Peer => "peer",
            WhatAmI::Client => "client",
        }
    }

    pub fn try_from(value: ZInt) -> Option<Self> {
        const CLIENT: ZInt = WhatAmI::Client as ZInt;
        const ROUTER: ZInt = WhatAmI::Router as ZInt;
        const PEER: ZInt = WhatAmI::Peer as ZInt;
        match value {
            CLIENT => Some(WhatAmI::Client),
            ROUTER => Some(WhatAmI::Router),
            PEER => Some(WhatAmI::Peer),
            _ => None,
        }
    }
}

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

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 std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("either 'router', 'client' or 'peer'")
    }
    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, &["router", "client", "peer"]))
    }
    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 From<WhatAmI> for ZInt {
    fn from(w: WhatAmI) -> Self {
        w as ZInt
    }
}

use std::{num::NonZeroU8, ops::BitOr};
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WhatAmIMatcher(pub NonZeroU8);

impl WhatAmIMatcher {
    pub fn try_from<T: std::convert::TryInto<u8>>(i: T) -> Option<Self> {
        let i = i.try_into().ok()?;
        if 127 < i && i < 136 {
            Some(WhatAmIMatcher(unsafe { NonZeroU8::new_unchecked(i) }))
        } else {
            None
        }
    }

    pub fn is_empty(self) -> bool {
        self.0.get() == 128
    }

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

    pub fn to_str(self) -> &'static str {
        match self.0.get() {
            128 => "",
            129 => "router",
            130 => "peer",
            132 => "client",
            131 => "router|peer",
            134 => "client|peer",
            133 => "client|router",
            135 => "client|router|peer",
            _ => "invalid_matcher",
        }
    }
}

impl std::str::FromStr for WhatAmIMatcher {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut inner = 128;
        for s in s.split('|') {
            match s.trim() {
                "" => {}
                "router" => inner |= WhatAmI::Router as u8,
                "client" => inner |= WhatAmI::Client as u8,
                "peer" => inner |= WhatAmI::Peer as u8,
                _ => return Err(()),
            }
        }
        Self::try_from(inner).ok_or(())
    }
}

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 std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a | separated list of whatami variants ('peer', 'client' or 'router')")
    }
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        v.parse().map_err(|_| {
            serde::de::Error::invalid_value(
                serde::de::Unexpected::Str(v),
                &"a | separated list of whatami variants ('peer', 'client' or 'router')",
            )
        })
    }
    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 WhatAmIMatcher {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_str(WhatAmIMatcherVisitor)
    }
}

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

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

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) })
    }
}

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