You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
1.4 KiB
62 lines
1.4 KiB
4 years ago
|
#ifndef _REINTERPRET_H
|
||
|
#define _REINTERPRET_H
|
||
|
|
||
|
#include <panic.h>
|
||
|
|
||
4 years ago
|
#ifdef __cplusplus
|
||
|
#define restrict __restrict__
|
||
|
#include <cstddef>
|
||
|
#include <cstdint>
|
||
|
#else
|
||
|
#include <stddef.h>
|
||
|
#include <stdint.h>
|
||
|
#endif
|
||
|
|
||
4 years ago
|
#ifdef __cplusplus
|
||
|
template<typename T>
|
||
|
struct span {
|
||
|
inline span(T* ptr, std::size_t len) : ptr(ptr), len(len) {}
|
||
|
|
||
|
template<typename U>
|
||
|
inline span<U> reinterpret() const
|
||
|
{
|
||
|
auto bytes = size_bytes();
|
||
|
//if (len_b % sizeof(U) != 0) panic("Cannot reinterpret T to U due to unmatch sizing constraints.");
|
||
|
|
||
4 years ago
|
return span<U>((U*)ptr, bytes / sizeof(U));
|
||
4 years ago
|
}
|
||
|
|
||
4 years ago
|
inline const T& operator[](std::size_t i) const
|
||
4 years ago
|
{
|
||
4 years ago
|
if (i >= len) panic("Out of bounds access: %lu >= %lu", i, len);
|
||
4 years ago
|
return ptr[i];
|
||
|
}
|
||
4 years ago
|
inline T& operator[](std::size_t i)
|
||
4 years ago
|
{
|
||
4 years ago
|
if (i >= len) panic("Out of bounds access: %lu >= %lu", i, len);
|
||
4 years ago
|
return ptr[i];
|
||
|
}
|
||
|
|
||
|
inline const T* as_ptr() const { return ptr; }
|
||
|
inline T* as_ptr() { return ptr; }
|
||
|
|
||
|
inline const T* operator&() const { return as_ptr(); }
|
||
|
inline T* operator&() { return as_ptr(); }
|
||
|
|
||
|
inline std::size_t size_bytes() const { return len * sizeof(T); }
|
||
|
inline std::size_t size() const { return len; }
|
||
|
private:
|
||
|
T* const ptr;
|
||
|
const std::size_t len;
|
||
|
};
|
||
|
|
||
|
extern "C" {
|
||
|
#endif
|
||
4 years ago
|
uint64_t* bytes_to_long(uint8_t* ptr, size_t ptr_sz, size_t* restrict nsize);
|
||
4 years ago
|
float* bytes_to_float(uint8_t* ptr, size_t ptr_sz, size_t* restrict nsize);
|
||
|
#ifdef __cplusplus
|
||
|
}
|
||
|
#endif
|
||
|
|
||
|
#endif /* _REINTERPRET_H */
|