libluna: Add PathParser, a C++-style way of iterating over path sections

Still uses strtok under the hood, though.
This commit is contained in:
apio 2023-03-10 22:17:03 +01:00
parent 5a9da55e05
commit 4c66017807
Signed by: apio
GPG Key ID: B8A7D06E42258954
3 changed files with 62 additions and 0 deletions

View File

@ -17,6 +17,7 @@ set(FREESTANDING_SOURCES
src/DebugLog.cpp
src/Heap.cpp
src/Spinlock.cpp
src/PathParser.cpp
src/UBSAN.cpp
)

View File

@ -0,0 +1,28 @@
#pragma once
#include <luna/CString.h>
#include <luna/Heap.h>
class PathParser
{
public:
static Result<PathParser> create(const char* path);
PathParser(PathParser&& other);
PathParser(const PathParser&) = delete;
~PathParser();
bool is_absolute() const
{
return *m_original == '/';
}
Option<const char*> next();
private:
PathParser(const char* original, char* copy);
const char* m_original { nullptr };
char* m_copy { nullptr };
bool m_already_called_next { false };
};

View File

@ -0,0 +1,33 @@
#include <luna/PathParser.h>
Result<PathParser> PathParser::create(const char* path)
{
char* copy = strdup(path);
if (!copy) return err(ENOMEM);
return PathParser { path, copy };
}
PathParser::PathParser(const char* original, char* copy) : m_original(original), m_copy(copy)
{
}
PathParser::PathParser(PathParser&& other) : m_original(other.m_original), m_copy(other.m_copy)
{
other.m_copy = nullptr;
}
PathParser::~PathParser()
{
if (m_copy) free_impl(m_copy);
}
Option<const char*> PathParser::next()
{
char* result = strtok(m_already_called_next ? nullptr : m_copy, "/");
m_already_called_next = true;
if (!result) return {};
return result;
}