From 3b51ecc35beeb0203cbeca0ccc1137984b228359 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Sun, 17 Sep 2023 20:00:31 -0700 Subject: [PATCH] [wpiutil] SpanExtras: Add take_back and take_front (#5651) Also allow sized spans as input (return is always dynamic size). --- .../src/main/native/include/wpi/SpanExtras.h | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/wpiutil/src/main/native/include/wpi/SpanExtras.h b/wpiutil/src/main/native/include/wpi/SpanExtras.h index aa7b9abcf5..790a66f0ea 100644 --- a/wpiutil/src/main/native/include/wpi/SpanExtras.h +++ b/wpiutil/src/main/native/include/wpi/SpanExtras.h @@ -10,19 +10,49 @@ namespace wpi { /// Drop the first \p N elements of the array. -template -constexpr std::span drop_front(std::span in, +template +constexpr std::span drop_front(std::span in, typename std::span::size_type n = 1) { assert(in.size() >= n && "Dropping more elements than exist"); return in.subspan(n, in.size() - n); } /// Drop the last \p N elements of the array. -template -constexpr std::span drop_back(std::span in, +template +constexpr std::span drop_back(std::span in, typename std::span::size_type n = 1) { assert(in.size() >= n && "Dropping more elements than exist"); return in.subspan(0, in.size() - n); } +/** + * Returns a span equal to @p in but with only the first @p n + * elements remaining. If @p n is greater than the length of the + * span, the entire span is returned. + */ +template +constexpr std::span take_front(std::span in, + typename std::span::size_type n = 1) { + auto length = in.size(); + if (n >= length) { + return in; + } + return drop_back(in, length - n); +} + +/** + * Returns a span equal to @p in but with only the last @p n + * elements remaining. If @p n is greater than the length of the + * span, the entire span is returned. + */ +template +constexpr std::span take_back(std::span in, + typename std::span::size_type n = 1) { + auto length = in.size(); + if (n >= length) { + return in; + } + return drop_front(in, length - n); +} + } // namespace wpi