synapse-primitives 0.0.2

Core types and ID hashing for Synapse RPC framework
Documentation
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Bitfield flag packing for efficient boolean storage
//!
//! This module provides utilities to pack multiple boolean flags into a single
//! integer, reducing memory usage and protocol overhead.
//!
//! # Examples
//!
//! ```
//! use synapse_primitives::flags::Flags64;
//!
//! let mut flags = Flags64::new();
//! flags.set(0, true);  // require_auth
//! flags.set(1, true);  // idempotent
//! flags.set(2, false); // allow_batch
//!
//! assert!(flags.get(0));
//! assert!(flags.get(1));
//! assert!(!flags.get(2));
//! ```

use std::fmt;

/// 64-bit flag container (can hold up to 64 boolean flags)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Flags64(u64);

/// 32-bit flag container (can hold up to 32 boolean flags)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Flags32(u32);

impl Flags64 {
    /// Maximum number of flags (0-63)
    pub const MAX_FLAGS: u8 = 64;

    /// Create empty flags (all false)
    pub const fn new() -> Self {
        Self(0)
    }

    /// Create from raw u64 value
    pub const fn from_raw(value: u64) -> Self {
        Self(value)
    }

    /// Get the raw u64 value
    pub const fn as_u64(&self) -> u64 {
        self.0
    }

    /// Set a flag at the given bit position
    ///
    /// # Panics
    ///
    /// Panics if `bit` >= 64
    pub fn set(&mut self, bit: u8, value: bool) {
        assert!(bit < 64, "Bit position must be < 64");
        if value {
            self.0 |= 1u64 << bit;
        } else {
            self.0 &= !(1u64 << bit);
        }
    }

    /// Get a flag at the given bit position
    ///
    /// # Panics
    ///
    /// Panics if `bit` >= 64
    pub const fn get(&self, bit: u8) -> bool {
        assert!(bit < 64, "Bit position must be < 64");
        (self.0 & (1u64 << bit)) != 0
    }

    /// Set multiple flags from an iterator of (bit, value) pairs
    pub fn set_multiple<I>(&mut self, flags: I)
    where
        I: IntoIterator<Item = (u8, bool)>,
    {
        for (bit, value) in flags {
            self.set(bit, value);
        }
    }

    /// Count the number of set flags (population count)
    pub const fn count_set(&self) -> u32 {
        self.0.count_ones()
    }

    /// Check if any flags are set
    pub const fn any(&self) -> bool {
        self.0 != 0
    }

    /// Check if all flags are unset
    pub const fn none(&self) -> bool {
        self.0 == 0
    }

    /// Check if all flags are set
    pub const fn all(&self) -> bool {
        self.0 == u64::MAX
    }

    /// Clear all flags
    pub fn clear(&mut self) {
        self.0 = 0;
    }

    /// Merge with another flag set (bitwise OR)
    pub fn merge(&mut self, other: Flags64) {
        self.0 |= other.0;
    }

    /// Intersect with another flag set (bitwise AND)
    pub fn intersect(&mut self, other: Flags64) {
        self.0 &= other.0;
    }

    /// Check if this flag set contains all flags from another set
    pub const fn contains(&self, other: Flags64) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl Flags32 {
    /// Maximum number of flags (0-31)
    pub const MAX_FLAGS: u8 = 32;

    /// Create empty flags (all false)
    pub const fn new() -> Self {
        Self(0)
    }

    /// Create from raw u32 value
    pub const fn from_raw(value: u32) -> Self {
        Self(value)
    }

    /// Get the raw u32 value
    pub const fn as_u32(&self) -> u32 {
        self.0
    }

    /// Set a flag at the given bit position
    ///
    /// # Panics
    ///
    /// Panics if `bit` >= 32
    pub fn set(&mut self, bit: u8, value: bool) {
        assert!(bit < 32, "Bit position must be < 32");
        if value {
            self.0 |= 1u32 << bit;
        } else {
            self.0 &= !(1u32 << bit);
        }
    }

    /// Get a flag at the given bit position
    ///
    /// # Panics
    ///
    /// Panics if `bit` >= 32
    pub const fn get(&self, bit: u8) -> bool {
        assert!(bit < 32, "Bit position must be < 32");
        (self.0 & (1u32 << bit)) != 0
    }

    /// Set multiple flags from an iterator
    pub fn set_multiple<I>(&mut self, flags: I)
    where
        I: IntoIterator<Item = (u8, bool)>,
    {
        for (bit, value) in flags {
            self.set(bit, value);
        }
    }

    /// Count the number of set flags
    pub const fn count_set(&self) -> u32 {
        self.0.count_ones()
    }

    /// Check if any flags are set
    pub const fn any(&self) -> bool {
        self.0 != 0
    }

    /// Check if all flags are unset
    pub const fn none(&self) -> bool {
        self.0 == 0
    }

    /// Clear all flags
    pub fn clear(&mut self) {
        self.0 = 0;
    }

    /// Merge with another flag set (bitwise OR)
    pub fn merge(&mut self, other: Flags32) {
        self.0 |= other.0;
    }

    /// Intersect with another flag set (bitwise AND)
    pub fn intersect(&mut self, other: Flags32) {
        self.0 &= other.0;
    }

    /// Check if this flag set contains all flags from another set
    pub const fn contains(&self, other: Flags32) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl From<Flags64> for u64 {
    fn from(f: Flags64) -> u64 {
        f.0
    }
}

impl From<u64> for Flags64 {
    fn from(value: u64) -> Flags64 {
        Flags64(value)
    }
}

impl From<Flags32> for u32 {
    fn from(f: Flags32) -> u32 {
        f.0
    }
}

impl From<u32> for Flags32 {
    fn from(value: u32) -> Flags32 {
        Flags32(value)
    }
}

impl fmt::Binary for Flags64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:064b}", self.0)
    }
}

impl fmt::Binary for Flags32 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:032b}", self.0)
    }
}

/// Macro to define a typed flag set with named flags
///
/// Note: Requires the `paste` crate for generating setter method names.
///
/// # Examples
///
/// ```ignore
/// use synapse_primitives::define_flags;
///
/// define_flags! {
///     RequestFlags: Flags64 {
///         REQUIRE_AUTH = 0,
///         IDEMPOTENT = 1,
///         ALLOW_BATCH = 2,
///         COMPRESS_RESPONSE = 3,
///     }
/// }
///
/// let mut flags = RequestFlags::new();
/// flags.set_require_auth(true);
/// flags.set_idempotent(true);
///
/// assert!(flags.require_auth());
/// assert!(flags.idempotent());
/// assert!(!flags.allow_batch());
/// ```
#[macro_export]
macro_rules! define_flags {
    (
        $name:ident: $base:ty {
            $($flag:ident = $bit:expr),* $(,)?
        }
    ) => {
        pub struct $name($base);

        impl $name {
            pub const fn new() -> Self {
                Self(<$base>::new())
            }

            pub const fn from_raw(value: impl Into<$base>) -> Self {
                Self(value.into())
            }

            $(
                pub const fn $flag(&self) -> bool {
                    self.0.get($bit)
                }

                paste::paste! {
                    pub fn [<set_ $flag>](&mut self, value: bool) {
                        self.0.set($bit, value);
                    }
                }
            )*

            pub const fn as_raw(&self) -> $base {
                self.0
            }
        }

        impl Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }
    };
}

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

    #[test]
    fn test_flags64_basic() {
        let mut flags = Flags64::new();
        assert!(flags.none());
        assert!(!flags.any());

        flags.set(0, true);
        assert!(flags.any());
        assert!(flags.get(0));
        assert!(!flags.get(1));

        flags.set(63, true);
        assert!(flags.get(63));
        assert_eq!(flags.count_set(), 2);
    }

    #[test]
    fn test_flags32_basic() {
        let mut flags = Flags32::new();
        assert!(flags.none());

        flags.set(0, true);
        flags.set(31, true);
        assert_eq!(flags.count_set(), 2);
    }

    #[test]
    fn test_set_multiple() {
        let mut flags = Flags64::new();
        flags.set_multiple(vec![(0, true), (5, true), (10, true)]);

        assert!(flags.get(0));
        assert!(flags.get(5));
        assert!(flags.get(10));
        assert!(!flags.get(1));
        assert_eq!(flags.count_set(), 3);
    }

    #[test]
    fn test_merge() {
        let mut flags1 = Flags64::new();
        flags1.set(0, true);
        flags1.set(1, true);

        let mut flags2 = Flags64::new();
        flags2.set(2, true);
        flags2.set(3, true);

        flags1.merge(flags2);
        assert!(flags1.get(0));
        assert!(flags1.get(1));
        assert!(flags1.get(2));
        assert!(flags1.get(3));
        assert_eq!(flags1.count_set(), 4);
    }

    #[test]
    fn test_intersect() {
        let mut flags1 = Flags64::new();
        flags1.set(0, true);
        flags1.set(1, true);
        flags1.set(2, true);

        let mut flags2 = Flags64::new();
        flags2.set(1, true);
        flags2.set(2, true);
        flags2.set(3, true);

        flags1.intersect(flags2);
        assert!(!flags1.get(0));
        assert!(flags1.get(1));
        assert!(flags1.get(2));
        assert!(!flags1.get(3));
    }

    #[test]
    fn test_contains() {
        let mut flags1 = Flags64::new();
        flags1.set(0, true);
        flags1.set(1, true);
        flags1.set(2, true);

        let mut flags2 = Flags64::new();
        flags2.set(0, true);
        flags2.set(1, true);

        assert!(flags1.contains(flags2));

        flags2.set(5, true);
        assert!(!flags1.contains(flags2));
    }

    #[test]
    fn test_clear() {
        let mut flags = Flags64::new();
        flags.set(0, true);
        flags.set(10, true);
        assert!(flags.any());

        flags.clear();
        assert!(flags.none());
    }

    #[test]
    fn test_from_raw() {
        let flags = Flags64::from_raw(0b1010);
        assert!(!flags.get(0));
        assert!(flags.get(1));
        assert!(!flags.get(2));
        assert!(flags.get(3));
    }
}