1 // Copyright 2020 The Dawn Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef COMMON_ITYP_SPAN_H_ 16 #define COMMON_ITYP_SPAN_H_ 17 18 #include "common/TypedInteger.h" 19 #include "common/UnderlyingType.h" 20 21 #include <type_traits> 22 23 namespace ityp { 24 25 // ityp::span is a helper class that wraps an unowned packed array of type |Value|. 26 // It stores the size and pointer to first element. It has the restriction that 27 // indices must be a particular type |Index|. This provides a type-safe way to index 28 // raw pointers. 29 template <typename Index, typename Value> 30 class span { 31 using I = UnderlyingType<Index>; 32 33 public: span()34 constexpr span() : mData(nullptr), mSize(0) { 35 } span(Value * data,Index size)36 constexpr span(Value* data, Index size) : mData(data), mSize(size) { 37 } 38 39 constexpr Value& operator[](Index i) const { 40 ASSERT(i < mSize); 41 return mData[static_cast<I>(i)]; 42 } 43 data()44 Value* data() noexcept { 45 return mData; 46 } 47 data()48 const Value* data() const noexcept { 49 return mData; 50 } 51 begin()52 Value* begin() noexcept { 53 return mData; 54 } 55 begin()56 const Value* begin() const noexcept { 57 return mData; 58 } 59 end()60 Value* end() noexcept { 61 return mData + static_cast<I>(mSize); 62 } 63 end()64 const Value* end() const noexcept { 65 return mData + static_cast<I>(mSize); 66 } 67 front()68 Value& front() { 69 ASSERT(mData != nullptr); 70 ASSERT(static_cast<I>(mSize) >= 0); 71 return *mData; 72 } 73 front()74 const Value& front() const { 75 ASSERT(mData != nullptr); 76 ASSERT(static_cast<I>(mSize) >= 0); 77 return *mData; 78 } 79 back()80 Value& back() { 81 ASSERT(mData != nullptr); 82 ASSERT(static_cast<I>(mSize) >= 0); 83 return *(mData + static_cast<I>(mSize) - 1); 84 } 85 back()86 const Value& back() const { 87 ASSERT(mData != nullptr); 88 ASSERT(static_cast<I>(mSize) >= 0); 89 return *(mData + static_cast<I>(mSize) - 1); 90 } 91 size()92 Index size() const { 93 return mSize; 94 } 95 96 private: 97 Value* mData; 98 Index mSize; 99 }; 100 101 } // namespace ityp 102 103 #endif // COMMON_ITYP_SPAN_H_ 104