mpdec 4.0.1

wrapper for libmpdec math library
Documentation
use std::{
    cell::{RefCell, RefMut},
    ops::{Deref, DerefMut},
};

use mpdec_sys::{mpd_context_t, mpd_defaultcontext};

pub type Context = mpd_context_t;

fn default_context() -> Context {
    let mut ctx: Context = unsafe { std::mem::zeroed() };
    unsafe { mpd_defaultcontext(&mut ctx) };
    ctx.traps = 0;
    ctx
}

thread_local! {
    static CONTEXT: RefCell<Context> = RefCell::new(default_context());
}

pub struct ContextGuard {
    pub(crate) inner: RefMut<'static, Context>,
}

impl Deref for ContextGuard {
    type Target = Context;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl DerefMut for ContextGuard {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

pub fn get_context() -> ContextGuard {
    CONTEXT.with(|ctx| {
        let inner: RefMut<Context> = ctx.borrow_mut();
        let static_inner: RefMut<'static, Context> = unsafe { std::mem::transmute(inner) };
        ContextGuard {
            inner: static_inner,
        }
    })
}