Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
revoxhere
GitHub Repository: revoxhere/duino-coin
Path: blob/master/ESP_Code/Counter.h
925 views
1
#ifndef _COUNTER_H_
2
#define _COUNTER_H_
3
4
#include <Arduino.h>
5
#include <string.h>
6
7
template <unsigned int max_digits>
8
class Counter {
9
10
public:
11
Counter() { reset(); }
12
13
void reset() {
14
memset(buffer, '0', max_digits);
15
buffer[max_digits] = '\0';
16
val = 0;
17
len = 1;
18
}
19
20
inline Counter &operator++() {
21
inc_string(buffer + max_digits - 1);
22
++val;
23
return *this;
24
}
25
26
inline operator unsigned int() const { return val; }
27
inline const char *c_str() const { return buffer + max_digits - len; }
28
inline size_t strlen() const { return len; }
29
30
protected:
31
inline void inc_string(char *c) {
32
// In theory, the line below should be uncommented to avoid writing outside the buffer. In practice however,
33
// with max_digits set to 10 or more, we can fit all possible unsigned 32-bit integers in the buffer.
34
// The check is skipped to gain a small extra speed improvement.
35
// if (c >= buffer) return;
36
37
if (*c < '9') {
38
*c += 1;
39
}
40
else {
41
*c = '0';
42
inc_string(c - 1);
43
len = max(max_digits - (c - buffer) + 1, len);
44
}
45
}
46
47
protected:
48
char buffer[max_digits + 1];
49
unsigned int val;
50
size_t len;
51
};
52
53
#endif
54
55