Luna/libluna/include/luna/StaticString.h

111 lines
2.1 KiB
C
Raw Normal View History

2023-02-27 14:13:23 +00:00
#pragma once
#include <luna/CString.h>
2023-08-08 10:39:03 +00:00
#include <luna/Common.h>
#include <luna/StringView.h>
2023-02-27 14:13:23 +00:00
#include <luna/Types.h>
template <usize Size> class StaticString
{
public:
StaticString() = default;
StaticString(const char* string)
{
adopt(string);
}
2023-04-23 08:53:48 +00:00
template <usize OtherSize> StaticString(const StaticString<OtherSize>& other)
{
adopt(other.chars());
}
2023-02-27 14:13:23 +00:00
void adopt(const char* string)
{
usize length = strlcpy(m_buffer, string, sizeof(m_buffer));
if (length > Size) { m_length = Size; }
else
m_length = length;
}
void adopt(const char* string, usize length)
{
if (length > Size) length = Size;
memcpy(m_buffer, string, length);
m_buffer[length] = 0;
m_length = length;
}
void adopt(StringView string)
{
2023-08-08 10:39:03 +00:00
usize length = strlcpy(m_buffer, string.chars(), min(sizeof(m_buffer), string.length() + 1));
if (length > Size) { m_length = Size; }
else
m_length = length;
}
2023-02-27 14:13:23 +00:00
StaticString<Size>& operator=(const char* string)
{
adopt(string);
return *this;
}
StaticString<Size>& operator=(StringView string)
{
adopt(string);
return *this;
}
template <usize OtherSize> StaticString<Size>& operator=(const StaticString<OtherSize>& string)
2023-02-27 14:13:23 +00:00
{
if constexpr (OtherSize == Size)
2023-02-27 14:13:23 +00:00
{
if (this == &string) return *this;
}
adopt(string.chars());
return *this;
}
const char* chars() const
{
return m_buffer;
}
char* data()
{
return m_buffer;
}
void set_length(usize len)
{
m_length = len;
}
2023-02-27 14:13:23 +00:00
usize length() const
{
return m_length;
}
void trim(StringView delim)
{
isize i = (isize)m_length;
while (i--)
{
char c = m_buffer[i];
if (!strchr(delim.chars(), c)) break;
}
i++;
m_buffer[i] = '\0';
m_length = (usize)i;
}
2023-02-27 14:13:23 +00:00
private:
char m_buffer[Size + 1];
usize m_length { 0 };
};