common: Add more null checks in CString.

Co-authored-by: Vinicius Rangel <me@viniciusrangel.dev>
This commit is contained in:
squidbus 2024-09-20 15:53:34 -07:00
parent 397c511c1d
commit fecd596e81

View file

@ -9,6 +9,9 @@
namespace Common {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-undefined-compare"
/**
* @brief A null-terminated string with a fixed maximum length
* This class is not meant to be used as a general-purpose string class
@ -29,20 +32,27 @@ public:
explicit CString(const CString<M>& other)
requires(M <= N)
{
if (this == nullptr) {
return;
}
std::ranges::copy(other.begin(), other.end(), data);
}
void FromString(const std::basic_string_view<T>& str) {
if (this == nullptr) {
return;
}
size_t p = str.copy(data, N - 1);
data[p] = '\0';
}
void Zero() {
if (this == nullptr) {
return;
}
std::ranges::fill(data, 0);
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-undefined-compare"
explicit(false) operator std::basic_string_view<T>() const {
if (this == nullptr) {
return {};
@ -70,21 +80,32 @@ public:
}
return std::basic_string_view<T>{data};
}
#pragma clang diagnostic pop
char* begin() {
if (this == nullptr) {
return nullptr;
}
return data;
}
const char* begin() const {
if (this == nullptr) {
return nullptr;
}
return data;
}
char* end() {
if (this == nullptr) {
return nullptr;
}
return data + N;
}
const char* end() const {
if (this == nullptr) {
return nullptr;
}
return data + N;
}
@ -127,7 +148,10 @@ public:
}
};
};
static_assert(sizeof(CString<13>) == sizeof(char[13])); // Ensure size still matches a simple array
static_assert(std::weakly_incrementable<CString<13>::Iterator>);
#pragma clang diagnostic pop
} // namespace Common