FastLED 3.9.15
Loading...
Searching...
No Matches
bit_cast.h
Go to the documentation of this file.
1#pragma once
2
3// What is bit cast?
4// Bit cast is a safe version of reinterpret_cast that is robust against strict aliasing rules
5// that are used in aggressive compiler optimizations.
6
7#include "fl/type_traits.h"
8#include "fl/int.h"
9
10namespace fl {
11
12//-------------------------------------------------------------------------------
13// bit_cast - Safe type-punning utility (C++20 std::bit_cast equivalent)
14//-------------------------------------------------------------------------------
15
16// Helper trait for bitcast - check if a type can be bitcast (relax POD requirement)
17template <typename T>
23
24// Specializations for const types
25template <typename T>
26struct is_bitcast_compatible<const T> {
27 static constexpr bool value = is_bitcast_compatible<T>::value;
28};
29
30// Specializations for pointer types
31template <typename T>
33 static constexpr bool value = true;
34};
35
36// C++20-style bit_cast for safe type reinterpretation
37// Uses union for zero-cost type punning - compiler optimizes to direct assignment
38template <typename To, typename From>
39To bit_cast(const From& from) noexcept {
40 static_assert(sizeof(To) == sizeof(From), "bit_cast: types must have the same size");
41 static_assert(is_bitcast_compatible<To>::value, "bit_cast: destination type must be bitcast compatible");
42 static_assert(is_bitcast_compatible<From>::value, "bit_cast: source type must be bitcast compatible");
43
44 union { // robust against strict aliasing rules
45 From from_val;
46 To to_val;
47 } u;
48 u.from_val = from;
49 return u.to_val;
50}
51
52// Overload for pointer types - converts storage pointer to typed pointer safely
53template <typename To>
54To* bit_cast_ptr(void* storage) noexcept {
55 return bit_cast<To*>(storage);
56}
57
58template <typename To>
59const To* bit_cast_ptr(const void* storage) noexcept {
60 return bit_cast<const To*>(storage);
61}
62
63// Additional utility for uptr conversions (common pattern in the codebase)
64template <typename T>
65uptr ptr_to_int(T* ptr) noexcept {
66 return bit_cast<uptr>(ptr);
67}
68
69template <typename T>
70T* int_to_ptr(uptr value) noexcept {
71 return bit_cast<T*>(value);
72}
73
74} // namespace fl
uptr ptr_to_int(T *ptr) noexcept
Definition bit_cast.h:65
To * bit_cast_ptr(void *storage) noexcept
Definition bit_cast.h:54
To bit_cast(const From &from) noexcept
Definition bit_cast.h:39
T * int_to_ptr(uptr value) noexcept
Definition bit_cast.h:70
IMPORTANT!
Definition crgb.h:20
static constexpr bool value
Definition bit_cast.h:33
static constexpr bool value
Definition bit_cast.h:27
static constexpr bool value
Definition bit_cast.h:19
static constexpr bool value
static constexpr bool value
static constexpr bool value