Skip to content

Instantly share code, notes, and snippets.

@hugmanrique
Created June 4, 2022 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hugmanrique/f84631db88e17f071c7ab67e1481fb57 to your computer and use it in GitHub Desktop.
Save hugmanrique/f84631db88e17f071c7ab67e1481fb57 to your computer and use it in GitHub Desktop.
use anyhow::Result;
use bluer::Address;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{ErrorKind, Read, Write};
use std::ops::Deref;
use std::path::PathBuf;
/// A set of paired device addresses, backed by a file.
pub struct PairedDevices {
file: File,
addresses: HashSet<Address>,
}
impl PairedDevices {
/// Reads the list of paired addresses from the given path.
///
/// Even if incorrect, assumes that the file will not change
/// due to external events until dropped.
pub fn read(path: &PathBuf) -> Result<Self> {
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(path)?;
let mut buffer = [0; 6];
let mut addresses = HashSet::new();
loop {
match file.read_exact(&mut buffer) {
Ok(_) => {
addresses.insert(Address::new(buffer.clone()));
}
Err(e) if e.kind() == ErrorKind::UnexpectedEof => break,
Err(e) => return Err(e.into()),
}
}
Ok(Self { file, addresses })
}
pub fn add(&mut self, address: Address) -> Result<()> {
if self.addresses.insert(address) {
self.file.write_all(&address.0)?;
}
Ok(())
}
}
impl Deref for PairedDevices {
type Target = HashSet<Address>;
fn deref(&self) -> &Self::Target {
&self.addresses
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment