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
// Copyright (c) 2022-2023 Yuki Kishimoto
// Copyright (c) 2023-2024 Rust Nostr Developers
// Distributed under the MIT software license

//! Relay Service Flags

use std::ops::{BitOr, BitOrAssign, BitXor, BitXorAssign};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

/// Relay Service Flags
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RelayServiceFlags(u64);

impl Default for RelayServiceFlags {
    /// Default flags: `READ`, `WRITE` and `PING`
    fn default() -> Self {
        Self::READ | Self::WRITE | Self::PING
    }
}

impl RelayServiceFlags {
    /// NONE means no services supported.
    pub const NONE: Self = Self(0);

    /// READ means that client will perform read operations with relay.
    pub const READ: Self = Self(1 << 0);

    /// WRITE means that client will perform write operations with relay.
    pub const WRITE: Self = Self(1 << 1);

    /// PING means that
    pub const PING: Self = Self(1 << 2);

    /// Add [RelayServiceFlags] together.
    pub fn add(&mut self, other: Self) -> Self {
        self.0 |= other.0;
        *self
    }

    /// Remove [RelayServiceFlags] from this.
    pub fn remove(&mut self, other: Self) -> Self {
        self.0 ^= other.0;
        *self
    }

    fn has(self, flags: Self) -> bool {
        (self.0 | flags.0) == self.0
    }

    fn to_u64(self) -> u64 {
        self.0
    }
}

impl BitOr for RelayServiceFlags {
    type Output = Self;

    fn bitor(mut self, rhs: Self) -> Self {
        self.add(rhs)
    }
}

impl BitOrAssign for RelayServiceFlags {
    fn bitor_assign(&mut self, rhs: Self) {
        self.add(rhs);
    }
}

impl BitXor for RelayServiceFlags {
    type Output = Self;

    fn bitxor(mut self, rhs: Self) -> Self {
        self.remove(rhs)
    }
}

impl BitXorAssign for RelayServiceFlags {
    fn bitxor_assign(&mut self, rhs: Self) {
        self.remove(rhs);
    }
}

/// Realy Service Flags which can be safely shared between threads.
#[derive(Debug, Clone)]
pub struct AtomicRelayServiceFlags {
    flags: Arc<AtomicU64>,
}

impl Default for AtomicRelayServiceFlags {
    fn default() -> Self {
        Self::new(RelayServiceFlags::default())
    }
}

impl AtomicRelayServiceFlags {
    /// Compose new from [RelayServiceFlags]
    pub fn new(flags: RelayServiceFlags) -> Self {
        Self {
            flags: Arc::new(AtomicU64::new(flags.to_u64())),
        }
    }

    /// Add [RelayServiceFlags] together.
    pub fn add(&self, other: RelayServiceFlags) {
        let _ = self
            .flags
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |f| {
                let mut f: RelayServiceFlags = RelayServiceFlags(f);
                let new = f.add(other);
                Some(new.to_u64())
            });
    }

    /// Remove [RelayServiceFlags] from this.
    pub fn remove(&self, other: RelayServiceFlags) {
        let _ = self
            .flags
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |f| {
                let mut f: RelayServiceFlags = RelayServiceFlags(f);
                let new = f.remove(other);
                Some(new.to_u64())
            });
    }

    /// Check whether [RelayServiceFlags] are included in this one.
    pub fn has(&self, flags: RelayServiceFlags) -> bool {
        let _f: u64 = self.flags.load(Ordering::SeqCst);
        let f: RelayServiceFlags = RelayServiceFlags(_f);
        f.has(flags)
    }

    /// Check if `READ` service is enabled
    pub fn has_read(&self) -> bool {
        self.has(RelayServiceFlags::READ)
    }

    /// Check if `WRITE` service is enabled
    pub fn has_write(&self) -> bool {
        self.has(RelayServiceFlags::WRITE)
    }

    /// Check if `PING` service is enabled
    pub fn has_ping(&self) -> bool {
        self.has(RelayServiceFlags::PING)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_service_flags() {
        let all = [
            RelayServiceFlags::READ,
            RelayServiceFlags::WRITE,
            RelayServiceFlags::PING,
        ];

        let flags = RelayServiceFlags::NONE;
        for f in all.into_iter() {
            assert!(!flags.has(f));
        }

        let mut flags = RelayServiceFlags::READ | RelayServiceFlags::WRITE;
        assert!(flags.has(RelayServiceFlags::READ));
        assert!(flags.has(RelayServiceFlags::WRITE));
        assert!(!flags.has(RelayServiceFlags::PING));

        // Try to add flag
        flags.add(RelayServiceFlags::PING);
        assert!(flags.has(RelayServiceFlags::PING));

        // Try to remove flag
        flags.remove(RelayServiceFlags::WRITE);
        assert!(flags.has(RelayServiceFlags::READ));
        assert!(flags.has(RelayServiceFlags::PING));

        // Try to re-add already existing flag
        flags.add(RelayServiceFlags::PING);
        assert!(flags.has(RelayServiceFlags::READ));
        assert!(flags.has(RelayServiceFlags::PING));
    }
}