libluna: Add PathParser, a C++-style way of iterating over path sections
Still uses strtok under the hood, though.
This commit is contained in:
parent
5a9da55e05
commit
4c66017807
@ -17,6 +17,7 @@ set(FREESTANDING_SOURCES
|
||||
src/DebugLog.cpp
|
||||
src/Heap.cpp
|
||||
src/Spinlock.cpp
|
||||
src/PathParser.cpp
|
||||
src/UBSAN.cpp
|
||||
)
|
||||
|
||||
|
28
libluna/include/luna/PathParser.h
Normal file
28
libluna/include/luna/PathParser.h
Normal 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 };
|
||||
};
|
33
libluna/src/PathParser.cpp
Normal file
33
libluna/src/PathParser.cpp
Normal 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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user