Line data Source code
1 : #include "LinewiseInput.h"
2 : #include "Grid2d.h"
3 :
4 : #include <algorithm>
5 : #include <ranges>
6 :
7 87 : LinewiseInput::LinewiseInput(std::string_view const text) {
8 55769 : for (auto it = text.begin(); it != text.end();) {
9 55682 : auto lineStart = it;
10 55682 : it = std::find(it, text.end(), '\n');
11 55682 : _lines.emplace_back(lineStart, it);
12 55682 : if (it != text.end())
13 55596 : ++it;
14 55682 : }
15 87 : }
16 :
17 6 : std::vector<std::span<std::string_view const>> LinewiseInput::splitOnEmptyLines() const {
18 6 : std::vector<std::span<std::string_view const>> result;
19 :
20 704 : for (auto it = _lines.begin(); it != _lines.end();) {
21 1390 : while (it->empty() && it != _lines.end())
22 692 : ++it;
23 698 : auto startIt = it;
24 8648 : it = std::find_if(it, _lines.end(), [](std::string_view const s) { return s.empty(); });
25 698 : result.emplace_back(startIt, it);
26 698 : }
27 6 : return result;
28 6 : }
29 :
30 17 : bool LinewiseInput::allLinesOfSameSize() const {
31 17 : if (_lines.empty())
32 0 : return true;
33 1981 : return std::all_of(std::next(_lines.begin()), _lines.end(), [this](std::string_view const s) {
34 1981 : return s.size() == _lines.front().size();
35 1981 : });
36 17 : }
37 :
38 220 : Grid2d<char> makeCharGrid2d(std::span<std::string_view const> const lines) {
39 220 : size_t const xSize = lines.front().size();
40 220 : size_t const ySize = lines.size();
41 220 : Grid2d<char> result(xSize, ySize);
42 :
43 220 : Grid2d<char>::IndexType y = 0;
44 4673 : std::ranges::for_each(std::ranges::reverse_view(lines), [&](std::string_view line) {
45 4673 : DEBUG_ASSERT(line.size() == xSize);
46 326398 : for (size_t x = 0; x < xSize; ++x)
47 321725 : result[x, y] = line[x];
48 4673 : ++y;
49 4673 : });
50 :
51 220 : return result;
52 220 : }
53 :
54 20 : Grid2d<char> LinewiseInput::makeCharGrid2d() const { return ::makeCharGrid2d(_lines); }
55 :
56 : Grid2d<char> LinewiseInput::makeCharGrid2dWithGhostLayers(int const numGhostLayers,
57 17 : char const fillElement) const {
58 17 : DEBUG_ASSERT(allLinesOfSameSize());
59 17 : using IndexType = Grid2d<char>::IndexType;
60 17 : size_t const xSize = _lines.front().size();
61 17 : size_t const ySize = _lines.size();
62 :
63 17 : Grid2d<char> result(xSize, ySize, fillElement, numGhostLayers);
64 :
65 17 : IndexType y = 0;
66 1998 : std::ranges::for_each(std::ranges::reverse_view(_lines), [&](std::string_view line) {
67 256586 : for (IndexType x = 0; x < result.xSize(); ++x)
68 254588 : result[x, y] = line[x];
69 1998 : ++y;
70 1998 : });
71 :
72 17 : return result;
73 17 : }
74 :
75 6 : std::generator<std::string_view> getLineWise(std::string_view const text) {
76 4306 : for (auto it = text.begin(); it != text.end();) {
77 4300 : auto lineStart = it;
78 4300 : it = std::find(it, text.end(), '\n');
79 4300 : co_yield std::string_view{lineStart, it};
80 4300 : if (it != text.end())
81 4294 : ++it;
82 4300 : }
83 6 : }
|