artichoke_backend/extn/core/math/
mod.rs

1//! The Ruby Math module.
2//!
3//! The Math module contains module functions for basic trigonometric and
4//! transcendental functions. See class [`Float`] for a list of constants that
5//! define Ruby's floating point accuracy.
6//!
7//! You can use the `Math` module by accessing it in the interpreter. `Math` is
8//! globally available in the root namespace.
9//!
10//! ```ruby
11//! Math.hypot(3, 4)
12//! ```
13//!
14//! This module implements the core math module with [`spinoso-math`] and
15//! re-exports some of its internals.
16//!
17//! [`Float`]: https://ruby-doc.org/core-3.1.2/Float.html
18//! [`spinoso-math`]: spinoso_math
19
20use std::borrow::Cow;
21
22use crate::extn::prelude::*;
23
24pub(in crate::extn) mod mruby;
25pub(super) mod trampoline;
26
27#[doc(inline)]
28pub use spinoso_math::{DomainError, E, Math, PI};
29use spinoso_math::{Error as MathError, NotImplementedError as MathNotImplementedError};
30
31impl RubyException for DomainError {
32    fn message(&self) -> Cow<'_, [u8]> {
33        let message = DomainError::message(*self);
34        Cow::Borrowed(message.as_bytes())
35    }
36
37    fn name(&self) -> Cow<'_, str> {
38        "DomainError".into()
39    }
40
41    fn vm_backtrace(&self, interp: &mut Artichoke) -> Option<Vec<Vec<u8>>> {
42        let _ = interp;
43        None
44    }
45
46    fn as_mrb_value(&self, interp: &mut Artichoke) -> Option<sys::mrb_value> {
47        let message = interp.try_convert_mut(self.message()).ok()?;
48        let value = interp.new_instance::<Self>(&[message]).ok().flatten()?;
49        Some(value.inner())
50    }
51}
52
53impl From<DomainError> for Error {
54    fn from(exception: DomainError) -> Self {
55        let err: Box<dyn RubyException> = Box::new(exception);
56        Self::from(err)
57    }
58}
59
60impl From<MathNotImplementedError> for Error {
61    fn from(err: MathNotImplementedError) -> Self {
62        let exc = NotImplementedError::from(err.message());
63        exc.into()
64    }
65}
66
67impl From<MathError> for Error {
68    fn from(err: MathError) -> Self {
69        match err {
70            MathError::Domain(err) => err.into(),
71            MathError::NotImplemented(err) => err.into(),
72        }
73    }
74}