libm/
lib.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! A shim impelementation of the libm crate, binding directly to the in-tree libc's versions of
6//! these functions.
7
8#[macro_use]
9extern crate static_assertions;
10
11// Make sure we aren't building for one of the "esoteric systems" on which c_int is not identical
12// to i32 (https://doc.rust-lang.org/std/os/raw/type.c_int.html).
13assert_type_eq_all!(std::os::raw::c_int, i32);
14
15extern "C" {
16    #[link_name = "cbrt"]
17    fn cbrt_raw(x: f64) -> f64;
18
19    #[link_name = "exp"]
20    fn exp_raw(x: f64) -> f64;
21
22    #[link_name = "frexpf"]
23    fn frexpf_raw(x: f32, exp: *mut i32) -> f32;
24
25    #[link_name = "ldexp"]
26    fn ldexp_raw(x: f64, n: i32) -> f64;
27
28    #[link_name = "ldexpf"]
29    fn ldexpf_raw(x: f32, n: i32) -> f32;
30
31    #[link_name = "log"]
32    fn log_raw(x: f64) -> f64;
33
34    #[link_name = "modf"]
35    fn modf_raw(x: f64, integer_part: *mut f64) -> f64;
36
37    #[link_name = "sqrt"]
38    fn sqrt_raw(x: f64) -> f64;
39
40    #[link_name = "fabs"]
41    fn fabs_raw(x: f64) -> f64;
42}
43
44/// Cube root
45#[inline]
46pub fn cbrt(x: f64) -> f64 {
47    unsafe { cbrt_raw(x) }
48}
49
50/// Returns 'e' raised to the power `x`.
51#[inline]
52pub fn exp(x: f64) -> f64 {
53    unsafe { exp_raw(x) }
54}
55
56/// Decomposes given floating point value x into a normalized fraction and an integral power of two.
57#[inline]
58pub fn frexpf(x: f32) -> (f32, i32) {
59    let mut exp: i32 = 0;
60    let v = unsafe { frexpf_raw(x, &mut exp) };
61    (v, exp)
62}
63
64/// Multiplies an f64 arg by the number 2 raised to the exp power.
65#[inline]
66pub fn ldexp(x: f64, n: i32) -> f64 {
67    unsafe { ldexp_raw(x, n) }
68}
69
70/// Multiplies an f32 arg by the number 2 raised to the exp power.
71#[inline]
72pub fn ldexpf(x: f32, n: i32) -> f32 {
73    unsafe { ldexpf_raw(x, n) }
74}
75
76/// Returns the base-'e' logarithm of the provided number.
77#[inline]
78pub fn log(x: f64) -> f64 {
79    unsafe { log_raw(x) }
80}
81
82/// Returns the fractional and integral parts of an f64. The return ordering `(fractional_part,
83/// integral_part)` is based on the libm crate from crates.io.
84#[inline]
85pub fn modf(x: f64) -> (f64, f64) {
86    let mut integral_part = 0.0;
87    let fractional_part = unsafe { modf_raw(x, &mut integral_part) };
88    (fractional_part, integral_part)
89}
90
91/// Returns the square root of the provided number.
92#[inline]
93pub fn sqrt(x: f64) -> f64 {
94    unsafe { sqrt_raw(x) }
95}
96
97/// Returns the absolute value (i.e. magnitude) of the argument x
98#[inline]
99pub fn fabs(x: f64) -> f64 {
100    unsafe { fabs_raw(x) }
101}