artichoke_backend/extn/core/math/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//! The Ruby Math module.
//!
//! The Math module contains module functions for basic trigonometric and
//! transcendental functions. See class [`Float`] for a list of constants that
//! define Ruby's floating point accuracy.
//!
//! You can use the `Math` module by accessing it in the interpreter. `Math` is
//! globally available in the root namespace.
//!
//! ```ruby
//! Math.hypot(3, 4)
//! ```
//!
//! This module implements the core math module with [`spinoso-math`] and
//! re-exports some of its internals.
//!
//! [`Float`]: https://ruby-doc.org/core-3.1.2/Float.html
//! [`spinoso-math`]: spinoso_math

use std::borrow::Cow;

use crate::extn::prelude::*;

pub(in crate::extn) mod mruby;
pub(super) mod trampoline;

#[doc(inline)]
pub use spinoso_math::{DomainError, Math, E, PI};
use spinoso_math::{Error as MathError, NotImplementedError as MathNotImplementedError};

impl RubyException for DomainError {
    fn message(&self) -> Cow<'_, [u8]> {
        let message = DomainError::message(*self);
        Cow::Borrowed(message.as_bytes())
    }

    fn name(&self) -> Cow<'_, str> {
        "DomainError".into()
    }

    fn vm_backtrace(&self, interp: &mut Artichoke) -> Option<Vec<Vec<u8>>> {
        let _ = interp;
        None
    }

    fn as_mrb_value(&self, interp: &mut Artichoke) -> Option<sys::mrb_value> {
        let message = interp.try_convert_mut(self.message()).ok()?;
        let value = interp.new_instance::<Self>(&[message]).ok().flatten()?;
        Some(value.inner())
    }
}

impl From<DomainError> for Error {
    fn from(exception: DomainError) -> Self {
        let err: Box<dyn RubyException> = Box::new(exception);
        Self::from(err)
    }
}

impl From<MathNotImplementedError> for Error {
    fn from(err: MathNotImplementedError) -> Self {
        let exc = NotImplementedError::from(err.message());
        exc.into()
    }
}

impl From<MathError> for Error {
    fn from(err: MathError) -> Self {
        match err {
            MathError::Domain(err) => err.into(),
            MathError::NotImplemented(err) => err.into(),
        }
    }
}