nros C++ API
Lightweight ROS 2 client for embedded real-time systems (C++ headers)
Loading...
Searching...
No Matches
fixed_string.hpp
Go to the documentation of this file.
1// nros-cpp: FixedString — fixed-capacity null-terminated string
2// Freestanding C++14 — no exceptions, no STL required
3//
4// Memory layout is repr(C) compatible: identical to char[N].
5// Used by codegen-generated message structs for string fields.
6
13#ifndef NROS_CPP_FIXED_STRING_HPP
14#define NROS_CPP_FIXED_STRING_HPP
15
16#include <cstddef>
17#include <string.h>
18
19namespace nros {
20
33template <size_t N> struct FixedString {
34 char data[N];
35
37 FixedString() { data[0] = '\0'; }
38
40 FixedString& operator=(const char* s) {
41 if (s == nullptr) {
42 data[0] = '\0';
43 return *this;
44 }
45 size_t i = 0;
46 for (; i < N - 1 && s[i] != '\0'; ++i) {
47 data[i] = s[i];
48 }
49 data[i] = '\0';
50 return *this;
51 }
52
54 const char* c_str() const { return data; }
55
57 size_t length() const {
58 size_t len = 0;
59 while (len < N && data[len] != '\0')
60 ++len;
61 return len;
62 }
63
65 static constexpr size_t capacity() { return N - 1; }
66
68 bool operator==(const char* s) const {
69 if (s == nullptr) return data[0] == '\0';
70 return strncmp(data, s, N) == 0;
71 }
72
73 bool operator!=(const char* s) const { return !(*this == s); }
74};
75
76} // namespace nros
77
78#endif // NROS_CPP_FIXED_STRING_HPP
Definition future.hpp:40
Definition nros.hpp:42
Definition fixed_string.hpp:33
FixedString & operator=(const char *s)
Assign from a C string. Truncates if longer than capacity.
Definition fixed_string.hpp:40
const char * c_str() const
Get a pointer to the null-terminated string.
Definition fixed_string.hpp:54
char data[N]
Definition fixed_string.hpp:34
bool operator==(const char *s) const
Compare with a C string.
Definition fixed_string.hpp:68
FixedString()
Default constructor — empty string.
Definition fixed_string.hpp:37
static constexpr size_t capacity()
Maximum number of characters (excluding null terminator).
Definition fixed_string.hpp:65
size_t length() const
Get the length of the string (up to N-1).
Definition fixed_string.hpp:57
bool operator!=(const char *s) const
Definition fixed_string.hpp:73