~aleteoryx/muditaos

ref: d9a66b8b47f730a198242706c578d48617a28d92 muditaos/module-utils/math/Math.hpp -rw-r--r-- 2.1 KiB
d9a66b8b — Lefucjusz Revert "[MOS-170] Report domestic roaming as home network" 2 years ago
                                                                                
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
// Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md

#pragma once

#include <cstdint>
#include <cmath>

namespace trigonometry
{
    using SideLength = std::int32_t;
    using Degrees    = std::int32_t;
    using Radians    = double;

    constexpr Degrees FullAngle  = 360;
    constexpr Degrees HalfAngle  = 180;
    constexpr Degrees RightAngle = 90;

    constexpr static inline auto toRadians(Degrees degrees) noexcept -> Radians
    {
        return degrees * M_PI / HalfAngle;
    }

    struct AdjacentSide
    {
        static auto fromAngle(Radians angle, SideLength hypotenuse) -> SideLength
        {
            return std::round(std::cos(angle) * hypotenuse);
        }

        static auto fromCosine(double cosine, SideLength hypotenuse) -> SideLength
        {
            return std::round(cosine * hypotenuse);
        }
    };

    struct OppositeSide
    {
        static auto fromAngle(Radians angle, SideLength hypotenuse) -> SideLength
        {
            return std::round(std::sin(angle) * hypotenuse);
        }

        static auto fromSine(double sine, SideLength hypotenuse) -> SideLength
        {
            return std::round(sine * hypotenuse);
        }
    };
} // namespace trigonometry

namespace binary
{
    constexpr static inline auto isPowerOfTwo(unsigned int x) -> bool
    {
        return x == 0 ? false : __builtin_popcount(x) == 1;
    }

    static inline auto floorPowerOfTwo(unsigned int x) -> unsigned int
    {
        constexpr auto xBitCount = sizeof(x) * 8;

        if (x == 0) {
            return 0;
        }
        else if (isPowerOfTwo(x)) {
            return x;
        }

        return 1 << (xBitCount - __builtin_clz(x) - 1);
    }

    static inline auto ceilPowerOfTwo(unsigned int x) -> unsigned int
    {
        constexpr auto xBitCount = sizeof(x) * 8;
        auto leadingZeroes       = __builtin_clz(x);

        if (leadingZeroes == 0 || x == 0) {
            return 0;
        }
        else if (isPowerOfTwo(x)) {
            return x;
        }

        return 1 << (xBitCount - leadingZeroes);
    }

} // namespace binary