2020-02-17 08:58:09 +08:00
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <istream>
|
|
|
|
|
2020-02-25 19:39:27 +08:00
|
|
|
template <typename C, int delimiterCount, int blockSize = 0x1000 / sizeof(C)> // windows file block size
|
2020-02-17 08:58:09 +08:00
|
|
|
class BlockMarkupIterator
|
|
|
|
{
|
|
|
|
public:
|
2021-01-31 03:07:37 +08:00
|
|
|
BlockMarkupIterator(const std::istream& stream, const std::basic_string_view<C>(&delimiters)[delimiterCount]) : streambuf(*stream.rdbuf())
|
2020-02-17 08:58:09 +08:00
|
|
|
{
|
2020-02-25 19:39:27 +08:00
|
|
|
std::copy_n(delimiters, delimiterCount, this->delimiters.begin());
|
2020-02-17 08:58:09 +08:00
|
|
|
}
|
2020-02-25 19:39:27 +08:00
|
|
|
|
|
|
|
std::optional<std::array<std::basic_string<C>, delimiterCount>> Next()
|
2020-02-17 08:58:09 +08:00
|
|
|
{
|
2020-02-25 19:39:27 +08:00
|
|
|
std::array<std::basic_string<C>, delimiterCount> results;
|
|
|
|
Find(delimiters[0], true);
|
|
|
|
for (int i = 0; i < delimiterCount; ++i)
|
2020-02-17 08:58:09 +08:00
|
|
|
{
|
2020-02-25 19:39:27 +08: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-17 08:58:09 +08:00
|
|
|
}
|
|
|
|
return results;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2020-02-25 19:39:27 +08:00
|
|
|
std::optional<std::basic_string<C>> Find(std::basic_string_view<C> delimiter, bool discard)
|
2020-02-17 08:58:09 +08:00
|
|
|
{
|
2020-02-25 19:39:27 +08: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 18:45:07 +08:00
|
|
|
if (!streambuf.sgetn((char*)(buffer.data() + oldSize), blockSize * sizeof(C))) return {};
|
2020-02-25 19:39:27 +08:00
|
|
|
i = max(0, oldSize - (int)delimiter.size());
|
|
|
|
if (discard)
|
|
|
|
{
|
|
|
|
buffer.erase(0, i);
|
|
|
|
i = 0;
|
|
|
|
}
|
|
|
|
}
|
2020-02-17 08:58:09 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
static constexpr C endImpl[5] = { '|', 'E', 'N', 'D', '|' };
|
|
|
|
static constexpr std::basic_string_view end{ endImpl, 5 };
|
|
|
|
|
2020-02-25 19:39:27 +08:00
|
|
|
std::basic_streambuf<char>& streambuf;
|
|
|
|
std::basic_string<C> buffer;
|
|
|
|
std::array<std::basic_string_view<C>, delimiterCount> delimiters;
|
2020-02-17 08:58:09 +08:00
|
|
|
};
|