ug_misc 0.1
Miscellaneous C++ header library
Loading...
Searching...
No Matches
int_finder.hpp
Go to the documentation of this file.
1/*
2 * SPDX-Licence-Identifier: MIT
3 *
4 * Copyright 2025 Larry Chips
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the “Software”), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24#pragma once
25
66
67#include <cstdint>
68#include <limits>
69#include <string_view>
70#include <type_traits>
71#include "ugmisc/bitops.hpp"
72#include "ugmisc/features.hpp"
73#include "ugmisc/member.hpp"
74#include "ugmisc/quote.hpp"
75
76
77namespace ugmisc {
78
79
81enum int_sign { INVALID_SIGN = 0, UNSIGNED = 1, SIGNED = 2 };
82
83
84
85
86constexpr int_sign flip( int_sign s ) {
87 return static_cast<int_sign>(((unsigned)s) ^ 3);
88}
89
90
91
92
102enum sign_opt : std::uint8_t {
103 SELECT_SIGN_OPTION_NONE = 0,
104 SELECT_UNSIGNED = 1,
105 SELECT_SIGNED = 2,
109
110 SELECT_SIGN_OPTION_MAX = SELECT_VALUE_SIGN,
111 SELECT_SIGN_OPTION_MASK = 7,
112};
113
114
115
116
117constexpr std::string_view get_name(sign_opt opt) {
118 switch( opt ) {
119 case SELECT_SIGN_OPTION_NONE:
120 return "NONE";
121 case SELECT_UNSIGNED:
122 return "SELECT_UNSIGNED";
123 case SELECT_SIGNED:
124 return "SELECT_SIGNED";
125 case SELECT_TYPE_SIGN:
126 return "SELECT_TYPE_SIGN";
127 case SELECT_VALUE_SIGN:
128 return "SELECT_VALUE_SIGN";
129 default:
130 return "INVALID";
131 }
132};
133
134
135
136
137
138template<class T>
139constexpr int_sign sign(sign_opt opt, T v) {
140
141 switch( opt ) {
142 case SELECT_UNSIGNED: return UNSIGNED;
143 case SELECT_SIGNED: return SIGNED;
144 case SELECT_TYPE_SIGN:
145 return std::is_signed_v<T> ? SIGNED : UNSIGNED;
147 return v < 0 ? SIGNED : UNSIGNED;
148 default:
149 return INVALID_SIGN;
150 }
151}
152
153
154
155
156enum sign_flag : std::uint8_t {
157 SELECT_SIGN_FLAGS_NONE,
168
175
177};
178
179
180constexpr sign_flag operator~(sign_flag f) {
181 return static_cast<sign_flag>((~(std::uint8_t)f)&(std::uint8_t)SELECT_SIGN_FLAGS_MASK);
182}
183
184
185constexpr sign_flag operator|(sign_flag a, sign_flag b) {
186 return static_cast<sign_flag>((std::uint8_t)a | (std::uint8_t)b);
187}
188
189
190constexpr bool smallest(sign_flag s) {
191 return (std::uint8_t)SELECT_SIGN_SMALLEST & (std::uint8_t)s;
192}
193
194
195constexpr bool allow_value_sign_loss(sign_flag s) {
196 return (std::uint8_t)SELECT_SIGN_ALLOW_VALUE_SIGN_LOSS & (std::uint8_t)s;
197}
198
199
200/*
201 * This might have to be a string instead of a string_view if we add more
202 * flags, because we can't just special case every combination.
203 *
204 * Then we would have to ditch the constexpr too.
205 */
206constexpr std::string_view get_name(sign_flag flags) {
207 bool smol = smallest(flags);
208 bool signloss = allow_value_sign_loss(flags);
209 if ( smol && signloss ) {
210 return "SELECT_SIGN_SMALLEST|SELECT_SIGN_ALLOW_VALUE_SIGN_LOSS";
211 } else if ( smol ) {
212 return "SELECT_SIGN_SMALLEST";
213 } else if ( signloss ) {
214 return "SELECT_SIGN_ALLOW_VALUE_SIGN_LOSS";
215 } else {
216 return "NONE";
217 }
218}
219
220
221
222
224namespace intfind_ {
225
226
227
228
229template<class T>
230inline constexpr bool is_opt = std::is_convertible_v<T, sign_opt>;
231
232template<class T>
233inline constexpr bool is_flag = std::is_convertible_v<T, sign_flag>;
234
235
236
237
243template< class T >
244constexpr sign_opt sign_opt_or_not(T t) {
245 if constexpr ( is_opt<T> ) {
246 return static_cast<sign_opt>(t);
247 } else if constexpr ( is_flag<T> ) {
248 return SELECT_SIGN_OPTION_NONE;
249 } else {
250 static_assert( false );
251 }
252}
253
254
255template<class T> constexpr bool is_non_null_opt(T t) {
256 return (unsigned)sign_opt_or_not(t);
257}
258
259
260template<class T> constexpr sign_flag sign_flag_or_not(T t) {
261 if constexpr ( is_flag<T> ) {
262 return static_cast<sign_flag>(t);
263 } else if constexpr ( is_opt<T> ) {
264 return SELECT_SIGN_FLAGS_NONE;
265 } else {
266 static_assert(
267 false,
268 "sign_flag_or_not takes sign_flag and sign_opt, "
269 "and types convertible to them."
270 );
271 }
272}
273
274
275
276
282template<auto...Opts>
283constexpr sign_opt combine_sign_opts_f()
284{
285 constexpr sign_opt opt_array[sizeof...(Opts)] = { sign_opt_or_not(Opts)... };
286 sign_opt found_opt = SELECT_SIGN_OPTION_NONE;
287 for( sign_opt opt: opt_array ) {
288 if ( opt == SELECT_SIGN_OPTION_NONE ) {
289 continue;
290 }
291 if ( found_opt != SELECT_SIGN_OPTION_NONE && opt != found_opt ) {
292 return SELECT_SIGN_OPTION_NONE;
293 }
294 found_opt = opt;
295 }
296 return found_opt;
297}
298
299
300
301
302template<auto...Opts> static constexpr sign_opt combined_sign_opts
303 = combine_sign_opts_f<Opts...>();
304
305
306template<auto...Flags> static constexpr sign_flag combined_sign_flags
307 = (SELECT_SIGN_FLAGS_NONE | ... | sign_flag_or_not(Flags));
308
309
310
311
312template<auto...Opt>
313static constexpr bool valid_sign_opts = (unsigned)combined_sign_opts<Opt...>;
314
315
316
317
318template<auto...Opt>
319static constexpr bool any_sign_opts = (... || is_non_null_opt(Opt));
320
321
322
323
331template<bool HasOpt>
332class flag_opt_combo {
333 const sign_flag m_flags;
334
335public:
336 flag_opt_combo(const flag_opt_combo&) = default;
337 constexpr flag_opt_combo(sign_flag sflags) : m_flags(sflags) {}
338
339 constexpr sign_flag flags() const { return m_flags; }
340 constexpr sign_opt safe_opt() const { return SELECT_SIGN_OPTION_NONE; }
341 constexpr sign_opt opt() const {
342 static_assert(
343 false,
344 "This flag_opt_combo does not have an option."
345 );
346 return safe_opt();
347 }
348
349 constexpr operator sign_flag() const { return flags(); }
350};
351
352
353template<>
354class flag_opt_combo<true> : public flag_opt_combo<false> {
355 const sign_opt m_opt;
356
357public:
358 flag_opt_combo(const flag_opt_combo&) = default;
359 constexpr flag_opt_combo(sign_opt sopt, sign_flag sflags)
360 : flag_opt_combo<false>(sflags), m_opt(sopt)
361 {}
362
363 constexpr sign_opt opt() const { return m_opt; }
364 constexpr sign_opt safe_opt() const { return opt(); }
365
366 constexpr operator sign_opt() const { return opt(); }
367};
368
369
370
371
372template<auto...args>
373constexpr auto combine_flags_opts()
374{
375 constexpr sign_flag flags = combined_sign_flags<args...>;
376 constexpr sign_opt opt = combined_sign_opts<args...>;
377 constexpr bool valid_opts = valid_sign_opts<args...>;
378 constexpr bool any_opts = any_sign_opts<args...>;
379
380 if constexpr ( any_opts ) {
381 static_assert( valid_opts );
382 return flag_opt_combo<true>{opt, flags};
383 } else {
384 return flag_opt_combo<false>{flags};
385 }
386}
387
388
389
390
391
392} /* intfind_ */
394// INTERNAL
395
396
397
398
399#ifndef UGMISC_INT_FINDER_MAX_INT_WIDTH
404# define UGMISC_INT_FINDER_MAX_INT_WIDTH (1U << 12);
405#endif
412
413
414
415
422template<unsigned N> struct get_int_types {};
423
424
438template<> struct get_int_types<8> {
439 using unsigned_type = std::uint8_t;
440 using signed_type = std::int8_t;
441};
442
443
447template<> struct get_int_types<16> {
448 using unsigned_type = std::uint16_t;
449 using signed_type = std::int16_t;
450};
451
452
456template<> struct get_int_types<32> {
457#ifndef UGMISC_TEST_INT_FINDER_SKIP_U32
458 using unsigned_type = std::uint32_t;
459#endif
460 using signed_type = std::int32_t;
461};
462
463
467template<> struct get_int_types<64> {
468 using unsigned_type = std::uint64_t;
469 using signed_type = std::int64_t;
470};
471
472
473
474
476namespace intfind_ {
477
478
479
480
481constexpr unsigned round_up_to_pow2(unsigned x) {
482 unsigned hi = 1U << bitwidth(x);
483 unsigned lo = hi >> 1;
484 return x ? (lo == x ? lo : hi) : 1;
485}
486
487
488
489
490/*
491 * This allows us to test the existence of a type easily.
492 *
493 * Resulting declarations are listed below for clarity.
494 */
495UGMISC_MEMBER_TYPE_TEST(unsigned_type);
496UGMISC_MEMBER_TYPE_TEST(signed_type);
497// has_member_type_unsigned_type< T >; // T can be a type_list.
498// member_type_unsigned_type< T, D (optional) > // T can be type_list,
499 // D is a default type.
500// member_type_test_unsigned_type< T > // Usually not used directly.
501// has_member_type_signed_type< T >; // T can be a type_list.
502// member_type_signed_type< T, D (optional) > // T can be type_list,
503 // D is a default type.
504// member_type_test_signed_type< T > // Usually not used directly.
505
506
507
508template<unsigned N>
509constexpr bool check_member_int_types(get_int_types<N> t) {
510 static_assert( N <= max_int_width,
511 "Integer width must be no more than "
513 " bits."
514 );
515 using T = decltype(t);
516
517 if constexpr ( has_member_type_unsigned_type<T> ) {
518 using I = typename T::unsigned_type;
519 using limits = std::numeric_limits<I>;
520 constexpr unsigned bits = limits::digits;
521 static_assert( limits::radix == 2 );
522 static_assert( limits::is_integer );
523 static_assert( ! limits::is_signed );
524 static_assert( bits == N );
525 }
526
527 if constexpr ( has_member_type_signed_type<T> ) {
528 using I = typename T::signed_type;
529 using limits = std::numeric_limits<I>;
530 constexpr unsigned bits = limits::digits + 1; // Sign bit.
531 static_assert( limits::radix == 2 );
532 static_assert( limits::is_integer );
533 static_assert( limits::is_signed );
534 static_assert( bits == N );
535 }
536
537 return true;
538}
539
540
541
542
547template<unsigned N> struct get_int_types : public ::ugmisc::get_int_types<N> {
548private:
549 static constexpr bool _check =
550 check_member_int_types(::ugmisc::get_int_types<N>{});
551};
552
553
554
555
556} /* intfind_ (::ugmisc::intfind_) */
558// INTERNAL
559
560
561
562
576template<unsigned N, int_sign Sign>
577inline constexpr bool has_int_type =
578 Sign == UNSIGNED
579 ? intfind_::has_member_type_unsigned_type< intfind_::get_int_types<N> >
580 : intfind_::has_member_type_signed_type< intfind_::get_int_types<N> >
581 ;
582
583
585template<unsigned N> inline constexpr bool has_unsigned_type =
587
589template<unsigned N> inline constexpr bool has_signed_type = has_int_type<N, SIGNED>;
590
592template<unsigned N> inline constexpr bool has_both_int_types =
594
596template<unsigned N> inline constexpr bool has_either_int_type =
598
599
600
601
603template<unsigned N> using exact_unsigned_type = typename intfind_::get_int_types<N>::unsigned_type;
604
606template<unsigned N> using exact_signed_type = typename intfind_::get_int_types<N>::signed_type;
607
608
609
610
612namespace intfind_ {
613
614
620template<unsigned N, int_sign S> struct get_exact_int_type;
621
622
623template<unsigned N>
624struct get_exact_int_type<N, UNSIGNED> {
625 using type = typename get_int_types<N>::unsigned_type;
626};
627
628template<unsigned N>
629struct get_exact_int_type<N, SIGNED> {
630 using type = typename get_int_types<N>::signed_type;
631};
632
633
634} /* intfind_ */
636// INTERNAL
637
638
642template<unsigned N, int_sign S> using exact_int_type =
643 typename intfind_::get_exact_int_type<N, S>::type;
644
645
646
647
649namespace intfind_ {
650
651
652
653
654#ifdef UGMISC_TEST_INT_FINDER_INNER_LOOP_MAX
655static constexpr unsigned find_inner_loop_max = UGMISC_TEST_INT_FINDER_INNER_LOOP_MAX;
656#else
657static constexpr unsigned find_inner_loop_max = 100;
658#endif
659
660
661
662
669template<unsigned Min, int_sign Sign, unsigned Max>
670constexpr auto find_type_100() {
671 static_assert( Max - Min < find_inner_loop_max );
672 static_assert( Max <= max_int_width );
673 static_assert( Min <= Max );
674 static_assert( Sign == UNSIGNED || Sign == SIGNED );
675
676 if constexpr ( has_int_type<Min, Sign> ) {
678 } else if constexpr ( Min == Max ) {
679 return false;
680 } else {
681 return find_type_100<Min+1, Sign, Max>();
682 }
683}
684
685
686
687
700template<unsigned Min, int_sign Sign, unsigned Max = max_int_width>
701constexpr auto find_type() {
702 static_assert(Max <= max_int_width);
703 static_assert(Max >= Min);
704 static_assert( Sign == UNSIGNED || Sign == SIGNED );
705
706 constexpr unsigned near_max = std::min(Min+find_inner_loop_max-1, Max);
707 constexpr bool last_iter = near_max == Max;
708
709 if constexpr ( find_type_100<Min, Sign, near_max>() ) {
710 return find_type_100<Min, Sign, near_max>();
711 } else if constexpr ( last_iter ) {
712 return false;
713 } else {
714 return find_type<near_max+1, Sign, Max>();
715 }
716}
717
718
719
720
721}
723// INTERNAL
724
725
726
727
734template<unsigned N, int_sign S>
736 std::enable_if_t<
737 intfind_::find_type<N, S>(),
738 decltype(intfind_::find_type<N, S>())
739 >;
740
741
745template<unsigned N>
747
748
752template<unsigned N>
754
755
756
757
777template< bool IncludingSignBit, class T >
780 constexpr bool use_sign_bit = std::is_signed_v<T> && IncludingSignBit;
781 constexpr unsigned extra_bits = use_sign_bit ? 1 : 0;
782 const U w = v >= 0 ? (U)v : ~(U)v;
783 return bitwidth(w) + extra_bits;
784}
785
786
787
788
790namespace intfind_ {
791
792
793
794
795template<class T>
796struct range_result_compare {
797 const T value;
798 range_result_compare(const range_result_compare&) = default;
799 constexpr range_result_compare(T v) : value(v) {}
800 constexpr bool valid() const { return value; }
801 constexpr unsigned size() const { return sizeof(T); }
802 constexpr unsigned used_bits() const {
803 unsigned sign_bit = std::numeric_limits<T>::is_signed ? 1 : 0;
804 return std::numeric_limits<T>::digits + sign_bit;
805 }
806};
807
808
809
810
811/*
812 * When looking for a smaller result type, a valid one always wins if the other
813 * is invalid. We care most about storage size, then used bits.
814 */
815template<class T, class U>
816constexpr bool operator < (range_result_compare<T> a, range_result_compare<U> b) {
817 if ( !a.valid() ) { return false; }
818 if ( !b.valid() ) { return true; }
819 if ( a.size() < b.size() ) { return true; }
820 if ( a.size() > b.size() ) { return false; }
821 return a.used_bits() < b.used_bits();
822}
823
824
825
826
827template<auto V, auto...SelectArgs>
828constexpr auto as_least_required_type() {
829 constexpr auto S = intfind_::combine_flags_opts<SelectArgs...>();
830 constexpr int_sign pref_sign = sign(S, V);
831 constexpr int_sign other_sign = flip(pref_sign);
832 constexpr int_sign value_sign = V < 0 ? SIGNED : UNSIGNED;
833
834 constexpr bool may_be_unsigned =
835 value_sign == UNSIGNED
836 || allow_value_sign_loss(S)
837 ;
838
839 constexpr unsigned value_bits = signed_bitwidth<true>(V);
840 constexpr bool choose_smaller = smallest(S);
841
842 // pref_value is a value which converts to true in boolean context if a
843 // type was found, and whose type (in that case) is the type found.
844 // Otherwise it will be false, and its type will be bool.
845 constexpr auto pref_value =
846 intfind_::find_type<value_bits, pref_sign>();
847 constexpr auto other_value =
848 intfind_::find_type<value_bits, other_sign>();
849
850 using pref_t = decltype(pref_value);
851 using other_t = decltype(other_value);
852
853 constexpr bool pref_valid = pref_value && (std::numeric_limits<pref_t>::is_signed || may_be_unsigned);
854
855 /*
856 * We never treat the sign select option as a mere suggestion unless
857 * allowing a smaller type of the other sign to be chosen.
858 */
859 constexpr bool other_valid = other_value && (std::numeric_limits<other_t>::is_signed || may_be_unsigned) && choose_smaller;
860
861 static_assert(
862 pref_valid || other_valid,
863 "least_required_type could not find a type that satisfies all "
864 "requirements."
865 );
866
867
868 constexpr bool use_pref = [=]() -> bool {
869 // Find out whether to use the found type (if any) of the preferred
870 // sign, or the other one. Usually there will always be a pair of
871 // types of one size available, signed and unsigned, so most of these
872 // cases will not be matched.
873 if constexpr ( ! other_valid ) {
874 // We have a valid type of preferred sign, and no type of other sign.
875 return true;
876 } else if constexpr ( ! pref_valid ) {
877 // No preferred sign available, but the other sign is available.
878 return false;
879 } else if constexpr (
880 choose_smaller && other_valid
881 &&
882 range_result_compare{other_value} < range_result_compare{pref_value}
883 )
884 {
885 // There is a smaller type available that is large enough but not
886 // of the preferred type.
887 return false;
888 } else {
889 // Special cases have been exhausted (probably not really, sorry).
890 return true;
891 }
892 }();
893
894 if constexpr ( use_pref ) {
895 static_assert(
896 pref_valid,
897 "This is Larry's fault."
898 " An earlier static assertion should have failed already."
899 );
900 return static_cast<pref_t>(V);
901 } else {
902 static_assert(
903 other_valid,
904 "This is Larry's fault."
905 " An earlier static assertion should have failed already."
906 );
907 return static_cast<other_t>(V);
908 }
909}
910
911
912
913
914} /* intfind_ (::ugmisc::intfind_) */
916// INTERNAL
917
918
919
920
935template<auto V, auto...S>
936inline constexpr auto as_least_required_int_type =
937 intfind_::as_least_required_type<V, S...>();
938
939
940
941
950template<auto V, auto...S>
952
953
954
955
956} /* ugmisc */
Provides constexpr bit counting functions.
constexpr bitwise_uint_only< T > bitwidth(T) noexcept
Definition bitops.hpp:235
Feature detection.
sign_opt
Definition int_finder.hpp:102
@ SELECT_VALUE_SIGN
Select a signed type iff the value is negative.
Definition int_finder.hpp:108
@ SELECT_TYPE_SIGN
Definition int_finder.hpp:106
typename intfind_::get_exact_int_type< N, S >::type exact_int_type
Definition int_finder.hpp:642
std::enable_if_t< intfind_::find_type< N, S >(), decltype(intfind_::find_type< N, S >()) > least_int_type
Definition int_finder.hpp:735
constexpr bool has_unsigned_type
Definition int_finder.hpp:585
decltype(as_least_required_int_type< V, S... >) least_required_int_type
Definition int_finder.hpp:951
#define UGMISC_INT_FINDER_MAX_INT_WIDTH
Definition int_finder.hpp:404
constexpr bool has_either_int_type
Definition int_finder.hpp:596
sign_flag
Definition int_finder.hpp:156
@ SELECT_SIGN_ALLOW_VALUE_SIGN_LOSS
Definition int_finder.hpp:174
@ SELECT_SIGN_SMALLEST
Definition int_finder.hpp:167
least_int_type< N, UNSIGNED > least_unsigned_type
Definition int_finder.hpp:746
typename intfind_::get_int_types< N >::signed_type exact_signed_type
Definition int_finder.hpp:606
least_int_type< N, SIGNED > least_signed_type
Definition int_finder.hpp:753
typename intfind_::get_int_types< N >::unsigned_type exact_unsigned_type
Definition int_finder.hpp:603
constexpr int_only< T, unsigned > signed_bitwidth(T v)
Definition int_finder.hpp:778
int_sign
Used to select signed or unsigned types.
Definition int_finder.hpp:81
constexpr auto as_least_required_int_type
Definition int_finder.hpp:936
constexpr bool has_int_type
Definition int_finder.hpp:577
constexpr bool has_both_int_types
Definition int_finder.hpp:592
constexpr bool has_signed_type
Definition int_finder.hpp:589
constexpr unsigned max_int_width
Definition int_finder.hpp:411
Macros which declare templates for testing named members of types.
#define UGMISC_MEMBER_TYPE_TEST(NAME)
Definition member.hpp:340
#define UGMISC_QQ(...)
Definition quote.hpp:52
std::enable_if_t< std::numeric_limits< T >::is_integer, R > int_only
Definition sfinae_helpers.hpp:157
Definition int_finder.hpp:422