<commit_before>/*
 * Copyright © 2017 Mozilla Foundation
 *
 * This program is made available under an ISC-style license.  See the
 * accompanying file LICENSE for details.
 */

#include "gtest/gtest.h"
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <atomic>
#include "cubeb/cubeb.h"
#include "common.h"

#define SAMPLE_FREQUENCY 48000
#if (defined(_WIN32) || defined(__WIN32__))
#define STREAM_FORMAT CUBEB_SAMPLE_FLOAT32LE
#else
#define STREAM_FORMAT CUBEB_SAMPLE_S16LE
#endif

std::atomic<bool> load_callback{ false };

long data_cb(cubeb_stream * stream, void * user, const void * inputbuffer, void * outputbuffer, long nframes)
{
  if (load_callback) {
    printf("Sleeping...\n");
    delay(100000);
    printf("Sleeping done\n");
  }
  return nframes;
}

void state_cb(cubeb_stream * stream, void * /*user*/, cubeb_state state)
{
  ASSERT_TRUE(!!stream);

  switch (state) {
  case CUBEB_STATE_STARTED:
    printf("stream started\n"); break;
  case CUBEB_STATE_STOPPED:
    printf("stream stopped\n"); break;
  case CUBEB_STATE_DRAINED:
    FAIL() << "this test is not supposed to drain"; break;
  case CUBEB_STATE_ERROR:
    printf("stream error\n"); break;
  default:
    FAIL() << "this test is not supposed to have a weird state"; break;
  }
}

TEST(cubeb, overload_callback)
{
  cubeb * ctx;
  cubeb_stream * stream;
  cubeb_stream_params output_params;
  int r;
  uint32_t latency_frames = 0;

  r = cubeb_init(&ctx, "Cubeb callback overload", NULL);
  ASSERT_EQ(r, CUBEB_OK);

  output_params.format = STREAM_FORMAT;
  output_params.rate = 48000;
  output_params.channels = 2;
  output_params.layout = CUBEB_LAYOUT_STEREO;

  r = cubeb_get_min_latency(ctx, output_params, &latency_frames);
  ASSERT_EQ(r, CUBEB_OK);

  r = cubeb_stream_init(ctx, &stream, "Cubeb",
                        NULL, NULL, NULL, &output_params,
                        latency_frames, data_cb, state_cb, NULL);
  ASSERT_EQ(r, CUBEB_OK);

  cubeb_stream_start(stream);
  delay(500);
  // This causes the callback to sleep for a large number of seconds.
  load_callback = true;
  delay(500);
  cubeb_stream_stop(stream);

  cubeb_stream_destroy(stream);
  cubeb_destroy(ctx);
}
<commit_msg>Replace printf by fprintf with stderr<commit_after>/*
 * Copyright © 2017 Mozilla Foundation
 *
 * This program is made available under an ISC-style license.  See the
 * accompanying file LICENSE for details.
 */

#include "gtest/gtest.h"
#if !defined(_XOPEN_SOURCE)
#define _XOPEN_SOURCE 600
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <atomic>
#include "cubeb/cubeb.h"
#include "common.h"

#define SAMPLE_FREQUENCY 48000
#if (defined(_WIN32) || defined(__WIN32__))
#define STREAM_FORMAT CUBEB_SAMPLE_FLOAT32LE
#else
#define STREAM_FORMAT CUBEB_SAMPLE_S16LE
#endif

std::atomic<bool> load_callback{ false };

long data_cb(cubeb_stream * stream, void * user, const void * inputbuffer, void * outputbuffer, long nframes)
{
  if (load_callback) {
    fprintf(stderr, "Sleeping...\n");
    delay(100000);
    fprintf(stderr, "Sleeping done\n");
  }
  return nframes;
}

void state_cb(cubeb_stream * stream, void * /*user*/, cubeb_state state)
{
  ASSERT_TRUE(!!stream);

  switch (state) {
  case CUBEB_STATE_STARTED:
    fprintf(stderr, "stream started\n"); break;
  case CUBEB_STATE_STOPPED:
    fprintf(stderr, "stream stopped\n"); break;
  case CUBEB_STATE_DRAINED:
    FAIL() << "this test is not supposed to drain"; break;
  case CUBEB_STATE_ERROR:
    fprintf(stderr, "stream error\n"); break;
  default:
    FAIL() << "this test is not supposed to have a weird state"; break;
  }
}

TEST(cubeb, overload_callback)
{
  cubeb * ctx;
  cubeb_stream * stream;
  cubeb_stream_params output_params;
  int r;
  uint32_t latency_frames = 0;

  r = cubeb_init(&ctx, "Cubeb callback overload", NULL);
  ASSERT_EQ(r, CUBEB_OK);

  output_params.format = STREAM_FORMAT;
  output_params.rate = 48000;
  output_params.channels = 2;
  output_params.layout = CUBEB_LAYOUT_STEREO;

  r = cubeb_get_min_latency(ctx, output_params, &latency_frames);
  ASSERT_EQ(r, CUBEB_OK);

  r = cubeb_stream_init(ctx, &stream, "Cubeb",
                        NULL, NULL, NULL, &output_params,
                        latency_frames, data_cb, state_cb, NULL);
  ASSERT_EQ(r, CUBEB_OK);

  cubeb_stream_start(stream);
  delay(500);
  // This causes the callback to sleep for a large number of seconds.
  load_callback = true;
  delay(500);
  cubeb_stream_stop(stream);

  cubeb_stream_destroy(stream);
  cubeb_destroy(ctx);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativecategory_p.h"
#include "qdeclarativeplaceicon_p.h"
#include "qdeclarativegeoserviceprovider_p.h"

#include <QtDeclarative/QDeclarativeInfo>
#include <QtLocation/QGeoServiceProvider>
#include <QtLocation/QPlaceManager>

QT_USE_NAMESPACE

/*!
    \qmlclass Category QDeclarativeCategory
    \inqmlmodule QtLocation 5
    \ingroup qml-QtLocation5-places
    \since QtLocation 5.0

    \brief The Category element represents a category that a \l Place can be associated with.

    Categories are used to search for places based on the categories they are associated with.  The
    list of available categories can be obtained from the \l CategoryModel.  The
    \l PlaceSearchModel has a \l {PlaceSearchModel::categories}{categories} property that is used
    to limit the search results to places with the specified categories.

    If the \l Plugin supports it, categories can be created or removed.  To create a new category
    construct a new Category object and set its properties, then invoke the \l save() method.

    \snippet snippets/declarative/places.qml QtLocation import
    \codeline
    \snippet snippets/declarative/places.qml Category
    \dots 0
    \snippet snippets/declarative/places.qml Category save

    To remove a category ensure that the \l plugin and categoryId properties are set and call the
    \l remove() method.

    \sa CategoryModel
*/

QDeclarativeCategory::QDeclarativeCategory(QObject* parent)
    : QObject(parent), m_icon(0), m_reply(0)
{
}

QDeclarativeCategory::QDeclarativeCategory(const QPlaceCategory &category,
                                           QDeclarativeGeoServiceProvider *plugin,
                                           QObject *parent)
        : QObject(parent),
          m_category(category),
          m_icon(0), m_plugin(plugin), m_reply(0)
{
    Q_ASSERT(plugin);
    setCategory(category);
}

QDeclarativeCategory::~QDeclarativeCategory() {}

// From QDeclarativeParserStatus
void QDeclarativeCategory::componentComplete()
{
    m_complete = true;
}

/*!
    \qmlproperty Plugin Category::plugin

    This property holds the plugin to which the category belongs.
*/
void QDeclarativeCategory::setPlugin(QDeclarativeGeoServiceProvider *plugin)
{
    if (m_plugin == plugin)
        return;

    m_plugin = plugin;
    if (m_complete)
        emit pluginChanged();
    QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
    QPlaceManager *placeManager = serviceProvider->placeManager();
    if (!placeManager || serviceProvider->error() != QGeoServiceProvider::NoError) {
        qmlInfo(this) << tr("Warning: Plugin does not support places.");
        return;
    }
}

QDeclarativeGeoServiceProvider* QDeclarativeCategory::plugin() const
{
    return m_plugin;
}

/*!
    \qmlproperty QPlaceCategory Category::category

    This property is used to provide an interface between C++ and QML code.  First a pointer to a
    Category object must be obtained from C++, then use the \l {QObject::property()}{property()} and
    \l {QObject::setProperty()}{setProperty()} functions to get and set the \c category property.

    The following gets the QPlaceCategory representing this object from C++:

    \snippet snippets/cpp/cppqml.cpp Category get

    The following sets the properties of this object based on a QPlaceCategory object from C++:

    \snippet snippets/cpp/cppqml.cpp Category set
*/
void QDeclarativeCategory::setCategory(const QPlaceCategory &category)
{
    QPlaceCategory previous = m_category;
    m_category = category;

    if (category.name() != previous.name())
        emit nameChanged();

    if (category.categoryId() != previous.categoryId())
        emit categoryIdChanged();

    if (m_icon && m_icon->parent() == this) {
        m_icon->setPlugin(m_plugin);
        m_icon->setBaseUrl(m_category.icon().baseUrl());
        m_icon->setFullUrl(m_category.icon().fullUrl());
    } else if (!m_icon || m_icon->parent() != this){
        m_icon = new QDeclarativePlaceIcon(m_category.icon(), m_plugin, this);
        emit iconChanged();
    }
}

QPlaceCategory QDeclarativeCategory::category()
{
    m_category.setIcon(m_icon ? m_icon->icon() : QPlaceIcon());
    return m_category;
}

/*!
    \qmlproperty string Category::categoryId

    This property holds the id of the category.  The categoryId is a string which uniquely
    identifies this category within the categories \l plugin.
*/
void QDeclarativeCategory::setCategoryId(const QString &id)
{
    if (m_category.categoryId() != id) {
        m_category.setCategoryId(id);
        emit categoryIdChanged();
    }
}

QString QDeclarativeCategory::categoryId() const
{
    return m_category.categoryId();
}

/*!
    \qmlproperty string Category::name

    This property holds name of the category.
*/
void QDeclarativeCategory::setName(const QString &name)
{
    if (m_category.name() != name) {
        m_category.setName(name);
        emit nameChanged();
    }
}

QString QDeclarativeCategory::name() const
{
    return m_category.name();
}

/*!
    \qmlproperty enumeration Category::visibility

    This property holds the visibility of the category.  It can be one of:

    \table
        \row
            \o Category.UnspecifiedVisibility
            \o The visibility of the category is unspecified, the default visibility of the plugin
               will be used.
        \row
            \o Category.DeviceVisibility
            \o The category is limited to the current device.  The category will not be transferred
               off of the device.
        \row
            \o Category.PrivateVisibility
            \o The category is private to the current user.  The category may be transferred to an
               online service but is only ever visible to the current user.
        \row
            \o Category.PublicVisibility
            \o The category is public.
    \endtable
*/
QDeclarativeCategory::Visibility QDeclarativeCategory::visibility() const
{
    return static_cast<QDeclarativeCategory::Visibility>(m_category.visibility());
}

void QDeclarativeCategory::setVisibility(Visibility visibility)
{
    if (static_cast<QDeclarativeCategory::Visibility>(m_category.visibility()) == visibility)
        return;

    m_category.setVisibility(static_cast<QtLocation::Visibility>(visibility));
    emit visibilityChanged();
}

/*!
    \qmlproperty PlaceIcon Category::icon

    This property holds the icon associated with the category.
*/
QDeclarativePlaceIcon *QDeclarativeCategory::icon() const
{
    return m_icon;
}

void QDeclarativeCategory::setIcon(QDeclarativePlaceIcon *icon)
{
    if (m_icon == icon)
        return;

    if (m_icon && m_icon->parent() == this)
        delete m_icon;

    m_icon = icon;
    emit iconChanged();
}

/*!
    \qmlmethod string Category::errorString()

    Returns a string description of the error of the last operation.
    If the last operation completed successfully then the string is empty.
*/
QString QDeclarativeCategory::errorString() const
{
    return m_errorString;
}

/*!
    \qmlproperty enumeration Category::status

    This property holds the status of the category.  It can be one of:

    \table
        \row
            \o Category.Ready
            \o No Error occurred during the last operation, further operations may be performed on
               the category.
        \row
            \o Category.Saving
            \o The category is currently being saved, no other operations may be perfomed until the
               current operation completes.
        \row
            \o Category.Removing
            \o The category is currently being removed, no other operations can be performed until
               the current operation completes.
        \row
            \o Category.Error
            \o An error occurred during the last operation, further operations can still be
               performed on the category.
    \endtable
*/
void QDeclarativeCategory::setStatus(Status status)
{
    if (m_status != status) {
        m_status = status;
        emit statusChanged();
    }
}

QDeclarativeCategory::Status QDeclarativeCategory::status() const
{
    return m_status;
}

/*!
    \qmlmethod void Category::save()

    This method saves the category to the backend service.
*/
void QDeclarativeCategory::save(const QString &parentId)
{
    QPlaceManager *placeManager = manager();
    if (!placeManager)
        return;

    m_reply = placeManager->saveCategory(category(), parentId);
    connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    setStatus(QDeclarativeCategory::Saving);
}

/*!
    \qmlmethod void Category::remove()

    This method permanently removes the category from the backend service.
*/
void QDeclarativeCategory::remove()
{
    QPlaceManager *placeManager = manager();
    if (!placeManager)
        return;

    m_reply = placeManager->removeCategory(m_category.categoryId());
    connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    setStatus(QDeclarativeCategory::Removing);
}

void QDeclarativeCategory::replyFinished()
{
    if (!m_reply)
        return;

    if (m_reply->error() == QPlaceReply::NoError) {
        switch (m_reply->type()) {
        case (QPlaceReply::IdReply) : {
            QPlaceIdReply *idReply = qobject_cast<QPlaceIdReply *>(m_reply);

            switch (idReply->operationType()) {
            case QPlaceIdReply::SaveCategory:
                setCategoryId(idReply->id());
                break;
            case QPlaceIdReply::RemoveCategory:
                setCategoryId(QString());
                break;
            default:
                //Other operation types shouldn't ever be received.
                break;
            }
            break;
        }
        default:
            //other types of replies shouldn't ever be received.
            break;
        }

        m_errorString.clear();

        m_reply->deleteLater();
        m_reply = 0;

        setStatus(QDeclarativeCategory::Ready);
    } else {
        m_errorString = m_reply->errorString();

        m_reply->deleteLater();
        m_reply = 0;

        setStatus(QDeclarativeCategory::Error);
    }
}

/*
    Helper function to return the manager, this manager is intended to be used
    to perform the next operation.
*/
QPlaceManager *QDeclarativeCategory::manager()
{
    if (m_status != QDeclarativeCategory::Ready && m_status != QDeclarativeCategory::Error)
        return 0;

    if (m_reply) {
        m_reply->abort();
        m_reply->deleteLater();
        m_reply = 0;
    }

    if (!m_plugin) {
           qmlInfo(this) << tr("Plugin not assigned to category");
           return 0;
    }

    QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
    if (!serviceProvider)
        return 0;

    QPlaceManager *placeManager = serviceProvider->placeManager();

    if (!placeManager) {
        qmlInfo(this) << tr("Places not supported by %1 Plugin.").arg(m_plugin->name());
        return 0;
    }

    return placeManager;
}
<commit_msg>Fix uninitialized member variables in Category element.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativecategory_p.h"
#include "qdeclarativeplaceicon_p.h"
#include "qdeclarativegeoserviceprovider_p.h"

#include <QtDeclarative/QDeclarativeInfo>
#include <QtLocation/QGeoServiceProvider>
#include <QtLocation/QPlaceManager>

QT_USE_NAMESPACE

/*!
    \qmlclass Category QDeclarativeCategory
    \inqmlmodule QtLocation 5
    \ingroup qml-QtLocation5-places
    \since QtLocation 5.0

    \brief The Category element represents a category that a \l Place can be associated with.

    Categories are used to search for places based on the categories they are associated with.  The
    list of available categories can be obtained from the \l CategoryModel.  The
    \l PlaceSearchModel has a \l {PlaceSearchModel::categories}{categories} property that is used
    to limit the search results to places with the specified categories.

    If the \l Plugin supports it, categories can be created or removed.  To create a new category
    construct a new Category object and set its properties, then invoke the \l save() method.

    \snippet snippets/declarative/places.qml QtLocation import
    \codeline
    \snippet snippets/declarative/places.qml Category
    \dots 0
    \snippet snippets/declarative/places.qml Category save

    To remove a category ensure that the \l plugin and categoryId properties are set and call the
    \l remove() method.

    \sa CategoryModel
*/

QDeclarativeCategory::QDeclarativeCategory(QObject* parent)
:   QObject(parent), m_icon(0), m_plugin(0), m_reply(0), m_complete(false), m_status(Ready)
{
}

QDeclarativeCategory::QDeclarativeCategory(const QPlaceCategory &category,
                                           QDeclarativeGeoServiceProvider *plugin,
                                           QObject *parent)
:   QObject(parent), m_category(category), m_icon(0), m_plugin(plugin), m_reply(0),
    m_complete(false), m_status(Ready)
{
    Q_ASSERT(plugin);
    setCategory(category);
}

QDeclarativeCategory::~QDeclarativeCategory() {}

// From QDeclarativeParserStatus
void QDeclarativeCategory::componentComplete()
{
    m_complete = true;
}

/*!
    \qmlproperty Plugin Category::plugin

    This property holds the plugin to which the category belongs.
*/
void QDeclarativeCategory::setPlugin(QDeclarativeGeoServiceProvider *plugin)
{
    if (m_plugin == plugin)
        return;

    m_plugin = plugin;
    if (m_complete)
        emit pluginChanged();
    QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
    QPlaceManager *placeManager = serviceProvider->placeManager();
    if (!placeManager || serviceProvider->error() != QGeoServiceProvider::NoError) {
        qmlInfo(this) << tr("Warning: Plugin does not support places.");
        return;
    }
}

QDeclarativeGeoServiceProvider* QDeclarativeCategory::plugin() const
{
    return m_plugin;
}

/*!
    \qmlproperty QPlaceCategory Category::category

    This property is used to provide an interface between C++ and QML code.  First a pointer to a
    Category object must be obtained from C++, then use the \l {QObject::property()}{property()} and
    \l {QObject::setProperty()}{setProperty()} functions to get and set the \c category property.

    The following gets the QPlaceCategory representing this object from C++:

    \snippet snippets/cpp/cppqml.cpp Category get

    The following sets the properties of this object based on a QPlaceCategory object from C++:

    \snippet snippets/cpp/cppqml.cpp Category set
*/
void QDeclarativeCategory::setCategory(const QPlaceCategory &category)
{
    QPlaceCategory previous = m_category;
    m_category = category;

    if (category.name() != previous.name())
        emit nameChanged();

    if (category.categoryId() != previous.categoryId())
        emit categoryIdChanged();

    if (m_icon && m_icon->parent() == this) {
        m_icon->setPlugin(m_plugin);
        m_icon->setBaseUrl(m_category.icon().baseUrl());
        m_icon->setFullUrl(m_category.icon().fullUrl());
    } else if (!m_icon || m_icon->parent() != this){
        m_icon = new QDeclarativePlaceIcon(m_category.icon(), m_plugin, this);
        emit iconChanged();
    }
}

QPlaceCategory QDeclarativeCategory::category()
{
    m_category.setIcon(m_icon ? m_icon->icon() : QPlaceIcon());
    return m_category;
}

/*!
    \qmlproperty string Category::categoryId

    This property holds the id of the category.  The categoryId is a string which uniquely
    identifies this category within the categories \l plugin.
*/
void QDeclarativeCategory::setCategoryId(const QString &id)
{
    if (m_category.categoryId() != id) {
        m_category.setCategoryId(id);
        emit categoryIdChanged();
    }
}

QString QDeclarativeCategory::categoryId() const
{
    return m_category.categoryId();
}

/*!
    \qmlproperty string Category::name

    This property holds name of the category.
*/
void QDeclarativeCategory::setName(const QString &name)
{
    if (m_category.name() != name) {
        m_category.setName(name);
        emit nameChanged();
    }
}

QString QDeclarativeCategory::name() const
{
    return m_category.name();
}

/*!
    \qmlproperty enumeration Category::visibility

    This property holds the visibility of the category.  It can be one of:

    \table
        \row
            \o Category.UnspecifiedVisibility
            \o The visibility of the category is unspecified, the default visibility of the plugin
               will be used.
        \row
            \o Category.DeviceVisibility
            \o The category is limited to the current device.  The category will not be transferred
               off of the device.
        \row
            \o Category.PrivateVisibility
            \o The category is private to the current user.  The category may be transferred to an
               online service but is only ever visible to the current user.
        \row
            \o Category.PublicVisibility
            \o The category is public.
    \endtable
*/
QDeclarativeCategory::Visibility QDeclarativeCategory::visibility() const
{
    return static_cast<QDeclarativeCategory::Visibility>(m_category.visibility());
}

void QDeclarativeCategory::setVisibility(Visibility visibility)
{
    if (static_cast<QDeclarativeCategory::Visibility>(m_category.visibility()) == visibility)
        return;

    m_category.setVisibility(static_cast<QtLocation::Visibility>(visibility));
    emit visibilityChanged();
}

/*!
    \qmlproperty PlaceIcon Category::icon

    This property holds the icon associated with the category.
*/
QDeclarativePlaceIcon *QDeclarativeCategory::icon() const
{
    return m_icon;
}

void QDeclarativeCategory::setIcon(QDeclarativePlaceIcon *icon)
{
    if (m_icon == icon)
        return;

    if (m_icon && m_icon->parent() == this)
        delete m_icon;

    m_icon = icon;
    emit iconChanged();
}

/*!
    \qmlmethod string Category::errorString()

    Returns a string description of the error of the last operation.
    If the last operation completed successfully then the string is empty.
*/
QString QDeclarativeCategory::errorString() const
{
    return m_errorString;
}

/*!
    \qmlproperty enumeration Category::status

    This property holds the status of the category.  It can be one of:

    \table
        \row
            \o Category.Ready
            \o No Error occurred during the last operation, further operations may be performed on
               the category.
        \row
            \o Category.Saving
            \o The category is currently being saved, no other operations may be perfomed until the
               current operation completes.
        \row
            \o Category.Removing
            \o The category is currently being removed, no other operations can be performed until
               the current operation completes.
        \row
            \o Category.Error
            \o An error occurred during the last operation, further operations can still be
               performed on the category.
    \endtable
*/
void QDeclarativeCategory::setStatus(Status status)
{
    if (m_status != status) {
        m_status = status;
        emit statusChanged();
    }
}

QDeclarativeCategory::Status QDeclarativeCategory::status() const
{
    return m_status;
}

/*!
    \qmlmethod void Category::save()

    This method saves the category to the backend service.
*/
void QDeclarativeCategory::save(const QString &parentId)
{
    QPlaceManager *placeManager = manager();
    if (!placeManager)
        return;

    m_reply = placeManager->saveCategory(category(), parentId);
    connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    setStatus(QDeclarativeCategory::Saving);
}

/*!
    \qmlmethod void Category::remove()

    This method permanently removes the category from the backend service.
*/
void QDeclarativeCategory::remove()
{
    QPlaceManager *placeManager = manager();
    if (!placeManager)
        return;

    m_reply = placeManager->removeCategory(m_category.categoryId());
    connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
    setStatus(QDeclarativeCategory::Removing);
}

void QDeclarativeCategory::replyFinished()
{
    if (!m_reply)
        return;

    if (m_reply->error() == QPlaceReply::NoError) {
        switch (m_reply->type()) {
        case (QPlaceReply::IdReply) : {
            QPlaceIdReply *idReply = qobject_cast<QPlaceIdReply *>(m_reply);

            switch (idReply->operationType()) {
            case QPlaceIdReply::SaveCategory:
                setCategoryId(idReply->id());
                break;
            case QPlaceIdReply::RemoveCategory:
                setCategoryId(QString());
                break;
            default:
                //Other operation types shouldn't ever be received.
                break;
            }
            break;
        }
        default:
            //other types of replies shouldn't ever be received.
            break;
        }

        m_errorString.clear();

        m_reply->deleteLater();
        m_reply = 0;

        setStatus(QDeclarativeCategory::Ready);
    } else {
        m_errorString = m_reply->errorString();

        m_reply->deleteLater();
        m_reply = 0;

        setStatus(QDeclarativeCategory::Error);
    }
}

/*
    Helper function to return the manager, this manager is intended to be used
    to perform the next operation.
*/
QPlaceManager *QDeclarativeCategory::manager()
{
    if (m_status != QDeclarativeCategory::Ready && m_status != QDeclarativeCategory::Error)
        return 0;

    if (m_reply) {
        m_reply->abort();
        m_reply->deleteLater();
        m_reply = 0;
    }

    if (!m_plugin) {
           qmlInfo(this) << tr("Plugin not assigned to category");
           return 0;
    }

    QGeoServiceProvider *serviceProvider = m_plugin->sharedGeoServiceProvider();
    if (!serviceProvider)
        return 0;

    QPlaceManager *placeManager = serviceProvider->placeManager();

    if (!placeManager) {
        qmlInfo(this) << tr("Places not supported by %1 Plugin.").arg(m_plugin->name());
        return 0;
    }

    return placeManager;
}
<|endoftext|>


<commit_before>#include "storehouse/s3/s3_storage.h"

#include <aws/s3/model/Bucket.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/core/Aws.h>
#include <fstream>
#include <sstream>
#include <fcntl.h>

namespace storehouse {

using Aws::S3::S3Client;

class S3RandomReadFile : public RandomReadFile {
 public:
  S3RandomReadFile(const std::string& name, const std::string& bucket,
                   S3Client* client)
      : name_(name), bucket_(bucket), client_(client) {}

  StoreResult read(uint64_t offset, size_t requested_size, uint8_t* data,
                   size_t& size_read) override {
    uint64_t file_size;
    auto result = get_size(file_size);
    int64_t size_to_read = std::min((int64_t)(file_size - offset), (int64_t)requested_size);
    size_to_read = std::max(size_to_read, (int64_t)0);

    size_read = 0;
    if (result != StoreResult::Success
        || (size_to_read == 0 && requested_size == 0)) {
      return result;
    }

    if (size_to_read == 0 && requested_size > 0) {
      return StoreResult::EndOfFile;
    }

    Aws::S3::Model::GetObjectRequest object_request;

    std::stringstream range_request;
    range_request << "bytes=" << offset << "-" << (offset + size_to_read - 1);

    object_request.WithBucket(bucket_).WithKey(name_).WithRange(range_request.str());

    auto get_object_outcome = client_->GetObject(object_request);

    if (get_object_outcome.IsSuccess()) {
      size_read = get_object_outcome.GetResult().GetContentLength();
      get_object_outcome.GetResult().GetBody().
          rdbuf()->sgetn((char*)data, size_read);

      if (size_read != requested_size) {
        return StoreResult::EndOfFile;
      }
      return StoreResult::Success;
    } else {
      auto error = get_object_outcome.GetError();
      LOG(WARNING) << "Error opening file: " <<
        get_full_path() << " - " <<
        error.GetMessage();

      return StoreResult::TransientFailure;
    }
  }

  StoreResult get_size(uint64_t& size) override {
    Aws::S3::Model::HeadObjectRequest object_request;
    object_request.WithBucket(bucket_).WithKey(name_);

    auto head_object_outcome = client_->HeadObject(object_request);

    if (head_object_outcome.IsSuccess()) {
      size = (uint64_t)head_object_outcome.GetResult().GetContentLength();
    } else {
      LOG(WARNING) << "Error getting size - HeadObject error: " <<
          head_object_outcome.GetError().GetExceptionName() << " " <<
          head_object_outcome.GetError().GetMessage() <<
          " for object: " << get_full_path();
      return StoreResult::TransientFailure;
    }

    return StoreResult::Success;
  }

  const std::string path() override { return name_; }

 private:
  std::string bucket_;
  std::string name_;
  S3Client* client_;

  std::string get_full_path() {
    return bucket_ + "/" + name_;
  }
};

class S3WriteFile : public WriteFile {
 public:
  S3WriteFile(const std::string& name, const std::string& bucket,
                   S3Client* client)
      : name_(name), bucket_(bucket), client_(client), tfd_(-1) {
    tmpfilename_ = strdup("/tmp/scannerXXXXXX");

    tfd_ = mkstemp(tmpfilename_);
    LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
      << "Failed to create temp file for writing";
    tfp_ = fdopen(tfd_, "wb+");
    LOG_IF(FATAL, tfp_ == NULL) << "Failed to open temp file for writing";

    has_changed_ = true;
  }

  ~S3WriteFile() {
    save();

    int err;
    err = std::fclose(tfp_);
    LOG_IF(FATAL, err < 0)
      << "fclose temp file " << tmpfilename_ << " "
      << "failed with error: " << strerror(errno);

    err = unlink(tmpfilename_);
    LOG_IF(FATAL, err < 0)
      << "unlink temp file " << tmpfilename_ << " "
      << "failed with error: " << strerror(errno);
    free(tmpfilename_);
  }

  StoreResult append(size_t size, const uint8_t* data) override {
    LOG_IF(FATAL, tfp_ == NULL) << "assertion failure: null file pointer";
    LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
      << "S3WriteFile: closed file descriptor for " << get_full_path();
    size_t size_written = fwrite(data, sizeof(uint8_t), size, tfp_);
    LOG_IF(FATAL, size_written != size)
      << "S3WriteFile: did not write all " << size << " "
      << "bytes to tmp file for file " << get_full_path() << " "
      << "with error: " << strerror(errno);
    has_changed_ = true;
    return StoreResult::Success;
  }

  StoreResult save() override {
    if (!has_changed_) { return StoreResult::Success; }

    std::fflush(tfp_);

    auto input_data = Aws::MakeShared<Aws::FStream>("PutObjectInputStream",
            tmpfilename_, std::ios_base::in | std::ios_base::binary);

    Aws::S3::Model::PutObjectRequest put_object_request;
    put_object_request.WithKey(name_).WithBucket(bucket_);

    put_object_request.SetBody(input_data);
    auto put_object_outcome = client_->PutObject(put_object_request);

    if(!put_object_outcome.IsSuccess()) {
      auto error = put_object_outcome.GetError();
      LOG(WARNING) << "Save Error: error while putting object: " <<
        get_full_path() << " - " <<
        error.GetExceptionName() << " " <<
        error.GetMessage();
      return StoreResult::TransientFailure;
    }

    has_changed_ = false;

    return StoreResult::Success;
  }

  const std::string path() override { return name_; }

 private:
  std::string bucket_;
  std::string name_;
  S3Client* client_;
  int tfd_;
  FILE* tfp_;
  char* tmpfilename_;
  bool has_changed_;

  std::string get_full_path() {
    return bucket_ + "/" + name_;
  }
};

uint64_t S3Storage::num_clients = 0;
std::mutex S3Storage::num_clients_mutex;

S3Storage::S3Storage(S3Config config) : bucket_(config.bucket) {
  std::lock_guard<std::mutex> guard(num_clients_mutex);
  if (num_clients == 0) {
    Aws::InitAPI(sdk_options_);
  }
  num_clients++;

  Aws::Client::ClientConfiguration cc;
  cc.scheme = Aws::Http::Scheme::HTTPS;
  cc.region = config.endpointRegion;
  cc.endpointOverride = config.endpointOverride;
  cc.connectTimeoutMs = 1000 * 60 * 10;
  cc.requestTimeoutMs = 1000 * 60 * 10;

  client_ = new S3Client(cc);
}

S3Storage::~S3Storage() {
  std::lock_guard<std::mutex> guard(num_clients_mutex);
  delete client_;

  num_clients--;
  if (num_clients == 0) {
    Aws::ShutdownAPI(sdk_options_);
  }
}

StoreResult S3Storage::get_file_info(const std::string& name,
                                     FileInfo& file_info) {
  S3RandomReadFile s3read_file(name, bucket_, client_);
  file_info.file_exists = false;
  file_info.file_is_folder = (name[name.length()-1] == '/');
  auto result = s3read_file.get_size(file_info.size);
  if (result == StoreResult::Success) {
  	file_info.file_exists = true;
  }
  return result;
}

StoreResult S3Storage::make_random_read_file(const std::string& name,
                                             RandomReadFile*& file) {
  file = new S3RandomReadFile(name, bucket_, client_);
  return StoreResult::Success;
}

StoreResult S3Storage::make_write_file(const std::string& name,
                                       WriteFile*& file) {
  file = new S3WriteFile(name, bucket_, client_);
  return StoreResult::Success;
}

StoreResult S3Storage::make_dir(const std::string& name) {
  Aws::S3::Model::PutObjectRequest put_object_request;
  put_object_request.WithKey(name + "/").WithBucket(bucket_);
  auto put_object_outcome = client_->PutObject(put_object_request);

  if(!put_object_outcome.IsSuccess()) {
    LOG(WARNING) << "Save Error: error while making dir: " <<
        bucket_ << "/" << name << " - " <<
        put_object_outcome.GetError().GetExceptionName() << " " <<
        put_object_outcome.GetError().GetMessage();
    return StoreResult::TransientFailure;
  }
  return StoreResult::Success;
}

StoreResult S3Storage::delete_file(const std::string& name) {
  return StoreResult::Success;
}

StoreResult S3Storage::delete_dir(const std::string& name, bool recursive) {
  return StoreResult::Success;
}
}
<commit_msg>Fix handling of transient failures in s3 backend<commit_after>#include "storehouse/s3/s3_storage.h"

#include <aws/s3/model/Bucket.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/s3/model/PutObjectRequest.h>
#include <aws/s3/model/HeadObjectRequest.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/core/Aws.h>
#include <fstream>
#include <sstream>
#include <fcntl.h>

namespace storehouse {

using Aws::S3::S3Client;

class S3RandomReadFile : public RandomReadFile {
 public:
  S3RandomReadFile(const std::string& name, const std::string& bucket,
                   S3Client* client)
      : name_(name), bucket_(bucket), client_(client) {}

  StoreResult read(uint64_t offset, size_t requested_size, uint8_t* data,
                   size_t& size_read) override {
    uint64_t file_size;
    auto result = get_size(file_size);
    int64_t size_to_read = std::min((int64_t)(file_size - offset), (int64_t)requested_size);
    size_to_read = std::max(size_to_read, (int64_t)0);

    size_read = 0;
    if (result != StoreResult::Success
        || (size_to_read == 0 && requested_size == 0)) {
      return result;
    }

    if (size_to_read == 0 && requested_size > 0) {
      return StoreResult::EndOfFile;
    }

    Aws::S3::Model::GetObjectRequest object_request;

    std::stringstream range_request;
    range_request << "bytes=" << offset << "-" << (offset + size_to_read - 1);

    object_request.WithBucket(bucket_).WithKey(name_).WithRange(range_request.str());

    auto get_object_outcome = client_->GetObject(object_request);

    if (get_object_outcome.IsSuccess()) {
      size_read = get_object_outcome.GetResult().GetContentLength();
      get_object_outcome.GetResult().GetBody().
          rdbuf()->sgetn((char*)data, size_read);

      if (size_read != requested_size) {
        return StoreResult::EndOfFile;
      }
      return StoreResult::Success;
    } else {
      auto error = get_object_outcome.GetError();
      LOG(WARNING) << "Error opening file: " <<
        get_full_path() << " - " <<
        error.GetMessage();

      if (error.ShouldRetry()) {
        return StoreResult::TransientFailure;
      } else {
        return StoreResult::ReadFailure;
      }
    }
  }

  StoreResult get_size(uint64_t& size) override {
    Aws::S3::Model::HeadObjectRequest object_request;
    object_request.WithBucket(bucket_).WithKey(name_);

    auto head_object_outcome = client_->HeadObject(object_request);

    if (head_object_outcome.IsSuccess()) {
      size = (uint64_t)head_object_outcome.GetResult().GetContentLength();
    } else {
      LOG(WARNING) << "Error getting size - HeadObject error: " <<
          head_object_outcome.GetError().GetExceptionName() << " " <<
          head_object_outcome.GetError().GetMessage() <<
          " for object: " << get_full_path();

      if (head_object_outcome.GetError().ShouldRetry()) {
        return StoreResult::TransientFailure;
      } else {
        return StoreResult::ReadFailure;
      }
    }

    return StoreResult::Success;
  }

  const std::string path() override { return name_; }

 private:
  std::string bucket_;
  std::string name_;
  S3Client* client_;

  std::string get_full_path() {
    return bucket_ + "/" + name_;
  }
};

class S3WriteFile : public WriteFile {
 public:
  S3WriteFile(const std::string& name, const std::string& bucket,
                   S3Client* client)
      : name_(name), bucket_(bucket), client_(client), tfd_(-1) {
    tmpfilename_ = strdup("/tmp/scannerXXXXXX");

    tfd_ = mkstemp(tmpfilename_);
    LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
      << "Failed to create temp file for writing";
    tfp_ = fdopen(tfd_, "wb+");
    LOG_IF(FATAL, tfp_ == NULL) << "Failed to open temp file for writing";

    has_changed_ = true;
  }

  ~S3WriteFile() {
    save();

    int err;
    err = std::fclose(tfp_);
    LOG_IF(FATAL, err < 0)
      << "fclose temp file " << tmpfilename_ << " "
      << "failed with error: " << strerror(errno);

    err = unlink(tmpfilename_);
    LOG_IF(FATAL, err < 0)
      << "unlink temp file " << tmpfilename_ << " "
      << "failed with error: " << strerror(errno);
    free(tmpfilename_);
  }

  StoreResult append(size_t size, const uint8_t* data) override {
    LOG_IF(FATAL, tfp_ == NULL) << "assertion failure: null file pointer";
    LOG_IF(FATAL, tfd_ == -1 || fcntl(tfd_, F_GETFD) == -1)
      << "S3WriteFile: closed file descriptor for " << get_full_path();
    size_t size_written = fwrite(data, sizeof(uint8_t), size, tfp_);
    LOG_IF(FATAL, size_written != size)
      << "S3WriteFile: did not write all " << size << " "
      << "bytes to tmp file for file " << get_full_path() << " "
      << "with error: " << strerror(errno);
    has_changed_ = true;
    return StoreResult::Success;
  }

  StoreResult save() override {
    if (!has_changed_) { return StoreResult::Success; }

    std::fflush(tfp_);

    auto input_data = Aws::MakeShared<Aws::FStream>("PutObjectInputStream",
            tmpfilename_, std::ios_base::in | std::ios_base::binary);

    Aws::S3::Model::PutObjectRequest put_object_request;
    put_object_request.WithKey(name_).WithBucket(bucket_);

    put_object_request.SetBody(input_data);
    auto put_object_outcome = client_->PutObject(put_object_request);

    if(!put_object_outcome.IsSuccess()) {
      auto error = put_object_outcome.GetError();
      LOG(WARNING) << "Save Error: error while putting object: " <<
        get_full_path() << " - " <<
        error.GetExceptionName() << " " <<
        error.GetMessage();

      if (error.ShouldRetry()) {
        return StoreResult::TransientFailure;
      } else {
        return StoreResult::SaveFailure;
      }
    }

    has_changed_ = false;

    return StoreResult::Success;
  }

  const std::string path() override { return name_; }

 private:
  std::string bucket_;
  std::string name_;
  S3Client* client_;
  int tfd_;
  FILE* tfp_;
  char* tmpfilename_;
  bool has_changed_;

  std::string get_full_path() {
    return bucket_ + "/" + name_;
  }
};

uint64_t S3Storage::num_clients = 0;
std::mutex S3Storage::num_clients_mutex;

S3Storage::S3Storage(S3Config config) : bucket_(config.bucket) {
  std::lock_guard<std::mutex> guard(num_clients_mutex);
  if (num_clients == 0) {
    Aws::InitAPI(sdk_options_);
  }
  num_clients++;

  Aws::Client::ClientConfiguration cc;
  cc.scheme = Aws::Http::Scheme::HTTPS;
  cc.region = config.endpointRegion;
  cc.endpointOverride = config.endpointOverride;
  cc.connectTimeoutMs = 1000 * 60 * 10;
  cc.requestTimeoutMs = 1000 * 60 * 10;

  client_ = new S3Client(cc);
}

S3Storage::~S3Storage() {
  std::lock_guard<std::mutex> guard(num_clients_mutex);
  delete client_;

  num_clients--;
  if (num_clients == 0) {
    Aws::ShutdownAPI(sdk_options_);
  }
}

StoreResult S3Storage::get_file_info(const std::string& name,
                                     FileInfo& file_info) {
  S3RandomReadFile s3read_file(name, bucket_, client_);
  file_info.file_exists = false;
  file_info.file_is_folder = (name[name.length()-1] == '/');
  auto result = s3read_file.get_size(file_info.size);
  if (result == StoreResult::Success) {
  	file_info.file_exists = true;
  }
  return result;
}

StoreResult S3Storage::make_random_read_file(const std::string& name,
                                             RandomReadFile*& file) {
  file = new S3RandomReadFile(name, bucket_, client_);
  return StoreResult::Success;
}

StoreResult S3Storage::make_write_file(const std::string& name,
                                       WriteFile*& file) {
  file = new S3WriteFile(name, bucket_, client_);
  return StoreResult::Success;
}

StoreResult S3Storage::make_dir(const std::string& name) {
  Aws::S3::Model::PutObjectRequest put_object_request;
  put_object_request.WithKey(name + "/").WithBucket(bucket_);
  auto put_object_outcome = client_->PutObject(put_object_request);

  if(!put_object_outcome.IsSuccess()) {
    LOG(WARNING) << "Save Error: error while making dir: " <<
        bucket_ << "/" << name << " - " <<
        put_object_outcome.GetError().GetExceptionName() << " " <<
        put_object_outcome.GetError().GetMessage();

    if (put_object_outcome.GetError().ShouldRetry()) {
      return StoreResult::TransientFailure;
    } else {
      return StoreResult::MkDirFailure;
    }
  }
  return StoreResult::Success;
}

StoreResult S3Storage::delete_file(const std::string& name) {
  return StoreResult::Success;
}

StoreResult S3Storage::delete_dir(const std::string& name, bool recursive) {
  return StoreResult::Success;
}
}
<|endoftext|>


<commit_before>
//
// ===============================================================================
// clReflect
// -------------------------------------------------------------------------------
// Copyright (c) 2011 Don Williamson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// ===============================================================================
//

#include <clcpp\Database.h>
#include "DatabaseLoader.h"

namespace
{
	int CompareNames(clcpp::Name name, unsigned int hash)
	{
		return hash - name.hash;
	}

	int ComparePrimitives(const clcpp::Primitive* primitive, unsigned int hash)
	{
		return hash - primitive->name.hash;
	}

	int ComparePrimitives(const clcpp::Primitive& primitive, unsigned int hash)
	{
		return hash - primitive.name.hash;
	}

	template <typename ARRAY_TYPE, typename COMPARE_L_TYPE, typename COMPARE_R_TYPE, int (COMPARE_FUNC)(COMPARE_L_TYPE, COMPARE_R_TYPE)>
	int BinarySearch(const clcpp::CArray<ARRAY_TYPE>& entries, COMPARE_R_TYPE compare_value)
	{
		// TODO: Return multiple entries

		int first = 0;
		int last = entries.size() - 1;

		// Binary search
		while (first <= last)
		{
			// Identify the mid point
			int mid = (first + last) / 2;

			int cmp = COMPARE_FUNC(entries[mid], compare_value);
			if (cmp > 0)
			{
				// Shift search to local upper half
				first = mid + 1;
			}
			else if (cmp < 0)
			{
				// Shift search to local lower half
				last = mid - 1;
			}
			else
			{
				// Exact match found
				return mid;
			}
		}

		return -1;
	}
}

const clcpp::Primitive* clcpp::internal::FindPrimitive(const CArray<const Primitive*>& primitives, unsigned int hash)
{
	int index = BinarySearch<const Primitive*, const Primitive*, unsigned int, ComparePrimitives>(primitives, hash);
	if (index == -1)
	{
		return 0;
	}
	return primitives[index];
}

clcpp::Database::Database()
	: m_DatabaseMem(0)
	, m_Allocator(0)
{
}

clcpp::Database::~Database()
{
	if (m_DatabaseMem)
	{
		m_Allocator->Free(m_DatabaseMem);
	}
}

clcpp::Name clcpp::Database::GetName(const char* text) const
{
	// Null pointer
	if (text == 0)
	{
		return clcpp::Name();
	}

	// Hash and exit on no value
	unsigned int hash = internal::HashNameString(text);
	if (hash == 0)
	{
		return clcpp::Name();
	}

	// Lookup the name by hash and see
	int index = BinarySearch<Name, Name, unsigned int, CompareNames>(m_DatabaseMem->names, hash);
	if (index == -1)
	{
		return clcpp::Name();
	}

	return m_DatabaseMem->names[index];
}

const clcpp::Type* clcpp::Database::GetType(unsigned int hash) const
{
	return FindPrimitive(m_DatabaseMem->type_primitives, hash);
}

const clcpp::Namespace* clcpp::Database::GetNamespace(unsigned int hash) const
{
	int index = BinarySearch<Namespace, const Primitive&, unsigned int, ComparePrimitives>(m_DatabaseMem->namespaces, hash);
	if (index == -1)
	{
		return 0;
	}
	return &m_DatabaseMem->namespaces[index];
}

const clcpp::Function* clcpp::Database::GetFunction(unsigned int hash) const
{
	int index = BinarySearch<Function, const Primitive&, unsigned int, ComparePrimitives>(m_DatabaseMem->functions, hash);
	if (index == -1)
	{
		return 0;
	}
	return &m_DatabaseMem->functions[index];
}

bool clcpp::Database::Load(IFile* file, IAllocator* allocator)
{
	internal::Assert(m_DatabaseMem == 0 && "Database already loaded");
	m_Allocator = allocator;
	m_DatabaseMem = internal::LoadMemoryMappedDatabase(file, m_Allocator);
	return m_DatabaseMem != 0;
}
<commit_msg>Fixed subtract bug with the binary search and larger than int range hashes.<commit_after>
//
// ===============================================================================
// clReflect
// -------------------------------------------------------------------------------
// Copyright (c) 2011 Don Williamson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// ===============================================================================
//

#include <clcpp\Database.h>
#include "DatabaseLoader.h"

namespace
{
	unsigned int GetNameHash(clcpp::Name name)
	{
		return name.hash;
	}
	unsigned int GetPrimitiveHash(const clcpp::Primitive& primitive)
	{
		return primitive.name.hash;
	}
	unsigned int GetPrimitivePtrHash(const clcpp::Primitive* primitive)
	{
		return primitive->name.hash;
	}

	template <typename ARRAY_TYPE, typename COMPARE_L_TYPE, unsigned int (GET_HASH_FUNC)(COMPARE_L_TYPE)>
	int BinarySearch(const clcpp::CArray<ARRAY_TYPE>& entries, unsigned int compare_hash)
	{
		// TODO: Return multiple entries

		int first = 0;
		int last = entries.size() - 1;

		// Binary search
		while (first <= last)
		{
			// Identify the mid point
			int mid = (first + last) / 2;

			unsigned entry_hash = GET_HASH_FUNC(entries[mid]);
			if (compare_hash > entry_hash)
			{
				// Shift search to local upper half
				first = mid + 1;
			}
			else if (compare_hash < entry_hash)
			{
				// Shift search to local lower half
				last = mid - 1;
			}
			else
			{
				// Exact match found
				return mid;
			}
		}

		return -1;
	}
}

const clcpp::Primitive* clcpp::internal::FindPrimitive(const CArray<const Primitive*>& primitives, unsigned int hash)
{
	int index = BinarySearch<const Primitive*, const Primitive*, GetPrimitivePtrHash>(primitives, hash);
	if (index == -1)
	{
		return 0;
	}
	return primitives[index];
}

clcpp::Database::Database()
	: m_DatabaseMem(0)
	, m_Allocator(0)
{
}

clcpp::Database::~Database()
{
	if (m_DatabaseMem)
	{
		m_Allocator->Free(m_DatabaseMem);
	}
}

clcpp::Name clcpp::Database::GetName(const char* text) const
{
	// Null pointer
	if (text == 0)
	{
		return clcpp::Name();
	}

	// Hash and exit on no value
	unsigned int hash = internal::HashNameString(text);
	if (hash == 0)
	{
		return clcpp::Name();
	}

	// Lookup the name by hash and see
	int index = BinarySearch<Name, Name, GetNameHash>(m_DatabaseMem->names, hash);
	if (index == -1)
	{
		return clcpp::Name();
	}

	return m_DatabaseMem->names[index];
}

const clcpp::Type* clcpp::Database::GetType(unsigned int hash) const
{
	return FindPrimitive(m_DatabaseMem->type_primitives, hash);
}

const clcpp::Namespace* clcpp::Database::GetNamespace(unsigned int hash) const
{
	int index = BinarySearch<Namespace, const Primitive&, GetPrimitiveHash>(m_DatabaseMem->namespaces, hash);
	if (index == -1)
	{
		return 0;
	}
	return &m_DatabaseMem->namespaces[index];
}

const clcpp::Function* clcpp::Database::GetFunction(unsigned int hash) const
{
	int index = BinarySearch<Function, const Primitive&, GetPrimitiveHash>(m_DatabaseMem->functions, hash);
	if (index == -1)
	{
		return 0;
	}
	return &m_DatabaseMem->functions[index];
}

bool clcpp::Database::Load(IFile* file, IAllocator* allocator)
{
	internal::Assert(m_DatabaseMem == 0 && "Database already loaded");
	m_Allocator = allocator;
	m_DatabaseMem = internal::LoadMemoryMappedDatabase(file, m_Allocator);
	return m_DatabaseMem != 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/task.h"
#include "base/timer.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::TimeDelta;

namespace {

class OneShotTimerTester {
 public:
  OneShotTimerTester(bool* did_run, unsigned milliseconds = 10)
      : did_run_(did_run),
        delay_ms_(milliseconds) {
  }
  void Start() {
    timer_.Start(TimeDelta::FromMilliseconds(delay_ms_), this,
                 &OneShotTimerTester::Run);
  }
 private:
  void Run() {
    *did_run_ = true;
    MessageLoop::current()->Quit();
  }
  bool* did_run_;
  base::OneShotTimer<OneShotTimerTester> timer_;
  const unsigned delay_ms_;
};

class OneShotSelfDeletingTimerTester {
 public:
  OneShotSelfDeletingTimerTester(bool* did_run) :
      did_run_(did_run),
      timer_(new base::OneShotTimer<OneShotSelfDeletingTimerTester>()) {
  }
  void Start() {
    timer_->Start(TimeDelta::FromMilliseconds(10), this,
                  &OneShotSelfDeletingTimerTester::Run);
  }
 private:
  void Run() {
    *did_run_ = true;
    timer_.reset();
    MessageLoop::current()->Quit();
  }
  bool* did_run_;
  scoped_ptr<base::OneShotTimer<OneShotSelfDeletingTimerTester> > timer_;
};

class RepeatingTimerTester {
 public:
  RepeatingTimerTester(bool* did_run) : did_run_(did_run), counter_(10) {
  }
  void Start() {
    timer_.Start(TimeDelta::FromMilliseconds(10), this,
                 &RepeatingTimerTester::Run);
  }
 private:
  void Run() {
    if (--counter_ == 0) {
      *did_run_ = true;
      MessageLoop::current()->Quit();
    }
  }
  bool* did_run_;
  int counter_;
  base::RepeatingTimer<RepeatingTimerTester> timer_;
};

void RunTest_OneShotTimer(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run = false;
  OneShotTimerTester f(&did_run);
  f.Start();

  MessageLoop::current()->Run();

  EXPECT_TRUE(did_run);
}

void RunTest_OneShotTimer_Cancel(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run_a = false;
  OneShotTimerTester* a = new OneShotTimerTester(&did_run_a);

  // This should run before the timer expires.
  MessageLoop::current()->DeleteSoon(FROM_HERE, a);

  // Now start the timer.
  a->Start();

  bool did_run_b = false;
  OneShotTimerTester b(&did_run_b);
  b.Start();

  MessageLoop::current()->Run();

  EXPECT_FALSE(did_run_a);
  EXPECT_TRUE(did_run_b);
}

void RunTest_OneShotSelfDeletingTimer(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run = false;
  OneShotSelfDeletingTimerTester f(&did_run);
  f.Start();

  MessageLoop::current()->Run();

  EXPECT_TRUE(did_run);
}

void RunTest_RepeatingTimer(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run = false;
  RepeatingTimerTester f(&did_run);
  f.Start();

  MessageLoop::current()->Run();

  EXPECT_TRUE(did_run);
}

void RunTest_RepeatingTimer_Cancel(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run_a = false;
  RepeatingTimerTester* a = new RepeatingTimerTester(&did_run_a);

  // This should run before the timer expires.
  MessageLoop::current()->DeleteSoon(FROM_HERE, a);

  // Now start the timer.
  a->Start();

  bool did_run_b = false;
  RepeatingTimerTester b(&did_run_b);
  b.Start();

  MessageLoop::current()->Run();

  EXPECT_FALSE(did_run_a);
  EXPECT_TRUE(did_run_b);
}

class DelayTimerTarget {
 public:
  DelayTimerTarget()
      : signaled_(false) {
  }

  bool signaled() const { return signaled_; }

  void Signal() {
    ASSERT_FALSE(signaled_);
    signaled_ = true;
  }

 private:
  bool signaled_;
};

void RunTest_DelayTimer_NoCall(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  // If Delay is never called, the timer shouldn't go off.
  DelayTimerTarget target;
  base::DelayTimer<DelayTimerTarget> timer(
      TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);

  bool did_run = false;
  OneShotTimerTester tester(&did_run);
  tester.Start();
  MessageLoop::current()->Run();

  ASSERT_FALSE(target.signaled());
}

void RunTest_DelayTimer_OneCall(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  DelayTimerTarget target;
  base::DelayTimer<DelayTimerTarget> timer(
      TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
  timer.Reset();

  bool did_run = false;
  OneShotTimerTester tester(&did_run, 100 /* milliseconds */);
  tester.Start();
  MessageLoop::current()->Run();

  ASSERT_TRUE(target.signaled());
}

struct ResetHelper {
  ResetHelper(base::DelayTimer<DelayTimerTarget>* timer,
              DelayTimerTarget* target)
      : timer_(timer),
        target_(target) {
  }

  void Reset() {
    ASSERT_FALSE(target_->signaled());
    timer_->Reset();
  }

 private:
  base::DelayTimer<DelayTimerTarget> *const timer_;
  DelayTimerTarget *const target_;
};

void RunTest_DelayTimer_Reset(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  // If Delay is never called, the timer shouldn't go off.
  DelayTimerTarget target;
  base::DelayTimer<DelayTimerTarget> timer(
      TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
  timer.Reset();

  ResetHelper reset_helper(&timer, &target);

  base::OneShotTimer<ResetHelper> timers[20];
  for (size_t i = 0; i < arraysize(timers); ++i) {
    timers[i].Start(TimeDelta::FromMilliseconds(i * 10), &reset_helper,
                    &ResetHelper::Reset);
  }

  bool did_run = false;
  OneShotTimerTester tester(&did_run, 300);
  tester.Start();
  MessageLoop::current()->Run();

  ASSERT_TRUE(target.signaled());
}

}  // namespace

//-----------------------------------------------------------------------------
// Each test is run against each type of MessageLoop.  That way we are sure
// that timers work properly in all configurations.

TEST(TimerTest, OneShotTimer) {
  RunTest_OneShotTimer(MessageLoop::TYPE_DEFAULT);
  RunTest_OneShotTimer(MessageLoop::TYPE_UI);
  RunTest_OneShotTimer(MessageLoop::TYPE_IO);
}

TEST(TimerTest, OneShotTimer_Cancel) {
  RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_DEFAULT);
  RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_UI);
  RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_IO);
}

// If underline timer does not handle properly, we will crash or fail
// in full page heap or purify environment.
TEST(TimerTest, OneShotSelfDeletingTimer) {
  RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_DEFAULT);
  RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_UI);
  RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_IO);
}

TEST(TimerTest, RepeatingTimer) {
  RunTest_RepeatingTimer(MessageLoop::TYPE_DEFAULT);
  RunTest_RepeatingTimer(MessageLoop::TYPE_UI);
  RunTest_RepeatingTimer(MessageLoop::TYPE_IO);
}

TEST(TimerTest, RepeatingTimer_Cancel) {
  RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_DEFAULT);
  RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_UI);
  RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_IO);
}

TEST(TimerTest, DelayTimer_NoCall) {
  RunTest_DelayTimer_NoCall(MessageLoop::TYPE_DEFAULT);
  RunTest_DelayTimer_NoCall(MessageLoop::TYPE_UI);
  RunTest_DelayTimer_NoCall(MessageLoop::TYPE_IO);
}

TEST(TimerTest, DelayTimer_OneCall) {
  RunTest_DelayTimer_OneCall(MessageLoop::TYPE_DEFAULT);
  RunTest_DelayTimer_OneCall(MessageLoop::TYPE_UI);
  RunTest_DelayTimer_OneCall(MessageLoop::TYPE_IO);
}

TEST(TimerTest, DelayTimer_Reset) {
  RunTest_DelayTimer_Reset(MessageLoop::TYPE_DEFAULT);
  RunTest_DelayTimer_Reset(MessageLoop::TYPE_UI);
  RunTest_DelayTimer_Reset(MessageLoop::TYPE_IO);
}

TEST(TimerTest, MessageLoopShutdown) {
  // This test is designed to verify that shutdown of the
  // message loop does not cause crashes if there were pending
  // timers not yet fired.  It may only trigger exceptions
  // if debug heap checking (or purify) is enabled.
  bool did_run = false;
  {
    OneShotTimerTester a(&did_run);
    OneShotTimerTester b(&did_run);
    OneShotTimerTester c(&did_run);
    OneShotTimerTester d(&did_run);
    {
      MessageLoop loop(MessageLoop::TYPE_DEFAULT);
      a.Start();
      b.Start();
    }  // MessageLoop destructs by falling out of scope.
  }  // OneShotTimers destruct.  SHOULD NOT CRASH, of course.

  EXPECT_EQ(false, did_run);
}
<commit_msg>Build fix<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/scoped_ptr.h"
#include "base/task.h"
#include "base/timer.h"
#include "testing/gtest/include/gtest/gtest.h"

using base::TimeDelta;

namespace {

class OneShotTimerTester {
 public:
  OneShotTimerTester(bool* did_run, unsigned milliseconds = 10)
      : did_run_(did_run),
        delay_ms_(milliseconds) {
  }
  void Start() {
    timer_.Start(TimeDelta::FromMilliseconds(delay_ms_), this,
                 &OneShotTimerTester::Run);
  }
 private:
  void Run() {
    *did_run_ = true;
    MessageLoop::current()->Quit();
  }
  bool* did_run_;
  base::OneShotTimer<OneShotTimerTester> timer_;
  const unsigned delay_ms_;
};

class OneShotSelfDeletingTimerTester {
 public:
  OneShotSelfDeletingTimerTester(bool* did_run) :
      did_run_(did_run),
      timer_(new base::OneShotTimer<OneShotSelfDeletingTimerTester>()) {
  }
  void Start() {
    timer_->Start(TimeDelta::FromMilliseconds(10), this,
                  &OneShotSelfDeletingTimerTester::Run);
  }
 private:
  void Run() {
    *did_run_ = true;
    timer_.reset();
    MessageLoop::current()->Quit();
  }
  bool* did_run_;
  scoped_ptr<base::OneShotTimer<OneShotSelfDeletingTimerTester> > timer_;
};

class RepeatingTimerTester {
 public:
  RepeatingTimerTester(bool* did_run) : did_run_(did_run), counter_(10) {
  }
  void Start() {
    timer_.Start(TimeDelta::FromMilliseconds(10), this,
                 &RepeatingTimerTester::Run);
  }
 private:
  void Run() {
    if (--counter_ == 0) {
      *did_run_ = true;
      MessageLoop::current()->Quit();
    }
  }
  bool* did_run_;
  int counter_;
  base::RepeatingTimer<RepeatingTimerTester> timer_;
};

void RunTest_OneShotTimer(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run = false;
  OneShotTimerTester f(&did_run);
  f.Start();

  MessageLoop::current()->Run();

  EXPECT_TRUE(did_run);
}

void RunTest_OneShotTimer_Cancel(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run_a = false;
  OneShotTimerTester* a = new OneShotTimerTester(&did_run_a);

  // This should run before the timer expires.
  MessageLoop::current()->DeleteSoon(FROM_HERE, a);

  // Now start the timer.
  a->Start();

  bool did_run_b = false;
  OneShotTimerTester b(&did_run_b);
  b.Start();

  MessageLoop::current()->Run();

  EXPECT_FALSE(did_run_a);
  EXPECT_TRUE(did_run_b);
}

void RunTest_OneShotSelfDeletingTimer(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run = false;
  OneShotSelfDeletingTimerTester f(&did_run);
  f.Start();

  MessageLoop::current()->Run();

  EXPECT_TRUE(did_run);
}

void RunTest_RepeatingTimer(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run = false;
  RepeatingTimerTester f(&did_run);
  f.Start();

  MessageLoop::current()->Run();

  EXPECT_TRUE(did_run);
}

void RunTest_RepeatingTimer_Cancel(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  bool did_run_a = false;
  RepeatingTimerTester* a = new RepeatingTimerTester(&did_run_a);

  // This should run before the timer expires.
  MessageLoop::current()->DeleteSoon(FROM_HERE, a);

  // Now start the timer.
  a->Start();

  bool did_run_b = false;
  RepeatingTimerTester b(&did_run_b);
  b.Start();

  MessageLoop::current()->Run();

  EXPECT_FALSE(did_run_a);
  EXPECT_TRUE(did_run_b);
}

class DelayTimerTarget {
 public:
  DelayTimerTarget()
      : signaled_(false) {
  }

  bool signaled() const { return signaled_; }

  void Signal() {
    ASSERT_FALSE(signaled_);
    signaled_ = true;
  }

 private:
  bool signaled_;
};

void RunTest_DelayTimer_NoCall(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  // If Delay is never called, the timer shouldn't go off.
  DelayTimerTarget target;
  base::DelayTimer<DelayTimerTarget> timer(
      TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);

  bool did_run = false;
  OneShotTimerTester tester(&did_run);
  tester.Start();
  MessageLoop::current()->Run();

  ASSERT_FALSE(target.signaled());
}

void RunTest_DelayTimer_OneCall(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  DelayTimerTarget target;
  base::DelayTimer<DelayTimerTarget> timer(
      TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal);
  timer.Reset();

  bool did_run = false;
  OneShotTimerTester tester(&did_run, 100 /* milliseconds */);
  tester.Start();
  MessageLoop::current()->Run();

  ASSERT_TRUE(target.signaled());
}

struct ResetHelper {
  ResetHelper(base::DelayTimer<DelayTimerTarget>* timer,
              DelayTimerTarget* target)
      : timer_(timer),
        target_(target) {
  }

  void Reset() {
    ASSERT_FALSE(target_->signaled());
    timer_->Reset();
  }

 private:
  base::DelayTimer<DelayTimerTarget> *const timer_;
  DelayTimerTarget *const target_;
};

void RunTest_DelayTimer_Reset(MessageLoop::Type message_loop_type) {
  MessageLoop loop(message_loop_type);

  // If Delay is never called, the timer shouldn't go off.
  DelayTimerTarget target;
  base::DelayTimer<DelayTimerTarget> timer(
      TimeDelta::FromMilliseconds(50), &target, &DelayTimerTarget::Signal);
  timer.Reset();

  ResetHelper reset_helper(&timer, &target);

  base::OneShotTimer<ResetHelper> timers[20];
  for (size_t i = 0; i < arraysize(timers); ++i) {
    timers[i].Start(TimeDelta::FromMilliseconds(i * 10), &reset_helper,
                    &ResetHelper::Reset);
  }

  bool did_run = false;
  OneShotTimerTester tester(&did_run, 300);
  tester.Start();
  MessageLoop::current()->Run();

  ASSERT_TRUE(target.signaled());
}

}  // namespace

//-----------------------------------------------------------------------------
// Each test is run against each type of MessageLoop.  That way we are sure
// that timers work properly in all configurations.

TEST(TimerTest, OneShotTimer) {
  RunTest_OneShotTimer(MessageLoop::TYPE_DEFAULT);
  RunTest_OneShotTimer(MessageLoop::TYPE_UI);
  RunTest_OneShotTimer(MessageLoop::TYPE_IO);
}

TEST(TimerTest, OneShotTimer_Cancel) {
  RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_DEFAULT);
  RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_UI);
  RunTest_OneShotTimer_Cancel(MessageLoop::TYPE_IO);
}

// If underline timer does not handle properly, we will crash or fail
// in full page heap or purify environment.
TEST(TimerTest, OneShotSelfDeletingTimer) {
  RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_DEFAULT);
  RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_UI);
  RunTest_OneShotSelfDeletingTimer(MessageLoop::TYPE_IO);
}

TEST(TimerTest, RepeatingTimer) {
  RunTest_RepeatingTimer(MessageLoop::TYPE_DEFAULT);
  RunTest_RepeatingTimer(MessageLoop::TYPE_UI);
  RunTest_RepeatingTimer(MessageLoop::TYPE_IO);
}

TEST(TimerTest, RepeatingTimer_Cancel) {
  RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_DEFAULT);
  RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_UI);
  RunTest_RepeatingTimer_Cancel(MessageLoop::TYPE_IO);
}

TEST(TimerTest, DelayTimer_NoCall) {
  RunTest_DelayTimer_NoCall(MessageLoop::TYPE_DEFAULT);
  RunTest_DelayTimer_NoCall(MessageLoop::TYPE_UI);
  RunTest_DelayTimer_NoCall(MessageLoop::TYPE_IO);
}

TEST(TimerTest, DelayTimer_OneCall) {
  RunTest_DelayTimer_OneCall(MessageLoop::TYPE_DEFAULT);
  RunTest_DelayTimer_OneCall(MessageLoop::TYPE_UI);
  RunTest_DelayTimer_OneCall(MessageLoop::TYPE_IO);
}

TEST(TimerTest, DelayTimer_Reset) {
  RunTest_DelayTimer_Reset(MessageLoop::TYPE_DEFAULT);
  RunTest_DelayTimer_Reset(MessageLoop::TYPE_UI);
  RunTest_DelayTimer_Reset(MessageLoop::TYPE_IO);
}

TEST(TimerTest, MessageLoopShutdown) {
  // This test is designed to verify that shutdown of the
  // message loop does not cause crashes if there were pending
  // timers not yet fired.  It may only trigger exceptions
  // if debug heap checking (or purify) is enabled.
  bool did_run = false;
  {
    OneShotTimerTester a(&did_run);
    OneShotTimerTester b(&did_run);
    OneShotTimerTester c(&did_run);
    OneShotTimerTester d(&did_run);
    {
      MessageLoop loop(MessageLoop::TYPE_DEFAULT);
      a.Start();
      b.Start();
    }  // MessageLoop destructs by falling out of scope.
  }  // OneShotTimers destruct.  SHOULD NOT CRASH, of course.

  EXPECT_EQ(false, did_run);
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QSettings>
#include <QLabel>
#include <QWSServer>
#include <QProgressBar>
#include "choiceview.h"
#include "spawner.h"
#include "footer.h"

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  QRect max(0, 0, 600, 800 - 26);
  QWSServer::setMaxWindowRect(max);

//  app.setStyleSheet("ChoiceView { background: white }");

  QSettings settings("runcible", "lobby");
  QString browsePath = settings.value("browse-path", "/home").toString();
  QUrl browseUrl("file:" + browsePath);

  Footer statusBar;
  statusBar.setWindowFlags(Qt::FramelessWindowHint);
  statusBar.move(0, 800-26);
  statusBar.resize(600, 26);

  statusBar.show();

  ChoiceView view;
  view.setWindowFlags(Qt::FramelessWindowHint);
  view.setChoices(QList<Choice>()
      << Choice(QObject::tr("Browse"), browseUrl.toString())
      );

  Spawner spawner;

  QObject::connect(&view, SIGNAL(back()), &app, SLOT(quit()));
  QObject::connect(&view, SIGNAL(choiceMade(Choice)), &spawner, SLOT(openId(Choice)));
  QObject::connect(QWSServer::instance(), SIGNAL(windowEvent(QWSWindow *, QWSServer::WindowEvent)),
      &statusBar, SLOT(windowEvent(QWSWindow *, QWSServer::WindowEvent)));

  view.setWindowTitle("Lobby");
  view.setWindowFlags(Qt::FramelessWindowHint);
  view.showMaximized();

  return app.exec();
}
<commit_msg>Removed unnecessary includes<commit_after>#include <QApplication>
#include <QSettings>
#include <QWSServer>
#include "choiceview.h"
#include "spawner.h"
#include "footer.h"

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  QRect max(0, 0, 600, 800 - 26);
  QWSServer::setMaxWindowRect(max);

//  app.setStyleSheet("ChoiceView { background: white }");

  QSettings settings("runcible", "lobby");
  QString browsePath = settings.value("browse-path", "/home").toString();
  QUrl browseUrl("file:" + browsePath);

  Footer statusBar;
  statusBar.setWindowFlags(Qt::FramelessWindowHint);
  statusBar.move(0, 800-26);
  statusBar.resize(600, 26);

  statusBar.show();

  ChoiceView view;
  view.setWindowFlags(Qt::FramelessWindowHint);
  view.setChoices(QList<Choice>()
      << Choice(QObject::tr("Browse"), browseUrl.toString())
      );

  Spawner spawner;

  QObject::connect(&view, SIGNAL(back()), &app, SLOT(quit()));
  QObject::connect(&view, SIGNAL(choiceMade(Choice)), &spawner, SLOT(openId(Choice)));
  QObject::connect(QWSServer::instance(), SIGNAL(windowEvent(QWSWindow *, QWSServer::WindowEvent)),
      &statusBar, SLOT(windowEvent(QWSWindow *, QWSServer::WindowEvent)));

  view.setWindowTitle("Lobby");
  view.setWindowFlags(Qt::FramelessWindowHint);
  view.showMaximized();

  return app.exec();
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;

fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
                               const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
                               const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
        fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
        fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
        fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
        fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
        uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
            l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
            l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );

            if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
            }
            else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
            {
                l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
                l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
                l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
                FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
            }
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
            l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
                {
                    l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_def_mn_freq_ratio <= literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
                }
                else if ((l_def_mn_freq_ratio > literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>HCODE: DD21 makefile changes for CME,PGPE and SGPE<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9n_mcs_scom.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9n_mcs_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0b0111 = 0b0111;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_1 = 1;
constexpr uint64_t literal_8 = 8;
constexpr uint64_t literal_25 = 25;
constexpr uint64_t literal_0b001111 = 0b001111;
constexpr uint64_t literal_0b0001100000000 = 0b0001100000000;
constexpr uint64_t literal_1350 = 1350;
constexpr uint64_t literal_1000 = 1000;
constexpr uint64_t literal_0b0000000000001000 = 0b0000000000001000;

fapi2::ReturnCode p9n_mcs_scom(const fapi2::Target<fapi2::TARGET_TYPE_MCS>& TGT0,
                               const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1, const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT2,
                               const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& TGT3)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT2, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT2, l_chip_ec));
        fapi2::ATTR_CHIP_EC_FEATURE_HW398139_Type l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW398139, TGT2, l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139));
        fapi2::ATTR_RISK_LEVEL_Type l_TGT1_ATTR_RISK_LEVEL;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_RISK_LEVEL, TGT1, l_TGT1_ATTR_RISK_LEVEL));
        fapi2::ATTR_FREQ_PB_MHZ_Type l_TGT1_ATTR_FREQ_PB_MHZ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FREQ_PB_MHZ, TGT1, l_TGT1_ATTR_FREQ_PB_MHZ));
        fapi2::ATTR_MSS_FREQ_Type l_TGT3_ATTR_MSS_FREQ;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, TGT3, l_TGT3_ATTR_MSS_FREQ));
        uint64_t l_def_mn_freq_ratio = ((literal_1000 * l_TGT3_ATTR_MSS_FREQ) / l_TGT1_ATTR_FREQ_PB_MHZ);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010810ull, l_scom_buffer ));

            l_scom_buffer.insert<46, 4, 60, uint64_t>(literal_0b0111 );
            l_scom_buffer.insert<62, 1, 63, uint64_t>(literal_0 );
            constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON = 0x1;
            l_scom_buffer.insert<61, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PF_DROP_CMDLIST_ON );

            if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 == literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_8 );
            }
            else if ((l_TGT2_ATTR_CHIP_EC_FEATURE_HW398139 != literal_1))
            {
                l_scom_buffer.insert<32, 7, 57, uint64_t>(literal_25 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                l_scom_buffer.insert<55, 6, 58, uint64_t>(literal_0b001111 );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                constexpr auto l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCPERF1_ENABLE_PREFETCH_PROMOTE_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010810ull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x5010811ull, l_scom_buffer ));

                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON = 0x1;
                l_scom_buffer.insert<20, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_CENTAUR_SYNC_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON = 0x1;
                l_scom_buffer.insert<9, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_64_128B_READ_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON = 0x1;
                l_scom_buffer.insert<8, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_ENABLE_DROP_FP_DYN64_ACTIVE_ON );
                constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF = 0x0;
                l_scom_buffer.insert<7, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE0_CENTAURP_ENABLE_ECRESP_OFF );
                FAPI_TRY(fapi2::putScom(TGT0, 0x5010811ull, l_scom_buffer));
            }
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010812ull, l_scom_buffer ));

            constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON = 0x1;
            l_scom_buffer.insert<10, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE1_DISABLE_FP_M_BIT_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5010812ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5010813ull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_TGT1_ATTR_RISK_LEVEL == literal_0))
                {
                    l_scom_buffer.insert<1, 13, 51, uint64_t>(literal_0b0001100000000 );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                if ((l_def_mn_freq_ratio <= literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF = 0x0;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_OFF );
                }
                else if ((l_def_mn_freq_ratio > literal_1350))
                {
                    constexpr auto l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON = 0x1;
                    l_scom_buffer.insert<0, 1, 63, uint64_t>(l_MC01_PBI01_SCOMFIR_MCMODE2_FORCE_SFSTAT_ACTIVE_ON );
                }
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) )
            {
                l_scom_buffer.insert<24, 16, 48, uint64_t>(literal_0b0000000000001000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x5010813ull, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/**********************************************************\

  This file is distributed under the MIT License.
  See accompanying file LICENSE for details.

  tests/SimpleTreeTester.cpp

\**********************************************************/

#include "TestSettings.h"

#ifdef TEST_SIMPLE_TREE

#undef NDEBUG

#include "../../momo/TreeSet.h"
#include "../../momo/TreeMap.h"

#include <string>
#include <iostream>

class SimpleTreeTester
{
public:
	static void TestAll()
	{
		std::cout << "TreeSet: " << std::flush;
		TestStrTreeSet();
		std::cout << "ok" << std::endl;

		std::cout << "TreeMap: " << std::flush;
		TestStrTreeMap();
		std::cout << "ok" << std::endl;
	}

	static void TestStrTreeSet()
	{
		typedef momo::TreeSet<std::string> TreeSet;
		std::string s1 = "s1";
		TreeSet set = { s1, "s2" };
		set.Insert("s3");
		set = set;
		set = std::move(set);
		assert(set.GetCount() == 3);
		assert(set.HasKey("s2"));
		typename TreeSet::ConstIterator iter = set.Find("s1");
		assert(*iter == "s1");
		typename TreeSet::ExtractedItem rs;
		set.Remove(iter, rs);
		assert(rs.GetItem() == "s1");
		iter = set.Find("s1");
		assert(iter == set.GetEnd());
		set.Insert(&s1, &s1 + 1);
		set.ResetKey(set.LowerBound("s1"), s1);
		set.ResetKey(set.UpperBound(s1), "s2");
		set.Remove("s2");
		for (const std::string& s : set)
			assert(s == "s1" || s == "s3");
		set.Clear();
		assert(set.IsEmpty());
	}

	static void TestStrTreeMap()
	{
		typedef momo::TreeMap<std::string, std::string> TreeMap;
		std::string s1 = "s1";
		std::string s2 = "s2";
		std::string s3 = "s3";
		std::string s4 = "s4";
		std::string s5 = "s5";
		TreeMap map = { {"s1", "s1"}, {"s2", s2} };
		map.Insert(s3, "s3");
		map.Insert(s4, s4);
		map[s5] = "s5";
		assert((std::string)map["s5"] == s5);
		map["s6"] = "s6";
		map.ResetKey(map.LowerBound("s1"), s1);
		map.ResetKey(map.UpperBound(s1), "s2");
		map = map;
		map = std::move(map);
		assert(map.GetCount() == 6);
		assert(map.HasKey(s2));
		typename TreeMap::ConstIterator iter1 = map.Find(s1);
		assert(iter1->key == s1 && iter1->value == s1);
		map.Remove(s1);
		typename TreeMap::Iterator iter2 = map.Find("s5");
		assert(iter2->key == s5 && iter2->value == s5);
		map.Remove(iter2);
		map.Remove(s3);
		map.Remove("s4");
		std::pair<std::string, std::string> pair("s4", s4);
		map.InsertFS(&pair, &pair + 1);
		map.InsertKV(map.Find(s2), std::next(map.Find(s2)));	//?
		assert(map.GetCount() == 3);
		map.Remove(s4);
		for (auto ref : map)
			assert(ref.value == "s2" || ref.value == "s6");
		for (auto ref : (const TreeMap&)map)
			assert(ref.value == "s2" || ref.value == "s6");
		assert(map.GetCount() == 2);
		map.Clear();
		assert(map.IsEmpty());
	}
};

static int testSimpleTree = (SimpleTreeTester::TestAll(), 0);

#endif // TEST_SIMPLE_TREE
<commit_msg>SimpleTreeTester<commit_after>/**********************************************************\

  This file is distributed under the MIT License.
  See accompanying file LICENSE for details.

  tests/SimpleTreeTester.cpp

\**********************************************************/

#include "TestSettings.h"

#ifdef TEST_SIMPLE_TREE

#undef NDEBUG

#include "../../momo/TreeSet.h"
#include "../../momo/TreeMap.h"

#include <string>
#include <iostream>

class SimpleTreeTester
{
public:
	static void TestAll()
	{
		std::cout << "momo::TreeSet: " << std::flush;
		TestStrTreeSet();
		std::cout << "ok" << std::endl;

		std::cout << "momo::TreeMap: " << std::flush;
		TestStrTreeMap();
		std::cout << "ok" << std::endl;
	}

	static void TestStrTreeSet()
	{
		typedef momo::TreeSet<std::string> TreeSet;
		std::string s1 = "s1";
		TreeSet set = { s1, "s2" };
		set.Insert("s3");
		set = set;
		set = std::move(set);
		assert(set.GetCount() == 3);
		assert(set.HasKey("s2"));
		typename TreeSet::ConstIterator iter = set.Find("s1");
		assert(*iter == "s1");
		typename TreeSet::ExtractedItem rs;
		set.Remove(iter, rs);
		assert(rs.GetItem() == "s1");
		iter = set.Find("s1");
		assert(iter == set.GetEnd());
		set.Insert(&s1, &s1 + 1);
		set.ResetKey(set.LowerBound("s1"), s1);
		set.ResetKey(set.UpperBound(s1), "s2");
		set.Remove("s2");
		for (const std::string& s : set)
			assert(s == "s1" || s == "s3");
		set.Clear();
		assert(set.IsEmpty());
	}

	static void TestStrTreeMap()
	{
		typedef momo::TreeMap<std::string, std::string> TreeMap;
		std::string s1 = "s1";
		std::string s2 = "s2";
		std::string s3 = "s3";
		std::string s4 = "s4";
		std::string s5 = "s5";
		TreeMap map = { {"s1", "s1"}, {"s2", s2} };
		map.Insert(s3, "s3");
		map.Insert(s4, s4);
		map[s5] = "s5";
		assert((std::string)map["s5"] == s5);
		map["s6"] = "s6";
		map.ResetKey(map.LowerBound("s1"), s1);
		map.ResetKey(map.UpperBound(s1), "s2");
		map = map;
		map = std::move(map);
		assert(map.GetCount() == 6);
		assert(map.HasKey(s2));
		typename TreeMap::ConstIterator iter1 = map.Find(s1);
		assert(iter1->key == s1 && iter1->value == s1);
		map.Remove(s1);
		typename TreeMap::Iterator iter2 = map.Find("s5");
		assert(iter2->key == s5 && iter2->value == s5);
		map.Remove(iter2);
		map.Remove(s3);
		map.Remove("s4");
		std::pair<std::string, std::string> pair("s4", s4);
		map.InsertFS(&pair, &pair + 1);
		map.InsertKV(map.Find(s2), std::next(map.Find(s2)));	//?
		assert(map.GetCount() == 3);
		map.Remove(s4);
		for (auto ref : map)
			assert(ref.value == "s2" || ref.value == "s6");
		for (auto ref : (const TreeMap&)map)
			assert(ref.value == "s2" || ref.value == "s6");
		assert(map.GetCount() == 2);
		map.Clear();
		assert(map.IsEmpty());
	}
};

static int testSimpleTree = (SimpleTreeTester::TestAll(), 0);

#endif // TEST_SIMPLE_TREE
<|endoftext|>