From f120cf2eeeba83092e14c2b16f5b36d2776b85ee Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Tue, 19 Oct 2021 15:31:22 +1100 Subject: [PATCH] Make DynNum thread-safe --- src/numbers/dynnum.rs | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/numbers/dynnum.rs b/src/numbers/dynnum.rs index eebfdb9..7e4c78b 100644 --- a/src/numbers/dynnum.rs +++ b/src/numbers/dynnum.rs @@ -20,6 +20,7 @@ use super::{Assign, Fixed, GuardedFixed, NativeFloat64, Number, Rational}; use num_traits::{Num, One, Zero}; //use wasm_bindgen::prelude::wasm_bindgen; +use std::cell::Cell; use std::cmp::{Ord, Ordering}; use std::fmt; use std::mem::ManuallyDrop; @@ -27,6 +28,7 @@ use std::ops::{self, Deref, DerefMut}; /// Represents the underlying implementation for [DynNum]s //#[wasm_bindgen] +#[derive(Copy, Clone)] pub enum NumKind { /// See [crate::numbers::fixed] Fixed, @@ -38,15 +40,15 @@ pub enum NumKind { Rational, } -/// Determines which underlying implementation to use -static mut KIND: NumKind = NumKind::Fixed; +thread_local! { + /// Determines which underlying implementation to use + static KIND: Cell = Cell::new(NumKind::Fixed); +} /// Returns which underlying implementation is in use #[inline] -fn get_kind() -> &'static NumKind { - unsafe { - return &KIND; - } +fn get_kind() -> NumKind { + return KIND.with(|kind_cell| kind_cell.get()); } /// A wrapper for different numeric types using dynamic dispatch @@ -60,9 +62,9 @@ pub union DynNum { impl DynNum { /// Set which underlying implementation to use pub fn set_kind(kind: NumKind) { - unsafe { - KIND = kind; - } + KIND.with(|kind_cell| { + kind_cell.set(kind); + }); } }