From fe348d56c098ca1ff6434ef233517accf434fc96 Mon Sep 17 00:00:00 2001 From: apio Date: Fri, 7 Apr 2023 15:14:46 +0200 Subject: [PATCH] String+StringView: Add split() --- libluna/include/luna/String.h | 2 ++ libluna/include/luna/StringView.h | 3 +++ libluna/src/String.cpp | 5 +++++ libluna/src/StringView.cpp | 27 +++++++++++++++++++++++++++ 4 files changed, 37 insertions(+) diff --git a/libluna/include/luna/String.h b/libluna/include/luna/String.h index de8dab1b..fa3ca9e0 100644 --- a/libluna/include/luna/String.h +++ b/libluna/include/luna/String.h @@ -26,6 +26,8 @@ class String Result substring(usize begin, usize size) const; + Result> split(StringView delim) const; + static Result format(const String& fmt, ...); static Result format(StringView fmt, ...); diff --git a/libluna/include/luna/StringView.h b/libluna/include/luna/StringView.h index a9a04d41..3d8ff8df 100644 --- a/libluna/include/luna/StringView.h +++ b/libluna/include/luna/StringView.h @@ -1,5 +1,6 @@ #pragma once #include +#include class String; @@ -37,6 +38,8 @@ class StringView bool operator==(const char* other) const; bool operator==(StringView other) const; + Result> split(StringView delim) const; + Iterator begin() const { return m_string; diff --git a/libluna/src/String.cpp b/libluna/src/String.cpp index a9be76ca..d3a1c2d5 100644 --- a/libluna/src/String.cpp +++ b/libluna/src/String.cpp @@ -75,6 +75,11 @@ Result String::substring(usize begin, usize size) const return String { dup, size }; } +Result> String::split(StringView delim) const +{ + return view().split(delim); +} + const char& String::operator[](usize index) const { expect(index < m_length, "index out of range"); diff --git a/libluna/src/StringView.cpp b/libluna/src/StringView.cpp index 054f0ebd..664da077 100644 --- a/libluna/src/StringView.cpp +++ b/libluna/src/StringView.cpp @@ -46,6 +46,33 @@ bool StringView::operator==(StringView other) const return !strcmp(m_string, other.m_string); } +Result> StringView::split(StringView delim) const +{ + Vector result; + String str; + + char* copy = strndup(m_string, m_length); + + char* segment = strtok(copy, delim.chars()); + if (!segment) goto end; + + str = TRY(String::from_cstring(segment)); + TRY(result.try_append(move(str))); + + while (true) + { + segment = strtok(nullptr, delim.chars()); + if (!segment) goto end; + + str = TRY(String::from_cstring(segment)); + TRY(result.try_append(move(str))); + } + +end: + free_impl(copy); + return result; +} + Result StringView::to_string() { return String::from_cstring(m_string);