source: cpp/common/nonstd_span.h @ 1346

Last change on this file since 1346 was 1346, checked in by Maciej Komosinski, 9 days ago

Added compatibility with MinGW compiler

File size: 1.8 KB
Line 
1// This file is a part of Framsticks SDK.  http://www.framsticks.com/
2// Copyright (C) 2019-2025  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#include <cstdint> // uint8_t
11
12// Remove this and use std::span when available (c++20)
13
14template<class ElementType> class span
15{
16public:
17        constexpr span() noexcept
18        {
19                data_ = NULL;
20                size_ = 0;
21        }
22        constexpr span(ElementType* first, size_t count) noexcept
23        {
24                data_ = first;
25                size_ = count;
26        }
27        constexpr span(ElementType* first, ElementType* end) noexcept
28        {
29                data_ = first;
30                size_ = end - first;
31        }
32        template<size_t N> constexpr span(ElementType(&arr)[N]) noexcept
33        {
34                data_ = arr;
35                size_ = N;
36        }
37
38        size_t size() const { return size_; }
39        size_t size_bytes() const { return size_ * sizeof(ElementType); }
40        ElementType& operator[](size_t idx) const { return data_[idx]; }
41
42        ElementType* begin() const { return data_; }
43        ElementType* end() const { return data_ + size_; }
44
45protected:
46        ElementType* data_;
47        size_t size_;
48};
49
50inline std::string stringFromSpan(const span<uint8_t>& s) { return std::string(s.begin(), s.end()); }
51inline std::string stringFromSpan(const span<char>& s) { return std::string(s.begin(), s.end()); }
52// 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().
53inline span<uint8_t> spanFromVector(std::vector<uint8_t>& v) { return span<uint8_t>(&v.front(), ((uint8_t*)&v.front())+v.size()); }
54inline span<uint8_t> spanFromVector(std::vector<char>& v) { return span<uint8_t>((uint8_t*)&v.front(), ((uint8_t*)&v.front())+v.size()); }
55
56#endif
Note: See TracBrowser for help on using the repository browser.