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