Skip to content

Commit 9172252

Browse files
committed
Slice
1 parent 8b5a7e4 commit 9172252

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

src/AudioBasic/Collections/Slice.h

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#pragma once
2+
#include <stddef.h>
3+
#include <stdint.h>
4+
5+
namespace audio_tools {
6+
7+
/**
8+
* @brief Helps to split up a big memory array into smaller slices. There are no
9+
* additinal heap allocations!
10+
* @ingroup collections
11+
* @author Phil Schatzmann
12+
*/
13+
template <class T>
14+
class Slice {
15+
public:
16+
Slice(T* start, size_t len) {
17+
this->start = start;
18+
this->len = len;
19+
}
20+
21+
/// Returns the data
22+
T* data() { return start; }
23+
24+
/// Returns the (result) data size in bytes
25+
size_t size() { return len; }
26+
27+
/// Returns the number of slices
28+
size_t slices(int sliceSize){
29+
int result = len / sliceSize;
30+
return len % sliceSize == 0 ? result : result+1;
31+
}
32+
33+
operator bool() { return len > 0; }
34+
35+
/// Returns the slice at the indicated index;
36+
Slice slice(int sliceSize, int idx) {
37+
int start_pos = idx * sliceSize;
38+
int end_pos = start_pos + sliceSize;
39+
if (end_pos > len) {
40+
end_pos = len;
41+
}
42+
43+
if (start_pos < len) {
44+
assert(start!=nullptr);
45+
return Slice(start + start_pos, end_pos - start_pos);
46+
} else {
47+
return Slice(nullptr, 0);
48+
}
49+
}
50+
51+
protected:
52+
T* start = nullptr;
53+
size_t len = 0;
54+
};
55+
56+
} // namespace audio_tools

0 commit comments

Comments
 (0)