<commit_before>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

#include <QtDebug>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QBuffer>
#include <QtCore/QMimeDatabase>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QHttpMultiPart>
#ifndef QT_NO_SSL
#include <QtNetwork/QSslError>
#endif
#include <QtQml/QQmlEngine>
#include <QtQml/QJSValueIterator>

#include "request.h"
#include "response.h"
#include "config.h"
#include "serialization.h"

namespace com { namespace cutehacks { namespace duperagent {

ContentTypeMap contentTypes;

RequestPrototype::RequestPrototype(QQmlEngine *engine, Method method, const QUrl &url) :
    QObject(0),
    m_method(method),
    m_engine(engine),
    m_network(engine->networkAccessManager()),
    m_request(0),
    m_reply(0),
    m_multipart(0),
    m_timeout(-1),
    m_timer(0),
    m_redirects(5),
    m_redirectCount(0)
{
    getConfig()->init(m_engine);
    m_request = new QNetworkRequest(QUrl(url.toString()));
    m_engine->setObjectOwnership(this, QQmlEngine::JavaScriptOwnership);
    m_self = m_engine->newQObject(this);
}

RequestPrototype::~RequestPrototype()
{
    delete m_request;
    delete m_multipart;
}

QJSValue RequestPrototype::use(QJSValue fn)
{
    if (fn.isCallable()) {
        fn.call(QJSValueList() << self());
    } else {
        qWarning("'use' expects a function");
    }
    return self();
}

QJSValue RequestPrototype::timeout(int ms)
{
    m_timeout = ms;
    return self();
}

QJSValue RequestPrototype::clearTimeout()
{
    m_timeout = -1;
    return self();
}

QJSValue RequestPrototype::abort()
{
    if (m_reply && m_reply->isRunning())
        m_reply->abort();
    return self();
}

QJSValue RequestPrototype::set(const QJSValue &field, const QJSValue &val)
{
    if (field.isObject()) {
        QJSValueIterator it(field);
        while (it.next()) {
            m_request->setRawHeader(
                        it.name().toUtf8(),
                        it.value().toString().toUtf8());
        }
    } else {
        m_request->setRawHeader(
                    field.toString().toUtf8(),
                    val.toString().toUtf8());
    }

    return self();
}

QJSValue RequestPrototype::unset(const QString &field)
{
    m_request->setRawHeader(
                field.toUtf8(),
                QByteArray());

    return self();
}

QJSValue RequestPrototype::type(const QJSValue &type)
{
    QString t = type.toString();
    if (contentTypes.contains(t)) {
        m_request->setHeader(QNetworkRequest::ContentTypeHeader,
                             contentTypes.value(t));
    } else {
        m_request->setHeader(QNetworkRequest::ContentTypeHeader, t);
    }
    return self();
}

QJSValue RequestPrototype::accept(const QJSValue &type)
{
    const QByteArray ACCEPT_HEADER("Accept");
    QByteArray t = type.toString().toUtf8();
    if (contentTypes.contains(t)) {
        m_request->setRawHeader(ACCEPT_HEADER, contentTypes.value(t));
    } else {
        m_request->setRawHeader(ACCEPT_HEADER, t);
    }
    return self();
}

QJSValue RequestPrototype::auth(const QString &user, const QString &password)
{
    const QByteArray AUTH_HEADER("Authorization");
    QByteArray value = QByteArray("Basic ").append(
                (user + ":" + password)
                .toUtf8()
                .toBase64(QByteArray::Base64UrlEncoding));

    m_request->setRawHeader(AUTH_HEADER, value);
    return self();
}

QJSValue RequestPrototype::redirects(int redirects)
{
    m_redirects = redirects;
    return self();
}

QJSValue RequestPrototype::query(const QJSValue &query)
{
    if (query.isObject()) {
        QJSValueIterator it(query);
        while (it.next()) {
            m_query.addQueryItem(
                        it.name(),
                        it.value().toString());
        }
    } else if (query.isString()) {
        QUrlQuery parsed(query.toString());
        QList<QPair<QString, QString> > items =
                parsed.queryItems(QUrl::FullyDecoded);
        QPair<QString, QString> pair;
        foreach(pair, items) {
            m_query.addQueryItem(pair.first, pair.second);
        }
    } else {
        qWarning("'query' expects an object or string");
    }

    return self();
}

QJSValue RequestPrototype::field(const QJSValue &name, const QJSValue &value)
{
    if (!m_multipart)
        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);

    QString dispositionHeader("form-data; name=\"");
    dispositionHeader += name.toString();
    dispositionHeader += "\";";

    QHttpPart field;
    field.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);
    field.setBody(value.toString().toUtf8());

    m_multipart->append(field);

    return self();
}

QJSValue RequestPrototype::attach(const QJSValue &name, const QJSValue &path,
                                  const QJSValue &filename)
{
    if (!m_multipart)
        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);

    QString dispositionHeader("form-data; name=\"");
    dispositionHeader += name.toString();
    dispositionHeader += "\";";

    QFile *file = new QFile(path.toString(), m_multipart);

    if (!file->exists()) {
        qWarning("File does not exist");
        return self();
    }

    if (!file->open(QIODevice::ReadOnly)) {
        qWarning("Could not open file for reading");
        return self();
    }

    QFileInfo fileInfo(*file);

    QString fname = filename.isString() ? filename.toString() : fileInfo.fileName();
    dispositionHeader += " filename=\"" + fname + "\"";

    QHttpPart attachment;
    attachment.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);

    // TODO: Move the mimeDB somewhere more static
    QMimeDatabase mimeDB;
    QString contentType = mimeDB.mimeTypeForFile(fileInfo).name();
    if (!contentType.isEmpty())
        attachment.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));

    attachment.setBodyDevice(file);

    m_multipart->append(attachment);

    return self();
}

QJSValue RequestPrototype::send(const QJSValue &data)
{
    QByteArray type = m_request->header(QNetworkRequest::ContentTypeHeader)
            .toByteArray();

    if (data.isObject() && m_data.isObject()) {
        // merge with existing data
        QJSValueIterator it(data);
        while (it.hasNext()) {
            m_data.setProperty(it.name(), it.value());
        }
    } else if(data.isString()) {
        if (type.isEmpty()) {
            type = contentTypes["form"];
        }
        if (type == contentTypes["form"]) {
            if (m_data.isString()) {
                m_data = QJSValue(m_data.toString() + "&" + data.toString());
            } else {
                m_data = data;
            }
        } else {
            if (m_data.isString()) {
                m_data = QJSValue(m_data.toString() + data.toString());
            } else {
                m_data = data;
            }
        }
    } else {
        m_data = data;
    }

    if (type.isEmpty())
        type = contentTypes["json"];

    m_request->setHeader(QNetworkRequest::ContentTypeHeader, type);

    return self();
}

QJSValue RequestPrototype::withCredentials()
{
    return self();
}

QJSValue RequestPrototype::end(QJSValue callback)
{
    m_callback = callback;

    dispatchRequest();

    return self();
}

QByteArray RequestPrototype::serializeData()
{
    QByteArray type = m_request->header(
                QNetworkRequest::ContentTypeHeader).toByteArray();

    if (type.contains(contentTypes["json"])) {
        JsonCodec json(m_engine);
        return json.stringify(m_data);
    }
    return m_data.toString().toUtf8();
}

void RequestPrototype::dispatchRequest()
{
    QUrl url = m_request->url();
    url.setQuery(m_query);
    m_request->setUrl(url);

    switch (m_method) {
    case Get:
        m_reply = m_network->get(*m_request);
        break;
    case Post:
        if (m_multipart) {
            m_reply = m_network->post(*m_request, m_multipart);
        } else {
            m_reply = m_network->post(*m_request, serializeData());
        }
        break;
    case Put:
        if (m_multipart) {
            m_reply = m_network->put(*m_request, m_multipart);
        } else {
            m_reply = m_network->put(*m_request, serializeData());
        }
        break;
    case Delete:
        m_reply = m_network->deleteResource(*m_request);
        break;
    case Patch:
        m_request->setAttribute(QNetworkRequest::CustomVerbAttribute, "PATCH");
        m_rawData = serializeData();
        m_reply = m_network->sendCustomRequest(*m_request, "PATCH",
                                               new QBuffer(&m_rawData, this));
        break;
    case Head:
        m_reply = m_network->head(*m_request);
        break;
    default:
        qWarning("Unsupported method");
    }

    emit started();

    connect(m_reply, SIGNAL(finished()), this, SLOT(handleFinished()));
#ifndef QT_NO_SSL
    connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(handleSslErrors(QList<QSslError>)));
#endif

    if (m_timeout > 0)
        m_timer = startTimer(m_timeout);
}

void RequestPrototype::handleFinished()
{
    killTimer(m_timer);

    int status = m_reply->attribute(
                QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QVariant redir = m_reply->attribute(
                QNetworkRequest::RedirectionTargetAttribute);

    if (redir.isValid()) {
        m_redirectCount++;
        if (m_redirectCount <= m_redirects) {
            QUrl location = m_request->url().resolved(redir.toUrl());
            if (location.scheme() == "file") {
                qWarning("Invalid redirect URL scheme");
                return;
            }

            QNetworkRequest *req = new QNetworkRequest(*m_request);
            req->setUrl(location);
            delete m_request;
            m_request = req;
            m_reply->deleteLater();
            m_reply = 0;

            if (status >= 301 && status <= 303) {
                if (m_method == Post) {
                    // TODO: Strip Content-* headers

                    // TODO: Strip send data

                    m_multipart = 0;
                }

                if (status == 303 || m_method != Head) {
                    m_method = Get;
                }
            } else if (status != 307 && status != 308) {
                // Don't change methods on 307/308
                qWarning("Unhandled redirect status code");
                return;
            }
            dispatchRequest();
            return;
        } else {
            m_error = createError("Too many redirects");
        }
    }

    if (!m_error.isError() && m_reply->error() != QNetworkReply::NoError) {
        m_error = createError(m_reply->errorString());
        m_error.setProperty("code", m_reply->error());
        if (status >= 400) {
            m_error.setProperty("status", status);
            // TODO: Add "method" property
        }
    }

    QJSValueList args;

    ResponsePrototype *rep = new ResponsePrototype(m_engine, m_reply);
    args << m_error << m_engine->newQObject(rep);

    if (m_callback.isCallable()) {
        m_callback.call(args);
    } else {
        qWarning() << QString("%1 is not callable").arg(m_callback.toString());
    }
}

QJSValue RequestPrototype::createError(const QString &message, ErrorType type)
{
    QString err;
    switch (type) {
    case RangeError:
        err = "RangeError";
        break;
    case ReferenceError:
        err = "ReferenceError";
        break;
    case SyntaxError:
        err = "SyntaxError";
        break;
    case TypeError:
        err = "TypeError";
        break;
    case URIError:
        err = "URIError";
        break;
    case InternalError:
        err = "InternalError";
        break;
    case Error:
    default:
        err = "Error";
    }

    QString script = "new %1('%2');";
    return m_engine->evaluate(script.arg(err).arg(message));
}

#ifndef QT_NO_SSL
void RequestPrototype::handleSslErrors(const QList<QSslError> &errors)
{

}
#endif

void RequestPrototype::timerEvent(QTimerEvent *)
{
    m_error = createError(QString("Timeout of %1 ms exceeded").arg(m_timeout));
    abort();
}

} } }
<commit_msg>Prevent infinite looping when chaining multiple send requests<commit_after>// Copyright 2015 Cutehacks AS. All rights reserved.
// License can be found in the LICENSE file.

#include <QtDebug>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QBuffer>
#include <QtCore/QMimeDatabase>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QHttpMultiPart>
#ifndef QT_NO_SSL
#include <QtNetwork/QSslError>
#endif
#include <QtQml/QQmlEngine>
#include <QtQml/QJSValueIterator>

#include "request.h"
#include "response.h"
#include "config.h"
#include "serialization.h"

namespace com { namespace cutehacks { namespace duperagent {

ContentTypeMap contentTypes;

RequestPrototype::RequestPrototype(QQmlEngine *engine, Method method, const QUrl &url) :
    QObject(0),
    m_method(method),
    m_engine(engine),
    m_network(engine->networkAccessManager()),
    m_request(0),
    m_reply(0),
    m_multipart(0),
    m_timeout(-1),
    m_timer(0),
    m_redirects(5),
    m_redirectCount(0)
{
    getConfig()->init(m_engine);
    m_request = new QNetworkRequest(QUrl(url.toString()));
    m_engine->setObjectOwnership(this, QQmlEngine::JavaScriptOwnership);
    m_self = m_engine->newQObject(this);
}

RequestPrototype::~RequestPrototype()
{
    delete m_request;
    delete m_multipart;
}

QJSValue RequestPrototype::use(QJSValue fn)
{
    if (fn.isCallable()) {
        fn.call(QJSValueList() << self());
    } else {
        qWarning("'use' expects a function");
    }
    return self();
}

QJSValue RequestPrototype::timeout(int ms)
{
    m_timeout = ms;
    return self();
}

QJSValue RequestPrototype::clearTimeout()
{
    m_timeout = -1;
    return self();
}

QJSValue RequestPrototype::abort()
{
    if (m_reply && m_reply->isRunning())
        m_reply->abort();
    return self();
}

QJSValue RequestPrototype::set(const QJSValue &field, const QJSValue &val)
{
    if (field.isObject()) {
        QJSValueIterator it(field);
        while (it.next()) {
            m_request->setRawHeader(
                        it.name().toUtf8(),
                        it.value().toString().toUtf8());
        }
    } else {
        m_request->setRawHeader(
                    field.toString().toUtf8(),
                    val.toString().toUtf8());
    }

    return self();
}

QJSValue RequestPrototype::unset(const QString &field)
{
    m_request->setRawHeader(
                field.toUtf8(),
                QByteArray());

    return self();
}

QJSValue RequestPrototype::type(const QJSValue &type)
{
    QString t = type.toString();
    if (contentTypes.contains(t)) {
        m_request->setHeader(QNetworkRequest::ContentTypeHeader,
                             contentTypes.value(t));
    } else {
        m_request->setHeader(QNetworkRequest::ContentTypeHeader, t);
    }
    return self();
}

QJSValue RequestPrototype::accept(const QJSValue &type)
{
    const QByteArray ACCEPT_HEADER("Accept");
    QByteArray t = type.toString().toUtf8();
    if (contentTypes.contains(t)) {
        m_request->setRawHeader(ACCEPT_HEADER, contentTypes.value(t));
    } else {
        m_request->setRawHeader(ACCEPT_HEADER, t);
    }
    return self();
}

QJSValue RequestPrototype::auth(const QString &user, const QString &password)
{
    const QByteArray AUTH_HEADER("Authorization");
    QByteArray value = QByteArray("Basic ").append(
                (user + ":" + password)
                .toUtf8()
                .toBase64(QByteArray::Base64UrlEncoding));

    m_request->setRawHeader(AUTH_HEADER, value);
    return self();
}

QJSValue RequestPrototype::redirects(int redirects)
{
    m_redirects = redirects;
    return self();
}

QJSValue RequestPrototype::query(const QJSValue &query)
{
    if (query.isObject()) {
        QJSValueIterator it(query);
        while (it.next()) {
            m_query.addQueryItem(
                        it.name(),
                        it.value().toString());
        }
    } else if (query.isString()) {
        QUrlQuery parsed(query.toString());
        QList<QPair<QString, QString> > items =
                parsed.queryItems(QUrl::FullyDecoded);
        QPair<QString, QString> pair;
        foreach(pair, items) {
            m_query.addQueryItem(pair.first, pair.second);
        }
    } else {
        qWarning("'query' expects an object or string");
    }

    return self();
}

QJSValue RequestPrototype::field(const QJSValue &name, const QJSValue &value)
{
    if (!m_multipart)
        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);

    QString dispositionHeader("form-data; name=\"");
    dispositionHeader += name.toString();
    dispositionHeader += "\";";

    QHttpPart field;
    field.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);
    field.setBody(value.toString().toUtf8());

    m_multipart->append(field);

    return self();
}

QJSValue RequestPrototype::attach(const QJSValue &name, const QJSValue &path,
                                  const QJSValue &filename)
{
    if (!m_multipart)
        m_multipart = new QHttpMultiPart(QHttpMultiPart::FormDataType, this);

    QString dispositionHeader("form-data; name=\"");
    dispositionHeader += name.toString();
    dispositionHeader += "\";";

    QFile *file = new QFile(path.toString(), m_multipart);

    if (!file->exists()) {
        qWarning("File does not exist");
        return self();
    }

    if (!file->open(QIODevice::ReadOnly)) {
        qWarning("Could not open file for reading");
        return self();
    }

    QFileInfo fileInfo(*file);

    QString fname = filename.isString() ? filename.toString() : fileInfo.fileName();
    dispositionHeader += " filename=\"" + fname + "\"";

    QHttpPart attachment;
    attachment.setHeader(QNetworkRequest::ContentDispositionHeader, dispositionHeader);

    // TODO: Move the mimeDB somewhere more static
    QMimeDatabase mimeDB;
    QString contentType = mimeDB.mimeTypeForFile(fileInfo).name();
    if (!contentType.isEmpty())
        attachment.setHeader(QNetworkRequest::ContentTypeHeader, QVariant(contentType));

    attachment.setBodyDevice(file);

    m_multipart->append(attachment);

    return self();
}

QJSValue RequestPrototype::send(const QJSValue &data)
{
    QByteArray type = m_request->header(QNetworkRequest::ContentTypeHeader)
            .toByteArray();

    if (data.isObject() && m_data.isObject()) {
        // merge with existing data
        QJSValueIterator it(data);
        while (it.next()) {
            m_data.setProperty(it.name(), it.value());
        }
    } else if(data.isString()) {
        if (type.isEmpty()) {
            type = contentTypes["form"];
        }
        if (type == contentTypes["form"]) {
            if (m_data.isString()) {
                m_data = QJSValue(m_data.toString() + "&" + data.toString());
            } else {
                m_data = data;
            }
        } else {
            if (m_data.isString()) {
                m_data = QJSValue(m_data.toString() + data.toString());
            } else {
                m_data = data;
            }
        }
    } else {
        m_data = data;
    }

    if (type.isEmpty())
        type = contentTypes["json"];

    m_request->setHeader(QNetworkRequest::ContentTypeHeader, type);

    return self();
}

QJSValue RequestPrototype::withCredentials()
{
    return self();
}

QJSValue RequestPrototype::end(QJSValue callback)
{
    m_callback = callback;

    dispatchRequest();

    return self();
}

QByteArray RequestPrototype::serializeData()
{
    QByteArray type = m_request->header(
                QNetworkRequest::ContentTypeHeader).toByteArray();

    if (type.contains(contentTypes["json"])) {
        JsonCodec json(m_engine);
        return json.stringify(m_data);
    }
    return m_data.toString().toUtf8();
}

void RequestPrototype::dispatchRequest()
{
    QUrl url = m_request->url();
    url.setQuery(m_query);
    m_request->setUrl(url);

    switch (m_method) {
    case Get:
        m_reply = m_network->get(*m_request);
        break;
    case Post:
        if (m_multipart) {
            m_reply = m_network->post(*m_request, m_multipart);
        } else {
            m_reply = m_network->post(*m_request, serializeData());
        }
        break;
    case Put:
        if (m_multipart) {
            m_reply = m_network->put(*m_request, m_multipart);
        } else {
            m_reply = m_network->put(*m_request, serializeData());
        }
        break;
    case Delete:
        m_reply = m_network->deleteResource(*m_request);
        break;
    case Patch:
        m_request->setAttribute(QNetworkRequest::CustomVerbAttribute, "PATCH");
        m_rawData = serializeData();
        m_reply = m_network->sendCustomRequest(*m_request, "PATCH",
                                               new QBuffer(&m_rawData, this));
        break;
    case Head:
        m_reply = m_network->head(*m_request);
        break;
    default:
        qWarning("Unsupported method");
    }

    emit started();

    connect(m_reply, SIGNAL(finished()), this, SLOT(handleFinished()));
#ifndef QT_NO_SSL
    connect(m_reply, SIGNAL(sslErrors(QList<QSslError>)),
            this, SLOT(handleSslErrors(QList<QSslError>)));
#endif

    if (m_timeout > 0)
        m_timer = startTimer(m_timeout);
}

void RequestPrototype::handleFinished()
{
    killTimer(m_timer);

    int status = m_reply->attribute(
                QNetworkRequest::HttpStatusCodeAttribute).toInt();
    QVariant redir = m_reply->attribute(
                QNetworkRequest::RedirectionTargetAttribute);

    if (redir.isValid()) {
        m_redirectCount++;
        if (m_redirectCount <= m_redirects) {
            QUrl location = m_request->url().resolved(redir.toUrl());
            if (location.scheme() == "file") {
                qWarning("Invalid redirect URL scheme");
                return;
            }

            QNetworkRequest *req = new QNetworkRequest(*m_request);
            req->setUrl(location);
            delete m_request;
            m_request = req;
            m_reply->deleteLater();
            m_reply = 0;

            if (status >= 301 && status <= 303) {
                if (m_method == Post) {
                    // TODO: Strip Content-* headers

                    // TODO: Strip send data

                    m_multipart = 0;
                }

                if (status == 303 || m_method != Head) {
                    m_method = Get;
                }
            } else if (status != 307 && status != 308) {
                // Don't change methods on 307/308
                qWarning("Unhandled redirect status code");
                return;
            }
            dispatchRequest();
            return;
        } else {
            m_error = createError("Too many redirects");
        }
    }

    if (!m_error.isError() && m_reply->error() != QNetworkReply::NoError) {
        m_error = createError(m_reply->errorString());
        m_error.setProperty("code", m_reply->error());
        if (status >= 400) {
            m_error.setProperty("status", status);
            // TODO: Add "method" property
        }
    }

    QJSValueList args;

    ResponsePrototype *rep = new ResponsePrototype(m_engine, m_reply);
    args << m_error << m_engine->newQObject(rep);

    if (m_callback.isCallable()) {
        m_callback.call(args);
    } else {
        qWarning() << QString("%1 is not callable").arg(m_callback.toString());
    }
}

QJSValue RequestPrototype::createError(const QString &message, ErrorType type)
{
    QString err;
    switch (type) {
    case RangeError:
        err = "RangeError";
        break;
    case ReferenceError:
        err = "ReferenceError";
        break;
    case SyntaxError:
        err = "SyntaxError";
        break;
    case TypeError:
        err = "TypeError";
        break;
    case URIError:
        err = "URIError";
        break;
    case InternalError:
        err = "InternalError";
        break;
    case Error:
    default:
        err = "Error";
    }

    QString script = "new %1('%2');";
    return m_engine->evaluate(script.arg(err).arg(message));
}

#ifndef QT_NO_SSL
void RequestPrototype::handleSslErrors(const QList<QSslError> &errors)
{

}
#endif

void RequestPrototype::timerEvent(QTimerEvent *)
{
    m_error = createError(QString("Timeout of %1 ms exceeded").arg(m_timeout));
    abort();
}

} } }
<|endoftext|>


<commit_before>#include <bits/stdc++.h>

const int MOD = 1000000000;

int main() {
    char *t = new char;
    srand(time(0) + (long long)t);
    delete t;
    register int n, m;
    n = rand() % MOD + 1, m = rand() % MOD + 1;
    while (std::__gcd(n, m) != 1) {
        n = rand() % MOD + 1, m = rand() % MOD + 1;
    }
    std::cout << n << ' ' << m << '\n';
    return 0;
}<commit_msg>BZOJ3337<commit_after>#include <bits/stdc++.h>
int a[100010];
int main() {
    register int n = 100000, q = 100000;
    std::cout << n << '\n';
    for (register int i = 1; i <= n; i++) {
        a[i] = i;
    }
    std::random_shuffle(a + 1, a + n + 1);
    for (register int i = 1; i < n; i++) {
        std::cout << a[i] << ' ';
    }
    std::cout << a[n] << '\n';
    std::cout << q << '\n';
    q /= 4;
    register int l[2] = {1, n / 2}, r[2] = {n / 2, n};
    const int LIMIT = (INT_MAX / n - 1) / 2;
    for (register int i = 1; i <= q; i++) {
        if (l[0] > r[0]) std::swap(l[0], r[0]);
        std::cout << "3 " << (l[0]++) << ' ' << (r[0]--) << '\n';
        if (l[1] > r[1]) std::swap(l[1], r[1]);
        std::cout << "5 " << (l[1]++) << ' ' << (r[1]--) << ' '
                  << i * 1234ll % LIMIT << '\n';
        register int s = i + n / 2, t = n * 3 / 4 - i;
        if (s > t) std::swap(s, t);
        std::cout << "9 " << s << ' ' << t << ' '
                  << i * 123456ll % (INT_MAX / 2) << '\n';
    }
    for (register int i = 1; i <= q; i++) {
        std::cout << "9 " << i << ' ' << n - i + 1 << ' '
                  << i * 123456ll % (INT_MAX / 2) << '\n';
    }
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2017 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <experimental/string_view>
#include <memory>
#include <optional>
#include <stdexcept>
#include <unordered_set>

#include <seastar/core/future.hh>
#include <seastar/core/print.hh>
#include <seastar/core/sstring.hh>

#include "auth/resource.hh"
#include "seastarx.hh"
#include "stdx.hh"

namespace auth {

struct role_config final {
    bool is_superuser{false};
    bool can_login{false};
};

// Differential update for altering existing roles.
struct role_config_update final {
    std::optional<bool> is_superuser{};
    std::optional<bool> can_login{};
};

// A logical argument error for a role-management operation.
class roles_argument_exception : public std::invalid_argument {
public:
    using std::invalid_argument::invalid_argument;
};

class role_already_exists : public roles_argument_exception {
    std::shared_ptr<sstring> _role_name;

public:
    explicit role_already_exists(stdx::string_view role_name)
            : roles_argument_exception(sprint("The '%s' role already exists.", role_name))
            , _role_name(std::make_shared<sstring>(role_name)) {
    }

    stdx::string_view role_name() const noexcept {
        return *_role_name;
    }
};

class nonexistant_role : public roles_argument_exception {
    std::shared_ptr<sstring> _role_name;

public:
    explicit nonexistant_role(stdx::string_view role_name)
            : roles_argument_exception(sprint("The role '%s' does not exist.", role_name))
            , _role_name(std::make_shared<sstring>(role_name)) {
    }

    stdx::string_view role_name() const noexcept {
        return *_role_name;
    }
};

class role_already_included : public roles_argument_exception {
    std::shared_ptr<sstring> _role_name, _grantee_name;

public:
    role_already_included(stdx::string_view grantee_name, stdx::string_view role_name)
            : roles_argument_exception(
                      sprint("'%s' already includes role '%s'.", grantee_name, role_name))
            , _role_name(std::make_shared<sstring>(role_name))
            , _grantee_name(std::make_shared<sstring>(grantee_name)) {
    }

    stdx::string_view role_name() const noexcept {
        return *_role_name;
    }

    stdx::string_view grantee_name() const noexcept {
        return *_grantee_name;
    }
};

class revoke_ungranted_role : public roles_argument_exception {
    std::shared_ptr<sstring> _role_name, _revokee_name;

public:
    revoke_ungranted_role(stdx::string_view revokee_name, stdx::string_view role_name)
            : roles_argument_exception(
                      sprint("'%s' was not granted role '%s', so it cannot be revoked.", revokee_name, role_name))
            , _role_name(std::make_shared<sstring>(role_name))
            , _revokee_name(std::make_shared<sstring>(revokee_name)) {
    }

    stdx::string_view role_name() const noexcept {
        return *_role_name;
    }

    stdx::string_view revokee_name() const noexcept {
        return *_revokee_name;
    }
};

enum class recursive_role_query { yes, no };

// Abstract role manager.
//
// All implementations should throw role-related exceptions as documented, but authorization-related checking is
// handled by the CQL layer, and not here.
class role_manager {
public:
    virtual ~role_manager() = default;

    virtual stdx::string_view qualified_java_name() const noexcept = 0;

    virtual future<> start() = 0;

    virtual future<> stop() = 0;

    // Must throw `role_already_exists` for a role that has previously been created.
    virtual future<> create(stdx::string_view role_name, const role_config&) = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<> drop(stdx::string_view role_name) = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<> alter(stdx::string_view role_name, const role_config_update&) = 0;

    // Grant `role_name` to `grantee_name`.
    //
    // Must throw `nonexistant_role` if either the role or the grantee do not exist.
    //
    // Must throw `role_already_included` if granting the role would be redundant, or create a cycle.
    virtual future<> grant(stdx::string_view grantee_name, stdx::string_view role_name) = 0;

    // Revoke `role_name` from `revokee_name`.
    //
    // Must throw `nonexistant_role` if either the role or the revokee do not exist.
    //
    // Must throw `revoke_ungranted_role` if the role was not granted.
    virtual future<> revoke(stdx::string_view revokee_name, stdx::string_view role_name) = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<std::unordered_set<sstring>> query_granted(stdx::string_view grantee, recursive_role_query) const = 0;

    virtual future<std::unordered_set<sstring>> query_all() const = 0;

    virtual future<bool> exists(stdx::string_view role_name) const = 0;

    /// Must throw `nonexistant_role` if the role does not exist.
    virtual future<bool> is_superuser(stdx::string_view role_name) const = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<bool> can_login(stdx::string_view role_name) const = 0;
};

}
<commit_msg>auth/role_manager: Remove unnecessary exn. info<commit_after>/*
 * Copyright (C) 2017 ScyllaDB
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <experimental/string_view>
#include <memory>
#include <optional>
#include <stdexcept>
#include <unordered_set>

#include <seastar/core/future.hh>
#include <seastar/core/print.hh>
#include <seastar/core/sstring.hh>

#include "auth/resource.hh"
#include "seastarx.hh"
#include "stdx.hh"

namespace auth {

struct role_config final {
    bool is_superuser{false};
    bool can_login{false};
};

// Differential update for altering existing roles.
struct role_config_update final {
    std::optional<bool> is_superuser{};
    std::optional<bool> can_login{};
};

// A logical argument error for a role-management operation.
class roles_argument_exception : public std::invalid_argument {
public:
    using std::invalid_argument::invalid_argument;
};

class role_already_exists : public roles_argument_exception {
public:
    explicit role_already_exists(stdx::string_view role_name)
            : roles_argument_exception(sprint("The '%s' role already exists.", role_name)) {
    }
};

class nonexistant_role : public roles_argument_exception {
public:
    explicit nonexistant_role(stdx::string_view role_name)
            : roles_argument_exception(sprint("The role '%s' does not exist.", role_name)) {
    }
};

class role_already_included : public roles_argument_exception {
public:
    role_already_included(stdx::string_view grantee_name, stdx::string_view role_name)
            : roles_argument_exception(
                      sprint("'%s' already includes role '%s'.", grantee_name, role_name)) {
    }
};

class revoke_ungranted_role : public roles_argument_exception {
public:
    revoke_ungranted_role(stdx::string_view revokee_name, stdx::string_view role_name)
            : roles_argument_exception(
                      sprint("'%s' was not granted role '%s', so it cannot be revoked.", revokee_name, role_name)) {
    }
};

enum class recursive_role_query { yes, no };

// Abstract role manager.
//
// All implementations should throw role-related exceptions as documented, but authorization-related checking is
// handled by the CQL layer, and not here.
class role_manager {
public:
    virtual ~role_manager() = default;

    virtual stdx::string_view qualified_java_name() const noexcept = 0;

    virtual future<> start() = 0;

    virtual future<> stop() = 0;

    // Must throw `role_already_exists` for a role that has previously been created.
    virtual future<> create(stdx::string_view role_name, const role_config&) = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<> drop(stdx::string_view role_name) = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<> alter(stdx::string_view role_name, const role_config_update&) = 0;

    // Grant `role_name` to `grantee_name`.
    //
    // Must throw `nonexistant_role` if either the role or the grantee do not exist.
    //
    // Must throw `role_already_included` if granting the role would be redundant, or create a cycle.
    virtual future<> grant(stdx::string_view grantee_name, stdx::string_view role_name) = 0;

    // Revoke `role_name` from `revokee_name`.
    //
    // Must throw `nonexistant_role` if either the role or the revokee do not exist.
    //
    // Must throw `revoke_ungranted_role` if the role was not granted.
    virtual future<> revoke(stdx::string_view revokee_name, stdx::string_view role_name) = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<std::unordered_set<sstring>> query_granted(stdx::string_view grantee, recursive_role_query) const = 0;

    virtual future<std::unordered_set<sstring>> query_all() const = 0;

    virtual future<bool> exists(stdx::string_view role_name) const = 0;

    /// Must throw `nonexistant_role` if the role does not exist.
    virtual future<bool> is_superuser(stdx::string_view role_name) const = 0;

    // Must throw `nonexistant_role` if the role does not exist.
    virtual future<bool> can_login(stdx::string_view role_name) const = 0;
};

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unoatrcn.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mib $ $Date: 2001-07-04 13:33:12 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

extern ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  SvUnoAttributeContainer_CreateInstance();

class SvXMLAttrContainerData;

class SvUnoAttributeContainer : public ::cppu::WeakAggImplHelper3<
                                            ::com::sun::star::lang::XServiceInfo,
                                            ::com::sun::star::lang::XUnoTunnel,
                                            ::com::sun::star::container::XNameContainer >
{
private:
    SvXMLAttrContainerData* mpContainer;

    sal_uInt16 getIndexByName(const ::rtl::OUString& aName ) const;

public:
    SvUnoAttributeContainer( SvXMLAttrContainerData* pContainer = NULL );
    virtual ~SvUnoAttributeContainer();

    SvXMLAttrContainerData* GetContainerImpl() const { return mpContainer; }

    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
    static SvUnoAttributeContainer* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xInt ) throw();
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::container::XElementAccess
    virtual ::com::sun::star::uno::Type  SAL_CALL getElementType(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL hasElements(void) throw( ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::container::XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName(const ::rtl::OUString& aName) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL hasByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::container::XNameReplace
    virtual void SAL_CALL replaceByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::container::XNameContainer
    virtual void SAL_CALL insertByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL removeByName(const ::rtl::OUString& Name) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::lang::XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService(const ::rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException );

    friend  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SvUnoAttributeContainer_CreateInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) throw( ::com::sun::star::uno::Exception );
};

<commit_msg>INTEGRATION: CWS sb25 (1.2.434); FILE MERGED 2004/11/15 16:44:49 sb 1.2.434.1: #i37077# Reduce number of exported symbols of xmloff dynamic library.<commit_after>/*************************************************************************
 *
 *  $RCSfile: unoatrcn.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-11 14:20:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_XMLOFF_DLLAPI_H
#include "xmloff/dllapi.h"
#endif

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase3.hxx>
#endif

extern ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >  SvUnoAttributeContainer_CreateInstance();

class SvXMLAttrContainerData;

class XMLOFF_DLLPUBLIC SvUnoAttributeContainer:
    public ::cppu::WeakAggImplHelper3<
        ::com::sun::star::lang::XServiceInfo,
        ::com::sun::star::lang::XUnoTunnel,
        ::com::sun::star::container::XNameContainer >
{
private:
    SvXMLAttrContainerData* mpContainer;

    SAL_DLLPRIVATE sal_uInt16 getIndexByName(const ::rtl::OUString& aName )
        const;

public:
    SvUnoAttributeContainer( SvXMLAttrContainerData* pContainer = NULL );
    virtual ~SvUnoAttributeContainer();

    SvXMLAttrContainerData* GetContainerImpl() const { return mpContainer; }

    static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId() throw();
    static SvUnoAttributeContainer* getImplementation( ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > xInt ) throw();
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);

    // ::com::sun::star::container::XElementAccess
    virtual ::com::sun::star::uno::Type  SAL_CALL getElementType(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL hasElements(void) throw( ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::container::XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName(const ::rtl::OUString& aName) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL hasByName(const ::rtl::OUString& aName) throw( ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::container::XNameReplace
    virtual void SAL_CALL replaceByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::container::XNameContainer
    virtual void SAL_CALL insertByName(const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement) throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL removeByName(const ::rtl::OUString& Name) throw( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException );

    // ::com::sun::star::lang::XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService(const ::rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException );

    friend  ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SvUnoAttributeContainer_CreateInstance( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > & rSMgr ) throw( ::com::sun::star::uno::Exception );
};

<|endoftext|>


<commit_before>//===- FuzzerIO.cpp - IO utils. -------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// IO functions.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <iterator>
#include <fstream>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>

namespace fuzzer {

static long GetEpoch(const std::string &Path) {
  struct stat St;
  if (stat(Path.c_str(), &St)) {
    Printf("Can not stat: %s; exiting\n", Path.c_str());
    exit(1);
  }
  return St.st_mtime;
}

static std::vector<std::string> ListFilesInDir(const std::string &Dir,
                                               long *Epoch) {
  std::vector<std::string> V;
  if (Epoch) {
    auto E = GetEpoch(Dir.c_str());
    if (*Epoch >= E) return V;
    *Epoch = E;
  }
  DIR *D = opendir(Dir.c_str());
  if (!D) {
    Printf("No such directory: %s; exiting\n", Dir.c_str());
    exit(1);
  }
  while (auto E = readdir(D)) {
    if (E->d_type == DT_REG || E->d_type == DT_LNK)
      V.push_back(E->d_name);
  }
  closedir(D);
  return V;
}

Unit FileToVector(const std::string &Path) {
  std::ifstream T(Path);
  return Unit((std::istreambuf_iterator<char>(T)),
              std::istreambuf_iterator<char>());
}

std::string FileToString(const std::string &Path) {
  std::ifstream T(Path);
  return std::string((std::istreambuf_iterator<char>(T)),
                     std::istreambuf_iterator<char>());
}

void CopyFileToErr(const std::string &Path) {
  Printf("%s", FileToString(Path).c_str());
}

void WriteToFile(const Unit &U, const std::string &Path) {
  // Use raw C interface because this function may be called from a sig handler.
  FILE *Out = fopen(Path.c_str(), "w");
  if (!Out) return;
  fwrite(U.data(), sizeof(U[0]), U.size(), Out);
  fclose(Out);
}

void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
                            long *Epoch) {
  long E = Epoch ? *Epoch : 0;
  for (auto &X : ListFilesInDir(Path, Epoch)) {
    auto FilePath = DirPlusFile(Path, X);
    if (Epoch && GetEpoch(FilePath) < E) continue;
    V->push_back(FileToVector(FilePath));
  }
}

std::string DirPlusFile(const std::string &DirPath,
                        const std::string &FileName) {
  return DirPath + "/" + FileName;
}

void PrintFileAsBase64(const std::string &Path) {
  std::string Cmd = "base64 -w 0 < " + Path + "; echo";
  ExecuteCommand(Cmd);
}

void Printf(const char *Fmt, ...) {
  va_list ap;
  va_start(ap, Fmt);
  vfprintf(stderr, Fmt, ap);
  va_end(ap);
}

}  // namespace fuzzer
<commit_msg>[libFuzzer] fix minor inefficiency, PR24584<commit_after>//===- FuzzerIO.cpp - IO utils. -------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// IO functions.
//===----------------------------------------------------------------------===//
#include "FuzzerInternal.h"
#include <iterator>
#include <fstream>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cstdio>

namespace fuzzer {

static long GetEpoch(const std::string &Path) {
  struct stat St;
  if (stat(Path.c_str(), &St)) {
    Printf("Can not stat: %s; exiting\n", Path.c_str());
    exit(1);
  }
  return St.st_mtime;
}

static std::vector<std::string> ListFilesInDir(const std::string &Dir,
                                               long *Epoch) {
  std::vector<std::string> V;
  if (Epoch) {
    auto E = GetEpoch(Dir);
    if (*Epoch >= E) return V;
    *Epoch = E;
  }
  DIR *D = opendir(Dir.c_str());
  if (!D) {
    Printf("No such directory: %s; exiting\n", Dir.c_str());
    exit(1);
  }
  while (auto E = readdir(D)) {
    if (E->d_type == DT_REG || E->d_type == DT_LNK)
      V.push_back(E->d_name);
  }
  closedir(D);
  return V;
}

Unit FileToVector(const std::string &Path) {
  std::ifstream T(Path);
  return Unit((std::istreambuf_iterator<char>(T)),
              std::istreambuf_iterator<char>());
}

std::string FileToString(const std::string &Path) {
  std::ifstream T(Path);
  return std::string((std::istreambuf_iterator<char>(T)),
                     std::istreambuf_iterator<char>());
}

void CopyFileToErr(const std::string &Path) {
  Printf("%s", FileToString(Path).c_str());
}

void WriteToFile(const Unit &U, const std::string &Path) {
  // Use raw C interface because this function may be called from a sig handler.
  FILE *Out = fopen(Path.c_str(), "w");
  if (!Out) return;
  fwrite(U.data(), sizeof(U[0]), U.size(), Out);
  fclose(Out);
}

void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V,
                            long *Epoch) {
  long E = Epoch ? *Epoch : 0;
  for (auto &X : ListFilesInDir(Path, Epoch)) {
    auto FilePath = DirPlusFile(Path, X);
    if (Epoch && GetEpoch(FilePath) < E) continue;
    V->push_back(FileToVector(FilePath));
  }
}

std::string DirPlusFile(const std::string &DirPath,
                        const std::string &FileName) {
  return DirPath + "/" + FileName;
}

void PrintFileAsBase64(const std::string &Path) {
  std::string Cmd = "base64 -w 0 < " + Path + "; echo";
  ExecuteCommand(Cmd);
}

void Printf(const char *Fmt, ...) {
  va_list ap;
  va_start(ap, Fmt);
  vfprintf(stderr, Fmt, ap);
  va_end(ap);
}

}  // namespace fuzzer
<|endoftext|>


<commit_before>//======- ParsedAttr.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ParsedAttr class implementation
//
//===----------------------------------------------------------------------===//

#include "clang/Sema/ParsedAttr.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/AttrSubjectMatchRules.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include <cassert>
#include <cstddef>
#include <utility>

using namespace clang;

IdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,
                                     IdentifierInfo *Ident) {
  IdentifierLoc *Result = new (Ctx) IdentifierLoc;
  Result->Loc = Loc;
  Result->Ident = Ident;
  return Result;
}

size_t ParsedAttr::allocated_size() const {
  if (IsAvailability) return AttributeFactory::AvailabilityAllocSize;
  else if (IsTypeTagForDatatype)
    return AttributeFactory::TypeTagForDatatypeAllocSize;
  else if (IsProperty)
    return AttributeFactory::PropertyAllocSize;
  else if (HasParsedType)
    return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
                            detail::TypeTagForDatatypeData, ParsedType,
                            detail::PropertyData>(0, 0, 0, 1, 0);
  return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
                          detail::TypeTagForDatatypeData, ParsedType,
                          detail::PropertyData>(NumArgs, 0, 0, 0, 0);
}

AttributeFactory::AttributeFactory() {
  // Go ahead and configure all the inline capacity.  This is just a memset.
  FreeLists.resize(InlineFreeListsCapacity);
}
AttributeFactory::~AttributeFactory() = default;

static size_t getFreeListIndexForSize(size_t size) {
  assert(size >= sizeof(ParsedAttr));
  assert((size % sizeof(void*)) == 0);
  return ((size - sizeof(ParsedAttr)) / sizeof(void *));
}

void *AttributeFactory::allocate(size_t size) {
  // Check for a previously reclaimed attribute.
  size_t index = getFreeListIndexForSize(size);
  if (index < FreeLists.size() && !FreeLists[index].empty()) {
    ParsedAttr *attr = FreeLists[index].back();
    FreeLists[index].pop_back();
    return attr;
  }

  // Otherwise, allocate something new.
  return Alloc.Allocate(size, alignof(AttributeFactory));
}

void AttributeFactory::deallocate(ParsedAttr *Attr) {
  size_t size = Attr->allocated_size();
  size_t freeListIndex = getFreeListIndexForSize(size);

  // Expand FreeLists to the appropriate size, if required.
  if (freeListIndex >= FreeLists.size())
    FreeLists.resize(freeListIndex + 1);

#if !NDEBUG
  // In debug mode, zero out the attribute to help find memory overwriting.
  memset(Attr, 0, size);
#endif

  // Add 'Attr' to the appropriate free-list.
  FreeLists[freeListIndex].push_back(Attr);
}

void AttributeFactory::reclaimPool(AttributePool &cur) {
  for (ParsedAttr *AL : cur.Attrs)
    deallocate(AL);
}

void AttributePool::takePool(AttributePool &pool) {
  Attrs.insert(Attrs.end(), pool.Attrs.begin(), pool.Attrs.end());
  pool.Attrs.clear();
}

#include "clang/Sema/AttrParsedAttrKinds.inc"

static StringRef normalizeAttrName(StringRef AttrName, StringRef ScopeName,
                                   ParsedAttr::Syntax SyntaxUsed) {
  // Normalize the attribute name, __foo__ becomes foo. This is only allowable
  // for GNU attributes.
  bool IsGNU = SyntaxUsed == ParsedAttr::AS_GNU ||
               ((SyntaxUsed == ParsedAttr::AS_CXX11 ||
                 SyntaxUsed == ParsedAttr::AS_C2x) &&
                ScopeName == "gnu");
  if (IsGNU && AttrName.size() >= 4 && AttrName.startswith("__") &&
      AttrName.endswith("__"))
    AttrName = AttrName.slice(2, AttrName.size() - 2);

  return AttrName;
}

ParsedAttr::Kind ParsedAttr::getKind(const IdentifierInfo *Name,
                                     const IdentifierInfo *ScopeName,
                                     Syntax SyntaxUsed) {
  StringRef AttrName = Name->getName();

  SmallString<64> FullName;
  if (ScopeName)
    FullName += ScopeName->getName();

  AttrName = normalizeAttrName(AttrName, FullName, SyntaxUsed);

  // Ensure that in the case of C++11 attributes, we look for '::foo' if it is
  // unscoped.
  if (ScopeName || SyntaxUsed == AS_CXX11 || SyntaxUsed == AS_C2x)
    FullName += "::";
  FullName += AttrName;

  return ::getAttrKind(FullName, SyntaxUsed);
}

unsigned ParsedAttr::getAttributeSpellingListIndex() const {
  // Both variables will be used in tablegen generated
  // attribute spell list index matching code.
  StringRef Scope = ScopeName ? ScopeName->getName() : "";
  StringRef Name = normalizeAttrName(AttrName->getName(), Scope,
                                     (ParsedAttr::Syntax)SyntaxUsed);

#include "clang/Sema/AttrSpellingListIndex.inc"

}

struct ParsedAttrInfo {
  unsigned NumArgs : 4;
  unsigned OptArgs : 4;
  unsigned HasCustomParsing : 1;
  unsigned IsTargetSpecific : 1;
  unsigned IsType : 1;
  unsigned IsStmt : 1;
  unsigned IsKnownToGCC : 1;
  unsigned IsSupportedByPragmaAttribute : 1;

  bool (*DiagAppertainsToDecl)(Sema &S, const ParsedAttr &Attr, const Decl *);
  bool (*DiagLangOpts)(Sema &S, const ParsedAttr &Attr);
  bool (*ExistsInTarget)(const TargetInfo &Target);
  unsigned (*SpellingIndexToSemanticSpelling)(const ParsedAttr &Attr);
  void (*GetPragmaAttributeMatchRules)(
      llvm::SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &Rules,
      const LangOptions &LangOpts);
};

namespace {

#include "clang/Sema/AttrParsedAttrImpl.inc"

} // namespace

static const ParsedAttrInfo &getInfo(const ParsedAttr &A) {
  return AttrInfoMap[A.getKind()];
}

unsigned ParsedAttr::getMinArgs() const { return getInfo(*this).NumArgs; }

unsigned ParsedAttr::getMaxArgs() const {
  return getMinArgs() + getInfo(*this).OptArgs;
}

bool ParsedAttr::hasCustomParsing() const {
  return getInfo(*this).HasCustomParsing;
}

bool ParsedAttr::diagnoseAppertainsTo(Sema &S, const Decl *D) const {
  return getInfo(*this).DiagAppertainsToDecl(S, *this, D);
}

bool ParsedAttr::appliesToDecl(const Decl *D,
                               attr::SubjectMatchRule MatchRule) const {
  return checkAttributeMatchRuleAppliesTo(D, MatchRule);
}

void ParsedAttr::getMatchRules(
    const LangOptions &LangOpts,
    SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &MatchRules)
    const {
  return getInfo(*this).GetPragmaAttributeMatchRules(MatchRules, LangOpts);
}

bool ParsedAttr::diagnoseLangOpts(Sema &S) const {
  return getInfo(*this).DiagLangOpts(S, *this);
}

bool ParsedAttr::isTargetSpecificAttr() const {
  return getInfo(*this).IsTargetSpecific;
}

bool ParsedAttr::isTypeAttr() const { return getInfo(*this).IsType; }

bool ParsedAttr::isStmtAttr() const { return getInfo(*this).IsStmt; }

bool ParsedAttr::existsInTarget(const TargetInfo &Target) const {
  return getInfo(*this).ExistsInTarget(Target);
}

bool ParsedAttr::isKnownToGCC() const { return getInfo(*this).IsKnownToGCC; }

bool ParsedAttr::isSupportedByPragmaAttribute() const {
  return getInfo(*this).IsSupportedByPragmaAttribute;
}

unsigned ParsedAttr::getSemanticSpelling() const {
  return getInfo(*this).SpellingIndexToSemanticSpelling(*this);
}

bool ParsedAttr::hasVariadicArg() const {
  // If the attribute has the maximum number of optional arguments, we will
  // claim that as being variadic. If we someday get an attribute that
  // legitimately bumps up against that maximum, we can use another bit to track
  // whether it's truly variadic or not.
  return getInfo(*this).OptArgs == 15;
}
<commit_msg>Fix Wundef NDEBUG warning; NFC<commit_after>//======- ParsedAttr.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the ParsedAttr class implementation
//
//===----------------------------------------------------------------------===//

#include "clang/Sema/ParsedAttr.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/AttrSubjectMatchRules.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include <cassert>
#include <cstddef>
#include <utility>

using namespace clang;

IdentifierLoc *IdentifierLoc::create(ASTContext &Ctx, SourceLocation Loc,
                                     IdentifierInfo *Ident) {
  IdentifierLoc *Result = new (Ctx) IdentifierLoc;
  Result->Loc = Loc;
  Result->Ident = Ident;
  return Result;
}

size_t ParsedAttr::allocated_size() const {
  if (IsAvailability) return AttributeFactory::AvailabilityAllocSize;
  else if (IsTypeTagForDatatype)
    return AttributeFactory::TypeTagForDatatypeAllocSize;
  else if (IsProperty)
    return AttributeFactory::PropertyAllocSize;
  else if (HasParsedType)
    return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
                            detail::TypeTagForDatatypeData, ParsedType,
                            detail::PropertyData>(0, 0, 0, 1, 0);
  return totalSizeToAlloc<ArgsUnion, detail::AvailabilityData,
                          detail::TypeTagForDatatypeData, ParsedType,
                          detail::PropertyData>(NumArgs, 0, 0, 0, 0);
}

AttributeFactory::AttributeFactory() {
  // Go ahead and configure all the inline capacity.  This is just a memset.
  FreeLists.resize(InlineFreeListsCapacity);
}
AttributeFactory::~AttributeFactory() = default;

static size_t getFreeListIndexForSize(size_t size) {
  assert(size >= sizeof(ParsedAttr));
  assert((size % sizeof(void*)) == 0);
  return ((size - sizeof(ParsedAttr)) / sizeof(void *));
}

void *AttributeFactory::allocate(size_t size) {
  // Check for a previously reclaimed attribute.
  size_t index = getFreeListIndexForSize(size);
  if (index < FreeLists.size() && !FreeLists[index].empty()) {
    ParsedAttr *attr = FreeLists[index].back();
    FreeLists[index].pop_back();
    return attr;
  }

  // Otherwise, allocate something new.
  return Alloc.Allocate(size, alignof(AttributeFactory));
}

void AttributeFactory::deallocate(ParsedAttr *Attr) {
  size_t size = Attr->allocated_size();
  size_t freeListIndex = getFreeListIndexForSize(size);

  // Expand FreeLists to the appropriate size, if required.
  if (freeListIndex >= FreeLists.size())
    FreeLists.resize(freeListIndex + 1);

#ifndef NDEBUG
  // In debug mode, zero out the attribute to help find memory overwriting.
  memset(Attr, 0, size);
#endif

  // Add 'Attr' to the appropriate free-list.
  FreeLists[freeListIndex].push_back(Attr);
}

void AttributeFactory::reclaimPool(AttributePool &cur) {
  for (ParsedAttr *AL : cur.Attrs)
    deallocate(AL);
}

void AttributePool::takePool(AttributePool &pool) {
  Attrs.insert(Attrs.end(), pool.Attrs.begin(), pool.Attrs.end());
  pool.Attrs.clear();
}

#include "clang/Sema/AttrParsedAttrKinds.inc"

static StringRef normalizeAttrName(StringRef AttrName, StringRef ScopeName,
                                   ParsedAttr::Syntax SyntaxUsed) {
  // Normalize the attribute name, __foo__ becomes foo. This is only allowable
  // for GNU attributes.
  bool IsGNU = SyntaxUsed == ParsedAttr::AS_GNU ||
               ((SyntaxUsed == ParsedAttr::AS_CXX11 ||
                 SyntaxUsed == ParsedAttr::AS_C2x) &&
                ScopeName == "gnu");
  if (IsGNU && AttrName.size() >= 4 && AttrName.startswith("__") &&
      AttrName.endswith("__"))
    AttrName = AttrName.slice(2, AttrName.size() - 2);

  return AttrName;
}

ParsedAttr::Kind ParsedAttr::getKind(const IdentifierInfo *Name,
                                     const IdentifierInfo *ScopeName,
                                     Syntax SyntaxUsed) {
  StringRef AttrName = Name->getName();

  SmallString<64> FullName;
  if (ScopeName)
    FullName += ScopeName->getName();

  AttrName = normalizeAttrName(AttrName, FullName, SyntaxUsed);

  // Ensure that in the case of C++11 attributes, we look for '::foo' if it is
  // unscoped.
  if (ScopeName || SyntaxUsed == AS_CXX11 || SyntaxUsed == AS_C2x)
    FullName += "::";
  FullName += AttrName;

  return ::getAttrKind(FullName, SyntaxUsed);
}

unsigned ParsedAttr::getAttributeSpellingListIndex() const {
  // Both variables will be used in tablegen generated
  // attribute spell list index matching code.
  StringRef Scope = ScopeName ? ScopeName->getName() : "";
  StringRef Name = normalizeAttrName(AttrName->getName(), Scope,
                                     (ParsedAttr::Syntax)SyntaxUsed);

#include "clang/Sema/AttrSpellingListIndex.inc"

}

struct ParsedAttrInfo {
  unsigned NumArgs : 4;
  unsigned OptArgs : 4;
  unsigned HasCustomParsing : 1;
  unsigned IsTargetSpecific : 1;
  unsigned IsType : 1;
  unsigned IsStmt : 1;
  unsigned IsKnownToGCC : 1;
  unsigned IsSupportedByPragmaAttribute : 1;

  bool (*DiagAppertainsToDecl)(Sema &S, const ParsedAttr &Attr, const Decl *);
  bool (*DiagLangOpts)(Sema &S, const ParsedAttr &Attr);
  bool (*ExistsInTarget)(const TargetInfo &Target);
  unsigned (*SpellingIndexToSemanticSpelling)(const ParsedAttr &Attr);
  void (*GetPragmaAttributeMatchRules)(
      llvm::SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &Rules,
      const LangOptions &LangOpts);
};

namespace {

#include "clang/Sema/AttrParsedAttrImpl.inc"

} // namespace

static const ParsedAttrInfo &getInfo(const ParsedAttr &A) {
  return AttrInfoMap[A.getKind()];
}

unsigned ParsedAttr::getMinArgs() const { return getInfo(*this).NumArgs; }

unsigned ParsedAttr::getMaxArgs() const {
  return getMinArgs() + getInfo(*this).OptArgs;
}

bool ParsedAttr::hasCustomParsing() const {
  return getInfo(*this).HasCustomParsing;
}

bool ParsedAttr::diagnoseAppertainsTo(Sema &S, const Decl *D) const {
  return getInfo(*this).DiagAppertainsToDecl(S, *this, D);
}

bool ParsedAttr::appliesToDecl(const Decl *D,
                               attr::SubjectMatchRule MatchRule) const {
  return checkAttributeMatchRuleAppliesTo(D, MatchRule);
}

void ParsedAttr::getMatchRules(
    const LangOptions &LangOpts,
    SmallVectorImpl<std::pair<attr::SubjectMatchRule, bool>> &MatchRules)
    const {
  return getInfo(*this).GetPragmaAttributeMatchRules(MatchRules, LangOpts);
}

bool ParsedAttr::diagnoseLangOpts(Sema &S) const {
  return getInfo(*this).DiagLangOpts(S, *this);
}

bool ParsedAttr::isTargetSpecificAttr() const {
  return getInfo(*this).IsTargetSpecific;
}

bool ParsedAttr::isTypeAttr() const { return getInfo(*this).IsType; }

bool ParsedAttr::isStmtAttr() const { return getInfo(*this).IsStmt; }

bool ParsedAttr::existsInTarget(const TargetInfo &Target) const {
  return getInfo(*this).ExistsInTarget(Target);
}

bool ParsedAttr::isKnownToGCC() const { return getInfo(*this).IsKnownToGCC; }

bool ParsedAttr::isSupportedByPragmaAttribute() const {
  return getInfo(*this).IsSupportedByPragmaAttribute;
}

unsigned ParsedAttr::getSemanticSpelling() const {
  return getInfo(*this).SpellingIndexToSemanticSpelling(*this);
}

bool ParsedAttr::hasVariadicArg() const {
  // If the attribute has the maximum number of optional arguments, we will
  // claim that as being variadic. If we someday get an attribute that
  // legitimately bumps up against that maximum, we can use another bit to track
  // whether it's truly variadic or not.
  return getInfo(*this).OptArgs == 15;
}
<|endoftext|>


<commit_before>//===========================================
//  PC-BSD source code
//  Copyright (c) 2016, PC-BSD Software/iXsystems
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "mainUI.h"
#include "ui_mainUI.h"

// === PUBLIC ===
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
  ui->setupUi(this); //load the designer form
  ui->stackedWidget->setCurrentWidget(ui->page_auth);
  InitializeUI();
}

MainUI::~MainUI(){

}
// === PRIVATE ===
void MainUI::InitializeUI(){
  //First load any pre-existing settings
  bool haslocalhost = S_CORE->localhostAvailable();
  ui->actionLocalhost_Auto_Connect->setVisible(haslocalhost);
  ui->actionLocalhost_Auto_Connect->setEnabled(haslocalhost);
  ui->actionLocalhost_Auto_Connect->setChecked(false);
  if(haslocalhost){
    ui->actionLocalhost_Auto_Connect->setChecked(settings->value("auto-auth-localhost",true).toBool());
    ui->line_auth_host->setText("localhost");
    //Also load the currently-running user for this process and place that into the UI automatically
    //Note: This will only be valid on FreeBSD systems (since the server is only for FreeBSD)
    #ifdef __FreeBSD__
    #include <sys/types.h>
    #include <unistd.h>
    ui->line_auth_user->setText( getlogin() );
    #endif
    if(!ui->line_auth_user->text().isEmpty()){ ui->line_auth_pass->setFocus();  }
    else{ ui->line_auth_user->setFocus(); }
  }else{
    ui->line_auth_host->setFocus();
  }

  //Now setup the signals/slots
  connect(S_CORE, SIGNAL(clientAuthorized()), this, SLOT(Authorized()) );
  connect(S_CORE, SIGNAL(clientUnauthorized()), this, SLOT(NoAuthorization()) );
  connect(S_CORE, SIGNAL(clientDisconnected()), this, SLOT(NoAuthorization()) );
  connect(S_CORE, SIGNAL(newReply(QString,QString,QString,QJsonValue)), this, SLOT( NewMessage(QString,QString,QString,QJsonValue)) );
  connect(ui->line_auth_pass, SIGNAL(returnPressed()), this, SLOT(auth_connect()) );
  connect(ui->push_auth_connect, SIGNAL(clicked()), this, SLOT(auth_connect()) );
  connect(ui->actionClose_Application, SIGNAL(triggered()), this, SLOT(close()) );
  connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(auth_disconnect()) );
  connect(ui->actionLocalhost_Auto_Connect, SIGNAL(triggered()), this, SLOT(auto_local_auth_changed()) );

  //Now Run any automatic auth routines
  if(!ui->line_auth_user->text().isEmpty() && ui->actionLocalhost_Auto_Connect->isChecked() ){
    QTimer::singleShot(0,this, SLOT(auth_connect()) );
  }
}

// === PRIVATE SLOTS ===
//UI Signals
void MainUI::auth_connect(){
  qDebug() << " UI Start Connection";
  S_CORE->openConnection(ui->line_auth_user->text(), ui->line_auth_pass->text(), ui->line_auth_host->text() );
  ui->line_auth_pass->clear();
}

void MainUI::auth_disconnect(){
  qDebug() << "UI Closing Connection";
  S_CORE->closeConnection();
}

void MainUI::auto_local_auth_changed(){
  settings->setValue("auto-auth-localhost",  ui->actionLocalhost_Auto_Connect->isChecked());
}

// Temporary Test Functions
void MainUI::on_push_tmp_sendmsg_clicked(){
  //QString args = QJsonDocument::fromJson(ui->line_tmp_json->text()).object();
  QJsonValue args;
  QString txt = ui->line_tmp_json->text();
  if(txt.startsWith("{")){ args = QJsonDocument::fromJson(txt.toUtf8()).object(); }
  else if(txt.startsWith("[")){ args = QJsonDocument::fromJson(txt.toUtf8()).array(); }
  else{ args = QJsonValue(txt); }
  S_CORE->communicate("sampleID", ui->line_tmp_namesp->text(), ui->line_tmp_name->text(), args );
}

void MainUI::NewMessage(QString id, QString ns, QString nm, QJsonValue args){
  qDebug() << "New Message:" << id << ns << nm << args;
  ui->label_tmp_reply->setText(QJsonDocument(args.toObject()).toJson() );
}

//Core Signals
void MainUI::NoAuthorization(){
  qDebug() << "Lost Server authentication";
  ui->stackedWidget->setCurrentWidget(ui->page_auth);
  ui->line_auth_user->clear();
}

void MainUI::Authorized(){
  qDebug() << "Got Server Authentication";
  ui->stackedWidget->setCurrentWidget(ui->page_main);
}
<commit_msg>Move includes to top<commit_after>//===========================================
//  PC-BSD source code
//  Copyright (c) 2016, PC-BSD Software/iXsystems
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "mainUI.h"
#include "ui_mainUI.h"

#ifdef __FreeBSD__
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif

// === PUBLIC ===
MainUI::MainUI() : QMainWindow(), ui(new Ui::MainUI){
  ui->setupUi(this); //load the designer form
  ui->stackedWidget->setCurrentWidget(ui->page_auth);
  InitializeUI();
}

MainUI::~MainUI(){

}
// === PRIVATE ===
void MainUI::InitializeUI(){
  //First load any pre-existing settings
  bool haslocalhost = S_CORE->localhostAvailable();
  ui->actionLocalhost_Auto_Connect->setVisible(haslocalhost);
  ui->actionLocalhost_Auto_Connect->setEnabled(haslocalhost);
  ui->actionLocalhost_Auto_Connect->setChecked(false);
  if(haslocalhost){
    ui->actionLocalhost_Auto_Connect->setChecked(settings->value("auto-auth-localhost",true).toBool());
    ui->line_auth_host->setText("localhost");
    //Also load the currently-running user for this process and place that into the UI automatically
    //Note: This will only be valid on FreeBSD systems (since the server is only for FreeBSD)
    #ifdef __FreeBSD__
    ui->line_auth_user->setText( getlogin() );
    #endif
    if(!ui->line_auth_user->text().isEmpty()){ ui->line_auth_pass->setFocus();  }
    else{ ui->line_auth_user->setFocus(); }
  }else{
    ui->line_auth_host->setFocus();
  }

  //Now setup the signals/slots
  connect(S_CORE, SIGNAL(clientAuthorized()), this, SLOT(Authorized()) );
  connect(S_CORE, SIGNAL(clientUnauthorized()), this, SLOT(NoAuthorization()) );
  connect(S_CORE, SIGNAL(clientDisconnected()), this, SLOT(NoAuthorization()) );
  connect(S_CORE, SIGNAL(newReply(QString,QString,QString,QJsonValue)), this, SLOT( NewMessage(QString,QString,QString,QJsonValue)) );
  connect(ui->line_auth_pass, SIGNAL(returnPressed()), this, SLOT(auth_connect()) );
  connect(ui->push_auth_connect, SIGNAL(clicked()), this, SLOT(auth_connect()) );
  connect(ui->actionClose_Application, SIGNAL(triggered()), this, SLOT(close()) );
  connect(ui->actionDisconnect, SIGNAL(triggered()), this, SLOT(auth_disconnect()) );
  connect(ui->actionLocalhost_Auto_Connect, SIGNAL(triggered()), this, SLOT(auto_local_auth_changed()) );

  //Now Run any automatic auth routines
  if(!ui->line_auth_user->text().isEmpty() && ui->actionLocalhost_Auto_Connect->isChecked() ){
    QTimer::singleShot(0,this, SLOT(auth_connect()) );
  }
}

// === PRIVATE SLOTS ===
//UI Signals
void MainUI::auth_connect(){
  qDebug() << " UI Start Connection";
  S_CORE->openConnection(ui->line_auth_user->text(), ui->line_auth_pass->text(), ui->line_auth_host->text() );
  ui->line_auth_pass->clear();
}

void MainUI::auth_disconnect(){
  qDebug() << "UI Closing Connection";
  S_CORE->closeConnection();
}

void MainUI::auto_local_auth_changed(){
  settings->setValue("auto-auth-localhost",  ui->actionLocalhost_Auto_Connect->isChecked());
}

// Temporary Test Functions
void MainUI::on_push_tmp_sendmsg_clicked(){
  //QString args = QJsonDocument::fromJson(ui->line_tmp_json->text()).object();
  QJsonValue args;
  QString txt = ui->line_tmp_json->text();
  if(txt.startsWith("{")){ args = QJsonDocument::fromJson(txt.toUtf8()).object(); }
  else if(txt.startsWith("[")){ args = QJsonDocument::fromJson(txt.toUtf8()).array(); }
  else{ args = QJsonValue(txt); }
  S_CORE->communicate("sampleID", ui->line_tmp_namesp->text(), ui->line_tmp_name->text(), args );
}

void MainUI::NewMessage(QString id, QString ns, QString nm, QJsonValue args){
  qDebug() << "New Message:" << id << ns << nm << args;
  ui->label_tmp_reply->setText(QJsonDocument(args.toObject()).toJson() );
}

//Core Signals
void MainUI::NoAuthorization(){
  qDebug() << "Lost Server authentication";
  ui->stackedWidget->setCurrentWidget(ui->page_auth);
  ui->line_auth_user->clear();
}

void MainUI::Authorized(){
  qDebug() << "Got Server Authentication";
  ui->stackedWidget->setCurrentWidget(ui->page_main);
}
<|endoftext|>