• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2018 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkSpan_DEFINED
9 #define SkSpan_DEFINED
10 
11 #include <cstddef>
12 #include <string>
13 #include <vector>
14 
15 #include "include/private/SkTo.h"
16 
17 template <typename T>
18 class SkSpan {
19 public:
SkSpan()20     constexpr SkSpan() : fPtr{nullptr}, fSize{0} {}
SkSpan(T * ptr,size_t size)21     constexpr SkSpan(T* ptr, size_t size) : fPtr{ptr}, fSize{size} {}
22     template <typename U, typename = typename std::enable_if<std::is_same<const U, T>::value>::type>
SkSpan(const SkSpan<U> & that)23     constexpr SkSpan(const SkSpan<U>& that) : fPtr(that.data()), fSize{that.size()} {}
24     constexpr SkSpan(const SkSpan& o) = default;
25     constexpr SkSpan& operator=(const SkSpan& that) {
26         fPtr = that.fPtr;
27         fSize = that.fSize;
28         return *this;
29     }
30     constexpr T& operator [] (size_t i) const { return fPtr[i]; }
front()31     constexpr T& front() const { return fPtr[0]; }
back()32     constexpr T& back()  const { return fPtr[fSize - 1]; }
begin()33     constexpr T* begin() const { return fPtr; }
end()34     constexpr T* end() const { return fPtr + fSize; }
cbegin()35     constexpr const T* cbegin() const { return fPtr; }
cend()36     constexpr const T* cend() const { return fPtr + fSize; }
data()37     constexpr T* data() const { return fPtr; }
size()38     constexpr size_t size() const { return fSize; }
empty()39     constexpr bool empty() const { return fSize == 0; }
size_bytes()40     constexpr size_t size_bytes() const { return fSize * sizeof(T); }
first(size_t prefixLen)41     constexpr SkSpan<T> first(size_t prefixLen) { return SkSpan<T>{fPtr, prefixLen}; }
42 
43 private:
44     T* fPtr;
45     size_t fSize;
46 };
47 
48 template <typename T, typename S>
SkMakeSpan(T * p,S s)49 inline constexpr SkSpan<T> SkMakeSpan(T* p, S s) { return SkSpan<T>{p, SkTo<size_t>(s)}; }
50 
51 template <size_t N, typename T>
SkMakeSpan(T (& a)[N])52 inline constexpr SkSpan<T> SkMakeSpan(T(&a)[N]) { return SkSpan<T>{a, N}; }
53 
54 template <typename Container>
55 inline auto SkMakeSpan(Container& c)
56         -> SkSpan<typename std::remove_reference<decltype(*(c.data()))>::type> {
57     return {c.data(), c.size()};
58 }
59 #endif  // SkSpan_DEFINED
60