kakoune/src/array_view.hh

70 lines
1.8 KiB
C++
Raw Normal View History

2015-01-06 14:40:56 +01:00
#ifndef array_view_hh_INCLUDED
#define array_view_hh_INCLUDED
#include <vector>
#include <initializer_list>
namespace Kakoune
{
2015-01-06 14:40:56 +01:00
// An ArrayView provides a typed, non owning view of a memory
// range with an interface similar to std::vector.
template<typename T>
2015-01-06 14:40:56 +01:00
class ArrayView
{
public:
2013-04-09 20:05:40 +02:00
using size_t = std::size_t;
2015-01-06 14:40:56 +01:00
ArrayView()
: m_pointer(nullptr), m_size(0) {}
2015-01-06 14:40:56 +01:00
ArrayView(const T& oneval)
: m_pointer(&oneval), m_size(1) {}
2015-01-06 14:40:56 +01:00
ArrayView(const T* pointer, size_t size)
: m_pointer(pointer), m_size(size) {}
2015-01-06 14:40:56 +01:00
ArrayView(const T* begin, const T* end)
: m_pointer(begin), m_size(end - begin) {}
template<typename Iterator>
2015-01-06 14:40:56 +01:00
ArrayView(const Iterator& begin, const Iterator& end)
: m_pointer(&(*begin)), m_size(end - begin) {}
2015-01-09 14:57:21 +01:00
template<typename Alloc>
ArrayView(const std::vector<T, Alloc>& v)
: m_pointer(&v[0]), m_size(v.size()) {}
2015-01-06 14:40:56 +01:00
ArrayView(const std::initializer_list<T>& v)
: m_pointer(v.begin()), m_size(v.size()) {}
const T* pointer() const { return m_pointer; }
size_t size() const { return m_size; }
const T& operator[](size_t n) const { return *(m_pointer + n); }
const T* begin() const { return m_pointer; }
const T* end() const { return m_pointer+m_size; }
using reverse_iterator = std::reverse_iterator<const T*>;
reverse_iterator rbegin() const { return reverse_iterator(m_pointer+m_size); }
reverse_iterator rend() const { return reverse_iterator(m_pointer); }
const T& front() const { return *m_pointer; }
const T& back() const { return *(m_pointer + m_size - 1); }
bool empty() const { return m_size == 0; }
2015-01-06 14:40:56 +01:00
ArrayView subrange(size_t first, size_t count) const
{
2015-01-06 14:40:56 +01:00
return ArrayView(m_pointer + first, count);
}
private:
const T* m_pointer;
size_t m_size;
};
}
2015-01-06 14:40:56 +01:00
#endif // array_view_hh_INCLUDED