Make DynNum thread-safe

This commit is contained in:
RunasSudo 2021-10-19 15:31:22 +11:00
parent 75ec78b1a6
commit f120cf2eee
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A

View File

@ -20,6 +20,7 @@ use super::{Assign, Fixed, GuardedFixed, NativeFloat64, Number, Rational};
use num_traits::{Num, One, Zero}; use num_traits::{Num, One, Zero};
//use wasm_bindgen::prelude::wasm_bindgen; //use wasm_bindgen::prelude::wasm_bindgen;
use std::cell::Cell;
use std::cmp::{Ord, Ordering}; use std::cmp::{Ord, Ordering};
use std::fmt; use std::fmt;
use std::mem::ManuallyDrop; use std::mem::ManuallyDrop;
@ -27,6 +28,7 @@ use std::ops::{self, Deref, DerefMut};
/// Represents the underlying implementation for [DynNum]s /// Represents the underlying implementation for [DynNum]s
//#[wasm_bindgen] //#[wasm_bindgen]
#[derive(Copy, Clone)]
pub enum NumKind { pub enum NumKind {
/// See [crate::numbers::fixed] /// See [crate::numbers::fixed]
Fixed, Fixed,
@ -38,15 +40,15 @@ pub enum NumKind {
Rational, Rational,
} }
thread_local! {
/// Determines which underlying implementation to use /// Determines which underlying implementation to use
static mut KIND: NumKind = NumKind::Fixed; static KIND: Cell<NumKind> = Cell::new(NumKind::Fixed);
}
/// Returns which underlying implementation is in use /// Returns which underlying implementation is in use
#[inline] #[inline]
fn get_kind() -> &'static NumKind { fn get_kind() -> NumKind {
unsafe { return KIND.with(|kind_cell| kind_cell.get());
return &KIND;
}
} }
/// A wrapper for different numeric types using dynamic dispatch /// A wrapper for different numeric types using dynamic dispatch
@ -60,9 +62,9 @@ pub union DynNum {
impl DynNum { impl DynNum {
/// Set which underlying implementation to use /// Set which underlying implementation to use
pub fn set_kind(kind: NumKind) { pub fn set_kind(kind: NumKind) {
unsafe { KIND.with(|kind_cell| {
KIND = kind; kind_cell.set(kind);
} });
} }
} }