<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "StressDivergenceTruss.h"

#include "Material.h"
#include "SymmElasticityTensor.h"

template<>
InputParameters validParams<StressDivergenceTruss>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addCoupledVar("disp_x", "The x displacement");
  params.addCoupledVar("disp_y", "The y displacement");
  params.addCoupledVar("disp_z", "The z displacement");
  params.addCoupledVar("temp", "The temperature");
  params.addCoupledVar("area", "Cross-sectional area of truss element");
  params.addParam<std::string>("appended_property_name", "", "Name appended to material properties to make them unique");

  params.set<bool>("use_displaced_mesh") = true;

  return params;
}

StressDivergenceTruss::StressDivergenceTruss(const std::string & name, InputParameters parameters)
  :Kernel(name, parameters),
   _axial_stress(getMaterialProperty<Real>("axial_stress" + getParam<std::string>("appended_property_name"))),
   _E_over_L(getMaterialProperty<Real>("e_over_l" + getParam<std::string>("appended_property_name"))),
   _component(getParam<unsigned int>("component")),
   _xdisp_coupled(isCoupled("disp_x")),
   _ydisp_coupled(isCoupled("disp_y")),
   _zdisp_coupled(isCoupled("disp_z")),
   _temp_coupled(isCoupled("temp")),
   _xdisp_var(_xdisp_coupled ? coupled("disp_x") : 0),
   _ydisp_var(_ydisp_coupled ? coupled("disp_y") : 0),
   _zdisp_var(_zdisp_coupled ? coupled("disp_z") : 0),
   _temp_var(_temp_coupled ? coupled("temp") : 0),
   _area(coupledValue("area")),
   _orientation(NULL)
{}

void
StressDivergenceTruss::initialSetup()
{
  // Assume that all trusses are one dimensional in the call below
  _orientation = &_subproblem.assembly(_tid).getFE(FEType(), 1)->get_dxyzdxi();
}

void
StressDivergenceTruss::computeResidual()
{
  DenseVector<Number> & re = _assembly.residualBlock(_var.number());
  mooseAssert(re.size() == 2, "Truss elements must have two nodes");
  _local_re.resize(re.size());
  _local_re.zero();

  RealGradient orientation( (*_orientation)[0] );
  orientation /= orientation.size();
  VectorValue<Real> force_local = _axial_stress[0] * _area[0] * orientation;

  int sign(-_test[0][0]/std::abs(_test[0][0]));
  _local_re(0) = sign * force_local(_component);
  _local_re(1) = -_local_re(0);

  re += _local_re;

  if (_has_save_in)
  {
    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
    for (unsigned int i=0; i<_save_in.size(); i++)
      _save_in[i]->sys().solution().add_vector(_local_re, _save_in[i]->dofIndices());
  }
}

void
StressDivergenceTruss::computeStiffness(ColumnMajorMatrix & stiff_global)
{
  RealGradient orientation( (*_orientation)[0] );
  orientation /= orientation.size();

  // Now get a rotation matrix
  // The orientation is the first row of the matrix.
  // Need two other directions.
  VectorValue<Real> & row1( orientation );
  VectorValue<Real> row3( row1 );
  unsigned zero_index(0);
  if (row3(1) != 0)
  {
    zero_index = 1;
  }
  if (row3(2) != 0)
  {
    zero_index = 2;
  }
  row3(zero_index) += 1;
  VectorValue<Real> row2 = orientation.cross( row3 );
  row3 = orientation.cross( row2 );

  Real k = _E_over_L[0] * _area[0];

  stiff_global(0,0) = row1(0)*row1(0)*k;
  stiff_global(0,1) = row1(0)*row2(0)*k;
  stiff_global(0,2) = row1(0)*row3(0)*k;
  stiff_global(1,0) = row2(0)*row1(0)*k;
  stiff_global(1,1) = row2(0)*row2(0)*k;
  stiff_global(1,2) = row2(0)*row3(0)*k;
  stiff_global(2,0) = row3(0)*row1(0)*k;
  stiff_global(2,1) = row3(0)*row2(0)*k;
  stiff_global(2,2) = row3(0)*row3(0)*k;
}

void
StressDivergenceTruss::computeJacobian()
{

  DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), _var.number());
  _local_ke.resize(ke.m(), ke.n());
  _local_ke.zero();

  ColumnMajorMatrix stiff_global(3,3);
  computeStiffness( stiff_global );

  for (_i = 0; _i < _test.size(); _i++)
  {
    for (_j = 0; _j < _phi.size(); _j++)
    {
      int sign( _i == _j ? 1 : -1 );
      _local_ke(_i, _j) += sign * stiff_global(_component, _component);
    }
  }

  ke += _local_ke;

  if (_has_diag_save_in)
  {
    unsigned int rows = ke.m();
    DenseVector<Number> diag(rows);
    for (unsigned int i=0; i<rows; i++)
      diag(i) = _local_ke(i,i);

    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
    for (unsigned int i=0; i<_diag_save_in.size(); i++)
      _diag_save_in[i]->sys().solution().add_vector(diag, _diag_save_in[i]->dofIndices());
  }
}

void
StressDivergenceTruss::computeOffDiagJacobian(unsigned int jvar)
{
  if (jvar == _var.number())
  {
    computeJacobian();
  }
  else
  {
    unsigned int coupled_component = 0;

    bool active(false);

    if ( _xdisp_coupled && jvar == _xdisp_var )
    {
      coupled_component = 0;
      active = true;
    }
    else if ( _ydisp_coupled && jvar == _ydisp_var )
    {
      coupled_component = 1;
      active = true;
    }
    else if ( _zdisp_coupled && jvar == _zdisp_var )
    {
      coupled_component = 2;
      active = true;
    }

    DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), jvar);

    if (active)
    {
      ColumnMajorMatrix stiff_global(3,3);
      computeStiffness( stiff_global );

      for (_i=0; _i<_test.size(); _i++)
      {
        for (_j=0; _j<_phi.size(); _j++)
        {
          int sign( _i == _j ? 1 : -1 );
          ke(_i,_j) += sign * stiff_global(_component, coupled_component);
        }
      }
    }
    else if ( false ) // Need some code here for coupling with temperature
    {
    }
  }
}
<commit_msg>Correct Jacobian for truss elements closes #5271<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/
#include "StressDivergenceTruss.h"

#include "Material.h"
#include "SymmElasticityTensor.h"

template<>
InputParameters validParams<StressDivergenceTruss>()
{
  InputParameters params = validParams<Kernel>();
  params.addRequiredParam<unsigned int>("component", "An integer corresponding to the direction the variable this kernel acts in. (0 for x, 1 for y, 2 for z)");
  params.addCoupledVar("disp_x", "The x displacement");
  params.addCoupledVar("disp_y", "The y displacement");
  params.addCoupledVar("disp_z", "The z displacement");
  params.addCoupledVar("temp", "The temperature");
  params.addCoupledVar("area", "Cross-sectional area of truss element");
  params.addParam<std::string>("appended_property_name", "", "Name appended to material properties to make them unique");

  params.set<bool>("use_displaced_mesh") = true;

  return params;
}

StressDivergenceTruss::StressDivergenceTruss(const std::string & name, InputParameters parameters)
  :Kernel(name, parameters),
   _axial_stress(getMaterialProperty<Real>("axial_stress" + getParam<std::string>("appended_property_name"))),
   _E_over_L(getMaterialProperty<Real>("e_over_l" + getParam<std::string>("appended_property_name"))),
   _component(getParam<unsigned int>("component")),
   _xdisp_coupled(isCoupled("disp_x")),
   _ydisp_coupled(isCoupled("disp_y")),
   _zdisp_coupled(isCoupled("disp_z")),
   _temp_coupled(isCoupled("temp")),
   _xdisp_var(_xdisp_coupled ? coupled("disp_x") : 0),
   _ydisp_var(_ydisp_coupled ? coupled("disp_y") : 0),
   _zdisp_var(_zdisp_coupled ? coupled("disp_z") : 0),
   _temp_var(_temp_coupled ? coupled("temp") : 0),
   _area(coupledValue("area")),
   _orientation(NULL)
{}

void
StressDivergenceTruss::initialSetup()
{
  // Assume that all trusses are one dimensional in the call below
  _orientation = &_subproblem.assembly(_tid).getFE(FEType(), 1)->get_dxyzdxi();
}

void
StressDivergenceTruss::computeResidual()
{
  DenseVector<Number> & re = _assembly.residualBlock(_var.number());
  mooseAssert(re.size() == 2, "Truss elements must have two nodes");
  _local_re.resize(re.size());
  _local_re.zero();

  RealGradient orientation( (*_orientation)[0] );
  orientation /= orientation.size();
  VectorValue<Real> force_local = _axial_stress[0] * _area[0] * orientation;

  int sign(-_test[0][0]/std::abs(_test[0][0]));
  _local_re(0) = sign * force_local(_component);
  _local_re(1) = -_local_re(0);

  re += _local_re;

  if (_has_save_in)
  {
    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
    for (unsigned int i=0; i<_save_in.size(); i++)
      _save_in[i]->sys().solution().add_vector(_local_re, _save_in[i]->dofIndices());
  }
}

void
StressDivergenceTruss::computeStiffness(ColumnMajorMatrix & stiff_global)
{
  RealGradient orientation( (*_orientation)[0] );
  orientation /= orientation.size();

  Real k = _E_over_L[0] * _area[0];
  stiff_global(0,0) = orientation(0)*orientation(0)*k;
  stiff_global(0,1) = orientation(0)*orientation(1)*k;
  stiff_global(0,2) = orientation(0)*orientation(2)*k;
  stiff_global(1,0) = orientation(1)*orientation(0)*k;
  stiff_global(1,1) = orientation(1)*orientation(1)*k;
  stiff_global(1,2) = orientation(1)*orientation(2)*k;
  stiff_global(2,0) = orientation(2)*orientation(0)*k;
  stiff_global(2,1) = orientation(2)*orientation(1)*k;
  stiff_global(2,2) = orientation(2)*orientation(2)*k;
}

void
StressDivergenceTruss::computeJacobian()
{

  DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), _var.number());
  _local_ke.resize(ke.m(), ke.n());
  _local_ke.zero();

  ColumnMajorMatrix stiff_global(3,3);
  computeStiffness( stiff_global );

  for (_i = 0; _i < _test.size(); _i++)
  {
    for (_j = 0; _j < _phi.size(); _j++)
    {
      int sign( _i == _j ? 1 : -1 );
      _local_ke(_i, _j) += sign * stiff_global(_component, _component);
    }
  }

  ke += _local_ke;

  if (_has_diag_save_in)
  {
    unsigned int rows = ke.m();
    DenseVector<Number> diag(rows);
    for (unsigned int i=0; i<rows; i++)
      diag(i) = _local_ke(i,i);

    Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx);
    for (unsigned int i=0; i<_diag_save_in.size(); i++)
      _diag_save_in[i]->sys().solution().add_vector(diag, _diag_save_in[i]->dofIndices());
  }
}

void
StressDivergenceTruss::computeOffDiagJacobian(unsigned int jvar)
{
  if (jvar == _var.number())
  {
    computeJacobian();
  }
  else
  {
    unsigned int coupled_component = 0;

    bool active(false);

    if ( _xdisp_coupled && jvar == _xdisp_var )
    {
      coupled_component = 0;
      active = true;
    }
    else if ( _ydisp_coupled && jvar == _ydisp_var )
    {
      coupled_component = 1;
      active = true;
    }
    else if ( _zdisp_coupled && jvar == _zdisp_var )
    {
      coupled_component = 2;
      active = true;
    }

    DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), jvar);

    if (active)
    {
      ColumnMajorMatrix stiff_global(3,3);
      computeStiffness( stiff_global );

      for (_i=0; _i<_test.size(); _i++)
      {
        for (_j=0; _j<_phi.size(); _j++)
        {
          int sign( _i == _j ? 1 : -1 );
          ke(_i,_j) += sign * stiff_global(_component, coupled_component);
        }
      }
    }
    else if ( false ) // Need some code here for coupling with temperature
    {
    }
  }
}
<|endoftext|>


<commit_before>//===-- llvm-c++filt.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Demangle/Demangle.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <iostream>

using namespace llvm;

static cl::opt<bool>
    Types("types",
          cl::desc("attempt to demangle types as well as function names"),
          cl::init(false));
static cl::alias TypesShort("t", cl::desc("alias for --types"),
                            cl::aliasopt(Types));

static cl::list<std::string>
Decorated(cl::Positional, cl::desc("<mangled>"), cl::ZeroOrMore);

static void demangle(llvm::raw_ostream &OS, const std::string &Mangled) {
  int Status;
  char *Demangled = nullptr;
  if (Types || ((Mangled.size() >= 2 && Mangled.compare(0, 2, "_Z")) ||
                (Mangled.size() >= 4 && Mangled.compare(0, 4, "___Z"))))
    Demangled = itaniumDemangle(Mangled.c_str(), nullptr, nullptr, &Status);
  OS << (Demangled ? Demangled : Mangled) << '\n';
  free(Demangled);
}

int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal(argv[0]);
  PrettyStackTraceProgram X(argc, argv);

  cl::ParseCommandLineOptions(argc, argv, "llvm symbol undecoration tool\n");

  if (Decorated.empty())
    for (std::string Mangled; std::getline(std::cin, Mangled);)
      demangle(llvm::outs(), Mangled);
  else
    for (const auto &Symbol : Decorated)
      demangle(llvm::outs(), Symbol);

  return EXIT_SUCCESS;
}
<commit_msg>llvm-cxxfilt: support the `-s` option<commit_after>//===-- llvm-c++filt.cpp --------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Demangle/Demangle.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#include <cstdlib>
#include <iostream>

using namespace llvm;

enum Style {
  Auto,  ///< auto-detect mangling
  GNU,   ///< GNU
  Lucid, ///< Lucid compiler (lcc)
  ARM,
  HP,    ///< HP compiler (xCC)
  EDG,   ///< EDG compiler
  GNUv3, ///< GNU C++ v3 ABI
  Java,  ///< Java (gcj)
  GNAT   ///< ADA copiler (gnat)
};
static cl::opt<Style>
    Format("format", cl::desc("decoration style"),
           cl::values(clEnumValN(Auto, "auto", "auto-detect style"),
                      clEnumValN(GNU, "gnu", "GNU (itanium) style")),
           cl::init(Auto));
static cl::alias FormatShort("s", cl::desc("alias for --format"),
                             cl::aliasopt(Format));

static cl::opt<bool>
    Types("types",
          cl::desc("attempt to demangle types as well as function names"),
          cl::init(false));
static cl::alias TypesShort("t", cl::desc("alias for --types"),
                            cl::aliasopt(Types));

static cl::list<std::string>
Decorated(cl::Positional, cl::desc("<mangled>"), cl::ZeroOrMore);

static void demangle(llvm::raw_ostream &OS, const std::string &Mangled) {
  int Status;
  char *Demangled = nullptr;
  if (Types || ((Mangled.size() >= 2 && Mangled.compare(0, 2, "_Z")) ||
                (Mangled.size() >= 4 && Mangled.compare(0, 4, "___Z"))))
    Demangled = itaniumDemangle(Mangled.c_str(), nullptr, nullptr, &Status);
  OS << (Demangled ? Demangled : Mangled) << '\n';
  free(Demangled);
}

int main(int argc, char **argv) {
  sys::PrintStackTraceOnErrorSignal(argv[0]);
  PrettyStackTraceProgram X(argc, argv);

  cl::ParseCommandLineOptions(argc, argv, "llvm symbol undecoration tool\n");

  if (Decorated.empty())
    for (std::string Mangled; std::getline(std::cin, Mangled);)
      demangle(llvm::outs(), Mangled);
  else
    for (const auto &Symbol : Decorated)
      demangle(llvm::outs(), Symbol);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "oox/dump/dffdumper.hxx"

#if OOX_INCLUDE_DUMPER

namespace oox {
namespace dump {

// ============================================================================

namespace {

const sal_uInt16 DFF_ID_BSE                 = 0xF007;   /// BLIP store entry.
const sal_uInt16 DFF_ID_BSTORECONTAINER     = 0xF001;   /// BLIP store container.
const sal_uInt16 DFF_ID_CHILDANCHOR         = 0xF00F;   /// Child anchor (in groups).
const sal_uInt16 DFF_ID_CLIENTANCHOR        = 0xF010;   /// Client anchor.
const sal_uInt16 DFF_ID_DG                  = 0xF008;   /// Drawing.
const sal_uInt16 DFF_ID_DGG                 = 0xF006;   /// Drawing group.
const sal_uInt16 DFF_ID_OPT                 = 0xF00B;   /// Property set.
const sal_uInt16 DFF_ID_OPT2                = 0xF121;   /// Secondary property set.
const sal_uInt16 DFF_ID_OPT3                = 0xF122;   /// Ternary property set.
const sal_uInt16 DFF_ID_SP                  = 0xF00A;   /// Shape.
const sal_uInt16 DFF_ID_SPGR                = 0xF009;   /// Shape group.
const sal_uInt16 DFF_ID_SPLITMENUCOLORS     = 0xF11E;   /// Current toolbar colors.

const sal_uInt16 DFF_OPT_IDMASK             = 0x3FFF;
const sal_uInt16 DFF_OPT_PICTURE            = 0x4000;
const sal_uInt16 DFF_OPT_COMPLEX            = 0x8000;
const sal_uInt16 DFF_OPT_FLAGSMASK          = 0x003F;

} // namespace

// ============================================================================

bool DffStreamObject::implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize )
{
    sal_uInt16 nRecId;
    rBaseStrm >> mnInstVer >> nRecId >> mnRealSize;
    ornRecId = nRecId;
    ornRecSize = isContainer() ? 0 : mnRealSize;
    return !rBaseStrm.isEof();
}

void DffStreamObject::implWriteExtHeader()
{
    const sal_Char* pcListName = "DFF-RECORD-INST";
    switch( getRecId() )
    {
        case DFF_ID_BSE:                pcListName = "DFFBSE-RECORD-INST";          break;  // BLIP type
        case DFF_ID_BSTORECONTAINER:    pcListName = "DFFBSTORECONT-RECORD-INST";   break;  // BLIP count
        case DFF_ID_DG:                 pcListName = "DFFDG-RECORD-INST";           break;  // drawing ID
        case DFF_ID_OPT:                pcListName = "DFFOPT-RECORD-INST";          break;  // property count
        case DFF_ID_SP:                 pcListName = "DFFSP-RECORD-INST";           break;  // shape type
        case DFF_ID_SPLITMENUCOLORS:    pcListName = "DFFSPLITMENUC-RECORD-INST";   break;  // number of colors
    }
    MultiItemsGuard aMultiGuard( mxOut );
    writeHexItem( "instance", mnInstVer, pcListName );
    if( isContainer() ) writeDecItem( "container-size", mnRealSize );
}

void DffStreamObject::implDumpRecordBody()
{
    switch( getRecId() )
    {
        case DFF_ID_BSE:
            dumpDec< sal_uInt8 >( "win-type", "DFFBSE-TYPE" );
            dumpDec< sal_uInt8 >( "mac-type", "DFFBSE-TYPE" );
            dumpGuid( "guid" );
            dumpDec< sal_uInt16 >( "tag" );
            dumpDec< sal_uInt32 >( "blip-size" );
            dumpDec< sal_uInt32 >( "blip-refcount" );
            dumpDec< sal_uInt32 >( "blip-streampos" );
            dumpDec< sal_uInt8 >( "blip-usage", "DFFBSE-USAGE" );
            dumpDec< sal_uInt8 >( "blip-name-len" );
            dumpUnused( 2 );
        break;

        case DFF_ID_CHILDANCHOR:
            dumpDec< sal_uInt32 >( "left" );
            dumpDec< sal_uInt32 >( "top" );
            dumpDec< sal_uInt32 >( "right" );
            dumpDec< sal_uInt32 >( "bottom" );
        break;

        case DFF_ID_CLIENTANCHOR:
            implDumpClientAnchor();
        break;

        case DFF_ID_DG:
            dumpDec< sal_uInt32 >( "shape-count" );
            dumpHex< sal_uInt32 >( "max-shape-id", "CONV-DEC" );
        break;

        case DFF_ID_DGG:
        {
            dumpHex< sal_uInt32 >( "max-shape-id", "CONV-DEC" );
            sal_uInt32 nClusters = dumpDec< sal_uInt32 >( "id-cluster-count" );
            dumpDec< sal_uInt32 >( "shape-count" );
            dumpDec< sal_uInt32 >( "drawing-count" );
            mxOut->resetItemIndex( 1 );
            TableGuard aTabGuard( mxOut, 15, 16 );
            for( sal_uInt32 nCluster = 1; !mxStrm->isEof() && (nCluster < nClusters); ++nCluster )
            {
                MultiItemsGuard aMultiGuard( mxOut );
                writeEmptyItem( "#cluster" );
                dumpDec< sal_uInt32 >( "drawing-id" );
                dumpHex< sal_uInt32 >( "next-free-id", "CONV-DEC" );
            }
        }
        break;

        case DFF_ID_OPT:
        case DFF_ID_OPT2:
        case DFF_ID_OPT3:
            dumpDffOpt();
        break;

        case DFF_ID_SP:
            dumpHex< sal_uInt32 >( "shape-id", "CONV-DEC" );
            dumpHex< sal_uInt32 >( "shape-flags", "DFFSP-FLAGS" );
        break;

        case DFF_ID_SPGR:
            dumpDec< sal_uInt32 >( "left" );
            dumpDec< sal_uInt32 >( "top" );
            dumpDec< sal_uInt32 >( "right" );
            dumpDec< sal_uInt32 >( "bottom" );
        break;

        case DFF_ID_SPLITMENUCOLORS:
            dumpDffSimpleColor( "fill-color" );
            dumpDffSimpleColor( "line-color" );
            dumpDffSimpleColor( "shadow-color" );
            dumpDffSimpleColor( "3d-color" );
        break;
    }
}

void DffStreamObject::implDumpClientAnchor()
{
}

sal_uInt32 DffStreamObject::dumpDffSimpleColor( const String& rName )
{
    return dumpHex< sal_uInt32 >( rName, "DFF-SIMPLE-COLOR" );
}

namespace {

enum PropType { PROPTYPE_BINARY, PROPTYPE_STRING, PROPTYPE_BLIP, PROPTYPE_COLORARRAY };

struct PropInfo
{
    OUString            maName;
    PropType            meType;
    sal_uInt16          mnId;
    sal_uInt32          mnSize;
    inline explicit     PropInfo( const OUString& rName, PropType eType, sal_uInt16 nId, sal_uInt32 nSize ) :
                            maName( rName ), meType( eType ), mnId( nId ), mnSize( nSize ) {}
};

typedef ::std::vector< PropInfo > PropInfoVector;

} // namespace

void DffStreamObject::dumpDffOpt()
{
    sal_uInt16 nPropCount = getInst();
    PropInfoVector aPropInfos;
    mxOut->resetItemIndex();
    for( sal_uInt16 nPropIdx = 0; !mxStrm->isEof() && (nPropIdx < nPropCount); ++nPropIdx )
    {
        sal_uInt16 nPropId = dumpDffOptPropHeader();
        sal_uInt16 nBaseId = nPropId & DFF_OPT_IDMASK;
        sal_uInt32 nValue = mxStrm->readuInt32();

        IndentGuard aIndent( mxOut );
        if( getFlag( nPropId, DFF_OPT_COMPLEX ) )
        {
            writeHexItem( "complex-size", nValue, "CONV-DEC" );
            String aName;
            PropType eType = PROPTYPE_BINARY;
            ItemFormatMap::const_iterator aIt = maComplexProps.find( nBaseId );
            if( aIt != maComplexProps.end() )
            {
                const ItemFormat& rItemFmt = aIt->second;
                aName = rItemFmt.maItemName;
                if ( rItemFmt.maListName == "binary" )
                    eType = PROPTYPE_BINARY;
                else if ( rItemFmt.maListName == "string" )
                    eType = PROPTYPE_STRING;
                else if ( rItemFmt.maListName == "blip" )
                    eType = PROPTYPE_BLIP;
                else if ( rItemFmt.maListName == "colorarray" )
                    eType = PROPTYPE_COLORARRAY;
            }
            aPropInfos.push_back( PropInfo( aName( "property-data" ), eType, nBaseId, nValue ) );
        }
        else
        {
            ItemFormatMap::const_iterator aIt = maSimpleProps.find( nBaseId );
            if( aIt != maSimpleProps.end() )
            {
                const ItemFormat& rItemFmt = aIt->second;
                // flags always at end of block of 64 properties
                if( (nBaseId & DFF_OPT_FLAGSMASK) == DFF_OPT_FLAGSMASK )
                {
                    FlagsList* pFlagsList = dynamic_cast< FlagsList* >( cfg().getNameList( rItemFmt.maListName ).get() );
                    sal_Int64 nOldIgnoreFlags = 0;
                    if( pFlagsList )
                    {
                        nOldIgnoreFlags = pFlagsList->getIgnoreFlags();
                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags | 0xFFFF0000 | ~(nValue >> 16) );
                    }
                    writeValueItem( rItemFmt, nValue );
                    if( pFlagsList )
                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags );
                }
                else
                    writeValueItem( rItemFmt, nValue );
            }
            else
                writeHexItem( "value", nValue );
        }
    }

    mxOut->resetItemIndex();
    for( PropInfoVector::iterator aIt = aPropInfos.begin(), aEnd = aPropInfos.end(); !mxStrm->isEof() && (aIt != aEnd); ++aIt )
    {
        mxOut->startMultiItems();
        writeEmptyItem( "#complex-data" );
        writeHexItem( "id", aIt->mnId, "DFFOPT-PROPERTY-NAMES" );
        mxOut->endMultiItems();
        IndentGuard aIndent( mxOut );
        switch( aIt->meType )
        {
            case PROPTYPE_BINARY:
                dumpBinary( aIt->maName, aIt->mnSize );
            break;
            case PROPTYPE_STRING:
                dumpUnicodeArray( aIt->maName, aIt->mnSize / 2, true );
            break;
            case PROPTYPE_BLIP:
                dumpBinary( aIt->maName, aIt->mnSize );
            break;
            case PROPTYPE_COLORARRAY:
                dumpBinary( aIt->maName, aIt->mnSize );
            break;
        }
    }
}

sal_uInt16 DffStreamObject::dumpDffOptPropHeader()
{
    MultiItemsGuard aMultiGuard( mxOut );
    TableGuard aTabGuard( mxOut, 11 );
    writeEmptyItem( "#prop" );
    return dumpHex< sal_uInt16 >( "id", "DFFOPT-PROPERTY-ID" );
}

// ============================================================================

} // namespace dump
} // namespace oox

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>-Werror,-Wunused-const-variable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include "oox/dump/dffdumper.hxx"

#if OOX_INCLUDE_DUMPER

namespace oox {
namespace dump {

// ============================================================================

namespace {

const sal_uInt16 DFF_ID_BSE                 = 0xF007;   /// BLIP store entry.
const sal_uInt16 DFF_ID_BSTORECONTAINER     = 0xF001;   /// BLIP store container.
const sal_uInt16 DFF_ID_CHILDANCHOR         = 0xF00F;   /// Child anchor (in groups).
const sal_uInt16 DFF_ID_CLIENTANCHOR        = 0xF010;   /// Client anchor.
const sal_uInt16 DFF_ID_DG                  = 0xF008;   /// Drawing.
const sal_uInt16 DFF_ID_DGG                 = 0xF006;   /// Drawing group.
const sal_uInt16 DFF_ID_OPT                 = 0xF00B;   /// Property set.
const sal_uInt16 DFF_ID_OPT2                = 0xF121;   /// Secondary property set.
const sal_uInt16 DFF_ID_OPT3                = 0xF122;   /// Ternary property set.
const sal_uInt16 DFF_ID_SP                  = 0xF00A;   /// Shape.
const sal_uInt16 DFF_ID_SPGR                = 0xF009;   /// Shape group.
const sal_uInt16 DFF_ID_SPLITMENUCOLORS     = 0xF11E;   /// Current toolbar colors.

const sal_uInt16 DFF_OPT_IDMASK             = 0x3FFF;
const sal_uInt16 DFF_OPT_COMPLEX            = 0x8000;
const sal_uInt16 DFF_OPT_FLAGSMASK          = 0x003F;

} // namespace

// ============================================================================

bool DffStreamObject::implReadRecordHeader( BinaryInputStream& rBaseStrm, sal_Int64& ornRecId, sal_Int64& ornRecSize )
{
    sal_uInt16 nRecId;
    rBaseStrm >> mnInstVer >> nRecId >> mnRealSize;
    ornRecId = nRecId;
    ornRecSize = isContainer() ? 0 : mnRealSize;
    return !rBaseStrm.isEof();
}

void DffStreamObject::implWriteExtHeader()
{
    const sal_Char* pcListName = "DFF-RECORD-INST";
    switch( getRecId() )
    {
        case DFF_ID_BSE:                pcListName = "DFFBSE-RECORD-INST";          break;  // BLIP type
        case DFF_ID_BSTORECONTAINER:    pcListName = "DFFBSTORECONT-RECORD-INST";   break;  // BLIP count
        case DFF_ID_DG:                 pcListName = "DFFDG-RECORD-INST";           break;  // drawing ID
        case DFF_ID_OPT:                pcListName = "DFFOPT-RECORD-INST";          break;  // property count
        case DFF_ID_SP:                 pcListName = "DFFSP-RECORD-INST";           break;  // shape type
        case DFF_ID_SPLITMENUCOLORS:    pcListName = "DFFSPLITMENUC-RECORD-INST";   break;  // number of colors
    }
    MultiItemsGuard aMultiGuard( mxOut );
    writeHexItem( "instance", mnInstVer, pcListName );
    if( isContainer() ) writeDecItem( "container-size", mnRealSize );
}

void DffStreamObject::implDumpRecordBody()
{
    switch( getRecId() )
    {
        case DFF_ID_BSE:
            dumpDec< sal_uInt8 >( "win-type", "DFFBSE-TYPE" );
            dumpDec< sal_uInt8 >( "mac-type", "DFFBSE-TYPE" );
            dumpGuid( "guid" );
            dumpDec< sal_uInt16 >( "tag" );
            dumpDec< sal_uInt32 >( "blip-size" );
            dumpDec< sal_uInt32 >( "blip-refcount" );
            dumpDec< sal_uInt32 >( "blip-streampos" );
            dumpDec< sal_uInt8 >( "blip-usage", "DFFBSE-USAGE" );
            dumpDec< sal_uInt8 >( "blip-name-len" );
            dumpUnused( 2 );
        break;

        case DFF_ID_CHILDANCHOR:
            dumpDec< sal_uInt32 >( "left" );
            dumpDec< sal_uInt32 >( "top" );
            dumpDec< sal_uInt32 >( "right" );
            dumpDec< sal_uInt32 >( "bottom" );
        break;

        case DFF_ID_CLIENTANCHOR:
            implDumpClientAnchor();
        break;

        case DFF_ID_DG:
            dumpDec< sal_uInt32 >( "shape-count" );
            dumpHex< sal_uInt32 >( "max-shape-id", "CONV-DEC" );
        break;

        case DFF_ID_DGG:
        {
            dumpHex< sal_uInt32 >( "max-shape-id", "CONV-DEC" );
            sal_uInt32 nClusters = dumpDec< sal_uInt32 >( "id-cluster-count" );
            dumpDec< sal_uInt32 >( "shape-count" );
            dumpDec< sal_uInt32 >( "drawing-count" );
            mxOut->resetItemIndex( 1 );
            TableGuard aTabGuard( mxOut, 15, 16 );
            for( sal_uInt32 nCluster = 1; !mxStrm->isEof() && (nCluster < nClusters); ++nCluster )
            {
                MultiItemsGuard aMultiGuard( mxOut );
                writeEmptyItem( "#cluster" );
                dumpDec< sal_uInt32 >( "drawing-id" );
                dumpHex< sal_uInt32 >( "next-free-id", "CONV-DEC" );
            }
        }
        break;

        case DFF_ID_OPT:
        case DFF_ID_OPT2:
        case DFF_ID_OPT3:
            dumpDffOpt();
        break;

        case DFF_ID_SP:
            dumpHex< sal_uInt32 >( "shape-id", "CONV-DEC" );
            dumpHex< sal_uInt32 >( "shape-flags", "DFFSP-FLAGS" );
        break;

        case DFF_ID_SPGR:
            dumpDec< sal_uInt32 >( "left" );
            dumpDec< sal_uInt32 >( "top" );
            dumpDec< sal_uInt32 >( "right" );
            dumpDec< sal_uInt32 >( "bottom" );
        break;

        case DFF_ID_SPLITMENUCOLORS:
            dumpDffSimpleColor( "fill-color" );
            dumpDffSimpleColor( "line-color" );
            dumpDffSimpleColor( "shadow-color" );
            dumpDffSimpleColor( "3d-color" );
        break;
    }
}

void DffStreamObject::implDumpClientAnchor()
{
}

sal_uInt32 DffStreamObject::dumpDffSimpleColor( const String& rName )
{
    return dumpHex< sal_uInt32 >( rName, "DFF-SIMPLE-COLOR" );
}

namespace {

enum PropType { PROPTYPE_BINARY, PROPTYPE_STRING, PROPTYPE_BLIP, PROPTYPE_COLORARRAY };

struct PropInfo
{
    OUString            maName;
    PropType            meType;
    sal_uInt16          mnId;
    sal_uInt32          mnSize;
    inline explicit     PropInfo( const OUString& rName, PropType eType, sal_uInt16 nId, sal_uInt32 nSize ) :
                            maName( rName ), meType( eType ), mnId( nId ), mnSize( nSize ) {}
};

typedef ::std::vector< PropInfo > PropInfoVector;

} // namespace

void DffStreamObject::dumpDffOpt()
{
    sal_uInt16 nPropCount = getInst();
    PropInfoVector aPropInfos;
    mxOut->resetItemIndex();
    for( sal_uInt16 nPropIdx = 0; !mxStrm->isEof() && (nPropIdx < nPropCount); ++nPropIdx )
    {
        sal_uInt16 nPropId = dumpDffOptPropHeader();
        sal_uInt16 nBaseId = nPropId & DFF_OPT_IDMASK;
        sal_uInt32 nValue = mxStrm->readuInt32();

        IndentGuard aIndent( mxOut );
        if( getFlag( nPropId, DFF_OPT_COMPLEX ) )
        {
            writeHexItem( "complex-size", nValue, "CONV-DEC" );
            String aName;
            PropType eType = PROPTYPE_BINARY;
            ItemFormatMap::const_iterator aIt = maComplexProps.find( nBaseId );
            if( aIt != maComplexProps.end() )
            {
                const ItemFormat& rItemFmt = aIt->second;
                aName = rItemFmt.maItemName;
                if ( rItemFmt.maListName == "binary" )
                    eType = PROPTYPE_BINARY;
                else if ( rItemFmt.maListName == "string" )
                    eType = PROPTYPE_STRING;
                else if ( rItemFmt.maListName == "blip" )
                    eType = PROPTYPE_BLIP;
                else if ( rItemFmt.maListName == "colorarray" )
                    eType = PROPTYPE_COLORARRAY;
            }
            aPropInfos.push_back( PropInfo( aName( "property-data" ), eType, nBaseId, nValue ) );
        }
        else
        {
            ItemFormatMap::const_iterator aIt = maSimpleProps.find( nBaseId );
            if( aIt != maSimpleProps.end() )
            {
                const ItemFormat& rItemFmt = aIt->second;
                // flags always at end of block of 64 properties
                if( (nBaseId & DFF_OPT_FLAGSMASK) == DFF_OPT_FLAGSMASK )
                {
                    FlagsList* pFlagsList = dynamic_cast< FlagsList* >( cfg().getNameList( rItemFmt.maListName ).get() );
                    sal_Int64 nOldIgnoreFlags = 0;
                    if( pFlagsList )
                    {
                        nOldIgnoreFlags = pFlagsList->getIgnoreFlags();
                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags | 0xFFFF0000 | ~(nValue >> 16) );
                    }
                    writeValueItem( rItemFmt, nValue );
                    if( pFlagsList )
                        pFlagsList->setIgnoreFlags( nOldIgnoreFlags );
                }
                else
                    writeValueItem( rItemFmt, nValue );
            }
            else
                writeHexItem( "value", nValue );
        }
    }

    mxOut->resetItemIndex();
    for( PropInfoVector::iterator aIt = aPropInfos.begin(), aEnd = aPropInfos.end(); !mxStrm->isEof() && (aIt != aEnd); ++aIt )
    {
        mxOut->startMultiItems();
        writeEmptyItem( "#complex-data" );
        writeHexItem( "id", aIt->mnId, "DFFOPT-PROPERTY-NAMES" );
        mxOut->endMultiItems();
        IndentGuard aIndent( mxOut );
        switch( aIt->meType )
        {
            case PROPTYPE_BINARY:
                dumpBinary( aIt->maName, aIt->mnSize );
            break;
            case PROPTYPE_STRING:
                dumpUnicodeArray( aIt->maName, aIt->mnSize / 2, true );
            break;
            case PROPTYPE_BLIP:
                dumpBinary( aIt->maName, aIt->mnSize );
            break;
            case PROPTYPE_COLORARRAY:
                dumpBinary( aIt->maName, aIt->mnSize );
            break;
        }
    }
}

sal_uInt16 DffStreamObject::dumpDffOptPropHeader()
{
    MultiItemsGuard aMultiGuard( mxOut );
    TableGuard aTabGuard( mxOut, 11 );
    writeEmptyItem( "#prop" );
    return dumpHex< sal_uInt16 >( "id", "DFFOPT-PROPERTY-ID" );
}

// ============================================================================

} // namespace dump
} // namespace oox

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#pragma once

#include "default_handler.hpp"
#include <proxygen/httpserver/ResponseBuilder.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <folly/io/IOBuf.h>
#include <string>
#include <memory>

struct CloseConnection {
static proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {
    return b.closeConnection();
}
};

struct KeepConnection {
static proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {
    return b;
}
};

template<typename ConnectionPolicy = KeepConnection>
class DirectResponseHandler : public DefaultHandler {
public:
    explicit DirectResponseHandler(int code, std::string body = "")
        : code_(code)
        , body_(folly::IOBuf::copyBuffer(body))
    {}

    virtual void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept override {}
    virtual void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override {}

    virtual void onEOM() noexcept override {
        ConnectionPolicy::Apply(
            proxygen::ResponseBuilder(downstream_)
            .status(code_, proxygen::HTTPMessage::getDefaultReason(code_))
            .body(std::move(body_)))
            .sendWithEOM();
    }

private:
    const int code_;
    std::unique_ptr<folly::IOBuf> body_;
};

<commit_msg>refactored DirectResponseHandler<commit_after>#pragma once

#include "default_handler.hpp"
#include <proxygen/httpserver/ResponseBuilder.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include <folly/io/IOBuf.h>
#include <string>
#include <memory>

struct CloseConnection {
static proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {
    return b.closeConnection();
}
};

struct KeepConnection {
static proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {
    return b;
}
};

struct NoStore {
static proxygen::ResponseBuilder& Apply(proxygen::ResponseBuilder& b) {
    return b.header(proxygen::HTTP_HEADER_CACHE_CONTROL, "no-store");
}
};

template<typename... Policy>
class DirectResponseHandler : public DefaultHandler {
public:
    explicit DirectResponseHandler(int code, std::string body = "")
        : code_(code)
        , body_(folly::IOBuf::copyBuffer(body))
    {}

    virtual void onRequest(std::unique_ptr<proxygen::HTTPMessage> headers) noexcept override {}
    virtual void onBody(std::unique_ptr<folly::IOBuf> body) noexcept override {}

    virtual void onEOM() noexcept override {
        auto rb = proxygen::ResponseBuilder(downstream_);
        rb.status(code_, proxygen::HTTPMessage::getDefaultReason(code_));
        for(auto& p: { Policy::Apply... }) p(rb);
        rb.body(std::move(body_));
        rb.sendWithEOM();
    }

private:
    const int code_;
    std::unique_ptr<folly::IOBuf> body_;
};

template<typename... Policy>
using NoStoreDirectResponseHandler = DirectResponseHandler<NoStore, Policy...>;
<|endoftext|>


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

#include <signal.h>
#include <stdarg.h>

#include "webrtc/base/gunit.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/physicalsocketserver.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/base/socket_unittest.h"
#include "webrtc/base/testutils.h"
#include "webrtc/base/thread.h"

namespace rtc {

class PhysicalSocketTest : public SocketTest {
};

TEST_F(PhysicalSocketTest, TestConnectIPv4) {
  SocketTest::TestConnectIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectIPv6) {
  SocketTest::TestConnectIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv4) {
  SocketTest::TestConnectWithDnsLookupIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv6) {
  SocketTest::TestConnectWithDnsLookupIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectFailIPv4) {
  SocketTest::TestConnectFailIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectFailIPv6) {
  SocketTest::TestConnectFailIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv4) {
  SocketTest::TestConnectWithDnsLookupFailIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv6) {
  SocketTest::TestConnectWithDnsLookupFailIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv4) {
  SocketTest::TestConnectWithClosedSocketIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv6) {
  SocketTest::TestConnectWithClosedSocketIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv4) {
  SocketTest::TestConnectWhileNotClosedIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv6) {
  SocketTest::TestConnectWhileNotClosedIPv6();
}

TEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv4) {
  SocketTest::TestServerCloseDuringConnectIPv4();
}

TEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv6) {
  SocketTest::TestServerCloseDuringConnectIPv6();
}

TEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv4) {
  SocketTest::TestClientCloseDuringConnectIPv4();
}

TEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv6) {
  SocketTest::TestClientCloseDuringConnectIPv6();
}

TEST_F(PhysicalSocketTest, TestServerCloseIPv4) {
  SocketTest::TestServerCloseIPv4();
}

TEST_F(PhysicalSocketTest, TestServerCloseIPv6) {
  SocketTest::TestServerCloseIPv6();
}

TEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv4) {
  SocketTest::TestCloseInClosedCallbackIPv4();
}

TEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv6) {
  SocketTest::TestCloseInClosedCallbackIPv6();
}

TEST_F(PhysicalSocketTest, TestSocketServerWaitIPv4) {
  SocketTest::TestSocketServerWaitIPv4();
}

TEST_F(PhysicalSocketTest, TestSocketServerWaitIPv6) {
  SocketTest::TestSocketServerWaitIPv6();
}

TEST_F(PhysicalSocketTest, TestTcpIPv4) {
  SocketTest::TestTcpIPv4();
}

TEST_F(PhysicalSocketTest, TestTcpIPv6) {
  SocketTest::TestTcpIPv6();
}

TEST_F(PhysicalSocketTest, TestUdpIPv4) {
  SocketTest::TestUdpIPv4();
}

TEST_F(PhysicalSocketTest, TestUdpIPv6) {
  SocketTest::TestUdpIPv6();
}

TEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv4) {
  SocketTest::TestUdpReadyToSendIPv4();
}

TEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv6) {
  SocketTest::TestUdpReadyToSendIPv6();
}

TEST_F(PhysicalSocketTest, TestGetSetOptionsIPv4) {
  SocketTest::TestGetSetOptionsIPv4();
}

TEST_F(PhysicalSocketTest, TestGetSetOptionsIPv6) {
  SocketTest::TestGetSetOptionsIPv6();
}

#if defined(WEBRTC_POSIX)

class PosixSignalDeliveryTest : public testing::Test {
 public:
  static void RecordSignal(int signum) {
    signals_received_.push_back(signum);
    signaled_thread_ = Thread::Current();
  }

 protected:
  void SetUp() {
    ss_.reset(new PhysicalSocketServer());
  }

  void TearDown() {
    ss_.reset(NULL);
    signals_received_.clear();
    signaled_thread_ = NULL;
  }

  bool ExpectSignal(int signum) {
    if (signals_received_.empty()) {
      LOG(LS_ERROR) << "ExpectSignal(): No signal received";
      return false;
    }
    if (signals_received_[0] != signum) {
      LOG(LS_ERROR) << "ExpectSignal(): Received signal " <<
          signals_received_[0] << ", expected " << signum;
      return false;
    }
    signals_received_.erase(signals_received_.begin());
    return true;
  }

  bool ExpectNone() {
    bool ret = signals_received_.empty();
    if (!ret) {
      LOG(LS_ERROR) << "ExpectNone(): Received signal " << signals_received_[0]
          << ", expected none";
    }
    return ret;
  }

  static std::vector<int> signals_received_;
  static Thread *signaled_thread_;

  scoped_ptr<PhysicalSocketServer> ss_;
};

std::vector<int> PosixSignalDeliveryTest::signals_received_;
Thread *PosixSignalDeliveryTest::signaled_thread_ = NULL;

// Test receiving a synchronous signal while not in Wait() and then entering
// Wait() afterwards.
TEST_F(PosixSignalDeliveryTest, RaiseThenWait) {
  ASSERT_TRUE(ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal));
  raise(SIGTERM);
  EXPECT_TRUE(ss_->Wait(0, true));
  EXPECT_TRUE(ExpectSignal(SIGTERM));
  EXPECT_TRUE(ExpectNone());
}

// Test that we can handle getting tons of repeated signals and that we see all
// the different ones.
TEST_F(PosixSignalDeliveryTest, InsanelyManySignals) {
  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);
  ss_->SetPosixSignalHandler(SIGINT, &RecordSignal);
  for (int i = 0; i < 10000; ++i) {
    raise(SIGTERM);
  }
  raise(SIGINT);
  EXPECT_TRUE(ss_->Wait(0, true));
  // Order will be lowest signal numbers first.
  EXPECT_TRUE(ExpectSignal(SIGINT));
  EXPECT_TRUE(ExpectSignal(SIGTERM));
  EXPECT_TRUE(ExpectNone());
}

// Test that a signal during a Wait() call is detected.
TEST_F(PosixSignalDeliveryTest, SignalDuringWait) {
  ss_->SetPosixSignalHandler(SIGALRM, &RecordSignal);
  alarm(1);
  EXPECT_TRUE(ss_->Wait(1500, true));
  EXPECT_TRUE(ExpectSignal(SIGALRM));
  EXPECT_TRUE(ExpectNone());
}

class RaiseSigTermRunnable : public Runnable {
  void Run(Thread *thread) {
    thread->socketserver()->Wait(1000, false);

    // Allow SIGTERM. This will be the only thread with it not masked so it will
    // be delivered to us.
    sigset_t mask;
    sigemptyset(&mask);
    pthread_sigmask(SIG_SETMASK, &mask, NULL);

    // Raise it.
    raise(SIGTERM);
  }
};

// Test that it works no matter what thread the kernel chooses to give the
// signal to (since it's not guaranteed to be the one that Wait() runs on).
TEST_F(PosixSignalDeliveryTest, SignalOnDifferentThread) {
  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);
  // Mask out SIGTERM so that it can't be delivered to this thread.
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGTERM);
  EXPECT_EQ(0, pthread_sigmask(SIG_SETMASK, &mask, NULL));
  // Start a new thread that raises it. It will have to be delivered to that
  // thread. Our implementation should safely handle it and dispatch
  // RecordSignal() on this thread.
  scoped_ptr<Thread> thread(new Thread());
  scoped_ptr<RaiseSigTermRunnable> runnable(new RaiseSigTermRunnable());
  thread->Start(runnable.get());
  EXPECT_TRUE(ss_->Wait(1500, true));
  EXPECT_TRUE(ExpectSignal(SIGTERM));
  EXPECT_EQ(Thread::Current(), signaled_thread_);
  EXPECT_TRUE(ExpectNone());
}

#endif

}  // namespace rtc
<commit_msg>Rebase webrtc/base with r6555 version of talk/base: cd webrtc/base svn diff -r 6521:6555 http://webrtc.googlecode.com/svn/trunk/talk/base > 6555.diff patch -p0 -i 6555.diff<commit_after>/*
 *  Copyright 2004 The WebRTC Project Authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include <signal.h>
#include <stdarg.h>

#include "webrtc/base/gunit.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/physicalsocketserver.h"
#include "webrtc/base/scoped_ptr.h"
#include "webrtc/base/socket_unittest.h"
#include "webrtc/base/testutils.h"
#include "webrtc/base/thread.h"

namespace rtc {

class PhysicalSocketTest : public SocketTest {
};

TEST_F(PhysicalSocketTest, TestConnectIPv4) {
  SocketTest::TestConnectIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectIPv6) {
  SocketTest::TestConnectIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv4) {
  SocketTest::TestConnectWithDnsLookupIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupIPv6) {
  SocketTest::TestConnectWithDnsLookupIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectFailIPv4) {
  SocketTest::TestConnectFailIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectFailIPv6) {
  SocketTest::TestConnectFailIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv4) {
  SocketTest::TestConnectWithDnsLookupFailIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWithDnsLookupFailIPv6) {
  SocketTest::TestConnectWithDnsLookupFailIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv4) {
  SocketTest::TestConnectWithClosedSocketIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWithClosedSocketIPv6) {
  SocketTest::TestConnectWithClosedSocketIPv6();
}

TEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv4) {
  SocketTest::TestConnectWhileNotClosedIPv4();
}

TEST_F(PhysicalSocketTest, TestConnectWhileNotClosedIPv6) {
  SocketTest::TestConnectWhileNotClosedIPv6();
}

TEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv4) {
  SocketTest::TestServerCloseDuringConnectIPv4();
}

TEST_F(PhysicalSocketTest, TestServerCloseDuringConnectIPv6) {
  SocketTest::TestServerCloseDuringConnectIPv6();
}

TEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv4) {
  SocketTest::TestClientCloseDuringConnectIPv4();
}

TEST_F(PhysicalSocketTest, TestClientCloseDuringConnectIPv6) {
  SocketTest::TestClientCloseDuringConnectIPv6();
}

TEST_F(PhysicalSocketTest, TestServerCloseIPv4) {
  SocketTest::TestServerCloseIPv4();
}

TEST_F(PhysicalSocketTest, TestServerCloseIPv6) {
  SocketTest::TestServerCloseIPv6();
}

TEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv4) {
  SocketTest::TestCloseInClosedCallbackIPv4();
}

TEST_F(PhysicalSocketTest, TestCloseInClosedCallbackIPv6) {
  SocketTest::TestCloseInClosedCallbackIPv6();
}

TEST_F(PhysicalSocketTest, TestSocketServerWaitIPv4) {
  SocketTest::TestSocketServerWaitIPv4();
}

TEST_F(PhysicalSocketTest, TestSocketServerWaitIPv6) {
  SocketTest::TestSocketServerWaitIPv6();
}

TEST_F(PhysicalSocketTest, TestTcpIPv4) {
  SocketTest::TestTcpIPv4();
}

TEST_F(PhysicalSocketTest, TestTcpIPv6) {
  SocketTest::TestTcpIPv6();
}

TEST_F(PhysicalSocketTest, TestUdpIPv4) {
  SocketTest::TestUdpIPv4();
}

TEST_F(PhysicalSocketTest, TestUdpIPv6) {
  SocketTest::TestUdpIPv6();
}

// Disable for TSan v2, see
// https://code.google.com/p/webrtc/issues/detail?id=3498 for details.
#if !defined(THREAD_SANITIZER)

TEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv4) {
  SocketTest::TestUdpReadyToSendIPv4();
}

#endif // if !defined(THREAD_SANITIZER)

TEST_F(PhysicalSocketTest, TestUdpReadyToSendIPv6) {
  SocketTest::TestUdpReadyToSendIPv6();
}

TEST_F(PhysicalSocketTest, TestGetSetOptionsIPv4) {
  SocketTest::TestGetSetOptionsIPv4();
}

TEST_F(PhysicalSocketTest, TestGetSetOptionsIPv6) {
  SocketTest::TestGetSetOptionsIPv6();
}

#if defined(WEBRTC_POSIX)

class PosixSignalDeliveryTest : public testing::Test {
 public:
  static void RecordSignal(int signum) {
    signals_received_.push_back(signum);
    signaled_thread_ = Thread::Current();
  }

 protected:
  void SetUp() {
    ss_.reset(new PhysicalSocketServer());
  }

  void TearDown() {
    ss_.reset(NULL);
    signals_received_.clear();
    signaled_thread_ = NULL;
  }

  bool ExpectSignal(int signum) {
    if (signals_received_.empty()) {
      LOG(LS_ERROR) << "ExpectSignal(): No signal received";
      return false;
    }
    if (signals_received_[0] != signum) {
      LOG(LS_ERROR) << "ExpectSignal(): Received signal " <<
          signals_received_[0] << ", expected " << signum;
      return false;
    }
    signals_received_.erase(signals_received_.begin());
    return true;
  }

  bool ExpectNone() {
    bool ret = signals_received_.empty();
    if (!ret) {
      LOG(LS_ERROR) << "ExpectNone(): Received signal " << signals_received_[0]
          << ", expected none";
    }
    return ret;
  }

  static std::vector<int> signals_received_;
  static Thread *signaled_thread_;

  scoped_ptr<PhysicalSocketServer> ss_;
};

std::vector<int> PosixSignalDeliveryTest::signals_received_;
Thread *PosixSignalDeliveryTest::signaled_thread_ = NULL;

// Test receiving a synchronous signal while not in Wait() and then entering
// Wait() afterwards.
TEST_F(PosixSignalDeliveryTest, RaiseThenWait) {
  ASSERT_TRUE(ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal));
  raise(SIGTERM);
  EXPECT_TRUE(ss_->Wait(0, true));
  EXPECT_TRUE(ExpectSignal(SIGTERM));
  EXPECT_TRUE(ExpectNone());
}

// Test that we can handle getting tons of repeated signals and that we see all
// the different ones.
TEST_F(PosixSignalDeliveryTest, InsanelyManySignals) {
  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);
  ss_->SetPosixSignalHandler(SIGINT, &RecordSignal);
  for (int i = 0; i < 10000; ++i) {
    raise(SIGTERM);
  }
  raise(SIGINT);
  EXPECT_TRUE(ss_->Wait(0, true));
  // Order will be lowest signal numbers first.
  EXPECT_TRUE(ExpectSignal(SIGINT));
  EXPECT_TRUE(ExpectSignal(SIGTERM));
  EXPECT_TRUE(ExpectNone());
}

// Test that a signal during a Wait() call is detected.
TEST_F(PosixSignalDeliveryTest, SignalDuringWait) {
  ss_->SetPosixSignalHandler(SIGALRM, &RecordSignal);
  alarm(1);
  EXPECT_TRUE(ss_->Wait(1500, true));
  EXPECT_TRUE(ExpectSignal(SIGALRM));
  EXPECT_TRUE(ExpectNone());
}

class RaiseSigTermRunnable : public Runnable {
  void Run(Thread *thread) {
    thread->socketserver()->Wait(1000, false);

    // Allow SIGTERM. This will be the only thread with it not masked so it will
    // be delivered to us.
    sigset_t mask;
    sigemptyset(&mask);
    pthread_sigmask(SIG_SETMASK, &mask, NULL);

    // Raise it.
    raise(SIGTERM);
  }
};

// Test that it works no matter what thread the kernel chooses to give the
// signal to (since it's not guaranteed to be the one that Wait() runs on).
TEST_F(PosixSignalDeliveryTest, SignalOnDifferentThread) {
  ss_->SetPosixSignalHandler(SIGTERM, &RecordSignal);
  // Mask out SIGTERM so that it can't be delivered to this thread.
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGTERM);
  EXPECT_EQ(0, pthread_sigmask(SIG_SETMASK, &mask, NULL));
  // Start a new thread that raises it. It will have to be delivered to that
  // thread. Our implementation should safely handle it and dispatch
  // RecordSignal() on this thread.
  scoped_ptr<Thread> thread(new Thread());
  scoped_ptr<RaiseSigTermRunnable> runnable(new RaiseSigTermRunnable());
  thread->Start(runnable.get());
  EXPECT_TRUE(ss_->Wait(1500, true));
  EXPECT_TRUE(ExpectSignal(SIGTERM));
  EXPECT_EQ(Thread::Current(), signaled_thread_);
  EXPECT_TRUE(ExpectNone());
}

#endif

}  // namespace rtc
<|endoftext|>


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

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

#include "taskpane/TaskPaneControlFactory.hxx"

#include "strings.hrc"
#include "sdresid.hxx"

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif

namespace sd
{

    class ViewShellBase;
    extern ::Window * createSlideTransitionPanel( ::Window* pParent, ViewShellBase& rBase );

namespace toolpanel { namespace controls {

SlideTransitionPanel::SlideTransitionPanel(TreeNode* pParent, ViewShellBase& rBase)
    : SubToolPanel (pParent),
      maPreferredSize( 100, 200 )
{
    mpWrappedControl = createSlideTransitionPanel( pParent->GetWindow(), rBase );
    mpWrappedControl->Show();
}

SlideTransitionPanel::~SlideTransitionPanel()
{
    delete mpWrappedControl;
}

std::auto_ptr<ControlFactory> SlideTransitionPanel::CreateControlFactory (ViewShellBase& rBase)
{
    return std::auto_ptr<ControlFactory>(
        new ControlFactoryWithArgs1<SlideTransitionPanel,ViewShellBase>(rBase));
}

Size SlideTransitionPanel::GetPreferredSize()
{
    return maPreferredSize;
}
sal_Int32 SlideTransitionPanel::GetPreferredWidth(sal_Int32 )
{
    return maPreferredSize.Width();
}
sal_Int32 SlideTransitionPanel::GetPreferredHeight(sal_Int32 )
{
    return maPreferredSize.Height();
}
::Window* SlideTransitionPanel::GetWindow()
{
    return mpWrappedControl;
}
bool SlideTransitionPanel::IsResizable()
{
    return true;
}
bool SlideTransitionPanel::IsExpandable() const
{
    return true;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> SlideTransitionPanel::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    if (GetWindow() != NULL)
        return GetWindow()->GetAccessible();
    else
        return NULL;
}

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

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

#include "taskpane/TaskPaneControlFactory.hxx"

#include "strings.hrc"
#include "sdresid.hxx"
#include <com/sun/star/frame/XModel.hpp>

namespace sd
{

    class ViewShellBase;
    extern ::Window * createSlideTransitionPanel( ::Window* pParent, ViewShellBase& rBase );

namespace toolpanel { namespace controls {

SlideTransitionPanel::SlideTransitionPanel(TreeNode* pParent, ViewShellBase& rBase)
    : SubToolPanel (pParent),
      maPreferredSize( 100, 200 )
{
    mpWrappedControl = createSlideTransitionPanel( pParent->GetWindow(), rBase );
    mpWrappedControl->Show();
}

SlideTransitionPanel::~SlideTransitionPanel()
{
    delete mpWrappedControl;
}

std::auto_ptr<ControlFactory> SlideTransitionPanel::CreateControlFactory (ViewShellBase& rBase)
{
    return std::auto_ptr<ControlFactory>(
        new ControlFactoryWithArgs1<SlideTransitionPanel,ViewShellBase>(rBase));
}

Size SlideTransitionPanel::GetPreferredSize()
{
    return maPreferredSize;
}
sal_Int32 SlideTransitionPanel::GetPreferredWidth(sal_Int32 )
{
    return maPreferredSize.Width();
}
sal_Int32 SlideTransitionPanel::GetPreferredHeight(sal_Int32 )
{
    return maPreferredSize.Height();
}
::Window* SlideTransitionPanel::GetWindow()
{
    return mpWrappedControl;
}
bool SlideTransitionPanel::IsResizable()
{
    return true;
}
bool SlideTransitionPanel::IsExpandable() const
{
    return true;
}

::com::sun::star::uno::Reference<
    ::com::sun::star::accessibility::XAccessible> SlideTransitionPanel::CreateAccessibleObject (
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& )
{
    if (GetWindow() != NULL)
        return GetWindow()->GetAccessible();
    else
        return NULL;
}

} } } // end of namespace ::sd::toolpanel::controls
<|endoftext|>


<commit_before>#include "ChineseRemainderTheorem.h"

#include <vector>
#include <iostream>

using namespace std;

template <class T>
T chineseRemainderTheorem(const vector <T> &a, const vector <T> &m)
{
    vector <T> u = chineseRemainderTheoremHelper(m);
    T ans = 0, M = 1;
    for (int i = 0; i < u.size(); i++)
    {
        ans += a[i] * u[i];
        M *= m[i];
    }
    while (ans < 0)
        ans += M;
    return ans % M;
}

template <class T>
vector <T> chineseRemainderTheoremHelper(const vector <T> &m)
{
    vector <T> ret;
    T prod = 1;
    for (int i = 0; i < m.size(); i++)
        prod *= m[i];
    for (int i = 0; i < m.size(); i++)
        ret.push_back(euclid(m[i], prod/m[i]));
    return ret;
}

// Returns a number x such that x%m1==1 and x%m2==0
template <class T>
T euclid(T m1, T m2)
{
    T s = 0, ss = 1, t = 1, tt = 0, r = m2, rr = m1;
    while (r)
    {
        T q = rr / r;
        T v;
        v = r; r = rr - q*r; rr = v;
        v = s; s = ss - q*s; ss = v;
        v = t; t = tt - q*t; tt = v;
    }
    return tt * m2;
}

int test()
{
    // Solve x==2 (mod 3), x==3 (mod 4), x==1 (mod 5)
    vector <int> a;
    a.push_back(2);
    a.push_back(3);
    a.push_back(1);

    vector <int> m;
    m.push_back(3);
    m.push_back(4);
    m.push_back(5);

    cout << chineseRemainderTheorem(a, m);
    return 1;
}

<commit_msg>Added unsigned<commit_after>#include "ChineseRemainderTheorem.h"

#include <vector>
#include <iostream>

using namespace std;

template <class T>
T chineseRemainderTheorem(const vector <T> &a, const vector <T> &m)
{
    vector <T> u = chineseRemainderTheoremHelper(m);
    T ans = 0, M = 1;
    for (unsigned int i = 0; i < u.size(); i++)
    {
        ans += a[i] * u[i];
        M *= m[i];
    }
    while (ans < 0)
        ans += M;
    return ans % M;
}

template <class T>
vector <T> chineseRemainderTheoremHelper(const vector <T> &m)
{
    vector <T> ret;
    T prod = 1;
    for (unsigned int i = 0; i < m.size(); i++)
        prod *= m[i];
    for (unsigned int i = 0; i < m.size(); i++)
        ret.push_back(euclid(m[i], prod/m[i]));
    return ret;
}

// Returns a number x such that x%m1==1 and x%m2==0
template <class T>
T euclid(T m1, T m2)
{
    T s = 0, ss = 1, t = 1, tt = 0, r = m2, rr = m1;
    while (r)
    {
        T q = rr / r;
        T v;
        v = r; r = rr - q*r; rr = v;
        v = s; s = ss - q*s; ss = v;
        v = t; t = tt - q*t; tt = v;
    }
    return tt * m2;
}

int test()
{
    // Solve x==2 (mod 3), x==3 (mod 4), x==1 (mod 5)
    vector <int> a;
    a.push_back(2);
    a.push_back(3);
    a.push_back(1);

    vector <int> m;
    m.push_back(3);
    m.push_back(4);
    m.push_back(5);

    cout << chineseRemainderTheorem(a, m);
    return 1;
}

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "myLevel.hpp"
#include "net.h"

MyLevel::MyLevel() : AnnAbstractLevel()
{
}

void MyLevel::load()
{
	//For having a lighter syntax :
	auto engine(AnnEngine::Instance());

	//Load Sinbad:
	auto Sinbad (engine->createGameObject("Sinbad.mesh"));
	Sinbad->setUpPhysics(100, phyShapeType::boxShape);
	//Add it to the level list
	levelContent.push_back(Sinbad);

	//Load Ground:
	auto Ground (engine->createGameObject("Ground.mesh"));
	Ground->setPos(0,-2,0);
	Ground->setUpPhysics();
	//Add it to the level list
	levelContent.push_back(Ground);

	//Create a light source
	auto light(engine->addLight());
	light->setPosition(0,1,3);
	//Add it to the level lst
	levelLighting.push_back(light);

	engine->setAmbiantLight(Ogre::ColourValue::White/2);

	engine->getPlayer()->setPosition(AnnVect3(0,1,0));

	engine->resetPlayerPhysics();

}

int MyLevel::initializeServer(int port)
{
	std::stringstream ss;
	if(port < netNS::MIN_PORT)
	{
		AnnDebug() << "Invalid port number";
		return netNS::NET_ERROR;
	}
	// ------ init network stuff -------
	error = net.createServer(port, netNS::UDP);
	if(error != netNS::NET_OK)
	{
		AnnDebug() << net.getError(error);
		return netNS::NET_ERROR;
	}

	for (int i=0; i<MAX_PLAYERS; i++)
	{
		player[i].setConnected(false);
		player[i].setActive(false);
	}

	// AnnEngine::Instance()->getPlayer()->setPosition(AnnVect3(0,0,2.1));

	AnnDebug() << "---- Server ----";
	net.getLocalIP(localIP);
	ss << "Server IP: " << localIP;
	AnnDebug() << ss.str();
	ss.str("");
	ss << "Port: " << port;
	AnnDebug() << ss.str();
	return netNS::NET_OK;
}

// --- Do network communications ---
void MyLevel::communicate(float frameTime)
{
	// communicate with client
	doClientCommunication();
	// Calculate elapsed time for network communications
	netTime += frameTime;
	if(netTime < netNS::NET_TIMER)
		return;
	netTime -= netNS::NET_TIMER;
	// check for inactive clients, called every NET_TIMER seconds
	checkNetworkTimeout();
}

// --- Check for network timeout ---

void MyLevel::checkNetworkTimeout()
{
	std::stringstream ss;
	for (int i=0; i<MAX_PLAYERS; i++)
	{
		if (player[i].getConnected())
		{
			player[i].incTimeout();
			// if communication timout
			if (player[i].getTimeout() > netNS::MAX_ERRORS)
			{
				player[i].setActive(false);
				ss << "***** Player " << i << " disconnected. *****";
				AnnDebug() << ss.str();
			}
		}
	}
}

void MyLevel::doClientCommunication()
{
	int playN;
	int size;
	prepareDataForClient();
	for (int i=0; i<MAX_PLAYERS; i++)
	{
		size = sizeof(toServerData);
		if( net.readData((char*) &toServerData, size, remoteIP) == netNS::NET_OK)
		{
			if(size > 0)
			{
				playN = toServerData.playerN;
				if (playN == 255)
				{
					//clientWantsTiJoin(); TODO
				}
				else
				{
					if (player[playN].getConnected())
					{
						if (player[playN].getActive())
							player[playN].setButtons(toServerData.buttons);
						size = sizeof(toClientData);
						// send player the latest game data
						net.sendData((char*) &toClientData, size, player[i].getNetIP());
						player[playN].setTimeout(0);
						player[playN].setCommWarnings(0);
					}
				}
			}
		}
		else    // No more incomming data ? break !!
		{
			break;
		}
	}
}

void MyLevel::prepareDataForClient()
{
	for (int i=0; i<MAX_PLAYERS; i++)
	{
		toClientData.player[i].playerData = player[i].getNetData();
	}
}

//========================================================================
// Client is requesting to join game
//========================================================================

void MyLevel::clientWantToJoin()
{
	std::stringstream ss;
	int size;
	int status;
	connectResponse.number = 255;
	if (playerCount == 0)
	{
		//roundOver = true;
		// score system goes here (TODO)
	}
	AnnDebug() << "Player requesting to join.";
	// find available player position to use
	for(int i=0; i<MAX_PLAYERS; i++) // search all player position
	{
		if (player[i].getConnected() == false) // if this position available
		{
			player[i].setConnected(true);
			player[i].setTimeout(0);
			player[i].setCommWarnings(0);
			player[i].setNetIP(remoteIP); // save player's IP
			player[i].setCommErrors(0); // clear old errors
			// send SERVER_ID adn player number to client
			strcpy_s(connectResponse.response, netNS::SERVER_ID);
			connectResponse.number = (UCHAR)i;
			size = sizeof(connectResponse);
			status = net.sendData((char*) &connectResponse, size, remoteIP, port);
			if (status == netNS::NET_ERROR)
			{
				AnnDebug() << net.getError(status); // display error
				return;
			}
			toServerData.playerN = i; // clear join request from
									 //  input buffer
			ss << "Connected player as number: " << i;
			AnnDebug() << ss.str(); // found available player
			return;
		}
	}
	// send SERVER_FULL to client
	strcpy_s(connectResponse.response, netNS::SERVER_FULL);
	size = sizeof(connectResponse);
	status = net.sendData((char*)&connectResponse, size, remoteIP, port);
	AnnDebug() << "server full.";
}

void MyLevel::runLogic()
{
}<commit_msg>#13 networking server face<commit_after>#include "stdafx.h"
#include "myLevel.hpp"
#include "net.h"

MyLevel::MyLevel() : AnnAbstractLevel()
{
}

void MyLevel::load()
{
	//For having a lighter syntax :
	auto engine(AnnEngine::Instance());

	//Load Sinbad:
	auto Sinbad (engine->createGameObject("Sinbad.mesh"));
	Sinbad->setUpPhysics(100, phyShapeType::boxShape);
	//Add it to the level list
	levelContent.push_back(Sinbad);

	//Load Ground:
	auto Ground (engine->createGameObject("Ground.mesh"));
	Ground->setPos(0,-2,0);
	Ground->setUpPhysics();
	//Add it to the level list
	levelContent.push_back(Ground);

	//Create a light source
	auto light(engine->addLight());
	light->setPosition(0,1,3);
	//Add it to the level lst
	levelLighting.push_back(light);

	engine->setAmbiantLight(Ogre::ColourValue::White/2);

	engine->getPlayer()->setPosition(AnnVect3(0,1,0));

	engine->resetPlayerPhysics();

}

int MyLevel::initializeServer(int port)
{
	std::stringstream ss;
	if(port < netNS::MIN_PORT)
	{
		AnnDebug() << "Invalid port number";
		return netNS::NET_ERROR;
	}
	// ------ init network stuff -------
	error = net.createServer(port, netNS::UDP);
	if(error != netNS::NET_OK)
	{
		AnnDebug() << net.getError(error);
		return netNS::NET_ERROR;
	}

	for (int i=0; i<MAX_PLAYERS; i++)
	{
		player[i].setConnected(false);
		player[i].setActive(false);
	}

	// AnnEngine::Instance()->getPlayer()->setPosition(AnnVect3(0,0,2.1));

	AnnDebug() << "---- Server ----";
	net.getLocalIP(localIP);
	ss << "Server IP: " << localIP;
	AnnDebug() << ss.str();
	ss.str("");
	ss << "Port: " << port;
	AnnDebug() << ss.str();
	return netNS::NET_OK;
}

// --- Do network communications ---
void MyLevel::communicate(float frameTime)
{
	// communicate with client
	doClientCommunication();
	// Calculate elapsed time for network communications
	netTime += frameTime;
	if(netTime < netNS::NET_TIMER)
		return;
	netTime -= netNS::NET_TIMER;
	// check for inactive clients, called every NET_TIMER seconds
	checkNetworkTimeout();
}

// --- Check for network timeout ---

void MyLevel::checkNetworkTimeout()
{
	std::stringstream ss;
	for (int i=0; i<MAX_PLAYERS; i++)
	{
		if (player[i].getConnected())
		{
			player[i].incTimeout();
			// if communication timout
			if (player[i].getTimeout() > netNS::MAX_ERRORS)
			{
				player[i].setActive(false);
				ss << "***** Player " << i << " disconnected. *****";
				AnnDebug() << ss.str();
			}
		}
	}
}

void MyLevel::doClientCommunication()
{
	int playN;
	int size;
	prepareDataForClient();
	for (int i=0; i<MAX_PLAYERS; i++)
	{
		size = sizeof(toServerData);
		if( net.readData((char*) &toServerData, size, remoteIP) == netNS::NET_OK)
		{
			if(size > 0)
			{
				playN = toServerData.playerN;
				if (playN == 255)
				{
					//clientWantsTiJoin(); TODO
				}
				else
				{
					if (player[playN].getConnected())
					{
						if (player[playN].getActive())
							player[playN].setButtons(toServerData.buttons);
						size = sizeof(toClientData);
						// send player the latest game data
						net.sendData((char*) &toClientData, size, player[i].getNetIP());
						player[playN].setTimeout(0);
						player[playN].setCommWarnings(0);
					}
				}
			}
		}
		else    // No more incomming data ? break !!
		{
			break;
		}
	}
}

void MyLevel::prepareDataForClient()
{
	for (int i=0; i<MAX_PLAYERS; i++)
	{
		toClientData.player[i].playerData = player[i].getNetData();
	}
}

//========================================================================
// Client is requesting to join game
//========================================================================

void MyLevel::clientWantToJoin()
{
	std::stringstream ss;
	int size;
	int status;
	connectResponse.number = 255;
	if (playerCount == 0)
	{
		//roundOver = true;
		// score system goes here (TODO)
	}
	AnnDebug() << "Player requesting to join.";
	// find available player position to use
	for(int i=0; i<MAX_PLAYERS; i++) // search all player position
	{
		if (player[i].getConnected() == false) // if this position available
		{
			player[i].setConnected(true);
			player[i].setTimeout(0);
			player[i].setCommWarnings(0);
			player[i].setNetIP(remoteIP); // save player's IP
			player[i].setCommErrors(0); // clear old errors
			// send SERVER_ID adn player number to client
			strcpy_s(connectResponse.response, netNS::SERVER_ID);
			connectResponse.number = (UCHAR)i;
			size = sizeof(connectResponse);
			status = net.sendData((char*) &connectResponse, size, remoteIP, port);
			if (status == netNS::NET_ERROR)
			{
				AnnDebug() << net.getError(status); // display error
				return;
			}
			toServerData.playerN = i; // clear join request from
									 //  input buffer
			ss << "Connected player as number: " << i;
			AnnDebug() << ss.str(); // found available player
			return;
		}
	}
	// send SERVER_FULL to client
	strcpy_s(connectResponse.response, netNS::SERVER_FULL);
	size = sizeof(connectResponse);
	status = net.sendData((char*)&connectResponse, size, remoteIP, port);
	AnnDebug() << "server full.";
}

void MyLevel::runLogic()
{
	communicate(frameTime);
}<|endoftext|>


<commit_before>// CodeSamples.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "UserTypeToString.h"
#include <cstdio>
#include <string.h>
#include <crtdbg.h>

void _invalid_parameter(const wchar_t * expression,
    const wchar_t * function,
    const wchar_t * file,
    unsigned int line,
    uintptr_t pReserved
    )
{
    wprintf(L"Invalid parameter detected in function %s."
        L" File: %s Line: %d\n", function, file, line);
    wprintf(L"Expression: %s\n", expression);
}

void TestSecureCrtFunctions()
{
    _invalid_parameter_handler oldHandler, newHandler;
    newHandler = _invalid_parameter;
    oldHandler = _set_invalid_parameter_handler(newHandler);

    // Experimentation with C-Run time functions
    wchar_t* src = L"this is a string that is too big to copy to the destination";
    wchar_t destination[10] = { 0 };
    try
    {
        auto result = wcscpy_s(destination, 10, src);
        if (result != 0)
        {
            wprintf(L"copy failed!\n");
        }
        wprintf(destination);
    }
    catch (...)
    {
        wprintf(L"copy failed!\n");
    }
}

int main(int argc, wchar_t* argv[])
{
	// Test streaming a user defined type to an output stream
	/*UserTypeToString obj("Shawn Fox", 25, 14000000.35);
	std::cout << obj << std::endl;*/

	return 0;
}

<commit_msg>Turn off assertion pop-up for CRT function assertions.<commit_after>// CodeSamples.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "UserTypeToString.h"
#include <cstdio>
#include <string.h>
#include <crtdbg.h>

void _invalid_parameter(const wchar_t * expression,
    const wchar_t * function,
    const wchar_t * file,
    unsigned int line,
    uintptr_t pReserved
    )
{
    wprintf(L"Invalid parameter detected in function %s."
        L" File: %s Line: %d\n", function, file, line);
    wprintf(L"Expression: %s\n", expression);
}

void TestSecureCrtFunctions()
{
    _invalid_parameter_handler oldHandler, newHandler;
    newHandler = _invalid_parameter;
    oldHandler = _set_invalid_parameter_handler(newHandler);
    // Disable the message box for assertions.
    _CrtSetReportMode(_CRT_ASSERT, 0);

    // Experimentation with C-Run time functions
    wchar_t* src = L"this is a string that is too big to copy to the destination";
    wchar_t destination[10] = { 0 };
    try
    {
        auto result = wcscpy_s(destination, 10, src);
        if (result != 0)
        {
            wprintf(L"copy failed!\n");
        }
        wprintf(destination);
    }
    catch (...)
    {
        wprintf(L"copy failed!\n");
    }
}

int main(int argc, wchar_t* argv[])
{
	// Test streaming a user defined type to an output stream
	/*UserTypeToString obj("Shawn Fox", 25, 14000000.35);
	std::cout << obj << std::endl;*/
    TestSecureCrtFunctions();
	return 0;
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkUnicodeString.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

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

#include "vtkUnicodeString.h"

#include <vtkObject.h>
#include <utf8.h>

#include <vtkstd/map>
#include <vtkstd/stdexcept>

///////////////////////////////////////////////////////////////////////////
// vtkUnicodeString::const_iterator

vtkUnicodeString::const_iterator::const_iterator()
{
}

vtkUnicodeString::const_iterator::const_iterator(vtkstd::string::const_iterator position) :
  Position(position)
{
}

vtkUnicodeString::value_type vtkUnicodeString::const_iterator::operator*() const
{
  return utf8::unchecked::peek_next(this->Position);
}

bool vtkUnicodeString::const_iterator::operator==(const const_iterator& rhs) const
{
  return this->Position == rhs.Position;
}

bool vtkUnicodeString::const_iterator::operator!=(const const_iterator& rhs) const
{
  return !(*this == rhs);
}

vtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator++()
{
  utf8::unchecked::advance(this->Position, 1);
  return *this;
}

vtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator++(int)
{
  const_iterator result(this->Position);
  utf8::unchecked::advance(this->Position, 1);
  return result;
}

///////////////////////////////////////////////////////////////////////////
// vtkUnicodeString

vtkUnicodeString::vtkUnicodeString()
{
}

vtkUnicodeString::vtkUnicodeString(const vtkUnicodeString& rhs) :
  Storage(rhs.Storage)
{
}

vtkUnicodeString::vtkUnicodeString(size_type count, value_type character)
{
  for(size_type i = 0; i != count; ++i)
    utf8::append(character, vtkstd::back_inserter(this->Storage));
}

vtkUnicodeString::vtkUnicodeString(const_iterator first, const_iterator last) :
  Storage(first.Position, last.Position)
{
}

bool vtkUnicodeString::is_utf8(const char* value)
{
  return vtkUnicodeString::is_utf8(vtkstd::string(value ? value : ""));
}

bool vtkUnicodeString::is_utf8(const vtkstd::string& value)
{
  return utf8::is_valid(value.begin(), value.end());
}

vtkUnicodeString vtkUnicodeString::from_utf8(const char* value)
{
  return vtkUnicodeString::from_utf8(vtkstd::string(value ? value : ""));
}

vtkUnicodeString vtkUnicodeString::from_utf8(const vtkstd::string& value)
{
  vtkUnicodeString result;
  if(utf8::is_valid(value.begin(), value.end()))
    {
    result.Storage = value;
    }
  else
    {
    vtkGenericWarningMacro("vtkUnicodeString::from_utf8(): not a valid UTF-8 string.");
    }
  return result;
}

vtkUnicodeString vtkUnicodeString::from_utf16(const vtkTypeUInt16* value)
{
  vtkUnicodeString result;

  if(value)
    {
    size_type length = 0;
    while(value[length])
      ++length;

    try
      {
      utf8::utf16to8(value, value + length, vtkstd::back_inserter(result.Storage));
      }
    catch(utf8::invalid_utf16&)
      {
      vtkGenericWarningMacro(<< "vtkUnicodeString::from_utf16(): not a valid UTF-16 string.");
      }
    }

  return result;
}

vtkUnicodeString& vtkUnicodeString::operator=(const vtkUnicodeString& rhs)
{
  if(this == &rhs)
    return *this;

  this->Storage = rhs.Storage;
  return *this;
}

vtkUnicodeString::const_iterator vtkUnicodeString::begin() const
{
  return const_iterator(this->Storage.begin());
}

vtkUnicodeString::const_iterator vtkUnicodeString::end() const
{
  return const_iterator(this->Storage.end());
}

vtkUnicodeString::value_type vtkUnicodeString::at(size_type offset) const
{
  if(offset >= this->character_count())
    throw vtkstd::out_of_range("character out-of-range");

  vtkstd::string::const_iterator iterator = this->Storage.begin();
  utf8::unchecked::advance(iterator, offset);
  return utf8::unchecked::peek_next(iterator);
}

vtkUnicodeString::value_type vtkUnicodeString::operator[](size_type offset) const
{
  vtkstd::string::const_iterator iterator = this->Storage.begin();
  utf8::unchecked::advance(iterator, offset);
  return utf8::unchecked::peek_next(iterator);
}

const char* vtkUnicodeString::utf8_str() const
{
  return this->Storage.c_str();
}

void vtkUnicodeString::utf8_str(vtkstd::string& result) const
{
  result = this->Storage;
}

vtkstd::vector<vtkTypeUInt16> vtkUnicodeString::utf16_str() const
{
  vtkstd::vector<vtkTypeUInt16> result;
  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));
  return result;
}

void vtkUnicodeString::utf16_str(vtkstd::vector<vtkTypeUInt16>& result) const
{
  result.clear();
  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));
}

vtkUnicodeString::size_type vtkUnicodeString::byte_count() const
{
  return this->Storage.size();
}

vtkUnicodeString::size_type vtkUnicodeString::character_count() const
{
  return utf8::unchecked::distance(this->Storage.begin(), this->Storage.end());
}

bool vtkUnicodeString::empty() const
{
  return this->Storage.empty();
}

vtkUnicodeString& vtkUnicodeString::operator+=(value_type value)
{
  this->push_back(value);
  return *this;
}

vtkUnicodeString& vtkUnicodeString::operator+=(const vtkUnicodeString& rhs)
{
  this->append(rhs);
  return *this;
}

void vtkUnicodeString::push_back(value_type character)
{
  try
    {
    utf8::append(character, vtkstd::back_inserter(this->Storage));
    }
  catch(utf8::invalid_code_point&)
    {
    vtkGenericWarningMacro("vtkUnicodeString::push_back(): " << character << "is not a valid Unicode code point");
    }
}

void vtkUnicodeString::append(const vtkUnicodeString& value)
{
  this->Storage.append(value.Storage);
}

void vtkUnicodeString::append(size_type count, value_type character)
{
  try
    {
    this->Storage.append(vtkUnicodeString(count, character).Storage);
    }
  catch(utf8::invalid_code_point&)
    {
    vtkGenericWarningMacro("vtkUnicodeString::append(): " << character << "is not a valid Unicode code point");
    }
}

void vtkUnicodeString::append(const_iterator first, const_iterator last)
{
  this->Storage.append(first.Position, last.Position);
}

void vtkUnicodeString::assign(const vtkUnicodeString& value)
{
  this->Storage.assign(value.Storage);
}

void vtkUnicodeString::assign(size_type count, value_type character)
{
  try
    {
    this->Storage.assign(vtkUnicodeString(count, character).Storage);
    }
  catch(utf8::invalid_code_point&)
    {
    vtkGenericWarningMacro("vtkUnicodeString::assign(): " << character << "is not a valid Unicode code point");
    }
}

void vtkUnicodeString::assign(const_iterator first, const_iterator last)
{
  this->Storage.assign(first.Position, last.Position);
}

void vtkUnicodeString::clear()
{
  this->Storage.clear();
}

vtkUnicodeString vtkUnicodeString::fold_case() const
{
  typedef vtkstd::map<value_type, vtkUnicodeString> map_t;

  static map_t map;
  if(map.empty())
    {
    #include <vtkUnicodeCaseFoldData.h>

    for(value_type* i = &vtkUnicodeCaseFoldData[0]; *i; ++i)
      {
      const value_type code = *i;
      vtkUnicodeString mapping;
      for(++i; *i; ++i)
        {
        mapping.push_back(*i);
        }
      map.insert(vtkstd::make_pair(code, mapping));
      }
    }

  vtkUnicodeString result;

  for(vtkUnicodeString::const_iterator source = this->begin(); source != this->end(); ++source)
    {
    map_t::const_iterator target = map.find(*source);
    if(target != map.end())
      {
      result.append(target->second);
      }
    else
      {
      result.push_back(*source);
      }
    }

  return result;
}

int vtkUnicodeString::compare(const vtkUnicodeString& rhs) const
{
  return this->Storage.compare(rhs.Storage);
}

void vtkUnicodeString::swap(vtkUnicodeString& rhs)
{
  vtkstd::swap(this->Storage, rhs.Storage);
}

bool operator==(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) == 0;
}

bool operator!=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) != 0;
}

bool operator<(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) < 0;
}

bool operator<=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) <= 0;
}

bool operator>=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) >= 0;
}

bool operator>(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) > 0;
}
<commit_msg>COMP: Borland stl string does not have iterator-to-iterator assign or append signatures, but it does have iterator-plus-length signatures.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkUnicodeString.cxx

-------------------------------------------------------------------------
  Copyright 2008 Sandia Corporation.
  Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
  the U.S. Government retains certain rights in this software.
-------------------------------------------------------------------------

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

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

#include "vtkUnicodeString.h"

#include <vtkObject.h>
#include <utf8.h>

#include <vtkstd/map>
#include <vtkstd/stdexcept>

///////////////////////////////////////////////////////////////////////////
// vtkUnicodeString::const_iterator

vtkUnicodeString::const_iterator::const_iterator()
{
}

vtkUnicodeString::const_iterator::const_iterator(vtkstd::string::const_iterator position) :
  Position(position)
{
}

vtkUnicodeString::value_type vtkUnicodeString::const_iterator::operator*() const
{
  return utf8::unchecked::peek_next(this->Position);
}

bool vtkUnicodeString::const_iterator::operator==(const const_iterator& rhs) const
{
  return this->Position == rhs.Position;
}

bool vtkUnicodeString::const_iterator::operator!=(const const_iterator& rhs) const
{
  return !(*this == rhs);
}

vtkUnicodeString::const_iterator& vtkUnicodeString::const_iterator::operator++()
{
  utf8::unchecked::advance(this->Position, 1);
  return *this;
}

vtkUnicodeString::const_iterator vtkUnicodeString::const_iterator::operator++(int)
{
  const_iterator result(this->Position);
  utf8::unchecked::advance(this->Position, 1);
  return result;
}

///////////////////////////////////////////////////////////////////////////
// vtkUnicodeString

vtkUnicodeString::vtkUnicodeString()
{
}

vtkUnicodeString::vtkUnicodeString(const vtkUnicodeString& rhs) :
  Storage(rhs.Storage)
{
}

vtkUnicodeString::vtkUnicodeString(size_type count, value_type character)
{
  for(size_type i = 0; i != count; ++i)
    utf8::append(character, vtkstd::back_inserter(this->Storage));
}

vtkUnicodeString::vtkUnicodeString(const_iterator first, const_iterator last) :
  Storage(first.Position, last.Position)
{
}

bool vtkUnicodeString::is_utf8(const char* value)
{
  return vtkUnicodeString::is_utf8(vtkstd::string(value ? value : ""));
}

bool vtkUnicodeString::is_utf8(const vtkstd::string& value)
{
  return utf8::is_valid(value.begin(), value.end());
}

vtkUnicodeString vtkUnicodeString::from_utf8(const char* value)
{
  return vtkUnicodeString::from_utf8(vtkstd::string(value ? value : ""));
}

vtkUnicodeString vtkUnicodeString::from_utf8(const vtkstd::string& value)
{
  vtkUnicodeString result;
  if(utf8::is_valid(value.begin(), value.end()))
    {
    result.Storage = value;
    }
  else
    {
    vtkGenericWarningMacro("vtkUnicodeString::from_utf8(): not a valid UTF-8 string.");
    }
  return result;
}

vtkUnicodeString vtkUnicodeString::from_utf16(const vtkTypeUInt16* value)
{
  vtkUnicodeString result;

  if(value)
    {
    size_type length = 0;
    while(value[length])
      ++length;

    try
      {
      utf8::utf16to8(value, value + length, vtkstd::back_inserter(result.Storage));
      }
    catch(utf8::invalid_utf16&)
      {
      vtkGenericWarningMacro(<< "vtkUnicodeString::from_utf16(): not a valid UTF-16 string.");
      }
    }

  return result;
}

vtkUnicodeString& vtkUnicodeString::operator=(const vtkUnicodeString& rhs)
{
  if(this == &rhs)
    return *this;

  this->Storage = rhs.Storage;
  return *this;
}

vtkUnicodeString::const_iterator vtkUnicodeString::begin() const
{
  return const_iterator(this->Storage.begin());
}

vtkUnicodeString::const_iterator vtkUnicodeString::end() const
{
  return const_iterator(this->Storage.end());
}

vtkUnicodeString::value_type vtkUnicodeString::at(size_type offset) const
{
  if(offset >= this->character_count())
    throw vtkstd::out_of_range("character out-of-range");

  vtkstd::string::const_iterator iterator = this->Storage.begin();
  utf8::unchecked::advance(iterator, offset);
  return utf8::unchecked::peek_next(iterator);
}

vtkUnicodeString::value_type vtkUnicodeString::operator[](size_type offset) const
{
  vtkstd::string::const_iterator iterator = this->Storage.begin();
  utf8::unchecked::advance(iterator, offset);
  return utf8::unchecked::peek_next(iterator);
}

const char* vtkUnicodeString::utf8_str() const
{
  return this->Storage.c_str();
}

void vtkUnicodeString::utf8_str(vtkstd::string& result) const
{
  result = this->Storage;
}

vtkstd::vector<vtkTypeUInt16> vtkUnicodeString::utf16_str() const
{
  vtkstd::vector<vtkTypeUInt16> result;
  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));
  return result;
}

void vtkUnicodeString::utf16_str(vtkstd::vector<vtkTypeUInt16>& result) const
{
  result.clear();
  utf8::unchecked::utf8to16(this->Storage.begin(), this->Storage.end(), vtkstd::back_inserter(result));
}

vtkUnicodeString::size_type vtkUnicodeString::byte_count() const
{
  return this->Storage.size();
}

vtkUnicodeString::size_type vtkUnicodeString::character_count() const
{
  return utf8::unchecked::distance(this->Storage.begin(), this->Storage.end());
}

bool vtkUnicodeString::empty() const
{
  return this->Storage.empty();
}

vtkUnicodeString& vtkUnicodeString::operator+=(value_type value)
{
  this->push_back(value);
  return *this;
}

vtkUnicodeString& vtkUnicodeString::operator+=(const vtkUnicodeString& rhs)
{
  this->append(rhs);
  return *this;
}

void vtkUnicodeString::push_back(value_type character)
{
  try
    {
    utf8::append(character, vtkstd::back_inserter(this->Storage));
    }
  catch(utf8::invalid_code_point&)
    {
    vtkGenericWarningMacro("vtkUnicodeString::push_back(): " << character << "is not a valid Unicode code point");
    }
}

void vtkUnicodeString::append(const vtkUnicodeString& value)
{
  this->Storage.append(value.Storage);
}

void vtkUnicodeString::append(size_type count, value_type character)
{
  try
    {
    this->Storage.append(vtkUnicodeString(count, character).Storage);
    }
  catch(utf8::invalid_code_point&)
    {
    vtkGenericWarningMacro("vtkUnicodeString::append(): " << character << "is not a valid Unicode code point");
    }
}

void vtkUnicodeString::append(const_iterator first, const_iterator last)
{
  this->Storage.append(first.Position, last.Position-first.Position);
}

void vtkUnicodeString::assign(const vtkUnicodeString& value)
{
  this->Storage.assign(value.Storage);
}

void vtkUnicodeString::assign(size_type count, value_type character)
{
  try
    {
    this->Storage.assign(vtkUnicodeString(count, character).Storage);
    }
  catch(utf8::invalid_code_point&)
    {
    vtkGenericWarningMacro("vtkUnicodeString::assign(): " << character << "is not a valid Unicode code point");
    }
}

void vtkUnicodeString::assign(const_iterator first, const_iterator last)
{
  this->Storage.assign(first.Position, last.Position-first.Position);
}

void vtkUnicodeString::clear()
{
  this->Storage.clear();
}

vtkUnicodeString vtkUnicodeString::fold_case() const
{
  typedef vtkstd::map<value_type, vtkUnicodeString> map_t;

  static map_t map;
  if(map.empty())
    {
    #include <vtkUnicodeCaseFoldData.h>

    for(value_type* i = &vtkUnicodeCaseFoldData[0]; *i; ++i)
      {
      const value_type code = *i;
      vtkUnicodeString mapping;
      for(++i; *i; ++i)
        {
        mapping.push_back(*i);
        }
      map.insert(vtkstd::make_pair(code, mapping));
      }
    }

  vtkUnicodeString result;

  for(vtkUnicodeString::const_iterator source = this->begin(); source != this->end(); ++source)
    {
    map_t::const_iterator target = map.find(*source);
    if(target != map.end())
      {
      result.append(target->second);
      }
    else
      {
      result.push_back(*source);
      }
    }

  return result;
}

int vtkUnicodeString::compare(const vtkUnicodeString& rhs) const
{
  return this->Storage.compare(rhs.Storage);
}

void vtkUnicodeString::swap(vtkUnicodeString& rhs)
{
  vtkstd::swap(this->Storage, rhs.Storage);
}

bool operator==(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) == 0;
}

bool operator!=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) != 0;
}

bool operator<(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) < 0;
}

bool operator<=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) <= 0;
}

bool operator>=(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) >= 0;
}

bool operator>(const vtkUnicodeString& lhs, const vtkUnicodeString& rhs)
{
  return lhs.compare(rhs) > 0;
}
<|endoftext|>