<commit_before>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "medialibrary/IMediaLibrary.h"
#include "test/common/NoopCallback.h"
#include "test/common/util.h"
#include "compat/Mutex.h"
#include "compat/ConditionVariable.h"

#include <iostream>
#include <condition_variable>
#include <mutex>
#include <unistd.h>
#include <cassert>

class TestCb : public mock::NoopCallback
{
public:
    TestCb()
        : m_isDiscoveryCompleted( false )
        , m_isParsingCompleted( false )
        , m_isIdle( false )
        , m_error( false )
    {
    }

    bool waitForCompletion()
    {
        std::unique_lock<compat::Mutex> lock( m_mutex );
        m_cond.wait( lock, [this](){
            return (m_isDiscoveryCompleted == true &&
                    m_isParsingCompleted == true &&
                    m_isIdle == true) || m_error;
        });
        return m_error == false;
    }

private:
    virtual void onDiscoveryStarted() override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isDiscoveryCompleted = false;
            m_isParsingCompleted = false;
        }
        m_cond.notify_all();
    }

    virtual void onDiscoveryCompleted() override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isDiscoveryCompleted = true;
        }
        m_cond.notify_all();
    }

    virtual void onDiscoveryFailed( const std::string& ) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_error = true;
        }
        m_cond.notify_all();
    }

    virtual void onParsingStatsUpdated( uint32_t done, uint32_t scheduled ) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isParsingCompleted = (done == scheduled);
        }
        m_cond.notify_all();
    }
    virtual void onBackgroundTasksIdleChanged(bool isIdle) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isIdle = isIdle;
        }
        m_cond.notify_all();
    }

private:
    compat::ConditionVariable m_cond;
    compat::Mutex m_mutex;
    bool m_isDiscoveryCompleted;
    bool m_isParsingCompleted;
    bool m_isIdle;
    bool m_error;
};

int main( int argc, char** argv )
{
    if ( argc < 2 )
    {
        std::cerr << "usage: " << argv[0] << " <entrypoint> [nb_runs] [-q]" << std::endl;
        return 1;
    }

    auto mlDir = getTempPath( "discoverer_test" );
    auto dbPath = mlDir + "/test.db";
    auto nbRuns = 1;
    auto quiet = false;
    for ( auto i = 2; i < argc; ++i )
    {
        if ( !strcmp( argv[i], "-q" ) )
            quiet = true;
        else
            nbRuns = atoi( argv[i] );
    }

    unlink( dbPath.c_str() );

    auto testCb = std::make_unique<TestCb>();
    std::unique_ptr<medialibrary::IMediaLibrary> ml{
        NewMediaLibrary( dbPath.c_str(), mlDir.c_str(), false )
    };

    ml->setVerbosity( quiet == true ? medialibrary::LogLevel::Error :
                                      medialibrary::LogLevel::Debug );
    ml->initialize( testCb.get() );
    auto res = ml->setDiscoverNetworkEnabled( true );
    assert( res );
    for ( auto i = 0; i < nbRuns; ++i )
    {
        ml->discover( argv[1] );
        res = testCb->waitForCompletion();
        if ( res == false )
            return 1;
        if ( i < nbRuns - 1 )
            ml->forceRescan();
    }
    return 0;
}
<commit_msg>test: discoverer: Allow a local path to be provided<commit_after>/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015-2018 Hugo Beauzée-Luyssen, Videolabs, VideoLAN
 *
 * Authors: Hugo Beauzée-Luyssen <hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "medialibrary/IMediaLibrary.h"
#include "test/common/NoopCallback.h"
#include "test/common/util.h"
#include "compat/Mutex.h"
#include "compat/ConditionVariable.h"
#include "utils/Filename.h"
#include "utils/Url.h"
#include "medialibrary/filesystem/Errors.h"

#include <iostream>
#include <condition_variable>
#include <mutex>
#include <unistd.h>
#include <cassert>

class TestCb : public mock::NoopCallback
{
public:
    TestCb()
        : m_isDiscoveryCompleted( false )
        , m_isParsingCompleted( false )
        , m_isIdle( false )
        , m_error( false )
    {
    }

    bool waitForCompletion()
    {
        std::unique_lock<compat::Mutex> lock( m_mutex );
        m_cond.wait( lock, [this](){
            return (m_isDiscoveryCompleted == true &&
                    m_isParsingCompleted == true &&
                    m_isIdle == true) || m_error;
        });
        return m_error == false;
    }

private:
    virtual void onDiscoveryStarted() override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isDiscoveryCompleted = false;
            m_isParsingCompleted = false;
        }
        m_cond.notify_all();
    }

    virtual void onDiscoveryCompleted() override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isDiscoveryCompleted = true;
        }
        m_cond.notify_all();
    }

    virtual void onDiscoveryFailed( const std::string& ) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_error = true;
        }
        m_cond.notify_all();
    }

    virtual void onParsingStatsUpdated( uint32_t done, uint32_t scheduled ) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isParsingCompleted = (done == scheduled);
        }
        m_cond.notify_all();
    }
    virtual void onBackgroundTasksIdleChanged(bool isIdle) override
    {
        {
            std::lock_guard<compat::Mutex> lock( m_mutex );
            m_isIdle = isIdle;
        }
        m_cond.notify_all();
    }

private:
    compat::ConditionVariable m_cond;
    compat::Mutex m_mutex;
    bool m_isDiscoveryCompleted;
    bool m_isParsingCompleted;
    bool m_isIdle;
    bool m_error;
};

int main( int argc, char** argv )
{
    if ( argc < 2 )
    {
        std::cerr << "usage: " << argv[0] << " <entrypoint> [nb_runs] [-q]" << std::endl;
        return 1;
    }

    auto mlDir = getTempPath( "discoverer_test" );
    auto dbPath = mlDir + "/test.db";
    auto nbRuns = 1;
    auto quiet = false;
    for ( auto i = 2; i < argc; ++i )
    {
        if ( !strcmp( argv[i], "-q" ) )
            quiet = true;
        else
            nbRuns = atoi( argv[i] );
    }

    std::string target;
    try
    {
        utils::url::scheme( argv[1] );
        target = argv[1];
    }
    catch ( const medialibrary::fs::errors::UnhandledScheme& )
    {
        target = utils::file::toMrl( argv[1] );
    }

    unlink( dbPath.c_str() );

    auto testCb = std::make_unique<TestCb>();
    std::unique_ptr<medialibrary::IMediaLibrary> ml{
        NewMediaLibrary( dbPath.c_str(), mlDir.c_str(), false )
    };

    ml->setVerbosity( quiet == true ? medialibrary::LogLevel::Error :
                                      medialibrary::LogLevel::Debug );
    ml->initialize( testCb.get() );
    auto res = ml->setDiscoverNetworkEnabled( true );
    assert( res );
    for ( auto i = 0; i < nbRuns; ++i )
    {
        ml->discover( target );
        res = testCb->waitForCompletion();
        if ( res == false )
            return 1;
        if ( i < nbRuns - 1 )
            ml->forceRescan();
    }
    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 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-CHROMIUM file.

#include "browser/permission_manager.h"

#include "base/callback.h"
#include "content/public/browser/permission_type.h"

namespace brightray {

PermissionManager::PermissionManager() {
}

PermissionManager::~PermissionManager() {
}

void PermissionManager::RequestPermission(
    content::PermissionType permission,
    content::RenderFrameHost* render_frame_host,
    int request_id,
    const GURL& requesting_origin,
    bool user_gesture,
    const base::Callback<void(content::PermissionStatus)>& callback) {
  callback.Run(content::PERMISSION_STATUS_GRANTED);
}

void PermissionManager::CancelPermissionRequest(
    content::PermissionType permission,
    content::RenderFrameHost* render_frame_host,
    int request_id,
    const GURL& requesting_origin) {
}

void PermissionManager::ResetPermission(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
}

content::PermissionStatus PermissionManager::GetPermissionStatus(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
  return content::PERMISSION_STATUS_GRANTED;
}

void PermissionManager::RegisterPermissionUsage(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
}

int PermissionManager::SubscribePermissionStatusChange(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin,
    const base::Callback<void(content::PermissionStatus)>& callback) {
  return -1;
}

void PermissionManager::UnsubscribePermissionStatusChange(int subscription_id) {
}

}  // namespace brightray
<commit_msg>Grant ChildProcessSecurityPolicy for MIDI from PermissionManager<commit_after>// Copyright (c) 2015 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-CHROMIUM file.

#include "browser/permission_manager.h"

#include "base/callback.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/permission_type.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"

namespace brightray {

PermissionManager::PermissionManager() {
}

PermissionManager::~PermissionManager() {
}

void PermissionManager::RequestPermission(
    content::PermissionType permission,
    content::RenderFrameHost* render_frame_host,
    int request_id,
    const GURL& requesting_origin,
    bool user_gesture,
    const base::Callback<void(content::PermissionStatus)>& callback) {
  if (permission == content::PermissionType::MIDI_SYSEX) {
    content::ChildProcessSecurityPolicy::GetInstance()->
        GrantSendMidiSysExMessage(render_frame_host->GetProcess()->GetID());
  }
  callback.Run(content::PERMISSION_STATUS_GRANTED);
}

void PermissionManager::CancelPermissionRequest(
    content::PermissionType permission,
    content::RenderFrameHost* render_frame_host,
    int request_id,
    const GURL& requesting_origin) {
}

void PermissionManager::ResetPermission(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
}

content::PermissionStatus PermissionManager::GetPermissionStatus(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
  return content::PERMISSION_STATUS_GRANTED;
}

void PermissionManager::RegisterPermissionUsage(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin) {
}

int PermissionManager::SubscribePermissionStatusChange(
    content::PermissionType permission,
    const GURL& requesting_origin,
    const GURL& embedding_origin,
    const base::Callback<void(content::PermissionStatus)>& callback) {
  return -1;
}

void PermissionManager::UnsubscribePermissionStatusChange(int subscription_id) {
}

}  // namespace brightray
<|endoftext|>


<commit_before>#include "iostream"
#include "cstdlib"
#include "optional"

using namespace std;

/*
  LinkedList
    - Estrutura fundamental, pois todos os outros partem dele
    - Tamanho variavel**
    - Um nó aponta para o proximo, se o nó for o "primeiro" o mesmo é NULL
*/

template<class T>
struct Node{
  T value;
  Node *next;
};

template<class T>
class LinkedList{
private:
  Node<T> *head;

  int deepSearch(Node<T> *actualNode, int actualSize = 0){
    if(actualNode == NULL)
      return actualSize;

    deepSearch(actualNode->next, ++actualSize);
  }

  std::optional<T> recursiveElementSearch(Node<T> *actualNode, int objectiveLevel, int actualLevel = 0){
    if(actualNode == NULL)
      return {};

    if(actualLevel == objectiveLevel)
      return actualNode->value;

    return recursiveElementSearch(actualNode->next, objectiveLevel, ++actualLevel);
  }

public:
  LinkedList(){
    head = NULL;
  }

  void push(int value){
    Node<T> *n = new Node<T>();
    n->value = value;
    n->next = head;
    head = n;
  }

  std::optional<T> pop(){
    if(head == NULL)
      return {};

    Node<T> *n = head;
    int ret = n->value;
    head = head->next;

    delete n;
    return ret;
  }

  std::optional<T> peek(){
    return head == NULL ? {} : head->value;
  }

  std::optional<T> at(int index){
    if(auto element = recursiveElementSearch(head, index))
        return *element;

    return {};
  }

  bool any(){
    return head == NULL ? false : true;
  }

  int size(){
    return deepSearch(head);
  }
};

int main(){
  LinkedList<int> list;

  cout << list.any() << endl;

  list.push(12);
  list.push(55);
  list.push(16);

  cout << list.any() << endl;
  cout << list.at(3).value_or(0) << endl;

  cout << list.pop().value_or(0) << endl;
  cout << list.pop().value_or(0) << endl;
  cout << list.pop().value_or(0) << endl;
}
<commit_msg>array<commit_after>#include "iostream"
#include "cstdlib"
#include "optional"

using namespace std;

/*
  LinkedList
    - Estrutura fundamental, pois todos os outros partem dele
    - Tamanho variavel**
    - Um nó aponta para o proximo, se o nó for o "primeiro" o mesmo é NULL
*/

template<class T>
struct Node{
  T value;
  Node *next;
};

template<class T>
class LinkedList{
private:
  Node<T> *head;

  int deep_search(Node<T> *actualNode, int actualSize = 0){
    if(actualNode == NULL)
      return actualSize;

    deep_search(actualNode->next, ++actualSize);
  }

  std::optional<T> recursive_element_search(Node<T> *actualNode, int objectiveLevel, int actualLevel = 0){
    if(actualNode == NULL)
      return {};

    if(actualLevel == objectiveLevel)
      return actualNode->value;

    return recursive_element_search(actualNode->next, objectiveLevel, ++actualLevel);
  }

  void fill_array(Node<T> *actualNode, T *array, int actualIndex = 0){
    if(actualNode == NULL)
      return;

    array[actualIndex] = actualNode->value;
    fill_array(actualNode->next, array, ++actualIndex);
  }

public:
  LinkedList(){
    head = NULL;
  }

  void push_back(int value){
    Node<T> *n = new Node<T>();
    n->value = value;
    n->next = head;
    head = n;
  }

  std::optional<T> pop_back(){
    if(head == NULL)
      return {};

    Node<T> *n = head;
    int ret = n->value;
    head = head->next;

    delete n;
    return ret;
  }

  std::optional<T> peek_back(){
    if(head == NULL)
      return {};

    return head->value;
  }

  std::optional<T> at(int index){
    if(auto element = recursive_element_search(head, index))
        return *element;

    return {};
  }

  bool any(){
    return head == NULL ? false : true;
  }

  int size(){
    return deep_search(head);
  }

  T* to_array(){
    T *array = new T[size()];
    fill_array(head, array);
    return array;
  }
};

int main(){
  LinkedList<int> list;

  cout << list.any() << endl;

  list.push_back(12);
  list.push_back(55);
  list.push_back(16);

  cout << list.any() << endl;
  cout << list.at(3).value_or(0) << endl;

  cout << list.pop_back().value_or(0) << endl;
  cout << list.pop_back().value_or(0) << endl;
  cout << list.pop_back().value_or(0) << endl;
}
<|endoftext|>


<commit_before>//  (C) Copyright Gennadiy Rozental 2001-2002.
//  Permission to copy, use, modify, sell and distribute this software
//  is granted provided this copyright notice appears in all copies.
//  This software is provided "as is" without express or implied warranty,
//  and with no claim as to its suitability for any purpose.

//  See http://www.boost.org for most recent version including documentation.
//
//  File        : $RCSfile$
//
//  Version     : $Id$
//
//  Description : tests floating point comparison algorithms
// ***************************************************************************

// Boost.Test
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_result.hpp>
#include <boost/test/floating_point_comparison.hpp>
using namespace boost::unit_test_framework;

// STL
#include <iostream>

//____________________________________________________________________________//

#define CHECK_TOOL_USAGE( tool_usage, check )               \
{                                                           \
    boost::test_toolbox::output_test_stream output;         \
                                                            \
    unit_test_log::instance().set_log_stream( output );     \
    { unit_test_result_saver saver;                         \
      tool_usage;                                           \
    }                                                       \
    unit_test_log::instance().set_log_stream( std::cout );  \
    BOOST_CHECK( check );                                   \
}

//____________________________________________________________________________//

#if !defined(__BORLANDC__)
#define CHECK_PATTERN( msg, shift ) \
    (boost::wrap_stringstream().ref() << __FILE__ << "(" << __LINE__ << "): " << msg).str()

#else

#define CHECK_PATTERN( msg, shift ) \
    (boost::wrap_stringstream().ref() << __FILE__ << "(" << (__LINE__-shift) << "): " << msg).str()

#endif
//____________________________________________________________________________//

template<typename FPT>
void
test_BOOST_CHECK_CLOSE( FPT ) {
#undef  TEST_CASE_NAME
#define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_CLOSE_all" << "\"" <<
    unit_test_log::instance().set_log_threshold_level( log_messages );

    BOOST_MESSAGE( "testing BOOST_CHECK_CLOSE for " << typeid(FPT).name() );

#define BOOST_CHECK_CLOSE_SHOULD_PASS( first, second, e )       \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
    epsilon = static_cast<FPT>(e);                              \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),                 \
        output.is_empty()                                       \
    )

#define BOOST_CHECK_CLOSE_SHOULD_PASS_N( first, second, num )   \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, (num) ),                   \
        output.is_empty()                                       \
    )

#define BOOST_CHECK_CLOSE_SHOULD_FAIL( first, second, e )       \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
    epsilon = static_cast<FPT>(e);                              \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),                 \
        output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
                                        << fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
    )

#define BOOST_CHECK_CLOSE_SHOULD_FAIL_N( first, second, num )   \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
    epsilon = num * std::numeric_limits<FPT>::epsilon()/2;      \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, num ),                     \
        output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
        << fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
    )

    FPT fp1, fp2, epsilon, tmp;

    BOOST_CHECK_CLOSE_SHOULD_PASS( 1, 1, 0 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-20, 1e-7 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-30, 1e-7 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, -1e-10, 1e-3 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, 0.123457, 1e-6 );

    BOOST_CHECK_CLOSE_SHOULD_PASS( 0.123456, 0.123457, 1e-5 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, -0.123457, 1e-5 );

    BOOST_CHECK_CLOSE_SHOULD_PASS( 1.23456e28, 1.23457e28, 1e-5 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.23456e-10, 1.23457e-11, 1e-5 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.111e-10, 1.112e-10, 0.0008999 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.112e-10, 1.111e-10, 0.0008999 );

    BOOST_CHECK_CLOSE_SHOULD_PASS( 1     , 1.0001, 1.1e-4 );
    BOOST_CHECK_CLOSE_SHOULD_PASS( 1.0002, 1.0001, 1.1e-4 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1     , 1.0002, 1.1e-4 );

    BOOST_CHECK_CLOSE_SHOULD_PASS_N( 1, 1+std::numeric_limits<FPT>::epsilon() / 2, 1 );

    tmp = static_cast<FPT>(1e-10);
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp+tmp, 2e-10, 1+2 );

    tmp = static_cast<FPT>(3.1);
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp, 9.61, 1+2 );

    tmp = 11;
    tmp /= 10;
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( (tmp*tmp-tmp), 11./100, 1+3 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL_N( 100*(tmp*tmp-tmp), 11, 3 );

    tmp = static_cast<FPT>(1e15+1e-10);
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp+tmp*tmp, 2e30+2e-20+4e5, 3+5 );

    fp1     = static_cast<FPT>(1.0001);
    fp2     = static_cast<FPT>(1001.1001);
    tmp     = static_cast<FPT>(1.0001);

    for( int i=0; i < 1000; i++ )
        fp1 = fp1 + tmp;

    CHECK_TOOL_USAGE(
        BOOST_CHECK_CLOSE( fp1, fp2, 1000 ),
        output.is_empty()
    );
}

void
test_BOOST_CHECK_CLOSE_all() {
    test_BOOST_CHECK_CLOSE<float>( (float)0 );
    test_BOOST_CHECK_CLOSE<double>( (double)0 );
    test_BOOST_CHECK_CLOSE<long double>( (long double)0 );

    double fp1     = 1.00000001;
    double fp2     = 1.00000002;
    double epsilon = 1e-8;

    CHECK_TOOL_USAGE(
        BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
        output.is_empty()
    );

    CHECK_TOOL_USAGE(
        BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),
        output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed ["
                                        << fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 3 ) )
    );

    fp1     = 1.23456e-10;
    fp2     = 1.23457e-10;
    epsilon = 8.1e-6;

    CHECK_TOOL_USAGE(
        BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
        output.is_empty()
    );

    CHECK_TOOL_USAGE(
        BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon ), 2, ( fp1, fp2 ) ),
        output.is_equal( CHECK_PATTERN(
                    "error in " TEST_CASE_NAME ": test close_at_tolerance<double>( epsilon )(fp1, fp2) "
                    "failed for (" << fp1 << ", " << fp2 << ")\n", 4 ) )
    );
}

//____________________________________________________________________________//

test_suite*
init_unit_test_suite( int /*argc*/, char* /*argv*/[] ) {
    test_suite* test = BOOST_TEST_SUITE("FP compare test");

    test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_CLOSE_all ) );

    return test;
}

//____________________________________________________________________________//

// ***************************************************************************
//  Revision History :
//
//  $Log$
//  Revision 1.1  2003/02/13 08:47:11  rogeeff
//  *** empty log message ***
//

// ***************************************************************************

// EOF
<commit_msg>cwpro8 fix<commit_after>//  (C) Copyright Gennadiy Rozental 2001-2002.
//  Permission to copy, use, modify, sell and distribute this software
//  is granted provided this copyright notice appears in all copies.
//  This software is provided "as is" without express or implied warranty,
//  and with no claim as to its suitability for any purpose.

//  See http://www.boost.org for most recent version including documentation.
//
//  File        : $RCSfile$
//
//  Version     : $Id$
//
//  Description : tests floating point comparison algorithms
// ***************************************************************************

// Boost.Test
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/unit_test_result.hpp>
using namespace boost::unit_test_framework;

// STL
#include <iostream>

//____________________________________________________________________________//

#define CHECK_TOOL_USAGE( tool_usage, check )               \
{                                                           \
    boost::test_toolbox::output_test_stream output;         \
                                                            \
    unit_test_log::instance().set_log_stream( output );     \
    { unit_test_result_saver saver;                         \
      tool_usage;                                           \
    }                                                       \
    unit_test_log::instance().set_log_stream( std::cout );  \
    BOOST_CHECK( check );                                   \
}

//____________________________________________________________________________//

#if !defined(__BORLANDC__)
#define CHECK_PATTERN( msg, shift ) \
    (boost::wrap_stringstream().ref() << __FILE__ << "(" << __LINE__ << "): " << msg).str()

#else

#define CHECK_PATTERN( msg, shift ) \
    (boost::wrap_stringstream().ref() << __FILE__ << "(" << (__LINE__-shift) << "): " << msg).str()

#endif
//____________________________________________________________________________//

template<typename FPT>
void
test_BOOST_CHECK_CLOSE( FPT ) {
#undef  TEST_CASE_NAME
#define TEST_CASE_NAME << '\"' << "test_BOOST_CHECK_CLOSE_all" << "\"" <<
    unit_test_log::instance().set_log_threshold_level( log_messages );

    BOOST_MESSAGE( "testing BOOST_CHECK_CLOSE for " << typeid(FPT).name() );

#define BOOST_CHECK_CLOSE_SHOULD_PASS( first, second, e )       \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
    epsilon = static_cast<FPT>(e);                              \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),                 \
        output.is_empty()                                       \
    )

#define BOOST_CHECK_CLOSE_SHOULD_PASS_N( first, second, num )   \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, (num) ),                   \
        output.is_empty()                                       \
    )

#define BOOST_CHECK_CLOSE_SHOULD_FAIL( first, second, e )       \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
    epsilon = static_cast<FPT>(e);                              \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),                 \
        output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
                                        << fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
    )

#define BOOST_CHECK_CLOSE_SHOULD_FAIL_N( first, second, num )   \
    fp1     = static_cast<FPT>(first);                          \
    fp2     = static_cast<FPT>(second);                         \
    epsilon = num * std::numeric_limits<FPT>::epsilon()/2;      \
                                                                \
    CHECK_TOOL_USAGE(                                           \
        BOOST_CHECK_CLOSE( fp1, fp2, num ),                     \
        output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed [" \
        << fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 0 ) ) \
    )

    FPT fp1, fp2, epsilon, tmp;

    BOOST_CHECK_CLOSE_SHOULD_PASS( 1, 1, 0 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-20, 1e-7 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, 1e-30, 1e-7 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0, -1e-10, 1e-3 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, 0.123457, 1e-6 );

    BOOST_CHECK_CLOSE_SHOULD_PASS( 0.123456, 0.123457, 1e-5 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 0.123456, -0.123457, 1e-5 );

    BOOST_CHECK_CLOSE_SHOULD_PASS( 1.23456e28, 1.23457e28, 1e-5 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.23456e-10, 1.23457e-11, 1e-5 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.111e-10, 1.112e-10, 0.0008999 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1.112e-10, 1.111e-10, 0.0008999 );

    BOOST_CHECK_CLOSE_SHOULD_PASS( 1     , 1.0001, 1.1e-4 );
    BOOST_CHECK_CLOSE_SHOULD_PASS( 1.0002, 1.0001, 1.1e-4 );

    BOOST_CHECK_CLOSE_SHOULD_FAIL( 1     , 1.0002, 1.1e-4 );

    BOOST_CHECK_CLOSE_SHOULD_PASS_N( 1, 1+std::numeric_limits<FPT>::epsilon() / 2, 1 );

    tmp = static_cast<FPT>(1e-10);
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp+tmp, 2e-10, 1+2 );

    tmp = static_cast<FPT>(3.1);
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp, 9.61, 1+2 );

    tmp = 11;
    tmp /= 10;
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( (tmp*tmp-tmp), 11./100, 1+3 );
    BOOST_CHECK_CLOSE_SHOULD_FAIL_N( 100*(tmp*tmp-tmp), 11, 3 );

    tmp = static_cast<FPT>(1e15+1e-10);
    BOOST_CHECK_CLOSE_SHOULD_PASS_N( tmp*tmp+tmp*tmp, 2e30+2e-20+4e5, 3+5 );

    fp1     = static_cast<FPT>(1.0001);
    fp2     = static_cast<FPT>(1001.1001);
    tmp     = static_cast<FPT>(1.0001);

    for( int i=0; i < 1000; i++ )
        fp1 = fp1 + tmp;

    CHECK_TOOL_USAGE(
        BOOST_CHECK_CLOSE( fp1, fp2, 1000 ),
        output.is_empty()
    );
}

void
test_BOOST_CHECK_CLOSE_all() {
    test_BOOST_CHECK_CLOSE<float>( (float)0 );
    test_BOOST_CHECK_CLOSE<double>( (double)0 );
    test_BOOST_CHECK_CLOSE<long double>( (long double)0 );

    double fp1     = 1.00000001;
    double fp2     = 1.00000002;
    double epsilon = 1e-8;

    CHECK_TOOL_USAGE(
        BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
        output.is_empty()
    );

    CHECK_TOOL_USAGE(
        BOOST_CHECK_CLOSE( fp1, fp2, epsilon ),
        output.is_equal( CHECK_PATTERN( "error in " TEST_CASE_NAME ": test fp1 ~= fp2 failed ["
                                        << fp1 << " !~= " << fp2 << " (+/-" << epsilon << ")]\n", 3 ) )
    );

    fp1     = 1.23456e-10;
    fp2     = 1.23457e-10;
    epsilon = 8.1e-6;

    CHECK_TOOL_USAGE(
        BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon, false ), 2, ( fp1, fp2 ) ),
        output.is_empty()
    );

    CHECK_TOOL_USAGE(
        BOOST_CHECK_PREDICATE( close_at_tolerance<double>( epsilon ), 2, ( fp1, fp2 ) ),
        output.is_equal( CHECK_PATTERN(
                    "error in " TEST_CASE_NAME ": test close_at_tolerance<double>( epsilon )(fp1, fp2) "
                    "failed for (" << fp1 << ", " << fp2 << ")\n", 4 ) )
    );
}

//____________________________________________________________________________//

test_suite*
init_unit_test_suite( int /*argc*/, char* /*argv*/[] ) {
    test_suite* test = BOOST_TEST_SUITE("FP compare test");

    test->add( BOOST_TEST_CASE( &test_BOOST_CHECK_CLOSE_all ) );

    return test;
}

//____________________________________________________________________________//

// ***************************************************************************
//  Revision History :
//
//  $Log$
//  Revision 1.2  2003/02/15 21:53:39  rogeeff
//  cwpro8 fix
//
//  Revision 1.1  2003/02/13 08:47:11  rogeeff
//  *** empty log message ***
//

// ***************************************************************************

// EOF
<|endoftext|>


<commit_before><commit_msg>Disable OCSP until we have fixed the crash in OCSP code.  As a result our EV checks must fail because EV requires revocation checking.  (We aren't downloading CRLs yet.)<commit_after><|endoftext|>


<commit_before><commit_msg><commit_after><|endoftext|>


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

#include "base/type_traits.h"

#include "base/basictypes.h"
#include <gtest/gtest.h>

namespace base {
namespace {

struct AStruct {};
class AClass {};
union AUnion {};
enum AnEnum { AN_ENUM_APPLE, AN_ENUM_BANANA, AN_ENUM_CARROT };
struct BStruct {
    int x;
};
class BClass {
    int ALLOW_UNUSED _x;
};

class Parent {};
class Child : public Parent {};

// is_empty<Type>
COMPILE_ASSERT(is_empty<AStruct>::value, IsEmpty);
COMPILE_ASSERT(is_empty<AClass>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BStruct>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BClass>::value, IsEmpty);

// is_pointer<Type>
COMPILE_ASSERT(!is_pointer<int>::value, IsPointer);
COMPILE_ASSERT(!is_pointer<int&>::value, IsPointer);
COMPILE_ASSERT(is_pointer<int*>::value, IsPointer);
COMPILE_ASSERT(is_pointer<const int*>::value, IsPointer);

// is_array<Type>
COMPILE_ASSERT(!is_array<int>::value, IsArray);
COMPILE_ASSERT(!is_array<int*>::value, IsArray);
COMPILE_ASSERT(!is_array<int(*)[3]>::value, IsArray);
COMPILE_ASSERT(is_array<int[]>::value, IsArray);
COMPILE_ASSERT(is_array<const int[]>::value, IsArray);
COMPILE_ASSERT(is_array<int[3]>::value, IsArray);

// is_non_const_reference<Type>
COMPILE_ASSERT(!is_non_const_reference<int>::value, IsNonConstReference);
COMPILE_ASSERT(!is_non_const_reference<const int&>::value, IsNonConstReference);
COMPILE_ASSERT(is_non_const_reference<int&>::value, IsNonConstReference);

// is_convertible<From, To>

// Extra parens needed to make preprocessor macro parsing happy. Otherwise,
// it sees the equivalent of:
//
//     (is_convertible < Child), (Parent > ::value)
//
// Silly C++.
COMPILE_ASSERT( (is_convertible<Child, Parent>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, Child>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, AStruct>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int, double>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int*, void*>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<void*, int*>::value), IsConvertible);

// Array types are an easy corner case.  Make sure to test that
// it does indeed compile.
COMPILE_ASSERT(!(is_convertible<int[10], double>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<double, int[10]>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int[10], int*>::value), IsConvertible);

// is_same<Type1, Type2>
COMPILE_ASSERT(!(is_same<Child, Parent>::value), IsSame);
COMPILE_ASSERT(!(is_same<Parent, Child>::value), IsSame);
COMPILE_ASSERT( (is_same<Parent, Parent>::value), IsSame);
COMPILE_ASSERT( (is_same<int*, int*>::value), IsSame);
COMPILE_ASSERT( (is_same<int, int>::value), IsSame);
COMPILE_ASSERT( (is_same<void, void>::value), IsSame);
COMPILE_ASSERT(!(is_same<int, double>::value), IsSame);

// is_class<Type>
COMPILE_ASSERT(is_class<AStruct>::value, IsClass);
COMPILE_ASSERT(is_class<AClass>::value, IsClass);
COMPILE_ASSERT(is_class<AUnion>::value, IsClass);
COMPILE_ASSERT(!is_class<AnEnum>::value, IsClass);
COMPILE_ASSERT(!is_class<int>::value, IsClass);
COMPILE_ASSERT(!is_class<char*>::value, IsClass);
COMPILE_ASSERT(!is_class<int&>::value, IsClass);
COMPILE_ASSERT(!is_class<char[3]>::value, IsClass);

// NOTE(gejun): Not work in gcc 3.4 yet.
#if !defined(__GNUC__) || __GNUC__ >= 4
COMPILE_ASSERT((is_enum<AnEnum>::value), IsEnum);
#endif
COMPILE_ASSERT(!(is_enum<AClass>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AStruct>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AUnion>::value), IsEnum);

COMPILE_ASSERT(!is_member_function_pointer<int>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int*>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<void*>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct*>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int, int)>::value,
               IsMemberFunctionPointer);

COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)()>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)(int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int) const>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int) const>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int) const>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int) const>::value,
               IsMemberFunctionPointer);

// False because we don't have a specialization for 5 params yet.
COMPILE_ASSERT(!is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int, int) const>::value,
               IsMemberFunctionPointer);

// add_const
COMPILE_ASSERT((is_same<add_const<int>::type, const int>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<long>::type, const long>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<std::string>::type, const std::string>::value),
               AddConst);
COMPILE_ASSERT((is_same<add_const<const int>::type, const int>::value),
               AddConst);
COMPILE_ASSERT((is_same<add_const<const long>::type, const long>::value),
               AddConst);
COMPILE_ASSERT((is_same<add_const<const std::string>::type,
                const std::string>::value), AddConst);

// add_volatile
COMPILE_ASSERT((is_same<add_volatile<int>::type, volatile int>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<long>::type, volatile long>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<std::string>::type,
                volatile std::string>::value), AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile int>::type, volatile int>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile long>::type, volatile long>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile std::string>::type,
                volatile std::string>::value), AddVolatile);

// add_reference
COMPILE_ASSERT((is_same<add_reference<int>::type, int&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<long>::type, long&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string>::type, std::string&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<int&>::type, int&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<long&>::type, long&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string&>::type,
                std::string&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<const int&>::type, const int&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<const long&>::type, const long&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<const std::string&>::type,
                const std::string&>::value), AddReference);

// add_cr_non_integral
COMPILE_ASSERT((is_same<add_cr_non_integral<int>::type, int>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<long>::type, long>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<std::string>::type,
                const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int>::type, const int&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long>::type, const long&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string>::type,
                const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int&>::type, const int&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long&>::type, const long&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string&>::type,
                const std::string&>::value), AddCrNonIntegral);

// remove_const
COMPILE_ASSERT((is_same<remove_const<const int>::type, int>::value),
               RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const long>::type, long>::value),
               RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const std::string>::type,
                std::string>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<int>::type, int>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<long>::type, long>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<std::string>::type, std::string>::value),
               RemoveConst);

// remove_reference
COMPILE_ASSERT((is_same<remove_reference<int&>::type, int>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long&>::type, long>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string&>::type,
                std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const int&>::type, const int>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const long&>::type, const long>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const std::string&>::type,
                const std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<int>::type, int>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long>::type, long>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string>::type, std::string>::value),
               RemoveReference);

}  // namespace
}  // namespace base
<commit_msg>Patch a minor fix to test/type_traits_unittest.cc from svn<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/type_traits.h"

#include "base/basictypes.h"
#include <gtest/gtest.h>

namespace base {
namespace {

struct AStruct {};
class AClass {};
union AUnion {};
enum AnEnum { AN_ENUM_APPLE, AN_ENUM_BANANA, AN_ENUM_CARROT };
struct BStruct {
    int x;
};
class BClass {
#if defined(__clang__)
    int ALLOW_UNUSED _x;
#else
    int _x;
#endif
};

class Parent {};
class Child : public Parent {};

// is_empty<Type>
COMPILE_ASSERT(is_empty<AStruct>::value, IsEmpty);
COMPILE_ASSERT(is_empty<AClass>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BStruct>::value, IsEmpty);
COMPILE_ASSERT(!is_empty<BClass>::value, IsEmpty);

// is_pointer<Type>
COMPILE_ASSERT(!is_pointer<int>::value, IsPointer);
COMPILE_ASSERT(!is_pointer<int&>::value, IsPointer);
COMPILE_ASSERT(is_pointer<int*>::value, IsPointer);
COMPILE_ASSERT(is_pointer<const int*>::value, IsPointer);

// is_array<Type>
COMPILE_ASSERT(!is_array<int>::value, IsArray);
COMPILE_ASSERT(!is_array<int*>::value, IsArray);
COMPILE_ASSERT(!is_array<int(*)[3]>::value, IsArray);
COMPILE_ASSERT(is_array<int[]>::value, IsArray);
COMPILE_ASSERT(is_array<const int[]>::value, IsArray);
COMPILE_ASSERT(is_array<int[3]>::value, IsArray);

// is_non_const_reference<Type>
COMPILE_ASSERT(!is_non_const_reference<int>::value, IsNonConstReference);
COMPILE_ASSERT(!is_non_const_reference<const int&>::value, IsNonConstReference);
COMPILE_ASSERT(is_non_const_reference<int&>::value, IsNonConstReference);

// is_convertible<From, To>

// Extra parens needed to make preprocessor macro parsing happy. Otherwise,
// it sees the equivalent of:
//
//     (is_convertible < Child), (Parent > ::value)
//
// Silly C++.
COMPILE_ASSERT( (is_convertible<Child, Parent>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, Child>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<Parent, AStruct>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int, double>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int*, void*>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<void*, int*>::value), IsConvertible);

// Array types are an easy corner case.  Make sure to test that
// it does indeed compile.
COMPILE_ASSERT(!(is_convertible<int[10], double>::value), IsConvertible);
COMPILE_ASSERT(!(is_convertible<double, int[10]>::value), IsConvertible);
COMPILE_ASSERT( (is_convertible<int[10], int*>::value), IsConvertible);

// is_same<Type1, Type2>
COMPILE_ASSERT(!(is_same<Child, Parent>::value), IsSame);
COMPILE_ASSERT(!(is_same<Parent, Child>::value), IsSame);
COMPILE_ASSERT( (is_same<Parent, Parent>::value), IsSame);
COMPILE_ASSERT( (is_same<int*, int*>::value), IsSame);
COMPILE_ASSERT( (is_same<int, int>::value), IsSame);
COMPILE_ASSERT( (is_same<void, void>::value), IsSame);
COMPILE_ASSERT(!(is_same<int, double>::value), IsSame);

// is_class<Type>
COMPILE_ASSERT(is_class<AStruct>::value, IsClass);
COMPILE_ASSERT(is_class<AClass>::value, IsClass);
COMPILE_ASSERT(is_class<AUnion>::value, IsClass);
COMPILE_ASSERT(!is_class<AnEnum>::value, IsClass);
COMPILE_ASSERT(!is_class<int>::value, IsClass);
COMPILE_ASSERT(!is_class<char*>::value, IsClass);
COMPILE_ASSERT(!is_class<int&>::value, IsClass);
COMPILE_ASSERT(!is_class<char[3]>::value, IsClass);

// NOTE(gejun): Not work in gcc 3.4 yet.
#if !defined(__GNUC__) || __GNUC__ >= 4
COMPILE_ASSERT((is_enum<AnEnum>::value), IsEnum);
#endif
COMPILE_ASSERT(!(is_enum<AClass>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AStruct>::value), IsEnum);
COMPILE_ASSERT(!(is_enum<AUnion>::value), IsEnum);

COMPILE_ASSERT(!is_member_function_pointer<int>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int*>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<void*>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<AStruct*>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<int(*)(int, int)>::value,
               IsMemberFunctionPointer);

COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)()>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<void (AStruct::*)(int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int) const>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<int (AStruct::*)(int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int) const>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int) const>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int) const>::value,
               IsMemberFunctionPointer);

// False because we don't have a specialization for 5 params yet.
COMPILE_ASSERT(!is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int, int)>::value,
               IsMemberFunctionPointer);
COMPILE_ASSERT(!is_member_function_pointer<
                 int (AStruct::*)(int, int, int, int, int) const>::value,
               IsMemberFunctionPointer);

// add_const
COMPILE_ASSERT((is_same<add_const<int>::type, const int>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<long>::type, const long>::value), AddConst);
COMPILE_ASSERT((is_same<add_const<std::string>::type, const std::string>::value),
               AddConst);
COMPILE_ASSERT((is_same<add_const<const int>::type, const int>::value),
               AddConst);
COMPILE_ASSERT((is_same<add_const<const long>::type, const long>::value),
               AddConst);
COMPILE_ASSERT((is_same<add_const<const std::string>::type,
                const std::string>::value), AddConst);

// add_volatile
COMPILE_ASSERT((is_same<add_volatile<int>::type, volatile int>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<long>::type, volatile long>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<std::string>::type,
                volatile std::string>::value), AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile int>::type, volatile int>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile long>::type, volatile long>::value),
               AddVolatile);
COMPILE_ASSERT((is_same<add_volatile<volatile std::string>::type,
                volatile std::string>::value), AddVolatile);

// add_reference
COMPILE_ASSERT((is_same<add_reference<int>::type, int&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<long>::type, long&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string>::type, std::string&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<int&>::type, int&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<long&>::type, long&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<std::string&>::type,
                std::string&>::value), AddReference);
COMPILE_ASSERT((is_same<add_reference<const int&>::type, const int&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<const long&>::type, const long&>::value),
               AddReference);
COMPILE_ASSERT((is_same<add_reference<const std::string&>::type,
                const std::string&>::value), AddReference);

// add_cr_non_integral
COMPILE_ASSERT((is_same<add_cr_non_integral<int>::type, int>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<long>::type, long>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<std::string>::type,
                const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int>::type, const int&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long>::type, const long&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string>::type,
                const std::string&>::value), AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const int&>::type, const int&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const long&>::type, const long&>::value),
               AddCrNonIntegral);
COMPILE_ASSERT((is_same<add_cr_non_integral<const std::string&>::type,
                const std::string&>::value), AddCrNonIntegral);

// remove_const
COMPILE_ASSERT((is_same<remove_const<const int>::type, int>::value),
               RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const long>::type, long>::value),
               RemoveConst);
COMPILE_ASSERT((is_same<remove_const<const std::string>::type,
                std::string>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<int>::type, int>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<long>::type, long>::value), RemoveConst);
COMPILE_ASSERT((is_same<remove_const<std::string>::type, std::string>::value),
               RemoveConst);

// remove_reference
COMPILE_ASSERT((is_same<remove_reference<int&>::type, int>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long&>::type, long>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string&>::type,
                std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const int&>::type, const int>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const long&>::type, const long>::value),
               RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<const std::string&>::type,
                const std::string>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<int>::type, int>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<long>::type, long>::value), RemoveReference);
COMPILE_ASSERT((is_same<remove_reference<std::string>::type, std::string>::value),
               RemoveReference);

}  // namespace
}  // namespace base
<|endoftext|>


<commit_before>#ifndef SIGNALSRLATCH_HPP_INCLUDED
#define SIGNALSRLATCH_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file SignalSRlatch.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Fri 28 Jun 2013 13:01:40
//! @brief S-R latch
//! @ingroup SignalComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalFFBDcomponents.nb*/

using namespace hopsan;

class SignalSRlatch : public ComponentSignal
{
private:
     int mNstep;
//==This code has been autogenerated using Compgen==
     //inputVariables
     double setCond;
     double resetCond;
     //outputVariables
     double Qstate;
     double notQstate;
     //InitialExpressions variables
     double oldQstate;
     double oldSetCond;
     double oldResetCond;
     //Expressions variables
     double DsetCond;
     double DresetCond;
     //Delay declarations
//==This code has been autogenerated using Compgen==
     //inputVariables pointers
     double *mpsetCond;
     double *mpresetCond;
     //inputParameters pointers
     //outputVariables pointers
     double *mpQstate;
     double *mpnotQstate;
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new SignalSRlatch();
     }

     void configure()
     {
//==This code has been autogenerated using Compgen==

        mNstep=9;

        //Add ports to the component
        //Add inputVariables to the component
            addInputVariable("setCond","On condition","",0.,&mpsetCond);
            addInputVariable("resetCond","off condition","",0.,&mpresetCond);

        //Add inputParammeters to the component
        //Add outputVariables to the component
            addOutputVariable("Qstate","Logical state","",0.,&mpQstate);
            addOutputVariable("notQstate","Logical inverse of \
state","",0.,&mpnotQstate);

//==This code has been autogenerated using Compgen==
        //Add constantParameters
     }

    void initialize()
     {
        //Read port variable pointers from nodes

        //Read variables from nodes

        //Read inputVariables from nodes
        setCond = (*mpsetCond);
        resetCond = (*mpresetCond);

        //Read inputParameters from nodes

        //Read outputVariables from nodes
        Qstate = (*mpQstate);
        notQstate = (*mpnotQstate);

//==This code has been autogenerated using Compgen==
        //InitialExpressions
        oldQstate = Qstate;
        oldSetCond = setCond;
        oldResetCond = resetCond;

        //Initialize delays

     }
    void simulateOneTimestep()
     {
        //Read variables from nodes

        //Read inputVariables from nodes
        setCond = (*mpsetCond);
        resetCond = (*mpresetCond);

        //LocalExpressions

          //Expressions
          DsetCond = onPositive(-oldSetCond + setCond);
          DresetCond = onPositive(-oldResetCond + resetCond);
          Qstate = -0.5 - onPositive(-0.5 + DresetCond) + onPositive(-0.5 + \
DsetCond) + onPositive(-0.5 + oldQstate);
          oldQstate = Qstate;
          notQstate = 1 - Qstate;

        //Calculate the delayed parts

        //Write new values to nodes
        //outputVariables
        (*mpQstate)=Qstate;
        (*mpnotQstate)=notQstate;

        //Update the delayed variabels

     }
    void deconfigure()
    {
        delete mpSolver;
    }
};
#endif // SIGNALSRLATCH_HPP_INCLUDED
<commit_msg>Behaviour corrected<commit_after>#ifndef SIGNALSRLATCH_HPP_INCLUDED
#define SIGNALSRLATCH_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file SignalSRlatch.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Wed 16 Oct 2013 09:59:45
//! @brief S-R latch
//! @ingroup SignalComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, HOPSAN++, CompgenModels}/SignalFFBDcomponents.nb*/

using namespace hopsan;

class SignalSRlatch : public ComponentSignal
{
private:
     int mNstep;
//==This code has been autogenerated using Compgen==
     //inputVariables
     double setCond;
     double resetCond;
     //outputVariables
     double Qstate;
     double notQstate;
     //InitialExpressions variables
     double oldQstate;
     double oldSetCond;
     double oldResetCond;
     //Expressions variables
     double DsetCond;
     double DresetCond;
     //Delay declarations
//==This code has been autogenerated using Compgen==
     //inputVariables pointers
     double *mpsetCond;
     double *mpresetCond;
     //inputParameters pointers
     //outputVariables pointers
     double *mpQstate;
     double *mpnotQstate;
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new SignalSRlatch();
     }

     void configure()
     {
//==This code has been autogenerated using Compgen==

        mNstep=9;

        //Add ports to the component
        //Add inputVariables to the component
            addInputVariable("setCond","On condition","",0.,&mpsetCond);
            addInputVariable("resetCond","off condition","",0.,&mpresetCond);

        //Add inputParammeters to the component
        //Add outputVariables to the component
            addOutputVariable("Qstate","Logical state","",0.,&mpQstate);
            addOutputVariable("notQstate","Logical inverse of \
state","",0.,&mpnotQstate);

//==This code has been autogenerated using Compgen==
        //Add constantParameters
     }

    void initialize()
     {
        //Read port variable pointers from nodes

        //Read variables from nodes

        //Read inputVariables from nodes
        setCond = (*mpsetCond);
        resetCond = (*mpresetCond);

        //Read inputParameters from nodes

        //Read outputVariables from nodes
        Qstate = (*mpQstate);
        notQstate = (*mpnotQstate);

//==This code has been autogenerated using Compgen==
        //InitialExpressions
        oldQstate = Qstate;
        oldSetCond = setCond;
        oldResetCond = resetCond;

        //Initialize delays

     }
    void simulateOneTimestep()
     {
        //Read variables from nodes

        //Read inputVariables from nodes
        setCond = (*mpsetCond);
        resetCond = (*mpresetCond);

        //LocalExpressions

          //Expressions
          DsetCond = onPositive(-oldSetCond + setCond);
          DresetCond = onPositive(-oldResetCond + resetCond);
          Qstate = limit(-2*onPositive(-0.5 + DresetCond) + 2*onPositive(-0.5 \
+ DsetCond) + 2*onPositive(-0.5 + oldQstate),0,1);
          oldQstate = Qstate;
          notQstate = 1 - Qstate;

        //Calculate the delayed parts

        //Write new values to nodes
        //outputVariables
        (*mpQstate)=Qstate;
        (*mpnotQstate)=notQstate;

        //Update the delayed variabels

     }
    void deconfigure()
    {
        delete mpSolver;
    }
};
#endif // SIGNALSRLATCH_HPP_INCLUDED
<|endoftext|>


<commit_before>#ifndef SLIC3RXS

#ifndef CONFIG_HPP
#define CONFIG_HPP

#include <initializer_list>
#include <memory>
#include <regex>

#include "PrintConfig.hpp"
#include "ConfigBase.hpp"

namespace Slic3r {

/// Exception class for invalid (but correct type) option values.
/// Thrown by validate()
class InvalidOptionValue : public std::runtime_error {
public:
    InvalidOptionValue(const char* v) : runtime_error(v) {}
    InvalidOptionValue(const std::string v) : runtime_error(v.c_str()) {}
};

/// Exception class to handle config options that don't exist.
class InvalidConfigOption : public std::runtime_error {};

/// Exception class for type mismatches
class InvalidOptionType : public std::runtime_error {
public:
    InvalidOptionType(const char* v) : runtime_error(v) {}
    InvalidOptionType(const std::string v) : runtime_error(v.c_str()) {}
};

class Config;
using config_ptr = std::shared_ptr<Config>;

class Config {
public:

    /// Factory method to construct a Config with all default values loaded.
    static std::shared_ptr<Config> new_from_defaults();

    /// Factory method to construct a Config with specific default values loaded.
    static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init);

    /// Factory method to construct a Config with specific default values loaded.
    static std::shared_ptr<Config> new_from_defaults(t_config_option_keys init);

    /// Factory method to construct a Config from CLI options.
    static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]);

    /// Factory method to construct a Config from an ini file.
    static std::shared_ptr<Config> new_from_ini(const std::string& inifile);

    /// Write a windows-style opt=value ini file with categories from the configuration store.
    void write_ini(const std::string& file) const;

    /// Parse a windows-style opt=value ini file with categories and load the configuration store.
    void read_ini(const std::string& file);

    /// Template function to retrieve and cast in hopefully a slightly nicer
    /// format than longwinded dynamic_cast<>
    template <class T>
    T& get(const t_config_option_key& opt_key, bool create=false) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return *(dynamic_cast<T*>(this->_config.optptr(opt_key, create)));
    }

    double getFloat(const t_config_option_key& opt_key, bool create=false) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getFloat();
    }

    int getInt(const t_config_option_key& opt_key, bool create=false) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getInt();
    }
    std::string getString(const t_config_option_key& opt_key, bool create=false) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getString();
    }

    /// Template function to dynamic cast and leave it in pointer form.
    template <class T>
    T* get_ptr(const t_config_option_key& opt_key, bool create=false) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return dynamic_cast<T*>(this->_config.optptr(opt_key, create));
    }

    /// Function to parse value from a string to whatever opt_key is.
    void set(const t_config_option_key& opt_key, const std::string& value);

    /// Function to parse value from an integer to whatever opt_key is, if
    /// opt_key is a numeric type. This will throw an exception and do
    /// nothing if called with an incorrect type.
    void set(const t_config_option_key& opt_key, const int value);

    /// Function to parse value from an integer to whatever opt_key is, if
    /// opt_key is a numeric type. This will throw an exception and do
    /// nothing if called with an incorrect type.
    void set(const t_config_option_key& opt_key, const double value);

    /// Method to validate the different configuration options.
    /// It will throw InvalidConfigOption exceptions on failure.
    bool validate();

    const DynamicPrintConfig& config() const { return _config; }
    bool empty() const { return _config.empty(); }

    /// Pass-through of apply()
    void apply(const config_ptr& other) { _config.apply(other->config()); }
    void apply(const Slic3r::Config& other) { _config.apply(other.config()); }

    Config();

private:
    std::regex _cli_pattern {"=(.+)$"};
    std::smatch _match_info {};

    /// Underlying configuration store.
    DynamicPrintConfig _config {};
};

bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);
bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);

} // namespace Slic3r

#endif // CONFIG_HPP

#endif // SLIC3RXS
<commit_msg>Default to pulling from defaults with get() functions.<commit_after>#ifndef SLIC3RXS

#ifndef CONFIG_HPP
#define CONFIG_HPP

#include <initializer_list>
#include <memory>
#include <regex>

#include "PrintConfig.hpp"
#include "ConfigBase.hpp"

namespace Slic3r {

/// Exception class for invalid (but correct type) option values.
/// Thrown by validate()
class InvalidOptionValue : public std::runtime_error {
public:
    InvalidOptionValue(const char* v) : runtime_error(v) {}
    InvalidOptionValue(const std::string v) : runtime_error(v.c_str()) {}
};

/// Exception class to handle config options that don't exist.
class InvalidConfigOption : public std::runtime_error {};

/// Exception class for type mismatches
class InvalidOptionType : public std::runtime_error {
public:
    InvalidOptionType(const char* v) : runtime_error(v) {}
    InvalidOptionType(const std::string v) : runtime_error(v.c_str()) {}
};

class Config;
using config_ptr = std::shared_ptr<Config>;

class Config {
public:

    /// Factory method to construct a Config with all default values loaded.
    static std::shared_ptr<Config> new_from_defaults();

    /// Factory method to construct a Config with specific default values loaded.
    static std::shared_ptr<Config> new_from_defaults(std::initializer_list<std::string> init);

    /// Factory method to construct a Config with specific default values loaded.
    static std::shared_ptr<Config> new_from_defaults(t_config_option_keys init);

    /// Factory method to construct a Config from CLI options.
    static std::shared_ptr<Config> new_from_cli(const int& argc, const char* argv[]);

    /// Factory method to construct a Config from an ini file.
    static std::shared_ptr<Config> new_from_ini(const std::string& inifile);

    /// Write a windows-style opt=value ini file with categories from the configuration store.
    void write_ini(const std::string& file) const;

    /// Parse a windows-style opt=value ini file with categories and load the configuration store.
    void read_ini(const std::string& file);

    double getFloat(const t_config_option_key& opt_key, bool create=true) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getFloat();
    }

    int getInt(const t_config_option_key& opt_key, bool create=true) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getInt();
    }
    std::string getString(const t_config_option_key& opt_key, bool create=true) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return (dynamic_cast<ConfigOption*>(this->_config.optptr(opt_key, create)))->getString();
    }

    /// Template function to dynamic cast and leave it in pointer form.
    template <class T>
    T* get_ptr(const t_config_option_key& opt_key, bool create=true) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return dynamic_cast<T*>(this->_config.optptr(opt_key, create));
    }

    /// Template function to retrieve and cast in hopefully a slightly nicer
    /// format than longwinded dynamic_cast<>
    template <class T>
    T& get(const t_config_option_key& opt_key, bool create=true) {
        if (print_config_def.options.count(opt_key) == 0) throw InvalidOptionType(opt_key + std::string(" is an invalid option."));
        return *(dynamic_cast<T*>(this->_config.optptr(opt_key, create)));
    }

    /// Function to parse value from a string to whatever opt_key is.
    void set(const t_config_option_key& opt_key, const std::string& value);

    /// Function to parse value from an integer to whatever opt_key is, if
    /// opt_key is a numeric type. This will throw an exception and do
    /// nothing if called with an incorrect type.
    void set(const t_config_option_key& opt_key, const int value);

    /// Function to parse value from an integer to whatever opt_key is, if
    /// opt_key is a numeric type. This will throw an exception and do
    /// nothing if called with an incorrect type.
    void set(const t_config_option_key& opt_key, const double value);

    /// Method to validate the different configuration options.
    /// It will throw InvalidConfigOption exceptions on failure.
    bool validate();

    const DynamicPrintConfig& config() const { return _config; }
    bool empty() const { return _config.empty(); }

    /// Pass-through of apply()
    void apply(const config_ptr& other) { _config.apply(other->config()); }
    void apply(const Slic3r::Config& other) { _config.apply(other.config()); }

    Config();

private:
    std::regex _cli_pattern {"=(.+)$"};
    std::smatch _match_info {};

    /// Underlying configuration store.
    DynamicPrintConfig _config {};
};

bool is_valid_int(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);
bool is_valid_float(const std::string& type, const ConfigOptionDef& opt, const std::string& ser_value);

} // namespace Slic3r

#endif // CONFIG_HPP

#endif // SLIC3RXS
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/execution/executor/new_executor_traits/is_simple_executor.hpp>
#include <agency/execution/executor/new_executor_traits/is_bulk_executor.hpp>

namespace agency
{

template<class T>
using new_is_executor = agency::detail::disjunction<
  is_simple_executor<T>,
  is_bulk_executor<T>
>;

namespace detail
{

// a fake Concept to use with __AGENCY_REQUIRES
template<class T>
constexpr bool Executor()
{
  return is_executor<T>();
}

} // end detail
} // end agency

<commit_msg>Fix the implementation of detail::Executor()<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/execution/executor/new_executor_traits/is_simple_executor.hpp>
#include <agency/execution/executor/new_executor_traits/is_bulk_executor.hpp>

namespace agency
{

template<class T>
using new_is_executor = agency::detail::disjunction<
  is_simple_executor<T>,
  is_bulk_executor<T>
>;

namespace detail
{

// a fake Concept to use with __AGENCY_REQUIRES
template<class T>
constexpr bool Executor()
{
  return new_is_executor<T>();
}

} // end detail
} // end agency

<|endoftext|>