skullc-peripherals/Peripherals/Inc/peripherals_utility.hpp
Erki 8e96588829
All checks were successful
continuous-integration/drone/push Build is passing
Add zeroInitialized to peripherals utility
2021-06-06 13:11:18 +03:00

73 lines
1.2 KiB
C++

/*
* peripherals_utility.hpp
*
* Created on: Feb 24, 2021
* Author: erki
*/
#ifndef PERIPHERALS_UTILITY_HPP_
#define PERIPHERALS_UTILITY_HPP_
#include <cstdint>
#include <cstring>
#include <type_traits>
namespace Peripherals
{
#define SKULLC_CONCAT_IMPL(x, y) x##y
#define SKULLC_CONCAT(x, y) SKULLC_CONCAT_IMPL(x, y)
#define SKULLC_TAG struct SKULLC_CONCAT(SkullCTag_, __COUNTER__)
template<typename T>
constexpr const T& Clamp(const T& v, const T& lo, const T& hi)
{
if (v > hi)
return hi;
else if (v < lo)
return lo;
else
return v;
}
template<typename T, std::size_t N>
T ByteToTypeBE(const std::uint8_t a[N])
{
T t(0);
for (std::size_t i = 0; i < N; i++)
{
t |= a[i] << (i * 8);
}
return t;
}
template<typename T, std::size_t N>
T ByteToTypeLE(const std::uint8_t a[N])
{
T t(0);
for (std::size_t i = N; i >= 0; i--)
{
t |= a[i] << ((i - 1) * 8);
}
return t;
}
template<typename T>
constexpr T zeroInitialized()
{
static_assert(std::is_trivially_default_constructible<T>::value, "Struct is not trivially default constructible.");
T t;
std::memset(&t, 0, sizeof(T));
return t;
}
}// namespace Peripherals
#endif /* PERIPHERALS_UTILITY_HPP_ */