<commit_before>// Catch
#include <catch.hpp>

// C++ Standard Library
#include <cstdlib>
#include <cmath>

// Mantella
#include <mantella>

TEST_CASE("random: getRandomRotationMatrix", "") {
  SECTION("Generates uniform distributed 2-dimensional rotation.") {
    arma::Col<double>::fixed<10000> angles;
    for (std::size_t n = 0; n < angles.n_elem; ++n) {
      arma::Col<double>::fixed<2> rotatedUnitVector = mant::getRandomRotationMatrix(2) * arma::Col<double>::fixed<2>({-2, 1});
      angles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
    }

    arma::Col<unsigned int> histogram = arma::histc(angles, arma::linspace<arma::Col<double>>(-arma::datum::pi, arma::datum::pi, 10));
    CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / angles.n_elem);
  }

  SECTION("Generates uniform distributed 3-dimensional rotation.") {
    arma::Col<double>::fixed<10000> rollAngles;
    arma::Col<double>::fixed<10000> pitchAngles;
    arma::Col<double>::fixed<10000> yawAngles;
    for (std::size_t n = 0; n < rollAngles.n_elem; ++n) {
      arma::Col<double>::fixed<3> rotatedUnitVector = mant::getRandomRotationMatrix(3) * arma::Col<double>::fixed<3>({-2, 1, 3});
      rollAngles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
      pitchAngles.at(n) = std::atan2(rotatedUnitVector.at(2), rotatedUnitVector.at(1));
      yawAngles.at(n) = std::atan2(rotatedUnitVector.at(0), rotatedUnitVector.at(2));
    }

    arma::Col<unsigned int> histogram;

    histogram = arma::histc(rollAngles, arma::linspace<arma::Col<double>>(-arma::datum::pi, arma::datum::pi, 10));
    CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / rollAngles.n_elem);

    histogram = arma::histc(pitchAngles, arma::linspace<arma::Col<double>>(-arma::datum::pi, arma::datum::pi, 10));
    CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / pitchAngles.n_elem);

    histogram = arma::histc(yawAngles, arma::linspace<arma::Col<double>>(-arma::datum::pi, arma::datum::pi, 10));
    CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / yawAngles.n_elem);
  }
}

TEST_CASE("random: getRandomPermutation(unsigned int, unsigned int)", "") {
  SECTION("Generates uniform distributed partitial permutations.") {
    arma::Mat<unsigned int>::fixed<10, 40000> permutations;
    for (std::size_t n = 0; n < permutations.n_cols; ++n) {
      permutations.col(n) = mant::getRandomPermutation(static_cast<unsigned int>(permutations.n_rows) + 1, static_cast<unsigned int>(permutations.n_rows));
    }

    arma::Col<unsigned int> centers(permutations.n_rows);
    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      centers.at(n) = n;
    }

    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      arma::Row<unsigned int> histogram = arma::hist(permutations.row(n), centers);
      CHECK(0.1 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
    }
  }

  SECTION("Throws an exception, if cycle size > number of elements.") {
    CHECK_THROWS_AS(mant::getRandomPermutation(10, 11), std::logic_error);
  }
}

TEST_CASE("random: getRandomPermutation(unsigned int)", "") {
  SECTION("Generates uniform distributed permutations.") {
    arma::Mat<unsigned int>::fixed<10, 10000> permutations;
    for (std::size_t n = 0; n < permutations.n_cols; ++n) {
      permutations.col(n) = mant::getRandomPermutation(static_cast<unsigned int>(permutations.n_rows));
    }

    arma::Col<unsigned int> centers(permutations.n_rows);
    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      centers.at(n) = n;
    }

    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      arma::Row<unsigned int> histogram = arma::hist(permutations.row(n), centers);
      CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
    }
  }
}

<commit_msg>test: Fixed the histogram used in testRandom<commit_after>// Catch
#include <catch.hpp>

// C++ Standard Library
#include <cstdlib>
#include <cmath>

// Mantella
#include <mantella>

TEST_CASE("random: getRandomRotationMatrix", "") {
  SECTION("Generates uniform distributed 2-dimensional rotation.") {
    arma::Col<double>::fixed<10000> angles;
    for (std::size_t n = 0; n < angles.n_elem; ++n) {
      arma::Col<double>::fixed<2> rotatedUnitVector = mant::getRandomRotationMatrix(2) * arma::Col<double>::fixed<2>({-2.0, 1.0});
      angles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
    }

    arma::Col<unsigned int> histogram = arma::hist(angles, arma::linspace<arma::Col<double>>(-arma::datum::pi + arma::datum::pi/10.0, arma::datum::pi - arma::datum::pi/10.0, 10));
    CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / angles.n_elem);
  }

  SECTION("Generates uniform distributed 3-dimensional rotation.") {
    arma::Col<double>::fixed<10000> rollAngles;
    arma::Col<double>::fixed<10000> pitchAngles;
    arma::Col<double>::fixed<10000> yawAngles;
    for (std::size_t n = 0; n < rollAngles.n_elem; ++n) {
      arma::Col<double>::fixed<3> rotatedUnitVector = mant::getRandomRotationMatrix(3) * arma::Col<double>::fixed<3>({-2.0, 1.0, 3.0});
      rollAngles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
      pitchAngles.at(n) = std::atan2(rotatedUnitVector.at(2), rotatedUnitVector.at(1));
      yawAngles.at(n) = std::atan2(rotatedUnitVector.at(0), rotatedUnitVector.at(2));
    }

    arma::Col<unsigned int> histogram;

    histogram = arma::hist(rollAngles, arma::linspace<arma::Col<double>>(-arma::datum::pi + arma::datum::pi/10.0, arma::datum::pi - arma::datum::pi/10.0, 10));
    CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / rollAngles.n_elem);

    histogram = arma::hist(pitchAngles, arma::linspace<arma::Col<double>>(-arma::datum::pi + arma::datum::pi/10.0, arma::datum::pi - arma::datum::pi/10.0, 10));
    CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / pitchAngles.n_elem);

    histogram = arma::hist(yawAngles, arma::linspace<arma::Col<double>>(-arma::datum::pi + arma::datum::pi/10.0, arma::datum::pi - arma::datum::pi/10.0, 10));
    CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / yawAngles.n_elem);
  }
}

TEST_CASE("random: getRandomPermutation(unsigned int, unsigned int)", "") {
  SECTION("Generates uniform distributed partitial permutations.") {
    arma::Mat<unsigned int>::fixed<10, 40000> permutations;
    for (std::size_t n = 0; n < permutations.n_cols; ++n) {
      permutations.col(n) = mant::getRandomPermutation(static_cast<unsigned int>(permutations.n_rows) + 1, static_cast<unsigned int>(permutations.n_rows));
    }

    arma::Col<unsigned int> centers(permutations.n_rows);
    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      centers.at(n) = n;
    }

    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      arma::Row<unsigned int> histogram = arma::hist(permutations.row(n), centers);
      CHECK(0.1 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
    }
  }

  SECTION("Throws an exception, if cycle size > number of elements.") {
    CHECK_THROWS_AS(mant::getRandomPermutation(10, 11), std::logic_error);
  }
}

TEST_CASE("random: getRandomPermutation(unsigned int)", "") {
  SECTION("Generates uniform distributed permutations.") {
    arma::Mat<unsigned int>::fixed<10, 10000> permutations;
    for (std::size_t n = 0; n < permutations.n_cols; ++n) {
      permutations.col(n) = mant::getRandomPermutation(static_cast<unsigned int>(permutations.n_rows));
    }

    arma::Col<unsigned int> centers(permutations.n_rows);
    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      centers.at(n) = n;
    }

    for (std::size_t n = 0; n < permutations.n_rows; ++n) {
      arma::Row<unsigned int> histogram = arma::hist(permutations.row(n), centers);
      CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
    }
  }
}

<|endoftext|>


<commit_before>/* Copyright (c) 2011-2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <map>
#include <string>
#include <gtest/gtest.h>

#include "Common.h"

namespace DLog {

namespace {

using std::map;
using std::pair;
using std::string;
using std::vector;

class TObj {
  public:
    explicit TObj(const std::string& name) {
        EXPECT_EQ("foo", name);
        ++liveCount;
    }
    ~TObj() { --liveCount; }
    static uint32_t liveCount;
};
uint32_t TObj::liveCount;

const map<int, string> empty {};

const map<int, string> digits {
    { 1, "one" },
    { 2, "two" },
    { 3, "three" },
};

} // anonymous namespace

TEST(unique, basic) {
    TObj::liveCount = 0;
    {
        std::unique_ptr<TObj> x = unique<TObj>("foo");
        EXPECT_EQ(1U, TObj::liveCount);
    }
    EXPECT_EQ(0U, TObj::liveCount);
}

TEST(downCast, basic) {
    EXPECT_DEATH(downCast<uint8_t>(256), "");
    EXPECT_DEATH(downCast<int8_t>(192), "");
    EXPECT_DEATH(downCast<uint8_t>(-10), "");
    uint8_t x = downCast<uint8_t>(55UL);
    EXPECT_EQ(55, x);
}

TEST(sorted, basic) {
    EXPECT_EQ((vector<int> {}),
              sorted(vector<int> {}));
    EXPECT_EQ((vector<int> { 1, 5, 7}),
              sorted(vector<int> {5, 1, 7}));
}

TEST(getKeys, basic) {
    EXPECT_EQ((vector<int>{}),
              getKeys(empty));
    EXPECT_EQ((vector<int>{ 1, 2, 3 }),
              getKeys(digits));
}

TEST(getValues, basic) {
    EXPECT_EQ((vector<string>{}),
              getValues(empty));
    EXPECT_EQ((vector<string>{ "one", "two", "three" }),
              getValues(digits));
}

TEST(getItems, basic) {
    EXPECT_EQ((vector<pair<int, string>>{}),
              getItems(empty));
    EXPECT_EQ((vector<pair<int, string>>{
                    {1, "one"},
                    {2, "two"},
                    {3, "three"},
               }),
              getItems(digits));
}

TEST(hasOnly, basic) {
    EXPECT_TRUE(hasOnly((vector<int>{}), 1));
    EXPECT_TRUE(hasOnly((vector<int>{1}), 1));
    EXPECT_TRUE(hasOnly((vector<int>{1, 1}), 1));
    EXPECT_TRUE(hasOnly((vector<int>{1, 1, 1}), 1));
    EXPECT_FALSE(hasOnly((vector<int>{1, 2}), 1));
    EXPECT_FALSE(hasOnly((vector<int>{1, 2}), 2));
}

// Tests for format come from the RAMCloud project.
TEST(format, basic) {
    EXPECT_EQ("rofl3", format("rofl3"));
    EXPECT_EQ("rofl3", format("r%sl%d", "of", 3));
}

TEST(format, large) {
    char x[3000];
    memset(x, 0xcc, sizeof(x));
    x[sizeof(x) - 1] = '\0';
    EXPECT_EQ(x, format("%s", x));
}

TEST(isPrintable, str) {
    EXPECT_TRUE(isPrintable(""));
    EXPECT_TRUE(isPrintable("foo"));
    EXPECT_FALSE(isPrintable("\n"));
}

TEST(isPrintable, data) {
    EXPECT_FALSE(isPrintable("", 0));
    EXPECT_TRUE(isPrintable("", 1));
    EXPECT_TRUE(isPrintable("foo", 4));
    EXPECT_FALSE(isPrintable("foo", 3));
    EXPECT_FALSE(isPrintable("\n", 2));
}

} // namespace DLog
<commit_msg>Put include/Common.h tests into a single test case<commit_after>/* Copyright (c) 2011-2012 Stanford University
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <map>
#include <string>
#include <gtest/gtest.h>

#include "Common.h"

namespace DLog {

namespace {

using std::map;
using std::pair;
using std::string;
using std::vector;

class TObj {
  public:
    explicit TObj(const std::string& name) {
        EXPECT_EQ("foo", name);
        ++liveCount;
    }
    ~TObj() { --liveCount; }
    static uint32_t liveCount;
};
uint32_t TObj::liveCount;

const map<int, string> empty {};

const map<int, string> digits {
    { 1, "one" },
    { 2, "two" },
    { 3, "three" },
};

} // anonymous namespace

TEST(Common, unique) {
    TObj::liveCount = 0;
    {
        std::unique_ptr<TObj> x = unique<TObj>("foo");
        EXPECT_EQ(1U, TObj::liveCount);
    }
    EXPECT_EQ(0U, TObj::liveCount);
}

TEST(Common, downCast) {
    EXPECT_DEATH(downCast<uint8_t>(256), "");
    EXPECT_DEATH(downCast<int8_t>(192), "");
    EXPECT_DEATH(downCast<uint8_t>(-10), "");
    uint8_t x = downCast<uint8_t>(55UL);
    EXPECT_EQ(55, x);
}

TEST(Common, sorted) {
    EXPECT_EQ((vector<int> {}),
              sorted(vector<int> {}));
    EXPECT_EQ((vector<int> { 1, 5, 7}),
              sorted(vector<int> {5, 1, 7}));
}

TEST(Common, getKeys) {
    EXPECT_EQ((vector<int>{}),
              getKeys(empty));
    EXPECT_EQ((vector<int>{ 1, 2, 3 }),
              getKeys(digits));
}

TEST(Common, getValues) {
    EXPECT_EQ((vector<string>{}),
              getValues(empty));
    EXPECT_EQ((vector<string>{ "one", "two", "three" }),
              getValues(digits));
}

TEST(Common, getItems) {
    EXPECT_EQ((vector<pair<int, string>>{}),
              getItems(empty));
    EXPECT_EQ((vector<pair<int, string>>{
                    {1, "one"},
                    {2, "two"},
                    {3, "three"},
               }),
              getItems(digits));
}

TEST(Common, hasOnly) {
    EXPECT_TRUE(hasOnly((vector<int>{}), 1));
    EXPECT_TRUE(hasOnly((vector<int>{1}), 1));
    EXPECT_TRUE(hasOnly((vector<int>{1, 1}), 1));
    EXPECT_TRUE(hasOnly((vector<int>{1, 1, 1}), 1));
    EXPECT_FALSE(hasOnly((vector<int>{1, 2}), 1));
    EXPECT_FALSE(hasOnly((vector<int>{1, 2}), 2));
}

// Tests for format come from the RAMCloud project.
TEST(Common, formatBasic) {
    EXPECT_EQ("rofl3", format("rofl3"));
    EXPECT_EQ("rofl3", format("r%sl%d", "of", 3));
}

TEST(Common, formatLarge) {
    char x[3000];
    memset(x, 0xcc, sizeof(x));
    x[sizeof(x) - 1] = '\0';
    EXPECT_EQ(x, format("%s", x));
}

TEST(Common, isPrintableStr) {
    EXPECT_TRUE(isPrintable(""));
    EXPECT_TRUE(isPrintable("foo"));
    EXPECT_FALSE(isPrintable("\n"));
}

TEST(Common, isPrintableData) {
    EXPECT_FALSE(isPrintable("", 0));
    EXPECT_TRUE(isPrintable("", 1));
    EXPECT_TRUE(isPrintable("foo", 4));
    EXPECT_FALSE(isPrintable("foo", 3));
    EXPECT_FALSE(isPrintable("\n", 2));
}

} // namespace DLog
<|endoftext|>


<commit_before>/****************************************************************************
**
** This file is part of QMime
**
** Based on Qt Creator source code
**
** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
**
** 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.
**
****************************************************************************/

#include "qmimetype.h"   // Basis

#include "qmimetype_p.h"
#include "qmimedatabase_p.h"
#include "qmimeprovider_p.h"

#include "qmimeglobpattern_p.h"

#include <QtCore/QDebug>
#include <QtCore/QLocale>

QT_BEGIN_NAMESPACE

bool isQMimeTypeDebuggingActivated (false);

#ifndef QT_NO_DEBUG_OUTPUT
#define DBG() if (isQMimeTypeDebuggingActivated) qDebug() << Q_FUNC_INFO
#else
#define DBG() if (0) qDebug() << Q_FUNC_INFO
#endif

QMimeTypePrivate::QMimeTypePrivate()
{}

QMimeTypePrivate::QMimeTypePrivate(const QMimeType &other)
        : name(other.d->name)
        //, comment(other.d->comment)
        , localeComments(other.d->localeComments)
        , genericIconName(other.d->genericIconName)
        , iconName(other.d->iconName)
        , globPatterns(other.d->globPatterns)
{}

void QMimeTypePrivate::clear()
{
    name.clear();
    //comment.clear();
    localeComments.clear();
    genericIconName.clear();
    iconName.clear();
    globPatterns.clear();
}

/*!
    \fn bool QMimeTypePrivate::operator==(const QMimeTypePrivate &other) const;
    \brief Returns if the \a other object has the same value.
 */
bool QMimeTypePrivate::operator==(const QMimeTypePrivate &other) const
{
    return name == other.name &&
            //comment == other.comment &&
            localeComments == other.localeComments &&
            genericIconName == other.genericIconName &&
            iconName == other.iconName &&
            globPatterns == other.globPatterns;
}

void QMimeTypePrivate::addGlobPattern(const QString &pattern)
{
    globPatterns.append(pattern);
}

/*!
    \class QMimeType

    \brief The QMimeType class describes types of file or data, represented by a MIME type string.

    For instance a file named "readme.txt" has the MIME type "text/plain".
    The MIME type can be determined from the file name, or from the file
    contents, or from both. MIME type determination can also be done on
    buffers of data not coming from files.

    Determining the MIME type of a file can be useful to make sure your
    application supports it. It is also useful in file-manager-like applications
    or widgets, in order to display an appropriate icon() for the file, or even
    the descriptive comment() in detailed views.

    To check if a file has the expected MIME type, you should use inherits()
    rather than a simple string comparison based on the name(). This is because
    MIME types can inherit from each other: for instance a C source file is
    a specific type of plain text file, so text/x-csrc inherits text/plain.

    \sa QMimeDatabase
 */

/*!
    \fn QMimeType::QMimeType();
    \brief Initializes the attributes with default values that indicate an invalid MIME type.
 */
QMimeType::QMimeType() :
        d(new QMimeTypePrivate())
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

/*!
    \fn QMimeType::QMimeType(const QMimeType &other);
    \brief Initializes the attributes with the data of another MIME type.
    \a other The other MIME type the data of which is copied
 */
QMimeType::QMimeType(const QMimeType &other) :
        d(other.d)
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

#if !defined(Q_COMPILER_RVALUE_REFS) || TEST_COMPILER_RVALUE_REFS == 0
/*!
    \fn QMimeType &QMimeType::operator=(const QMimeType &other);
    \brief Assigns the data of another MIME type.
    \a other The other MIME type the data of which is assigned
 */
QMimeType &QMimeType::operator=(const QMimeType &other)
{
    if (d != other.d)
        d = other.d;
    return *this;
}
#endif

#ifdef Q_COMPILER_RVALUE_REFS
/*!
    \fn QMimeType::QMimeType(QMimeType &&other);
    \brief Moves the data of another rvalue MIME type into the attributes.
    \a other The other rvalue MIME type the data of which is moved
 */
QMimeType::QMimeType(QMimeType &&other) :
        d(std::move(other.d))
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}
#endif

/*!
    \fn QMimeType::QMimeType(const QMimeTypePrivate &dd);
    \brief Assigns the data of a private MIME type object.
    \a dd The private MIME typeobject the data of which is assigned
 */
QMimeType::QMimeType(const QMimeTypePrivate &dd) :
        d(new QMimeTypePrivate(dd))
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

/*!
    \fn void QMimeType::swap(QMimeType &other);
    \brief Swaps the properties of a MIME type with the properties of another MIME type.
    \a other The other value MIME type the data of which is to be swapped with.
 */

/*!
    \fn QMimeType::~QMimeType();
    \brief Releases the d pointer.
 */
QMimeType::~QMimeType()
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

/*!
    \fn bool QMimeType::operator==(const QMimeType &other) const;
    \brief Tests for equality with another MIME type.
    \a other The other MIME type that is to be compared with
    Returns if the other MIME type is equal.
 */
bool QMimeType::operator==(const QMimeType &other) const
{
    return d == other.d || *d == *other.d;
}

/*!
    \fn bool QMimeType::operator!=(const QMimeType &other) const;
    \brief Tests for non-equality with another MIME type.
    \a other The other MIME type that is to be compared with
    Returns if the other MIME type is not equal.
 */

/*!
    \fn bool QMimeType::isValid() const;
    \brief Returns true if the MIME type is valid, otherwise returns false.
    A valid MIME type has a non-empty name().
    The invalid MIME type is the default-constructed QMimeType.
 */
bool QMimeType::isValid() const
{
    return !d->name.isEmpty();
}

/*!
    \fn bool QMimeType::isDefault() const;
    Returns true if this MIME type is the default MIME type which
    applies to all files: application/octet-stream.
 */
bool QMimeType::isDefault() const
{
    return d->name == QMimeDatabasePrivate::instance()->defaultMimeType();
}

/*!
    \fn QString QMimeType::name() const;
    \brief Returns the name of the MIME type.
 */
QString QMimeType::name() const
{
    return d->name;
}

#if 0
/*!
    \fn QStringList QMimeType::aliases() const;
    \brief Returns the aliases of the MIME type.
 */
// What is the use case for this? [apart from mimetypeviewer.cpp ...]
QStringList QMimeType::aliases() const
{
    return d->aliases;
}
#endif

/*!
    \fn QString QMimeType::comment(const QString& localeName) const;
    \brief Returns the description of the MIME type to be displayed on user interfaces.

    The system language (QLocale::system().name()) is used to select the appropriate translation.
    Another language can be specified by setting the \a localeName argument.
 */
QString QMimeType::comment(const QString& localeName) const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);

    QStringList languageList;
    if (!localeName.isEmpty())
        languageList << localeName;
    languageList << QLocale::system().name();
    languageList << QLocale::system().uiLanguages();
    Q_FOREACH(const QString& lang, languageList) {
        const QString comm = d->localeComments.value(lang);
        if (!comm.isEmpty())
            return comm;
        const int pos = lang.indexOf(QLatin1Char('_'));
        if (pos != -1) {
            // "pt_BR" not found? try just "pt"
            const QString shortLang = lang.left(pos);
            const QString commShort = d->localeComments.value(shortLang);
            if (!commShort.isEmpty())
                return commShort;
        }
    }

    // Use the mimetype name as fallback
    return d->name;
}

/*!
    \fn QString QMimeType::genericIconName() const;
    \brief Returns the file name of an icon image that represents the MIME type.
 */
QString QMimeType::genericIconName() const
{
    QMimeDatabasePrivate::instance()->provider()->loadGenericIcon(*d);
    return d->genericIconName;
}

/*!
    \fn QString QMimeType::iconName() const;
    \brief Returns the file name of an icon image that represents the MIME type.
 */
QString QMimeType::iconName() const
{
    QMimeDatabasePrivate::instance()->provider()->loadIcon(*d);
    if (d->iconName.isEmpty()) {
        // Make default icon name from the mimetype name
        d->iconName = name();
        const int slashindex = d->iconName.indexOf(QLatin1Char('/'));
        if (slashindex != -1)
            d->iconName[slashindex] = QLatin1Char('-');
    }
    return d->iconName;
}

/*!
    \fn QStringList QMimeType::globPatterns() const;
    \brief Returns the list of glob matching patterns.
 */
QStringList QMimeType::globPatterns() const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);
    return d->globPatterns;
}

QStringList QMimeType::parentMimeTypes() const
{
    return QMimeDatabasePrivate::instance()->provider()->parents(d->name);
}

static void collectParentMimeTypes(const QString& mime, QStringList& allParents)
{
    QStringList parents = QMimeDatabasePrivate::instance()->provider()->parents(mime);
    foreach(const QString& parent, parents) {
        // I would use QSet, but since order matters I better not
        if (!allParents.contains(parent))
            allParents.append(parent);
    }
    // We want a breadth-first search, so that the least-specific parent (octet-stream) is last
    // This means iterating twice, unfortunately.
    foreach(const QString& parent, parents) {
        collectParentMimeTypes(parent, allParents);
    }
}

QStringList QMimeType::allParentMimeTypes() const
{
    QStringList allParents;
    const QString canonical = d->name;
    if (!canonical.isEmpty())
        allParents.append(canonical);
    collectParentMimeTypes(d->name, allParents);

    return allParents;
}

/*!
    \fn QStringList QMimeType::suffixes() const;
    \brief Returns the known suffixes for the MIME type.
 */
QStringList QMimeType::suffixes() const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);

    QStringList result;
    foreach (const QString& pattern, d->globPatterns) {
        // Not a simple suffix if if looks like: README or *. or *.* or *.JP*G or *.JP?
        if (pattern.startsWith(QLatin1String("*.")) &&
            pattern.length() > 2 &&
            pattern.indexOf(QLatin1Char('*'), 2) < 0 && pattern.indexOf(QLatin1Char('?'), 2) < 0) {
            const QString suffix = pattern.mid(2);
            result.append(suffix);
        }
    }

    return result;
}

/*!
    \fn QString QMimeType::preferredSuffix() const;
    \brief Returns the preferred suffix for the MIME type.
 */
QString QMimeType::preferredSuffix() const
{
    const QStringList suffixList = suffixes();
    return suffixList.isEmpty() ? QString() : suffixList.at(0);
}

/*!
    \fn QString QMimeType::filterString() const;
    Returns a filter string usable for a file dialog.
*/
QString QMimeType::filterString() const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);
    QString filter;

    if (!d->globPatterns.empty()) {
        filter += comment() + QLatin1String(" (");
        for (int i = 0; i < d->globPatterns.size(); ++i) {
            if (i != 0)
                filter += QLatin1Char(' ');
            filter += d->globPatterns.at(i);
        }
        filter +=  QLatin1Char(')');
    }

    return filter;
}

/*!
    \fn bool QMimeType::inherits(const QString &mimeTypeName) const;
    Returns true if this mimetype is \a mimeTypeName, or inherits \a mimeTypeName,
    or \a mimeTypeName is an alias for this mimetype.
 */
bool QMimeType::inherits(const QString &mimeTypeName) const
{
    if (d->name == mimeTypeName)
        return true;
    return QMimeDatabasePrivate::instance()->inherits(d->name, mimeTypeName);
}

#undef DBG

QT_END_NAMESPACE
<commit_msg>Documentation<commit_after>/****************************************************************************
**
** This file is part of QMime
**
** Based on Qt Creator source code
**
** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
**
** 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.
**
****************************************************************************/

#include "qmimetype.h"   // Basis

#include "qmimetype_p.h"
#include "qmimedatabase_p.h"
#include "qmimeprovider_p.h"

#include "qmimeglobpattern_p.h"

#include <QtCore/QDebug>
#include <QtCore/QLocale>

QT_BEGIN_NAMESPACE

bool isQMimeTypeDebuggingActivated (false);

#ifndef QT_NO_DEBUG_OUTPUT
#define DBG() if (isQMimeTypeDebuggingActivated) qDebug() << Q_FUNC_INFO
#else
#define DBG() if (0) qDebug() << Q_FUNC_INFO
#endif

QMimeTypePrivate::QMimeTypePrivate()
{}

QMimeTypePrivate::QMimeTypePrivate(const QMimeType &other)
        : name(other.d->name)
        //, comment(other.d->comment)
        , localeComments(other.d->localeComments)
        , genericIconName(other.d->genericIconName)
        , iconName(other.d->iconName)
        , globPatterns(other.d->globPatterns)
{}

void QMimeTypePrivate::clear()
{
    name.clear();
    //comment.clear();
    localeComments.clear();
    genericIconName.clear();
    iconName.clear();
    globPatterns.clear();
}

/*!
    \fn bool QMimeTypePrivate::operator==(const QMimeTypePrivate &other) const;
    \brief Returns if the \a other object has the same value.
 */
bool QMimeTypePrivate::operator==(const QMimeTypePrivate &other) const
{
    return name == other.name &&
            //comment == other.comment &&
            localeComments == other.localeComments &&
            genericIconName == other.genericIconName &&
            iconName == other.iconName &&
            globPatterns == other.globPatterns;
}

void QMimeTypePrivate::addGlobPattern(const QString &pattern)
{
    globPatterns.append(pattern);
}

/*!
    \class QMimeType

    \brief The QMimeType class describes types of file or data, represented by a MIME type string.

    For instance a file named "readme.txt" has the MIME type "text/plain".
    The MIME type can be determined from the file name, or from the file
    contents, or from both. MIME type determination can also be done on
    buffers of data not coming from files.

    Determining the MIME type of a file can be useful to make sure your
    application supports it. It is also useful in file-manager-like applications
    or widgets, in order to display an appropriate icon() for the file, or even
    the descriptive comment() in detailed views.

    To check if a file has the expected MIME type, you should use inherits()
    rather than a simple string comparison based on the name(). This is because
    MIME types can inherit from each other: for instance a C source file is
    a specific type of plain text file, so text/x-csrc inherits text/plain.

    \sa QMimeDatabase
 */

/*!
    \fn QMimeType::QMimeType();
    \brief Initializes the attributes with default values that indicate an invalid MIME type.
 */
QMimeType::QMimeType() :
        d(new QMimeTypePrivate())
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

/*!
    \fn QMimeType::QMimeType(const QMimeType &other);
    \brief Initializes the attributes with the data of another MIME type.
    \a other The other MIME type the data of which is copied
 */
QMimeType::QMimeType(const QMimeType &other) :
        d(other.d)
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

#if !defined(Q_COMPILER_RVALUE_REFS) || TEST_COMPILER_RVALUE_REFS == 0
/*!
    \fn QMimeType &QMimeType::operator=(const QMimeType &other);
    \brief Assigns the data of another MIME type.
    \a other The other MIME type the data of which is assigned
 */
QMimeType &QMimeType::operator=(const QMimeType &other)
{
    if (d != other.d)
        d = other.d;
    return *this;
}
#endif

#ifdef Q_COMPILER_RVALUE_REFS
/*!
    \fn QMimeType::QMimeType(QMimeType &&other);
    \brief Moves the data of another rvalue MIME type into the attributes.
    \a other The other rvalue MIME type the data of which is moved
 */
QMimeType::QMimeType(QMimeType &&other) :
        d(std::move(other.d))
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}
#endif

/*!
    \fn QMimeType::QMimeType(const QMimeTypePrivate &dd);
    \brief Assigns the data of a private MIME type object.
    \a dd The private MIME typeobject the data of which is assigned
 */
QMimeType::QMimeType(const QMimeTypePrivate &dd) :
        d(new QMimeTypePrivate(dd))
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

/*!
    \fn void QMimeType::swap(QMimeType &other);
    \brief Swaps the properties of a MIME type with the properties of another MIME type.
    \a other The other value MIME type the data of which is to be swapped with.

    The swap() method helps with the implementatoin of assignment
    operators in an exception-safe way. For more information consult
    http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap.
 */

/*!
    \fn QMimeType::~QMimeType();
    \brief Releases the d pointer.
 */
QMimeType::~QMimeType()
{
    DBG() << "name():" << name();
    //DBG() << "aliases():" << aliases();
    //DBG() << "comment():" << comment();
    DBG() << "genericIconName():" << genericIconName();
    DBG() << "iconName():" << iconName();
    DBG() << "globPatterns():" << globPatterns();
    DBG() << "suffixes():" << suffixes();
    DBG() << "preferredSuffix():" << preferredSuffix();
}

/*!
    \fn bool QMimeType::operator==(const QMimeType &other) const;
    \brief Tests for equality with another MIME type.
    \a other The other MIME type that is to be compared with
    Returns if the other MIME type is equal.
 */
bool QMimeType::operator==(const QMimeType &other) const
{
    return d == other.d || *d == *other.d;
}

/*!
    \fn bool QMimeType::operator!=(const QMimeType &other) const;
    \brief Tests for non-equality with another MIME type.
    \a other The other MIME type that is to be compared with
    Returns if the other MIME type is not equal.
 */

/*!
    \fn bool QMimeType::isValid() const;
    \brief Returns true if the MIME type is valid, otherwise returns false.
    A valid MIME type has a non-empty name().
    The invalid MIME type is the default-constructed QMimeType.
 */
bool QMimeType::isValid() const
{
    return !d->name.isEmpty();
}

/*!
    \fn bool QMimeType::isDefault() const;
    Returns true if this MIME type is the default MIME type which
    applies to all files: application/octet-stream.
 */
bool QMimeType::isDefault() const
{
    return d->name == QMimeDatabasePrivate::instance()->defaultMimeType();
}

/*!
    \fn QString QMimeType::name() const;
    \brief Returns the name of the MIME type.
 */
QString QMimeType::name() const
{
    return d->name;
}

#if 0
/*!
    \fn QStringList QMimeType::aliases() const;
    \brief Returns the aliases of the MIME type.
 */
// What is the use case for this? [apart from mimetypeviewer.cpp ...]
QStringList QMimeType::aliases() const
{
    return d->aliases;
}
#endif

/*!
    \fn QString QMimeType::comment(const QString& localeName) const;
    \brief Returns the description of the MIME type to be displayed on user interfaces.

    The system language (QLocale::system().name()) is used to select the appropriate translation.
    Another language can be specified by setting the \a localeName argument.
 */
QString QMimeType::comment(const QString& localeName) const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);

    QStringList languageList;
    if (!localeName.isEmpty())
        languageList << localeName;
    languageList << QLocale::system().name();
    languageList << QLocale::system().uiLanguages();
    Q_FOREACH(const QString& lang, languageList) {
        const QString comm = d->localeComments.value(lang);
        if (!comm.isEmpty())
            return comm;
        const int pos = lang.indexOf(QLatin1Char('_'));
        if (pos != -1) {
            // "pt_BR" not found? try just "pt"
            const QString shortLang = lang.left(pos);
            const QString commShort = d->localeComments.value(shortLang);
            if (!commShort.isEmpty())
                return commShort;
        }
    }

    // Use the mimetype name as fallback
    return d->name;
}

/*!
    \fn QString QMimeType::genericIconName() const;
    \brief Returns the file name of an icon image that represents the MIME type.
 */
QString QMimeType::genericIconName() const
{
    QMimeDatabasePrivate::instance()->provider()->loadGenericIcon(*d);
    return d->genericIconName;
}

/*!
    \fn QString QMimeType::iconName() const;
    \brief Returns the file name of an icon image that represents the MIME type.
 */
QString QMimeType::iconName() const
{
    QMimeDatabasePrivate::instance()->provider()->loadIcon(*d);
    if (d->iconName.isEmpty()) {
        // Make default icon name from the mimetype name
        d->iconName = name();
        const int slashindex = d->iconName.indexOf(QLatin1Char('/'));
        if (slashindex != -1)
            d->iconName[slashindex] = QLatin1Char('-');
    }
    return d->iconName;
}

/*!
    \fn QStringList QMimeType::globPatterns() const;
    \brief Returns the list of glob matching patterns.
 */
QStringList QMimeType::globPatterns() const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);
    return d->globPatterns;
}

QStringList QMimeType::parentMimeTypes() const
{
    return QMimeDatabasePrivate::instance()->provider()->parents(d->name);
}

static void collectParentMimeTypes(const QString& mime, QStringList& allParents)
{
    QStringList parents = QMimeDatabasePrivate::instance()->provider()->parents(mime);
    foreach(const QString& parent, parents) {
        // I would use QSet, but since order matters I better not
        if (!allParents.contains(parent))
            allParents.append(parent);
    }
    // We want a breadth-first search, so that the least-specific parent (octet-stream) is last
    // This means iterating twice, unfortunately.
    foreach(const QString& parent, parents) {
        collectParentMimeTypes(parent, allParents);
    }
}

QStringList QMimeType::allParentMimeTypes() const
{
    QStringList allParents;
    const QString canonical = d->name;
    if (!canonical.isEmpty())
        allParents.append(canonical);
    collectParentMimeTypes(d->name, allParents);

    return allParents;
}

/*!
    \fn QStringList QMimeType::suffixes() const;
    \brief Returns the known suffixes for the MIME type.
 */
QStringList QMimeType::suffixes() const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);

    QStringList result;
    foreach (const QString& pattern, d->globPatterns) {
        // Not a simple suffix if if looks like: README or *. or *.* or *.JP*G or *.JP?
        if (pattern.startsWith(QLatin1String("*.")) &&
            pattern.length() > 2 &&
            pattern.indexOf(QLatin1Char('*'), 2) < 0 && pattern.indexOf(QLatin1Char('?'), 2) < 0) {
            const QString suffix = pattern.mid(2);
            result.append(suffix);
        }
    }

    return result;
}

/*!
    \fn QString QMimeType::preferredSuffix() const;
    \brief Returns the preferred suffix for the MIME type.
 */
QString QMimeType::preferredSuffix() const
{
    const QStringList suffixList = suffixes();
    return suffixList.isEmpty() ? QString() : suffixList.at(0);
}

/*!
    \fn QString QMimeType::filterString() const;
    Returns a filter string usable for a file dialog.
*/
QString QMimeType::filterString() const
{
    QMimeDatabasePrivate::instance()->provider()->loadMimeTypePrivate(*d);
    QString filter;

    if (!d->globPatterns.empty()) {
        filter += comment() + QLatin1String(" (");
        for (int i = 0; i < d->globPatterns.size(); ++i) {
            if (i != 0)
                filter += QLatin1Char(' ');
            filter += d->globPatterns.at(i);
        }
        filter +=  QLatin1Char(')');
    }

    return filter;
}

/*!
    \fn bool QMimeType::inherits(const QString &mimeTypeName) const;
    Returns true if this mimetype is \a mimeTypeName, or inherits \a mimeTypeName,
    or \a mimeTypeName is an alias for this mimetype.
 */
bool QMimeType::inherits(const QString &mimeTypeName) const
{
    if (d->name == mimeTypeName)
        return true;
    return QMimeDatabasePrivate::instance()->inherits(d->name, mimeTypeName);
}

#undef DBG

QT_END_NAMESPACE
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#define MUL_FUNCTOR(name, ...)                        \
    struct name {                                     \
        template <typename A, typename B, typename C> \
        static void apply(A&& a, B&& b, C& c) {       \
            __VA_ARGS__;                              \
        }                                             \
    };

MUL_FUNCTOR(default_gemm, c = etl::mul(a, b))
MUL_FUNCTOR(lazy_gemm, c = etl::lazy_mul(a, b))
MUL_FUNCTOR(strassen_gemm, c = etl::strassen_mul(a, b))
MUL_FUNCTOR(std_gemm, etl::impl::standard::mm_mul(a, b, c))
MUL_FUNCTOR(eblas_gemm, etl::impl::eblas::gemm(a, b, c))

MUL_FUNCTOR(default_gemv, c = etl::mul(a, b))
MUL_FUNCTOR(std_gemv, etl::impl::standard::mv_mul(a, b, c))

MUL_FUNCTOR(default_gevm, c = etl::mul(a, b))
MUL_FUNCTOR(std_gevm, etl::impl::standard::vm_mul(a, b, c))

#define GEMM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemm, default_gemm)
#define GEMM_TEST_CASE_SECTION_LAZY MUL_TEST_CASE_SECTIONS(lazy_gemm, lazy_gemm)
#define GEMM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemm, std_gemm)
#define GEMM_TEST_CASE_SECTION_STRASSEN MUL_TEST_CASE_SECTIONS(strassen_gemm, strassen_gemm)
#define GEMM_TEST_CASE_SECTION_EBLAS MUL_TEST_CASE_SECTIONS(eblas_gemm, eblas_gemm)

#define GEMV_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemv, default_gemv)
#define GEMV_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemv, std_gemv)

#define GEVM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gevm, default_gevm)
#define GEVM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gevm, std_gevm)

#ifdef ETL_BLAS_MODE
MUL_FUNCTOR(blas_gemm, etl::impl::blas::gemm(a, b, c))
MUL_FUNCTOR(blas_gemv, etl::impl::blas::gemv(a, b, c))
MUL_FUNCTOR(blas_gevm, etl::impl::blas::gevm(a, b, c))
#define GEMM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemm, blas_gemm)
#define GEMV_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemv, blas_gemv)
#define GEVM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gevm, blas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_BLAS
#define GEMV_TEST_CASE_SECTION_BLAS
#define GEVM_TEST_CASE_SECTION_BLAS
#endif

#ifdef ETL_CUBLAS_MODE
MUL_FUNCTOR(cublas_gemm, etl::impl::cublas::gemm(a, b, c); c.gpu_copy_from_if_necessary())
MUL_FUNCTOR(cublas_gemv, etl::impl::cublas::gemv(a, b, c); c.gpu_copy_from_if_necessary())
MUL_FUNCTOR(cublas_gevm, etl::impl::cublas::gevm(a, b, c); c.gpu_copy_from_if_necessary())
#define GEMM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemm, cublas_gemm)
#define GEMV_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemv, cublas_gemv)
#define GEVM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gevm, cublas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_CUBLAS
#define GEMV_TEST_CASE_SECTION_CUBLAS
#define GEVM_TEST_CASE_SECTION_CUBLAS
#endif

#define MUL_TEST_CASE_DECL(name, description)                                                 \
    template <typename T, typename Impl>                                                      \
    static void INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)(); \
    TEST_CASE(name, description)

#define MUL_TEST_CASE_SECTION(Tn, Impln)                                                         \
    SECTION(#Tn "_" #Impln) {                                                                    \
        INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)<Tn, Impln>(); \
    }

#define MUL_TEST_CASE_DEFN               \
    template <typename T, typename Impl> \
    static void INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)()

#define MUL_TEST_CASE_SECTIONS(S1, S2) \
    MUL_TEST_CASE_SECTION(float, S1)   \
    MUL_TEST_CASE_SECTION(double, S2)

#define GEMM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_STRASSEN     \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
        GEMM_TEST_CASE_SECTION_EBLAS        \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEMV_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMV_TEST_CASE_SECTION_DEFAULT      \
        GEMV_TEST_CASE_SECTION_STD          \
        GEMV_TEST_CASE_SECTION_BLAS         \
        GEMV_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEVM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEVM_TEST_CASE_SECTION_DEFAULT      \
        GEVM_TEST_CASE_SECTION_STD          \
        GEVM_TEST_CASE_SECTION_BLAS         \
        GEVM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN
<commit_msg>Proper selection in gemm tests<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#define MUL_FUNCTOR(name, ...)                        \
    struct name {                                     \
        template <typename A, typename B, typename C> \
        static void apply(A&& a, B&& b, C& c) {       \
            __VA_ARGS__;                              \
        }                                             \
    };

MUL_FUNCTOR(default_gemm, c = etl::mul(a, b))
MUL_FUNCTOR(lazy_gemm, c = etl::lazy_mul(a, b))
MUL_FUNCTOR(strassen_gemm, c = etl::strassen_mul(a, b))
MUL_FUNCTOR(std_gemm, c = selected_helper(etl::gemm_impl::STD, a * b))
MUL_FUNCTOR(eblas_gemm, c = selected_helper(etl::gemm_impl::FAST, a * b))

MUL_FUNCTOR(default_gemv, c = etl::mul(a, b))
MUL_FUNCTOR(std_gemv, c = selected_helper(etl::gemm_impl::STD, a * b))

MUL_FUNCTOR(default_gevm, c = etl::mul(a, b))
MUL_FUNCTOR(std_gevm, c = selected_helper(etl::gemm_impl::STD, a * b))

#define GEMM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemm, default_gemm)
#define GEMM_TEST_CASE_SECTION_LAZY MUL_TEST_CASE_SECTIONS(lazy_gemm, lazy_gemm)
#define GEMM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemm, std_gemm)
#define GEMM_TEST_CASE_SECTION_STRASSEN MUL_TEST_CASE_SECTIONS(strassen_gemm, strassen_gemm)
#define GEMM_TEST_CASE_SECTION_EBLAS MUL_TEST_CASE_SECTIONS(eblas_gemm, eblas_gemm)

#define GEMV_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gemv, default_gemv)
#define GEMV_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gemv, std_gemv)

#define GEVM_TEST_CASE_SECTION_DEFAULT MUL_TEST_CASE_SECTIONS(default_gevm, default_gevm)
#define GEVM_TEST_CASE_SECTION_STD MUL_TEST_CASE_SECTIONS(std_gevm, std_gevm)

#ifdef ETL_BLAS_MODE
MUL_FUNCTOR(blas_gemm, c = selected_helper(etl::gemm_impl::BLAS, a * b))
MUL_FUNCTOR(blas_gemv, c = selected_helper(etl::gemm_impl::BLAS, a * b))
MUL_FUNCTOR(blas_gevm, c = selected_helper(etl::gemm_impl::BLAS, a * b))
#define GEMM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemm, blas_gemm)
#define GEMV_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gemv, blas_gemv)
#define GEVM_TEST_CASE_SECTION_BLAS MUL_TEST_CASE_SECTIONS(blas_gevm, blas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_BLAS
#define GEMV_TEST_CASE_SECTION_BLAS
#define GEVM_TEST_CASE_SECTION_BLAS
#endif

#ifdef ETL_CUBLAS_MODE
MUL_FUNCTOR(cublas_gemm, c = selected_helper(etl::gemm_impl::CUBLAS, a * b))
MUL_FUNCTOR(cublas_gemv, c = selected_helper(etl::gemm_impl::CUBLAS, a * b))
MUL_FUNCTOR(cublas_gevm, c = selected_helper(etl::gemm_impl::CUBLAS, a * b))
#define GEMM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemm, cublas_gemm)
#define GEMV_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gemv, cublas_gemv)
#define GEVM_TEST_CASE_SECTION_CUBLAS MUL_TEST_CASE_SECTIONS(cublas_gevm, cublas_gevm)
#else
#define GEMM_TEST_CASE_SECTION_CUBLAS
#define GEMV_TEST_CASE_SECTION_CUBLAS
#define GEVM_TEST_CASE_SECTION_CUBLAS
#endif

#define MUL_TEST_CASE_DECL(name, description)                                                 \
    template <typename T, typename Impl>                                                      \
    static void INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)(); \
    TEST_CASE(name, description)

#define MUL_TEST_CASE_SECTION(Tn, Impln)                                                         \
    SECTION(#Tn "_" #Impln) {                                                                    \
        INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)<Tn, Impln>(); \
    }

#define MUL_TEST_CASE_DEFN               \
    template <typename T, typename Impl> \
    static void INTERNAL_CATCH_UNIQUE_NAME(____C_A_T_C_H____T_E_M_P_L_A_TE____T_E_S_T____)()

#define MUL_TEST_CASE_SECTIONS(S1, S2) \
    MUL_TEST_CASE_SECTION(float, S1)   \
    MUL_TEST_CASE_SECTION(double, S2)

#define GEMM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMM_TEST_CASE_SECTION_DEFAULT      \
        GEMM_TEST_CASE_SECTION_STD          \
        GEMM_TEST_CASE_SECTION_LAZY         \
        GEMM_TEST_CASE_SECTION_STRASSEN     \
        GEMM_TEST_CASE_SECTION_BLAS         \
        GEMM_TEST_CASE_SECTION_CUBLAS       \
        GEMM_TEST_CASE_SECTION_EBLAS        \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEMV_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEMV_TEST_CASE_SECTION_DEFAULT      \
        GEMV_TEST_CASE_SECTION_STD          \
        GEMV_TEST_CASE_SECTION_BLAS         \
        GEMV_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN

#define GEVM_TEST_CASE(name, description)   \
    MUL_TEST_CASE_DECL(name, description) { \
        GEVM_TEST_CASE_SECTION_DEFAULT      \
        GEVM_TEST_CASE_SECTION_STD          \
        GEVM_TEST_CASE_SECTION_BLAS         \
        GEVM_TEST_CASE_SECTION_CUBLAS       \
    }                                       \
    MUL_TEST_CASE_DEFN
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <cassert>

#include "critical_section_wrapper.h"
#include "rtp_dump.h"
#include "vie_sender.h"
#include "trace.h"

namespace webrtc {

ViESender::ViESender(int engine_id, int channel_id)
    : engine_id_(engine_id),
      channel_id_(channel_id),
      critsect_(*CriticalSectionWrapper::CreateCriticalSection()),
      external_encryption_(NULL),
      encryption_buffer_(NULL),
      transport_(NULL),
      rtp_dump_(NULL) {
}

ViESender::~ViESender() {
  delete &critsect_;

  if (encryption_buffer_) {
    delete[] encryption_buffer_;
    encryption_buffer_ = NULL;
  }

  if (rtp_dump_) {
    rtp_dump_->Stop();
    RtpDump::DestroyRtpDump(rtp_dump_);
    rtp_dump_ = NULL;
  }
}

int ViESender::RegisterExternalEncryption(Encryption* encryption) {
  CriticalSectionScoped cs(critsect_);
  if (external_encryption_) {
    return -1;
  }
  encryption_buffer_ = new WebRtc_UWord8[kViEMaxMtu];
  if (encryption_buffer_ == NULL) {
    return -1;
  }
  external_encryption_ = encryption;
  return 0;
}

int ViESender::DeregisterExternalEncryption() {
  CriticalSectionScoped cs(critsect_);
  if (external_encryption_ == NULL) {
    return -1;
  }
  if (encryption_buffer_) {
    delete encryption_buffer_;
    encryption_buffer_ = NULL;
  }
  external_encryption_ = NULL;
  return 0;
}

int ViESender::RegisterSendTransport(Transport* transport) {
  CriticalSectionScoped cs(critsect_);
  if (transport_) {
    return -1;
  }
  transport_ = transport;
  return 0;
}

int ViESender::DeregisterSendTransport() {
  CriticalSectionScoped cs(critsect_);
  if (transport_ == NULL) {
    return -1;
  }
  transport_ = NULL;
  return 0;
}

int ViESender::StartRTPDump(const char file_nameUTF8[1024]) {
  CriticalSectionScoped cs(critsect_);
  if (rtp_dump_) {
    // Packet dump is already started, restart it.
    rtp_dump_->Stop();
  } else {
    rtp_dump_ = RtpDump::CreateRtpDump();
    if (rtp_dump_ == NULL) {
      WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                   ViEId(engine_id_, channel_id_),
                   "StartSRTPDump: Failed to create RTP dump");
      return -1;
    }
  }
  if (rtp_dump_->Start(file_nameUTF8) != 0) {
    RtpDump::DestroyRtpDump(rtp_dump_);
    rtp_dump_ = NULL;
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                 ViEId(engine_id_, channel_id_),
                 "StartRTPDump: Failed to start RTP dump");
    return -1;
  }
  return 0;
}

int ViESender::StopRTPDump() {
  CriticalSectionScoped cs(critsect_);
  if (rtp_dump_) {
    if (rtp_dump_->IsActive()) {
      rtp_dump_->Stop();
    } else {
      WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                   ViEId(engine_id_, channel_id_),
                   "StopRTPDump: Dump not active");
    }
    RtpDump::DestroyRtpDump(rtp_dump_);
    rtp_dump_ = NULL;
  } else {
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                 ViEId(engine_id_, channel_id_),
                 "StopRTPDump: RTP dump not started");
    return -1;
  }
  return 0;
}

int ViESender::SendPacket(int vie_id, const void* data, int len) {
  CriticalSectionScoped cs(critsect_);
  if (!transport_) {
    // No transport
    return -1;
  }

  assert(ChannelId(vie_id) == channel_id_);

  // TODO(mflodman) Change decrypt to get rid of this cast.
  void* tmp_ptr = const_cast<void*>(data);
  unsigned char* send_packet = static_cast<unsigned char*>(tmp_ptr);
  int send_packet_length = len;

  if (rtp_dump_) {
    rtp_dump_->DumpPacket(send_packet, send_packet_length);
  }

  if (external_encryption_) {
    external_encryption_->encrypt(channel_id_, send_packet,
                                  encryption_buffer_, send_packet_length,
                                  static_cast<int*>(&send_packet_length));
    send_packet = encryption_buffer_;
  }

  return transport_->SendPacket(channel_id_, send_packet, send_packet_length);
}

int ViESender::SendRTCPPacket(int vie_id, const void* data, int len) {
  CriticalSectionScoped cs(critsect_);

  if (!transport_) {
    return -1;
  }

  assert(ChannelId(vie_id) == channel_id_);

  // Prepare for possible encryption and sending.
  // TODO(mflodman) Change decrypt to get rid of this cast.
  void* tmp_ptr = const_cast<void*>(data);
  unsigned char* send_packet = static_cast<unsigned char*>(tmp_ptr);
  int send_packet_length = len;

  if (rtp_dump_) {
    rtp_dump_->DumpPacket(send_packet, send_packet_length);
  }

  if (external_encryption_) {
    external_encryption_->encrypt_rtcp(
        channel_id_, send_packet, encryption_buffer_, send_packet_length,
        static_cast<int*>(&send_packet_length));
    send_packet = encryption_buffer_;
  }

  return transport_->SendRTCPPacket(channel_id_, send_packet,
                                    send_packet_length);
}

}  // namespace webrtc
<commit_msg>Add log when transport fails to send packet.<commit_after>/*
 *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <cassert>

#include "critical_section_wrapper.h"
#include "rtp_dump.h"
#include "vie_sender.h"
#include "trace.h"

namespace webrtc {

ViESender::ViESender(int engine_id, int channel_id)
    : engine_id_(engine_id),
      channel_id_(channel_id),
      critsect_(*CriticalSectionWrapper::CreateCriticalSection()),
      external_encryption_(NULL),
      encryption_buffer_(NULL),
      transport_(NULL),
      rtp_dump_(NULL) {
}

ViESender::~ViESender() {
  delete &critsect_;

  if (encryption_buffer_) {
    delete[] encryption_buffer_;
    encryption_buffer_ = NULL;
  }

  if (rtp_dump_) {
    rtp_dump_->Stop();
    RtpDump::DestroyRtpDump(rtp_dump_);
    rtp_dump_ = NULL;
  }
}

int ViESender::RegisterExternalEncryption(Encryption* encryption) {
  CriticalSectionScoped cs(critsect_);
  if (external_encryption_) {
    return -1;
  }
  encryption_buffer_ = new WebRtc_UWord8[kViEMaxMtu];
  if (encryption_buffer_ == NULL) {
    return -1;
  }
  external_encryption_ = encryption;
  return 0;
}

int ViESender::DeregisterExternalEncryption() {
  CriticalSectionScoped cs(critsect_);
  if (external_encryption_ == NULL) {
    return -1;
  }
  if (encryption_buffer_) {
    delete encryption_buffer_;
    encryption_buffer_ = NULL;
  }
  external_encryption_ = NULL;
  return 0;
}

int ViESender::RegisterSendTransport(Transport* transport) {
  CriticalSectionScoped cs(critsect_);
  if (transport_) {
    return -1;
  }
  transport_ = transport;
  return 0;
}

int ViESender::DeregisterSendTransport() {
  CriticalSectionScoped cs(critsect_);
  if (transport_ == NULL) {
    return -1;
  }
  transport_ = NULL;
  return 0;
}

int ViESender::StartRTPDump(const char file_nameUTF8[1024]) {
  CriticalSectionScoped cs(critsect_);
  if (rtp_dump_) {
    // Packet dump is already started, restart it.
    rtp_dump_->Stop();
  } else {
    rtp_dump_ = RtpDump::CreateRtpDump();
    if (rtp_dump_ == NULL) {
      WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                   ViEId(engine_id_, channel_id_),
                   "StartSRTPDump: Failed to create RTP dump");
      return -1;
    }
  }
  if (rtp_dump_->Start(file_nameUTF8) != 0) {
    RtpDump::DestroyRtpDump(rtp_dump_);
    rtp_dump_ = NULL;
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                 ViEId(engine_id_, channel_id_),
                 "StartRTPDump: Failed to start RTP dump");
    return -1;
  }
  return 0;
}

int ViESender::StopRTPDump() {
  CriticalSectionScoped cs(critsect_);
  if (rtp_dump_) {
    if (rtp_dump_->IsActive()) {
      rtp_dump_->Stop();
    } else {
      WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                   ViEId(engine_id_, channel_id_),
                   "StopRTPDump: Dump not active");
    }
    RtpDump::DestroyRtpDump(rtp_dump_);
    rtp_dump_ = NULL;
  } else {
    WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideo,
                 ViEId(engine_id_, channel_id_),
                 "StopRTPDump: RTP dump not started");
    return -1;
  }
  return 0;
}

int ViESender::SendPacket(int vie_id, const void* data, int len) {
  CriticalSectionScoped cs(critsect_);
  if (!transport_) {
    // No transport
    return -1;
  }

  assert(ChannelId(vie_id) == channel_id_);

  // TODO(mflodman) Change decrypt to get rid of this cast.
  void* tmp_ptr = const_cast<void*>(data);
  unsigned char* send_packet = static_cast<unsigned char*>(tmp_ptr);
  int send_packet_length = len;

  if (rtp_dump_) {
    rtp_dump_->DumpPacket(send_packet, send_packet_length);
  }

  if (external_encryption_) {
    external_encryption_->encrypt(channel_id_, send_packet,
                                  encryption_buffer_, send_packet_length,
                                  static_cast<int*>(&send_packet_length));
    send_packet = encryption_buffer_;
  }

  const int bytes_sent = transport_->SendPacket(channel_id_, send_packet,
                                                send_packet_length);
  if (bytes_sent != send_packet_length) {
    WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceVideo,
                 ViEId(engine_id_, channel_id_),
                 "ViESender::SendPacket - Transport failed to send RTP packet");
  }
  return bytes_sent;
}

int ViESender::SendRTCPPacket(int vie_id, const void* data, int len) {
  CriticalSectionScoped cs(critsect_);

  if (!transport_) {
    return -1;
  }

  assert(ChannelId(vie_id) == channel_id_);

  // Prepare for possible encryption and sending.
  // TODO(mflodman) Change decrypt to get rid of this cast.
  void* tmp_ptr = const_cast<void*>(data);
  unsigned char* send_packet = static_cast<unsigned char*>(tmp_ptr);
  int send_packet_length = len;

  if (rtp_dump_) {
    rtp_dump_->DumpPacket(send_packet, send_packet_length);
  }

  if (external_encryption_) {
    external_encryption_->encrypt_rtcp(
        channel_id_, send_packet, encryption_buffer_, send_packet_length,
        static_cast<int*>(&send_packet_length));
    send_packet = encryption_buffer_;
  }

  const int bytes_sent = transport_->SendRTCPPacket(channel_id_, send_packet,
                                                    send_packet_length);
  if (bytes_sent != send_packet_length) {
    WEBRTC_TRACE(
        webrtc::kTraceWarning, webrtc::kTraceVideo,
        ViEId(engine_id_, channel_id_),
        "ViESender::SendRTCPPacket - Transport failed to send RTCP packet");
  }
  return bytes_sent;
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: translatechanges.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 14:09:27 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"

#include "translatechanges.hxx"

#ifndef CONFIGMGR_CONFIGNODE_HXX_
#include "noderef.hxx"
#endif
#ifndef CONFIGMGR_CONFIGCHANGE_HXX_
#include "nodechange.hxx"
#endif
#ifndef CONFIGMGR_CONFIGCHANGEINFO_HXX_
#include "nodechangeinfo.hxx"
#endif
#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "apifactory.hxx"
#endif

namespace configmgr
{
// ---------------------------------------------------------------------------------------------------
    namespace css = ::com::sun::star;
    namespace uno       = css::uno;
    namespace lang      = css::lang;
    namespace util      = css::util;
    namespace beans     = css::beans;
    namespace container = css::container;
// ---------------------------------------------------------------------------------------------------

    namespace configuration
    {
        class NodeChange;
        class NodeChanges;
        class Tree;
        class NodeRef;
        class NodeID;
    }
// ---------------------------------------------------------------------------------------------------

    namespace configapi
    {
        using configuration::Tree;
        using configuration::TreeRef;
        using configuration::Name;
        using configuration::AbsolutePath;
        using configuration::RelativePath;
        using configuration::NodeRef;
        using configuration::NodeID;
        using configuration::NodeChangeInformation;
        using configuration::NodeChangeData;
        using configuration::NodeChangeLocation;
// ---------------------------------------------------------------------------------------------------
    //interpreting NodeChanges
// resolve the relative path from a given base to the changed node
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree)
{
    return resolveChangeLocation(aPath,aChange,aBaseTree,aBaseTree.getRootNode());
}
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree, NodeRef const& aBaseNode)
{
    OSL_ENSURE(aChange.isValidLocation(), "Trying to resolve against change location that wasn't set up properly");

    namespace Path = configuration::Path;

    typedef Path::Iterator Iter;

    Tree aChangeBaseTree = aChange.getBaseTree();

    AbsolutePath aOuterBasePath     = aBaseTree.getAbsolutePath(aBaseNode);
    AbsolutePath aChangeBasePath    = aChangeBaseTree.getAbsolutePath(aChange.getBaseNode());

    Iter aChangeIt = aChangeBasePath.begin(),   aChangeEnd = aChangeBasePath.end();
    Iter aOuterIt  = aOuterBasePath.begin(),    aOuterEnd  = aOuterBasePath.end();

    // First by resolve the base node pathes
    while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
    {
        if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
        ++aOuterIt;
        ++aChangeIt;
    }

    // Next consider the stored accessor
    if (aChangeIt != aChangeEnd) // stepping outward - prepend
    {
        Path::Rep aRemaining(aChangeIt, aChangeEnd);

        aPath = RelativePath(aRemaining).compose(aChange.getAccessor());
    }
    else if (aOuterIt == aOuterEnd) // exact match outside
    {
        aPath = aChange.getAccessor();
    }
    else //(aChangeIt == aChangeEnd) but outer left
    {
        RelativePath aAccessor = aChange.getAccessor();
        aChangeIt   = aAccessor.begin();
        aChangeEnd  = aAccessor.end();

        // resolve the outer path against the change accessor
        while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
        {
            if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
            ++aOuterIt;
            ++aChangeIt;
        }

        if (aOuterIt == aOuterEnd)
        {
            Path::Rep aRemaining(aChangeIt, aChangeEnd);

            aPath = RelativePath( aRemaining );
        }
    }

    return (aOuterIt == aOuterEnd); // resolved completely and assigned ??

}

// ---------------------------------------------------------------------------------------------------
// change path and base settings to start from the given base
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef)
{
    return rebaseChange(aChange,_aBaseTreeRef,_aBaseTreeRef.getRootNode());
}
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef, NodeRef const& aBaseNode)
{
    OSL_ENSURE(aChange.isValidLocation(), "Trying to rebase change location that wasn't set up properly");

    Tree aBaseTree(_aBaseTreeRef);

    RelativePath aNewPath;
    if (resolveChangeLocation(aNewPath,aChange,aBaseTree,aBaseNode))
    {
        aChange.setBase( aBaseTree, aBaseNode);
        aChange.setAccessor( aNewPath );
        return true;
    }
    else
        return false;
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects
bool resolveUnoObjects(UnoChange& aUnoChange, NodeChangeData const& aChange,
                       Factory& rFactory)
{
    if (aChange.isSetChange())
    {
        //Check we have ElementTree
        if ((aChange.element.newValue == NULL) &&
            (aChange.element.oldValue == NULL))
        {
            if( ( aChange.unoData.newValue.getValue()!=NULL) ||
               ( aChange.unoData.newValue.getValue()!=NULL))
            {
                return true;
            }
            else return false;
        }

        //Check if complex or simple type
        Tree aTree = aChange.isRemoveSetChange()?
            aChange.getOldElementTree():
            aChange.getNewElementTree();

        NodeRef aNodeRef = aTree.getRootNode();

        if (configuration::isStructuralNode(aTree, aNodeRef))
        {
            uno::Reference<uno::XInterface> aNewUnoObject = rFactory.findUnoElement(aChange.getNewElementNodeID());
            uno::Reference<uno::XInterface> aOldUnoObject = rFactory.findUnoElement(aChange.getOldElementNodeID());

            bool bFound = aNewUnoObject.is() || aOldUnoObject.is();
            aUnoChange.newValue <<= aNewUnoObject;
            aUnoChange.oldValue <<= aOldUnoObject;
            return bFound;
        }
        else
        {
            aUnoChange.newValue = configuration::getSimpleElementValue(aTree, aNodeRef);

            if (aChange.isReplaceSetChange() )
            {
                Tree aOldTree = aChange.getOldElementTree();

                aNodeRef = aOldTree.getRootNode();
                OSL_ENSURE(!configuration::isStructuralNode(aOldTree, aNodeRef), "resolveUnoObject types mismatch");
                aUnoChange.oldValue =  configuration::getSimpleElementValue(aOldTree, aNodeRef);
            }
            bool bFound = aUnoChange.newValue.hasValue() || aUnoChange.oldValue.hasValue();
            return bFound;
        }
    }
    else if (aChange.isValueChange())
    {
        aUnoChange.newValue = aChange.unoData.newValue;
        aUnoChange.oldValue = aChange.unoData.oldValue;
        return true;
    }
    else
    {
        return false;
    }
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects inplace
bool resolveToUno(NodeChangeData& aChange, Factory& rFactory)
{
    struct UnoChange aUnoChange;
    if (resolveUnoObjects(aUnoChange,aChange, rFactory))
    {
        aChange.unoData.newValue = aUnoChange.newValue;
        aChange.unoData.oldValue = aUnoChange.oldValue;
        return true;
    }
    else
        return false;
}
// ---------------------------------------------------------------------------------------------------

// building events
/// find the sending api object
void fillEventSource(lang::EventObject& rEvent, Tree const& aTree, NodeRef const& aNode, Factory& rFactory)
{
    rEvent.Source = rFactory.findUnoElement( NodeID(aTree,aNode) );
}
// ---------------------------------------------------------------------------------------------------

/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, Factory& rFactory)
{
    fillChange(rChange,aInfo,aBaseTree,aBaseTree.getRootNode(),rFactory);
}
/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, NodeRef const& aBaseNode, Factory& rFactory)
{
    RelativePath aRelativePath;
    if (!resolveChangeLocation(aRelativePath, aInfo.location, aBaseTree, aBaseNode))
        OSL_ENSURE(false, "WARNING: Change is not part of the given Tree");

    UnoChange aUnoChange;

    if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
        OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");

    rChange.Accessor        <<= aRelativePath.toString();
    rChange.Element         = aUnoChange.newValue;
    rChange.ReplacedElement = aUnoChange.oldValue;
}
// ---------------------------------------------------------------------------------------------------
/// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already)
void fillChangeFromResolved(util::ElementChange& rChange, NodeChangeInformation const& aInfo)
{
    rChange.Accessor        <<= aInfo.location.getAccessor().toString();
    rChange.Element         = aInfo.change.unoData.newValue;
    rChange.ReplacedElement = aInfo.change.unoData.oldValue;
}
// ---------------------------------------------------------------------------------------------------

/// fill a event from a NodeChangeInfo
bool fillEventData(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo, Factory& rFactory)
{
    UnoChange aUnoChange;
    if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
    {
        OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");
        return false;
    }

    rEvent.Accessor     <<= aInfo.location.getAccessor().getLocalName().getName().toString();
    rEvent.Element          = aUnoChange.newValue;
    rEvent.ReplacedElement  = aUnoChange.oldValue;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo)
{
    rEvent.Accessor         <<= aInfo.location.getAccessor().getLocalName().getName().toString();
    rEvent.Element          = aInfo.change.unoData.newValue;
    rEvent.ReplacedElement  = aInfo.change.unoData.oldValue;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventData(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore)
{
    if (!aInfo.isValueChange())
        return false;

     UnoChange aUnoChange;
    if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
        OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");

    rEvent.PropertyName     = aInfo.location.getAccessor().getLocalName().getName().toString();

    rEvent.NewValue         = aUnoChange.newValue;
    rEvent.OldValue         = aUnoChange.oldValue;

    rEvent.PropertyHandle   = -1;
     rEvent.Further         = bMore;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, bool bMore)
{
    if (!aInfo.isValueChange())
        return false;

    rEvent.PropertyName     = aInfo.location.getAccessor().getLocalName().getName().toString();

    rEvent.NewValue         = aInfo.change.unoData.newValue;
    rEvent.OldValue         = aInfo.change.unoData.oldValue;

    rEvent.PropertyHandle   = -1;
     rEvent.Further         = bMore;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
    }
// ---------------------------------------------------------------------------------------------------
}

<commit_msg>INTEGRATION: CWS changefileheader (1.11.16); FILE MERGED 2008/04/01 12:27:14 thb 1.11.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:38 rt 1.11.16.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: translatechanges.cxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_configmgr.hxx"

#include "translatechanges.hxx"
#include "noderef.hxx"
#include "nodechange.hxx"
#include "nodechangeinfo.hxx"
#include "apifactory.hxx"

namespace configmgr
{
// ---------------------------------------------------------------------------------------------------
    namespace css = ::com::sun::star;
    namespace uno       = css::uno;
    namespace lang      = css::lang;
    namespace util      = css::util;
    namespace beans     = css::beans;
    namespace container = css::container;
// ---------------------------------------------------------------------------------------------------

    namespace configuration
    {
        class NodeChange;
        class NodeChanges;
        class Tree;
        class NodeRef;
        class NodeID;
    }
// ---------------------------------------------------------------------------------------------------

    namespace configapi
    {
        using configuration::Tree;
        using configuration::TreeRef;
        using configuration::Name;
        using configuration::AbsolutePath;
        using configuration::RelativePath;
        using configuration::NodeRef;
        using configuration::NodeID;
        using configuration::NodeChangeInformation;
        using configuration::NodeChangeData;
        using configuration::NodeChangeLocation;
// ---------------------------------------------------------------------------------------------------
    //interpreting NodeChanges
// resolve the relative path from a given base to the changed node
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree)
{
    return resolveChangeLocation(aPath,aChange,aBaseTree,aBaseTree.getRootNode());
}
bool resolveChangeLocation(RelativePath& aPath, NodeChangeLocation const& aChange, Tree const& aBaseTree, NodeRef const& aBaseNode)
{
    OSL_ENSURE(aChange.isValidLocation(), "Trying to resolve against change location that wasn't set up properly");

    namespace Path = configuration::Path;

    typedef Path::Iterator Iter;

    Tree aChangeBaseTree = aChange.getBaseTree();

    AbsolutePath aOuterBasePath     = aBaseTree.getAbsolutePath(aBaseNode);
    AbsolutePath aChangeBasePath    = aChangeBaseTree.getAbsolutePath(aChange.getBaseNode());

    Iter aChangeIt = aChangeBasePath.begin(),   aChangeEnd = aChangeBasePath.end();
    Iter aOuterIt  = aOuterBasePath.begin(),    aOuterEnd  = aOuterBasePath.end();

    // First by resolve the base node pathes
    while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
    {
        if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
        ++aOuterIt;
        ++aChangeIt;
    }

    // Next consider the stored accessor
    if (aChangeIt != aChangeEnd) // stepping outward - prepend
    {
        Path::Rep aRemaining(aChangeIt, aChangeEnd);

        aPath = RelativePath(aRemaining).compose(aChange.getAccessor());
    }
    else if (aOuterIt == aOuterEnd) // exact match outside
    {
        aPath = aChange.getAccessor();
    }
    else //(aChangeIt == aChangeEnd) but outer left
    {
        RelativePath aAccessor = aChange.getAccessor();
        aChangeIt   = aAccessor.begin();
        aChangeEnd  = aAccessor.end();

        // resolve the outer path against the change accessor
        while (aOuterIt != aOuterEnd && aChangeIt != aChangeEnd)
        {
            if ( ! Path::matches(*aOuterIt,*aChangeIt) ) return false; // mismatch
            ++aOuterIt;
            ++aChangeIt;
        }

        if (aOuterIt == aOuterEnd)
        {
            Path::Rep aRemaining(aChangeIt, aChangeEnd);

            aPath = RelativePath( aRemaining );
        }
    }

    return (aOuterIt == aOuterEnd); // resolved completely and assigned ??

}

// ---------------------------------------------------------------------------------------------------
// change path and base settings to start from the given base
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef)
{
    return rebaseChange(aChange,_aBaseTreeRef,_aBaseTreeRef.getRootNode());
}
bool rebaseChange(NodeChangeLocation& aChange, TreeRef const& _aBaseTreeRef, NodeRef const& aBaseNode)
{
    OSL_ENSURE(aChange.isValidLocation(), "Trying to rebase change location that wasn't set up properly");

    Tree aBaseTree(_aBaseTreeRef);

    RelativePath aNewPath;
    if (resolveChangeLocation(aNewPath,aChange,aBaseTree,aBaseNode))
    {
        aChange.setBase( aBaseTree, aBaseNode);
        aChange.setAccessor( aNewPath );
        return true;
    }
    else
        return false;
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects
bool resolveUnoObjects(UnoChange& aUnoChange, NodeChangeData const& aChange,
                       Factory& rFactory)
{
    if (aChange.isSetChange())
    {
        //Check we have ElementTree
        if ((aChange.element.newValue == NULL) &&
            (aChange.element.oldValue == NULL))
        {
            if( ( aChange.unoData.newValue.getValue()!=NULL) ||
               ( aChange.unoData.newValue.getValue()!=NULL))
            {
                return true;
            }
            else return false;
        }

        //Check if complex or simple type
        Tree aTree = aChange.isRemoveSetChange()?
            aChange.getOldElementTree():
            aChange.getNewElementTree();

        NodeRef aNodeRef = aTree.getRootNode();

        if (configuration::isStructuralNode(aTree, aNodeRef))
        {
            uno::Reference<uno::XInterface> aNewUnoObject = rFactory.findUnoElement(aChange.getNewElementNodeID());
            uno::Reference<uno::XInterface> aOldUnoObject = rFactory.findUnoElement(aChange.getOldElementNodeID());

            bool bFound = aNewUnoObject.is() || aOldUnoObject.is();
            aUnoChange.newValue <<= aNewUnoObject;
            aUnoChange.oldValue <<= aOldUnoObject;
            return bFound;
        }
        else
        {
            aUnoChange.newValue = configuration::getSimpleElementValue(aTree, aNodeRef);

            if (aChange.isReplaceSetChange() )
            {
                Tree aOldTree = aChange.getOldElementTree();

                aNodeRef = aOldTree.getRootNode();
                OSL_ENSURE(!configuration::isStructuralNode(aOldTree, aNodeRef), "resolveUnoObject types mismatch");
                aUnoChange.oldValue =  configuration::getSimpleElementValue(aOldTree, aNodeRef);
            }
            bool bFound = aUnoChange.newValue.hasValue() || aUnoChange.oldValue.hasValue();
            return bFound;
        }
    }
    else if (aChange.isValueChange())
    {
        aUnoChange.newValue = aChange.unoData.newValue;
        aUnoChange.oldValue = aChange.unoData.oldValue;
        return true;
    }
    else
    {
        return false;
    }
}
// ---------------------------------------------------------------------------------------------------
// resolve non-uno elements to Uno Objects inplace
bool resolveToUno(NodeChangeData& aChange, Factory& rFactory)
{
    struct UnoChange aUnoChange;
    if (resolveUnoObjects(aUnoChange,aChange, rFactory))
    {
        aChange.unoData.newValue = aUnoChange.newValue;
        aChange.unoData.oldValue = aUnoChange.oldValue;
        return true;
    }
    else
        return false;
}
// ---------------------------------------------------------------------------------------------------

// building events
/// find the sending api object
void fillEventSource(lang::EventObject& rEvent, Tree const& aTree, NodeRef const& aNode, Factory& rFactory)
{
    rEvent.Source = rFactory.findUnoElement( NodeID(aTree,aNode) );
}
// ---------------------------------------------------------------------------------------------------

/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, Factory& rFactory)
{
    fillChange(rChange,aInfo,aBaseTree,aBaseTree.getRootNode(),rFactory);
}
/// fill a change info from a NodeChangeInfo
void fillChange(util::ElementChange& rChange, NodeChangeInformation const& aInfo, Tree const& aBaseTree, NodeRef const& aBaseNode, Factory& rFactory)
{
    RelativePath aRelativePath;
    if (!resolveChangeLocation(aRelativePath, aInfo.location, aBaseTree, aBaseNode))
        OSL_ENSURE(false, "WARNING: Change is not part of the given Tree");

    UnoChange aUnoChange;

    if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
        OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");

    rChange.Accessor        <<= aRelativePath.toString();
    rChange.Element         = aUnoChange.newValue;
    rChange.ReplacedElement = aUnoChange.oldValue;
}
// ---------------------------------------------------------------------------------------------------
/// fill a change info from a NodeChangeInfo (base,path and uno objects are assumed to be resolved already)
void fillChangeFromResolved(util::ElementChange& rChange, NodeChangeInformation const& aInfo)
{
    rChange.Accessor        <<= aInfo.location.getAccessor().toString();
    rChange.Element         = aInfo.change.unoData.newValue;
    rChange.ReplacedElement = aInfo.change.unoData.oldValue;
}
// ---------------------------------------------------------------------------------------------------

/// fill a event from a NodeChangeInfo
bool fillEventData(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo, Factory& rFactory)
{
    UnoChange aUnoChange;
    if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
    {
        OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");
        return false;
    }

    rEvent.Accessor     <<= aInfo.location.getAccessor().getLocalName().getName().toString();
    rEvent.Element          = aUnoChange.newValue;
    rEvent.ReplacedElement  = aUnoChange.oldValue;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo (uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(container::ContainerEvent& rEvent, NodeChangeInformation const& aInfo)
{
    rEvent.Accessor         <<= aInfo.location.getAccessor().getLocalName().getName().toString();
    rEvent.Element          = aInfo.change.unoData.newValue;
    rEvent.ReplacedElement  = aInfo.change.unoData.oldValue;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventData(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, Factory& rFactory, bool bMore)
{
    if (!aInfo.isValueChange())
        return false;

     UnoChange aUnoChange;
    if (!resolveUnoObjects(aUnoChange, aInfo.change, rFactory))
        OSL_ENSURE(false, "WARNING: Cannot find out old/new UNO objects involved in change");

    rEvent.PropertyName     = aInfo.location.getAccessor().getLocalName().getName().toString();

    rEvent.NewValue         = aUnoChange.newValue;
    rEvent.OldValue         = aUnoChange.oldValue;

    rEvent.PropertyHandle   = -1;
     rEvent.Further         = bMore;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
/// fill a event from a NodeChangeInfo(uno objects are assumed to be resolved already)
bool fillEventDataFromResolved(beans::PropertyChangeEvent& rEvent, NodeChangeInformation const& aInfo, bool bMore)
{
    if (!aInfo.isValueChange())
        return false;

    rEvent.PropertyName     = aInfo.location.getAccessor().getLocalName().getName().toString();

    rEvent.NewValue         = aInfo.change.unoData.newValue;
    rEvent.OldValue         = aInfo.change.unoData.oldValue;

    rEvent.PropertyHandle   = -1;
     rEvent.Further         = bMore;

    return !aInfo.isEmptyChange();
}
// ---------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------
    }
// ---------------------------------------------------------------------------------------------------
}

<|endoftext|>


<commit_before>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2009 FURUHASHI Sadayuki
//
//    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.
//
#ifndef MSGPACK_TYPE_STRING_HPP
#define MSGPACK_TYPE_STRING_HPP

#include "msgpack/object.hpp"
#include <string>

namespace msgpack {

inline std::string& operator>> (object const& o, std::string& v)
{
	if(o.type != type::BIN) { throw type_error(); }
	v.assign(o.via.bin.ptr, o.via.bin.size);
	return v;
}

template <typename Stream>
inline packer<Stream>& operator<< (packer<Stream>& o, const std::string& v)
{
	o.pack_bin(v.size());
	o.pack_bin_body(v.data(), v.size());
	return o;
}

inline void operator<< (object::with_zone& o, const std::string& v)
{
	o.type = type::BIN;
	char* ptr = (char*)o.zone->allocate_align(v.size());
	o.via.bin.ptr = ptr;
	o.via.bin.size = (uint32_t)v.size();
	memcpy(ptr, v.data(), v.size());
}

inline void operator<< (object& o, const std::string& v)
{
	o.type = type::BIN;
	o.via.bin.ptr = v.data();
	o.via.bin.size = (uint32_t)v.size();
}

}  // namespace msgpack

#endif /* msgpack/type/string.hpp */

<commit_msg>Added STR to std::string conversion.<commit_after>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2009 FURUHASHI Sadayuki
//
//    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.
//
#ifndef MSGPACK_TYPE_STRING_HPP
#define MSGPACK_TYPE_STRING_HPP

#include "msgpack/object.hpp"
#include <string>

namespace msgpack {

inline std::string& operator>> (object const& o, std::string& v)
{
	switch (o.type) {
	case type::BIN:
		v.assign(o.via.bin.ptr, o.via.bin.size);
		break;
	case type::STR:
		v.assign(o.via.str.ptr, o.via.str.size);
		break;
	default:
		throw type_error();
		break;
	}
	return v;
}

template <typename Stream>
inline packer<Stream>& operator<< (packer<Stream>& o, const std::string& v)
{
	o.pack_bin(v.size());
	o.pack_bin_body(v.data(), v.size());
	return o;
}

inline void operator<< (object::with_zone& o, const std::string& v)
{
	o.type = type::BIN;
	char* ptr = (char*)o.zone->allocate_align(v.size());
	o.via.bin.ptr = ptr;
	o.via.bin.size = (uint32_t)v.size();
	memcpy(ptr, v.data(), v.size());
}

inline void operator<< (object& o, const std::string& v)
{
	o.type = type::BIN;
	o.via.bin.ptr = v.data();
	o.via.bin.size = (uint32_t)v.size();
}

}  // namespace msgpack

#endif /* msgpack/type/string.hpp */

<|endoftext|>