FastLED 3.9.3
Loading...
Searching...
No Matches
str.cpp
1#include <stdlib.h>
2
3#include "str.h"
4#include "namespace.h"
5
6
7FASTLED_NAMESPACE_BEGIN
8
9namespace string_functions {
10// Yet, another good itoa implementation
11// returns: the length of the number string
12int itoa(int value, char *sp, int radix) {
13 char tmp[16]; // be careful with the length of the buffer
14 char *tp = tmp;
15 int i;
16 unsigned v;
17
18 int sign = (radix == 10 && value < 0);
19 if (sign)
20 v = -value;
21 else
22 v = (unsigned)value;
23
24 while (v || tp == tmp) {
25 i = v % radix;
26 v /= radix;
27 if (i < 10)
28 *tp++ = i + '0';
29 else
30 *tp++ = i + 'a' - 10;
31 }
32
33 int len = tp - tmp;
34
35 if (sign) {
36 *sp++ = '-';
37 len++;
38 }
39
40 while (tp > tmp)
41 *sp++ = *--tp;
42
43 return len;
44}
45
46} // namespace string_functions
47
48void StringFormatter::append(int val, StrN<64> *dst) {
49 char buf[63];
50 string_functions::itoa(val, buf, 63);
51 dst->append(buf);
52}
53
54StringHolder::StringHolder(const char *str) {
55 mLength = strlen(str);
56 mData = (char *)malloc(mLength + 1);
57 if (mData) {
58 memcpy(mData, str, mLength + 1);
59 } else {
60 mLength = 0;
61 }
62 mCapacity = mLength;
63}
64
65StringHolder::StringHolder(size_t length) {
66 mData = (char *)malloc(length + 1);
67 if (mData) {
68 mLength = length;
69 mData[mLength] = '\0';
70 } else {
71 mLength = 0;
72 }
73 mCapacity = mLength;
74}
75
76StringHolder::~StringHolder() {
77 free(mData); // Release the memory
78}
79
80void StringHolder::grow(size_t newLength) {
81 if (newLength <= mCapacity) {
82 // New length must be greater than current length
83 mLength = newLength;
84 return;
85 }
86 char *newData = (char *)realloc(mData, newLength + 1);
87 if (newData) {
88 mData = newData;
89 mLength = newLength;
90 mCapacity = newLength;
91 mData[mLength] = '\0'; // Ensure null-termination
92 } else {
93 // handle re-allocation failure.
94 char *newData = (char *)malloc(newLength + 1);
95 if (newData) {
96 memcpy(newData, mData, mLength + 1);
97 free(mData);
98 mData = newData;
99 mLength = newLength;
100 mCapacity = mLength;
101 } else {
102 // memory failure.
103 }
104 }
105}
106
107FASTLED_NAMESPACE_END
Definition str.h:69