File indexing completed on 2024-11-10 12:47:30

0001 /*
0002     SPDX-FileCopyrightText: 2020 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "kgraphqlminimizer_p.h"
0008 
0009 #include <QByteArray>
0010 
0011 KGraphQLMinimizer::KGraphQLMinimizer() = default;
0012 KGraphQLMinimizer::~KGraphQLMinimizer() = default;
0013 
0014 QByteArray KGraphQLMinimizer::minimizeQuery(const QByteArray &query)
0015 {
0016     m_out.clear();
0017     m_out.reserve(query.size());
0018 
0019     for (auto it = query.begin(); it != query.end(); ++it) {
0020         char c = (*it);
0021         if (c == '\r') c = '\n';
0022         if (c == '#') {
0023             while ((*it) != '\n' && it != query.end()) ++it;
0024             appendSpaceCompress('\n');
0025             continue;
0026         }
0027         appendSpaceCompress(c);
0028     }
0029 
0030     return std::move(m_out);
0031 }
0032 
0033 void KGraphQLMinimizer::appendSpaceCompress(char c)
0034 {
0035     if (m_out.isEmpty()) {
0036         if (!std::isspace(static_cast<unsigned char>(c))) {
0037             m_out.push_back(c);
0038         }
0039         return;
0040     }
0041 
0042     const auto prev = m_out.back();
0043     if (std::isspace(static_cast<unsigned char>(prev))) {
0044         if (std::isspace(static_cast<unsigned char>(c))) {
0045             if (c == '\n') {
0046                 m_out.back() = c;
0047             }
0048         } else {
0049             if (isPunctuator(c)) {
0050                 m_out.back() = c;
0051             } else {
0052                 m_out.push_back(c);
0053             }
0054         }
0055         return;
0056     }
0057 
0058     if (!std::isspace(static_cast<unsigned char>(c)) || !isPunctuator(prev)) {
0059         m_out.push_back(c);
0060     }
0061 }
0062 
0063 bool KGraphQLMinimizer::isPunctuator(char c) const
0064 {
0065     static const char punctuators[] = "!$(),.:=@[]{|}";
0066     return std::binary_search(std::begin(punctuators), std::end(punctuators), c);
0067 }