Blender V5.0
BLI_fixed_width_int_str.hh
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2024 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
8
9#pragma once
10
12#ifdef WITH_GMP
13
14# include <gmpxx.h>
15
16# include "BLI_array.hh"
17# include "BLI_fixed_width_int.hh"
18
20
21template<typename T, int S>
22inline void UIntF<T, S>::set_from_str(const StringRefNull str, const int base)
23{
24 mpz_t x;
25 mpz_init(x);
26 mpz_set_str(x, str.c_str(), base);
27 for (int i = 0; i < S; i++) {
28 static_assert(sizeof(T) <= sizeof(decltype(mpz_get_ui(x))));
29 this->v[i] = T(mpz_get_ui(x));
30 mpz_div_2exp(x, x, 8 * sizeof(T));
31 }
32 mpz_clear(x);
33}
34
35template<typename T, int S>
36inline void IntF<T, S>::set_from_str(const StringRefNull str, const int base)
37{
38 if (str[0] == '-') {
39 const UIntF<T, S> unsigned_value(str.c_str() + 1, base);
40 this->v = unsigned_value.v;
41 *this = -*this;
42 }
43 else {
44 const UIntF<T, S> unsigned_value(str.c_str(), base);
45 this->v = unsigned_value.v;
46 }
47}
48
49template<typename T, int S> inline std::string UIntF<T, S>::to_string(const int base) const
50{
51 mpz_t x;
52 mpz_init(x);
53 for (int i = S - 1; i >= 0; i--) {
54 static_assert(sizeof(T) <= sizeof(decltype(mpz_get_ui(x))));
55 mpz_mul_2exp(x, x, 8 * sizeof(T));
56 mpz_add_ui(x, x, this->v[i]);
57 }
58 /* Add 2 because of possible +/- sign and null terminator. */
59 /* Also see https://gmplib.org/manual/Converting-Integers. */
60 const int str_size = mpz_sizeinbase(x, base) + 2;
61 Array<char, 1024> str(str_size);
62 mpz_get_str(str.data(), base, x);
63 mpz_clear(x);
64 return std::string(str.data());
65}
66
67template<typename T, int S> inline std::string IntF<T, S>::to_string(const int base) const
68{
69 if (is_negative(*this)) {
70 std::string str = UIntF<T, S>(-*this).to_string(base);
71 str.insert(str.begin(), '-');
72 return str;
73 }
74 return UIntF<T, S>(*this).to_string();
75}
76
77} // namespace blender::fixed_width_int
78
79#endif /* WITH_GMP */
ATTR_WARN_UNUSED_RESULT const BMVert * v
#define str(s)
#define T
bool is_negative(const IntF< T, Size > &a)
i
Definition text_draw.cc:230