Luna/libluna/src/PathParser.cpp

62 lines
1.4 KiB
C++
Raw Normal View History

#include <luna/CPath.h>
#include <luna/PathParser.h>
#include <luna/ScopeGuard.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;
}
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);
}