refactor(favorite): stop using async fs operations, simplify and optimize

This commit is contained in:
Samuel Åkesson
2026-04-17 12:54:18 +02:00
parent 0e3118feb0
commit 9d18fe7d7e
2 changed files with 27 additions and 25 deletions

View File

@@ -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<Controller> =

View File

@@ -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<Vec<Address>> {
pub fn read_favorite_devices_from_disk() -> AppResult<Vec<Address>> {
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::<Vec<_>>()
.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")?;