From 854752ec0dc10277fa59531a3f3849817ddda0a0 Mon Sep 17 00:00:00 2001 From: ChUrl Date: Sun, 24 Jul 2022 21:49:38 +0200 Subject: [PATCH] primitive span implementation --- c_os/user/lib/Span.h | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 c_os/user/lib/Span.h diff --git a/c_os/user/lib/Span.h b/c_os/user/lib/Span.h new file mode 100644 index 0000000..33ef319 --- /dev/null +++ b/c_os/user/lib/Span.h @@ -0,0 +1,61 @@ +#ifndef SPAN_INCLUDE_H +#define SPAN_INCLUDE_H + +#include "user/lib/Iterator.h" +#include + +namespace bse { + + // 0 is unchecked + template + class span { + public: + using iterator = ContinuousIterator; + + private: + const T* ptr; + std::size_t sz = N; + + public: + span() = default; + + span(const T* first) : ptr(first) {} + + span(const T* first, const T* last) : ptr(first), sz(last - first) {} + + iterator begin() { return iterator(&ptr[0]); } + iterator begin() const { return iterator(&ptr[0]); } + // If size is unchecked end() is equal to begin() + iterator end() { return iterator(&ptr[N]); } + iterator end() const { return iterator(&ptr[N]); } + + constexpr T& operator[](std::size_t i) { + if constexpr (N != 0 && i >= N) { + return nullptr; + } + return ptr[i]; + } + + constexpr const T& operator[](std::size_t i) const { + if constexpr (N != 0 && i >= N) { + return nullptr; + } + return ptr[i]; + } + + T* data() { return &ptr[0]; } + const T* data() const { return &ptr[0]; } + + // First is inclusive, last exclusive [first, last) + span& subspan(std::size_t first, std::size_t last = N) { + return span(ptr + first, ptr + last - 1); + } + + std::size_t size() const { + return sz; + } + }; + +} // namespace bse + +#endif