stuff-from-scratch/src/core/serializers/TomlReader.h
2022-10-10 08:57:32 +01:00

124 lines
No EOL
2.2 KiB
C++

#pragma once
#include "File.h"
#include <filesystem>
#include <memory>
#include <unordered_map>
#include <iostream>
using Path = std::filesystem::path;
class TomlSection
{
public:
using Comment = std::pair<unsigned, std::string>;
TomlSection(const std::string& tag)
: mTag(tag)
{
}
void addComment(const Comment& comment)
{
mComments.push_back(comment);
}
void addSection(std::unique_ptr<TomlSection> section)
{
mSections[section->getTag()] = std::move(section);
}
void addValue(const std::string& key, const std::string& value)
{
mValues[key] = value;
}
std::string getTag() const
{
return mTag;
}
private:
unsigned mLineOffset{ 0 };
std::string mTag;
std::unordered_map<std::string, std::unique_ptr<TomlSection> > mSections;
std::unordered_map<std::string, std::string> mValues;
std::vector<Comment> mComments;
};
class TomlContent
{
private:
std::unique_ptr<TomlSection> mRootSection;
};
class TomlReader
{
public:
TomlReader()
: mContent(std::make_unique<TomlContent>())
{
}
TomlContent* getContent() const
{
return mContent.get();
}
void read(const Path& input_path)
{
const auto lines = File(input_path).readLines();
mLastSectionOffset = 0;
mWorkingSection = std::make_unique<TomlSection>("root");
for (const auto& line : lines)
{
processLine(line);
mLastSectionOffset++;
}
}
void processLine(const std::string& line)
{
bool in_comment{ false };
bool in_tag{ false };
std::string working_string;
for (auto c : line)
{
if (c == '#' && !in_comment)
{
in_comment = true;
}
else if (c == '[' && !in_comment && !in_tag)
{
in_tag = true;
}
else if (c == ']' && in_tag)
{
break;
}
else if (in_comment || in_tag)
{
working_string += c;
}
}
if (in_comment)
{
std::cout << "Found comment at: " << mLastSectionOffset << " with value " << working_string;
mWorkingSection->addComment({ mLastSectionOffset, working_string });
}
else if (in_tag)
{
std::cout << "Found tag at: " << mLastSectionOffset << " with value " << working_string;
}
}
private:
unsigned mLastSectionOffset{ 0 };
std::unique_ptr<TomlContent> mContent;
std::unique_ptr<TomlSection> mWorkingSection;
};