switchbot_api/
device_list.rs

1use super::Device;
2use std::ops::{Deref, DerefMut};
3
4/// A list of [`Device`]s.
5///
6/// This is almost identical to `Vec<Device>`, with a few additional features
7/// such as [`DeviceList::index_by_device_id()`].
8#[derive(Debug, Default, serde::Deserialize)]
9#[serde(transparent)] // This allows DeviceList to be deserialized as if it were just Vec<Device>
10pub struct DeviceList {
11    devices: Vec<Device>,
12}
13
14impl DeviceList {
15    pub fn new() -> Self {
16        Self {
17            devices: Vec::new(),
18        }
19    }
20
21    #[allow(dead_code)]
22    pub fn with_capacity(capacity: usize) -> Self {
23        Self {
24            devices: Vec::with_capacity(capacity),
25        }
26    }
27
28    pub fn push(&mut self, device: Device) {
29        self.devices.push(device);
30    }
31
32    pub fn extend<T: IntoIterator<Item = Device>>(&mut self, iter: T) {
33        self.devices.extend(iter);
34    }
35
36    pub fn index_by_device_id(&self, device_id: &str) -> Option<usize> {
37        self.devices.iter().position(|d| d.device_id() == device_id)
38    }
39
40    // Delegate common Vec methods
41    pub fn iter(&self) -> std::slice::Iter<'_, Device> {
42        self.devices.iter()
43    }
44
45    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, Device> {
46        self.devices.iter_mut()
47    }
48
49    pub fn get(&self, index: usize) -> Option<&Device> {
50        self.devices.get(index)
51    }
52
53    pub fn get_mut(&mut self, index: usize) -> Option<&mut Device> {
54        self.devices.get_mut(index)
55    }
56
57    pub fn is_empty(&self) -> bool {
58        self.devices.is_empty()
59    }
60
61    pub fn len(&self) -> usize {
62        self.devices.len()
63    }
64}
65
66impl Deref for DeviceList {
67    type Target = Vec<Device>;
68
69    fn deref(&self) -> &Self::Target {
70        &self.devices
71    }
72}
73
74impl DerefMut for DeviceList {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        &mut self.devices
77    }
78}
79
80impl IntoIterator for DeviceList {
81    type Item = Device;
82    type IntoIter = std::vec::IntoIter<Self::Item>;
83
84    fn into_iter(self) -> Self::IntoIter {
85        self.devices.into_iter()
86    }
87}