<commit_before>/* Copyright (C) 2016, Szilard Ledan <szledan@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "test.h"

#include "arg-parse.h"
#include <iostream>

// Configure and run tests.

int main(int argc, char* argv[])
{
    argparse::ArgParse args;

    {
        // Define options.
        args.def(argparse::Flag("--api", "-a", "Select api tests."));
        args.def(argparse::Flag("--manual", "-m", "Select manual tests.",
                                argparse::Value("program.name=show-help,help.add=true,tab=\t,mode.strict=true,help.compact=on,help.show=2", "options")));
        args.def(argparse::Flag("--unit", "-u", "Select unit tests."));
        args.def(argparse::Flag("--silent", "-s", "Fails show only."));

        // Parse argv and argc and check errors.
        if (!args.parse(argc, argv)) {
            std::cout << args.error() << std::endl;
            std::cout << args.help() << std::endl;
            return 1;
        }

        // Check help flags.
        if (args["--help"].isSet) {
            std::cout << args.help() << std::endl;
            return 0;
        }
    }

    // Collect running options.
    const bool none = !(args["-a"].isSet || args["-m"].isSet || args["-u"].isSet);
    const bool all = args["--all"].isSet || none;

    testargparse::TestContext ctx(!args["--silent"].isSet);

    // Run manual tests.
    if (args["--manual"].isSet || all) {
        ctx.param.str = args["--manual"].value.str;
        testargparse::manualTests(&ctx);
    }

    // Collect api tests.
    if (args["--api"].isSet || all) {
        testargparse::apiTests(&ctx);
    }

    // Collect unit and behavior tests.
    if (args["--unit"].isSet || all) {
        testargparse::unitAndBehaviorTests(&ctx);
    }

    // Run collected tests.
    int ret = ctx.run();

    return ret;
}
<commit_msg>Improve test suite<commit_after>/* Copyright (C) 2016, Szilard Ledan <szledan@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "test.h"

#include "arg-parse.h"
#include <iostream>

// Configure and run tests.

int main(int argc, char* argv[])
{
    struct {
        const bool nonSpecified() const { return !api && !unit && ! manual; }
        bool all = false;
        bool api = false;
        bool silent = false;
        bool unit = false;
        bool manual = false;
        std::string manualValue = "";
    } options;

    // Parse arguments.
    {
        using namespace argparse;
        ArgParse args;

        // Define options.
        args.def(Flag("--api", "-a", "Select api tests."));
        Value helpTestConfigs = Value("program.name=show-help,help.add=true,tab=\t,mode.strict=true,help.compact=on,help.show=2" /*!< Default value.*/,
                                      "options" /*!< Name of value.*/,
                                      "This value is interlaced, see more: ArgParse Api Reference." /*!< Description of value.*/);
        args.def(Flag("--manual", "-m", "Select manual tests.", helpTestConfigs));
        args.def(Flag("--unit", "-u", "Select unit tests."));
        args.def(Flag("--silent", "-s", "Fails show only."));

        // Parse argv and argc and check errors.
        if (!args.parse(argc, argv)) {
            std::cout << args.error() << std::endl;
            std::cout << args.help() << std::endl;
            return 1;
        }

        // Check help flags.
        if (args["--help"].isSet) {
            std::cout << args.help() << std::endl;
            return 0;
        }

        // Collect options.
        options.all = args["--all"].isSet;
        options.api = args["--api"].isSet;
        options.silent = args["--silent"].isSet;
        options.unit = args["--unit"].isSet;
        if ((options.manual = args["--manual"].isSet))
            options.manualValue = args["--manual"].value.str;
    }

    // Create test context.
    testargparse::TestContext ctx(!options.silent);

    const bool all = options.all || options.nonSpecified();

    // Run manual tests.
    if (options.manual || all) {
        ctx.param.str = options.manualValue;
        testargparse::manualTests(&ctx);
    }

    // Collect api tests.
    if (options.api || all) {
        testargparse::apiTests(&ctx);
    }

    // Collect unit and behavior tests.
    if (options.unit || all) {
        testargparse::unitAndBehaviorTests(&ctx);
    }

    // Run collected tests.
    int ret = ctx.run();

    return ret;
}
<|endoftext|>


<commit_before>// testLog4CPP.cpp : Derived from testCategory.cpp
//
#include "log4cpp/Portability.hh"
#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif

#include "log4cpp/Category.hh"
#include "log4cpp/Appender.hh"
#include "log4cpp/OstreamAppender.hh"
#include "log4cpp/FileAppender.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/BasicLayout.hh"
#include "log4cpp/Priority.hh"
#include "log4cpp/NDC.hh"
#include "log4cpp/PatternLayout.hh"

void test(std::string pattern, log4cpp::PatternLayout* layout, log4cpp::Category& cat)
{
	if (! layout->setConversionPattern(pattern)) {
		std::cout << "bad pattern: \"" << pattern << '\"' << std::endl;
    }
    cat.error("message");
}

int main(int argc, char* argv[])
{
    log4cpp::Appender* appender =
        new log4cpp::OstreamAppender("default", &std::cout);

    log4cpp::PatternLayout* layout = new log4cpp::PatternLayout();
    appender->setLayout(layout);

    log4cpp::Category& root = log4cpp::Category::getRoot();
    root.removeAllAppenders();
    root.addAppender(appender);
       root.setPriority(log4cpp::Priority::ERROR);
    std::string pattern;

    test("%% %r %c:%d (%R / %r) [%p] %x %m %% (%u) %n", layout, root);

    // test date format
    test("%d{%d %b %Y %H:%M:%S.%l} %m %n", layout, root);
    test("%d{%d %b %Y %H:%M:%S.%l", layout, root);
    test("%d", layout, root);

    test("%m %d%n", layout, root);
    int i;
    for (i = 0; i < 1000; i++) {
        root.error("%d message", i);
    }
    test("%m %d{%d %b %Y %H:%M:%S.%l}%n", layout, root);
    for (i = 0; i < 1000; i++) {
        root.error("%d message", i);
    }

    log4cpp::Category::shutdown();

    return 0;
}

<commit_msg> added tests for format specifiers and more.<commit_after>// testLog4CPP.cpp : Derived from testCategory.cpp
//
#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/NDC.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/BasicConfigurator.hh>

void test(std::string pattern, log4cpp::PatternLayout* layout, log4cpp::Category& cat)
{
    try {
        layout->setConversionPattern(pattern);
        cat.error("message");
    } catch(log4cpp::ConfigureFailure& f) {
        std::cerr << "configure failure: " << f.what() << std::endl;
    }
}

int main(int argc, char* argv[])
{
    log4cpp::BasicConfigurator::configure();
    log4cpp::PatternLayout* layout = new log4cpp::PatternLayout();
    log4cpp::Category::getRoot().getAppender()->setLayout(layout);

    log4cpp::Category& cat = log4cpp::Category::getInstance("cat1");

    log4cpp::NDC::push("ndc1");

    test("%% %r %c:%d (%R / %r) [%p] %x %m %% (%u) %n", layout, cat);

    // test format specifiers
    test(">%10m<%n", layout, cat);
    test(">%-10m<%n", layout, cat);
    test(">%3.5m<%n", layout, cat);
    test(">%.5m<%n", layout, cat);

    // category test
    test(">%c{2}<%n", layout, log4cpp::Category::getInstance("c1.c2.c3.c4"));

    // test date format
    test("%d{%d %b %Y %H:%M:%S.%l} %m %n", layout, cat);
    test("%d{%d %b %Y %H:%M:%S.%l", layout, cat);
    test("%d%n", layout, cat);

    test("%m %d%n", layout, cat);
    int i;
    for (i = 0; i < 10; i++) {
        cat.error("%d message", i);
    }
    test("%m %d{%H:%M:%S.%l %d %b %Y}%n", layout, cat);
    for (i = 0; i < 10; i++) {
        cat.error("%d message", i);
    }

    log4cpp::Category::shutdown();

    return 0;
}

<|endoftext|>


<commit_before>//
//  main2.cpp
//  test_SCUD
//
//  Created by Boris Vigman on 08/07/2017.
//  Copyright © 2017-2019 Boris Vigman. All rights reserved.
//

#include "scud.h"
using namespace SCUD;

#include <iostream>
#include <thread>
#include <chrono>
#include "vector"

template<typename TSchedulable,typename Tid> class Queue1:public LinkableQueue<int,void*>{

};
template<typename TSchedulable,typename Tid> class Dropper1:public LinkableDropper<int,void*>{
public:

    void processOnPush(TSchedulable sch, long long schedulingParam){
        int x=0;
    }
    void processOnPull(TSchedulable sch, long long schedulingParam){
        int x=0;
    }
    void processOnPullPush(TSchedulable sch, long long schedulingParam){
        int x=0;
    }
};
class Source{
    char priority;
    float weight;
    int label;
    long long delay;
    Queue1<int,void*> queue0;
    LinkableQueue<int,void*> queue1;
    Dropper1<int,void*> drop0;
    LinkableDropper<int,void*> drop1;
    LinkablePass<int, void*> pass1,pass2;
    //LinkablePass<int,void*> pass;
    void run(){
        SCUD_RC r0;
        drop1.unlink(&r0);
        drop0.setPriority(7);
        drop1.setPriority(priority);
        SCUD_RC rc= queue0.setPriority(priority);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue0.setWeight(weight);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue0.setLowThreshold(1);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue0.setHighThreshold(20);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue1.setDRRQuantum(0);
        rc=queue1.setDRRQuantum(50);
        rc=queue1.setWeight(5);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue1.setLowThreshold(1);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue1.setHighThreshold(30);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc= queue1.setPriority(priority);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        int count=10;

        //while(count>0){
        SCUD_RC status=SCUD_RC_OK;
        //queue.unlink(&status);
        //std::cout<<"loop: source"<<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        queue1.linkSuccessor(&drop1);
        queue0.linkSuccessor(&drop0);

        drop0.linkSuccessor(&queue0);
        //status=next->linkPredecessor(&drop1);

        //}
        while(1){
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));

            //buildCompound();
            auto start= std::chrono::high_resolution_clock::now() ;
            drop0.push(label, label*10);
            auto end= std::chrono::high_resolution_clock::now() ;
            auto diff = end - start;
            //std::cout<<"Push delay="<<std::chrono::duration <double, std::micro>(diff).count()<<std::endl;
            //std::cout<<"Queue1 ["<<label<<"] has "<<queue1.size()<<" objects"<<std::endl;
             start= std::chrono::high_resolution_clock::now() ;
            pass1.pullAndPush();
             end= std::chrono::high_resolution_clock::now() ;
             diff = end - start;
            //std::cout<<"Pull/Push delay="<<std::chrono::duration <double, std::micro>(diff).count()<<std::endl;
            //std::cout<<"Queue0 ["<<label<<"] has "<<queue0.size()<<" objects;"<<"Queue1 ["<<label<<"] has "<<queue1.size()<<" objects"<<std::endl;
            //breakCompound();
            /*
            count--;
            if(count<0){
                count=100;
                std::this_thread::sleep_for(std::chrono::milliseconds(delay*100));
            }
             */
        }
    }
public:
    Source(){weight=-1;priority=-1;label=-1;delay=100;}
    Source(int lbl, char p,float w,long long delayMilli){
        priority=p;
        weight=w;
        label=lbl;
        delay=delayMilli;
    }
    std::thread start() {
        return std::thread([=] { run(); });
    }
    void buildCompound(){
        drop0.linkSuccessor(&queue0);
        queue0.linkSuccessor(&pass1);
        pass1.linkSuccessor(&queue1);
        queue1.linkSuccessor(&pass2);
        pass2.linkSuccessor(&drop1);

    }
    void breakCompound(){
        SCUD_RC status=SCUD_RC_OK;
        Linkable<int,void*>::LinkedObjectsTuple lot1=drop1.unlink(&status);
        if(status!=SCUD_RC_OK){
            std::cout<<SCHelper::convertReturnCodeToString(status)<<std::endl;
        }
        Linkable<int,void*>::LinkedObjectsTuple lot2=queue0.unlink(&status);
        if(status!=SCUD_RC_OK){
            std::cout<<SCHelper::convertReturnCodeToString(status)<<std::endl;
        }
        Linkable<int,void*>::LinkedObjectsTuple lot3=queue1.unlink(&status);
        if(status!=SCUD_RC_OK){
            std::cout<<SCHelper::convertReturnCodeToString(status)<<std::endl;
        }
    }
    Linkable<int,void*>* compoundBegin(){
        return &drop0;
    }
    Linkable<int,void*>* compoundEnd(){
        return &drop1;
    }
};

class Sink{
    //LinkableSchedulerPriority<int, void*> scheduler;
    //LinkableSchedulerNaiveRR<int, void*> scheduler;
    LinkableSchedulerDRR<int, void*> scheduler;
    LinkableNull<int, void*> null;
    void run(){
        scheduler.setPriority(9);
        scheduler.setWeight(1);

//        while(1){
//            //std::cout<<"loop: sink"<<std::endl;
//            std::this_thread::sleep_for(std::chrono::milliseconds(100));
//            SCUD_RC rc=SCUD_RC_OK;
//            struct Linkable<int,void*>::Queueable res;
////            rc=next->pull(res);
////            if(rc==SCUD_RC_OK){
////                std::cout<<"Sink: Pulled object "<<res.scheduled<<" "<<std::endl;
////            }else{
////                std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
////            }
////            if(res.scheduled>100000){
////                int x=0;
////            }
//        }
    }
public:
    Sink(Linkable<int, void*>* l){

    }
    std::thread start() {
        return std::thread([=] { run(); });
    }
    void buildCompound(){
        scheduler.linkSuccessor(&null);
    };
    void breakCompound(){
        SCUD_RC status=SCUD_RC_OK;
        null.unlink(&status);
    };
    Linkable<int,void*>* compoundBegin(){
        return &scheduler;
    }
    Linkable<int,void*>* compoundEnd(){
        return &null;
    }

};
class Mixer{
    std::vector<Source*> v;
    Sink* sink;
    void run()
    {
        SCUD_RC rc=SCUD_RC_OK;
        sink->breakCompound();
        //std::cout<<"loop: mixer"<<std::endl;
        int s=v.size();
        //std::cout<<"loop: mixer 1"<<std::endl;
        for(int i=0;i<s;i++){
            v[i]->breakCompound();
            pull();
        }
        sink->buildCompound();
        for(int i=0;i<s;i++){
            v[i]->buildCompound();
            sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());
        }

        while (1) {
            //std::cout<<"loop: mixer 0"<<std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::cout<<"** ROUND **"<<std::endl;
            for(int j=0;j<100;++j)
            {

                pull();

            }
        }
    }

public:
    void addSource(Source* s){
        v.push_back(s);
    }
    void addSink(Sink* s){
        sink=s;
    }
    void addNull(){

    };
    void pull(){
        SCUD_RC rc=SCUD_RC_OK;
        struct Linkable<int,void*>::Queueable res;
        res.scheduled=-1;
        auto start= std::chrono::high_resolution_clock::now() ;
        rc=sink->compoundEnd()->pull(res);
        auto end= std::chrono::high_resolution_clock::now() ;
        auto diff = end - start;
        //std::cout<<"Pull delay="<<std::chrono::duration <double, std::micro>(diff).count()<<std::endl;

        if(rc==SCUD_RC_OK){
            std::cout<<"---Mixer: Pulled object "<<res.scheduled<<" "<<std::endl;
        }else if(rc==SCUD_RC_FAIL_LINK_NO_PACKET_AVAILABLE){
            std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        }
    }
    std::thread start() {
        return std::thread([=] { run(); });
    }
};
int main()
{
    Source s1(1,10,1,100);
    //Source s2(2,20,1,100);
    //Source s3(3,30,1,100);
    //Source s4(5,50,1,1000);

    Mixer m;
    m.addSource(&s1);
    //m.addSource(&s2);
    //m.addSource(&s3);
    //m.addSource(&s4);

    std::cout<<"SW version is: "<<SCHelper::version()<<std::endl;
    LinkableNull<int, void*> null;
    Sink si0(0);

    m.addSink(&si0);

    std::thread t1=s1.start();
    //std::thread t2=s2.start();
    //std::thread t3=s3.start();
    //std::thread t4=s4.start();
    std::thread ti0=si0.start();
    std::thread m0=m.start();

    t1.join();
    //t2.join();
    //t3.join();
    //t4.join();
    ti0.join();
    m0.join();
    std::cout << "done!\n";
}

<commit_msg>Update main.cpp<commit_after>//
//  main2.cpp
//  test_SCUD
//
//  Created by Boris Vigman on 08/07/2017.
//  Copyright © 2017-2019 Boris Vigman. All rights reserved.
//
/*
 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or (at your option) any later version.

 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 Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "scud.h"
using namespace SCUD;

#include <iostream>
#include <thread>
#include <chrono>
#include "vector"

template<typename TSchedulable,typename Tid> class Queue1:public LinkableQueue<int,void*>{

};
template<typename TSchedulable,typename Tid> class Dropper1:public LinkableDropper<int,void*>{
public:

    void processOnPush(TSchedulable sch, long long schedulingParam){
        int x=0;
    }
    void processOnPull(TSchedulable sch, long long schedulingParam){
        int x=0;
    }
    void processOnPullPush(TSchedulable sch, long long schedulingParam){
        int x=0;
    }
};
class Source{
    char priority;
    float weight;
    int label;
    long long delay;
    Queue1<int,void*> queue0;
    LinkableQueue<int,void*> queue1;
    Dropper1<int,void*> drop0;
    LinkableDropper<int,void*> drop1;
    LinkablePass<int, void*> pass1,pass2;
    //LinkablePass<int,void*> pass;
    void run(){
        SCUD_RC r0;
        drop1.unlink(&r0);
        drop0.setPriority(7);
        drop1.setPriority(priority);
        SCUD_RC rc= queue0.setPriority(priority);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue0.setWeight(weight);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue0.setLowThreshold(1);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue0.setHighThreshold(20);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue1.setDRRQuantum(0);
        rc=queue1.setDRRQuantum(50);
        rc=queue1.setWeight(5);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue1.setLowThreshold(1);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc=queue1.setHighThreshold(30);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        rc= queue1.setPriority(priority);std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        int count=10;

        //while(count>0){
        SCUD_RC status=SCUD_RC_OK;
        //queue.unlink(&status);
        //std::cout<<"loop: source"<<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));
        queue1.linkSuccessor(&drop1);
        queue0.linkSuccessor(&drop0);

        drop0.linkSuccessor(&queue0);
        //status=next->linkPredecessor(&drop1);

        //}
        while(1){
            std::this_thread::sleep_for(std::chrono::milliseconds(delay));

            //buildCompound();
            auto start= std::chrono::high_resolution_clock::now() ;
            drop0.push(label, label*10);
            auto end= std::chrono::high_resolution_clock::now() ;
            auto diff = end - start;
            //std::cout<<"Push delay="<<std::chrono::duration <double, std::micro>(diff).count()<<std::endl;
            //std::cout<<"Queue1 ["<<label<<"] has "<<queue1.size()<<" objects"<<std::endl;
             start= std::chrono::high_resolution_clock::now() ;
            pass1.pullAndPush();
             end= std::chrono::high_resolution_clock::now() ;
             diff = end - start;
            //std::cout<<"Pull/Push delay="<<std::chrono::duration <double, std::micro>(diff).count()<<std::endl;
            //std::cout<<"Queue0 ["<<label<<"] has "<<queue0.size()<<" objects;"<<"Queue1 ["<<label<<"] has "<<queue1.size()<<" objects"<<std::endl;
            //breakCompound();
            /*
            count--;
            if(count<0){
                count=100;
                std::this_thread::sleep_for(std::chrono::milliseconds(delay*100));
            }
             */
        }
    }
public:
    Source(){weight=-1;priority=-1;label=-1;delay=100;}
    Source(int lbl, char p,float w,long long delayMilli){
        priority=p;
        weight=w;
        label=lbl;
        delay=delayMilli;
    }
    std::thread start() {
        return std::thread([=] { run(); });
    }
    void buildCompound(){
        drop0.linkSuccessor(&queue0);
        queue0.linkSuccessor(&pass1);
        pass1.linkSuccessor(&queue1);
        queue1.linkSuccessor(&pass2);
        pass2.linkSuccessor(&drop1);

    }
    void breakCompound(){
        SCUD_RC status=SCUD_RC_OK;
        Linkable<int,void*>::LinkedObjectsTuple lot1=drop1.unlink(&status);
        if(status!=SCUD_RC_OK){
            std::cout<<SCHelper::convertReturnCodeToString(status)<<std::endl;
        }
        Linkable<int,void*>::LinkedObjectsTuple lot2=queue0.unlink(&status);
        if(status!=SCUD_RC_OK){
            std::cout<<SCHelper::convertReturnCodeToString(status)<<std::endl;
        }
        Linkable<int,void*>::LinkedObjectsTuple lot3=queue1.unlink(&status);
        if(status!=SCUD_RC_OK){
            std::cout<<SCHelper::convertReturnCodeToString(status)<<std::endl;
        }
    }
    Linkable<int,void*>* compoundBegin(){
        return &drop0;
    }
    Linkable<int,void*>* compoundEnd(){
        return &drop1;
    }
};

class Sink{
    //LinkableSchedulerPriority<int, void*> scheduler;
    //LinkableSchedulerNaiveRR<int, void*> scheduler;
    LinkableSchedulerDRR<int, void*> scheduler;
    LinkableNull<int, void*> null;
    void run(){
        scheduler.setPriority(9);
        scheduler.setWeight(1);

//        while(1){
//            //std::cout<<"loop: sink"<<std::endl;
//            std::this_thread::sleep_for(std::chrono::milliseconds(100));
//            SCUD_RC rc=SCUD_RC_OK;
//            struct Linkable<int,void*>::Queueable res;
////            rc=next->pull(res);
////            if(rc==SCUD_RC_OK){
////                std::cout<<"Sink: Pulled object "<<res.scheduled<<" "<<std::endl;
////            }else{
////                std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
////            }
////            if(res.scheduled>100000){
////                int x=0;
////            }
//        }
    }
public:
    Sink(Linkable<int, void*>* l){

    }
    std::thread start() {
        return std::thread([=] { run(); });
    }
    void buildCompound(){
        scheduler.linkSuccessor(&null);
    };
    void breakCompound(){
        SCUD_RC status=SCUD_RC_OK;
        null.unlink(&status);
    };
    Linkable<int,void*>* compoundBegin(){
        return &scheduler;
    }
    Linkable<int,void*>* compoundEnd(){
        return &null;
    }

};
class Mixer{
    std::vector<Source*> v;
    Sink* sink;
    void run()
    {
        SCUD_RC rc=SCUD_RC_OK;
        sink->breakCompound();
        //std::cout<<"loop: mixer"<<std::endl;
        int s=v.size();
        //std::cout<<"loop: mixer 1"<<std::endl;
        for(int i=0;i<s;i++){
            v[i]->breakCompound();
            pull();
        }
        sink->buildCompound();
        for(int i=0;i<s;i++){
            v[i]->buildCompound();
            sink->compoundBegin()->linkPredecessor(v[i]->compoundEnd());
        }

        while (1) {
            //std::cout<<"loop: mixer 0"<<std::endl;
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
            std::cout<<"** ROUND **"<<std::endl;
            for(int j=0;j<100;++j)
            {

                pull();

            }
        }
    }

public:
    void addSource(Source* s){
        v.push_back(s);
    }
    void addSink(Sink* s){
        sink=s;
    }
    void addNull(){

    };
    void pull(){
        SCUD_RC rc=SCUD_RC_OK;
        struct Linkable<int,void*>::Queueable res;
        res.scheduled=-1;
        auto start= std::chrono::high_resolution_clock::now() ;
        rc=sink->compoundEnd()->pull(res);
        auto end= std::chrono::high_resolution_clock::now() ;
        auto diff = end - start;
        //std::cout<<"Pull delay="<<std::chrono::duration <double, std::micro>(diff).count()<<std::endl;

        if(rc==SCUD_RC_OK){
            std::cout<<"---Mixer: Pulled object "<<res.scheduled<<" "<<std::endl;
        }else if(rc==SCUD_RC_FAIL_LINK_NO_PACKET_AVAILABLE){
            std::cout<<SCHelper::convertReturnCodeToString(rc)<<std::endl;
        }
    }
    std::thread start() {
        return std::thread([=] { run(); });
    }
};
int main()
{
    Source s1(1,10,1,100);
    //Source s2(2,20,1,100);
    //Source s3(3,30,1,100);
    //Source s4(5,50,1,1000);

    Mixer m;
    m.addSource(&s1);
    //m.addSource(&s2);
    //m.addSource(&s3);
    //m.addSource(&s4);

    std::cout<<"SW version is: "<<SCHelper::version()<<std::endl;
    LinkableNull<int, void*> null;
    Sink si0(0);

    m.addSink(&si0);

    std::thread t1=s1.start();
    //std::thread t2=s2.start();
    //std::thread t3=s3.start();
    //std::thread t4=s4.start();
    std::thread ti0=si0.start();
    std::thread m0=m.start();

    t1.join();
    //t2.join();
    //t3.join();
    //t4.join();
    ti0.join();
    m0.join();
    std::cout << "done!\n";
}

<|endoftext|>


<commit_before>#include <cassert>

#include "Vaca/Vaca.h"

using namespace Vaca;

void test_double_wrapper_fail()
{
  Frame a(L"first wrapper");

  try {
    Widget b(a.getHandle());	// second wrapper

    // CreateWidgetException wasn't throw
    assert(false);
  }
  catch (CreateWidgetException& e) {
    // expected behavior
  }
  catch (...) {
    assert(false);		// other kind of exception!!
  }
}

int main()
{
  Application app;
  test_double_wrapper_fail();
  return 0;
}
<commit_msg>Fixed warning about unused variable in catch().<commit_after>#include <cassert>

#include "Vaca/Vaca.h"

using namespace Vaca;

void test_double_wrapper_fail()
{
  Frame a(L"first wrapper");

  try {
    Widget b(a.getHandle());	// Second wrapper

    // CreateWidgetException wasn't throw
    assert(false);
  }
  catch (const CreateWidgetException&) {
    // Expected behavior
  }
  catch (...) {
    assert(false);		// Other kind of exception!!
  }
}

int main()
{
  Application app;
  test_double_wrapper_fail();
  return 0;
}
<|endoftext|>


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

#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif

namespace connectivity
{
    //**************************************************************
    //************ Class: ODatabaseMetaDataResultSetMetaData
    //**************************************************************
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>   ODatabaseMetaResultSetMetaData_BASE;

    class ODatabaseMetaDataResultSetMetaData :  public  ODatabaseMetaResultSetMetaData_BASE
    {
        friend class ODatabaseMetaDataResultSet;

        TIntVector                                  m_vMapping; // when not every column is needed
        ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
        ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;

        sal_Int32                                   m_nColCount;

    protected:
        void setColumnPrivilegesMap();
        void setColumnsMap();
        void setTablesMap();
        void setProcedureColumnsMap();
        void setPrimaryKeysMap();
        void setIndexInfoMap();
        void setTablePrivilegesMap();
        void setCrossReferenceMap();
        void setTypeInfoMap();
        void setProceduresMap();
        void setTableTypes();
        void setBestRowIdentifierMap() { setVersionColumnsMap();}
        void setVersionColumnsMap();
        void setExportedKeysMap() { setCrossReferenceMap(); }
        void setImportedKeysMap() { setCrossReferenceMap(); }
        void setCatalogsMap();
        void setSchemasMap();

    protected:
        ~ODatabaseMetaDataResultSetMetaData();
    public:
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        ODatabaseMetaDataResultSetMetaData( ODatabaseMetaDataResultSet* _pRes)
                :   m_nColCount(0)
        {
        }

        /// Avoid ambigous cast error from the compiler.
        inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
        { return this; }

        virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    };
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_

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

#ifndef _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_
#define _CONNECTIVITY_DATABASEMETADATARESULTSETMETADATA_HXX_

#ifndef _COM_SUN_STAR_SDBC_XRESULTSETMETADATA_HPP_
#include <com/sun/star/sdbc/XResultSetMetaData.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _VECTOR_
#include <vector>
#endif
#ifndef _CONNECTIVITY_FDATABASEMETADATARESULTSET_HXX_
#include "FDatabaseMetaDataResultSet.hxx"
#endif
#ifndef _CONNECTIVITY_COLUMN_HXX_
#include "OColumn.hxx"
#endif
#ifndef CONNECTIVITY_STDTYPEDEFS_HXX
#include "connectivity/StdTypeDefs.hxx"
#endif

namespace connectivity
{
    //**************************************************************
    //************ Class: ODatabaseMetaDataResultSetMetaData
    //**************************************************************
    typedef ::cppu::WeakImplHelper1< ::com::sun::star::sdbc::XResultSetMetaData>   ODatabaseMetaResultSetMetaData_BASE;

    class ODatabaseMetaDataResultSetMetaData :  public  ODatabaseMetaResultSetMetaData_BASE
    {
        TIntVector                                  m_vMapping; // when not every column is needed
        ::std::map<sal_Int32,connectivity::OColumn> m_mColumns;
        ::std::map<sal_Int32,connectivity::OColumn>::const_iterator m_mColumnsIter;

        sal_Int32                                   m_nColCount;
    protected:
        ~ODatabaseMetaDataResultSetMetaData();
    public:
        // ein Konstruktor, der fuer das Returnen des Objektes benoetigt wird:
        ODatabaseMetaDataResultSetMetaData( )
                :   m_nColCount(0)
        {
        }

        /// Avoid ambigous cast error from the compiler.
        inline operator ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSetMetaData > () throw()
        { return this; }

        virtual sal_Int32 SAL_CALL getColumnCount(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isAutoIncrement( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCaseSensitive( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSearchable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isCurrency( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL isNullable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isSigned( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnDisplaySize( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnLabel( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getSchemaName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getPrecision( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getScale( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getTableName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalogName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getColumnType( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnTypeName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isDefinitelyWritable( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getColumnServiceName( sal_Int32 column ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);

        // methods to set the right column mapping
        void setColumnPrivilegesMap();
        void setColumnsMap();
        void setTablesMap();
        void setProcedureColumnsMap();
        void setPrimaryKeysMap();
        void setIndexInfoMap();
        void setTablePrivilegesMap();
        void setCrossReferenceMap();
        void setTypeInfoMap();
        void setProceduresMap();
        void setTableTypes();
        void setBestRowIdentifierMap() { setVersionColumnsMap();}
        void setVersionColumnsMap();
        void setExportedKeysMap() { setCrossReferenceMap(); }
        void setImportedKeysMap() { setCrossReferenceMap(); }
        void setCatalogsMap();
        void setSchemasMap();
    };
}
#endif // _CONNECTIVITY_FILE_ADATABASEMETARESULTSETMETADATA_HXX_

<|endoftext|>


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

#include "test_msgpack.h"

#include "../src/log.h"
#include "../src/database_utils.h"

#include <fstream>
#include <sstream>

bool write_file_contents(const std::string& filename, const std::string& contents) {
	std::ofstream of(filename.data(), std::ios::out | std::ios::binary);
	if (of.bad())
		return false;
	of.write(contents.data(), contents.size());
	return true;
}

bool read_file_contents(const std::string& filename, std::string* contents) {
	std::ifstream in(filename.data(), std::ios::in | std::ios::binary);
	if (in.bad()) {
		return false;
	}

	in.seekg(0, std::ios::end);
	contents->resize(static_cast<size_t>(in.tellg()));
	in.seekg(0, std::ios::beg);
	in.read(&(*contents)[0], contents->size());
	in.close();
	return true;
}

int test_correct_cpp() {
#if defined(MSGPACK_USE_CPP03)
	L_ERR(nullptr, "ERROR: It is running c++03");
	return 1;
#else
	return 0;
#endif
}

int test_pack() {
	std::string buffer;
	if (!read_file_contents("examples/msgpack/json_test1.txt", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/json_test1.txt]");
		return 1;
	}

	rapidjson::Document doc;
	try {
		json_load(doc, buffer);
	} catch (const std::exception&) {
		return 1;
	}

	auto obj = MsgPack(doc);

	std::string pack_expected;
	if (!read_file_contents("examples/msgpack/test1.mpack", &pack_expected)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test1.mpack]");
		return 1;
	}

	if (pack_expected != obj.to_string()) {
		L_ERR(nullptr, "ERROR: MsgPack::to_MsgPack is no working correctly");
		return 1;
	}

	return 0;
}

int test_unpack() {
	std::string buffer;
	if (!read_file_contents("examples/msgpack/test1.mpack", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test1.mpack]");
		return 1;
	}

	MsgPack obj(buffer);

	std::string expected;
	if (!read_file_contents("examples/msgpack/json_test1_unpack.txt", &expected)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/json_test1_unpack.txt]");
		return 1;
	}

	std::string result = obj.to_string();
	if (expected != result) {
		L_ERR(nullptr, "ERROR: Add items with MsgPack is not working\n\nExpected: %s\n\nResult: %s\n", expected.c_str(), result.c_str());
		return 1;
	}

	return 0;
}

int test_explore_json() {
	std::string buffer;
	if (!read_file_contents("examples/msgpack/test2.mpack", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test2.mpack]");
		return 1;
	}

	MsgPack obj(buffer);

	std::string expected(
		"\"_id\":\"56892c5e23700e297bd84cd5\"\n"
		"\"about\":\"Minim ad irure pariatur nulla dolore occaecat ipsum. Qui ipsum enim aute do labore deserunt enim eu nulla duis cupidatat id est. Id cupidatat nostrud ad nulla culpa veniam nulla consequat enim sunt qui id enim. Aliquip ut deserunt irure consequat irure in fugiat. Esse veniam adipisicing deserunt culpa veniam consectetur qui ex amet. Commodo aute sit esse incididunt adipisicing non enim. Aliqua consectetur officia eiusmod veniam et amet qui adipisicing dolore voluptate reprehenderit anim commodo nulla.\"\n"
		"\"address\":\"422 Whitney Avenue, Walker, Arizona, 7324\"\n"
		"\"age\":29\n"
		"\"balance\":\"$2,952.99\"\n"
		"\"company\":\"PYRAMI\"\n"
		"\"email\":\"serena.joyner@pyrami.net\"\n"
		"\"eyeColor\":\"green\"\n"
		"\"favoriteFruit\":\"banana\"\n"
		"\"friends\":[3, {\"id\":1, \"name\":\"Norma Salas\"}]\n"
		"\"greeting\":\"Hello, Serena! You have 6 unread messages.\"\n"
		"\"guid\":\"e82fe710-dca6-41f3-be6c-52be4661a462\"\n"
		"\"index\":0\n"
		"\"isActive\":false\n"
		"\"latitude\":\"39.106713\"\n"
		"\"longitude\":\"75.253735\"\n"
		"\"name\":{\"first\":\"Jeremy\", \"last\":\"Joyner\"}\n"
		"\"phone\":\"+1 (859) 576-2384\"\n"
		"\"picture\":nil\n"
		"\"range\":[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
		"\"registered\":\"Thursday, September 4, 2014 1:27 PM\"\n"
		"\"tags\":[7, \"eiusmod\"]\n"
	);

	std::stringstream ss;
	for (auto x : obj) {
		ss << x << ":" << obj[x] << "\n";
	}

	if (ss.str() != expected) {
		L_ERR(nullptr, "ERROR: MsgPack does not explore the json correctly\n\nExpected: %s\n\nResult: %s\n", expected.c_str(), ss.str().c_str());
		return 1;
	}

	return 0;
}

int test_add_items() {
	std::string expected;
	if (!read_file_contents("examples/msgpack/json_test2.txt", &expected)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/json_test2.txt]");
		return 1;
	}

	std::string buffer;
	if (!read_file_contents("examples/msgpack/test2.mpack", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test2.mpack]");
		return 1;
	}

	MsgPack obj(buffer);

	obj["name"]["middle"]["other"] = "Jeremy";
	obj["range"][30] = "Other";
	obj["company"] = "DEIPI";
	obj["branch"] = "Morelia";
	obj["country"] = "México";

	std::string result = obj.to_string();
	if (expected != result) {
		L_ERR(nullptr, "ERROR: Add items with MsgPack is not working\n\nExpected: %s\n\nResult: %s\n", expected.c_str(), result.c_str());
		return 1;
	}

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

#include "test_msgpack.h"

#include "../src/log.h"
#include "../src/database_utils.h"

#include <fstream>
#include <sstream>

bool write_file_contents(const std::string& filename, const std::string& contents) {
	std::ofstream of(filename.data(), std::ios::out | std::ios::binary);
	if (of.bad())
		return false;
	of.write(contents.data(), contents.size());
	return true;
}

bool read_file_contents(const std::string& filename, std::string* contents) {
	std::ifstream in(filename.data(), std::ios::in | std::ios::binary);
	if (in.bad()) {
		return false;
	}

	in.seekg(0, std::ios::end);
	contents->resize(static_cast<size_t>(in.tellg()));
	in.seekg(0, std::ios::beg);
	in.read(&(*contents)[0], contents->size());
	in.close();
	return true;
}

int test_correct_cpp() {
#if defined(MSGPACK_USE_CPP03)
	L_ERR(nullptr, "ERROR: It is running c++03");
	return 1;
#else
	return 0;
#endif
}

int test_pack() {
	std::string buffer;
	if (!read_file_contents("examples/msgpack/json_test1.txt", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/json_test1.txt]");
		return 1;
	}

	rapidjson::Document doc;
	try {
		json_load(doc, buffer);
	} catch (const std::exception&) {
		return 1;
	}

	auto obj = MsgPack(doc);

	std::string pack_expected;
	if (!read_file_contents("examples/msgpack/test1.mpack", &pack_expected)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test1.mpack]");
		return 1;
	}

	if (pack_expected != obj.to_string()) {
		L_ERR(nullptr, "ERROR: MsgPack::to_MsgPack is no working correctly");
		return 1;
	}

	return 0;
}

int test_unpack() {
	std::string buffer;
	if (!read_file_contents("examples/msgpack/test1.mpack", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test1.mpack]");
		return 1;
	}

	MsgPack obj(buffer);

	std::string expected;
	if (!read_file_contents("examples/msgpack/json_test1_unpack.txt", &expected)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/json_test1_unpack.txt]");
		return 1;
	}

	std::string result = obj.to_json_string();
	if (expected != result) {
		L_ERR(nullptr, "ERROR: MsgPack::unpack is not working\n\nExpected: %s\n\nResult: %s\n", expected.c_str(), result.c_str());
		return 1;
	}

	return 0;
}

int test_explore_json() {
	std::string buffer;
	if (!read_file_contents("examples/msgpack/test2.mpack", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test2.mpack]");
		return 1;
	}

	MsgPack obj(buffer);

	std::string expected(
		"\"_id\":\"56892c5e23700e297bd84cd5\"\n"
		"\"about\":\"Minim ad irure pariatur nulla dolore occaecat ipsum. Qui ipsum enim aute do labore deserunt enim eu nulla duis cupidatat id est. Id cupidatat nostrud ad nulla culpa veniam nulla consequat enim sunt qui id enim. Aliquip ut deserunt irure consequat irure in fugiat. Esse veniam adipisicing deserunt culpa veniam consectetur qui ex amet. Commodo aute sit esse incididunt adipisicing non enim. Aliqua consectetur officia eiusmod veniam et amet qui adipisicing dolore voluptate reprehenderit anim commodo nulla.\"\n"
		"\"address\":\"422 Whitney Avenue, Walker, Arizona, 7324\"\n"
		"\"age\":29\n"
		"\"balance\":\"$2,952.99\"\n"
		"\"company\":\"PYRAMI\"\n"
		"\"email\":\"serena.joyner@pyrami.net\"\n"
		"\"eyeColor\":\"green\"\n"
		"\"favoriteFruit\":\"banana\"\n"
		"\"friends\":[3, {\"id\":1, \"name\":\"Norma Salas\"}]\n"
		"\"greeting\":\"Hello, Serena! You have 6 unread messages.\"\n"
		"\"guid\":\"e82fe710-dca6-41f3-be6c-52be4661a462\"\n"
		"\"index\":0\n"
		"\"isActive\":false\n"
		"\"latitude\":\"39.106713\"\n"
		"\"longitude\":\"75.253735\"\n"
		"\"name\":{\"first\":\"Jeremy\", \"last\":\"Joyner\"}\n"
		"\"phone\":\"+1 (859) 576-2384\"\n"
		"\"picture\":nil\n"
		"\"range\":[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n"
		"\"registered\":\"Thursday, September 4, 2014 1:27 PM\"\n"
		"\"tags\":[7, \"eiusmod\"]\n"
	);

	std::stringstream ss;
	for (auto x : obj) {
		ss << x << ":" << obj[x] << "\n";
	}

	if (ss.str() != expected) {
		L_ERR(nullptr, "ERROR: MsgPack does not explore the json correctly\n\nExpected: %s\n\nResult: %s\n", expected.c_str(), ss.str().c_str());
		return 1;
	}

	return 0;
}

int test_add_items() {
	std::string expected;
	if (!read_file_contents("examples/msgpack/json_test2.txt", &expected)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/json_test2.txt]");
		return 1;
	}

	std::string buffer;
	if (!read_file_contents("examples/msgpack/test2.mpack", &buffer)) {
		L_ERR(nullptr, "ERROR: Can not read the file [examples/test2.mpack]");
		return 1;
	}

	MsgPack obj(buffer);

	obj["name"]["middle"]["other"] = "Jeremy";
	obj["range"][30] = "Other";
	obj["company"] = "DEIPI";
	obj["branch"] = "Morelia";
	obj["country"] = "México";

	std::string result = obj.to_json_string();
	if (expected != result) {
		L_ERR(nullptr, "ERROR: Add items with MsgPack is not working\n\nExpected: %s\n\nResult: %s\n", expected.c_str(), result.c_str());
		return 1;
	}

	return 0;
}
<|endoftext|>


<commit_before>//
//  Utils.cpp
//  ee_x
//
//  Created by Zinge on 10/9/17.
//
//

#include <cassert>
#include <cstdarg>
#include <cstdlib>
#include <mutex>
#include <queue>
#include <sstream>
#include <thread>

#include "ee/Macro.hpp"
#include "ee/core/MessageBridge.hpp"
#include "ee/core/Utils.hpp"
#include "ee/core/internal/SpinLock.hpp"

namespace ee {
namespace core {
/*
void runOnUiThreadAndWait(const Runnable<void>& runnable) {
#ifdef EE_X_ANDROID
    if (std::this_thread::get_id() == uiThreadId_) {
        runnable();
        return;
    }
    std::mutex mtx;
    std::condition_variable cv;
    bool processed = false;
    runOnUiThread([runnable, &mtx, &cv, &processed] {
        std::unique_lock<std::mutex> lock(mtx);
        runnable();
        processed = true;
        lock.unlock();
        cv.notify_one();
    });
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [&processed] { return processed; });
#else  // EE_X_ANDROID
    runnable();
#endif // EE_X_ANDROID
}
*/

std::string toString(float value) {
    std::stringstream ss;
    ss << value;
    return ss.str();
}

std::string toString(bool value) {
    return value ? "true" : "false";
}

bool toBool(const std::string& value) {
    assert(value == "true" || value == "false");
    return value == "true";
}

std::string format(std::string formatString, ...) {
    std::va_list args;
    va_start(args, formatString);
    auto result = format(formatString, args);
    va_end(args);
    return result;
}

std::string format(std::string formatString, std::va_list args) {
    int final_n;
    auto n =
        2 * formatString.size(); /* Reserve two times as much as the length of
                                  the fmt_str */
    std::string str;
    std::unique_ptr<char[]> formatted;
    while (1) {
        formatted.reset(
            new char[n]); /* Wrap the plain char array into the unique_ptr */
        std::strcpy(&formatted[0], formatString.c_str());
        final_n = std::vsnprintf(&formatted[0], n, formatString.c_str(), args);
        if (final_n < 0 || final_n >= static_cast<int>(n))
            n += static_cast<std::size_t>(
                std::abs(final_n - static_cast<int>(n) + 1));
        else
            break;
    }
    return std::string(formatted.get());
}

namespace {
// clang-format off
constexpr auto k__isMainThread                  = "Utils_isMainThread";
constexpr auto k__runOnUiThread                 = "Utils_runOnUiThread";
constexpr auto k__runOnUiThreadCallback         = "Utils_runOnUiThreadCallback";
constexpr auto k__getSHA1CertificateFingerprint = "Utils_getSHA1CertificateFingerprint";
constexpr auto k__getVersionName                = "Utils_getVersionName";
constexpr auto k__getVersionCode                = "Utils_getVersionCode";
constexpr auto k__isApplicationInstalled        = "Utils_isApplicationInstalled";
constexpr auto k__openApplication               = "Utils_openApplication";
constexpr auto k__isTablet                      = "Utils_isTablet";
constexpr auto k__testConnection                = "Utils_testConnection";
constexpr auto k__getDeviceId                   = "Utils_getDeviceId";
// clang-format on
} // namespace

bool isMainThread() {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__isMainThread);
    return toBool(response);
}

namespace {
std::queue<Runnable<void>> q_;
SpinLock lock_;

void pushRunnable(const Runnable<void>& runnable) {
    std::lock_guard<SpinLock> guard(lock_);
    q_.push(runnable);
}

Runnable<void> popRunnable() {
    std::lock_guard<SpinLock> guard(lock_);
    assert(not q_.empty());
    auto runnable = q_.front();
    q_.pop();
    return runnable;
}

void runOnUiThreadCallback() {
    popRunnable()();
}

void registerHandler() {
    static std::once_flag flag;
    std::call_once(flag, [] {
        auto&& bridge = MessageBridge::getInstance();
        bridge.registerHandler(
            [](const std::string& message) {
                runOnUiThreadCallback();
                return "";
            },
            k__runOnUiThreadCallback);
    });
}
} // namespace

bool runOnUiThread(const Runnable<void>& runnable) {
    if (isMainThread()) {
        runnable();
        return true;
    }
    registerHandler();
    pushRunnable(runnable);
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__runOnUiThread);
    return toBool(response);
}

void runOnUiThreadAndWait(const Runnable<void>& runnable) {
    std::promise<void> promise;
    runOnUiThread([runnable, &promise] {
        runnable();
        promise.set_value();
    });
    return promise.get_future().get();
}

std::string getSHA1CertificateFingerprint() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getSHA1CertificateFingerprint);
}

std::string getVersionName() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getVersionName);
}

std::string getVersionCode() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getVersionCode);
}

bool isApplicationInstalled(const std::string& applicationId) {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__isApplicationInstalled, applicationId);
    return toBool(response);
}

bool openApplication(const std::string& applicationId) {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__openApplication, applicationId);
    return toBool(response);
}

bool isTablet() {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__isTablet);
    return toBool(response);
}

bool testConnection() {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__testConnection);
    return toBool(response);
}

std::string getDeviceId() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getDeviceId);
}
} // namespace core
} // namespace ee
<commit_msg>Fix crash with va_list.<commit_after>//
//  Utils.cpp
//  ee_x
//
//  Created by Zinge on 10/9/17.
//
//

#include <cassert>
#include <cstdarg>
#include <cstdlib>
#include <mutex>
#include <queue>
#include <sstream>
#include <thread>

#include "ee/Macro.hpp"
#include "ee/core/MessageBridge.hpp"
#include "ee/core/Utils.hpp"
#include "ee/core/internal/SpinLock.hpp"

namespace ee {
namespace core {
/*
void runOnUiThreadAndWait(const Runnable<void>& runnable) {
#ifdef EE_X_ANDROID
    if (std::this_thread::get_id() == uiThreadId_) {
        runnable();
        return;
    }
    std::mutex mtx;
    std::condition_variable cv;
    bool processed = false;
    runOnUiThread([runnable, &mtx, &cv, &processed] {
        std::unique_lock<std::mutex> lock(mtx);
        runnable();
        processed = true;
        lock.unlock();
        cv.notify_one();
    });
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [&processed] { return processed; });
#else  // EE_X_ANDROID
    runnable();
#endif // EE_X_ANDROID
}
*/

std::string toString(float value) {
    std::stringstream ss;
    ss << value;
    return ss.str();
}

std::string toString(bool value) {
    return value ? "true" : "false";
}

bool toBool(const std::string& value) {
    assert(value == "true" || value == "false");
    return value == "true";
}

std::string format(std::string formatString, ...) {
    std::va_list args;
    va_start(args, formatString);
    auto result = format(formatString, args);
    va_end(args);
    return result;
}

std::string format(std::string formatString, std::va_list args) {
    std::size_t n = formatString.size() * 2;
    while (true) {
        auto formatted = std::make_unique<char[]>(n);
        std::va_list temp_args;
        va_copy(temp_args, args);
        auto final_n =
            std::vsnprintf(&formatted[0], n, formatString.c_str(), temp_args);
        va_end(temp_args);
        if (final_n < 0 || final_n >= static_cast<int>(n)) {
            n += static_cast<std::size_t>(
                std::abs(final_n - static_cast<int>(n) + 1));
        } else {
            return std::string(formatted.get());
        }
    }
}

namespace {
// clang-format off
constexpr auto k__isMainThread                  = "Utils_isMainThread";
constexpr auto k__runOnUiThread                 = "Utils_runOnUiThread";
constexpr auto k__runOnUiThreadCallback         = "Utils_runOnUiThreadCallback";
constexpr auto k__getSHA1CertificateFingerprint = "Utils_getSHA1CertificateFingerprint";
constexpr auto k__getVersionName                = "Utils_getVersionName";
constexpr auto k__getVersionCode                = "Utils_getVersionCode";
constexpr auto k__isApplicationInstalled        = "Utils_isApplicationInstalled";
constexpr auto k__openApplication               = "Utils_openApplication";
constexpr auto k__isTablet                      = "Utils_isTablet";
constexpr auto k__testConnection                = "Utils_testConnection";
constexpr auto k__getDeviceId                   = "Utils_getDeviceId";
// clang-format on
} // namespace

bool isMainThread() {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__isMainThread);
    return toBool(response);
}

namespace {
std::queue<Runnable<void>> q_;
SpinLock lock_;

void pushRunnable(const Runnable<void>& runnable) {
    std::lock_guard<SpinLock> guard(lock_);
    q_.push(runnable);
}

Runnable<void> popRunnable() {
    std::lock_guard<SpinLock> guard(lock_);
    assert(not q_.empty());
    auto runnable = q_.front();
    q_.pop();
    return runnable;
}

void runOnUiThreadCallback() {
    popRunnable()();
}

void registerHandler() {
    static std::once_flag flag;
    std::call_once(flag, [] {
        auto&& bridge = MessageBridge::getInstance();
        bridge.registerHandler(
            [](const std::string& message) {
                runOnUiThreadCallback();
                return "";
            },
            k__runOnUiThreadCallback);
    });
}
} // namespace

bool runOnUiThread(const Runnable<void>& runnable) {
    if (isMainThread()) {
        runnable();
        return true;
    }
    registerHandler();
    pushRunnable(runnable);
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__runOnUiThread);
    return toBool(response);
}

void runOnUiThreadAndWait(const Runnable<void>& runnable) {
    std::promise<void> promise;
    runOnUiThread([runnable, &promise] {
        runnable();
        promise.set_value();
    });
    return promise.get_future().get();
}

std::string getSHA1CertificateFingerprint() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getSHA1CertificateFingerprint);
}

std::string getVersionName() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getVersionName);
}

std::string getVersionCode() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getVersionCode);
}

bool isApplicationInstalled(const std::string& applicationId) {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__isApplicationInstalled, applicationId);
    return toBool(response);
}

bool openApplication(const std::string& applicationId) {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__openApplication, applicationId);
    return toBool(response);
}

bool isTablet() {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__isTablet);
    return toBool(response);
}

bool testConnection() {
    auto&& bridge = MessageBridge::getInstance();
    auto response = bridge.call(k__testConnection);
    return toBool(response);
}

std::string getDeviceId() {
    auto&& bridge = MessageBridge::getInstance();
    return bridge.call(k__getDeviceId);
}
} // namespace core
} // namespace ee

<|endoftext|>


<commit_before>//
//  Testing.cpp
//  BattleShip
//
//  Created by Erik Talvi on 3/21/14.
//  Copyright (c) 2014 Prodigy. All rights reserved.
//

#define CATCH_CONFIG_MAIN // This tells Catch to provide main() - only do this in one cpp file
#include "catch.hpp"
#include <vector>
#include "ShipStrucs.h"
#include<string>
using std::string;

bool isValidBounds(int hole)
{
    return !(hole > 99 || hole < 0);
}

bool isLegalShip(std::vector<int> holes)
{
    int temp = holes[0];
    bool isVerticalShip = isValidBounds(temp);
    bool isHorizontalShip = isValidBounds(temp);

    for (int i = 1; i < holes.size(); i++)
    {
        if(isHorizontalShip && holes[i] != temp+1)
            isHorizontalShip = false;

        if(isVerticalShip && holes[i] != temp+10)
            isVerticalShip = false;

        temp = holes[i];

        if (isVerticalShip) {
            isVerticalShip = isValidBounds(temp);
        }
        if (isHorizontalShip) {
            isHorizontalShip = isValidBounds(temp);
        }

    }

    return (isVerticalShip || isHorizontalShip);
}

int coordinateToInt(string coord)
{
    char coordLetter = tolower(coord[0]);
    if(coordLetter < 'a' || coordLetter > 'j')
    {
        return 0;
    }

    char coordNumber = coord[1];
    if(coordNumber < '0' || coordNumber > '9')
    {
        return 0;
    }

    return (coordLetter - 'a' + 1)*10 + coordNumber - 58;
}

TEST_CASE ( "BATTLESHIP TESTING", "[submarineExists]" )
{
    vector<int> horizontalGood {1,2,3,4,5};
    vector<int> horzontalBad {1,3,5,7,8};
    vector<int> verticalGood {1,11,21,31,41};
    vector<int> verticalBad {1,3,7,6,5};
    vector<int> outOfBounds {-2,-1,0,1,2};
    vector<int> outOfBounds2 {81,91,101};

    REQUIRE( isLegalShip(horizontalGood) );
    REQUIRE( !isLegalShip(horzontalBad) );
    REQUIRE( isLegalShip(verticalGood) );
    REQUIRE( !isLegalShip(verticalBad) );
    REQUIRE( !isLegalShip(outOfBounds) );
    REQUIRE( !isLegalShip(outOfBounds2) );
    REQUIRE( coordinateToInt("C8") == 28 );
    REQUIRE( !coordinateToInt("1") );
    REQUIRE( coordinateToInt("g0") == 60 );
    REQUIRE( coordinateToInt("f4") == 54 );
    REQUIRE( coordinateToInt("F4") == 54 );
    REQUIRE( !coordinateToInt("k11") );
    REQUIRE( coordinateToInt("f11") == 51 ); // If more than one number for coordinate x it takes first digit
    REQUIRE( !coordinateToInt("-4") );

}

<commit_msg>Refactored coordinateToInt with separate functions for checking for valid coordinates…<commit_after>//
//  Testing.cpp
//  BattleShip
//
//  Created by Erik Talvi on 3/21/14.
//  Copyright (c) 2014 Prodigy. All rights reserved.

#define CATCH_CONFIG_MAIN // This tells Catch to provide main() - only do this in one cpp file
#include "catch.hpp"
#include "ShipStrucs.h"

#include <vector>

#include<string>
using std::string;

bool isValidBounds(int hole)
{
    return !(hole > 99 || hole < 0);
}

bool isLegalShip(std::vector<int> holes)
{
    int temp = holes[0];
    bool isVerticalShip = isValidBounds(temp);
    bool isHorizontalShip = isValidBounds(temp);

    for (int i = 1; i < holes.size(); i++)
    {
        if(isHorizontalShip && holes[i] != temp+1)
            isHorizontalShip = false;

        if(isVerticalShip && holes[i] != temp+10)
            isVerticalShip = false;

        temp = holes[i];

        if (isVerticalShip) {
            isVerticalShip = isValidBounds(temp);
        }
        if (isHorizontalShip) {
            isHorizontalShip = isValidBounds(temp);
        }

    }

    return (isVerticalShip || isHorizontalShip);
}

bool isValidCoordLetter(char coordLetter)
{
    return !(coordLetter < 'a' || coordLetter > 'j');
}

bool isValidCoordNumber(char coordNumber)
{
    return !(coordNumber < '0' || coordNumber > '9');
}

int coordinateToInt(string coord)
{
    if(coord.size() != 2)
        return 100;

    char coordLetter = tolower(coord[0]);

    if (!isValidCoordLetter(coordLetter))
        return 100;

    char coordNumber = coord[1];
    if (!isValidCoordNumber(coordNumber))
        return 100;

    return (coordLetter - 'a' + 1)*10 + coordNumber - 58;
}

TEST_CASE ( "BATTLESHIP TESTING", "[submarineExists]" )
{
    vector<int> horizontalGood {1,2,3,4,5};
    vector<int> horzontalBad {1,3,5,7,8};
    vector<int> verticalGood {1,11,21,31,41};
    vector<int> verticalBad {1,3,7,6,5};
    vector<int> outOfBounds {-2,-1,0,1,2};
    vector<int> outOfBounds2 {81,91,101};

    REQUIRE( isLegalShip(horizontalGood) );
    REQUIRE( !isLegalShip(horzontalBad) );
    REQUIRE( isLegalShip(verticalGood) );
    REQUIRE( !isLegalShip(verticalBad) );
    REQUIRE( !isLegalShip(outOfBounds) );
    REQUIRE( !isLegalShip(outOfBounds2) );
    REQUIRE( coordinateToInt("C8") == 28 );
    REQUIRE( coordinateToInt("1") == 100);
    REQUIRE( coordinateToInt("g0") == 60 );
    REQUIRE( coordinateToInt("f4") == 54 );
    REQUIRE( coordinateToInt("F4") == 54 );
    REQUIRE( coordinateToInt("k11") == 100 );
    REQUIRE( coordinateToInt("f11") == 100 );
    REQUIRE( coordinateToInt("-4") == 100 );

}

<|endoftext|>


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

#include "chrome/common/resource_bundle.h"

#include <atlbase.h>

#include "base/file_util.h"
#include "base/gfx/png_decoder.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/win_util.h"
#include "SkBitmap.h"

using namespace std;

ResourceBundle *ResourceBundle::g_shared_instance_ = NULL;

// Returns the flags that should be passed to LoadLibraryEx.
DWORD GetDataDllLoadFlags() {
  if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
    return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;

  return 0;
}

/* static */
void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {
  DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice";
  g_shared_instance_ = new ResourceBundle();

  g_shared_instance_->LoadLocaleResources(pref_locale);
}

/* static */
void ResourceBundle::CleanupSharedInstance() {
  if (g_shared_instance_) {
    delete g_shared_instance_;
    g_shared_instance_ = NULL;
  }
}

/* static */
ResourceBundle& ResourceBundle::GetSharedInstance() {
  // Must call InitSharedInstance before this function.
  CHECK(g_shared_instance_ != NULL);
  return *g_shared_instance_;
}

ResourceBundle::ResourceBundle()
    : locale_resources_dll_(NULL),
      theme_dll_(NULL) {
}

ResourceBundle::~ResourceBundle() {
  for (SkImageMap::iterator i = skia_images_.begin();
	   i != skia_images_.end(); i++) {
    delete i->second;
  }
  skia_images_.clear();

  if (locale_resources_dll_) {
    BOOL rv = FreeLibrary(locale_resources_dll_);
    DCHECK(rv);
  }
  if (theme_dll_) {
    BOOL rv = FreeLibrary(theme_dll_);
    DCHECK(rv);
  }
}

void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {
  DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded";
  const std::wstring& locale_path = GetLocaleDllPath(pref_locale);
  if (locale_path.empty()) {
    // It's possible that there are no locale dlls found, in which case we just
    // return.
    NOTREACHED();
    return;
  }

  // The dll should only have resources, not executable code.
  locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,
                                        GetDataDllLoadFlags());
  DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources";
}

std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {
  std::wstring locale_path;
  PathService::Get(chrome::DIR_LOCALES, &locale_path);

  const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);
  if (app_locale.empty())
    return app_locale;

  file_util::AppendToPath(&locale_path, app_locale + L".dll");
  return locale_path;
}

void ResourceBundle::LoadThemeResources() {
  DCHECK(NULL == theme_dll_) << "theme dll already loaded";
  std::wstring theme_dll_path;
  PathService::Get(chrome::DIR_THEMES, &theme_dll_path);
  file_util::AppendToPath(&theme_dll_path, L"default.dll");

  // The dll should only have resources, not executable code.
  theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,
                             GetDataDllLoadFlags());
  DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path;
}

/* static */
SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {
  void* data_ptr = NULL;
  size_t data_size;
  bool success = base::GetDataResourceFromModule(dll_inst, resource_id,
                                                 &data_ptr, &data_size);
  if (!success)
    return NULL;

  unsigned char* data = static_cast<unsigned char*>(data_ptr);

  // Decode the PNG.
  vector<unsigned char> png_data;
  int image_width;
  int image_height;
  if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,
                          &png_data, &image_width, &image_height)) {
    NOTREACHED() << "Unable to decode theme resource " << resource_id;
    return NULL;
  }

  return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,
                                                  image_width,
                                                  image_height);
}

SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {
  AutoLock lock_scope(lock_);

  SkImageMap::const_iterator found = skia_images_.find(resource_id);
  SkBitmap* bitmap = NULL;

  // If not found load and store the image
  if (found == skia_images_.end()) {
    // Load the image
    bitmap = LoadBitmap(theme_dll_, resource_id);
    // We did not find the bitmap in the theme DLL, try the current one.
    if (!bitmap)
      bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);
    skia_images_[resource_id] = bitmap;
  } else {
    bitmap = found->second;
  }

  // This bitmap will be returned when a bitmap is requested that can not be
  // found. The data inside is lazily initialized, so users must lock and
  static SkBitmap* empty_bitmap = NULL;

  // Handle the case where loading the bitmap failed.
  if (!bitmap) {
    LOG(WARNING) << "Unable to load bitmap with id " << resource_id;
    if (!empty_bitmap) {
      empty_bitmap = new SkBitmap();
    }
    return empty_bitmap;
  }
  return bitmap;
}

bool ResourceBundle::LoadImageResourceBytes(int resource_id,
                                            vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);
}

bool ResourceBundle::LoadDataResourceBytes(int resource_id,
                                           vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),
                                 resource_id, bytes);
}

bool ResourceBundle::LoadModuleResourceBytes(
    HINSTANCE module,
    int resource_id,
    std::vector<unsigned char>* bytes) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,
                                      &data_size)) {
    bytes->resize(data_size);
    memcpy(&(bytes->front()), data_ptr, data_size);
    return true;
  } else {
    return false;
  }
}

HICON ResourceBundle::LoadThemeIcon(int icon_id) {
  return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));
}

std::string ResourceBundle::GetDataResource(int resource_id) {
  return GetRawDataResource(resource_id).as_string();
}

StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(
        _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))
    return StringPiece(static_cast<const char*>(data_ptr), data_size);
  return StringPiece();
}

// Loads and returns the global accelerators from the current module.
HACCEL ResourceBundle::GetGlobalAccelerators() {
  return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),
                            MAKEINTRESOURCE(IDR_MAINFRAME));
}

// Loads and returns a cursor from the current module.
HCURSOR ResourceBundle::LoadCursor(int cursor_id) {
  return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),
                      MAKEINTRESOURCE(cursor_id));
}

std::wstring ResourceBundle::GetLocalizedString(int message_id) {
  // If for some reason we were unable to load a resource dll, return an empty
  // string (better than crashing).
  if (!locale_resources_dll_)
    return std::wstring();

  DCHECK(IS_INTRESOURCE(message_id));

  // Get a reference directly to the string resource.
  HINSTANCE hinstance = locale_resources_dll_;
  const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,
                                                                  message_id);
  if (!image) {
    // Fall back on the current module (shouldn't be any strings here except
    // in unittests).
    image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),
                                      message_id);
    if (!image) {
      NOTREACHED() << "unable to find resource: " << message_id;
      return std::wstring();
    }
  }
  // Copy into a wstring and return.
  return std::wstring(image->achString, image->nLength);
}

void ResourceBundle::LoadFontsIfNecessary() {
  AutoLock lock_scope(lock_);
  if (!base_font_.get()) {
    base_font_.reset(new ChromeFont());

    small_font_.reset(new ChromeFont());
    *small_font_ = base_font_->DeriveFont(-2);

    medium_font_.reset(new ChromeFont());
    *medium_font_ = base_font_->DeriveFont(3);

    medium_bold_font_.reset(new ChromeFont());
    *medium_bold_font_ =
        base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);

    large_font_.reset(new ChromeFont());
    *large_font_ = base_font_->DeriveFont(8);

    web_font_.reset(new ChromeFont());
    *web_font_ = base_font_->DeriveFont(1,
        base_font_->style() | ChromeFont::WEB);
  }
}

ChromeFont ResourceBundle::GetFont(FontStyle style) {
  LoadFontsIfNecessary();
  switch(style) {
    case SmallFont:
      return *small_font_;
    case MediumFont:
      return *medium_font_;
    case MediumBoldFont:
      return *medium_bold_font_;
    case LargeFont:
      return *large_font_;
    case WebFont:
      return *web_font_;
    default:
      return *base_font_;
  }
}

<commit_msg>Make sure we don't execute code from the theme dll.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/resource_bundle.h"

#include <atlbase.h>

#include "base/file_util.h"
#include "base/gfx/png_decoder.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/scoped_ptr.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/win_util.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/gfx/chrome_font.h"
#include "chrome/common/l10n_util.h"
#include "chrome/common/win_util.h"
#include "SkBitmap.h"

using namespace std;

ResourceBundle *ResourceBundle::g_shared_instance_ = NULL;

// Returns the flags that should be passed to LoadLibraryEx.
DWORD GetDataDllLoadFlags() {
  if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA)
    return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE;

  return LOAD_LIBRARY_AS_DATAFILE;
}

/* static */
void ResourceBundle::InitSharedInstance(const std::wstring& pref_locale) {
  DCHECK(g_shared_instance_ == NULL) << "ResourceBundle initialized twice";
  g_shared_instance_ = new ResourceBundle();

  g_shared_instance_->LoadLocaleResources(pref_locale);
}

/* static */
void ResourceBundle::CleanupSharedInstance() {
  if (g_shared_instance_) {
    delete g_shared_instance_;
    g_shared_instance_ = NULL;
  }
}

/* static */
ResourceBundle& ResourceBundle::GetSharedInstance() {
  // Must call InitSharedInstance before this function.
  CHECK(g_shared_instance_ != NULL);
  return *g_shared_instance_;
}

ResourceBundle::ResourceBundle()
    : locale_resources_dll_(NULL),
      theme_dll_(NULL) {
}

ResourceBundle::~ResourceBundle() {
  for (SkImageMap::iterator i = skia_images_.begin();
	   i != skia_images_.end(); i++) {
    delete i->second;
  }
  skia_images_.clear();

  if (locale_resources_dll_) {
    BOOL rv = FreeLibrary(locale_resources_dll_);
    DCHECK(rv);
  }
  if (theme_dll_) {
    BOOL rv = FreeLibrary(theme_dll_);
    DCHECK(rv);
  }
}

void ResourceBundle::LoadLocaleResources(const std::wstring& pref_locale) {
  DCHECK(NULL == locale_resources_dll_) << "locale dll already loaded";
  const std::wstring& locale_path = GetLocaleDllPath(pref_locale);
  if (locale_path.empty()) {
    // It's possible that there are no locale dlls found, in which case we just
    // return.
    NOTREACHED();
    return;
  }

  // The dll should only have resources, not executable code.
  locale_resources_dll_ = LoadLibraryEx(locale_path.c_str(), NULL,
                                        GetDataDllLoadFlags());
  DCHECK(locale_resources_dll_ != NULL) << "unable to load generated resources";
}

std::wstring ResourceBundle::GetLocaleDllPath(const std::wstring& pref_locale) {
  std::wstring locale_path;
  PathService::Get(chrome::DIR_LOCALES, &locale_path);

  const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale);
  if (app_locale.empty())
    return app_locale;

  file_util::AppendToPath(&locale_path, app_locale + L".dll");
  return locale_path;
}

void ResourceBundle::LoadThemeResources() {
  DCHECK(NULL == theme_dll_) << "theme dll already loaded";
  std::wstring theme_dll_path;
  PathService::Get(chrome::DIR_THEMES, &theme_dll_path);
  file_util::AppendToPath(&theme_dll_path, L"default.dll");

  // The dll should only have resources, not executable code.
  theme_dll_ = LoadLibraryEx(theme_dll_path.c_str(), NULL,
                             GetDataDllLoadFlags());
  DCHECK(theme_dll_ != NULL) << "unable to load " << theme_dll_path;
}

/* static */
SkBitmap* ResourceBundle::LoadBitmap(HINSTANCE dll_inst, int resource_id) {
  void* data_ptr = NULL;
  size_t data_size;
  bool success = base::GetDataResourceFromModule(dll_inst, resource_id,
                                                 &data_ptr, &data_size);
  if (!success)
    return NULL;

  unsigned char* data = static_cast<unsigned char*>(data_ptr);

  // Decode the PNG.
  vector<unsigned char> png_data;
  int image_width;
  int image_height;
  if (!PNGDecoder::Decode(data, data_size, PNGDecoder::FORMAT_BGRA,
                          &png_data, &image_width, &image_height)) {
    NOTREACHED() << "Unable to decode theme resource " << resource_id;
    return NULL;
  }

  return PNGDecoder::CreateSkBitmapFromBGRAFormat(png_data,
                                                  image_width,
                                                  image_height);
}

SkBitmap* ResourceBundle::GetBitmapNamed(int resource_id) {
  AutoLock lock_scope(lock_);

  SkImageMap::const_iterator found = skia_images_.find(resource_id);
  SkBitmap* bitmap = NULL;

  // If not found load and store the image
  if (found == skia_images_.end()) {
    // Load the image
    bitmap = LoadBitmap(theme_dll_, resource_id);
    // We did not find the bitmap in the theme DLL, try the current one.
    if (!bitmap)
      bitmap = LoadBitmap(_AtlBaseModule.GetModuleInstance(), resource_id);
    skia_images_[resource_id] = bitmap;
  } else {
    bitmap = found->second;
  }

  // This bitmap will be returned when a bitmap is requested that can not be
  // found. The data inside is lazily initialized, so users must lock and
  static SkBitmap* empty_bitmap = NULL;

  // Handle the case where loading the bitmap failed.
  if (!bitmap) {
    LOG(WARNING) << "Unable to load bitmap with id " << resource_id;
    if (!empty_bitmap) {
      empty_bitmap = new SkBitmap();
    }
    return empty_bitmap;
  }
  return bitmap;
}

bool ResourceBundle::LoadImageResourceBytes(int resource_id,
                                            vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(theme_dll_, resource_id, bytes);
}

bool ResourceBundle::LoadDataResourceBytes(int resource_id,
                                           vector<unsigned char>* bytes) {
  return LoadModuleResourceBytes(_AtlBaseModule.GetModuleInstance(),
                                 resource_id, bytes);
}

bool ResourceBundle::LoadModuleResourceBytes(
    HINSTANCE module,
    int resource_id,
    std::vector<unsigned char>* bytes) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(module, resource_id, &data_ptr,
                                      &data_size)) {
    bytes->resize(data_size);
    memcpy(&(bytes->front()), data_ptr, data_size);
    return true;
  } else {
    return false;
  }
}

HICON ResourceBundle::LoadThemeIcon(int icon_id) {
  return ::LoadIcon(theme_dll_, MAKEINTRESOURCE(icon_id));
}

std::string ResourceBundle::GetDataResource(int resource_id) {
  return GetRawDataResource(resource_id).as_string();
}

StringPiece ResourceBundle::GetRawDataResource(int resource_id) {
  void* data_ptr;
  size_t data_size;
  if (base::GetDataResourceFromModule(
        _AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size))
    return StringPiece(static_cast<const char*>(data_ptr), data_size);
  return StringPiece();
}

// Loads and returns the global accelerators from the current module.
HACCEL ResourceBundle::GetGlobalAccelerators() {
  return ::LoadAccelerators(_AtlBaseModule.GetModuleInstance(),
                            MAKEINTRESOURCE(IDR_MAINFRAME));
}

// Loads and returns a cursor from the current module.
HCURSOR ResourceBundle::LoadCursor(int cursor_id) {
  return ::LoadCursor(_AtlBaseModule.GetModuleInstance(),
                      MAKEINTRESOURCE(cursor_id));
}

std::wstring ResourceBundle::GetLocalizedString(int message_id) {
  // If for some reason we were unable to load a resource dll, return an empty
  // string (better than crashing).
  if (!locale_resources_dll_)
    return std::wstring();

  DCHECK(IS_INTRESOURCE(message_id));

  // Get a reference directly to the string resource.
  HINSTANCE hinstance = locale_resources_dll_;
  const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance,
                                                                  message_id);
  if (!image) {
    // Fall back on the current module (shouldn't be any strings here except
    // in unittests).
    image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(),
                                      message_id);
    if (!image) {
      NOTREACHED() << "unable to find resource: " << message_id;
      return std::wstring();
    }
  }
  // Copy into a wstring and return.
  return std::wstring(image->achString, image->nLength);
}

void ResourceBundle::LoadFontsIfNecessary() {
  AutoLock lock_scope(lock_);
  if (!base_font_.get()) {
    base_font_.reset(new ChromeFont());

    small_font_.reset(new ChromeFont());
    *small_font_ = base_font_->DeriveFont(-2);

    medium_font_.reset(new ChromeFont());
    *medium_font_ = base_font_->DeriveFont(3);

    medium_bold_font_.reset(new ChromeFont());
    *medium_bold_font_ =
        base_font_->DeriveFont(3, base_font_->style() | ChromeFont::BOLD);

    large_font_.reset(new ChromeFont());
    *large_font_ = base_font_->DeriveFont(8);

    web_font_.reset(new ChromeFont());
    *web_font_ = base_font_->DeriveFont(1,
        base_font_->style() | ChromeFont::WEB);
  }
}

ChromeFont ResourceBundle::GetFont(FontStyle style) {
  LoadFontsIfNecessary();
  switch(style) {
    case SmallFont:
      return *small_font_;
    case MediumFont:
      return *medium_font_;
    case MediumBoldFont:
      return *medium_bold_font_;
    case LargeFont:
      return *large_font_;
    case WebFont:
      return *web_font_;
    default:
      return *base_font_;
  }
}

<|endoftext|>