about summary refs log tree commit diff
path: root/absl/types/span.h
diff options
context:
space:
mode:
authorGirts <girtsf@users.noreply.github.com>2019-03-08T20·05-0800
committerDerek Mauro <761129+derekmauro@users.noreply.github.com>2019-03-08T20·05-0500
commitc1cecb25a94c075725e9d2640f6b978a8f61957b (patch)
tree505c35368522ebe4e6717b73f6c24e1279c5c173 /absl/types/span.h
parent38b704384cd2f17590b3922b97744be0b43622c9 (diff)
Implement Span::first and Span::last from C++20 (#274)
This implements `first` and `last` methods on `Span` that mimics
ones in `std::span`.
Diffstat (limited to 'absl/types/span.h')
-rw-r--r--absl/types/span.h34
1 files changed, 34 insertions, 0 deletions
diff --git a/absl/types/span.h b/absl/types/span.h
index bce18ebcb8..ea1808d3ba 100644
--- a/absl/types/span.h
+++ b/absl/types/span.h
@@ -485,6 +485,40 @@ class Span {
                : (base_internal::ThrowStdOutOfRange("pos > size()"), Span());
   }
 
+  // Span::first()
+  //
+  // Returns a `Span` containing first `len` elements. Parameter `len` is of
+  // type `size_type` and thus non-negative. `len` value must be <= size().
+  //
+  // Examples:
+  //
+  //   std::vector<int> vec = {10, 11, 12, 13};
+  //   absl::MakeSpan(vec).first(1);  // {10}
+  //   absl::MakeSpan(vec).first(3);  // {10, 11, 12}
+  //   absl::MakeSpan(vec).first(5);  // throws std::out_of_range
+  constexpr Span first(size_type len) const {
+    return (len <= size())
+               ? Span(data(), len)
+               : (base_internal::ThrowStdOutOfRange("len > size()"), Span());
+  }
+
+  // Span::last()
+  //
+  // Returns a `Span` containing last `len` elements. Parameter `len` is of
+  // type `size_type` and thus non-negative. `len` value must be <= size().
+  //
+  // Examples:
+  //
+  //   std::vector<int> vec = {10, 11, 12, 13};
+  //   absl::MakeSpan(vec).last(1);  // {13}
+  //   absl::MakeSpan(vec).last(3);  // {11, 12, 13}
+  //   absl::MakeSpan(vec).last(5);  // throws std::out_of_range
+  constexpr Span last(size_type len) const {
+    return (len <= size())
+               ? Span(data() + size() - len, len)
+               : (base_internal::ThrowStdOutOfRange("len > size()"), Span());
+  }
+
   // Support for absl::Hash.
   template <typename H>
   friend H AbslHashValue(H h, Span v) {