<commit_before>#include <sys/time.h>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/export.hpp>

#include "watcherGlobalFunctions.h"     // for NodeIdentifier::serialize()
#include "message.h"

using namespace std;

namespace watcher {
    namespace event {
        INIT_LOGGER(Message, "Message");

        Message::Message() : version(0), type(UNKNOWN_MESSAGE_TYPE), timestamp(0)
        {
            TRACE_ENTER();
            struct timeval tp;
            gettimeofday(&tp, NULL);
            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec/1000;
            TRACE_EXIT();
        }

        Message::Message(const MessageType &t, const unsigned int v) :
            version(v), type(t), timestamp(0)
        {
            TRACE_ENTER();
            struct timeval tp;
            gettimeofday(&tp, NULL);
            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec/1000;
            TRACE_EXIT();
        }

        Message::Message(const Message &other) :
            version(other.version), type(other.type), timestamp(other.timestamp)
        {
            TRACE_ENTER();
            TRACE_EXIT();
        }

        Message::~Message()
        {
            TRACE_ENTER();
            TRACE_EXIT();
        }

        bool Message::operator==(const Message &other) const
        {
            TRACE_ENTER();
            bool retVal = version==other.version && type==other.type;
            TRACE_EXIT_RET(retVal);
            return retVal;
        }

        Message &Message::operator=(const Message &other)
        {
            TRACE_ENTER();
            version=other.version;
            type=other.type;
            timestamp=other.timestamp;
            TRACE_EXIT();
            return *this;
        }

        // virtual
        std::ostream &Message::toStream(std::ostream &out) const
        {
            TRACE_ENTER();
            out << " version: " << version << " type: " << type << " time: " << timestamp << " ";
            TRACE_EXIT();
            return out;
        }

        ostream& operator<<(ostream &out, const Message &mess)
        {
            TRACE_ENTER();
            mess.operator<<(out);
            TRACE_EXIT();
            return out;
        }

        template <typename Archive> void Message::serialize(Archive & ar, const unsigned int /* file_version */)
        {
            TRACE_ENTER();
            ar & version;
            ar & type;
            ar & timestamp;
            ar & fromNodeID;
            TRACE_EXIT();
        }

        MessagePtr Message::unpack(std::istream& is)
        {
            boost::archive::text_iarchive ia(is);
            Message* ret = 0;
            try
            {
                ia >> ret;
            }
            catch (boost::archive::archive_exception& e)
            {
                LOG_WARN("Exception thrown while serializing the message: " << e.what());
                return MessagePtr();
            }
            return MessagePtr(ret);
        }

        void Message::pack(std::ostream& os) const
        {
            TRACE_ENTER();
            boost::archive::text_oarchive oa(os);
            const Message* base = this;
            oa << base;
            TRACE_EXIT();
        }
    }
}

BOOST_CLASS_EXPORT(watcher::event::Message);
<commit_msg>message: print fromNodeId in toStream().<commit_after>#include <sys/time.h>

#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/export.hpp>

#include "watcherGlobalFunctions.h"     // for NodeIdentifier::serialize()
#include "message.h"

using namespace std;

namespace watcher {
    namespace event {
        INIT_LOGGER(Message, "Message");

        Message::Message() : version(0), type(UNKNOWN_MESSAGE_TYPE), timestamp(0)
        {
            TRACE_ENTER();
            struct timeval tp;
            gettimeofday(&tp, NULL);
            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec/1000;
            TRACE_EXIT();
        }

        Message::Message(const MessageType &t, const unsigned int v) :
            version(v), type(t), timestamp(0)
        {
            TRACE_ENTER();
            struct timeval tp;
            gettimeofday(&tp, NULL);
            timestamp = (long long int)tp.tv_sec * 1000 + (long long int)tp.tv_usec/1000;
            TRACE_EXIT();
        }

        Message::Message(const Message &other) :
            version(other.version), type(other.type), timestamp(other.timestamp)
        {
            TRACE_ENTER();
            TRACE_EXIT();
        }

        Message::~Message()
        {
            TRACE_ENTER();
            TRACE_EXIT();
        }

        bool Message::operator==(const Message &other) const
        {
            TRACE_ENTER();
            bool retVal = version==other.version && type==other.type;
            TRACE_EXIT_RET(retVal);
            return retVal;
        }

        Message &Message::operator=(const Message &other)
        {
            TRACE_ENTER();
            version=other.version;
            type=other.type;
            timestamp=other.timestamp;
            TRACE_EXIT();
            return *this;
        }

        // virtual
        std::ostream &Message::toStream(std::ostream &out) const
        {
            TRACE_ENTER();
            out << "from: " << fromNodeID << " version: " << version << " type: " << type << " time: " << timestamp << " ";
            TRACE_EXIT();
            return out;
        }

        ostream& operator<<(ostream &out, const Message &mess)
        {
            TRACE_ENTER();
            mess.operator<<(out);
            TRACE_EXIT();
            return out;
        }

        template <typename Archive> void Message::serialize(Archive & ar, const unsigned int /* file_version */)
        {
            TRACE_ENTER();
            ar & version;
            ar & type;
            ar & timestamp;
            ar & fromNodeID;
            TRACE_EXIT();
        }

        MessagePtr Message::unpack(std::istream& is)
        {
            boost::archive::text_iarchive ia(is);
            Message* ret = 0;
            try
            {
                ia >> ret;
            }
            catch (boost::archive::archive_exception& e)
            {
                LOG_WARN("Exception thrown while serializing the message: " << e.what());
                return MessagePtr();
            }
            return MessagePtr(ret);
        }

        void Message::pack(std::ostream& os) const
        {
            TRACE_ENTER();
            boost::archive::text_oarchive oa(os);
            const Message* base = this;
            oa << base;
            TRACE_EXIT();
        }
    }
}

BOOST_CLASS_EXPORT(watcher::event::Message);
<|endoftext|>


<commit_before>#include "Configuration.h"
#include "CudaElfFactory.h"
#include "SMPElfFactory.h"
#include <matrix/Matrix.h>
#include <matrix/MatrixHelper.h>

#include <stdexcept>
#include <cstdlib>
#include <iostream>
#include <fstream>

#include <boost/program_options.hpp>

using namespace std;

Configuration::Configuration(int argc, char** argv)
    : argc(argc), _useFiles(false), arguments(argv), programName(argv[0]), _category("matrix")
{

}

bool Configuration::parseArguments()
{
    namespace po = boost::program_options;
    po::options_description desc("Options");

    try
    {
        desc.add_options()
            ("help", "Print help message")
            ("mode,m",               po::value<string>(&_mode)->required(), "Mode (smp|cuda)")
            ("numwarmups,w",         po::value<size_t>(&_numberOfWarmUps)->default_value(50), "Number of warmup rounds")
            ("numiter,n",            po::value<size_t>(&_numberOfIterations)->default_value(100), "Number of benchmark iterations")
            ("input,i",              po::value<string>(&_inputFile), "Input file")
            ("output,o",             po::value<string>(&_outputFile), "Output file")
            ("export_configuration", po::value<string>(&_exportConfigurationFile), "Measure cluster and export configuration")
            ("import_configuration", po::value<string>(&_importConfigurationFile), "Run benchmark with given configuration")
            ("skip_benchmark",       "Skip the benchmark run")
            ("left_rows",            po::value<size_t>(&_leftMatrixRows)->default_value(500), "Number of left rows to be generated (overridden for benchmark by input file)")
            ("common_rows_columns",  po::value<size_t>(&_commonMatrixRowsColumns)->default_value(500), "Number of left columns / right rows to be generated (overridden for benchmark by input file)")
            ("right_columns",        po::value<size_t>(&_rightMatrixColumns)->default_value(500), "Number of right columns to be generated (overridden for benchmark by input file)");

        po::variables_map vm;
        po::store(po::parse_command_line(argc, arguments, desc), vm);

        if(vm.count("help") || argc == 1)
        {
            cout << "Dwarf Mine Benchmark" << endl << desc << endl;
            return false;
        }

        po::notify(vm);

        if(vm.count("input") ^ vm.count("output"))
            throw logic_error("Both input and output are needed, if one is given");

        if(vm.count("input") && vm.count("output"))
           _useFiles = true;

        if(vm.count("mode") && (_mode != "smp" && _mode != "cuda"))
            throw logic_error("Mode must be smp or cuda");

    }
    catch(const po::error& e)
    {
        cerr << desc << endl;
        throw;
    }

    return true;
}

unique_ptr<ProblemStatement> generateProblemStatement(string elfCategory, size_t leftRows, size_t commonRowsColumns, size_t rightColumns)
{
    auto statement = unique_ptr<ProblemStatement>(new ProblemStatement(elfCategory));
    Matrix<float> left(leftRows, commonRowsColumns);
    Matrix<float> right(commonRowsColumns, rightColumns);
    auto distribution = uniform_real_distribution<float> (-100, +100);
    auto engine = mt19937(time(nullptr));
    auto generator = bind(distribution, engine);
    MatrixHelper::fill(left, generator);
    MatrixHelper::fill(right, generator);
    MatrixHelper::writeMatrixTo(*(statement->input), left);
    MatrixHelper::writeMatrixTo(*(statement->input), right);
    return statement;
}

unique_ptr<ProblemStatement> Configuration::getProblemStatement(bool forceGenerated)
{

    if(!_useFiles || forceGenerated)
    {
        return generateProblemStatement(_category, _leftMatrixRows, _commonMatrixRowsColumns, _rightMatrixColumns);
    }
    return unique_ptr<ProblemStatement>(new ProblemStatement(getElfCategory(), _inputFile, _outputFile));
}

unique_ptr<ElfFactory> Configuration::getElfFactory()
{
    return createElfFactory(_mode, getElfCategory());
}

size_t Configuration::getNumberOfIterations()
{
    return _numberOfIterations;
}

size_t Configuration::getNumberOfWarmUps()
{
    return _numberOfWarmUps;
}

string Configuration::getElfCategory() const
{
    return _category;
}

bool Configuration::exportConfiguration() const
{
    return _exportConfigurationFile != "";
}

bool Configuration::importConfiguration() const
{
    return _importConfigurationFile != "";
}

bool Configuration::skipBenchmark() const
{
    return _skipBenchmark;
}

std::string Configuration::getExportConfigurationFilename() const
{
    return _exportConfigurationFile;
}

std::string Configuration::getImportConfigurationFilename() const
{
    return _importConfigurationFile;
}

std::ostream& operator<<(std::ostream& s, const Configuration& c)
{
    s   << "Configuation: "
        << "\n\tMode: "<< c._mode
        << "\n\tWarmUps: " << c._numberOfWarmUps
        << "\n\tIterations: " << c._numberOfIterations;
    if (c._useFiles)
    {
        s   << "\n\tInput: " << c._inputFile
            << "\n\tOutput: " << c._outputFile;
    }
    else
    {
        s   << "\n\tMatrices: ("<<c._leftMatrixRows<<" x "<<c._commonMatrixRowsColumns<<") x ("<<c._commonMatrixRowsColumns<<" x "<<c._rightMatrixColumns<<")";
    }
    return s;
}
<commit_msg>configuration now checks the --skip_benchmark flag<commit_after>#include "Configuration.h"
#include "CudaElfFactory.h"
#include "SMPElfFactory.h"
#include <matrix/Matrix.h>
#include <matrix/MatrixHelper.h>

#include <stdexcept>
#include <cstdlib>
#include <iostream>
#include <fstream>

#include <boost/program_options.hpp>

using namespace std;

Configuration::Configuration(int argc, char** argv)
    : argc(argc), _useFiles(false), arguments(argv), programName(argv[0]), _category("matrix")
{

}

bool Configuration::parseArguments()
{
    namespace po = boost::program_options;
    po::options_description desc("Options");

    try
    {
        desc.add_options()
            ("help", "Print help message")
            ("mode,m",               po::value<string>(&_mode)->required(), "Mode (smp|cuda)")
            ("numwarmups,w",         po::value<size_t>(&_numberOfWarmUps)->default_value(50), "Number of warmup rounds")
            ("numiter,n",            po::value<size_t>(&_numberOfIterations)->default_value(100), "Number of benchmark iterations")
            ("input,i",              po::value<string>(&_inputFile), "Input file")
            ("output,o",             po::value<string>(&_outputFile), "Output file")
            ("export_configuration", po::value<string>(&_exportConfigurationFile), "Measure cluster and export configuration")
            ("import_configuration", po::value<string>(&_importConfigurationFile), "Run benchmark with given configuration")
            ("skip_benchmark",       "Skip the benchmark run")
            ("left_rows",            po::value<size_t>(&_leftMatrixRows)->default_value(500), "Number of left rows to be generated (overridden for benchmark by input file)")
            ("common_rows_columns",  po::value<size_t>(&_commonMatrixRowsColumns)->default_value(500), "Number of left columns / right rows to be generated (overridden for benchmark by input file)")
            ("right_columns",        po::value<size_t>(&_rightMatrixColumns)->default_value(500), "Number of right columns to be generated (overridden for benchmark by input file)");

        po::variables_map vm;
        po::store(po::parse_command_line(argc, arguments, desc), vm);

        if(vm.count("help") || argc == 1)
        {
            cout << "Dwarf Mine Benchmark" << endl << desc << endl;
            return false;
        }

        po::notify(vm);

        if(vm.count("input") ^ vm.count("output"))
            throw logic_error("Both input and output are needed, if one is given");

        if(vm.count("input") && vm.count("output"))
           _useFiles = true;

        if(vm.count("mode") && (_mode != "smp" && _mode != "cuda"))
            throw logic_error("Mode must be smp or cuda");

        _skipBenchmark = vm.count("skip_benchmark") > 0;

    }
    catch(const po::error& e)
    {
        cerr << desc << endl;
        throw;
    }

    return true;
}

unique_ptr<ProblemStatement> generateProblemStatement(string elfCategory, size_t leftRows, size_t commonRowsColumns, size_t rightColumns)
{
    auto statement = unique_ptr<ProblemStatement>(new ProblemStatement(elfCategory));
    Matrix<float> left(leftRows, commonRowsColumns);
    Matrix<float> right(commonRowsColumns, rightColumns);
    auto distribution = uniform_real_distribution<float> (-100, +100);
    auto engine = mt19937(time(nullptr));
    auto generator = bind(distribution, engine);
    MatrixHelper::fill(left, generator);
    MatrixHelper::fill(right, generator);
    MatrixHelper::writeMatrixTo(*(statement->input), left);
    MatrixHelper::writeMatrixTo(*(statement->input), right);
    return statement;
}

unique_ptr<ProblemStatement> Configuration::getProblemStatement(bool forceGenerated)
{

    if(!_useFiles || forceGenerated)
    {
        return generateProblemStatement(_category, _leftMatrixRows, _commonMatrixRowsColumns, _rightMatrixColumns);
    }
    return unique_ptr<ProblemStatement>(new ProblemStatement(getElfCategory(), _inputFile, _outputFile));
}

unique_ptr<ElfFactory> Configuration::getElfFactory()
{
    return createElfFactory(_mode, getElfCategory());
}

size_t Configuration::getNumberOfIterations()
{
    return _numberOfIterations;
}

size_t Configuration::getNumberOfWarmUps()
{
    return _numberOfWarmUps;
}

string Configuration::getElfCategory() const
{
    return _category;
}

bool Configuration::exportConfiguration() const
{
    return _exportConfigurationFile != "";
}

bool Configuration::importConfiguration() const
{
    return _importConfigurationFile != "";
}

bool Configuration::skipBenchmark() const
{
    return _skipBenchmark;
}

std::string Configuration::getExportConfigurationFilename() const
{
    return _exportConfigurationFile;
}

std::string Configuration::getImportConfigurationFilename() const
{
    return _importConfigurationFile;
}

std::ostream& operator<<(std::ostream& s, const Configuration& c)
{
    s   << "Configuation: "
        << "\n\tMode: "<< c._mode
        << "\n\tWarmUps: " << c._numberOfWarmUps
        << "\n\tIterations: " << c._numberOfIterations;
    if (c._useFiles)
    {
        s   << "\n\tInput: " << c._inputFile
            << "\n\tOutput: " << c._outputFile;
    }
    else
    {
        s   << "\n\tMatrices: ("<<c._leftMatrixRows<<" x "<<c._commonMatrixRowsColumns<<") x ("<<c._commonMatrixRowsColumns<<" x "<<c._rightMatrixColumns<<")";
    }
    return s;
}
<|endoftext|>


<commit_before>/**
 * @file gason.hpp
 * a simple and fast JSon parser in plain C/C++ with no dependency.
 *
 *
 * @author Ivan Vashchaev
 * @version 1.0.0
 * @date 2014-05-08
 * based on this commit: 9e292d4
 *
 * @author amir zamani
 * @version 2.0.0
 * @date 2014-05-16
 *
 */

#ifndef __GASON_HPP__
#define __GASON_HPP__
///////////////////////////////////////////////////////////////////////////////
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include <string.h>
///////////////////////////////////////////////////////////////////////////////
namespace gason {
///////////////////////////////////////////////////////////////////////////////
#ifndef nullptr
#   define nullptr      NULL
#endif
///////////////////////////////////////////////////////////////////////////////
/** tag (type) of each JSon element. */
enum JsonTag {
    JSON_TAG_NUMBER = 0,        ///< double (floating point) value
    JSON_TAG_STRING,            ///< string value
    JSON_TAG_BOOL,              ///< boolean (true/false) value
    JSON_TAG_ARRAY,             ///< an array value
    JSON_TAG_OBJECT,            ///< an object value
    JSON_TAG_NULL = 0xF         ///< null or invalid value
};
///////////////////////////////////////////////////////////////////////////////
struct JsonNode;
///////////////////////////////////////////////////////////////////////////////
/** JSon value of @sa JsonTag type. */
struct JsonValue {
    union {
        uint64_t    ival;
        double      fval;
    };

    JsonValue() : ival(JSON_VALUE_NULL) {
    }
    JsonValue(double x) : fval(x) {
    }
    JsonValue(JsonTag tag, void *p) {
        uint64_t x = (uint64_t)p;
        assert(tag <= JSON_VALUE_TAG_MASK);
        assert(x <= JSON_VALUE_PAYLOAD_MASK);
        ival = JSON_VALUE_NAN_MASK | ((uint64_t)tag << JSON_VALUE_TAG_SHIFT) | x;
    }
    uint64_t    getPayload() const {
        assert(!isDouble());
        return ival & JSON_VALUE_PAYLOAD_MASK;
    }

    bool        isDouble() const {
        return (int64_t)ival <= (int64_t)JSON_VALUE_NAN_MASK;
    }
    JsonTag     getTag() const {
        return isDouble() ? JSON_TAG_NUMBER : JsonTag((ival >> JSON_VALUE_TAG_SHIFT) & JSON_VALUE_TAG_MASK);
    }

    double      toNumber() const {
        assert(getTag() == JSON_TAG_NUMBER);
        return fval;
    }
    bool        toBool() const {
        assert(getTag() == JSON_TAG_BOOL);
        return (bool)getPayload();
    }
    char*       toString() const {
        assert(getTag() == JSON_TAG_STRING);
        return (char *)getPayload();
    }
    JsonNode*   toNode() const {
        assert(getTag() == JSON_TAG_ARRAY || getTag() == JSON_TAG_OBJECT);
        return (JsonNode *)getPayload();
    }

    /** returns true if this object is not NULL. */
    operator bool()const {
        return getTag() != JSON_TAG_NULL;
    }
    /** returns true if this object has typeof tag value. */
    bool        operator==(JsonTag tag) const {
        return getTag() == tag;
    }
    /** returns true if this object is not typeof tag value. */
    bool        operator!=(JsonTag tag) const {
        return getTag() != tag;
    }

    /** overloads @sa at. */
    JsonValue   operator[](size_t index) const {
        return at(index);
    }
    /** overloads @sa child. */
    JsonValue   operator()(const char* keyName) const {
        return child(keyName);
    }
    /** returns a child value associated with the key = keyName. */
    JsonValue   child(const char* keyName) const;
    /** returns the item at index position i in the array. */
    JsonValue   at(size_t i) const;

protected:
    static const uint64_t JSON_VALUE_PAYLOAD_MASK = 0x00007FFFFFFFFFFFULL;
    static const uint64_t JSON_VALUE_NAN_MASK     = 0x7FF8000000000000ULL;
    static const uint64_t JSON_VALUE_NULL         = 0x7FFF800000000000ULL;
    static const uint64_t JSON_VALUE_TAG_MASK     = 0xF;
    static const uint64_t JSON_VALUE_TAG_SHIFT    = 47;
};
///////////////////////////////////////////////////////////////////////////////
struct JsonNode {
    JsonValue   value;
    JsonNode*   next;
    char*       key;
};
///////////////////////////////////////////////////////////////////////////////
struct JsonIterator {
    JsonNode*   p;

    explicit JsonIterator(JsonNode* n = nullptr) : p(n) {
    }

    void        operator++() {
        p = p->next;
    }
    void        operator++(int) {
        p = p->next;
    }
    bool       isValid()const {
        return p != nullptr;
    }

    bool        operator==(const char* key) const {
        return strncmp(p->key, key, strlen(key)) == 0;
    }
    bool        operator!=(const JsonIterator &x) const {
        return p != x.p;
    }

    JsonNode*   operator*() const {
        return p;
    }
    JsonNode*   operator->() const {
        return p;
    }
};

inline JsonIterator begin(JsonValue o) {
    return JsonIterator(o.toNode());
}
inline JsonIterator end(JsonValue) {
    return JsonIterator(nullptr);
}
///////////////////////////////////////////////////////////////////////////////

enum JsonParseStatus {
    JSON_PARSE_OK,
    JSON_PARSE_BAD_NUMBER,
    JSON_PARSE_BAD_STRING,
    JSON_PARSE_BAD_IDENTIFIER,
    JSON_PARSE_STACK_OVERFLOW,
    JSON_PARSE_STACK_UNDERFLOW,
    JSON_PARSE_MISMATCH_BRACKET,
    JSON_PARSE_UNEXPECTED_CHARACTER,
    JSON_PARSE_UNQUOTED_KEY,
    JSON_PARSE_BREAKING_BAD
};

class JsonAllocator {
    struct  Zone;
    Zone*   head;

public:
    JsonAllocator() : head(nullptr) {
    }
    ~JsonAllocator();
    void*   allocate(size_t size);
    void    deallocate();
};

JsonParseStatus
jsonParse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator);

inline JsonParseStatus
jsonParse(char* str, JsonValue& value, JsonAllocator& allocator) {
    char *endptr = 0;
    return jsonParse(str, &endptr, &value, allocator);
}
///////////////////////////////////////////////////////////////////////////////
} // namespace gason
///////////////////////////////////////////////////////////////////////////////
#endif // __GASON_HPP__
<commit_msg>add hasNext() to JsonIterator. make getPayload() protected.<commit_after>/**
 * @file gason.hpp
 * a simple and fast JSon parser in plain C/C++ with no dependency.
 *
 *
 * @author Ivan Vashchaev
 * @version 1.0.0
 * @date 2014-05-08
 * based on this commit: 9e292d4
 *
 * @author amir zamani
 * @version 2.0.0
 * @date 2014-05-16
 *
 */

#ifndef __GASON_HPP__
#define __GASON_HPP__
///////////////////////////////////////////////////////////////////////////////
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include <string.h>
///////////////////////////////////////////////////////////////////////////////
namespace gason {
///////////////////////////////////////////////////////////////////////////////
#ifndef nullptr
#   define nullptr      NULL
#endif
///////////////////////////////////////////////////////////////////////////////
/** tag (type) of each JSon element. */
enum JsonTag {
    JSON_TAG_NUMBER = 0,        ///< double (floating point) value
    JSON_TAG_STRING,            ///< string value
    JSON_TAG_BOOL,              ///< boolean (true/false) value
    JSON_TAG_ARRAY,             ///< an array value
    JSON_TAG_OBJECT,            ///< an object value
    JSON_TAG_NULL = 0xF         ///< null or invalid value
};
///////////////////////////////////////////////////////////////////////////////
struct JsonNode;
///////////////////////////////////////////////////////////////////////////////
/** JSon value of @sa JsonTag type. */
struct JsonValue {
    union {
        uint64_t    ival;
        double      fval;
    };

    JsonValue() : ival(JSON_VALUE_NULL) {
    }
    JsonValue(double x) : fval(x) {
    }
    JsonValue(JsonTag tag, void *p) {
        uint64_t x = (uint64_t)p;
        assert(tag <= JSON_VALUE_TAG_MASK);
        assert(x <= JSON_VALUE_PAYLOAD_MASK);
        ival = JSON_VALUE_NAN_MASK | ((uint64_t)tag << JSON_VALUE_TAG_SHIFT) | x;
    }

    bool        isDouble() const {
        return (int64_t)ival <= (int64_t)JSON_VALUE_NAN_MASK;
    }
    JsonTag     getTag() const {
        return isDouble() ? JSON_TAG_NUMBER : JsonTag((ival >> JSON_VALUE_TAG_SHIFT) & JSON_VALUE_TAG_MASK);
    }

    // all toXXX() methods do assert().
    int         toInt() const {
        return (int) toNumber();
    }
    double      toNumber() const {
        assert(getTag() == JSON_TAG_NUMBER);
        return fval;
    }
    bool        toBool() const {
        assert(getTag() == JSON_TAG_BOOL);
        return (bool)getPayload();
    }
    char*       toString() const {
        assert(getTag() == JSON_TAG_STRING);
        return (char *)getPayload();
    }
    JsonNode*   toNode() const {
        assert(getTag() == JSON_TAG_ARRAY || getTag() == JSON_TAG_OBJECT);
        return (JsonNode *)getPayload();
    }

    /** returns true if this object is not NULL. */
    operator bool()const {
        return getTag() != JSON_TAG_NULL;
    }
    /** returns true if this object has typeof tag value. */
    bool        operator==(JsonTag tag) const {
        return getTag() == tag;
    }
    /** returns true if this object is not typeof tag value. */
    bool        operator!=(JsonTag tag) const {
        return getTag() != tag;
    }

    /** overloads @sa at. */
    JsonValue   operator[](size_t index) const {
        return at(index);
    }
    /** overloads @sa child. */
    JsonValue   operator()(const char* keyName) const {
        return child(keyName);
    }
    /** returns a child value associated with the key = keyName. */
    JsonValue   child(const char* keyName) const;
    /** returns the item at index position i in the array. */
    JsonValue   at(size_t i) const;

protected:
    uint64_t    getPayload() const {
        assert(!isDouble());
        return ival & JSON_VALUE_PAYLOAD_MASK;
    }

    static const uint64_t JSON_VALUE_PAYLOAD_MASK = 0x00007FFFFFFFFFFFULL;
    static const uint64_t JSON_VALUE_NAN_MASK     = 0x7FF8000000000000ULL;
    static const uint64_t JSON_VALUE_NULL         = 0x7FFF800000000000ULL;
    static const uint64_t JSON_VALUE_TAG_MASK     = 0xF;
    static const uint64_t JSON_VALUE_TAG_SHIFT    = 47;
};
///////////////////////////////////////////////////////////////////////////////
struct JsonNode {
    JsonValue   value;
    JsonNode*   next;
    char*       key;
};
///////////////////////////////////////////////////////////////////////////////
struct JsonIterator {
    JsonNode*   p;

    explicit JsonIterator(JsonNode* n = nullptr) : p(n) {
    }

    void       operator++() {
        p = p->next;
    }
    void       operator++(int) {
        p = p->next;
    }

    bool       isValid()const {
        return p != nullptr;
    }
    bool       hasNext()const {
        return p->next != nullptr;
    }

    bool       operator==(const char* key) const {
        return strncmp(p->key, key, strlen(key)) == 0;
    }
    bool       operator!=(const JsonIterator &x) const {
        return p != x.p;
    }

    JsonNode*  operator*() const {
        return p;
    }
    JsonNode*  operator->() const {
        return p;
    }
};

inline JsonIterator begin(JsonValue o) {
    return JsonIterator(o.toNode());
}
inline JsonIterator end(JsonValue) {
    return JsonIterator(nullptr);
}
///////////////////////////////////////////////////////////////////////////////

enum JsonParseStatus {
    JSON_PARSE_OK,
    JSON_PARSE_BAD_NUMBER,
    JSON_PARSE_BAD_STRING,
    JSON_PARSE_BAD_IDENTIFIER,
    JSON_PARSE_STACK_OVERFLOW,
    JSON_PARSE_STACK_UNDERFLOW,
    JSON_PARSE_MISMATCH_BRACKET,
    JSON_PARSE_UNEXPECTED_CHARACTER,
    JSON_PARSE_UNQUOTED_KEY,
    JSON_PARSE_BREAKING_BAD
};

class JsonAllocator {
    struct  Zone;
    Zone*   head;

public:
    JsonAllocator() : head(nullptr) {
    }
    ~JsonAllocator();
    void*   allocate(size_t size);
    void    deallocate();
};

JsonParseStatus
jsonParse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator);

inline JsonParseStatus
jsonParse(char* str, JsonValue& value, JsonAllocator& allocator) {
    char *endptr = 0;
    return jsonParse(str, &endptr, &value, allocator);
}
///////////////////////////////////////////////////////////////////////////////
} // namespace gason
///////////////////////////////////////////////////////////////////////////////
#endif // __GASON_HPP__
<|endoftext|>


<commit_before>/*
 * Copyright (c) [2014-2015] Novell, Inc.
 * Copyright (c) 2016 SUSE LLC
 *
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of version 2 of the GNU General Public License as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, contact Novell, Inc.
 *
 * To contact Novell about this file by physical or electronic mail, you may
 * find current contact information at www.novell.com.
 */

#include "storage/Action.h"
#include "storage/DevicegraphImpl.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/Partition.h"

namespace storage
{

    namespace Action
    {

	Text
	Create::text(const Actiongraph::Impl& actiongraph, Tense tense) const
	{
	    return get_device_rhs(actiongraph)->get_impl().do_create_text(tense);
	}

	void
	Create::commit(const Actiongraph::Impl& actiongraph) const
	{
	    get_device_rhs(actiongraph)->get_impl().do_create();
	}

	Text
	Delete::text(const Actiongraph::Impl& actiongraph, Tense tense) const
	{
	    return get_device_lhs(actiongraph)->get_impl().do_delete_text(tense);
	}

	void
	Delete::commit(const Actiongraph::Impl& actiongraph) const
	{
	    get_device_lhs(actiongraph)->get_impl().do_delete();
	}

	void
	Create::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const
	{
	    // Create actions are sometimes used just as sync points, they
	    // should not generate extra dependencies in those cases
	    if (only_sync) return;

	    Base::add_dependencies(v, actiongraph);

	    sid_t sid = actiongraph[v]->sid;

	    Devicegraph::Impl::vertex_descriptor v_in_rhs = actiongraph.get_devicegraph(RHS)->get_impl().find_vertex(sid);

	    // iterate parents
	    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;
	    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_rhs, actiongraph.get_devicegraph(RHS)->get_impl().graph); vi != vi_end; ++vi)
	    {
		sid_t parent_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();

		if (!actiongraph.get_devicegraph(LHS)->device_exists(parent_sid))
		{
		    // parents must be created beforehand if not existed

		    Actiongraph::Impl::vertex_descriptor tmp = actiongraph.actions_with_sid(parent_sid, ONLY_LAST).front();
		    actiongraph.add_edge(tmp, v);
		}
		else
		{
		    // children of parents must be deleted beforehand

		    Devicegraph::Impl::vertex_descriptor q = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(parent_sid);

		    Devicegraph::Impl::adjacency_iterator vi2, vi2_end;
		    for (boost::tie(vi2, vi2_end) = adjacent_vertices(q, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi2 != vi2_end; ++vi2)
		    {
			sid_t child_sid = actiongraph.get_devicegraph(LHS)->get_impl()[*vi2]->get_sid();

			vector<Actiongraph::Impl::vertex_descriptor> tmp = actiongraph.actions_with_sid(child_sid, ONLY_LAST);
			if (!tmp.empty())
			{
			    // Make sure it's a delete action
			    const Action::Base* tmp_action = actiongraph[tmp.front()];
			    if (dynamic_cast<const Action::Delete*>(tmp_action))
				actiongraph.add_edge(tmp.front(), v);
			}
		    }
		}
	    }

	}

	void
	Delete::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const
	{
	    Base::add_dependencies(v, actiongraph);

	    // all children must be deleted beforehand

	    sid_t sid = actiongraph[v]->sid;

	    Devicegraph::Impl::vertex_descriptor v_in_lhs = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(sid);

	    // iterate children
	    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;
	    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_lhs, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi != vi_end; ++vi)
	    {
		sid_t child_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();

		for (Actiongraph::Impl::vertex_descriptor tmp : actiongraph.actions_with_sid(child_sid, ONLY_FIRST))
		    actiongraph.add_edge(v, tmp);
	    }
	}

    }

}
<commit_msg>- removed unused check<commit_after>/*
 * Copyright (c) [2014-2015] Novell, Inc.
 * Copyright (c) 2016 SUSE LLC
 *
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of version 2 of the GNU General Public License as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, contact Novell, Inc.
 *
 * To contact Novell about this file by physical or electronic mail, you may
 * find current contact information at www.novell.com.
 */

#include "storage/Action.h"
#include "storage/DevicegraphImpl.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/Partition.h"

namespace storage
{

    namespace Action
    {

	Text
	Create::text(const Actiongraph::Impl& actiongraph, Tense tense) const
	{
	    return get_device_rhs(actiongraph)->get_impl().do_create_text(tense);
	}

	void
	Create::commit(const Actiongraph::Impl& actiongraph) const
	{
	    get_device_rhs(actiongraph)->get_impl().do_create();
	}

	Text
	Delete::text(const Actiongraph::Impl& actiongraph, Tense tense) const
	{
	    return get_device_lhs(actiongraph)->get_impl().do_delete_text(tense);
	}

	void
	Delete::commit(const Actiongraph::Impl& actiongraph) const
	{
	    get_device_lhs(actiongraph)->get_impl().do_delete();
	}

	void
	Create::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const
	{
	    Base::add_dependencies(v, actiongraph);

	    sid_t sid = actiongraph[v]->sid;

	    Devicegraph::Impl::vertex_descriptor v_in_rhs = actiongraph.get_devicegraph(RHS)->get_impl().find_vertex(sid);

	    // iterate parents
	    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;
	    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_rhs, actiongraph.get_devicegraph(RHS)->get_impl().graph); vi != vi_end; ++vi)
	    {
		sid_t parent_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();

		if (!actiongraph.get_devicegraph(LHS)->device_exists(parent_sid))
		{
		    // parents must be created beforehand if not existed

		    Actiongraph::Impl::vertex_descriptor tmp = actiongraph.actions_with_sid(parent_sid, ONLY_LAST).front();
		    actiongraph.add_edge(tmp, v);
		}
		else
		{
		    // children of parents must be deleted beforehand

		    Devicegraph::Impl::vertex_descriptor q = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(parent_sid);

		    Devicegraph::Impl::adjacency_iterator vi2, vi2_end;
		    for (boost::tie(vi2, vi2_end) = adjacent_vertices(q, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi2 != vi2_end; ++vi2)
		    {
			sid_t child_sid = actiongraph.get_devicegraph(LHS)->get_impl()[*vi2]->get_sid();

			vector<Actiongraph::Impl::vertex_descriptor> tmp = actiongraph.actions_with_sid(child_sid, ONLY_LAST);
			if (!tmp.empty())
			{
			    // Make sure it's a delete action
			    const Action::Base* tmp_action = actiongraph[tmp.front()];
			    if (dynamic_cast<const Action::Delete*>(tmp_action))
				actiongraph.add_edge(tmp.front(), v);
			}
		    }
		}
	    }

	}

	void
	Delete::add_dependencies(Actiongraph::Impl::vertex_descriptor v, Actiongraph::Impl& actiongraph) const
	{
	    Base::add_dependencies(v, actiongraph);

	    // all children must be deleted beforehand

	    sid_t sid = actiongraph[v]->sid;

	    Devicegraph::Impl::vertex_descriptor v_in_lhs = actiongraph.get_devicegraph(LHS)->get_impl().find_vertex(sid);

	    // iterate children
	    Devicegraph::Impl::inv_adjacency_iterator vi, vi_end;
	    for (boost::tie(vi, vi_end) = inv_adjacent_vertices(v_in_lhs, actiongraph.get_devicegraph(LHS)->get_impl().graph); vi != vi_end; ++vi)
	    {
		sid_t child_sid = actiongraph.get_devicegraph(RHS)->get_impl()[*vi]->get_sid();

		for (Actiongraph::Impl::vertex_descriptor tmp : actiongraph.actions_with_sid(child_sid, ONLY_FIRST))
		    actiongraph.add_edge(v, tmp);
	    }
	}

    }

}
<|endoftext|>


<commit_before>//
// Copyright (c) 2002-2010 The ANGLE 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.
//

// Config.cpp: Implements the egl::Config class, describing the format, type
// and size for an egl::Surface. Implements EGLConfig and related functionality.
// [EGL 1.5] section 3.4 page 19.

#include "libANGLE/Config.h"
#include "libANGLE/AttributeMap.h"

#include <algorithm>
#include <vector>

#include "angle_gl.h"
#include <EGL/eglext.h>

#include "common/debug.h"

namespace egl
{

Config::Config()
    : renderTargetFormat(GL_NONE),
      depthStencilFormat(GL_NONE),
      bufferSize(0),
      redSize(0),
      greenSize(0),
      blueSize(0),
      luminanceSize(0),
      alphaSize(0),
      alphaMaskSize(0),
      bindToTextureRGB(EGL_FALSE),
      bindToTextureRGBA(EGL_FALSE),
      colorBufferType(EGL_NONE),
      configCaveat(EGL_NONE),
      configID(0),
      conformant(0),
      depthSize(0),
      level(0),
      matchNativePixmap(EGL_FALSE),
      maxPBufferWidth(0),
      maxPBufferHeight(0),
      maxPBufferPixels(0),
      maxSwapInterval(0),
      minSwapInterval(0),
      nativeRenderable(EGL_FALSE),
      nativeVisualID(0),
      nativeVisualType(0),
      renderableType(0),
      sampleBuffers(0),
      samples(0),
      stencilSize(0),
      surfaceType(0),
      transparentType(EGL_NONE),
      transparentRedValue(0),
      transparentGreenValue(0),
      transparentBlueValue(0)
{
}

EGLint ConfigSet::add(const Config &config)
{
    // Set the config's ID to a small number that starts at 1 ([EGL 1.5] section 3.4)
    EGLint id = mConfigs.size() + 1;

    Config copyConfig(config);
    copyConfig.configID = id;
    mConfigs.insert(std::make_pair(id, copyConfig));

    return id;
}

const Config &ConfigSet::get(EGLint id) const
{
    return mConfigs.at(id);
}

void ConfigSet::clear()
{
    mConfigs.clear();
}

size_t ConfigSet::size() const
{
    return mConfigs.size();
}

bool ConfigSet::contains(const Config *config) const
{
    for (auto i = mConfigs.begin(); i != mConfigs.end(); i++)
    {
        const Config &item = i->second;
        if (config == &item)
        {
            return true;
        }
    }

    return false;
}

// Function object used by STL sorting routines for ordering Configs according to [EGL 1.5] section 3.4.1.2 page 28.
class ConfigSorter
{
  public:
    explicit ConfigSorter(const AttributeMap &attributeMap)
    {
        scanForWantedComponents(attributeMap);
    }

    bool operator()(const Config *x, const Config *y) const
    {
        return (*this)(*x, *y);
    }

    bool operator()(const Config &x, const Config &y) const
    {
        #define SORT(attribute)                        \
            if (x.attribute != y.attribute)            \
            {                                          \
                return x.attribute < y.attribute;      \
            }

        META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);
        SORT(configCaveat);

        META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);
        SORT(colorBufferType);

        // By larger total number of color bits, only considering those that are requested to be > 0.
        EGLint xComponentsSize = wantedComponentsSize(x);
        EGLint yComponentsSize = wantedComponentsSize(y);
        if (xComponentsSize != yComponentsSize)
        {
            return xComponentsSize > yComponentsSize;
        }

        SORT(bufferSize);
        SORT(sampleBuffers);
        SORT(samples);
        SORT(depthSize);
        SORT(stencilSize);
        SORT(alphaMaskSize);
        SORT(nativeVisualType);
        SORT(configID);

        #undef SORT

        return false;
    }

  private:
    void scanForWantedComponents(const AttributeMap &attributeMap)
    {
        // [EGL 1.5] section 3.4.1.2 page 30
        // Sorting rule #3: by larger total number of color bits, not considering
        // components that are 0 or don't-care.
        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)
        {
            EGLint attributeKey = attribIter->first;
            EGLint attributeValue = attribIter->second;
            if (attributeKey != 0 && attributeValue != EGL_DONT_CARE)
            {
                switch (attributeKey)
                {
                case EGL_RED_SIZE:       mWantRed = true; break;
                case EGL_GREEN_SIZE:     mWantGreen = true; break;
                case EGL_BLUE_SIZE:      mWantBlue = true; break;
                case EGL_ALPHA_SIZE:     mWantAlpha = true; break;
                case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;
                }
            }
        }
    }

    EGLint wantedComponentsSize(const Config &config) const
    {
        EGLint total = 0;

        if (mWantRed)       total += config.redSize;
        if (mWantGreen)     total += config.greenSize;
        if (mWantBlue)      total += config.blueSize;
        if (mWantAlpha)     total += config.alphaSize;
        if (mWantLuminance) total += config.luminanceSize;

        return total;
    }

    bool mWantRed;
    bool mWantGreen;
    bool mWantBlue;
    bool mWantAlpha;
    bool mWantLuminance;
};

std::vector<const Config*> ConfigSet::filter(const AttributeMap &attributeMap) const
{
    std::vector<const Config*> result;
    result.reserve(mConfigs.size());

    for (auto configIter = mConfigs.begin(); configIter != mConfigs.end(); configIter++)
    {
        const Config &config = configIter->second;
        bool match = true;

        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)
        {
            EGLint attributeKey = attribIter->first;
            EGLint attributeValue = attribIter->second;

            switch (attributeKey)
            {
              case EGL_BUFFER_SIZE:               match = config.bufferSize >= attributeValue;                        break;
              case EGL_ALPHA_SIZE:                match = config.alphaSize >= attributeValue;                         break;
              case EGL_BLUE_SIZE:                 match = config.blueSize >= attributeValue;                          break;
              case EGL_GREEN_SIZE:                match = config.greenSize >= attributeValue;                         break;
              case EGL_RED_SIZE:                  match = config.redSize >= attributeValue;                           break;
              case EGL_DEPTH_SIZE:                match = config.depthSize >= attributeValue;                         break;
              case EGL_STENCIL_SIZE:              match = config.stencilSize >= attributeValue;                       break;
              case EGL_CONFIG_CAVEAT:             match = config.configCaveat == (EGLenum)attributeValue;             break;
              case EGL_CONFIG_ID:                 match = config.configID == attributeValue;                          break;
              case EGL_LEVEL:                     match = config.level >= attributeValue;                             break;
              case EGL_NATIVE_RENDERABLE:         match = config.nativeRenderable == (EGLBoolean)attributeValue;      break;
              case EGL_NATIVE_VISUAL_TYPE:        match = config.nativeVisualType == attributeValue;                  break;
              case EGL_SAMPLES:                   match = config.samples >= attributeValue;                           break;
              case EGL_SAMPLE_BUFFERS:            match = config.sampleBuffers >= attributeValue;                     break;
              case EGL_SURFACE_TYPE:              match = (config.surfaceType & attributeValue) == attributeValue;    break;
              case EGL_TRANSPARENT_TYPE:          match = config.transparentType == (EGLenum)attributeValue;          break;
              case EGL_TRANSPARENT_BLUE_VALUE:    match = config.transparentBlueValue == attributeValue;              break;
              case EGL_TRANSPARENT_GREEN_VALUE:   match = config.transparentGreenValue == attributeValue;             break;
              case EGL_TRANSPARENT_RED_VALUE:     match = config.transparentRedValue == attributeValue;               break;
              case EGL_BIND_TO_TEXTURE_RGB:       match = config.bindToTextureRGB == (EGLBoolean)attributeValue;      break;
              case EGL_BIND_TO_TEXTURE_RGBA:      match = config.bindToTextureRGBA == (EGLBoolean)attributeValue;     break;
              case EGL_MIN_SWAP_INTERVAL:         match = config.minSwapInterval == attributeValue;                   break;
              case EGL_MAX_SWAP_INTERVAL:         match = config.maxSwapInterval == attributeValue;                   break;
              case EGL_LUMINANCE_SIZE:            match = config.luminanceSize >= attributeValue;                     break;
              case EGL_ALPHA_MASK_SIZE:           match = config.alphaMaskSize >= attributeValue;                     break;
              case EGL_COLOR_BUFFER_TYPE:         match = config.colorBufferType == (EGLenum)attributeValue;          break;
              case EGL_RENDERABLE_TYPE:           match = (config.renderableType & attributeValue) == attributeValue; break;
              case EGL_MATCH_NATIVE_PIXMAP:       match = false; UNIMPLEMENTED();                                     break;
              case EGL_CONFORMANT:                match = (config.conformant & attributeValue) == attributeValue;     break;
              case EGL_MAX_PBUFFER_WIDTH:         match = config.maxPBufferWidth >= attributeValue;                   break;
              case EGL_MAX_PBUFFER_HEIGHT:        match = config.maxPBufferHeight >= attributeValue;                  break;
              case EGL_MAX_PBUFFER_PIXELS:        match = config.maxPBufferPixels >= attributeValue;                  break;
              default: UNREACHABLE();
            }

            if (!match)
            {
                break;
            }
        }

        if (match)
        {
            result.push_back(&config);
        }
    }

    // Sort the result
    std::sort(result.begin(), result.end(), ConfigSorter(attributeMap));

    return result;
}

}
<commit_msg>Do not use std::set::at in Config.cpp.<commit_after>//
// Copyright (c) 2002-2010 The ANGLE 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.
//

// Config.cpp: Implements the egl::Config class, describing the format, type
// and size for an egl::Surface. Implements EGLConfig and related functionality.
// [EGL 1.5] section 3.4 page 19.

#include "libANGLE/Config.h"
#include "libANGLE/AttributeMap.h"

#include <algorithm>
#include <vector>

#include "angle_gl.h"
#include <EGL/eglext.h>

#include "common/debug.h"

namespace egl
{

Config::Config()
    : renderTargetFormat(GL_NONE),
      depthStencilFormat(GL_NONE),
      bufferSize(0),
      redSize(0),
      greenSize(0),
      blueSize(0),
      luminanceSize(0),
      alphaSize(0),
      alphaMaskSize(0),
      bindToTextureRGB(EGL_FALSE),
      bindToTextureRGBA(EGL_FALSE),
      colorBufferType(EGL_NONE),
      configCaveat(EGL_NONE),
      configID(0),
      conformant(0),
      depthSize(0),
      level(0),
      matchNativePixmap(EGL_FALSE),
      maxPBufferWidth(0),
      maxPBufferHeight(0),
      maxPBufferPixels(0),
      maxSwapInterval(0),
      minSwapInterval(0),
      nativeRenderable(EGL_FALSE),
      nativeVisualID(0),
      nativeVisualType(0),
      renderableType(0),
      sampleBuffers(0),
      samples(0),
      stencilSize(0),
      surfaceType(0),
      transparentType(EGL_NONE),
      transparentRedValue(0),
      transparentGreenValue(0),
      transparentBlueValue(0)
{
}

EGLint ConfigSet::add(const Config &config)
{
    // Set the config's ID to a small number that starts at 1 ([EGL 1.5] section 3.4)
    EGLint id = mConfigs.size() + 1;

    Config copyConfig(config);
    copyConfig.configID = id;
    mConfigs.insert(std::make_pair(id, copyConfig));

    return id;
}

const Config &ConfigSet::get(EGLint id) const
{
    ASSERT(mConfigs.find(id) != mConfigs.end());
    return mConfigs.find(id)->second;
}

void ConfigSet::clear()
{
    mConfigs.clear();
}

size_t ConfigSet::size() const
{
    return mConfigs.size();
}

bool ConfigSet::contains(const Config *config) const
{
    for (auto i = mConfigs.begin(); i != mConfigs.end(); i++)
    {
        const Config &item = i->second;
        if (config == &item)
        {
            return true;
        }
    }

    return false;
}

// Function object used by STL sorting routines for ordering Configs according to [EGL 1.5] section 3.4.1.2 page 28.
class ConfigSorter
{
  public:
    explicit ConfigSorter(const AttributeMap &attributeMap)
    {
        scanForWantedComponents(attributeMap);
    }

    bool operator()(const Config *x, const Config *y) const
    {
        return (*this)(*x, *y);
    }

    bool operator()(const Config &x, const Config &y) const
    {
        #define SORT(attribute)                        \
            if (x.attribute != y.attribute)            \
            {                                          \
                return x.attribute < y.attribute;      \
            }

        META_ASSERT(EGL_NONE < EGL_SLOW_CONFIG && EGL_SLOW_CONFIG < EGL_NON_CONFORMANT_CONFIG);
        SORT(configCaveat);

        META_ASSERT(EGL_RGB_BUFFER < EGL_LUMINANCE_BUFFER);
        SORT(colorBufferType);

        // By larger total number of color bits, only considering those that are requested to be > 0.
        EGLint xComponentsSize = wantedComponentsSize(x);
        EGLint yComponentsSize = wantedComponentsSize(y);
        if (xComponentsSize != yComponentsSize)
        {
            return xComponentsSize > yComponentsSize;
        }

        SORT(bufferSize);
        SORT(sampleBuffers);
        SORT(samples);
        SORT(depthSize);
        SORT(stencilSize);
        SORT(alphaMaskSize);
        SORT(nativeVisualType);
        SORT(configID);

        #undef SORT

        return false;
    }

  private:
    void scanForWantedComponents(const AttributeMap &attributeMap)
    {
        // [EGL 1.5] section 3.4.1.2 page 30
        // Sorting rule #3: by larger total number of color bits, not considering
        // components that are 0 or don't-care.
        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)
        {
            EGLint attributeKey = attribIter->first;
            EGLint attributeValue = attribIter->second;
            if (attributeKey != 0 && attributeValue != EGL_DONT_CARE)
            {
                switch (attributeKey)
                {
                case EGL_RED_SIZE:       mWantRed = true; break;
                case EGL_GREEN_SIZE:     mWantGreen = true; break;
                case EGL_BLUE_SIZE:      mWantBlue = true; break;
                case EGL_ALPHA_SIZE:     mWantAlpha = true; break;
                case EGL_LUMINANCE_SIZE: mWantLuminance = true; break;
                }
            }
        }
    }

    EGLint wantedComponentsSize(const Config &config) const
    {
        EGLint total = 0;

        if (mWantRed)       total += config.redSize;
        if (mWantGreen)     total += config.greenSize;
        if (mWantBlue)      total += config.blueSize;
        if (mWantAlpha)     total += config.alphaSize;
        if (mWantLuminance) total += config.luminanceSize;

        return total;
    }

    bool mWantRed;
    bool mWantGreen;
    bool mWantBlue;
    bool mWantAlpha;
    bool mWantLuminance;
};

std::vector<const Config*> ConfigSet::filter(const AttributeMap &attributeMap) const
{
    std::vector<const Config*> result;
    result.reserve(mConfigs.size());

    for (auto configIter = mConfigs.begin(); configIter != mConfigs.end(); configIter++)
    {
        const Config &config = configIter->second;
        bool match = true;

        for (auto attribIter = attributeMap.begin(); attribIter != attributeMap.end(); attribIter++)
        {
            EGLint attributeKey = attribIter->first;
            EGLint attributeValue = attribIter->second;

            switch (attributeKey)
            {
              case EGL_BUFFER_SIZE:               match = config.bufferSize >= attributeValue;                        break;
              case EGL_ALPHA_SIZE:                match = config.alphaSize >= attributeValue;                         break;
              case EGL_BLUE_SIZE:                 match = config.blueSize >= attributeValue;                          break;
              case EGL_GREEN_SIZE:                match = config.greenSize >= attributeValue;                         break;
              case EGL_RED_SIZE:                  match = config.redSize >= attributeValue;                           break;
              case EGL_DEPTH_SIZE:                match = config.depthSize >= attributeValue;                         break;
              case EGL_STENCIL_SIZE:              match = config.stencilSize >= attributeValue;                       break;
              case EGL_CONFIG_CAVEAT:             match = config.configCaveat == (EGLenum)attributeValue;             break;
              case EGL_CONFIG_ID:                 match = config.configID == attributeValue;                          break;
              case EGL_LEVEL:                     match = config.level >= attributeValue;                             break;
              case EGL_NATIVE_RENDERABLE:         match = config.nativeRenderable == (EGLBoolean)attributeValue;      break;
              case EGL_NATIVE_VISUAL_TYPE:        match = config.nativeVisualType == attributeValue;                  break;
              case EGL_SAMPLES:                   match = config.samples >= attributeValue;                           break;
              case EGL_SAMPLE_BUFFERS:            match = config.sampleBuffers >= attributeValue;                     break;
              case EGL_SURFACE_TYPE:              match = (config.surfaceType & attributeValue) == attributeValue;    break;
              case EGL_TRANSPARENT_TYPE:          match = config.transparentType == (EGLenum)attributeValue;          break;
              case EGL_TRANSPARENT_BLUE_VALUE:    match = config.transparentBlueValue == attributeValue;              break;
              case EGL_TRANSPARENT_GREEN_VALUE:   match = config.transparentGreenValue == attributeValue;             break;
              case EGL_TRANSPARENT_RED_VALUE:     match = config.transparentRedValue == attributeValue;               break;
              case EGL_BIND_TO_TEXTURE_RGB:       match = config.bindToTextureRGB == (EGLBoolean)attributeValue;      break;
              case EGL_BIND_TO_TEXTURE_RGBA:      match = config.bindToTextureRGBA == (EGLBoolean)attributeValue;     break;
              case EGL_MIN_SWAP_INTERVAL:         match = config.minSwapInterval == attributeValue;                   break;
              case EGL_MAX_SWAP_INTERVAL:         match = config.maxSwapInterval == attributeValue;                   break;
              case EGL_LUMINANCE_SIZE:            match = config.luminanceSize >= attributeValue;                     break;
              case EGL_ALPHA_MASK_SIZE:           match = config.alphaMaskSize >= attributeValue;                     break;
              case EGL_COLOR_BUFFER_TYPE:         match = config.colorBufferType == (EGLenum)attributeValue;          break;
              case EGL_RENDERABLE_TYPE:           match = (config.renderableType & attributeValue) == attributeValue; break;
              case EGL_MATCH_NATIVE_PIXMAP:       match = false; UNIMPLEMENTED();                                     break;
              case EGL_CONFORMANT:                match = (config.conformant & attributeValue) == attributeValue;     break;
              case EGL_MAX_PBUFFER_WIDTH:         match = config.maxPBufferWidth >= attributeValue;                   break;
              case EGL_MAX_PBUFFER_HEIGHT:        match = config.maxPBufferHeight >= attributeValue;                  break;
              case EGL_MAX_PBUFFER_PIXELS:        match = config.maxPBufferPixels >= attributeValue;                  break;
              default: UNREACHABLE();
            }

            if (!match)
            {
                break;
            }
        }

        if (match)
        {
            result.push_back(&config);
        }
    }

    // Sort the result
    std::sort(result.begin(), result.end(), ConfigSorter(attributeMap));

    return result;
}

}
<|endoftext|>


<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include<string>
#include<sstream>

#include"ork/command_Line.hpp"

namespace ork {

int invoke_main(const std::vector<string>&args, main_func f) {
	std::vector<const char_t*>argv;
	argv.push_back(ORK("this_should_be_the_invoked_command"));
	for(const string&arg : args)argv.push_back(arg.c_str());

	string_stream cmd;
	for(const char_t*const arg : argv) {
		cmd << arg << ORK(" ");
	}
	ORK_LOG(severity_level::info) << ORK("\n -- Command Line: ") << cmd.str();

	return f(static_cast<int>(argv.size()), argv.data());
}

command_handler::command_handler()
	: _desc_str()//Initialized by call_add_options
	, _desc(BORK("Standard Options"))
	, _vm() {}

void command_handler::call_add_options() {
	_desc.add_options()
		(BORK("help,h"), BORK("Produce help message"));//Short option aliases do not work until notify, so we can't use them for help
	add_options(_desc);

	b_string_stream desc_byte;
	desc_byte << _desc;//string operation only defined for std::ostream
	_desc_str = ORK_BYTE_2_STR(desc_byte.str());
}

bool command_handler::process_commands(const options::basic_parsed_options<char_t>&ops) {
	try {
		options::store(ops, _vm);
		if(_vm.count(BORK("help"))) {//Check here to ignore any missing options
			ORK_LOG(severity_level::info) << ORK('\n') << _desc_str << ORK('\n');
			return false;
		}
		options::notify(_vm);//Exceptions for missing required options raised here

		string_stream options;
		options << ORK("\n -- Command Line Options:");
		for(auto&option : _desc.options()) {
			const bstring option_name = option->long_name();
			string option_value = ORK("Unspecified");
			if(_vm.count(option_name)) {
				extract_option_value(option_name, option_value);
			}
			options << ORK("\n  - ") << ORK_BYTE_2_STR(option_name) << ORK(": ") << option_value;
		}
		ORK_LOG(severity_level::info) << options.str();
	}
	catch(options::error &e) {
		ORK_LOG(severity_level::error) << ORK("\nProblem storing command line options:\n  - ") << ORK_BYTE_2_STR(e.what());
		ORK_LOG(severity_level::error) << ORK('\n') << _desc_str << ORK('\n');
		return false;
	}

	return true;
}

#define COMMAND_CATCH \
	catch(options::error &e) {\
		ORK_LOG(severity_level::error) << ORK("\nProblem parsing command line options:\n  - ") << ORK_BYTE_2_STR(e.what());\
		ORK_LOG(severity_level::error) << ORK('\n') << _desc_str << ORK('\n');\
		return false;\
	}

bool command_handler::operator()(const int argc, const char_t*const argv[]) {
	try {
		call_add_options();
		options::basic_parsed_options<char_t>ops(options::parse_command_line<char_t>(argc, argv, _desc));
		return process_commands(ops);
	}
	COMMAND_CATCH
}

bool command_handler::operator()(const int argc, const char_t*const argv[], const bstring&positional_op) {
	try {
		call_add_options();
		options::positional_options_description p;
		p.add(positional_op.c_str(), -1);
		options::basic_parsed_options<char_t>ops(options::command_line_parser(argc, argv).options(_desc).positional(p).run());
		return process_commands(ops);
	}
	COMMAND_CATCH
}

bool command_handler::operator()(const bstring&env_prefix) {
	try {
		call_add_options();
		options::basic_parsed_options<char_t>ops(options::parse_environment(_desc, env_prefix));
		return process_commands(ops);
	}
	COMMAND_CATCH
}

bool command_handler::operator()(std::istream&config_file) {
	try {
		call_add_options();
		options::basic_parsed_options<char_t>ops(options::parse_config_file(config_file, _desc));
		return process_commands(ops);
	}
	COMMAND_CATCH
}

}//namespace ork
<commit_msg>Added a typedef for command parser<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#include<string>
#include<sstream>

#include"ork/command_Line.hpp"

namespace ork {

int invoke_main(const std::vector<string>&args, main_func f) {
	std::vector<const char_t*>argv;
	argv.push_back(ORK("this_should_be_the_invoked_command"));
	for(const string&arg : args)argv.push_back(arg.c_str());

	string_stream cmd;
	for(const char_t*const arg : argv) {
		cmd << arg << ORK(" ");
	}
	ORK_LOG(severity_level::info) << ORK("\n -- Command Line: ") << cmd.str();

	return f(static_cast<int>(argv.size()), argv.data());
}

command_handler::command_handler()
	: _desc_str()//Initialized by call_add_options
	, _desc(BORK("Standard Options"))
	, _vm() {}

void command_handler::call_add_options() {
	_desc.add_options()
		(BORK("help,h"), BORK("Produce help message"));//Short option aliases do not work until notify, so we can't use them for help
	add_options(_desc);

	b_string_stream desc_byte;
	desc_byte << _desc;//string operation only defined for std::ostream
	_desc_str = ORK_BYTE_2_STR(desc_byte.str());
}

bool command_handler::process_commands(const options::basic_parsed_options<char_t>&ops) {
	try {
		options::store(ops, _vm);
		if(_vm.count(BORK("help"))) {//Check here to ignore any missing options
			ORK_LOG(severity_level::info) << ORK('\n') << _desc_str << ORK('\n');
			return false;
		}
		options::notify(_vm);//Exceptions for missing required options raised here

		string_stream options;
		options << ORK("\n -- Command Line Options:");
		for(auto&option : _desc.options()) {
			const bstring option_name = option->long_name();
			string option_value = ORK("Unspecified");
			if(_vm.count(option_name)) {
				extract_option_value(option_name, option_value);
			}
			options << ORK("\n  - ") << ORK_BYTE_2_STR(option_name) << ORK(": ") << option_value;
		}
		ORK_LOG(severity_level::info) << options.str();
	}
	catch(options::error &e) {
		ORK_LOG(severity_level::error) << ORK("\nProblem storing command line options:\n  - ") << ORK_BYTE_2_STR(e.what());
		ORK_LOG(severity_level::error) << ORK('\n') << _desc_str << ORK('\n');
		return false;
	}

	return true;
}

#define COMMAND_CATCH \
	catch(options::error &e) {\
		ORK_LOG(severity_level::error) << ORK("\nProblem parsing command line options:\n  - ") << ORK_BYTE_2_STR(e.what());\
		ORK_LOG(severity_level::error) << ORK('\n') << _desc_str << ORK('\n');\
		return false;\
	}

bool command_handler::operator()(const int argc, const char_t*const argv[]) {
	try {
		call_add_options();
		options::basic_parsed_options<char_t>ops(options::parse_command_line<char_t>(argc, argv, _desc));
		return process_commands(ops);
	}
	COMMAND_CATCH
}

#if ORK_UNICODE
using command_line_parser = options::basic_command_line_parser<wchar_t>;
#else
using command_line_parser = options::basic_command_line_parser<char>;
#endif

bool command_handler::operator()(const int argc, const char_t*const argv[], const bstring&positional_op) {
	try {
		call_add_options();
		options::positional_options_description p;
		p.add(positional_op.c_str(), -1);
		options::basic_parsed_options<char_t>ops(command_line_parser(argc, argv).options(_desc).positional(p).run());
		return process_commands(ops);
	}
	COMMAND_CATCH
}

bool command_handler::operator()(const bstring&env_prefix) {
	try {
		call_add_options();
		options::basic_parsed_options<char_t>ops(options::parse_environment(_desc, env_prefix));
		return process_commands(ops);
	}
	COMMAND_CATCH
}

bool command_handler::operator()(std::istream&config_file) {
	try {
		call_add_options();
		options::basic_parsed_options<char_t>ops(options::parse_config_file(config_file, _desc));
		return process_commands(ops);
	}
	COMMAND_CATCH
}

}//namespace ork
<|endoftext|>


<commit_before><commit_msg>test: add smoke-crud-onerow.<commit_after><|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_vas_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_vas_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0x00DD0201C0000000 = 0x00DD0201C0000000;
constexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000;
constexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000;
constexpr uint64_t literal_0x1 = 0x1;
constexpr uint64_t literal_0xFC = 0xFC;

fapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, TGT0, l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700));
        fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID));
        fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID));
        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer ));

            if ((l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700 != literal_0))
            {
                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DD0201C0000000 );
            }
            else if (( true ))
            {
                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer ));

                l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer ));

                l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer ));

                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer ));

                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer));
            }
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer ));

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
            {
                l_scom_buffer.insert<0, 4, 60, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID );
                l_scom_buffer.insert<4, 3, 61, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer ));

            constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;
            l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF );

            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))
            {
                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1;
                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))
            {
                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0;
                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF );
            }

            l_scom_buffer.insert<20, 8, 56, uint64_t>(literal_0xFC );
            l_scom_buffer.insert<28, 8, 56, uint64_t>(literal_0xFC );
            FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer ));

                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer));
            }
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Adding p9a support.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_vas_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_vas_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0x00200102000D7FFF = 0x00200102000D7FFF;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0 = 0;
constexpr uint64_t literal_0x00DD0201C0000000 = 0x00DD0201C0000000;
constexpr uint64_t literal_0x00DF0201C0000000 = 0x00DF0201C0000000;
constexpr uint64_t literal_0x0080000000000000 = 0x0080000000000000;
constexpr uint64_t literal_0x1 = 0x1;
constexpr uint64_t literal_0xFC = 0xFC;

fapi2::ReturnCode p9_vas_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0,
                              const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::ATTR_CHIP_EC_FEATURE_HW414700_Type l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW414700, TGT0, l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700));
        fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID));
        fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID_Type l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID, TGT1, l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID));
        fapi2::ATTR_PROC_FABRIC_PUMP_MODE_Type l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_PROC_FABRIC_PUMP_MODE, TGT1, l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x3011803ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00200102000D7FFF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x3011803ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x3011806ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x3011806ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x3011807ull, l_scom_buffer ));

            if ((l_TGT0_ATTR_CHIP_EC_FEATURE_HW414700 != literal_0))
            {
                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DD0201C0000000 );
            }
            else if (( true ))
            {
                l_scom_buffer.insert<0, 54, 0, uint64_t>(literal_0x00DF0201C0000000 );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x3011807ull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180aull, l_scom_buffer ));

                l_scom_buffer.insert<8, 31, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180aull, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180bull, l_scom_buffer ));

                l_scom_buffer.insert<8, 28, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180bull, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180eull, l_scom_buffer ));

                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180eull, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301180full, l_scom_buffer ));

                l_scom_buffer.insert<8, 44, 8, uint64_t>(literal_0x0080000000000000 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301180full, l_scom_buffer));
            }
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10))
                || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301184dull, l_scom_buffer ));

                if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                        && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
                {
                    l_scom_buffer.insert<0, 4, 60, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_GROUP_ID );
                    l_scom_buffer.insert<4, 3, 61, uint64_t>(l_TGT1_ATTR_FABRIC_ADDR_EXTENSION_CHIP_ID );
                }

                if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
                {
                    l_scom_buffer.insert<19, 1, 63, uint64_t>(literal_0x1 );
                }

                FAPI_TRY(fapi2::putScom(TGT0, 0x301184dull, l_scom_buffer));
            }
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x301184eull, l_scom_buffer ));

            constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF = 0x0;
            l_scom_buffer.insert<13, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_ADDR_BAR_MODE_OFF );

            if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_GROUP))
            {
                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON = 0x1;
                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_ON );
            }
            else if ((l_TGT1_ATTR_PROC_FABRIC_PUMP_MODE == fapi2::ENUM_ATTR_PROC_FABRIC_PUMP_MODE_CHIP_IS_NODE))
            {
                constexpr auto l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF = 0x0;
                l_scom_buffer.insert<14, 1, 63, uint64_t>(l_VA_VA_SOUTH_VA_EG_EG_SCF_SKIP_G_OFF );
            }

            l_scom_buffer.insert<20, 8, 56, uint64_t>(literal_0xFC );
            l_scom_buffer.insert<28, 8, 56, uint64_t>(literal_0xFC );
            FAPI_TRY(fapi2::putScom(TGT0, 0x301184eull, l_scom_buffer));
        }
        {
            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x20)) )
            {
                FAPI_TRY(fapi2::getScom( TGT0, 0x301184full, l_scom_buffer ));

                l_scom_buffer.insert<0, 1, 63, uint64_t>(literal_0x1 );
                FAPI_TRY(fapi2::putScom(TGT0, 0x301184full, l_scom_buffer));
            }
        }

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


<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "kernel/expr.h"

namespace lean {
bool is_lt(expr const & a, expr const & b, bool use_hash) {
    if (is_eqp(a, b))                    return false;
    if (!a && b)                         return true;  // the null expression is the smallest one
    if (a && !b)                         return false;
    if (a.kind() != b.kind())            return a.kind() < b.kind();
    if (use_hash && a.hash() < b.hash()) return true;
    if (a == b)                          return false;
    if (is_var(a))                       return var_idx(a) < var_idx(b);
    switch (a.kind()) {
    case expr_kind::Var:
        lean_unreachable(); // LCOV_EXCL_LINE
    case expr_kind::Constant:
        return const_name(a) < const_name(b);
    case expr_kind::App:
        if (num_args(a) != num_args(b))
            return num_args(a) < num_args(b);
        for (unsigned i = 0; i < num_args(a); i++) {
            if (arg(a, i) != arg(b, i))
                return is_lt(arg(a, i), arg(b, i), use_hash);
        }
        lean_unreachable(); // LCOV_EXCL_LINE
    case expr_kind::Eq:
        if (eq_lhs(a) != eq_lhs(b))
            return is_lt(eq_lhs(a), eq_lhs(b), use_hash);
        else
            return is_lt(eq_rhs(a), eq_rhs(b), use_hash);
    case expr_kind::Lambda:   // Remark: we ignore get_abs_name because we want alpha-equivalence
    case expr_kind::Pi:
        if (abst_domain(a) != abst_domain(b))
            return is_lt(abst_domain(a), abst_domain(b), use_hash);
        else
            return is_lt(abst_body(a), abst_body(b), use_hash);
    case expr_kind::Type:
        return ty_level(a) < ty_level(b);
    case expr_kind::Value:
        return to_value(a) < to_value(b);
    case expr_kind::Let:
        if (let_type(a) != let_type(b)) {
            return is_lt(let_type(a), let_type(b), use_hash);
        } else if (let_value(a) != let_value(b)){
            return is_lt(let_value(a), let_value(b), use_hash);
        } else {
            return is_lt(let_body(a), let_body(b), use_hash);
        }
    case expr_kind::MetaVar:
        if (metavar_name(a) != metavar_name(b)) {
            return metavar_name(a) < metavar_name(b);
        } else {
            auto it1  = metavar_lctx(a).begin();
            auto it2  = metavar_lctx(b).begin();
            auto end1 = metavar_lctx(a).end();
            auto end2 = metavar_lctx(b).end();
            for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
                if (it1->kind() != it2->kind()) {
                    return it1->kind() < it2->kind();
                } else if (it1->s() != it2->s()) {
                    return it1->s() < it2->s();
                } else if (it1->is_inst()) {
                    if (it1->v() != it2->v())
                        return is_lt(it1->v(), it2->v(), use_hash);
                } else {
                    if (it1->n() != it2->n())
                        return it1->n() < it2->n();
                }
            }
            return it1 == end1 && it2 != end2;
        }
    }
    lean_unreachable(); // LCOV_EXCL_LINE
}
}
<commit_msg>fix(library/expr_lt): fix bug when using hash codes<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include "kernel/expr.h"

namespace lean {
bool is_lt(expr const & a, expr const & b, bool use_hash) {
    if (is_eqp(a, b))                    return false;
    if (!a && b)                         return true;  // the null expression is the smallest one
    if (a && !b)                         return false;
    if (a.kind() != b.kind())            return a.kind() < b.kind();
    if (use_hash) {
        if (a.hash() < b.hash()) return true;
        if (a.hash() > b.hash()) return false;
    }
    if (a == b)                          return false;
    if (is_var(a))                       return var_idx(a) < var_idx(b);
    switch (a.kind()) {
    case expr_kind::Var:
        lean_unreachable(); // LCOV_EXCL_LINE
    case expr_kind::Constant:
        return const_name(a) < const_name(b);
    case expr_kind::App:
        if (num_args(a) != num_args(b))
            return num_args(a) < num_args(b);
        for (unsigned i = 0; i < num_args(a); i++) {
            if (arg(a, i) != arg(b, i))
                return is_lt(arg(a, i), arg(b, i), use_hash);
        }
        lean_unreachable(); // LCOV_EXCL_LINE
    case expr_kind::Eq:
        if (eq_lhs(a) != eq_lhs(b))
            return is_lt(eq_lhs(a), eq_lhs(b), use_hash);
        else
            return is_lt(eq_rhs(a), eq_rhs(b), use_hash);
    case expr_kind::Lambda:   // Remark: we ignore get_abs_name because we want alpha-equivalence
    case expr_kind::Pi:
        if (abst_domain(a) != abst_domain(b))
            return is_lt(abst_domain(a), abst_domain(b), use_hash);
        else
            return is_lt(abst_body(a), abst_body(b), use_hash);
    case expr_kind::Type:
        return ty_level(a) < ty_level(b);
    case expr_kind::Value:
        return to_value(a) < to_value(b);
    case expr_kind::Let:
        if (let_type(a) != let_type(b)) {
            return is_lt(let_type(a), let_type(b), use_hash);
        } else if (let_value(a) != let_value(b)){
            return is_lt(let_value(a), let_value(b), use_hash);
        } else {
            return is_lt(let_body(a), let_body(b), use_hash);
        }
    case expr_kind::MetaVar:
        if (metavar_name(a) != metavar_name(b)) {
            return metavar_name(a) < metavar_name(b);
        } else {
            auto it1  = metavar_lctx(a).begin();
            auto it2  = metavar_lctx(b).begin();
            auto end1 = metavar_lctx(a).end();
            auto end2 = metavar_lctx(b).end();
            for (; it1 != end1 && it2 != end2; ++it1, ++it2) {
                if (it1->kind() != it2->kind()) {
                    return it1->kind() < it2->kind();
                } else if (it1->s() != it2->s()) {
                    return it1->s() < it2->s();
                } else if (it1->is_inst()) {
                    if (it1->v() != it2->v())
                        return is_lt(it1->v(), it2->v(), use_hash);
                } else {
                    if (it1->n() != it2->n())
                        return it1->n() < it2->n();
                }
            }
            return it1 == end1 && it2 != end2;
        }
    }
    lean_unreachable(); // LCOV_EXCL_LINE
}
}
<|endoftext|>