Skip to content

Commit

Permalink
enhance type safety in buffer_view with SerializableBuffer concept en…
Browse files Browse the repository at this point in the history
…forcement
  • Loading branch information
farukeryilmaz committed Dec 20, 2023
1 parent 971efed commit 846090e
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions include/bytepack/bytepack.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@

namespace bytepack {

template<typename T>
concept SerializableBuffer = std::is_fundamental_v<T>
&& std::is_pointer_v<T> == false && std::is_reference_v<T> == false;

/**
* @class buffer_view
* @brief A mutable class that represents a buffer for holding binary data.
Expand All @@ -42,20 +46,20 @@ namespace bytepack {
*/
class buffer_view {
public:
template<typename T, std::size_t N>
template<typename T, std::size_t N> requires SerializableBuffer<T>
explicit constexpr buffer_view(T(&array)[N]) noexcept
: data_{ array }, size_{ N * sizeof(T) },
ssize_{ to_ssize(N * sizeof(T)) } {}

template<typename T>
template<typename T> requires SerializableBuffer<T>
explicit constexpr buffer_view(T* ptr, std::size_t size) noexcept
: data_{ static_cast<void*>(ptr) }, size_{ size * sizeof(T) },
ssize_{ to_ssize(size * sizeof(T)) } {}

explicit buffer_view(std::string& str) noexcept
: data_{ str.data() }, size_{ str.size() }, ssize_{ to_ssize(str.size()) } {}

template<typename T, std::size_t N>
template<typename T, std::size_t N> requires SerializableBuffer<T>
explicit buffer_view(std::array<T, N>& array) noexcept
: data_{ array.data() }, size_{ N * sizeof(T) },
ssize_{ to_ssize(N * sizeof(T)) } {}
Expand All @@ -70,7 +74,7 @@ namespace bytepack {
* @tparam T The type to which the buffer's data will be cast.
* @return Pointer to the buffer's data cast to the specified type.
*/
template<typename T>
template<typename T> requires SerializableBuffer<T>
[[nodiscard]] constexpr T* as() const noexcept {
return static_cast<T*>(data_);
}
Expand Down

0 comments on commit 846090e

Please sign in to comment.