FastLED 3.9.12
Loading...
Searching...
No Matches
slice.h
1#pragma once
2
3#include <stdint.h>
4#include <stddef.h>
5
6namespace fl {
7
8// Slice<int> is equivalent to int* with a length. It is used to pass around
9// arrays of integers with a length, without needing to pass around a separate
10// length parameter.
11// It works just like an array of objects, but it also knows its length.
12template<typename T>
13class Slice {
14public:
15 Slice() : mData(nullptr), mSize(0) {}
16 Slice(T* data, size_t size) : mData(data), mSize(size) {}
17
18 Slice(const Slice& other) : mData(other.mData), mSize(other.mSize) {}
19
20
21 Slice& operator=(const Slice& other) {
22 mData = other.mData;
23 mSize = other.mSize;
24 return *this;
25 }
26
27 // Automatic promotion to const Slice<const T>
28 operator Slice<const T>() const {
29 return *this;
30 }
31
32 T& operator[](size_t index) {
33 // No bounds checking in embedded environment
34 return mData[index];
35 }
36
37 const T& operator[](size_t index) const {
38 // No bounds checking in embedded environment
39 return mData[index];
40 }
41
42 T* begin() const {
43 return mData;
44 }
45
46 T* end() const {
47 return mData + mSize;
48 }
49
50 size_t length() const {
51 return mSize;
52 }
53
54 const T* data() const {
55 return mData;
56 }
57
58 T* data() {
59 return mData;
60 }
61
62 size_t size() const {
63 return mSize;
64 }
65
66 Slice<T> slice(size_t start, size_t end) const {
67 // No bounds checking in embedded environment
68 return Slice<T>(mData + start, end - start);
69 }
70
71 Slice<T> slice(size_t start) const {
72 // No bounds checking in embedded environment
73 return Slice<T>(mData + start, mSize - start);
74 }
75
76 // Find the first occurrence of a value in the slice
77 // Returns the index of the first occurrence if found, or size_t(-1) if not found
78 size_t find(const T& value) const {
79 for (size_t i = 0; i < mSize; ++i) {
80 if (mData[i] == value) {
81 return i;
82 }
83 }
84 return size_t(-1);
85 }
86
87 bool pop_front() {
88 if (mSize == 0) {
89 return false;
90 }
91 ++mData;
92 --mSize;
93 return true;
94 }
95
96 bool pop_back() {
97 if (mSize == 0) {
98 return false;
99 }
100 --mSize;
101 return true;
102 }
103
104 T& front() {
105 return *mData;
106 }
107
108 const T& front() const {
109 return *mData;
110 }
111
112 T& back() {
113 return *(mData + mSize - 1);
114 }
115
116 const T& back() const {
117 return *(mData + mSize - 1);
118 }
119
120 bool empty() {
121 return mSize == 0;
122 }
123
124private:
125 T* mData;
126 size_t mSize;
127};
128
129} // namespace fl
Implements a simple red square effect for 2D LED grids.
Definition crgb.h:16