From cf8d3c6ff9589abb1961811e9114fb8c31c9acf5 Mon Sep 17 00:00:00 2001 From: apio Date: Sun, 22 Jan 2023 11:27:54 +0100 Subject: [PATCH] OwnedStringView: Add a method to extract a substring --- luna/include/luna/OwnedStringView.h | 3 +++ luna/src/OwnedStringView.cpp | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/luna/include/luna/OwnedStringView.h b/luna/include/luna/OwnedStringView.h index 876e9c60..09454b0f 100644 --- a/luna/include/luna/OwnedStringView.h +++ b/luna/include/luna/OwnedStringView.h @@ -5,6 +5,7 @@ class OwnedStringView { public: OwnedStringView(char* c_str); + OwnedStringView(char* c_str, usize length); OwnedStringView(); OwnedStringView(OwnedStringView&&); OwnedStringView(const OwnedStringView&) = delete; @@ -12,6 +13,8 @@ class OwnedStringView Result clone() const; + Result substring(usize begin, usize size) const; + static Result from_string_literal(const char* str); const char* chars() const diff --git a/luna/src/OwnedStringView.cpp b/luna/src/OwnedStringView.cpp index c53fc446..10637a23 100644 --- a/luna/src/OwnedStringView.cpp +++ b/luna/src/OwnedStringView.cpp @@ -21,6 +21,12 @@ OwnedStringView::OwnedStringView(char* c_str) if (m_string) { m_length = strlen(m_string); } } +OwnedStringView::OwnedStringView(char* c_str, usize length) +{ + m_string = c_str; + m_length = length; +} + OwnedStringView::~OwnedStringView() { if (m_string) free_impl(m_string); @@ -31,6 +37,14 @@ Result OwnedStringView::clone() const return from_string_literal(m_string); } +Result OwnedStringView::substring(usize begin, usize size) const +{ + if (begin + size >= size) return err(EINVAL); + char* const dup = strndup(m_string + begin, size); + if (!dup) return err(ENOMEM); + return OwnedStringView { dup, size }; +} + const char& OwnedStringView::operator[](usize index) const { expect(index < m_length, "index out of range");