libluna: Add StringView
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
apio 2023-03-29 17:43:10 +02:00
parent 01813ff0dd
commit ef01f187c3
Signed by: apio
GPG Key ID: B8A7D06E42258954
4 changed files with 88 additions and 0 deletions

View File

@ -14,6 +14,7 @@ set(FREESTANDING_SOURCES
src/Buffer.cpp src/Buffer.cpp
src/Stack.cpp src/Stack.cpp
src/String.cpp src/String.cpp
src/StringView.cpp
src/Utf8.cpp src/Utf8.cpp
src/TarStream.cpp src/TarStream.cpp
src/DebugLog.cpp src/DebugLog.cpp

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <luna/Result.h> #include <luna/Result.h>
#include <luna/StringView.h>
class String class String
{ {
@ -35,6 +36,11 @@ class String
return m_length == 0; return m_length == 0;
} }
StringView view() const
{
return { chars(), m_length };
}
const char& operator[](usize) const; const char& operator[](usize) const;
private: private:

View File

@ -0,0 +1,39 @@
#pragma once
#include <luna/Result.h>
class String;
class StringView
{
public:
StringView(const char* c_str);
StringView(const char* c_str, usize length);
StringView();
StringView(const StringView&);
Result<String> to_string();
const char* chars() const
{
return m_string;
}
usize length() const
{
return m_length;
}
bool is_empty() const
{
return m_length == 0;
}
const char& operator[](usize) const;
private:
const char* m_string { nullptr };
usize m_length { 0 };
};

View File

@ -0,0 +1,42 @@
#include <luna/CString.h>
#include <luna/String.h>
#include <luna/StringView.h>
static const char* empty = "";
StringView::StringView()
{
m_string = empty;
m_length = 0;
}
StringView::StringView(const StringView& other)
{
m_string = other.m_string;
m_length = other.m_length;
}
StringView::StringView(const char* c_str)
{
check(c_str);
m_string = c_str;
m_length = strlen(m_string);
}
StringView::StringView(const char* c_str, usize length)
{
check(c_str);
m_string = c_str;
m_length = length;
}
const char& StringView::operator[](usize index) const
{
expect(index < m_length, "index out of range");
return m_string[index];
}
Result<String> StringView::to_string()
{
return String::from_cstring(m_string);
}