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
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![warn(clippy::needless_borrow)]
// https://github.com/rust-lang/rust-clippy/pull/5998#issuecomment-731855891
#![allow(clippy::map_err_ignore)]
#![allow(clippy::option_if_let_else)]
#![allow(unknown_lints)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![warn(missing_copy_implementations)]
#![warn(rust_2018_idioms)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_qualifications)]
#![warn(variant_size_differences)]
#![forbid(unsafe_code)]
// Enable feature callouts in generated documentation:
// https://doc.rust-lang.org/beta/unstable-book/language-features/doc-cfg.html
//
// This approach is borrowed from tokio.
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, feature(doc_alias))]

//! 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.
//!
//! This crate defines math operations as free functions. These functions differ
//! from those defined in Rust [`core`] by returning a [`DomainError`] when an
//! input is outside of the domain of the function and results in [`NaN`].
//!
//! `spinoso-math` assumes the Ruby VM uses double precision [`f64`] floats.
//!
//! # Examples
//!
//! Compute the hypotenuse:
//!
//! ```
//! use spinoso_math as math;
//! assert_eq!(math::hypot(3.0, 4.0), 5.0);
//! ```
//!
//! Compute log with respect to the base 10 and handle domain errors:
//!
//! ```
//! use spinoso_math as math;
//! assert_eq!(math::log10(1.0), Ok(0.0));
//! assert_eq!(math::log10(10.0), Ok(1.0));
//! assert_eq!(math::log10(1e100), Ok(100.0));
//!
//! assert_eq!(math::log10(0.0), Ok(f64::NEG_INFINITY));
//! assert!(math::log10(-0.1).is_err());
//!
//! // A NaN return value is distinct from a `DomainError`.
//! assert!(matches!(math::log10(f64::NAN), Ok(result) if result.is_nan()));
//! ```
//!
//! # `no_std`
//!
//! This crate is `no_std` compatible when built without the `std` feature. This
//! crate does not depend on [`alloc`].
//!
//! # Crate features
//!
//! All features are enabled by default.
//!
//! - **full** - Enables implementations of math functions that do not have
//!   implementations in Rust [`core`]. Dropping this feature removes the
//!   [`libm`] dependency.
//! - **std** - Enables a dependency on the Rust Standard Library. Activating
//!   this feature enables [`std::error::Error`] impls on error types in this
//!   crate.
//!
//! [`Float`]: https://ruby-doc.org/core-2.6.3/Float.html
//! [`NaN`]: f64::NAN
//! [`alloc`]: https://doc.rust-lang.org/alloc/

use core::fmt;
#[cfg(feature = "std")]
use std::error;

#[doc(inline)]
pub use core::f64::consts::E;
#[doc(inline)]
pub use core::f64::consts::PI;

mod math;

pub use math::*;

/// A handle to the `Math` module.
///
/// This is a copy zero-sized type with no associated methods. This type exists
/// so a Ruby VM can attempt to unbox this type and statically dispatch to
/// functions defined in this crate.
///
/// # Examples
///
/// ```
/// # use spinoso_math::Math;
/// const MATH: Math = Math::new();
/// ```
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Math {
    _private: (),
}

impl Math {
    /// Constructs a new, default `Math`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::Math;
    /// const MATH: Math = Math::new();
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self { _private: () }
    }
}

/// Sum type of all errors possibly returned from `Math` functions.
///
/// Math functions in `spinoso-math` return errors in the following conditions:
///
/// - The parameters evaluate to a result that is out of range.
/// - The function is not implemented due to missing compile-time flags.
#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Error {
    /// Error that indicates a math function returned a value that was out of
    /// range.
    ///
    /// This error can be used to differentiate between [`NaN`](f64::NAN) inputs
    /// and what would be `NaN` outputs.
    ///
    /// See [`DomainError`].
    Domain(DomainError),
    /// Error that indicates a `Math` module function is not implemented.
    ///
    /// See [`NotImplementedError`].
    NotImplemented(NotImplementedError),
}

impl Error {
    /// Retrieve the exception message associated with this error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::{DomainError, Error, NotImplementedError};
    /// let err = Error::from(DomainError::new());
    /// assert_eq!(err.message(), "Math::DomainError");
    ///
    /// let err = Error::from(NotImplementedError::with_message(
    ///     "Artichoke was not built with Math::erf support"
    /// ));
    /// assert_eq!(err.message(), "Artichoke was not built with Math::erf support");
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        match self {
            Self::Domain(err) => err.message(),
            Self::NotImplemented(err) => err.message(),
        }
    }
}

impl From<DomainError> for Error {
    #[inline]
    fn from(err: DomainError) -> Self {
        Self::Domain(err)
    }
}

impl From<NotImplementedError> for Error {
    #[inline]
    fn from(err: NotImplementedError) -> Self {
        Self::NotImplemented(err)
    }
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Math error")
    }
}

#[cfg(feature = "std")]
impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Self::Domain(ref err) => Some(err),
            Self::NotImplemented(ref err) => Some(err),
        }
    }
}

/// Error that indicates a math function evaluated to an out of range value.
///
/// Domain errors have an associated message.
///
/// This error corresponds to the [Ruby `Math::DomainError` Exception class]. It
/// can be used to differentiate between [`NaN`](f64::NAN) inputs and what would
/// be `NaN` outputs.
///
/// # Examples
///
/// ```
/// # use spinoso_math::DomainError;
/// let err = DomainError::new();
/// assert_eq!(err.message(), "Math::DomainError");
///
/// let err = DomainError::with_message(
///     r#"Numerical argument is out of domain - "acos""#,
/// );
/// assert_eq!(err.message(), r#"Numerical argument is out of domain - "acos""#);
/// ```
///
/// [Ruby `Math::DomainError` Exception class]: https://ruby-doc.org/core-2.6.3/Math/DomainError.html
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct DomainError(&'static str);

impl From<&'static str> for DomainError {
    #[inline]
    fn from(message: &'static str) -> Self {
        Self(message)
    }
}

impl DomainError {
    /// Construct a new, default domain error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::DomainError;
    /// const ERR: DomainError = DomainError::new();
    /// assert_eq!(ERR.message(), "Math::DomainError");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        // [2.6.3] > Math::DomainError.new.message
        // => "Math::DomainError"
        Self("Math::DomainError")
    }

    /// Construct a new, domaine error with a message.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::DomainError;
    /// const ERR: DomainError = DomainError::with_message(
    ///     r#"Numerical argument is out of domain - "acos""#,
    /// );
    /// assert_eq!(ERR.message(), r#"Numerical argument is out of domain - "acos""#);
    /// ```
    #[inline]
    #[must_use]
    pub const fn with_message(message: &'static str) -> Self {
        Self(message)
    }

    /// Retrieve the exception message associated with this error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::DomainError;
    /// let err = DomainError::new();
    /// assert_eq!(err.message(), "Math::DomainError");
    ///
    /// let err = DomainError::with_message(
    ///     r#"Numerical argument is out of domain - "acos""#,
    /// );
    /// assert_eq!(err.message(), r#"Numerical argument is out of domain - "acos""#);
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        self.0
    }
}

impl fmt::Display for DomainError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0)
    }
}

#[cfg(feature = "std")]
impl error::Error for DomainError {}

/// Error that indicates a `Math` module function is not implemented.
///
/// Some math functions are not available in the [Rust core library] and require
/// this crate to be built with extra compile-time features to enable [additional
/// dependencies].
///
/// Not implemented errors have an associated message.
///
/// This error corresponds to the [Ruby `NotImplementedError` Exception class].
///
/// # Examples
///
/// ```
/// # use spinoso_math::NotImplementedError;
/// let err = NotImplementedError::new();
/// assert_eq!(err.message(), "NotImplementedError");
///
/// let err = NotImplementedError::with_message(
///     "Artichoke was not built with Math::erf support"
/// );
/// assert_eq!(err.message(), "Artichoke was not built with Math::erf support");
/// ```
///
/// [Rust core library]: https://doc.rust-lang.org/std/primitive.f64.html
/// [additional dependencies]: https://crates.io/crates/libm
/// [Ruby `NotImplementedError` Exception class]: https://ruby-doc.org/core-2.6.3/NotImplementedError.html
#[derive(Default, Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct NotImplementedError(&'static str);

impl NotImplementedError {
    /// Construct a new, default not implemented error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::NotImplementedError;
    /// const ERR: NotImplementedError = NotImplementedError::new();
    /// assert_eq!(ERR.message(), "NotImplementedError");
    /// ```
    #[inline]
    #[must_use]
    pub const fn new() -> Self {
        Self("NotImplementedError")
    }

    /// Construct a new, not implemented error with a message.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::NotImplementedError;
    /// const ERR: NotImplementedError = NotImplementedError::with_message(
    ///     "Artichoke was not built with Math::erf support"
    /// );
    /// assert_eq!(ERR.message(), "Artichoke was not built with Math::erf support");
    /// ```
    #[inline]
    #[must_use]
    pub const fn with_message(message: &'static str) -> Self {
        Self(message)
    }

    /// Retrieve the exception message associated with this not implemented
    /// error.
    ///
    /// # Examples
    ///
    /// ```
    /// # use spinoso_math::NotImplementedError;
    /// let err = NotImplementedError::new();
    /// assert_eq!(err.message(), "NotImplementedError");
    ///
    /// let err = NotImplementedError::with_message(
    ///     "Artichoke was not built with Math::erf support"
    /// );
    /// assert_eq!(err.message(), "Artichoke was not built with Math::erf support");
    /// ```
    #[inline]
    #[must_use]
    pub const fn message(self) -> &'static str {
        self.0
    }
}

impl From<&'static str> for NotImplementedError {
    #[inline]
    fn from(message: &'static str) -> Self {
        Self(message)
    }
}

impl fmt::Display for NotImplementedError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0)
    }
}

#[cfg(feature = "std")]
impl error::Error for NotImplementedError {}