Skip to content

Commit ec791b7

Browse files
refactor(downloads): substitute RefCells with RwLocks for thread safety
1 parent 649ec2c commit ec791b7

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

src/settings.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
use std::cell::RefCell;
21
use std::collections::BTreeMap;
32
use std::fmt;
43
use std::path::{Path, PathBuf};
54
use std::str::FromStr;
5+
use std::sync::RwLock;
66

77
use anyhow::{Context, Result};
88
use serde::{Deserialize, Serialize};
@@ -13,22 +13,22 @@ use crate::dist::{AutoInstallMode, Profile};
1313
use crate::errors::*;
1414
use crate::utils;
1515

16-
#[derive(Clone, Debug, Eq, PartialEq)]
16+
#[derive(Debug)]
1717
pub struct SettingsFile {
1818
path: PathBuf,
19-
cache: RefCell<Option<Settings>>,
19+
cache: RwLock<Option<Settings>>,
2020
}
2121

2222
impl SettingsFile {
2323
pub(crate) fn new(path: PathBuf) -> Self {
2424
Self {
2525
path,
26-
cache: RefCell::new(None),
26+
cache: RwLock::default(),
2727
}
2828
}
2929

3030
fn write_settings(&self) -> Result<()> {
31-
let settings = self.cache.borrow();
31+
let settings = self.cache.read().unwrap();
3232
utils::write_file(
3333
"settings",
3434
&self.path,
@@ -40,10 +40,10 @@ impl SettingsFile {
4040
fn read_settings(&self) -> Result<()> {
4141
let mut needs_save = false;
4242
{
43-
let b = self.cache.borrow();
43+
let b = self.cache.read().unwrap();
4444
if b.is_none() {
4545
drop(b);
46-
*self.cache.borrow_mut() = Some(if utils::is_file(&self.path) {
46+
*self.cache.write().unwrap() = Some(if utils::is_file(&self.path) {
4747
let content = utils::read_file("settings", &self.path)?;
4848
Settings::parse(&content).with_context(|| RustupError::ParsingFile {
4949
name: "settings",
@@ -65,14 +65,17 @@ impl SettingsFile {
6565
self.read_settings()?;
6666

6767
// Settings can no longer be None so it's OK to unwrap
68-
f(self.cache.borrow().as_ref().unwrap())
68+
f(self.cache.read().unwrap().as_ref().unwrap())
6969
}
7070

7171
pub(crate) fn with_mut<T, F: FnOnce(&mut Settings) -> Result<T>>(&self, f: F) -> Result<T> {
7272
self.read_settings()?;
7373

7474
// Settings can no longer be None so it's OK to unwrap
75-
let result = { f(self.cache.borrow_mut().as_mut().unwrap())? };
75+
let result = {
76+
let mut result = self.cache.write().unwrap();
77+
f(result.as_mut().unwrap())?
78+
};
7679
self.write_settings()?;
7780
Ok(result)
7881
}

0 commit comments

Comments
 (0)