source: cpp/common/nonstd_span.h @ 1340

Last change on this file since 1340 was 1340, checked in by Maciej Komosinski, 39 hours ago

Added helper functions

File size: 1.8 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 2019-2024  Maciej Komosinski and Szymon Ulatowski.
3// See LICENSE.txt for details.
4
5#ifndef _NONSTD_SPAN_H_
6#define _NONSTD_SPAN_H_
7
8#include <string>
9#include <vector>
10
11// Remove this and use std::span when available (c++20)
12
13template<class ElementType> class span
14{
15public:
16        constexpr span() noexcept
17        {
18                data_ = NULL;
19                size_ = 0;
20        }
21        constexpr span(ElementType* first, size_t count) noexcept
22        {
23                data_ = first;
24                size_ = count;
25        }
26        constexpr span(ElementType* first, ElementType* end) noexcept
27        {
28                data_ = first;
29                size_ = end - first;
30        }
31        template<size_t N> constexpr span(ElementType(&arr)[N]) noexcept
32        {
33                data_ = arr;
34                size_ = N;
35        }
36
37        size_t size() const { return size_; }
38        size_t size_bytes() const { return size_ * sizeof(ElementType); }
39        ElementType& operator[](size_t idx) const { return data_[idx]; }
40
41        ElementType* begin() const { return data_; }
42        ElementType* end() const { return data_ + size_; }
43
44protected:
45        ElementType* data_;
46        size_t size_;
47};
48
49inline std::string stringFromSpan(const span<uint8_t>& s) { return std::string(s.begin(), s.end()); }
50inline std::string stringFromSpan(const span<char>& s) { return std::string(s.begin(), s.end()); }
51// in both lines below, in the last argument, &*v.end() was replaced by front+size, because the debugging+extensive checking version of the STL library with std::vector complained when calling &*v.end().
52inline span<uint8_t> spanFromVector(std::vector<uint8_t>& v) { return span<uint8_t>(&v.front(), ((uint8_t*)&v.front())+v.size()); }
53inline span<uint8_t> spanFromVector(std::vector<char>& v) { return span<uint8_t>((uint8_t*)&v.front(), ((uint8_t*)&v.front())+v.size()); }
54
55#endif
Note: See TracBrowser for help on using the repository browser.