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
41/// Cube root
42#[inline]
43pub fn cbrt(x: f64) -> f64 {
44    unsafe { cbrt_raw(x) }
45}
46
47/// Returns 'e' raised to the power `x`.
48#[inline]
49pub fn exp(x: f64) -> f64 {
50    unsafe { exp_raw(x) }
51}
52
53/// Decomposes given floating point value x into a normalized fraction and an integral power of two.
54#[inline]
55pub fn frexpf(x: f32) -> (f32, i32) {
56    let mut exp: i32 = 0;
57    let v = unsafe { frexpf_raw(x, &mut exp) };
58    (v, exp)
59}
60
61/// Multiplies an f64 arg by the number 2 raised to the exp power.
62#[inline]
63pub fn ldexp(x: f64, n: i32) -> f64 {
64    unsafe { ldexp_raw(x, n) }
65}
66
67/// Multiplies an f32 arg by the number 2 raised to the exp power.
68#[inline]
69pub fn ldexpf(x: f32, n: i32) -> f32 {
70    unsafe { ldexpf_raw(x, n) }
71}
72
73/// Returns the base-'e' logarithm of the provided number.
74#[inline]
75pub fn log(x: f64) -> f64 {
76    unsafe { log_raw(x) }
77}
78
79/// Returns the fractional and integral parts of an f64. The return ordering `(fractional_part,
80/// integral_part)` is based on the libm crate from crates.io.
81#[inline]
82pub fn modf(x: f64) -> (f64, f64) {
83    let mut integral_part = 0.0;
84    let fractional_part = unsafe { modf_raw(x, &mut integral_part) };
85    (fractional_part, integral_part)
86}
87
88/// Returns the square root of the provided number.
89#[inline]
90pub fn sqrt(x: f64) -> f64 {
91    unsafe { sqrt_raw(x) }
92}