bitstring/fixed_bit_string/
traits.rs

1use crate::fixed_bit_string::Iter;
2
3/// A bit string with fixed length.
4///
5/// All bits must me mutable, and there must be no dependencies between
6/// bits (i.e. setting one bit must not change any other bit).
7pub trait FixedBitString {
8	/// Length of the bit string in bits.
9	const LEN: usize;
10
11	/// Treat bit string as integer, where bit 0 is the most significant
12	/// bit.
13	///
14	/// Increment by one, i.e. start by incrementing the bit with the
15	/// highest index.
16	///
17	/// Don't touch first `prefix` bits; return true on overflow.
18	///
19	/// # Panics
20	///
21	/// Should panic if `prefix > Self::LEN`.
22	fn inc(&mut self, prefix: usize) -> bool;
23
24	/// Iterate through all bit strings until `inc` overflows.
25	///
26	/// All generated values will share the first `prefix` bits.  If you
27	/// want to iterate over all values make sure to call
28	/// `self.set_false_from(prefix)` before.
29	///
30	/// # Panics
31	///
32	/// Should panic if `prefix > Self::LEN`.
33	fn iter(&self, prefix: usize) -> Iter<Self>
34	where
35		Self: Sized + Clone,
36	{
37		Iter::new(self.clone(), prefix)
38	}
39
40	/// Get the `ndx`th bit.
41	///
42	/// # Panics
43	///
44	/// Should panic if `ndx >= Self::LEN`.
45	fn get(&self, ndx: usize) -> bool;
46
47	/// Set the `ndx`th bit to `bit`.
48	///
49	/// # Panics
50	///
51	/// Should panic if `ndx >= Self::LEN`.
52	fn set(&mut self, ndx: usize, bit: bool);
53
54	/// Flips the `ndx`th bit.
55	///
56	/// # Panics
57	///
58	/// Should panic if `ndx >= Self::LEN`.
59	fn flip(&mut self, ndx: usize) {
60		let old_value = self.get(ndx);
61		self.set(ndx, !old_value);
62	}
63
64	/// Length of the longest shared prefix of two bit strings.
65	fn shared_prefix_len(&self, other: &Self) -> usize {
66		let max_len = Self::LEN;
67		for i in 0..max_len {
68			if self.get(i) != other.get(i) {
69				return i;
70			}
71		}
72		max_len
73	}
74
75	/// Set all bits in [ndx..] to `false`.
76	///
77	/// Doesn't do anything if `ndx >= Self::LEN`.
78	fn set_false_from(&mut self, ndx: usize);
79
80	/// Whether all bits in [ndx..] are `false`.
81	///
82	/// Returns `true` if `ndx >= Self::LEN`.
83	fn is_false_from(&self, ndx: usize) -> bool;
84
85	/// Set all bits in [ndx..] to `true`.
86	///
87	/// Doesn't do anything if `ndx >= Self::LEN`.
88	fn set_true_from(&mut self, ndx: usize);
89
90	/// Whether all bits in [ndx..] are `true`.
91	///
92	/// Returns `true` if `ndx >= Self::LEN`.
93	fn is_true_from(&self, ndx: usize) -> bool;
94
95	/// New bit string with all bits set to `false`.
96	fn new_all_false() -> Self;
97
98	/// New bit string with all bits set to `true`.
99	fn new_all_true() -> Self;
100
101	/// check whether another bit string `other` shares the first
102	/// `prefix` bits with `self`
103	///
104	/// # Panics
105	///
106	/// Should panic if `prefix > Self::LEN`.
107	fn contains(&self, prefix: usize, other: &Self) -> bool;
108}