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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
use rand::prelude::IteratorRandom;
use serde::Deserialize;
use serde::de::Error;
use crate::hal::BUTTON_COUNTS;
use crate::lights::LightDir;
use crate::{Column, Lights, Row};
use super::button::Button;
use std::convert::TryInto;
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord)]
/// A selection of multiple [`Button`s][`Button`].
pub struct Buttons {
// bitset where lowest order bit represents the first button
bits: u16,
}
impl Buttons {
/// Returns a selection containing all indices marked true in `arr`.
///
/// # Panics
///
/// This function will panic if `arr.len() > Button::COUNT`
#[must_use]
pub fn from_slice(arr: &[bool]) -> Buttons {
assert!(arr.len() <= Button::COUNT);
Self::from_indices(
arr.iter()
.enumerate()
.filter(|&(_, p)| *p)
.map(|(idx, _)| idx),
)
}
#[must_use]
/// Returns a new [`Buttons`] at index `button_index`.
///
/// # Panics
///
/// This function will panic if `button_index >= Button::COUNT`.
pub const fn from_index(button_index: usize) -> Buttons {
Self::from_bitset(1 << button_index)
}
/// Returns a new [`Buttons`] constructed from button indices contained in `indexes`.
///
/// # Panics
///
/// This function will panic if `indexes` contains an `index >= Button::COUNT`.
pub fn from_indices<I>(indexes: I) -> Buttons
where
I: IntoIterator<Item = usize>,
{
let mut bits: u16 = 0;
for index in indexes {
assert!(index < Button::COUNT);
bits |= 1 << index;
}
Buttons { bits }
}
/// Returns a new [`Buttons`] with `bits`. Each bit in `bits` represents whether an individual
/// button has been selected. The 0th bit selects [`Button::B1`].
///
/// # Panics
///
/// This function will panic if `bits >> Button::COUNT != 0`.
#[must_use]
pub const fn from_bitset(bits: u16) -> Buttons {
assert!(bits >> Button::COUNT == 0);
Buttons { bits }
}
/// Returns a [`Buttons`] with every button selected.
#[must_use]
pub const fn all() -> Buttons {
Buttons::from_bitset((1 << Button::COUNT) - 1)
}
/// Returns a [`Buttons`] with no button selected.
#[must_use]
pub const fn none() -> Buttons {
Self::from_bitset(0)
}
/// Returns a [`Buttons`] with only the buttons in `row` selected.
#[must_use]
pub const fn row(row: Row) -> Buttons {
match row {
Row::Top => Self::from_bitset(0b0001_1111),
Row::Bottom => Self::from_bitset(0b0011_1110_0000),
}
}
/// Return a selection of the two buttons in the column of zero-based `column_index`.
///
/// # Panics
///
/// If `column_index` >= `NUM_COLUMNS`.
///
/// # Example
///
/// ```
/// use boppo_core::{Buttons, Column};
/// let mut indices = Buttons::column(Column::C0).indices();
/// assert_eq!(indices.next(), Some(0));
/// assert_eq!(indices.next(), Some(5));
/// ```
#[must_use]
pub fn column(col: Column) -> Buttons {
Self::from_indices([col.index(), 5 + col.index()])
}
/// Return all buttons that are currently held down.
///
/// See also [`ButtonEvents`][crate::ButtonEvents] which is an alternative way to
/// receive button events.
#[expect(
clippy::missing_panics_doc,
reason = "This only panics if the library hasn't been initialised properly."
)]
pub fn currently_pressed() -> Buttons {
BUTTON_COUNTS.get().unwrap().borrow().currently_pressed()
}
/// Returns the number of buttons in this selection.
#[must_use]
pub fn len(&self) -> u32 {
self.bits.count_ones()
}
/// Returns `true` if no buttons are selected.
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns `true` if this selection contains `button`.
#[must_use]
pub fn contains(&self, button: Button) -> bool {
self.is_superset(button.into())
}
/// Returns `true` if `other` selects only buttons that `self` selects.
///
/// See also [`Buttons::is_subset`]
#[must_use]
pub fn is_superset(&self, other: Self) -> bool {
(self.bits | other.bits) == self.bits
}
/// Returns `true` if `self` selects only buttons that `other` selects.
///
/// See also [`Buttons::is_superset`]
#[must_use]
pub fn is_subset(&self, other: Self) -> bool {
other.is_superset(*self)
}
/// Returns a double-ended iterator over the indices of every [`Button`] in this selection.
#[must_use]
pub fn indices(&self) -> impl DoubleEndedIterator<Item = usize> + use<> {
Indices { bits: self.bits }
}
/// Returns a double-ended iterator over every [`Button`] in this selection.
#[must_use]
pub fn buttons(&self) -> impl DoubleEndedIterator<Item = Button> + use<> {
self.indices().map(|index| Button::from_index(index))
}
/// Returns the inversion of the current selection.
#[must_use]
pub fn invert(&self) -> Buttons {
Buttons {
bits: (!self.bits) & Buttons::all().bits,
}
}
/// Randomly choose `n` of the buttons that are active in `self`.
/// If `n == 1`, it's better to use [`choose_one_randomly`][Buttons::choose_one_randomly].
#[must_use]
pub fn choose_n_randomly(&self, n: usize) -> Buttons {
let mut chosen = [11; Button::COUNT];
let num_chosen = self
.indices()
.choose_multiple_fill(&mut rand::rng(), &mut chosen[0..n]);
Buttons::from_indices(chosen[0..num_chosen].iter().copied())
}
/// Randomly choose one [`Button`] from those active in `self`.
#[must_use]
pub fn choose_one_randomly(&self) -> Button {
// The compiler is smart enough to optimise even this nasty chain, making this wayy better than
// `choose_n_randomly` for this common case.
Button::from_index(self.choose_n_randomly(1).as_bitset().trailing_zeros() as usize)
}
/// Return the Buttons as if the device was rotate 180 degrees.
/// Button 1 becomes 10, 2 becomes 9... 5 becomes 6 and vise versa.
#[must_use]
pub fn rotate_180(&self) -> Buttons {
Buttons::from_bitset(self.bits.reverse_bits() >> 6)
}
/// A compact representation. The least significant bit represents if button 1 is pressed...
#[must_use]
pub const fn as_bitset(&self) -> u16 {
self.bits
}
/// Set [`self's`][`crate::Button`] lights to [`color`][`crate::color`].
pub fn set_color(self, color: crate::color::RGB) {
crate::LightsSetter::get().set_color(self.into(), color);
}
/// Set [`self's`][`crate::Button`] lights to [`color::OFF`][`crate::color::OFF`].
/// Shorthand for [`self.set_color(color::OFF)`][crate::Button::set_color]
pub fn set_off(self) {
self.set_color(crate::color::OFF);
}
/// Set the lowest button in this selection to `colors[0]` and second lowest
/// to `colors[1]` and so on.
/// If there are more colors than buttons the extra colors are ignored. If
/// there are less colors than buttons, the color of the extra buttons will
/// remain unchanged.
pub fn set_colors(self, colors: impl IntoIterator<Item = crate::color::RGB>) {
for (button, color) in self.buttons().zip(colors) {
button.set_color(color);
}
}
/// Returns a [`Lights`] containing every light for every [`Button`] in this selection.
#[must_use]
pub const fn lights(self) -> Lights {
let input = self.as_bitset() as u64;
let mut result: u64 = 0;
let mut i = 0;
while i < 10 {
// Check if bit i is set in input
if (input & (1 << i)) != 0 {
// Set 4 bits in the output starting at position 4*i
result |= 0b1111u64 << (4 * i);
}
i += 1;
}
Lights::from_bitset(result)
}
/// Returns a [`Lights`] containing only the light at `dir` for every [`Button`] in this selection.
#[must_use]
pub const fn lights_on(self, dir: LightDir) -> Lights {
let lights: Lights = self.lights();
lights.only(dir)
}
/// Returns an iterator over every [`Button`] in this selection.
#[must_use]
pub fn iter(&self) -> Box<dyn Iterator<Item = Button> + Send + Sync> {
self.into_iter()
}
}
impl IntoIterator for &Buttons {
type IntoIter = Box<dyn Iterator<Item = Button> + Send + Sync>;
type Item = Button;
fn into_iter(self) -> Self::IntoIter {
Buttons::into_iter(*self)
}
}
impl std::ops::BitAnd for Buttons {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output {
Buttons {
bits: self.bits & rhs.bits,
}
}
}
impl std::ops::BitAndAssign for Buttons {
fn bitand_assign(&mut self, rhs: Self) {
*self = *self & rhs;
}
}
impl std::ops::BitOr for Buttons {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output {
Buttons {
bits: self.bits | rhs.bits,
}
}
}
impl std::ops::BitOrAssign for Buttons {
fn bitor_assign(&mut self, rhs: Self) {
self.bits |= rhs.bits;
}
}
impl std::ops::BitXor for Buttons {
type Output = Self;
fn bitxor(self, rhs: Self) -> Self::Output {
Buttons {
bits: self.bits ^ rhs.bits,
}
}
}
impl std::ops::BitXorAssign for Buttons {
fn bitxor_assign(&mut self, rhs: Self) {
self.bits ^= rhs.bits;
}
}
impl std::ops::Not for Buttons {
type Output = Self;
fn not(self) -> Self::Output {
self.invert()
}
}
impl std::iter::IntoIterator for Buttons {
type Item = Button;
// TODO: remove Box
type IntoIter = Box<dyn Iterator<Item = Button> + Send + Sync>;
/// Iterates in order of index.
fn into_iter(self) -> Self::IntoIter {
Box::new(self.indices().map(Button::from_index))
}
}
impl From<Button> for Buttons {
fn from(button: Button) -> Self {
Buttons::from_index(button.index())
}
}
impl From<&[Button]> for Buttons {
fn from(buttons: &[Button]) -> Self {
buttons.iter().copied().collect()
}
}
impl FromIterator<Button> for Buttons {
fn from_iter<T: IntoIterator<Item = Button>>(iter: T) -> Self {
let mut res = Buttons::none();
for button in iter {
res |= button.into();
}
res
}
}
struct Indices {
bits: u16,
}
impl Iterator for Indices {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.bits == 0 {
None
} else {
let next = self.bits.trailing_zeros().try_into().unwrap();
self.bits = self.bits & (self.bits - 1);
Some(next)
}
}
}
impl DoubleEndedIterator for Indices {
fn next_back(&mut self) -> Option<Self::Item> {
if self.bits == 0 {
None
} else {
let next = self.bits.ilog2();
self.bits ^= 1u16 << next;
Some(next as usize)
}
}
}
impl<'de> Deserialize<'de> for Buttons {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value = serde_json::Value::deserialize(deserializer)?;
Ok(match value {
serde_json::Value::Number(number) => number
.as_u64()
.ok_or(D::Error::custom("number too large"))
.and_then(|idx| {
usize::try_from(idx).map_err(|_| D::Error::custom("number too large"))
})
.and_then(|idx| {
if idx < Button::COUNT {
Ok(idx)
} else {
Err(D::Error::custom("number too large"))
}
})
.map(Buttons::from_index)?,
serde_json::Value::String(s) => {
if s == "All" {
Buttons::all()
} else {
return Err(D::Error::custom("Unexpected JSON string value for Buttons"));
}
}
serde_json::Value::Array(values) => {
let numbers: Result<Vec<usize>, _> = values
.iter()
.map(|v| {
v.as_number()
.and_then(serde_json::Number::as_u64)
.ok_or(D::Error::custom("Buttons array has non-number"))
.and_then(|n| {
usize::try_from(n).map_err(|_| D::Error::custom("number too large"))
})
.and_then(|idx| {
if idx < Button::COUNT {
Ok(idx)
} else {
Err(D::Error::custom("number too large"))
}
})
})
.collect();
Buttons::from_indices(numbers?)
}
_ => return Err(D::Error::custom("Unexpected JSON type for Buttons")),
})
}
}
#[cfg(test)]
#[path = "./tests/buttons_test.rs"]
mod test;