Skip to content

Commit

Permalink
use once_cell to avoid unsafe blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Rennzie committed Nov 17, 2023
1 parent 17d04f2 commit bee43f1
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 5 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ env_logger = { version = "0.10.0", optional = true }
log = "0.4"
thiserror = "1.0"
float_eq = "1"
once_cell = "1.18.0"

[dev-dependencies]
# Needed for building doc-tests
Expand Down
10 changes: 6 additions & 4 deletions src/context/plain.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#[cfg(feature = "with_plain")]
use crate::authoring::*;
use crate::grid::ntv2::Ntv2Grid;
use once_cell::sync::Lazy;
use std::{
path::PathBuf,
sync::{Arc, Mutex},
Expand All @@ -24,8 +25,9 @@ pub struct Plain {
// Helper for Plain: Provide grid access for all `Op`s
// in all instantiations of `Plain` by handing out
// reference counted clones to a single heap allocation
static mut GRIDS: Mutex<GridCollection> =
Mutex::new(GridCollection(BTreeMap::<String, Arc<dyn Grid>>::new()));

static GRIDS: Lazy<Mutex<GridCollection>> =
Lazy::new(|| Mutex::new(GridCollection(BTreeMap::<String, Arc<dyn Grid>>::new())));

struct GridCollection(BTreeMap<String, Arc<dyn Grid>>);
impl GridCollection {
Expand Down Expand Up @@ -77,7 +79,7 @@ impl Default for Plain {

// To avoid having GRIDS growing through the roof, we clear it
// out every time a new Plain context is instantiated
unsafe { GRIDS.lock().unwrap().0.clear() }
GRIDS.lock().unwrap().0.clear();

let localpath: PathBuf = [".", "geodesy"].iter().collect();
paths.push(localpath);
Expand Down Expand Up @@ -254,7 +256,7 @@ impl Context for Plain {
// The GridCollection does all the hard work here, but accessing GRIDS,
// which is a mutable static is (mis-)diagnosed as unsafe by the compiler,
// even though the mutable static is behind a Mutex guard
unsafe { GRIDS.lock().unwrap().get_grid(name, &self.paths) }
GRIDS.lock().unwrap().get_grid(name, &self.paths)
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/grid/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pub mod ntv2;
use crate::prelude::*;
use std::{fmt::Debug, io::BufRead};

pub trait Grid: Debug {
pub trait Grid: Debug + Sync + Send {
fn bands(&self) -> usize;
/// Returns true if `coord` is contained by `self` or lies within a margin of
/// `margin` grid cell units. Typically `margin` should be on the order of 1
Expand Down

0 comments on commit bee43f1

Please sign in to comment.