Debian Codegraph @

src/engine/tools.h

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2025 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2009 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (at your option) any later version. *
12 * *
13 * This program is distributed in the hope that it will be useful, *
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
16 * GNU General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU General Public License *
19 * along with this program; if not, write to the *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #pragma once
25
26 #include <bitset>
27 #include <cmath>
28 #include <cstddef>
29 #include <cstdint>
30 #include <iomanip>
31 #include <limits>
32 #include <locale>
33 #include <optional>
34 #include <sstream>
35 #include <string>
36 #include <string_view>
37 #include <type_traits>
38 #include <vector>
39
40 template <typename T, std::enable_if_t<std::is_integral_v<T>, bool> = true>
41 std::string GetHexString( const T value, const int width = 8 )
42 {
43 std::ostringstream stream;
44
45 stream << "0x" << std::setw( width ) << std::setfill( '0' ) << std::hex << value;
46
47 return stream.str();
48 }
49
50 int Sign( const int i );
51
52 std::string StringTrim( std::string str );
53
54 std::string StringLower( std::string str );
55 std::string StringUpper( std::string str );
56
57 std::vector<std::string> StringSplit( const std::string_view str, const char sep );
58
59 void StringReplace( std::string & dst, const char * pred, const std::string_view src );
60
61 template <typename T, std::enable_if_t<std::is_integral_v<T>, bool> = true>
62 void StringReplace( std::string & dst, const char * pred, const T value )
63 {
64 StringReplace( dst, pred, std::to_string( value ) );
65 }
66
67 // Returns the number of bits that are set in the number passed as an argument
68 constexpr int CountBits( uint32_t val )
69 {
70 int res = 0;
71
72 // Using Brian Kernighan's algorithm: https://yuminlee2.medium.com/brian-kernighans-algorithm-count-set-bits-in-a-number-18ab05edca93
73 while ( val ) {
74 val &= ( val - 1 );
75 ++res;
76 }
77
78 return res;
79 }
80
81 namespace fheroes2
82 {
83 uint32_t calculateCRC32( const uint8_t * data, const size_t length );
84
85 template <size_t N>
86 std::bitset<N> makeBitsetFromVector( const std::vector<int> & vector )
87 {
88 std::bitset<N> result;
89 for ( const int index : vector ) {
90 result.set( index, true );
91 }
92 return result;
93 }
94
95 void replaceStringEnding( std::string & output, const char * originalEnding, const char * correctedEnding );
96
97 std::string abbreviateNumber( const int num );
98
99 // Appends the given modifier to the end of the given string (e.g. "Coliseum +2")
100 void appendModifierToString( std::string & str, const int mod );
101
102 // Performs case-insensitive string comparison, suitable for string sorting purposes. Returns true if the first parameter is
103 // "less than" the second, otherwise returns false.
104 template <typename CharType>
105 bool compareStringsCaseInsensitively( const std::basic_string<CharType> & lhs, const std::basic_string<CharType> & rhs )
106 {
107 typename std::basic_string<CharType>::const_iterator li = lhs.begin();
108 typename std::basic_string<CharType>::const_iterator ri = rhs.begin();
109
110 const std::locale currentGlobalLocale;
111
112 while ( li != lhs.end() && ri != rhs.end() ) {
113 const CharType lc = std::tolower( *li, currentGlobalLocale );
114 const CharType rc = std::tolower( *ri, currentGlobalLocale );
115
116 if ( lc < rc ) {
117 return true;
118 }
119 if ( lc > rc ) {
120 return false;
121 }
122 // The characters are "equal", so proceed to checking the next pair
123 ++li;
124 ++ri;
125 }
126
127 // We have reached the end of one (or both) of the strings, the first parameter is considered "less than" the second if it is shorter
128 return li == lhs.end() && ri != rhs.end();
129 }
130
131 // Performs a checked conversion of an integer value of type From to an integer type To. Returns an empty std::optional<To> if
132 // the source value does not fit into the target type.
133 template <typename To, typename From, std::enable_if_t<std::is_integral_v<To> && std::is_integral_v<From>, bool> = true>
134 constexpr std::optional<To> checkedCast( const From from )
135 {
136 // Both types have the same signedness
137 if constexpr ( std::is_signed_v<From> == std::is_signed_v<To> ) {
138 if ( from < std::numeric_limits<To>::min() || from > std::numeric_limits<To>::max() ) {
139 return {};
140 }
141 }
142 // From is signed, To is unsigned
143 else if constexpr ( std::is_signed_v<From> ) {
144 if ( from < 0 ) {
145 return {};
146 }
147
148 const std::make_unsigned_t<From> unsignedFrom = from;
149 if ( unsignedFrom > std::numeric_limits<To>::max() ) {
150 return {};
151 }
152 }
153 // From is unsigned, To is signed
154 else {
155 constexpr To maxTo = std::numeric_limits<To>::max();
156 static_assert( maxTo >= 0 );
157
158 constexpr std::make_unsigned_t<To> unsignedMaxTo = maxTo;
159 if ( from > unsignedMaxTo ) {
160 return {};
161 }
162 }
163
164 return static_cast<To>( from );
165 }
166
167 // Performs a checked conversion of a floating-point value of type From to an integer type To. Returns an empty std::optional<To>
168 // if the source value does not fit into the target type.
169 template <typename To, typename From,
170 std::enable_if_t<( std::is_integral_v<To> && std::numeric_limits<To>::radix == 2 && std ::is_floating_point_v<From> && std::numeric_limits<From>::is_iec559
171 && std::numeric_limits<From>::radix == 2 && std::numeric_limits<To>::digits < std::numeric_limits<From>::max_exponent ),
172 bool>
173 = true>
174 std::optional<To> checkedCast( const From from )
175 {
176 if ( !std::isfinite( from ) ) {
177 return {};
178 }
179
180 static_assert( std::numeric_limits<int8_t>::min() == -128 && std::numeric_limits<int8_t>::max() == 127,
181 "The following logic will only work on platforms with two's complement signed integer representation" );
182
183 // Value of 'from' in general case cannot be compared with std::numeric_limits<To>::max() the way it's usually done for integers due
184 // to the fact that most values exceeding a certain limit cannot be exactly represented in floating-point format. For instance, when
185 // converting from 'float' to 'int32_t', 'INT32_MAX' (2^31 - 1) cannot be exactly represented as 'float', because the significand of
186 // 'float' is just 24 bits long (23 "real" bits + 1 "imaginary" bit), therefore, only those integers whose absolute values do not
187 // exceed 2^24 can be guaranteed to be exactly represented. However, any sane integer which absolute value is 2^N can be exactly
188 // represented in an IEEE 754 floating-point format, and that's what we're going to use here.
189 if constexpr ( std::is_signed_v<To> ) {
190 // Value of 'from' should be not less than -(2^N) and also it should be less than 2^N, where N is a number of significant
191 // bits in the target type
192 if ( from < std::ldexp( static_cast<From>( -1.0 ), std::numeric_limits<To>::digits )
193 || from >= std::ldexp( static_cast<From>( 1.0 ), std::numeric_limits<To>::digits ) ) {
194 return {};
195 }
196 }
197 else {
198 // Value of 'from' should be not less than 0 and also it should be less than 2^N, where N is a number of significant bits
199 // in the target type
200 if ( from < 0 || from >= std::ldexp( static_cast<From>( 1.0 ), std::numeric_limits<To>::digits ) ) {
201 return {};
202 }
203 }
204
205 return static_cast<To>( from );
206 }
207 }