libfxd 0.2.dev
A fixed-point library for C++.
Loading...
Searching...
No Matches
constructors.hpp
Go to the documentation of this file.
1/*
2 * libfxd - a fixed-point library for C++
3 *
4 * Copyright 2023 Daniel K. O.
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#ifndef LIBFXD_CONSTRUCTORS_HPP
9#define LIBFXD_CONSTRUCTORS_HPP
10
11#include <cfenv>
12#include <cmath>
13#include <concepts>
14#include <type_traits>
15
16#include "fixed.hpp"
17
18#include "detail/bias.hpp"
19#include "detail/opacify.hpp"
20#include "detail/shift.hpp"
21
22
23namespace fxd {
24
25
30 template<int Int,
31 int Frac,
32 typename Raw>
33 template<std::integral I>
34 [[nodiscard]]
35 constexpr
37 noexcept
38 {
39 if constexpr (frac_bits < 0) {
40
41 // Shifting right.
42 // Bias negative values.
43 if (i < 0)
44 i += detail::make_bias_for(-frac_bits, i);
45
46 raw_value = detail::shr_real(i, -frac_bits);
47
48 } else {
49
50 // Shifting left.
51 // Use max bits to minimize spurious overflows.
52 using IWide = detail::max_int_for<raw_type>;
53 raw_value = detail::shl_real<IWide>(i, frac_bits);
54
55 }
56
57 }
58
59
60
61 template<int Int,
62 int Frac,
63 typename Raw>
64 template<std::floating_point Flt>
65 constexpr
67 noexcept
68 {
69 const auto scaled_f = std::ldexp(f, frac_bits);
70 raw_value = static_cast<raw_type>(scaled_f);
71 }
72
73
74
75 template<int Int, int Frac, typename Raw>
76 template<int Int2, int Frac2, typename Raw2>
77 requires (detail::is_safe_conversion_v<Int2, Frac2, Raw2,
78 Int, Frac, Raw>)
79 constexpr
81 noexcept :
82 raw_value{fixed_cast<fixed<Int, Frac, Raw>>(other).raw_value}
83 {}
84
85
86
91 template<int Int,
92 int Frac,
93 typename Raw>
94 [[nodiscard]]
95 constexpr
96 fixed<Int, Frac, Raw>
98 noexcept
99 {
100 fixed result;
101 result.raw_value = static_cast<Raw>(val);
102 return result;
103 }
104
105
106}
107
108
109#endif
This is the namespace where the entire library is defined.
Definition: casting.hpp:19
The fixed-point class template.
Definition: fixed.hpp:38
constexpr fixed() noexcept=default
Defaulted constructor.
static constexpr fixed from_raw(raw_type val) noexcept
Constructs a fixed from any raw bit representation (no conversion.)
Raw raw_type
The integral type that will hold the raw representation of the value.
Definition: fixed.hpp:41
raw_type raw_value
The raw value, stored as a bitfield.
Definition: fixed.hpp:65