<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbOGRDataToClassStatisticsFilter.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include <fstream>

int otbOGRDataToClassStatisticsFilterNew(int itkNotUsed(argc), char* itkNotUsed(argv) [])
{
  typedef otb::VectorImage<float> InputImageType;
  typedef otb::Image<unsigned char> MaskImageType;
  typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;

  FilterType::Pointer filter = FilterType::New();
  std::cout << filter << std::endl;
  return EXIT_SUCCESS;
}

int otbOGRDataToClassStatisticsFilter(int argc, char* argv[])
{
  typedef otb::VectorImage<float> InputImageType;
  typedef otb::Image<unsigned char> MaskImageType;
  typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;

  if (argc < 3)
    {
    std::cout << "Usage : "<<argv[0]<< " input_vector  output_stats" << std::endl;
    }

  std::string vectorPath(argv[1]);
  std::string outputPath(argv[2]);

  otb::ogr::DataSource::Pointer vectors = otb::ogr::DataSource::New(vectorPath);

  InputImageType::RegionType region;
  region.SetSize(0,99);
  region.SetSize(1,50);

  InputImageType::PointType origin;
  origin.Fill(0.5);

  InputImageType::SpacingType spacing;
  spacing[0] = 1.0;
  spacing[1] = -1.0;

  InputImageType::PixelType pixel(3);
  pixel.Fill(1);

  InputImageType::Pointer inputImage = InputImageType::New();
  inputImage->SetNumberOfComponentsPerPixel(3);
  inputImage->SetRegions(region);
  inputImage->SetOrigin(origin);
  inputImage->SetSpacing(spacing);
  inputImage->Allocate();
  inputImage->FillBuffer(pixel);

  MaskImageType::Pointer mask = MaskImageType::New();
  mask->SetRegions(region);
  mask->SetOrigin(origin);
  mask->SetSpacing(spacing);
  mask->Allocate();
  itk::ImageRegionIterator<MaskImageType> it(mask,region);
  unsigned int count = 0;
  for (it.GoToBegin(); !it.IsAtEnd() ; ++it, ++count)
    {
    it.Set(count % 2);
    }

  std::string fieldName("Label");

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(inputImage);
  filter->SetMask(mask);
  filter->SetOGRData(vectors);
  filter->SetFieldName(fieldName);
  filter->SetLayerIndex(0);

  filter->Update();

  FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get();
  FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get();
  FilterType::ClassCountMapType::const_iterator itClass;
  FilterType::PolygonSizeMapType::const_iterator itPoly;

  std::ofstream ofs;
  ofs.open(outputPath.c_str());
  ofs << "# Layer 0 : polygons"<<std::endl;
  ofs << "# Class sample counts"<<std::endl;
  for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
    {
    ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
    }
  ofs << "# Vector sizes"<<std::endl;
  for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
    {
    ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
    }

  filter->SetLayerIndex(1);
  filter->Update();

  ofs << "# Layer 1 : lines"<<std::endl;
  ofs << "# Class sample counts"<<std::endl;
  for (itClass = classCount.begin() ; itClass != classCount.end() ; ++itClass)
    {
    ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
    }
  ofs << "# Vector sizes"<<std::endl;
  for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
    {
    ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
    }

  filter->SetLayerIndex(2);
  filter->Update();

  ofs << "# Layer 2 : points"<<std::endl;
  ofs << "# Class sample counts"<<std::endl;
  for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
    {
    ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
    }
  ofs << "# Vector sizes"<<std::endl;
  for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
    {
    ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
    }

  ofs.close();
  return EXIT_SUCCESS;
}
<commit_msg>TEST: don't allocate input image in test<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "otbOGRDataToClassStatisticsFilter.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include <fstream>

int otbOGRDataToClassStatisticsFilterNew(int itkNotUsed(argc), char* itkNotUsed(argv) [])
{
  typedef otb::VectorImage<float> InputImageType;
  typedef otb::Image<unsigned char> MaskImageType;
  typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;

  FilterType::Pointer filter = FilterType::New();
  std::cout << filter << std::endl;
  return EXIT_SUCCESS;
}

int otbOGRDataToClassStatisticsFilter(int argc, char* argv[])
{
  typedef otb::VectorImage<float> InputImageType;
  typedef otb::Image<unsigned char> MaskImageType;
  typedef otb::OGRDataToClassStatisticsFilter<InputImageType,MaskImageType> FilterType;

  if (argc < 3)
    {
    std::cout << "Usage : "<<argv[0]<< " input_vector  output_stats" << std::endl;
    }

  std::string vectorPath(argv[1]);
  std::string outputPath(argv[2]);

  otb::ogr::DataSource::Pointer vectors = otb::ogr::DataSource::New(vectorPath);

  InputImageType::RegionType region;
  region.SetSize(0,99);
  region.SetSize(1,50);

  InputImageType::PointType origin;
  origin.Fill(0.5);

  InputImageType::SpacingType spacing;
  spacing[0] = 1.0;
  spacing[1] = -1.0;

  InputImageType::PixelType pixel(3);
  pixel.Fill(1);

  InputImageType::Pointer inputImage = InputImageType::New();
  inputImage->SetNumberOfComponentsPerPixel(3);
  inputImage->SetLargestPossibleRegion(region);
  inputImage->SetOrigin(origin);
  inputImage->SetSpacing(spacing);
  // Don't allocate the input image, the filter should not need it
  //inputImage->Allocate();
  //inputImage->FillBuffer(pixel);

  MaskImageType::Pointer mask = MaskImageType::New();
  mask->SetRegions(region);
  mask->SetOrigin(origin);
  mask->SetSpacing(spacing);
  mask->Allocate();
  itk::ImageRegionIterator<MaskImageType> it(mask,region);
  unsigned int count = 0;
  for (it.GoToBegin(); !it.IsAtEnd() ; ++it, ++count)
    {
    it.Set(count % 2);
    }

  std::string fieldName("Label");

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(inputImage);
  filter->SetMask(mask);
  filter->SetOGRData(vectors);
  filter->SetFieldName(fieldName);
  filter->SetLayerIndex(0);

  filter->Update();

  FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get();
  FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get();
  FilterType::ClassCountMapType::const_iterator itClass;
  FilterType::PolygonSizeMapType::const_iterator itPoly;

  std::ofstream ofs;
  ofs.open(outputPath.c_str());
  ofs << "# Layer 0 : polygons"<<std::endl;
  ofs << "# Class sample counts"<<std::endl;
  for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
    {
    ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
    }
  ofs << "# Vector sizes"<<std::endl;
  for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
    {
    ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
    }

  filter->SetLayerIndex(1);
  filter->Update();

  ofs << "# Layer 1 : lines"<<std::endl;
  ofs << "# Class sample counts"<<std::endl;
  for (itClass = classCount.begin() ; itClass != classCount.end() ; ++itClass)
    {
    ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
    }
  ofs << "# Vector sizes"<<std::endl;
  for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
    {
    ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
    }

  filter->SetLayerIndex(2);
  filter->Update();

  ofs << "# Layer 2 : points"<<std::endl;
  ofs << "# Class sample counts"<<std::endl;
  for (itClass = classCount.begin(); itClass != classCount.end() ; ++itClass)
    {
    ofs << "class "<< itClass->first << " = "<< itClass->second << std::endl;
    }
  ofs << "# Vector sizes"<<std::endl;
  for (itPoly = polySize.begin() ; itPoly != polySize.end() ; ++itPoly)
    {
    ofs << "feature " << itPoly->first << " = "<< itPoly->second << std::endl;
    }

  ofs.close();
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "k/interrupt.h"

#include "etl/armv7m/nvic.h"
#include "etl/armv7m/scb.h"
#include "etl/assert.h"

#include "k/reply_sender.h"
#include "k/scheduler.h"

using etl::armv7m::nvic;
using etl::armv7m::scb;
using etl::armv7m::Scb;

namespace k {

/******************************************************************************
 * InterruptBase
 */

InterruptBase::InterruptBase(uint32_t identifier)
  : _saved_brand{0},
    _target{},
    _sender_item{this},
    _priority{0},
    _identifier{identifier} {}

void InterruptBase::trigger() {
  disable_interrupt();
  _target.deliver_from(this);
  do_deferred_switch_from_irq();
}

void InterruptBase::deliver_from(Brand const & brand, Sender * sender) {
  Message m;
  Keys k;
  sender->on_delivery_accepted(m, k);
  switch (m.d0.get_selector()) {
    case 1:
      do_set_target(brand, m, k);
      break;

    case 2:
      do_enable(brand, m, k);
      break;

    default:
      do_extension(m.d0.get_selector(), brand, m, k);
      break;
  }
}

void InterruptBase::do_extension(Selector,
                                 Brand const &,
                                 Message const & m,
                                 Keys & k) {
  do_badop(m, k);
}

void InterruptBase::do_set_target(Brand const &, Message const &, Keys & k) {
  auto & reply = k.keys[0];
  auto & target = k.keys[1];

  ScopedReplySender reply_sender{reply};

  _target = target;
}

void InterruptBase::do_enable(Brand const &, Message const & m, Keys & k) {
  ScopedReplySender reply_sender{k.keys[0]};

  bool clear_pending = m.d1 != 0;

  if (clear_pending) clear_pending_interrupt();
  enable_interrupt();
}

Priority InterruptBase::get_priority() const {
  return _priority;
}

void InterruptBase::on_delivery_accepted(Message & m, Keys & k) {
  m = {
    Descriptor::zero().with_selector(1),
    _identifier,
  };
  k.keys[0] = make_key(0).ref();
  for (unsigned ki = 0; ki < config::n_message_keys; ++ki) {
    k.keys[ki] = Key::null();
  }
}

void InterruptBase::on_delivery_failed(Exception, uint32_t) {
  // Our attempt to deliver has failed.  This is an indication of a
  // configuration error.  Do nothing for now.
  // TODO: should this be able to raise some sort of alert?
}

void InterruptBase::block_in_send(Brand const & brand,
                              List<BlockingSender> & list) {
  _saved_brand = brand;
  list.insert(&_sender_item);
}

void InterruptBase::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) {
  b = _saved_brand;
  on_delivery_accepted(m, k);
}

void InterruptBase::on_blocked_delivery_failed(Exception, uint32_t) {
  // We appear to have been interrupted while blocked.
}

/******************************************************************************
 * Interrupt
 */

Interrupt::Interrupt(uint32_t irq)
  : InterruptBase{irq} {}

void Interrupt::disable_interrupt() {
  nvic.disable_irq(get_identifier());
}

void Interrupt::enable_interrupt() {
  nvic.enable_irq(get_identifier());
}

void Interrupt::clear_pending_interrupt() {
  nvic.clear_pending_irq(get_identifier());
}

}  // namespace k
<commit_msg>k/interrupt: fix error in message key production.<commit_after>#include "k/interrupt.h"

#include "etl/armv7m/nvic.h"
#include "etl/armv7m/scb.h"
#include "etl/assert.h"

#include "k/reply_sender.h"
#include "k/scheduler.h"

using etl::armv7m::nvic;
using etl::armv7m::scb;
using etl::armv7m::Scb;

namespace k {

/******************************************************************************
 * InterruptBase
 */

InterruptBase::InterruptBase(uint32_t identifier)
  : _saved_brand{0},
    _target{},
    _sender_item{this},
    _priority{0},
    _identifier{identifier} {}

void InterruptBase::trigger() {
  disable_interrupt();
  _target.deliver_from(this);
  do_deferred_switch_from_irq();
}

void InterruptBase::deliver_from(Brand const & brand, Sender * sender) {
  Message m;
  Keys k;
  sender->on_delivery_accepted(m, k);
  switch (m.d0.get_selector()) {
    case 1:
      do_set_target(brand, m, k);
      break;

    case 2:
      do_enable(brand, m, k);
      break;

    default:
      do_extension(m.d0.get_selector(), brand, m, k);
      break;
  }
}

void InterruptBase::do_extension(Selector,
                                 Brand const &,
                                 Message const & m,
                                 Keys & k) {
  do_badop(m, k);
}

void InterruptBase::do_set_target(Brand const &, Message const &, Keys & k) {
  auto & reply = k.keys[0];
  auto & target = k.keys[1];

  ScopedReplySender reply_sender{reply};

  _target = target;
}

void InterruptBase::do_enable(Brand const &, Message const & m, Keys & k) {
  ScopedReplySender reply_sender{k.keys[0]};

  bool clear_pending = m.d1 != 0;

  if (clear_pending) clear_pending_interrupt();
  enable_interrupt();
}

Priority InterruptBase::get_priority() const {
  return _priority;
}

void InterruptBase::on_delivery_accepted(Message & m, Keys & k) {
  m = {
    Descriptor::zero().with_selector(1),
    _identifier,
  };
  k.keys[0] = make_key(0).ref();
  for (unsigned ki = 1; ki < config::n_message_keys; ++ki) {
    k.keys[ki] = Key::null();
  }
}

void InterruptBase::on_delivery_failed(Exception, uint32_t) {
  // Our attempt to deliver has failed.  This is an indication of a
  // configuration error.  Do nothing for now.
  // TODO: should this be able to raise some sort of alert?
}

void InterruptBase::block_in_send(Brand const & brand,
                              List<BlockingSender> & list) {
  _saved_brand = brand;
  list.insert(&_sender_item);
}

void InterruptBase::on_blocked_delivery_accepted(Message & m, Brand & b, Keys & k) {
  b = _saved_brand;
  on_delivery_accepted(m, k);
}

void InterruptBase::on_blocked_delivery_failed(Exception, uint32_t) {
  // We appear to have been interrupted while blocked.
}

/******************************************************************************
 * Interrupt
 */

Interrupt::Interrupt(uint32_t irq)
  : InterruptBase{irq} {}

void Interrupt::disable_interrupt() {
  nvic.disable_irq(get_identifier());
}

void Interrupt::enable_interrupt() {
  nvic.enable_irq(get_identifier());
}

void Interrupt::clear_pending_interrupt() {
  nvic.clear_pending_irq(get_identifier());
}

}  // namespace k
<|endoftext|>


<commit_before>#pragma once
#include <bts/blockchain/types.hpp>

namespace bts { namespace blockchain {

static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
    {       1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) },
    {  100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) },
    {  200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) },
    {  300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) },
    {  400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) },
    {  500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) },
    {  600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) },
    {  700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) },
    {  800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) },
    {  900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) },
    { 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) },
    { 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) },
    { 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) },
    { 1300000, bts::blockchain::block_id_type( "623e5c04a77b7e688299a45bfb1d84a0bf3ea318" ) },
    { 1400000, bts::blockchain::block_id_type( "f7645d369b7a818c4acb94f3bedbcb7747dea9dd" ) },
    { 1500000, bts::blockchain::block_id_type( "a9027b880105fa89f4d0c2bf9a0df328fed3108d" ) },
    { 1600000, bts::blockchain::block_id_type( "1c08742243deda31c663130fca9ab8bd825803c5" ) },
    { 1603000, bts::blockchain::block_id_type( "1d85e3e412a5289f76204840bfe77a8176b6cd58" ) }
};

} } // bts::blockchain
<commit_msg>Update checkpoint<commit_after>#pragma once
#include <bts/blockchain/types.hpp>

namespace bts { namespace blockchain {

static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS
{
    {       1, bts::blockchain::block_id_type( "8abcfb93c52f999e3ef5288c4f837f4f15af5521" ) },
    {  100000, bts::blockchain::block_id_type( "96f98d49722848a6a47ad04aece8b9f93c9e9c23" ) },
    {  200000, bts::blockchain::block_id_type( "222ddc49db592103c51ad22cdc4140185ef564d9" ) },
    {  300000, bts::blockchain::block_id_type( "0d1d0b8f7f1f4590f8e083edc03869383ed74e3e" ) },
    {  400000, bts::blockchain::block_id_type( "053d398b6597d5c61365afd100d87b824bf49f65" ) },
    {  500000, bts::blockchain::block_id_type( "f02910a7115fb826984ce3a432cb371d5d7a99b8" ) },
    {  600000, bts::blockchain::block_id_type( "f278db8722235343c9db9f077fe67c54a5f25f3b" ) },
    {  700000, bts::blockchain::block_id_type( "f120ff9b159661b9ac084a0a69c58dcbd79cbb49" ) },
    {  800000, bts::blockchain::block_id_type( "0e94ad17c598e42e5ec2f522a05bf4df6a1778da" ) },
    {  900000, bts::blockchain::block_id_type( "a78e09bf1fd13bcd7b0959bc0764fe45db0a652d" ) },
    { 1000000, bts::blockchain::block_id_type( "20da1352f86f0fc7d5b42f5e96be86ea5b219b6f" ) },
    { 1100000, bts::blockchain::block_id_type( "bec7da4758ad453a49a9d9d4128acb92a1fdfd04" ) },
    { 1200000, bts::blockchain::block_id_type( "9e514e0f0a17d78be7c0045f9f22a253812c6c92" ) },
    { 1300000, bts::blockchain::block_id_type( "623e5c04a77b7e688299a45bfb1d84a0bf3ea318" ) },
    { 1400000, bts::blockchain::block_id_type( "f7645d369b7a818c4acb94f3bedbcb7747dea9dd" ) },
    { 1500000, bts::blockchain::block_id_type( "a9027b880105fa89f4d0c2bf9a0df328fed3108d" ) },
    { 1600000, bts::blockchain::block_id_type( "1c08742243deda31c663130fca9ab8bd825803c5" ) },
    { 1637000, bts::blockchain::block_id_type( "e9410f765fc402656ebe3b09073bb2bf28017f66" ) }
};

} } // bts::blockchain
<|endoftext|>


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

#include "storage/Devices/EncryptionImpl.h"
#include "storage/Devicegraph.h"

namespace storage
{

    using namespace std;

    Encryption*
    Encryption::create(Devicegraph* devicegraph, const string& name)
    {
	Encryption* ret = new Encryption(new Encryption::Impl(name));
	ret->Device::create(devicegraph);
	return ret;
    }

    Encryption*
    Encryption::load(Devicegraph* devicegraph, const xmlNode* node)
    {
	Encryption* ret = new Encryption(new Encryption::Impl(node));
	ret->Device::load(devicegraph);
	return ret;
    }

    Encryption::Encryption(Impl* impl)
	: BlkDevice(impl)
    {
    }

    MountByType
    Encryption::get_mount_by() const
    {
	return get_impl().get_mount_by();
    }

    void
    Encryption::set_mount_by(MountByType mount_by)
    {
	get_impl().set_mount_by(mount_by);
    }

    void
    Encryption::set_default_mount_by()
    {
	get_impl().set_default_mount_by();
    }

    const std::vector<string>&
    Encryption::get_crypt_options() const
    {
	return get_impl().get_crypt_options().get_opts();;
    }

    void
    Encryption::set_crypt_options(const vector<string>& crypt_options)
    {
	get_impl().set_crypt_options(crypt_options);
    }

    bool
    Encryption::is_in_etc_crypttab() const
    {
	return get_impl().is_in_etc_crypttab();
    }

    void
    Encryption::set_in_etc_crypttab(bool in_etc_crypttab)
    {
	get_impl().set_in_etc_crypttab(in_etc_crypttab);
    }

    Encryption*
    Encryption::clone() const
    {
	return new Encryption(get_impl().clone());
    }

    Encryption::Impl&
    Encryption::get_impl()
    {
	return dynamic_cast<Impl&>(Device::get_impl());
    }

    const Encryption::Impl&
    Encryption::get_impl() const
    {
	return dynamic_cast<const Impl&>(Device::get_impl());
    }

    EncryptionType
    Encryption::get_type() const
    {
	return get_impl().get_type();
    }

    void
    Encryption::set_type(EncryptionType type)
    {
	get_impl().set_type(type);
    }

    const std::string&
    Encryption::get_password() const
    {
	return get_impl().get_password();
    }

    void
    Encryption::set_password(const std::string& password)
    {
	get_impl().set_password(password);
    }

    const std::string&
    Encryption::get_key_file() const
    {
	return get_impl().get_key_file();
    }

    void
    Encryption::set_key_file(const std::string& key_file)
    {
	get_impl().set_key_file(key_file);
    }

    const string&
    Encryption::get_cipher() const
    {
	return get_impl().get_cipher();
    }

    void
    Encryption::set_cipher(const string& cipher)
    {
	get_impl().set_cipher(cipher);
    }

    unsigned int
    Encryption::get_key_size() const
    {
	return get_impl().get_key_size();
    }

    void
    Encryption::set_key_size(unsigned int key_size)
    {
	get_impl().set_key_size(key_size);
    }

    const BlkDevice*
    Encryption::get_blk_device() const
    {
	return get_impl().get_blk_device();
    }

    const string&
    Encryption::get_open_options() const
    {
	return get_impl().get_open_options();
    }

    void
    Encryption::set_open_options(const std::string& open_options)
    {
	get_impl().set_open_options(open_options);
    }

    vector<Encryption*>
    Encryption::get_all(Devicegraph* devicegraph)
    {
	return devicegraph->get_impl().get_devices_of_type<Encryption>();
    }

    vector<const Encryption*>
    Encryption::get_all(const Devicegraph* devicegraph)
    {
	return devicegraph->get_impl().get_devices_of_type<const Encryption>();
    }

    bool
    is_encryption(const Device* device)
    {
	return is_device_of_type<const Encryption>(device);
    }

    Encryption*
    to_encryption(Device* device)
    {
	return to_device_of_type<Encryption>(device);
    }

    const Encryption*
    to_encryption(const Device* device)
    {
	return to_device_of_type<const Encryption>(device);
    }

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

#include "storage/Devices/EncryptionImpl.h"
#include "storage/Devicegraph.h"

namespace storage
{

    using namespace std;

    Encryption*
    Encryption::create(Devicegraph* devicegraph, const string& name)
    {
	Encryption* ret = new Encryption(new Encryption::Impl(name));
	ret->Device::create(devicegraph);
	return ret;
    }

    Encryption*
    Encryption::load(Devicegraph* devicegraph, const xmlNode* node)
    {
	Encryption* ret = new Encryption(new Encryption::Impl(node));
	ret->Device::load(devicegraph);
	return ret;
    }

    Encryption::Encryption(Impl* impl)
	: BlkDevice(impl)
    {
    }

    MountByType
    Encryption::get_mount_by() const
    {
	return get_impl().get_mount_by();
    }

    void
    Encryption::set_mount_by(MountByType mount_by)
    {
	get_impl().set_mount_by(mount_by);
    }

    void
    Encryption::set_default_mount_by()
    {
	get_impl().set_default_mount_by();
    }

    const vector<string>&
    Encryption::get_crypt_options() const
    {
	return get_impl().get_crypt_options().get_opts();;
    }

    void
    Encryption::set_crypt_options(const vector<string>& crypt_options)
    {
	get_impl().set_crypt_options(crypt_options);
    }

    bool
    Encryption::is_in_etc_crypttab() const
    {
	return get_impl().is_in_etc_crypttab();
    }

    void
    Encryption::set_in_etc_crypttab(bool in_etc_crypttab)
    {
	get_impl().set_in_etc_crypttab(in_etc_crypttab);
    }

    Encryption*
    Encryption::clone() const
    {
	return new Encryption(get_impl().clone());
    }

    Encryption::Impl&
    Encryption::get_impl()
    {
	return dynamic_cast<Impl&>(Device::get_impl());
    }

    const Encryption::Impl&
    Encryption::get_impl() const
    {
	return dynamic_cast<const Impl&>(Device::get_impl());
    }

    EncryptionType
    Encryption::get_type() const
    {
	return get_impl().get_type();
    }

    void
    Encryption::set_type(EncryptionType type)
    {
	get_impl().set_type(type);
    }

    const string&
    Encryption::get_password() const
    {
	return get_impl().get_password();
    }

    void
    Encryption::set_password(const string& password)
    {
	get_impl().set_password(password);
    }

    const string&
    Encryption::get_key_file() const
    {
	return get_impl().get_key_file();
    }

    void
    Encryption::set_key_file(const string& key_file)
    {
	get_impl().set_key_file(key_file);
    }

    const string&
    Encryption::get_cipher() const
    {
	return get_impl().get_cipher();
    }

    void
    Encryption::set_cipher(const string& cipher)
    {
	get_impl().set_cipher(cipher);
    }

    unsigned int
    Encryption::get_key_size() const
    {
	return get_impl().get_key_size();
    }

    void
    Encryption::set_key_size(unsigned int key_size)
    {
	get_impl().set_key_size(key_size);
    }

    const BlkDevice*
    Encryption::get_blk_device() const
    {
	return get_impl().get_blk_device();
    }

    const string&
    Encryption::get_open_options() const
    {
	return get_impl().get_open_options();
    }

    void
    Encryption::set_open_options(const string& open_options)
    {
	get_impl().set_open_options(open_options);
    }

    vector<Encryption*>
    Encryption::get_all(Devicegraph* devicegraph)
    {
	return devicegraph->get_impl().get_devices_of_type<Encryption>();
    }

    vector<const Encryption*>
    Encryption::get_all(const Devicegraph* devicegraph)
    {
	return devicegraph->get_impl().get_devices_of_type<const Encryption>();
    }

    bool
    is_encryption(const Device* device)
    {
	return is_device_of_type<const Encryption>(device);
    }

    Encryption*
    to_encryption(Device* device)
    {
	return to_device_of_type<Encryption>(device);
    }

    const Encryption*
    to_encryption(const Device* device)
    {
	return to_device_of_type<const Encryption>(device);
    }

}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2011.  All rights reserved
 */
#ifndef	_Stroika_Foundation_Execution_AtomicOperations_inl_
#define	_Stroika_Foundation_Execution_AtomicOperations_inl_	1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#if		qCompilerAndStdLib_Supports_stdatomic
	#include	<atomic>
#elif	qPlatform_Windows
	#include	<windows.h>
#endif

#include	"../Debug/Assertions.h"

namespace	Stroika {
	namespace	Foundation {
		namespace	Execution {

//tmphack - this API I think I understand, but not the stdc++ one
#if defined(__GCC__)
	#define qDoGCCHackAroundMyBuggyStdcIml 1
#else
	#define qDoGCCHackAroundMyBuggyStdcIml 0
#endif

			inline	int32_t	AtomicIncrement (volatile int32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p));
					#else
						AssertNotImplemented ();
					#endif
				}
			inline	uint32_t	AtomicIncrement (volatile uint32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p)++;
					#elif	qPlatform_Windows
						return static_cast<uint32_t> (::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p)));
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicIncrement (volatile int64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p)++;
					#elif	qPlatform_Win64
						return ::InterlockedIncrement64 (p);
					#endif
				}
			inline	uint64_t	AtomicIncrement (volatile uint64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p)++;
					#elif	qPlatform_Win64
						return ::InterlockedIncrement64 (reinterpret_cast<volatile int64_t*> (p));
					#endif
				}
			#endif

			inline	int32_t	AtomicDecrement (volatile int32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicDecrement (volatile int64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement64 (p);
					#endif
				}
			inline	uint64_t	AtomicDecrement (volatile uint64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement64 (reinterpret_cast<volatile int64_t*> (p));
					#endif
				}
			#endif
			inline	uint32_t	AtomicDecrement (volatile uint32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
					#else
						AssertNotImplemented ();
					#endif
				}

			inline	int32_t	AtomicAdd (volatile int32_t* p, int32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicAdd (volatile int64_t* p, int64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, arg) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (p, arg);
					#endif
				}
			#endif
			inline	uint32_t	AtomicAdd (volatile uint32_t* p, uint32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, arg) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	uint64_t	AtomicAdd (volatile uint64_t* p, uint64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, arg) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), arg);
					#endif
				}
			#endif

			inline	int32_t	AtomicSubtract (volatile int32_t* p, int32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -arg);
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicSubtract (volatile int64_t* p, int64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (p, -arg);
					#endif
				}
			#endif
			inline	uint32_t	AtomicSubtract (volatile uint32_t* p, uint32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -static_cast<int32_t> (arg));
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	uint64_t	AtomicSubtract (volatile uint64_t* p, uint64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), -static_cast<int64_t> (arg));
					#endif
				}
			#endif

		}
	}
}
#endif	/*_Stroika_Foundation_Execution_AtomicOperations_inl_*/
<commit_msg>hopefully fixed gcc BWA for AtomicOperations.inl<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2011.  All rights reserved
 */
#ifndef	_Stroika_Foundation_Execution_AtomicOperations_inl_
#define	_Stroika_Foundation_Execution_AtomicOperations_inl_	1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
#if		qCompilerAndStdLib_Supports_stdatomic
	#include	<atomic>
#elif	qPlatform_Windows
	#include	<windows.h>
#endif

#include	"../Debug/Assertions.h"

namespace	Stroika {
	namespace	Foundation {
		namespace	Execution {

//tmphack - this API I think I understand, but not the stdc++ one
#if defined(__GNUC__)
	#define qDoGCCHackAroundMyBuggyStdcIml 1
#else
	#define qDoGCCHackAroundMyBuggyStdcIml 0
#endif

			inline	int32_t	AtomicIncrement (volatile int32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p));
					#else
						AssertNotImplemented ();
					#endif
				}
			inline	uint32_t	AtomicIncrement (volatile uint32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p)++;
					#elif	qPlatform_Windows
						return static_cast<uint32_t> (::InterlockedIncrement (reinterpret_cast<volatile LONG*> (p)));
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicIncrement (volatile int64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p)++;
					#elif	qPlatform_Win64
						return ::InterlockedIncrement64 (p);
					#endif
				}
			inline	uint64_t	AtomicIncrement (volatile uint64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p)++;
					#elif	qPlatform_Win64
						return ::InterlockedIncrement64 (reinterpret_cast<volatile int64_t*> (p));
					#endif
				}
			#endif

			inline	int32_t	AtomicDecrement (volatile int32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicDecrement (volatile int64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement64 (p);
					#endif
				}
			inline	uint64_t	AtomicDecrement (volatile uint64_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement64 (reinterpret_cast<volatile int64_t*> (p));
					#endif
				}
			#endif
			inline	uint32_t	AtomicDecrement (volatile uint32_t* p)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, 1) - 1;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p)++;
					#elif	qPlatform_Windows
						return ::InterlockedDecrement (reinterpret_cast<volatile LONG*> (p));
					#else
						AssertNotImplemented ();
					#endif
				}

			inline	int32_t	AtomicAdd (volatile int32_t* p, int32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, 1) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicAdd (volatile int64_t* p, int64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, arg) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (p, arg);
					#endif
				}
			#endif
			inline	uint32_t	AtomicAdd (volatile uint32_t* p, uint32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, arg) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), arg);
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	uint64_t	AtomicAdd (volatile uint64_t* p, uint64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_add (p, arg) + arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), arg);
					#endif
				}
			#endif

			inline	int32_t	AtomicSubtract (volatile int32_t* p, int32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int32_t*> ((int32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -arg);
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	int64_t	AtomicSubtract (volatile int64_t* p, int64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<int64_t*> ((int64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (p, -arg);
					#endif
				}
			#endif
			inline	uint32_t	AtomicSubtract (volatile uint32_t* p, uint32_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint32_t*> ((uint32_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd (reinterpret_cast<volatile LONG*> (p), -static_cast<int32_t> (arg));
					#else
						AssertNotImplemented ();
					#endif
				}
			#if		qCompilerAndStdLib_Supports_stdatomic || qPlatform_Win64
			inline	uint64_t	AtomicSubtract (volatile uint64_t* p, uint64_t arg)
				{
					RequireNotNull (p);
					#if		qDoGCCHackAroundMyBuggyStdcIml
						return __sync_fetch_and_sub (p, arg) - arg;
					#endif
					#if		qCompilerAndStdLib_Supports_stdatomic
// A BIT of a WAG about how to use stdc++ atomics... -- LGP 2011-09-02
//Pretty sure wrong but not sure what right way is...
						atomic<uint64_t*> ((uint64_t*)p) += arg;
					#elif	qPlatform_Windows
						return ::InterlockedExchangeAdd64 (reinterpret_cast<volatile int64_t*> (p), -static_cast<int64_t> (arg));
					#endif
				}
			#endif

		}
	}
}
#endif	/*_Stroika_Foundation_Execution_AtomicOperations_inl_*/
<|endoftext|>


<commit_before>/****************************************************************************
 *
 * Copyright 2018 Samsung Electronics All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 ****************************************************************************/

#include <memory>
#include <media/MediaPlayer.h>
#include <media/FileInputDataSource.h>
#include "tc_common.h"

static const char *dummyfilepath = "/mnt/fileinputdatasource.raw";

static void SetUp(void)
{
	FILE *fp = fopen(dummyfilepath, "w");
	fputs("dummydata", fp);
	fclose(fp);
}

static void TearDown()
{
	remove(dummyfilepath);
}

static void utc_media_MediaPlayer_create_p(void)
{
	media::MediaPlayer mp;
	TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_create_n(void)
{
	media::MediaPlayer mp;
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_ERROR);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_destroy_p(void)
{
	media::MediaPlayer mp;
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_OK);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_destroy_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setDataSource_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	source->setSampleRate(20000);
	source->setChannels(2);
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(std::move(source)), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setDataSource_n(void)
{
	media::MediaPlayer mp;
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(nullptr), media::PLAYER_ERROR);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setObserver_p(void)
{
	media::MediaPlayer mp;
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(nullptr), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setObserver_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(nullptr), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_prepare_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));

	TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_prepare_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_unprepare_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_unprepare_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_start_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_start_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_pause_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();
	mp.start();

	TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_pause_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_stop_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();
	mp.start();

	TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_stop_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_getVolume_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	TC_ASSERT_GEQ("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_getVolume_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_LT("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setVolume_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	auto ret =  mp.setVolume(0);
	TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", ret, media::PLAYER_OK);
	TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.getVolume(), 0);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setVolume_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.setVolume(0), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

int utc_media_MediaPlayer_main(void)
{
	SetUp();
	utc_media_MediaPlayer_create_p();
	utc_media_MediaPlayer_create_n();
	utc_media_MediaPlayer_destroy_p();
	utc_media_MediaPlayer_destroy_n();
	utc_media_MediaPlayer_setDataSource_p();
	utc_media_MediaPlayer_setDataSource_n();
	utc_media_MediaPlayer_setObserver_p();
	utc_media_MediaPlayer_setObserver_n();
	utc_media_MediaPlayer_prepare_p();
	utc_media_MediaPlayer_prepare_n();
	utc_media_MediaPlayer_unprepare_p();
	utc_media_MediaPlayer_unprepare_n();
	utc_media_MediaPlayer_start_p();
	utc_media_MediaPlayer_start_n();
	utc_media_MediaPlayer_pause_p();
	utc_media_MediaPlayer_pause_n();
	utc_media_MediaPlayer_stop_p();
	utc_media_MediaPlayer_stop_n();
	utc_media_MediaPlayer_getVolume_p();
	utc_media_MediaPlayer_getVolume_n();
	utc_media_MediaPlayer_setVolume_p();
	utc_media_MediaPlayer_setVolume_n();
	TearDown();
	return 0;
}
<commit_msg>ta_tc/media: Implement MediaPlayer utc<commit_after>/****************************************************************************
 *
 * Copyright 2018 Samsung Electronics All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the License.
 *
 ****************************************************************************/

#include <memory>
#include <media/MediaPlayer.h>
#include <media/FileInputDataSource.h>
#include "tc_common.h"

static const char *dummyfilepath = "/mnt/fileinputdatasource.raw";

class EmptyObserver : public media::MediaPlayerObserverInterface
{
public:
	void onPlaybackStarted(Id id) override;
	void onPlaybackFinished(Id id) override;
	void onPlaybackError(Id id) override;
};

void EmptyObserver::onPlaybackStarted(Id id)
{
}

void EmptyObserver::onPlaybackFinished(Id id)
{
}

void EmptyObserver::onPlaybackError(Id id)
{
}

static void SetUp(void)
{
	FILE *fp = fopen(dummyfilepath, "w");
	fputs("dummydata", fp);
	fclose(fp);
}

static void TearDown()
{
	remove(dummyfilepath);
}

static void utc_media_MediaPlayer_create_p(void)
{
	media::MediaPlayer mp;
	TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_create_n(void)
{
	media::MediaPlayer mp;
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_create", mp.create(), media::PLAYER_ERROR);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_destroy_p(void)
{
	media::MediaPlayer mp;
	auto observer = std::make_shared<EmptyObserver>();
	mp.create();
	mp.setObserver(observer);

	TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_OK);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_destroy_n(void)
{
	/* destroy without create */
	{
		media::MediaPlayer mp;

		TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_ERROR);
	}

	/* destroy At invalid time */
	{
		media::MediaPlayer mp;
		std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
		mp.create();
		mp.setDataSource(std::move(source));
		mp.prepare();

		TC_ASSERT_EQ("utc_media_MediaPlayer_destroy", mp.destroy(), media::PLAYER_ERROR);

		mp.unprepare();
		mp.destroy();
	}

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setDataSource_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	source->setSampleRate(20000);
	source->setChannels(2);
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(std::move(source)), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setDataSource_n(void)
{
	/* setDataSource without create */
	{
		media::MediaPlayer mp;
		std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
		source->setSampleRate(20000);
		source->setChannels(2);

		TC_ASSERT_EQ("setDataSource", mp.setDataSource(std::move(source)), media::PLAYER_ERROR);
	}

	/* setDataSource with nullptr */
	{
		media::MediaPlayer mp;
		mp.create();

		TC_ASSERT_EQ("utc_media_MediaPlayer_setDataSource", mp.setDataSource(nullptr), media::PLAYER_ERROR);

		mp.destroy();
	}

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setObserver_p(void)
{
	media::MediaPlayer mp;
	auto observer = std::make_shared<EmptyObserver>();
	mp.create();

	TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(observer), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setObserver_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_setObserver", mp.setObserver(nullptr), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_prepare_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));

	TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_prepare_n(void)
{
	/* prepare without create */
	{
		media::MediaPlayer mp;

		TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);
	}

	/* prepare twice */
	{
		media::MediaPlayer mp;
		std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
		mp.create();
		mp.setDataSource(std::move(source));
		mp.prepare();

		TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);

		mp.unprepare();
		mp.destroy();
	}

	/* prepare without setting datasource */
	{
		media::MediaPlayer mp;
		mp.create();

		TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);

		mp.destroy();
	}

	/* prepare with invalid datasource */
	{
		media::MediaPlayer mp;
		std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource("non-exist-file")));
		mp.create();
		mp.setDataSource(std::move(source));

		TC_ASSERT_EQ("utc_media_MediaPlayer_prepare", mp.prepare(), media::PLAYER_ERROR);

		mp.destroy();
	}

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_unprepare_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_OK);

	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_unprepare_n(void)
{
	/* unprepare without create */
	{
		media::MediaPlayer mp;

		TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_ERROR);
	}

	/* unprepare twice */
	{
		media::MediaPlayer mp;
		std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
		mp.create();
		mp.setDataSource(std::move(source));
		mp.unprepare();

		TC_ASSERT_EQ("utc_media_MediaPlayer_unprepare", mp.unprepare(), media::PLAYER_ERROR);

		mp.unprepare();
		mp.destroy();
	}

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_start_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_start_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_start", mp.start(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_pause_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();
	mp.start();

	TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_pause_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_pause", mp.pause(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_stop_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();
	mp.start();

	TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_OK);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_stop_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_stop", mp.stop(), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_getVolume_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	TC_ASSERT_GEQ("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_getVolume_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_LT("utc_media_MediaPlayer_getVolume", mp.getVolume(), 0);

	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setVolume_p(void)
{
	media::MediaPlayer mp;
	std::unique_ptr<media::stream::FileInputDataSource> source = std::move(std::unique_ptr<media::stream::FileInputDataSource>(new media::stream::FileInputDataSource(dummyfilepath)));
	mp.create();
	mp.setDataSource(std::move(source));
	mp.prepare();

	auto ret =  mp.setVolume(0);
	TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", ret, media::PLAYER_OK);
	TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.getVolume(), 0);

	mp.unprepare();
	mp.destroy();
	TC_SUCCESS_RESULT();
}

static void utc_media_MediaPlayer_setVolume_n(void)
{
	media::MediaPlayer mp;

	TC_ASSERT_EQ("utc_media_MediaPlayer_setVolume", mp.setVolume(0), media::PLAYER_ERROR);

	TC_SUCCESS_RESULT();
}

int utc_media_MediaPlayer_main(void)
{
	SetUp();
	utc_media_MediaPlayer_create_p();
	utc_media_MediaPlayer_create_n();
	utc_media_MediaPlayer_destroy_p();
	utc_media_MediaPlayer_destroy_n();
	utc_media_MediaPlayer_setDataSource_p();
	utc_media_MediaPlayer_setDataSource_n();
	utc_media_MediaPlayer_setObserver_p();
	utc_media_MediaPlayer_setObserver_n();
	utc_media_MediaPlayer_prepare_p();
	utc_media_MediaPlayer_prepare_n();
	utc_media_MediaPlayer_unprepare_p();
	utc_media_MediaPlayer_unprepare_n();
	utc_media_MediaPlayer_start_p();
	utc_media_MediaPlayer_start_n();
	utc_media_MediaPlayer_pause_p();
	utc_media_MediaPlayer_pause_n();
	utc_media_MediaPlayer_stop_p();
	utc_media_MediaPlayer_stop_n();
	utc_media_MediaPlayer_getVolume_p();
	utc_media_MediaPlayer_getVolume_n();
	utc_media_MediaPlayer_setVolume_p();
	utc_media_MediaPlayer_setVolume_n();
	TearDown();
	return 0;
}
<|endoftext|>


<commit_before>/* Copyright 2019 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "ml_metadata/metadata_store/metadata_access_object_factory.h"

#include <memory>

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "ml_metadata/metadata_store/query_config_executor.h"
#include "ml_metadata/metadata_store/rdbms_metadata_access_object.h"
#include "ml_metadata/util/return_utils.h"

namespace ml_metadata {

namespace {
// Creates MetadataAccessObject (MAO) with the input query config and the
// MetadataSource and returns the created MAO pointer.
// The query config has template queries and other config information.
// The MetadataSource is used to execute specific queries.
absl::Status CreateRDBMSMetadataAccessObject(
    const MetadataSourceQueryConfig& query_config,
    MetadataSource* const metadata_source, absl::optional<int64> schema_version,
    std::unique_ptr<MetadataAccessObject>* result) {
  if (!metadata_source->is_connected())
    MLMD_RETURN_IF_ERROR(metadata_source->Connect());
  std::unique_ptr<QueryExecutor> executor =
      schema_version && *schema_version != query_config.schema_version()
          ? absl::WrapUnique(new QueryConfigExecutor(
                query_config, metadata_source, *schema_version))
          : absl::WrapUnique(
                new QueryConfigExecutor(query_config, metadata_source));
  *result =
      absl::WrapUnique(new RDBMSMetadataAccessObject(std::move(executor)));
  return absl::OkStatus();
}

}  // namespace

absl::Status CreateMetadataAccessObject(
    const MetadataSourceQueryConfig& query_config,
    MetadataSource* const metadata_source,
    std::unique_ptr<MetadataAccessObject>* result) {
  return CreateMetadataAccessObject(query_config, metadata_source,
                                    /*schema_version=*/absl::nullopt,
                                    result);
}

absl::Status CreateMetadataAccessObject(
    const MetadataSourceQueryConfig& query_config,
    MetadataSource* const metadata_source, absl::optional<int64> schema_version,
    std::unique_ptr<MetadataAccessObject>* result) {
  switch (query_config.metadata_source_type()) {
    case UNKNOWN_METADATA_SOURCE:
      return absl::InvalidArgumentError(
          "Metadata source type is not specified.");
    case MYSQL_METADATA_SOURCE:
      return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
                                             schema_version, result);
    case SQLITE_METADATA_SOURCE:
      return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
                                             schema_version, result);
    default:
      return absl::UnimplementedError("Unknown Metadata source type.");
  }
}

}  // namespace ml_metadata
<commit_msg>Makes `enable_bufferwrite` available for MLMD Service through CDPush.<commit_after>/* Copyright 2019 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "ml_metadata/metadata_store/metadata_access_object_factory.h"

#include <memory>

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "ml_metadata/metadata_store/query_config_executor.h"
#include "ml_metadata/metadata_store/rdbms_metadata_access_object.h"
#include "ml_metadata/proto/metadata_source.pb.h"
#include "ml_metadata/util/return_utils.h"

namespace ml_metadata {

namespace {
// Creates MetadataAccessObject (MAO) with the input query config and the
// MetadataSource and returns the created MAO pointer.
// The query config has template queries and other config information.
// The MetadataSource is used to execute specific queries.
absl::Status CreateRDBMSMetadataAccessObject(
    const MetadataSourceQueryConfig& query_config,
    MetadataSource* const metadata_source, absl::optional<int64> schema_version,
    std::unique_ptr<MetadataAccessObject>* result) {
  if (!metadata_source->is_connected())
    MLMD_RETURN_IF_ERROR(metadata_source->Connect());
  std::unique_ptr<QueryExecutor> executor =
      schema_version && *schema_version != query_config.schema_version()
          ? absl::WrapUnique(new QueryConfigExecutor(
                query_config, metadata_source, *schema_version))
          : absl::WrapUnique(
                new QueryConfigExecutor(query_config, metadata_source));
  *result =
      absl::WrapUnique(new RDBMSMetadataAccessObject(std::move(executor)));
  return absl::OkStatus();
}

}  // namespace

absl::Status CreateMetadataAccessObject(
    const MetadataSourceQueryConfig& query_config,
    MetadataSource* const metadata_source,
    std::unique_ptr<MetadataAccessObject>* result) {
  return CreateMetadataAccessObject(query_config, metadata_source,
                                    /*schema_version=*/absl::nullopt,
                                    result);
}

absl::Status CreateMetadataAccessObject(
    const MetadataSourceQueryConfig& query_config,
    MetadataSource* const metadata_source, absl::optional<int64> schema_version,
    std::unique_ptr<MetadataAccessObject>* result) {
  switch (query_config.metadata_source_type()) {
    case UNKNOWN_METADATA_SOURCE:
      return absl::InvalidArgumentError(
          "Metadata source type is not specified.");
    case MYSQL_METADATA_SOURCE:
      return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
                                             schema_version, result);
    case SQLITE_METADATA_SOURCE:
      return CreateRDBMSMetadataAccessObject(query_config, metadata_source,
                                             schema_version, result);
    default:
      return absl::UnimplementedError("Unknown Metadata source type.");
  }
}

}  // namespace ml_metadata
<|endoftext|>


<commit_before>#ifndef LOG_HPP
#define LOG_HPP

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include "time.hpp"
#include "scoped_connection_pool.hpp"
#include "config.hpp"

namespace color {
    enum color_value : char {
        black = 0, red, green, yellow, blue, magenta, cyan, white, normal = -1
    };

    extern struct reset_t {} reset;
    extern struct bold_t {} bold;

    struct set {
        color_value col_;
        bool bold_;

        explicit set(color_value col, bool bold = false) : col_(col), bold_(bold) {}
    };

    std::ostream& operator << (std::ostream& o, set s);
    std::ostream& operator << (std::ostream& o, reset_t s);
    std::ostream& operator << (std::ostream& o, bold_t s);
}

class logger_base {
protected :
    bool color_ = false;
    bool stamp_ = false;

    virtual void print_(color::set s)     {}
    virtual void print_(color::reset_t s) {}
    virtual void print_(color::bold_t s)  {}

public :
    virtual ~logger_base() = 0;

    virtual bool is_open() const = 0;

    void print_stamp() {
        if (stamp_) {
            print(color::set(color::normal,true)); print("[");
            print(color::set(color::cyan,  true)); print(today_str("/"));
            print(color::set(color::normal,true)); print("|");
            print(color::set(color::green, true)); print(time_of_day_str(":"));
            print(color::set(color::normal,true)); print("] ");
            print(color::set(color::normal,false));
        }
    }

    virtual void print(const std::string& s) = 0;

    void print(color::set s) {
        if (color_) {
            print_(s);
        }
    }

    void print(color::reset_t s) {
        if (color_) {
            print_(s);
        }
    }

    void print(color::bold_t s) {
        if (color_) {
            print_(s);
        }
    }

    virtual void endl() = 0;
};

template<typename O>
class ostream_logger_base : public logger_base {
    O& out_;

protected :
    scoped_connection_pool pool_;

public :
    ~ostream_logger_base() override {}

    ostream_logger_base(O& o) : out_(o) {}

    void print(const std::string& t) override {
        out_ << t;
    }

    void print_(color::set s) override {
        out_ << s;
    }

    void print_(color::reset_t s) override {
        out_ << s;
    }

    void print_(color::bold_t s) override {
        out_ << s;
    }

    void endl() override {
        out_ << std::endl;
    }
};

template<typename O>
class ostream_logger : public ostream_logger_base<O> {
    O out_;

public :
    ~ostream_logger() override {}

    ostream_logger(config::state& conf, const std::string& name) :
        ostream_logger_base<O>(out_) {

        std::string file;
        if (conf.get_value("log."+name+".file", file, "") && !file.empty()) {
            bool append = true;
            conf.get_value("log."+name+".append", append, append);
            if (append) {
                out_.open(file, std::ios::app);
            } else {
                out_.open(file);
            }

            this->pool_ << conf.bind("log."+name+".color", this->color_);
            this->pool_ << conf.bind("log."+name+".stamp", this->stamp_);
        }
    }

    bool is_open() const override {
        return out_.is_open();
    }
};

class cout_logger : public ostream_logger_base<std::ostream> {
public :
    ~cout_logger() override {}

    cout_logger(config::state& conf) : ostream_logger_base<std::ostream>(std::cout) {
        pool_ << conf.bind("log.cout.color", color_);
        pool_ << conf.bind("log.cout.stamp", stamp_);
    }

    bool is_open() const override {
        return true;
    }
};

namespace logger_impl {
    template<typename T>
    struct has_std_to_string_t {
        template <typename U> static std::true_type  dummy(typename std::decay<
            decltype(std::to_string(std::declval<U>()))>::type*);
        template <typename U> static std::false_type dummy(...);
        using type = decltype(dummy<T>(0));
    };

    template<typename T>
    struct has_adl_to_string_t {
        template <typename U> static std::true_type  dummy(typename std::decay<
            decltype(to_string(std::declval<U>()))>::type*);
        template <typename U> static std::false_type dummy(...);
        using type = decltype(dummy<T>(0));
    };

    template<typename T>
    using has_to_string = std::integral_constant<bool, has_std_to_string_t<T>::type::value ||
                                                       has_adl_to_string_t<T>::type::value>;
}

class logger {
    std::vector<std::unique_ptr<logger_base>> out_;

public :
    logger() = default;

private :
    template<typename T>
    void forward_print_(const T& t) {
        for (auto& o : out_) {
            if (o->is_open()) {
                o->print(t);
            }
        }
    }

    template<typename T>
    void do_print__(const T& t, std::true_type) {
        using std::to_string;
        forward_print_(to_string(t));
    }

    template<typename T>
    void do_print__(const T& t, std::false_type) {
        std::ostringstream ss;
        ss << t;
        forward_print_(ss.str());
    }

    template<typename T>
    void print__(const T& t) {
        do_print__(t, logger_impl::has_to_string<T>{});
    }

    void print__(const std::string& str) {
        forward_print_(str);
    }

    void print__(const char* str) {
        forward_print_(std::string(str));
    }

    void print__(color::set s) {
        forward_print_(s);
    }

    void print__(color::reset_t s) {
        forward_print_(s);
    }

    void print__(color::bold_t s) {
        forward_print_(s);
    }

private :
    template<typename ... Args>
    void print_(Args&& ... args) {
        int v[] = {(print__(std::forward<Args>(args)), 0)...};
    }

    void print_stamp_() {
        for (auto& o : out_) {
            if (o->is_open()) {
                o->print_stamp();
            }
        }
    }

    void endl_() {
        for (auto& o : out_) {
            if (o->is_open()) {
                o->endl();
            }
        }
    }

public :
    template<typename T, typename ... Args>
    void add_output(Args&&... args) {
        out_.emplace_back(new T(std::forward<Args>(args)...));
    }

    template<typename ... Args>
    void print(Args&&... args) {
        print_stamp_();
        print_(std::forward<Args>(args)...);
        endl_();
    }

    template<typename ... Args>
    void print_header(color::color_value v, const std::string hdr, Args&&... args) {
        print_stamp_();
        print_(color::set(v, true));
        print_(hdr+": ");
        print_(color::reset);
        print_(std::forward<Args>(args)...);
        endl_();
    }

    template<typename ... Args>
    void error(Args&& ... args) {
        print_header(color::red, "error", std::forward<Args>(args)...);
    }

    template<typename ... Args>
    void warning(Args&& ... args) {
        print_header(color::yellow, "warning", std::forward<Args>(args)...);
    }

    template<typename ... Args>
    void note(Args&& ... args) {
        print_header(color::blue, "note", std::forward<Args>(args)...);
    }

    template<typename ... Args>
    void reason(Args&& ... args) {
        print_header(color::blue, "reason", std::forward<Args>(args)...);
    }
};

using file_logger = ostream_logger<std::ofstream>;

extern logger cout;

#endif

<commit_msg>Extended logger to support enumerations.<commit_after>#ifndef LOG_HPP
#define LOG_HPP

#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include "time.hpp"
#include "scoped_connection_pool.hpp"
#include "config.hpp"

namespace color {
    enum color_value : char {
        black = 0, red, green, yellow, blue, magenta, cyan, white, normal = -1
    };

    extern struct reset_t {} reset;
    extern struct bold_t {} bold;

    struct set {
        color_value col_;
        bool bold_;

        explicit set(color_value col, bool bold = false) : col_(col), bold_(bold) {}
    };

    std::ostream& operator << (std::ostream& o, set s);
    std::ostream& operator << (std::ostream& o, reset_t s);
    std::ostream& operator << (std::ostream& o, bold_t s);
}

class logger_base {
protected :
    bool color_ = false;
    bool stamp_ = false;

    virtual void print_(color::set s)     {}
    virtual void print_(color::reset_t s) {}
    virtual void print_(color::bold_t s)  {}

public :
    virtual ~logger_base() = 0;

    virtual bool is_open() const = 0;

    void print_stamp() {
        if (stamp_) {
            print(color::set(color::normal,true)); print("[");
            print(color::set(color::cyan,  true)); print(today_str("/"));
            print(color::set(color::normal,true)); print("|");
            print(color::set(color::green, true)); print(time_of_day_str(":"));
            print(color::set(color::normal,true)); print("] ");
            print(color::set(color::normal,false));
        }
    }

    virtual void print(const std::string& s) = 0;

    void print(color::set s) {
        if (color_) {
            print_(s);
        }
    }

    void print(color::reset_t s) {
        if (color_) {
            print_(s);
        }
    }

    void print(color::bold_t s) {
        if (color_) {
            print_(s);
        }
    }

    virtual void endl() = 0;
};

template<typename O>
class ostream_logger_base : public logger_base {
    O& out_;

protected :
    scoped_connection_pool pool_;

public :
    ~ostream_logger_base() override {}

    ostream_logger_base(O& o) : out_(o) {}

    void print(const std::string& t) override {
        out_ << t;
    }

    void print_(color::set s) override {
        out_ << s;
    }

    void print_(color::reset_t s) override {
        out_ << s;
    }

    void print_(color::bold_t s) override {
        out_ << s;
    }

    void endl() override {
        out_ << std::endl;
    }
};

template<typename O>
class ostream_logger : public ostream_logger_base<O> {
    O out_;

public :
    ~ostream_logger() override {}

    ostream_logger(config::state& conf, const std::string& name) :
        ostream_logger_base<O>(out_) {

        std::string file;
        if (conf.get_value("log."+name+".file", file, "") && !file.empty()) {
            bool append = true;
            conf.get_value("log."+name+".append", append, append);
            if (append) {
                out_.open(file, std::ios::app);
            } else {
                out_.open(file);
            }

            this->pool_ << conf.bind("log."+name+".color", this->color_);
            this->pool_ << conf.bind("log."+name+".stamp", this->stamp_);
        }
    }

    bool is_open() const override {
        return out_.is_open();
    }
};

class cout_logger : public ostream_logger_base<std::ostream> {
public :
    ~cout_logger() override {}

    cout_logger(config::state& conf) : ostream_logger_base<std::ostream>(std::cout) {
        pool_ << conf.bind("log.cout.color", color_);
        pool_ << conf.bind("log.cout.stamp", stamp_);
    }

    bool is_open() const override {
        return true;
    }
};

namespace logger_impl {
    template<typename T>
    struct has_std_to_string_t {
        template <typename U> static std::true_type  dummy(typename std::decay<
            decltype(std::to_string(std::declval<U>()))>::type*);
        template <typename U> static std::false_type dummy(...);
        using type = decltype(dummy<T>(0));
    };

    template<typename T>
    struct has_adl_to_string_t {
        template <typename U> static std::true_type  dummy(typename std::decay<
            decltype(to_string(std::declval<U>()))>::type*);
        template <typename U> static std::false_type dummy(...);
        using type = decltype(dummy<T>(0));
    };

    template<typename T>
    using has_to_string = std::integral_constant<bool, has_std_to_string_t<T>::type::value ||
                                                       has_adl_to_string_t<T>::type::value>;
}

class logger {
    std::vector<std::unique_ptr<logger_base>> out_;

public :
    logger() = default;

private :
    template<typename T>
    void forward_print_(const T& t) {
        for (auto& o : out_) {
            if (o->is_open()) {
                o->print(t);
            }
        }
    }

    template<typename T>
    void do_print__(const T& t, std::true_type, std::false_type) {
        using std::to_string;
        forward_print_(to_string(t));
    }

    template<typename T>
    void do_print__(const T& t, std::false_type, std::false_type) {
        std::ostringstream ss;
        ss << t;
        forward_print_(ss.str());
    }

    template<typename T, typename TS>
    void do_print__(const T& t, TS, std::true_type) {
        using std::to_string;
        forward_print_(to_string(static_cast<typename std::underlying_type<T>::type>(t)));
    }

    template<typename T>
    void print__(const T& t) {
        do_print__(t, logger_impl::has_to_string<T>{}, std::is_enum<T>{});
    }

    void print__(const std::string& str) {
        forward_print_(str);
    }

    void print__(const char* str) {
        forward_print_(std::string(str));
    }

    void print__(color::set s) {
        forward_print_(s);
    }

    void print__(color::reset_t s) {
        forward_print_(s);
    }

    void print__(color::bold_t s) {
        forward_print_(s);
    }

private :
    template<typename ... Args>
    void print_(Args&& ... args) {
        int v[] = {(print__(std::forward<Args>(args)), 0)...};
    }

    void print_stamp_() {
        for (auto& o : out_) {
            if (o->is_open()) {
                o->print_stamp();
            }
        }
    }

    void endl_() {
        for (auto& o : out_) {
            if (o->is_open()) {
                o->endl();
            }
        }
    }

public :
    template<typename T, typename ... Args>
    void add_output(Args&&... args) {
        out_.emplace_back(new T(std::forward<Args>(args)...));
    }

    template<typename ... Args>
    void print(Args&&... args) {
        print_stamp_();
        print_(std::forward<Args>(args)...);
        endl_();
    }

    template<typename ... Args>
    void print_header(color::color_value v, const std::string hdr, Args&&... args) {
        print_stamp_();
        print_(color::set(v, true));
        print_(hdr+": ");
        print_(color::reset);
        print_(std::forward<Args>(args)...);
        endl_();
    }

    template<typename ... Args>
    void error(Args&& ... args) {
        print_header(color::red, "error", std::forward<Args>(args)...);
    }

    template<typename ... Args>
    void warning(Args&& ... args) {
        print_header(color::yellow, "warning", std::forward<Args>(args)...);
    }

    template<typename ... Args>
    void note(Args&& ... args) {
        print_header(color::blue, "note", std::forward<Args>(args)...);
    }

    template<typename ... Args>
    void reason(Args&& ... args) {
        print_header(color::blue, "reason", std::forward<Args>(args)...);
    }
};

using file_logger = ostream_logger<std::ofstream>;

extern logger cout;

#endif

<|endoftext|>


<commit_before><commit_msg>Fix android compilation: missing cast when formatting value in string (#22382)<commit_after><|endoftext|>