structurereader.cpp 5.81 KB
Newer Older
1
2
3
4
5
6
7
/**
\file structurereader.cpp
\date 07/05/2021
\author Yann Boucher
\version 1
\brief StructureReader
**/
8
#define private public
9
10
11
12
13
14
15
#include "structurereader.hpp"

#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "structure.hpp"
Merwane Bouri's avatar
Merwane Bouri committed
16
#include <vector>
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

char StructureReader::peek() const
{
    if (m_idx >= m_data.size())
        throw StructureReaderException("Fichier invalide, la lecture a dépassé la fin du fichier.");
    return m_data[m_idx];
}

char StructureReader::read()
{
    char val = peek();
    ++m_idx;
    return val;
}

bool StructureReader::eof() const
{
    return m_idx >= m_data.size();
}

void StructureReader::expect(const std::string &str)
{
    read_white();
    if (m_data.substr(m_idx, str.size()) != str)
        throw StructureReaderException("Valeur attendue : " + str);
    m_idx += str.size();
    read_white();
}

bool StructureReader::accept(const std::string &str)
{
    read_white();
    if (m_data.substr(m_idx, str.size()) == str)
    {
        m_idx += str.size();
        read_white();
        return true;
    }
    return false;
}

std::string StructureReader::read_word()
{
    std::string str;
    while (m_idx < m_data.size() && !isspace(m_data[m_idx]))
        str += m_data[m_idx++];

    return str;
}

std::string StructureReader::read_line()
{
    std::string str;
    while (m_idx < m_data.size() && m_data[m_idx] != '\n')
        str += m_data[m_idx++];
    read_white();

    return str;
}

std::string StructureReader::data_left() const
{
    return m_data.substr(m_idx);
}

int StructureReader::read_int()
{
    read_white();

    size_t cars_read;
    int val;
    try
    {
90
        val = std::stoi(&m_data.c_str()[m_idx], &cars_read, 10);
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
    }
    catch (std::exception& e)
    {
        throw StructureReaderException("La valeur lue n'est pas un entier !");
    }

    m_idx += cars_read;
    read_white();
    return val;
}

void StructureReader::read_white()
{
    while (m_idx < m_data.size() && isspace(peek()))
        ++m_idx;
}

// ref : http://golly.sourceforge.net/Help/formats.html#rle
unsigned RLEStructureReader::read_state()
{
    char char_1 = read();
    if (char_1 == 'b' || char_1 == 'B' || char_1 == '.')
        return 0;
    else if (char_1 == 'o')
        return 1;
    else if (char_1 >= 'A' && char_1 <= 'X')
        return char_1 - 'A' + 1;
    else if (islower(char_1) && isalpha(char_1) && char_1 >= 'p' && char_1 <= 'q')
    {
        char char_2 = read();
        unsigned offset = (char_1 - 'p')*24 + 49;
        return offset + (char_2 - 'A');
    }
    // unknown chars are zero
    return 0;
}

// ref : http://golly.sourceforge.net/Help/formats.html#rle
Structure RLEStructureReader::read_structure()
{
    // ignore first comment lines
    while (accept("#"))
        read_line();

    // First Line
    {
        expect("x");
        expect("=");
        int x = read_int();
        expect(",");
        expect("y");
        expect("=");
        int y = read_int();
        std::string rule = "";
        if (accept(",") && accept("rule"))
        {
            expect("=");
            rule = read_word();
        }

        (void)x; (void)y; // ignore warnings
    }

    std::vector<std::pair<Coord, unsigned>> data;
    int x = 0, y = 0;

    while (!eof())
    {
        // comment line
        if (accept("#"))
        {
            //char tag = read();
            std::string line = read_line();
        }
        // end of data
        else if (accept("!"))
        {
            break;
        }
        // structure
        else
        {
            unsigned state = 0;
            unsigned run_count = 1;
            // <run_count> is > 1
            if (isdigit(peek()))
                run_count = read_int();
178
179
            // end of structure line
            if (accept("$"))
180
            {
181
182
183
184
185
186
187
188
189
190
191
192
                x = 0;
                y += run_count;
            }
            else
            {
                state = read_state();

                for (unsigned i = 0; i < run_count; ++i)
                {
                    data.push_back({{x, y}, state});
                    ++x;
                }
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
            }
        }
    }

    return Structure(data.begin(), data.end());
}



Structure JSONStructureReader::read_structure()
{
    std::vector<std::pair<Coord, unsigned>> data;

    QByteArray byteArray = QByteArray::fromStdString(data_left());
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray, &parseError);
    if(parseError.error != QJsonParseError::NoError)
    {
        throw StructureReaderException("Erreur de parsing JSON à " + std::to_string(parseError.offset) + ":" + parseError.errorString().toStdString());
    }

    QJsonObject root = jsonDoc.object();

216
217
    Structure s;

218
219
220
221
222
    if (!root.contains("cells"))
        throw StructureReaderException("Pas de champ 'cells' !");
    if (!root["cells"].isArray())
        throw StructureReaderException("'cells' doit être un array.");

223
224
225
226
227
    s.author = root.value("author").toString().toStdString();
    s.title = root.value("title").toString().toStdString();
    s.date = root.value("date").toString().toStdString();
    s.desc = root.value("desc").toString().toStdString();

228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    for (const auto& entry : root["cells"].toArray())
    {
        const char* msg = "Chaque entrée de 'cells' doit être un objet contenant des entiers x, y, et state.";

        if (!entry.isObject())
            throw StructureReaderException(msg);

        QJsonObject val = entry.toObject();
        if (!val.contains("x") || !val.contains("y") || !val.contains("state"))
            throw StructureReaderException(msg);
        if (!val["x"].isDouble() || !val["y"].isDouble() || !val["state"].isDouble())
            throw StructureReaderException(msg);

        data.push_back({{val["x"].toInt(), val["y"].toInt()}, val["state"].toInt()});
    }

244
245
    s.load(data.begin(), data.end());
    return s;
246
}