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