diff --git a/src/app.rs b/src/app.rs index fa00e2a..fa0ae58 100644 --- a/src/app.rs +++ b/src/app.rs @@ -101,7 +101,7 @@ impl App { ..Default::default() }; - let favorite_devices = read_favorite_devices_from_disk().await.unwrap_or_default(); + let favorite_devices = read_favorite_devices_from_disk().unwrap_or_default(); let handle = session.register_agent(agent).await?; let controllers: Vec = diff --git a/src/favorite.rs b/src/favorite.rs index bb26d7b..ceb7018 100644 --- a/src/favorite.rs +++ b/src/favorite.rs @@ -1,29 +1,29 @@ use crate::app::AppResult; use anyhow::Context; use bluer::Address; -use std::str::FromStr; -use tokio::io::{AsyncBufReadExt, BufReader}; +use std::{ + fs::File, + io::{BufRead, BufReader}, + str::FromStr, +}; -pub async fn read_favorite_devices_from_disk() -> AppResult> { +pub fn read_favorite_devices_from_disk() -> AppResult> { let data_dir = dirs::data_dir() .context("unable to find data_dir")? .join("bluetui"); - let file = tokio::fs::File::open(data_dir.join("favorites.txt")) - .await - .context("unable to open favorites file")?; + let file = + File::open(data_dir.join("favorites.txt")).context("unable to open favorites file")?; - let mut lines = BufReader::new(file).lines(); + let lines = BufReader::new(file).lines(); - let mut favorite_devices = Vec::new(); - - while let Some(line) = lines.next_line().await? { - if let Ok(addr) = Address::from_str(&line) { - favorite_devices.push(addr); - } - } - - Ok(favorite_devices) + lines + .map(|line| { + let line = line?; + let addr = Address::from_str(&line)?; + Ok(addr) + }) + .collect() } pub fn save_favorite_devices_to_disk(favorite_devices: &[Address]) -> AppResult<()> { @@ -31,17 +31,19 @@ pub fn save_favorite_devices_to_disk(favorite_devices: &[Address]) -> AppResult< .context("unable to find data_dir")? .join("bluetui"); + if !data_dir.exists() { + std::fs::create_dir_all(&data_dir) + .context("unable to create parent dir(s) to favorites file")?; + } + let file_path = data_dir.join("favorites.txt"); - let contents = favorite_devices - .iter() - .map(Address::to_string) - .collect::>() - .join("\n"); + let mut contents = + String::with_capacity(favorite_devices.len() * (Address::any().to_string() + "\n").len()); - if !data_dir.exists() { - std::fs::create_dir_all(data_dir) - .context("unable to create parent dir(s) to favorites file")?; + for device in favorite_devices { + contents.push_str(&device.to_string()); + contents.push('\n'); } std::fs::write(file_path, contents).context("error writing favorites file")?;