WPILibC++ 2024.3.2
SpanExtras.h
Go to the documentation of this file.
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5#pragma once
6
7#include <cassert>
8#include <span>
9
10namespace wpi {
11
12/// Drop the first \p N elements of the array.
13template <typename T, size_t N>
14constexpr std::span<T> drop_front(std::span<T, N> in,
15 typename std::span<T>::size_type n = 1) {
16 assert(in.size() >= n && "Dropping more elements than exist");
17 return in.subspan(n, in.size() - n);
18}
19
20/// Drop the last \p N elements of the array.
21template <typename T, size_t N>
22constexpr std::span<T> drop_back(std::span<T, N> in,
23 typename std::span<T>::size_type n = 1) {
24 assert(in.size() >= n && "Dropping more elements than exist");
25 return in.subspan(0, in.size() - n);
26}
27
28/**
29 * Returns a span equal to @p in but with only the first @p n
30 * elements remaining. If @p n is greater than the length of the
31 * span, the entire span is returned.
32 */
33template <typename T, size_t N>
34constexpr std::span<T> take_front(std::span<T, N> in,
35 typename std::span<T>::size_type n = 1) {
36 auto length = in.size();
37 if (n >= length) {
38 return in;
39 }
40 return drop_back(in, length - n);
41}
42
43/**
44 * Returns a span equal to @p in but with only the last @p n
45 * elements remaining. If @p n is greater than the length of the
46 * span, the entire span is returned.
47 */
48template <typename T, size_t N>
49constexpr std::span<T> take_back(std::span<T, N> in,
50 typename std::span<T>::size_type n = 1) {
51 auto length = in.size();
52 if (n >= length) {
53 return in;
54 }
55 return drop_front(in, length - n);
56}
57
58} // namespace wpi
constexpr auto in(type t, int set) -> bool
Definition: core.h:611
Definition: ntcore_cpp.h:26
constexpr std::span< T > drop_back(std::span< T, N > in, typename std::span< T >::size_type n=1)
Drop the last N elements of the array.
Definition: SpanExtras.h:22
constexpr std::span< T > drop_front(std::span< T, N > in, typename std::span< T >::size_type n=1)
Drop the first N elements of the array.
Definition: SpanExtras.h:14
constexpr std::span< T > take_front(std::span< T, N > in, typename std::span< T >::size_type n=1)
Returns a span equal to in but with only the first n elements remaining.
Definition: SpanExtras.h:34
constexpr std::span< T > take_back(std::span< T, N > in, typename std::span< T >::size_type n=1)
Returns a span equal to in but with only the last n elements remaining.
Definition: SpanExtras.h:49