2023-03-11 00:13:44 +00:00
|
|
|
#include <luna/CPath.h>
|
2023-03-10 21:17:03 +00:00
|
|
|
#include <luna/PathParser.h>
|
2023-03-11 00:13:44 +00:00
|
|
|
#include <luna/ScopeGuard.h>
|
2023-03-10 21:17:03 +00:00
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
2023-03-11 00:13:44 +00:00
|
|
|
|
|
|
|
Result<OwnedStringView> PathParser::basename()
|
|
|
|
{
|
|
|
|
char* copy = strdup(m_original);
|
|
|
|
if (!copy) return err(ENOMEM);
|
|
|
|
|
|
|
|
auto guard = make_scope_guard([copy] { free_impl(copy); });
|
|
|
|
|
|
|
|
char* result = ::basename(copy);
|
|
|
|
|
|
|
|
// We must copy this as we cannot rely on the original string.
|
|
|
|
return OwnedStringView::from_string_literal(result);
|
|
|
|
}
|
|
|
|
|
|
|
|
Result<OwnedStringView> PathParser::dirname()
|
|
|
|
{
|
|
|
|
char* copy = strdup(m_original);
|
|
|
|
if (!copy) return err(ENOMEM);
|
|
|
|
|
|
|
|
auto guard = make_scope_guard([copy] { free_impl(copy); });
|
|
|
|
|
|
|
|
char* result = ::dirname(copy);
|
|
|
|
|
|
|
|
// We must copy this as we cannot rely on the original string.
|
|
|
|
return OwnedStringView::from_string_literal(result);
|
|
|
|
}
|