2020-02-16 17:58:09 -07:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "common.h"
|
|
|
|
#include <istream>
|
|
|
|
|
2020-02-25 04:39:27 -07:00
|
|
|
template <typename C, int delimiterCount, int blockSize = 0x1000 / sizeof(C)> // windows file block size
|
2020-02-16 17:58:09 -07:00
|
|
|
class BlockMarkupIterator
|
|
|
|
{
|
|
|
|
public:
|
2020-03-16 02:56:04 -06:00
|
|
|
BlockMarkupIterator(const std::istream& stream, const std::basic_string_view<C>(&delimiters)[delimiterCount]) :
|
|
|
|
streambuf(*stream.rdbuf())
|
2020-02-16 17:58:09 -07:00
|
|
|
{
|
2020-02-25 04:39:27 -07:00
|
|
|
std::copy_n(delimiters, delimiterCount, this->delimiters.begin());
|
2020-02-16 17:58:09 -07:00
|
|
|
}
|
2020-02-25 04:39:27 -07:00
|
|
|
|
|
|
|
std::optional<std::array<std::basic_string<C>, delimiterCount>> Next()
|
2020-02-16 17:58:09 -07:00
|
|
|
{
|
2020-02-25 04:39:27 -07:00
|
|
|
std::array<std::basic_string<C>, delimiterCount> results;
|
|
|
|
Find(delimiters[0], true);
|
|
|
|
for (int i = 0; i < delimiterCount; ++i)
|
2020-02-16 17:58:09 -07:00
|
|
|
{
|
2020-02-25 04:39:27 -07:00
|
|
|
const auto delimiter = i + 1 < delimiterCount ? delimiters[i + 1] : end;
|
|
|
|
if (auto found = Find(delimiter, false)) results[i] = std::move(found.value());
|
|
|
|
else return {};
|
2020-02-16 17:58:09 -07:00
|
|
|
}
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2020-02-25 04:39:27 -07:00
|
|
|
std::optional<std::basic_string<C>> Find(std::basic_string_view<C> delimiter, bool discard)
|
2020-02-16 17:58:09 -07:00
|
|
|
{
|
2020-02-25 04:39:27 -07:00
|
|
|
for (int i = 0; ;)
|
|
|
|
{
|
|
|
|
int pos = buffer.find(delimiter, i);
|
|
|
|
if (pos != std::string::npos)
|
|
|
|
{
|
|
|
|
auto result = !discard ? std::optional(std::basic_string(buffer.begin(), buffer.begin() + pos)) : std::nullopt;
|
|
|
|
buffer.erase(buffer.begin(), buffer.begin() + pos + delimiter.size());
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
int oldSize = buffer.size();
|
|
|
|
buffer.resize(oldSize + blockSize);
|
2020-03-07 03:45:07 -07:00
|
|
|
if (!streambuf.sgetn((char*)(buffer.data() + oldSize), blockSize * sizeof(C))) return {};
|
2020-02-25 04:39:27 -07:00
|
|
|
i = max(0, oldSize - (int)delimiter.size());
|
|
|
|
if (discard)
|
|
|
|
{
|
|
|
|
buffer.erase(0, i);
|
|
|
|
i = 0;
|
|
|
|
}
|
|
|
|
}
|
2020-02-16 17:58:09 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
static constexpr C endImpl[5] = { '|', 'E', 'N', 'D', '|' };
|
|
|
|
static constexpr std::basic_string_view end{ endImpl, 5 };
|
|
|
|
|
2020-02-25 04:39:27 -07:00
|
|
|
std::basic_streambuf<char>& streambuf;
|
|
|
|
std::basic_string<C> buffer;
|
|
|
|
std::array<std::basic_string_view<C>, delimiterCount> delimiters;
|
2020-02-16 17:58:09 -07:00
|
|
|
};
|