From ef01f187c3f7f33ba9527df2dad960426990122a Mon Sep 17 00:00:00 2001 From: apio Date: Wed, 29 Mar 2023 17:43:10 +0200 Subject: [PATCH] libluna: Add StringView --- libluna/CMakeLists.txt | 1 + libluna/include/luna/String.h | 6 +++++ libluna/include/luna/StringView.h | 39 ++++++++++++++++++++++++++++ libluna/src/StringView.cpp | 42 +++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+) create mode 100644 libluna/include/luna/StringView.h create mode 100644 libluna/src/StringView.cpp diff --git a/libluna/CMakeLists.txt b/libluna/CMakeLists.txt index eb99bd36..0a5cc9de 100644 --- a/libluna/CMakeLists.txt +++ b/libluna/CMakeLists.txt @@ -14,6 +14,7 @@ set(FREESTANDING_SOURCES src/Buffer.cpp src/Stack.cpp src/String.cpp + src/StringView.cpp src/Utf8.cpp src/TarStream.cpp src/DebugLog.cpp diff --git a/libluna/include/luna/String.h b/libluna/include/luna/String.h index f9202d7c..219e4e2f 100644 --- a/libluna/include/luna/String.h +++ b/libluna/include/luna/String.h @@ -1,5 +1,6 @@ #pragma once #include +#include class String { @@ -35,6 +36,11 @@ class String return m_length == 0; } + StringView view() const + { + return { chars(), m_length }; + } + const char& operator[](usize) const; private: diff --git a/libluna/include/luna/StringView.h b/libluna/include/luna/StringView.h new file mode 100644 index 00000000..68c4885b --- /dev/null +++ b/libluna/include/luna/StringView.h @@ -0,0 +1,39 @@ +#pragma once +#include + +class String; + +class StringView +{ + public: + StringView(const char* c_str); + StringView(const char* c_str, usize length); + + StringView(); + + StringView(const StringView&); + + Result 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 }; +}; diff --git a/libluna/src/StringView.cpp b/libluna/src/StringView.cpp new file mode 100644 index 00000000..40161b7a --- /dev/null +++ b/libluna/src/StringView.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +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 StringView::to_string() +{ + return String::from_cstring(m_string); +}