Make DynNum thread-safe

This commit is contained in:
RunasSudo 2021-10-19 15:31:22 +11:00
parent 75ec78b1a6
commit f120cf2eee
No known key found for this signature in database
GPG Key ID: 7234E476BF21C61A
1 changed files with 11 additions and 9 deletions

View File

@ -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<NumKind> = 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);
});
}
}