1use std::collections::HashMap;
8
9use tokio::task::JoinHandle;
10
11use crate::transport::{TransportAddr, TransportError};
12
13use super::addr::BleAddr;
14
15pub struct BleConnection<S> {
17 pub stream: S,
19 pub recv_task: Option<JoinHandle<()>>,
21 pub send_mtu: u16,
23 pub recv_mtu: u16,
25 pub established_at: tokio::time::Instant,
27 pub is_static: bool,
29 pub addr: BleAddr,
31}
32
33impl<S> BleConnection<S> {
34 pub fn effective_mtu(&self) -> u16 {
36 self.send_mtu.min(self.recv_mtu)
37 }
38}
39
40impl<S> Drop for BleConnection<S> {
41 fn drop(&mut self) {
42 if let Some(task) = self.recv_task.take() {
43 task.abort();
44 }
45 }
46}
47
48pub struct ConnectionPool<S> {
50 connections: HashMap<TransportAddr, BleConnection<S>>,
51 max_connections: usize,
52}
53
54impl<S> ConnectionPool<S> {
55 pub fn new(max_connections: usize) -> Self {
57 Self {
58 connections: HashMap::new(),
59 max_connections,
60 }
61 }
62
63 pub fn len(&self) -> usize {
65 self.connections.len()
66 }
67
68 pub fn is_empty(&self) -> bool {
70 self.connections.is_empty()
71 }
72
73 pub fn is_full(&self) -> bool {
75 self.connections.len() >= self.max_connections
76 }
77
78 pub fn max_connections(&self) -> usize {
80 self.max_connections
81 }
82
83 pub fn get(&self, addr: &TransportAddr) -> Option<&BleConnection<S>> {
85 self.connections.get(addr)
86 }
87
88 pub fn get_mut(&mut self, addr: &TransportAddr) -> Option<&mut BleConnection<S>> {
90 self.connections.get_mut(addr)
91 }
92
93 pub fn contains(&self, addr: &TransportAddr) -> bool {
95 self.connections.contains_key(addr)
96 }
97
98 pub fn insert(
103 &mut self,
104 addr: TransportAddr,
105 conn: BleConnection<S>,
106 ) -> Result<Option<TransportAddr>, TransportError> {
107 use std::collections::hash_map::Entry;
108
109 if let Entry::Occupied(mut e) = self.connections.entry(addr.clone()) {
111 e.insert(conn);
112 return Ok(None);
113 }
114
115 if !self.is_full() {
117 self.connections.insert(addr, conn);
118 return Ok(None);
119 }
120
121 let evicted = self.find_eviction_candidate(conn.is_static)?;
123 self.connections.remove(&evicted);
124 self.connections.insert(addr, conn);
125 Ok(Some(evicted))
126 }
127
128 pub fn remove(&mut self, addr: &TransportAddr) -> Option<BleConnection<S>> {
130 self.connections.remove(addr)
131 }
132
133 pub fn addrs(&self) -> Vec<TransportAddr> {
135 self.connections.keys().cloned().collect()
136 }
137
138 fn find_eviction_candidate(
143 &self,
144 new_is_static: bool,
145 ) -> Result<TransportAddr, TransportError> {
146 if new_is_static {
147 self.connections
149 .iter()
150 .filter(|(_, c)| !c.is_static)
151 .min_by_key(|(_, c)| c.established_at)
152 .map(|(addr, _)| addr.clone())
153 .ok_or_else(|| {
154 TransportError::NotSupported("BLE pool full: all connections are static".into())
155 })
156 } else {
157 self.connections
159 .iter()
160 .filter(|(_, c)| !c.is_static)
161 .min_by_key(|(_, c)| c.established_at)
162 .map(|(addr, _)| addr.clone())
163 .ok_or_else(|| {
164 TransportError::NotSupported("BLE pool full: all connections are static".into())
165 })
166 }
167 }
168}
169
170#[cfg(test)]
175mod tests {
176 use super::*;
177
178 fn test_addr(n: u8) -> TransportAddr {
179 TransportAddr::from_string(&format!("hci0/AA:BB:CC:DD:EE:{n:02X}"))
180 }
181
182 fn test_ble_addr(n: u8) -> BleAddr {
183 BleAddr::from_mac("hci0", [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, n])
184 }
185
186 fn test_conn(n: u8, is_static: bool) -> BleConnection<()> {
187 BleConnection {
188 stream: (),
189 recv_task: None,
190 send_mtu: 2048,
191 recv_mtu: 2048,
192 established_at: tokio::time::Instant::now(),
193 is_static,
194 addr: test_ble_addr(n),
195 }
196 }
197
198 #[test]
199 fn test_pool_basic_insert() {
200 let mut pool: ConnectionPool<()> = ConnectionPool::new(7);
201 assert!(pool.is_empty());
202
203 pool.insert(test_addr(1), test_conn(1, false)).unwrap();
204 assert_eq!(pool.len(), 1);
205 assert!(!pool.is_empty());
206 assert!(pool.contains(&test_addr(1)));
207 }
208
209 #[test]
210 fn test_pool_remove() {
211 let mut pool: ConnectionPool<()> = ConnectionPool::new(7);
212 pool.insert(test_addr(1), test_conn(1, false)).unwrap();
213 assert!(pool.remove(&test_addr(1)).is_some());
214 assert!(pool.is_empty());
215 }
216
217 #[test]
218 fn test_pool_full_eviction() {
219 let mut pool: ConnectionPool<()> = ConnectionPool::new(3);
220 pool.insert(test_addr(1), test_conn(1, false)).unwrap();
221 pool.insert(test_addr(2), test_conn(2, false)).unwrap();
222 pool.insert(test_addr(3), test_conn(3, false)).unwrap();
223 assert!(pool.is_full());
224
225 let result = pool.insert(test_addr(4), test_conn(4, false));
227 assert!(result.is_ok());
228 assert!(result.unwrap().is_some()); assert_eq!(pool.len(), 3);
230 assert!(pool.contains(&test_addr(4)));
231 }
232
233 #[test]
234 fn test_pool_static_evicts_nonstatic() {
235 let mut pool: ConnectionPool<()> = ConnectionPool::new(2);
236 pool.insert(test_addr(1), test_conn(1, false)).unwrap();
237 pool.insert(test_addr(2), test_conn(2, false)).unwrap();
238
239 let result = pool.insert(test_addr(3), test_conn(3, true));
241 assert!(result.is_ok());
242 assert_eq!(pool.len(), 2);
243 assert!(pool.contains(&test_addr(3)));
244 }
245
246 #[test]
247 fn test_pool_all_static_rejects() {
248 let mut pool: ConnectionPool<()> = ConnectionPool::new(2);
249 pool.insert(test_addr(1), test_conn(1, true)).unwrap();
250 pool.insert(test_addr(2), test_conn(2, true)).unwrap();
251
252 let result = pool.insert(test_addr(3), test_conn(3, false));
254 assert!(result.is_err());
255 }
256
257 #[test]
258 fn test_pool_replace_existing() {
259 let mut pool: ConnectionPool<()> = ConnectionPool::new(2);
260 pool.insert(test_addr(1), test_conn(1, false)).unwrap();
261
262 let result = pool.insert(test_addr(1), test_conn(1, true));
264 assert!(result.is_ok());
265 assert_eq!(pool.len(), 1);
266 assert!(pool.get(&test_addr(1)).unwrap().is_static);
267 }
268
269 #[test]
270 fn test_pool_effective_mtu() {
271 let mut conn = test_conn(1, false);
272 conn.send_mtu = 1024;
273 conn.recv_mtu = 2048;
274 assert_eq!(conn.effective_mtu(), 1024);
275 }
276
277 #[test]
278 fn test_pool_addrs() {
279 let mut pool: ConnectionPool<()> = ConnectionPool::new(7);
280 pool.insert(test_addr(1), test_conn(1, false)).unwrap();
281 pool.insert(test_addr(2), test_conn(2, false)).unwrap();
282
283 let mut addrs = pool.addrs();
284 addrs.sort_by(|a, b| a.as_str().cmp(&b.as_str()));
285 assert_eq!(addrs.len(), 2);
286 }
287}