| 1 |
// Copyright (c) the JPEG XL Project Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Use of this source code is governed by a BSD-style |
| 4 |
// license that can be found in the LICENSE file. |
| 5 |
|
| 6 |
#ifndef LIB_JXL_BASE_SPAN_H_ |
| 7 |
#define LIB_JXL_BASE_SPAN_H_ |
| 8 |
|
| 9 |
// Span (array view) is a non-owning container that provides cheap "cut" |
| 10 |
// operations and could be used as "ArrayLike" data source for PaddedBytes. |
| 11 |
|
| 12 |
#include <cstddef> |
| 13 |
#include <cstdint> |
| 14 |
#include <type_traits> |
| 15 |
#include <vector> |
| 16 |
|
| 17 |
#include "lib/jxl/base/status.h" |
| 18 |
|
| 19 |
namespace jxl { |
| 20 |
|
| 21 |
template <typename T> |
| 22 |
class Span { |
| 23 |
public: |
| 24 |
constexpr Span() noexcept : Span(nullptr, 0) {} |
| 25 |
|
| 26 |
constexpr Span(T* array, size_t length) noexcept |
| 27 |
: ptr_(array), len_(length) {} |
| 28 |
|
| 29 |
template <size_t N> |
| 30 |
explicit constexpr Span(T (&a)[N]) noexcept : Span(a, N) {} |
| 31 |
|
| 32 |
template <typename U> |
| 33 |
constexpr Span(U* array, size_t length) noexcept |
| 34 |
: ptr_(reinterpret_cast<T*>(array)), len_(length) { |
| 35 |
static_assert(sizeof(U) == sizeof(T), "Incompatible type of source."); |
| 36 |
} |
| 37 |
|
| 38 |
template <typename ArrayLike> |
| 39 |
explicit constexpr Span(const ArrayLike& other) noexcept |
| 40 |
: Span(reinterpret_cast<T*>(other.data()), other.size()) { |
| 41 |
static_assert(sizeof(*other.data()) == sizeof(T), |
| 42 |
"Incompatible type of source."); |
| 43 |
} |
| 44 |
|
| 45 |
using NCT = typename std::remove_const<T>::type; |
| 46 |
|
| 47 |
constexpr T* data() const noexcept { return ptr_; } |
| 48 |
|
| 49 |
constexpr size_t size() const noexcept { return len_; } |
| 50 |
|
| 51 |
constexpr bool empty() const noexcept { return len_ == 0; } |
| 52 |
|
| 53 |
constexpr T* begin() const noexcept { return data(); } |
| 54 |
|
| 55 |
constexpr T* end() const noexcept { return data() + size(); } |
| 56 |
|
| 57 |
constexpr T& operator[](size_t i) const noexcept { |
| 58 |
// MSVC 2015 accepts this as constexpr, but not ptr_[i] |
| 59 |
return *(data() + i); |
| 60 |
} |
| 61 |
|
| 62 |
Status remove_prefix(size_t n) noexcept { |
| 63 |
JXL_ENSURE(size() >= n); |
| 64 |
ptr_ += n; |
| 65 |
len_ -= n; |
| 66 |
return true; |
| 67 |
} |
| 68 |
|
| 69 |
void AppendTo(std::vector<NCT>& dst) const { |
| 70 |
dst.insert(dst.end(), begin(), end()); |
| 71 |
} |
| 72 |
|
| 73 |
std::vector<NCT> Copy() const { return std::vector<NCT>(begin(), end()); } |
| 74 |
|
| 75 |
private: |
| 76 |
T* ptr_; |
| 77 |
size_t len_; |
| 78 |
}; |
| 79 |
|
| 80 |
typedef Span<const uint8_t> Bytes; |
| 81 |
|
| 82 |
} // namespace jxl |
| 83 |
|
| 84 |
#endif // LIB_JXL_BASE_SPAN_H_ |