Phosphor
span.h
1 /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
2 /*
3  * Copyright 2017 Couchbase, Inc
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #include <iostream>
19 #include <type_traits>
20 
21 #include <phosphor/platform/core.h>
22 
23 namespace gsl_p {
24 
28 template <typename T>
29 class span {
30 public:
31  constexpr span() = default;
32 
33  constexpr span(T* _d, size_t _s)
34  : _data(_d),
35  _size(_s) {
36  }
37 
38  constexpr T* data() const {
39  return _data;
40  }
41 
42  constexpr size_t size() const {
43  return _size;
44  }
45 
46  constexpr T* begin() const {
47  return _data;
48  }
49 
50  constexpr T* end() const {
51  return _data + _size;
52  }
53 
54  int compare(span v) const {
55  const size_t rlen = std::min(size(), v.size());
56  const int cmp =
57  std::char_traits<T>::compare(data(), v.data(), rlen);
58 
59  if (cmp != 0) {
60  return cmp;
61  } else if (size() < v.size()) {
62  return -1;
63  } else if (size() > v.size()) {
64  return 1;
65  } else {
66  return 0;
67  }
68  }
69 
70 private:
71  T* _data;
72  size_t _size;
73 };
74 
75 template <class CharT>
76 bool operator==(span<CharT> lhs, span<CharT> rhs) {
77  return lhs.compare(rhs) == 0;
78 }
79 
86 template <typename T, size_t N>
87 constexpr span<T> make_span(T (&s)[N]) {
88  return {s, N};
89 }
90 
96 template <size_t N>
97 constexpr span<const char> make_span(const char (&s)[N]) {
98  return {s, N - 1};
99 }
100 
101 using string_span = span<char>;
103 
104 inline std::ostream& operator<<(std::ostream& os, const gsl_p::cstring_span& s) {
105  return os.write(s.data(), s.size());
106 }
107 }
Definition: dyn_array.h:337
Definition: span.h:29
constexpr span< T > make_span(T(&s)[N])
Definition: span.h:87