<commit_before>/*
 * This file is part of signon
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com>
 * Contact: Alberto Mardegan <alberto.mardegan@canonical.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include <QVariant>

#include "libsignoncommon.h"
#include "identityinfo.h"
#include "identityinfoimpl.h"
#include "identity.h"

namespace SignOn {

IdentityInfo::IdentityInfo():
    impl(new IdentityInfoImpl(this))
{
    qRegisterMetaType<IdentityInfo>("SignOn::IdentityInfo");

    if (qMetaTypeId<IdentityInfo>() < QMetaType::User)
        BLAME() << "IdentityInfo::IdentityInfo() - "
            "IdentityInfo meta type not registered.";

    impl->m_id = 0;
    impl->m_storeSecret = false;
}

IdentityInfo::IdentityInfo(const IdentityInfo &other):
    impl(new IdentityInfoImpl(this))
{
    impl->copy(*(other.impl));
}

IdentityInfo &IdentityInfo::operator=(const IdentityInfo &other)
{
    impl->copy(*(other.impl));
    return *this;
}

IdentityInfo::IdentityInfo(const QString &caption,
                           const QString &userName,
                           const QMap<MethodName, MechanismsList> &methods):
    impl(new IdentityInfoImpl(this))
{
    impl->m_caption = caption;
    impl->m_userName = userName;
    impl->m_isEmpty = false;
    impl->m_authMethods = methods;
}

IdentityInfo::~IdentityInfo()
{
    if (impl) delete impl;
    impl = 0;
}

void IdentityInfo::setId(const quint32 id)
{
    impl->m_id = id;
}

quint32 IdentityInfo::id() const
{
    return impl->m_id;
}

void IdentityInfo::setUserName(const QString &userName)
{
    impl->m_userName = userName;
    impl->m_isEmpty = false;
}

const QString IdentityInfo::userName() const
{
    return impl->m_userName;
}

void IdentityInfo::setCaption(const QString &caption)
{
    impl->m_caption = caption;
}

const QString IdentityInfo::caption() const
{
    return impl->m_caption;
}

void IdentityInfo::setRealms(const QStringList &realms)
{
    impl->m_realms = realms;
}

QStringList IdentityInfo::realms() const
{
    return impl->m_realms;
}

void IdentityInfo::setOwner(const QString &ownerToken)
{
    impl->m_owner = ownerToken;
}

QString IdentityInfo::owner() const
{
    return impl->m_owner;
}

void IdentityInfo::setAccessControlList(const QStringList &accessControlList)
{
    impl->m_accessControlList = accessControlList;
}

QStringList IdentityInfo::accessControlList() const
{
    return impl->m_accessControlList;
}

QString IdentityInfo::secret() const
{
    return impl->m_secret;
}

void IdentityInfo::setSecret(const QString &secret, const bool storeSecret)
{
    impl->m_secret = secret;
    impl->m_storeSecret = storeSecret;
    impl->m_isEmpty = false;
}

bool IdentityInfo::isStoringSecret() const
{
    return impl->m_storeSecret;
}

void IdentityInfo::setStoreSecret(const bool storeSecret)
{
    impl->m_storeSecret = storeSecret;
}

void IdentityInfo::setMethod(const MethodName &method,
                             const MechanismsList &mechanismsList)
{
    if (impl->hasMethod(method))
        impl->updateMethod(method, mechanismsList);
    else
        impl->addMethod(method, mechanismsList);
}

void IdentityInfo::removeMethod(const MethodName &method)
{
    impl->removeMethod(method);
}

void IdentityInfo::setType(IdentityInfo::CredentialsType type)
{
    impl->setType(type);
}

IdentityInfo::CredentialsType IdentityInfo::type() const
{
    return impl->type();
}

QList<MethodName> IdentityInfo::methods() const
{
    return impl->m_authMethods.keys();
}

MechanismsList IdentityInfo::mechanisms(const MethodName &method) const
{
    return impl->m_authMethods.value(method, QStringList());
}

void IdentityInfo::setRefCount(qint32 refCount)
{
    impl->setRefCount(refCount);
}

qint32 IdentityInfo::refCount() const
{
    return impl->refCount();
}

} //namespace SignOn
<commit_msg>lib: allow storing a record with empty username and password<commit_after>/*
 * This file is part of signon
 *
 * Copyright (C) 2009-2010 Nokia Corporation.
 *
 * Contact: Aurel Popirtac <ext-aurel.popirtac@nokia.com>
 * Contact: Alberto Mardegan <alberto.mardegan@canonical.com>
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 */

#include <QVariant>

#include "libsignoncommon.h"
#include "identityinfo.h"
#include "identityinfoimpl.h"
#include "identity.h"

namespace SignOn {

IdentityInfo::IdentityInfo():
    impl(new IdentityInfoImpl(this))
{
    qRegisterMetaType<IdentityInfo>("SignOn::IdentityInfo");

    if (qMetaTypeId<IdentityInfo>() < QMetaType::User)
        BLAME() << "IdentityInfo::IdentityInfo() - "
            "IdentityInfo meta type not registered.";

    impl->m_id = 0;
    impl->m_storeSecret = false;
}

IdentityInfo::IdentityInfo(const IdentityInfo &other):
    impl(new IdentityInfoImpl(this))
{
    impl->copy(*(other.impl));
}

IdentityInfo &IdentityInfo::operator=(const IdentityInfo &other)
{
    impl->copy(*(other.impl));
    return *this;
}

IdentityInfo::IdentityInfo(const QString &caption,
                           const QString &userName,
                           const QMap<MethodName, MechanismsList> &methods):
    impl(new IdentityInfoImpl(this))
{
    impl->m_caption = caption;
    impl->m_userName = userName;
    impl->m_isEmpty = false;
    impl->m_authMethods = methods;
}

IdentityInfo::~IdentityInfo()
{
    if (impl) delete impl;
    impl = 0;
}

void IdentityInfo::setId(const quint32 id)
{
    impl->m_id = id;
}

quint32 IdentityInfo::id() const
{
    return impl->m_id;
}

void IdentityInfo::setUserName(const QString &userName)
{
    impl->m_userName = userName;
    impl->m_isEmpty = false;
}

const QString IdentityInfo::userName() const
{
    return impl->m_userName;
}

void IdentityInfo::setCaption(const QString &caption)
{
    impl->m_caption = caption;
    impl->m_isEmpty = false;
}

const QString IdentityInfo::caption() const
{
    return impl->m_caption;
}

void IdentityInfo::setRealms(const QStringList &realms)
{
    impl->m_realms = realms;
}

QStringList IdentityInfo::realms() const
{
    return impl->m_realms;
}

void IdentityInfo::setOwner(const QString &ownerToken)
{
    impl->m_owner = ownerToken;
}

QString IdentityInfo::owner() const
{
    return impl->m_owner;
}

void IdentityInfo::setAccessControlList(const QStringList &accessControlList)
{
    impl->m_accessControlList = accessControlList;
}

QStringList IdentityInfo::accessControlList() const
{
    return impl->m_accessControlList;
}

QString IdentityInfo::secret() const
{
    return impl->m_secret;
}

void IdentityInfo::setSecret(const QString &secret, const bool storeSecret)
{
    impl->m_secret = secret;
    impl->m_storeSecret = storeSecret;
    impl->m_isEmpty = false;
}

bool IdentityInfo::isStoringSecret() const
{
    return impl->m_storeSecret;
}

void IdentityInfo::setStoreSecret(const bool storeSecret)
{
    impl->m_storeSecret = storeSecret;
}

void IdentityInfo::setMethod(const MethodName &method,
                             const MechanismsList &mechanismsList)
{
    if (impl->hasMethod(method))
        impl->updateMethod(method, mechanismsList);
    else
        impl->addMethod(method, mechanismsList);
}

void IdentityInfo::removeMethod(const MethodName &method)
{
    impl->removeMethod(method);
}

void IdentityInfo::setType(IdentityInfo::CredentialsType type)
{
    impl->setType(type);
}

IdentityInfo::CredentialsType IdentityInfo::type() const
{
    return impl->type();
}

QList<MethodName> IdentityInfo::methods() const
{
    return impl->m_authMethods.keys();
}

MechanismsList IdentityInfo::mechanisms(const MethodName &method) const
{
    return impl->m_authMethods.value(method, QStringList());
}

void IdentityInfo::setRefCount(qint32 refCount)
{
    impl->setRefCount(refCount);
}

qint32 IdentityInfo::refCount() const
{
    return impl->refCount();
}

} //namespace SignOn
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <boost/program_options.hpp>

#include "InputFileStream.h"
#include "OutputFileStream.h"
#include "AlignedSentence.h"
#include "Parameter.h"
#include "Lattice.h"
#include "Rules.h"

using namespace std;

int main(int argc, char** argv)
{
  cerr << "Starting" << endl;

  Parameter params;

  namespace po = boost::program_options;
  po::options_description desc("Options");
  desc.add_options()
    ("help", "Print help messages")
    ("add", "additional options")
    ("revision,r", po::value<int>()->default_value(0), "Revision");

  po::variables_map vm;

  // input files;
  string pathTarget = argv[1];
  string pathSource = argv[2];
  string pathAlignment = argv[3];

  Moses::InputFileStream strmTarget(pathTarget);
  Moses::InputFileStream strmSource(pathSource);
  Moses::InputFileStream strmAlignment(pathAlignment);

  // MAIN LOOP
  string lineTarget, lineSource, lineAlignment;
  while (getline(strmTarget, lineTarget)) {
	  bool success;
	  success = getline(strmSource, lineSource);
	  if (!success) {
		  throw "Couldn't read source";
	  }
	  success = getline(strmAlignment, lineAlignment);
	  if (!success) {
		  throw "Couldn't read alignment";
	  }

	  cerr << "lineTarget=" << lineTarget << endl;
	  cerr << "lineSource=" << lineSource << endl;
	  cerr << "lineAlignment=" << lineAlignment << endl;

	  AlignedSentence alignedSentence(lineSource, lineTarget, lineAlignment);
	  alignedSentence.CreateConsistentPhrases(params);
	  //alignedSentence.Debug(cerr);

	  Lattice lattice(alignedSentence);
	  //cerr << "LATTICE:";
	  //lattice.Debug(cerr);

	  Rules rules(lattice, alignedSentence);
	  rules.CreateRules(params, alignedSentence.GetConsistentPhrases());
	  rules.Output(cout);

  }

  cerr << "Finished" << endl;
}

<commit_msg>output file<commit_after>#include <iostream>
#include <cstdlib>
#include <boost/program_options.hpp>

#include "InputFileStream.h"
#include "OutputFileStream.h"
#include "AlignedSentence.h"
#include "Parameter.h"
#include "Lattice.h"
#include "Rules.h"

using namespace std;

int main(int argc, char** argv)
{
  cerr << "Starting" << endl;

  Parameter params;

  namespace po = boost::program_options;
  po::options_description desc("Options");
  desc.add_options()
    ("help", "Print help messages")
    ("add", "additional options")
    ("revision,r", po::value<int>()->default_value(0), "Revision");

  po::variables_map vm;

  // input files;
  string pathTarget = argv[1];
  string pathSource = argv[2];
  string pathAlignment = argv[3];
  string pathExtract = argv[4];

  Moses::InputFileStream strmTarget(pathTarget);
  Moses::InputFileStream strmSource(pathSource);
  Moses::InputFileStream strmAlignment(pathAlignment);
  Moses::OutputFileStream m_extractFile(pathExtract);

  // MAIN LOOP
  string lineTarget, lineSource, lineAlignment;
  while (getline(strmTarget, lineTarget)) {
	  bool success;
	  success = getline(strmSource, lineSource);
	  if (!success) {
		  throw "Couldn't read source";
	  }
	  success = getline(strmAlignment, lineAlignment);
	  if (!success) {
		  throw "Couldn't read alignment";
	  }

	  cerr << "lineTarget=" << lineTarget << endl;
	  cerr << "lineSource=" << lineSource << endl;
	  cerr << "lineAlignment=" << lineAlignment << endl;

	  AlignedSentence alignedSentence(lineSource, lineTarget, lineAlignment);
	  alignedSentence.CreateConsistentPhrases(params);
	  //alignedSentence.Debug(cerr);

	  Lattice lattice(alignedSentence);
	  //cerr << "LATTICE:";
	  //lattice.Debug(cerr);

	  Rules rules(lattice, alignedSentence);
	  rules.CreateRules(params, alignedSentence.GetConsistentPhrases());
	  rules.Output(m_extractFile);

  }

  cerr << "Finished" << endl;
}

<|endoftext|>


<commit_before>/*
 * File:   ProcSingleton.cpp
 * Author: info@pascalsystem.pl
 *
 * Created on 25 maj 2015, 20:22
 */

#include "ProcSingleton.h"

void PascalSystem::Utils::ProcSingleton::createPid(int pid) {
    fd = getLockDescriptor(true);
    if (fd == -1) {
        throw std::runtime_error("error create process pid file");
    } else if (fd <= 0) {
        throw std::runtime_error("error lock process pid file");
    }

    std::string fileData = getPidFileLine(pid);
    write(fd, fileData.c_str(), fileData.length());
}

void PascalSystem::Utils::ProcSingleton::destroyPid() {
    releaseLockDescriptor(fd);
    fd = -1;
}

bool PascalSystem::Utils::ProcSingleton::isActive() {
    int tempFD = getLockDescriptor();
    if (tempFD > 0) {
        releaseLockDescriptor(tempFD);
        return false;
    }
    return true;
}

void PascalSystem::Utils::ProcSingleton::releaseLockDescriptor(int lockFD) {
    flock(lockFD, LOCK_UN);
    close(lockFD);
}

int PascalSystem::Utils::ProcSingleton::getLockDescriptor(bool create) {
    int lockFD;
    if (create) {
        lockFD = open(getPidFilePath().c_str(), O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0666);
    } else {
        lockFD = open(getPidFilePath().c_str(), O_RDONLY);
    }

    if (lockFD <= 0) {
        return -1;
    }
    int resultLock = flock(lockFD, LOCK_EX | LOCK_NB);
    if (resultLock != 0) {
        close(lockFD);
        return -2;
    }

    return lockFD;
}

std::string PascalSystem::Utils::ProcSingleton::getPidFileLine(int pid) {
    std::ostringstream ss;
    ss << pid << std::endl;
    return ss.str();
}<commit_msg>show error code when application running<commit_after>/*
 * File:   ProcSingleton.cpp
 * Author: info@pascalsystem.pl
 *
 * Created on 25 maj 2015, 20:22
 */

#include "ProcSingleton.h"

void PascalSystem::Utils::ProcSingleton::createPid(int pid) {
    fd = getLockDescriptor(true);
    if (fd == -1) {
        throw std::runtime_error("error create process pid file");
    } else if (fd <= 0) {
        throw std::runtime_error("error lock process pid file");
    }

    std::string fileData = getPidFileLine(pid);
    write(fd, fileData.c_str(), fileData.length());
}

void PascalSystem::Utils::ProcSingleton::destroyPid() {
    releaseLockDescriptor(fd);
    fd = -1;
}

bool PascalSystem::Utils::ProcSingleton::isActive() {
    int tempFD = getLockDescriptor();
    if (tempFD > 0) {
        releaseLockDescriptor(tempFD);
        return false;
    }
    std::cout << "Singleton running [code: " << tempFD << "]" << std::endl;
    return true;
}

void PascalSystem::Utils::ProcSingleton::releaseLockDescriptor(int lockFD) {
    flock(lockFD, LOCK_UN);
    close(lockFD);
}

int PascalSystem::Utils::ProcSingleton::getLockDescriptor(bool create) {
    int lockFD;
    if (create) {
        lockFD = open(getPidFilePath().c_str(), O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0666);
    } else {
        lockFD = open(getPidFilePath().c_str(), O_RDONLY);
    }

    if (lockFD <= 0) {
        return -1;
    }
    int resultLock = flock(lockFD, LOCK_EX | LOCK_NB);
    if (resultLock != 0) {
        close(lockFD);
        return -2;
    }

    return lockFD;
}

std::string PascalSystem::Utils::ProcSingleton::getPidFileLine(int pid) {
    std::ostringstream ss;
    ss << pid << std::endl;
    return ss.str();
}<|endoftext|>


<commit_before>//===- ConstantHandling.cpp - Implement ConstantHandling.h ----------------===//
//
// This file implements the various intrinsic operations, on constant values.
//
//===----------------------------------------------------------------------===//

#include "llvm/Optimizations/ConstantHandling.h"

namespace opt {

//===----------------------------------------------------------------------===//
//                             TemplateRules Class
//===----------------------------------------------------------------------===//
//
// TemplateRules - Implement a subclass of ConstRules that provides all
// operations as noops.  All other rules classes inherit from this class so
// that if functionality is needed in the future, it can simply be added here
// and to ConstRules without changing anything else...
//
// This class also provides subclasses with typesafe implementations of methods
// so that don't have to do type casting.
//
template<class ArgType, class SubClassName>
class TemplateRules : public ConstRules {

  //===--------------------------------------------------------------------===//
  // Redirecting functions that cast to the appropriate types
  //===--------------------------------------------------------------------===//

  virtual ConstPoolVal *not(const ConstPoolVal *V) const {
    return SubClassName::Not((const ArgType *)V);
  }

  virtual ConstPoolVal *add(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *sub(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *mul(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolBool *lessthan(const ConstPoolVal *V1,
                                  const ConstPoolVal *V2) const {
    return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
  }

  //===--------------------------------------------------------------------===//
  // Default "noop" implementations
  //===--------------------------------------------------------------------===//

  inline static ConstPoolVal *Not(const ArgType *V) { return 0; }

  inline static ConstPoolVal *Add(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Sub(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Mul(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolBool *LessThan(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
};

//===----------------------------------------------------------------------===//
//                             EmptyRules Class
//===----------------------------------------------------------------------===//
//
// EmptyRules provides a concrete base class of ConstRules that does nothing
//
static    // EmptyInst is static
struct EmptyRules : public TemplateRules<ConstPoolVal, EmptyRules> {
} EmptyInst;

//===----------------------------------------------------------------------===//
//                              BoolRules Class
//===----------------------------------------------------------------------===//
//
// BoolRules provides a concrete base class of ConstRules for the 'bool' type.
//
static   // BoolTyInst is static...
struct BoolRules : public TemplateRules<ConstPoolBool, BoolRules> {

  inline static ConstPoolVal *Not(const ConstPoolBool *V) {
    return new ConstPoolBool(!V->getValue());
  }

  inline static ConstPoolVal *Or(const ConstPoolBool *V1,
                                 const ConstPoolBool *V2) {
    bool Result = V1->getValue() | V2->getValue();
    return new ConstPoolBool(Result);
  }

  inline static ConstPoolVal *And(const ConstPoolBool *V1,
                                  const ConstPoolBool *V2) {
    bool Result = V1->getValue() & V2->getValue();
    return new ConstPoolBool(Result);
  }
} BoolTyInst;

//===----------------------------------------------------------------------===//
//                             DirectRules Class
//===----------------------------------------------------------------------===//
//
// DirectRules provides a concrete base classes of ConstRules for a variety of
// different types.  This allows the C++ compiler to automatically generate our
// constant handling operations in a typesafe and accurate manner.
//
template<class ConstPoolClass, class BuiltinType, const Type **Ty>
struct DirectRules
  : public TemplateRules<ConstPoolClass,
                         DirectRules<ConstPoolClass, BuiltinType, Ty> > {

  inline static ConstPoolVal *Not(const ConstPoolClass *V) {
    return new ConstPoolClass(*Ty, !(BuiltinType)V->getValue());;
  }

  inline static ConstPoolVal *Add(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() +
                         (BuiltinType)V2->getValue();
    return new ConstPoolClass(*Ty, Result);
  }

  inline static ConstPoolVal *Sub(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() -
                         (BuiltinType)V2->getValue();
    return new ConstPoolClass(*Ty, Result);
  }

  inline static ConstPoolVal *Mul(const ConstPoolClass *V1,
				   const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() *
                         (BuiltinType)V2->getValue();
    return new ConstPoolClass(*Ty, Result);
  }

  inline static ConstPoolBool *LessThan(const ConstPoolClass *V1,
                                        const ConstPoolClass *V2) {
    bool Result = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
    return new ConstPoolBool(Result);
  }
};

//===----------------------------------------------------------------------===//
//                            DirectRules Subclasses
//===----------------------------------------------------------------------===//
//
// Given the DirectRules class we can now implement lots of types with little
// code.  Thank goodness C++ compilers are great at stomping out layers of
// templates... can you imagine having to do this all by hand? (/me is lazy :)
//
static DirectRules<ConstPoolSInt,   signed char , &Type::SByteTy>  SByteTyInst;
static DirectRules<ConstPoolUInt, unsigned char , &Type::UByteTy>  UByteTyInst;
static DirectRules<ConstPoolSInt,   signed short, &Type::ShortTy>  ShortTyInst;
static DirectRules<ConstPoolUInt, unsigned short, &Type::UShortTy> UShortTyInst;
static DirectRules<ConstPoolSInt,   signed int  , &Type::IntTy>    IntTyInst;
static DirectRules<ConstPoolUInt, unsigned int  , &Type::UIntTy>   UIntTyInst;
static DirectRules<ConstPoolSInt,  int64_t      , &Type::LongTy>   LongTyInst;
static DirectRules<ConstPoolUInt, uint64_t      , &Type::ULongTy>  ULongTyInst;
static DirectRules<ConstPoolFP  , float         , &Type::FloatTy>  FloatTyInst;
static DirectRules<ConstPoolFP  , double        , &Type::DoubleTy> DoubleTyInst;

// ConstRules::find - Return the constant rules that take care of the specified
// type.  Note that this is cached in the Type value itself, so switch statement
// is only hit at most once per type.
//
const ConstRules *ConstRules::find(const Type *Ty) {
  const ConstRules *Result;
  switch (Ty->getPrimitiveID()) {
  case Type::BoolTyID:   Result = &BoolTyInst;   break;
  case Type::SByteTyID:  Result = &SByteTyInst;  break;
  case Type::UByteTyID:  Result = &UByteTyInst;  break;
  case Type::ShortTyID:  Result = &ShortTyInst;  break;
  case Type::UShortTyID: Result = &UShortTyInst; break;
  case Type::IntTyID:    Result = &IntTyInst;    break;
  case Type::UIntTyID:   Result = &UIntTyInst;   break;
  case Type::LongTyID:   Result = &LongTyInst;   break;
  case Type::ULongTyID:  Result = &ULongTyInst;  break;
  case Type::FloatTyID:  Result = &FloatTyInst;  break;
  case Type::DoubleTyID: Result = &DoubleTyInst; break;
  default:               Result = &EmptyInst;    break;
  }

  Ty->setConstRules(Result);   // Cache the value for future short circuiting!
  return Result;
}

} // End namespace opt
<commit_msg>Add support for casts<commit_after>//===- ConstantHandling.cpp - Implement ConstantHandling.h ----------------===//
//
// This file implements the various intrinsic operations, on constant values.
//
//===----------------------------------------------------------------------===//

#include "llvm/Optimizations/ConstantHandling.h"

namespace opt {

//===----------------------------------------------------------------------===//
//                             TemplateRules Class
//===----------------------------------------------------------------------===//
//
// TemplateRules - Implement a subclass of ConstRules that provides all
// operations as noops.  All other rules classes inherit from this class so
// that if functionality is needed in the future, it can simply be added here
// and to ConstRules without changing anything else...
//
// This class also provides subclasses with typesafe implementations of methods
// so that don't have to do type casting.
//
template<class ArgType, class SubClassName>
class TemplateRules : public ConstRules {

  //===--------------------------------------------------------------------===//
  // Redirecting functions that cast to the appropriate types
  //===--------------------------------------------------------------------===//

  virtual ConstPoolVal *not(const ConstPoolVal *V) const {
    return SubClassName::Not((const ArgType *)V);
  }

  virtual ConstPoolVal *add(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *sub(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *mul(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolBool *lessthan(const ConstPoolVal *V1,
                                  const ConstPoolVal *V2) const {
    return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
  }

  // Casting operators.  ick
  virtual ConstPoolBool *castToBool(const ConstPoolVal *V) const {
    return SubClassName::CastToBool((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToSByte(const ConstPoolVal *V) const {
    return SubClassName::CastToSByte((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUByte(const ConstPoolVal *V) const {
    return SubClassName::CastToUByte((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToShort(const ConstPoolVal *V) const {
    return SubClassName::CastToShort((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUShort(const ConstPoolVal *V) const {
    return SubClassName::CastToUShort((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToInt(const ConstPoolVal *V) const {
    return SubClassName::CastToInt((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUInt(const ConstPoolVal *V) const {
    return SubClassName::CastToUInt((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToLong(const ConstPoolVal *V) const {
    return SubClassName::CastToLong((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToULong(const ConstPoolVal *V) const {
    return SubClassName::CastToULong((const ArgType*)V);
  }
  virtual ConstPoolFP   *castToFloat(const ConstPoolVal *V) const {
    return SubClassName::CastToFloat((const ArgType*)V);
  }
  virtual ConstPoolFP   *castToDouble(const ConstPoolVal *V) const {
    return SubClassName::CastToDouble((const ArgType*)V);
  }

  //===--------------------------------------------------------------------===//
  // Default "noop" implementations
  //===--------------------------------------------------------------------===//

  inline static ConstPoolVal *Not(const ArgType *V) { return 0; }

  inline static ConstPoolVal *Add(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Sub(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Mul(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolBool *LessThan(const ArgType *V1, const ArgType *V2) {
    return 0;
  }

  // Casting operators.  ick
  inline static ConstPoolBool *CastToBool  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToSByte (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUByte (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToShort (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUShort(const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToInt   (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUInt  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToLong  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToULong (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolFP   *CastToFloat (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolFP   *CastToDouble(const ConstPoolVal *V) { return 0; }
};

//===----------------------------------------------------------------------===//
//                             EmptyRules Class
//===----------------------------------------------------------------------===//
//
// EmptyRules provides a concrete base class of ConstRules that does nothing
//
static    // EmptyInst is static
struct EmptyRules : public TemplateRules<ConstPoolVal, EmptyRules> {
} EmptyInst;

//===----------------------------------------------------------------------===//
//                              BoolRules Class
//===----------------------------------------------------------------------===//
//
// BoolRules provides a concrete base class of ConstRules for the 'bool' type.
//
static   // BoolTyInst is static...
struct BoolRules : public TemplateRules<ConstPoolBool, BoolRules> {

  inline static ConstPoolVal *Not(const ConstPoolBool *V) {
    return new ConstPoolBool(!V->getValue());
  }

  inline static ConstPoolVal *Or(const ConstPoolBool *V1,
                                 const ConstPoolBool *V2) {
    bool Result = V1->getValue() | V2->getValue();
    return new ConstPoolBool(Result);
  }

  inline static ConstPoolVal *And(const ConstPoolBool *V1,
                                  const ConstPoolBool *V2) {
    bool Result = V1->getValue() & V2->getValue();
    return new ConstPoolBool(Result);
  }
} BoolTyInst;

//===----------------------------------------------------------------------===//
//                             DirectRules Class
//===----------------------------------------------------------------------===//
//
// DirectRules provides a concrete base classes of ConstRules for a variety of
// different types.  This allows the C++ compiler to automatically generate our
// constant handling operations in a typesafe and accurate manner.
//
template<class ConstPoolClass, class BuiltinType, const Type **Ty>
struct DirectRules
  : public TemplateRules<ConstPoolClass,
                         DirectRules<ConstPoolClass, BuiltinType, Ty> > {

  inline static ConstPoolVal *Not(const ConstPoolClass *V) {
    return new ConstPoolClass(*Ty, !(BuiltinType)V->getValue());;
  }

  inline static ConstPoolVal *Add(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() +
                         (BuiltinType)V2->getValue();
    return new ConstPoolClass(*Ty, Result);
  }

  inline static ConstPoolVal *Sub(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() -
                         (BuiltinType)V2->getValue();
    return new ConstPoolClass(*Ty, Result);
  }

  inline static ConstPoolVal *Mul(const ConstPoolClass *V1,
				   const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() *
                         (BuiltinType)V2->getValue();
    return new ConstPoolClass(*Ty, Result);
  }

  inline static ConstPoolBool *LessThan(const ConstPoolClass *V1,
                                        const ConstPoolClass *V2) {
    bool Result = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
    return new ConstPoolBool(Result);
  }

  // Casting operators.  ick
#define DEF_CAST(TYPE, CLASS, CTYPE) \
  inline static CLASS *CastTo##TYPE  (const ConstPoolClass *V) {    \
    return new CLASS(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
  }

  DEF_CAST(Bool  , ConstPoolBool, bool)
  DEF_CAST(SByte , ConstPoolSInt, signed char)
  DEF_CAST(UByte , ConstPoolUInt, unsigned char)
  DEF_CAST(Short , ConstPoolSInt, signed short)
  DEF_CAST(UShort, ConstPoolUInt, unsigned short)
  DEF_CAST(Int   , ConstPoolSInt, signed int)
  DEF_CAST(UInt  , ConstPoolUInt, unsigned int)
  DEF_CAST(Long  , ConstPoolSInt, int64_t)
  DEF_CAST(ULong , ConstPoolUInt, uint64_t)
  DEF_CAST(Float , ConstPoolFP  , float)
  DEF_CAST(Double, ConstPoolFP  , double)
#undef DEF_CAST
};

//===----------------------------------------------------------------------===//
//                            DirectRules Subclasses
//===----------------------------------------------------------------------===//
//
// Given the DirectRules class we can now implement lots of types with little
// code.  Thank goodness C++ compilers are great at stomping out layers of
// templates... can you imagine having to do this all by hand? (/me is lazy :)
//
static DirectRules<ConstPoolSInt,   signed char , &Type::SByteTy>  SByteTyInst;
static DirectRules<ConstPoolUInt, unsigned char , &Type::UByteTy>  UByteTyInst;
static DirectRules<ConstPoolSInt,   signed short, &Type::ShortTy>  ShortTyInst;
static DirectRules<ConstPoolUInt, unsigned short, &Type::UShortTy> UShortTyInst;
static DirectRules<ConstPoolSInt,   signed int  , &Type::IntTy>    IntTyInst;
static DirectRules<ConstPoolUInt, unsigned int  , &Type::UIntTy>   UIntTyInst;
static DirectRules<ConstPoolSInt,  int64_t      , &Type::LongTy>   LongTyInst;
static DirectRules<ConstPoolUInt, uint64_t      , &Type::ULongTy>  ULongTyInst;
static DirectRules<ConstPoolFP  , float         , &Type::FloatTy>  FloatTyInst;
static DirectRules<ConstPoolFP  , double        , &Type::DoubleTy> DoubleTyInst;

// ConstRules::find - Return the constant rules that take care of the specified
// type.  Note that this is cached in the Type value itself, so switch statement
// is only hit at most once per type.
//
const ConstRules *ConstRules::find(const Type *Ty) {
  const ConstRules *Result;
  switch (Ty->getPrimitiveID()) {
  case Type::BoolTyID:   Result = &BoolTyInst;   break;
  case Type::SByteTyID:  Result = &SByteTyInst;  break;
  case Type::UByteTyID:  Result = &UByteTyInst;  break;
  case Type::ShortTyID:  Result = &ShortTyInst;  break;
  case Type::UShortTyID: Result = &UShortTyInst; break;
  case Type::IntTyID:    Result = &IntTyInst;    break;
  case Type::UIntTyID:   Result = &UIntTyInst;   break;
  case Type::LongTyID:   Result = &LongTyInst;   break;
  case Type::ULongTyID:  Result = &ULongTyInst;  break;
  case Type::FloatTyID:  Result = &FloatTyInst;  break;
  case Type::DoubleTyID: Result = &DoubleTyInst; break;
  default:               Result = &EmptyInst;    break;
  }

  Ty->setConstRules(Result);   // Cache the value for future short circuiting!
  return Result;
}

} // End namespace opt
<|endoftext|>


<commit_before>//===- ConstantHandling.cpp - Implement ConstantHandling.h ----------------===//
//
// This file implements the various intrinsic operations, on constant values.
//
//===----------------------------------------------------------------------===//

#include "llvm/Optimizations/ConstantHandling.h"

namespace opt {

AnnotationID ConstRules::AID(AnnotationManager::getID("opt::ConstRules",
						      &ConstRules::find));

//===----------------------------------------------------------------------===//
//                             TemplateRules Class
//===----------------------------------------------------------------------===//
//
// TemplateRules - Implement a subclass of ConstRules that provides all
// operations as noops.  All other rules classes inherit from this class so
// that if functionality is needed in the future, it can simply be added here
// and to ConstRules without changing anything else...
//
// This class also provides subclasses with typesafe implementations of methods
// so that don't have to do type casting.
//
template<class ArgType, class SubClassName>
class TemplateRules : public ConstRules {

  //===--------------------------------------------------------------------===//
  // Redirecting functions that cast to the appropriate types
  //===--------------------------------------------------------------------===//

  virtual ConstPoolVal *not(const ConstPoolVal *V) const {
    return SubClassName::Not((const ArgType *)V);
  }

  virtual ConstPoolVal *add(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *sub(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *mul(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolBool *lessthan(const ConstPoolVal *V1,
                                  const ConstPoolVal *V2) const {
    return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
  }

  // Casting operators.  ick
  virtual ConstPoolBool *castToBool(const ConstPoolVal *V) const {
    return SubClassName::CastToBool((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToSByte(const ConstPoolVal *V) const {
    return SubClassName::CastToSByte((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUByte(const ConstPoolVal *V) const {
    return SubClassName::CastToUByte((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToShort(const ConstPoolVal *V) const {
    return SubClassName::CastToShort((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUShort(const ConstPoolVal *V) const {
    return SubClassName::CastToUShort((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToInt(const ConstPoolVal *V) const {
    return SubClassName::CastToInt((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUInt(const ConstPoolVal *V) const {
    return SubClassName::CastToUInt((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToLong(const ConstPoolVal *V) const {
    return SubClassName::CastToLong((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToULong(const ConstPoolVal *V) const {
    return SubClassName::CastToULong((const ArgType*)V);
  }
  virtual ConstPoolFP   *castToFloat(const ConstPoolVal *V) const {
    return SubClassName::CastToFloat((const ArgType*)V);
  }
  virtual ConstPoolFP   *castToDouble(const ConstPoolVal *V) const {
    return SubClassName::CastToDouble((const ArgType*)V);
  }

  //===--------------------------------------------------------------------===//
  // Default "noop" implementations
  //===--------------------------------------------------------------------===//

  inline static ConstPoolVal *Not(const ArgType *V) { return 0; }

  inline static ConstPoolVal *Add(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Sub(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Mul(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolBool *LessThan(const ArgType *V1, const ArgType *V2) {
    return 0;
  }

  // Casting operators.  ick
  inline static ConstPoolBool *CastToBool  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToSByte (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUByte (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToShort (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUShort(const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToInt   (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUInt  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToLong  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToULong (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolFP   *CastToFloat (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolFP   *CastToDouble(const ConstPoolVal *V) { return 0; }
};

//===----------------------------------------------------------------------===//
//                             EmptyRules Class
//===----------------------------------------------------------------------===//
//
// EmptyRules provides a concrete base class of ConstRules that does nothing
//
struct EmptyRules : public TemplateRules<ConstPoolVal, EmptyRules> {
};

//===----------------------------------------------------------------------===//
//                              BoolRules Class
//===----------------------------------------------------------------------===//
//
// BoolRules provides a concrete base class of ConstRules for the 'bool' type.
//
struct BoolRules : public TemplateRules<ConstPoolBool, BoolRules> {

  inline static ConstPoolVal *Not(const ConstPoolBool *V) {
    return ConstPoolBool::get(!V->getValue());
  }

  inline static ConstPoolVal *Or(const ConstPoolBool *V1,
				 const ConstPoolBool *V2) {
    return ConstPoolBool::get(V1->getValue() | V2->getValue());
  }

  inline static ConstPoolVal *And(const ConstPoolBool *V1,
                                  const ConstPoolBool *V2) {
    return ConstPoolBool::get(V1->getValue() & V2->getValue());
  }
};

//===----------------------------------------------------------------------===//
//                             DirectRules Class
//===----------------------------------------------------------------------===//
//
// DirectRules provides a concrete base classes of ConstRules for a variety of
// different types.  This allows the C++ compiler to automatically generate our
// constant handling operations in a typesafe and accurate manner.
//
template<class ConstPoolClass, class BuiltinType, const Type **Ty>
struct DirectRules
  : public TemplateRules<ConstPoolClass,
                         DirectRules<ConstPoolClass, BuiltinType, Ty> > {

  inline static ConstPoolVal *Not(const ConstPoolClass *V) {
    return ConstPoolClass::get(*Ty, !(BuiltinType)V->getValue());;
  }

  inline static ConstPoolVal *Add(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() +
                         (BuiltinType)V2->getValue();
    return ConstPoolClass::get(*Ty, Result);
  }

  inline static ConstPoolVal *Sub(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() -
                         (BuiltinType)V2->getValue();
    return ConstPoolClass::get(*Ty, Result);
  }

  inline static ConstPoolVal *Mul(const ConstPoolClass *V1,
				   const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() *
                         (BuiltinType)V2->getValue();
    return ConstPoolClass::get(*Ty, Result);
  }

  inline static ConstPoolBool *LessThan(const ConstPoolClass *V1,
                                        const ConstPoolClass *V2) {
    bool Result = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
    return ConstPoolBool::get(Result);
  }

  // Casting operators.  ick
#define DEF_CAST(TYPE, CLASS, CTYPE) \
  inline static CLASS *CastTo##TYPE  (const ConstPoolClass *V) {    \
    return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
  }

  DEF_CAST(Bool  , ConstPoolBool, bool)
  DEF_CAST(SByte , ConstPoolSInt, signed char)
  DEF_CAST(UByte , ConstPoolUInt, unsigned char)
  DEF_CAST(Short , ConstPoolSInt, signed short)
  DEF_CAST(UShort, ConstPoolUInt, unsigned short)
  DEF_CAST(Int   , ConstPoolSInt, signed int)
  DEF_CAST(UInt  , ConstPoolUInt, unsigned int)
  DEF_CAST(Long  , ConstPoolSInt, int64_t)
  DEF_CAST(ULong , ConstPoolUInt, uint64_t)
  DEF_CAST(Float , ConstPoolFP  , float)
  DEF_CAST(Double, ConstPoolFP  , double)
#undef DEF_CAST
};

//===----------------------------------------------------------------------===//
//                            DirectRules Subclasses
//===----------------------------------------------------------------------===//
//
// Given the DirectRules class we can now implement lots of types with little
// code.  Thank goodness C++ compilers are great at stomping out layers of
// templates... can you imagine having to do this all by hand? (/me is lazy :)
//

// ConstRules::find - Return the constant rules that take care of the specified
// type.
//
Annotation *ConstRules::find(AnnotationID AID, const Annotable *TyA, void *) {
  assert(AID == ConstRules::AID && "Bad annotation for factory!");
  const Type *Ty = ((const Value*)TyA)->castTypeAsserting();

  switch (Ty->getPrimitiveID()) {
  case Type::BoolTyID: return new BoolRules();
  case Type::SByteTyID:
    return new DirectRules<ConstPoolSInt,   signed char , &Type::SByteTy>();
  case Type::UByteTyID:
    return new DirectRules<ConstPoolUInt, unsigned char , &Type::UByteTy>();
  case Type::ShortTyID:
    return new DirectRules<ConstPoolSInt,   signed short, &Type::ShortTy>();
  case Type::UShortTyID:
    return new DirectRules<ConstPoolUInt, unsigned short, &Type::UShortTy>();
  case Type::IntTyID:
    return new DirectRules<ConstPoolSInt,   signed int  , &Type::IntTy>();
  case Type::UIntTyID:
    return new DirectRules<ConstPoolUInt, unsigned int  , &Type::UIntTy>();
  case Type::LongTyID:
    return new DirectRules<ConstPoolSInt,  int64_t      , &Type::LongTy>();
  case Type::ULongTyID:
    return new DirectRules<ConstPoolUInt, uint64_t      , &Type::ULongTy>();
  case Type::FloatTyID:
    return new DirectRules<ConstPoolFP  , float         , &Type::FloatTy>();
  case Type::DoubleTyID:
    return new DirectRules<ConstPoolFP  , double        , &Type::DoubleTy>();
  default:
    return new EmptyRules();
  }
}

} // End namespace opt
<commit_msg>Use correct style casts Types are not all constant now<commit_after>//===- ConstantHandling.cpp - Implement ConstantHandling.h ----------------===//
//
// This file implements the various intrinsic operations, on constant values.
//
//===----------------------------------------------------------------------===//

#include "llvm/Optimizations/ConstantHandling.h"

namespace opt {

AnnotationID ConstRules::AID(AnnotationManager::getID("opt::ConstRules",
						      &ConstRules::find));

//===----------------------------------------------------------------------===//
//                             TemplateRules Class
//===----------------------------------------------------------------------===//
//
// TemplateRules - Implement a subclass of ConstRules that provides all
// operations as noops.  All other rules classes inherit from this class so
// that if functionality is needed in the future, it can simply be added here
// and to ConstRules without changing anything else...
//
// This class also provides subclasses with typesafe implementations of methods
// so that don't have to do type casting.
//
template<class ArgType, class SubClassName>
class TemplateRules : public ConstRules {

  //===--------------------------------------------------------------------===//
  // Redirecting functions that cast to the appropriate types
  //===--------------------------------------------------------------------===//

  virtual ConstPoolVal *not(const ConstPoolVal *V) const {
    return SubClassName::Not((const ArgType *)V);
  }

  virtual ConstPoolVal *add(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Add((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *sub(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Sub((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolVal *mul(const ConstPoolVal *V1,
                            const ConstPoolVal *V2) const {
    return SubClassName::Mul((const ArgType *)V1, (const ArgType *)V2);
  }

  virtual ConstPoolBool *lessthan(const ConstPoolVal *V1,
                                  const ConstPoolVal *V2) const {
    return SubClassName::LessThan((const ArgType *)V1, (const ArgType *)V2);
  }

  // Casting operators.  ick
  virtual ConstPoolBool *castToBool(const ConstPoolVal *V) const {
    return SubClassName::CastToBool((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToSByte(const ConstPoolVal *V) const {
    return SubClassName::CastToSByte((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUByte(const ConstPoolVal *V) const {
    return SubClassName::CastToUByte((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToShort(const ConstPoolVal *V) const {
    return SubClassName::CastToShort((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUShort(const ConstPoolVal *V) const {
    return SubClassName::CastToUShort((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToInt(const ConstPoolVal *V) const {
    return SubClassName::CastToInt((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToUInt(const ConstPoolVal *V) const {
    return SubClassName::CastToUInt((const ArgType*)V);
  }
  virtual ConstPoolSInt *castToLong(const ConstPoolVal *V) const {
    return SubClassName::CastToLong((const ArgType*)V);
  }
  virtual ConstPoolUInt *castToULong(const ConstPoolVal *V) const {
    return SubClassName::CastToULong((const ArgType*)V);
  }
  virtual ConstPoolFP   *castToFloat(const ConstPoolVal *V) const {
    return SubClassName::CastToFloat((const ArgType*)V);
  }
  virtual ConstPoolFP   *castToDouble(const ConstPoolVal *V) const {
    return SubClassName::CastToDouble((const ArgType*)V);
  }

  //===--------------------------------------------------------------------===//
  // Default "noop" implementations
  //===--------------------------------------------------------------------===//

  inline static ConstPoolVal *Not(const ArgType *V) { return 0; }

  inline static ConstPoolVal *Add(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Sub(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolVal *Mul(const ArgType *V1, const ArgType *V2) {
    return 0;
  }
  inline static ConstPoolBool *LessThan(const ArgType *V1, const ArgType *V2) {
    return 0;
  }

  // Casting operators.  ick
  inline static ConstPoolBool *CastToBool  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToSByte (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUByte (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToShort (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUShort(const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToInt   (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToUInt  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolSInt *CastToLong  (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolUInt *CastToULong (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolFP   *CastToFloat (const ConstPoolVal *V) { return 0; }
  inline static ConstPoolFP   *CastToDouble(const ConstPoolVal *V) { return 0; }
};

//===----------------------------------------------------------------------===//
//                             EmptyRules Class
//===----------------------------------------------------------------------===//
//
// EmptyRules provides a concrete base class of ConstRules that does nothing
//
struct EmptyRules : public TemplateRules<ConstPoolVal, EmptyRules> {
};

//===----------------------------------------------------------------------===//
//                              BoolRules Class
//===----------------------------------------------------------------------===//
//
// BoolRules provides a concrete base class of ConstRules for the 'bool' type.
//
struct BoolRules : public TemplateRules<ConstPoolBool, BoolRules> {

  inline static ConstPoolVal *Not(const ConstPoolBool *V) {
    return ConstPoolBool::get(!V->getValue());
  }

  inline static ConstPoolVal *Or(const ConstPoolBool *V1,
				 const ConstPoolBool *V2) {
    return ConstPoolBool::get(V1->getValue() | V2->getValue());
  }

  inline static ConstPoolVal *And(const ConstPoolBool *V1,
                                  const ConstPoolBool *V2) {
    return ConstPoolBool::get(V1->getValue() & V2->getValue());
  }
};

//===----------------------------------------------------------------------===//
//                             DirectRules Class
//===----------------------------------------------------------------------===//
//
// DirectRules provides a concrete base classes of ConstRules for a variety of
// different types.  This allows the C++ compiler to automatically generate our
// constant handling operations in a typesafe and accurate manner.
//
template<class ConstPoolClass, class BuiltinType, Type **Ty>
struct DirectRules
  : public TemplateRules<ConstPoolClass,
                         DirectRules<ConstPoolClass, BuiltinType, Ty> > {

  inline static ConstPoolVal *Not(const ConstPoolClass *V) {
    return ConstPoolClass::get(*Ty, !(BuiltinType)V->getValue());;
  }

  inline static ConstPoolVal *Add(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() +
                         (BuiltinType)V2->getValue();
    return ConstPoolClass::get(*Ty, Result);
  }

  inline static ConstPoolVal *Sub(const ConstPoolClass *V1,
                                  const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() -
                         (BuiltinType)V2->getValue();
    return ConstPoolClass::get(*Ty, Result);
  }

  inline static ConstPoolVal *Mul(const ConstPoolClass *V1,
				   const ConstPoolClass *V2) {
    BuiltinType Result = (BuiltinType)V1->getValue() *
                         (BuiltinType)V2->getValue();
    return ConstPoolClass::get(*Ty, Result);
  }

  inline static ConstPoolBool *LessThan(const ConstPoolClass *V1,
                                        const ConstPoolClass *V2) {
    bool Result = (BuiltinType)V1->getValue() < (BuiltinType)V2->getValue();
    return ConstPoolBool::get(Result);
  }

  // Casting operators.  ick
#define DEF_CAST(TYPE, CLASS, CTYPE) \
  inline static CLASS *CastTo##TYPE  (const ConstPoolClass *V) {    \
    return CLASS::get(Type::TYPE##Ty, (CTYPE)(BuiltinType)V->getValue()); \
  }

  DEF_CAST(Bool  , ConstPoolBool, bool)
  DEF_CAST(SByte , ConstPoolSInt, signed char)
  DEF_CAST(UByte , ConstPoolUInt, unsigned char)
  DEF_CAST(Short , ConstPoolSInt, signed short)
  DEF_CAST(UShort, ConstPoolUInt, unsigned short)
  DEF_CAST(Int   , ConstPoolSInt, signed int)
  DEF_CAST(UInt  , ConstPoolUInt, unsigned int)
  DEF_CAST(Long  , ConstPoolSInt, int64_t)
  DEF_CAST(ULong , ConstPoolUInt, uint64_t)
  DEF_CAST(Float , ConstPoolFP  , float)
  DEF_CAST(Double, ConstPoolFP  , double)
#undef DEF_CAST
};

//===----------------------------------------------------------------------===//
//                            DirectRules Subclasses
//===----------------------------------------------------------------------===//
//
// Given the DirectRules class we can now implement lots of types with little
// code.  Thank goodness C++ compilers are great at stomping out layers of
// templates... can you imagine having to do this all by hand? (/me is lazy :)
//

// ConstRules::find - Return the constant rules that take care of the specified
// type.
//
Annotation *ConstRules::find(AnnotationID AID, const Annotable *TyA, void *) {
  assert(AID == ConstRules::AID && "Bad annotation for factory!");
  const Type *Ty = ((const Value*)TyA)->castTypeAsserting();

  switch (Ty->getPrimitiveID()) {
  case Type::BoolTyID: return new BoolRules();
  case Type::SByteTyID:
    return new DirectRules<ConstPoolSInt,   signed char , &Type::SByteTy>();
  case Type::UByteTyID:
    return new DirectRules<ConstPoolUInt, unsigned char , &Type::UByteTy>();
  case Type::ShortTyID:
    return new DirectRules<ConstPoolSInt,   signed short, &Type::ShortTy>();
  case Type::UShortTyID:
    return new DirectRules<ConstPoolUInt, unsigned short, &Type::UShortTy>();
  case Type::IntTyID:
    return new DirectRules<ConstPoolSInt,   signed int  , &Type::IntTy>();
  case Type::UIntTyID:
    return new DirectRules<ConstPoolUInt, unsigned int  , &Type::UIntTy>();
  case Type::LongTyID:
    return new DirectRules<ConstPoolSInt,  int64_t      , &Type::LongTy>();
  case Type::ULongTyID:
    return new DirectRules<ConstPoolUInt, uint64_t      , &Type::ULongTy>();
  case Type::FloatTyID:
    return new DirectRules<ConstPoolFP  , float         , &Type::FloatTy>();
  case Type::DoubleTyID:
    return new DirectRules<ConstPoolFP  , double        , &Type::DoubleTy>();
  default:
    return new EmptyRules();
  }
}

} // End namespace opt
<|endoftext|>


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

#include "src/envoy/mixer/config.h"
#include "google/protobuf/stubs/status.h"
#include "google/protobuf/util/json_util.h"
#include "include/attributes_builder.h"

using ::google::protobuf::Message;
using ::google::protobuf::util::Status;
using ::istio::mixer::v1::Attributes;
using ::istio::mixer_client::AttributesBuilder;
using ::istio::mixer::v1::config::client::ServiceConfig;
using ::istio::mixer::v1::config::client::TransportConfig;

namespace Envoy {
namespace Http {
namespace Mixer {
namespace {

// The Json object name for static attributes.
const std::string kMixerAttributes("mixer_attributes");

// The Json object name to specify attributes which will be forwarded
// to the upstream istio proxy.
const std::string kForwardAttributes("forward_attributes");

// The Json object name for quota name and amount.
const std::string kQuotaName("quota_name");
const std::string kQuotaAmount("quota_amount");

// The Json object name to disable check cache, quota cache and report batch
const std::string kDisableCheckCache("disable_check_cache");
const std::string kDisableQuotaCache("disable_quota_cache");
const std::string kDisableReportBatch("disable_report_batch");

const std::string kNetworkFailPolicy("network_fail_policy");
const std::string kDisableTcpCheckCalls("disable_tcp_check_calls");

const std::string kV2Config("v2");

void ReadStringMap(const Json::Object& json, const std::string& name,
                   Attributes* attributes) {
  if (json.hasObject(name)) {
    json.getObject(name)->iterate(
        [attributes](const std::string& key, const Json::Object& obj) -> bool {
          AttributesBuilder(attributes).AddIpOrString(key, obj.asString());
          return true;
        });
  }
}

void ReadTransportConfig(const Json::Object& json, TransportConfig* config) {
  // Default is open, unless it specifically set to "close"
  config->set_network_fail_policy(TransportConfig::FAIL_OPEN);
  if (json.hasObject(kNetworkFailPolicy) &&
      json.getString(kNetworkFailPolicy) == "close") {
    config->set_network_fail_policy(TransportConfig::FAIL_CLOSE);
  }

  config->set_disable_check_cache(json.getBoolean(kDisableCheckCache, false));
  config->set_disable_quota_cache(json.getBoolean(kDisableQuotaCache, false));
  config->set_disable_report_batch(json.getBoolean(kDisableReportBatch, false));
}

bool ReadV2Config(const Json::Object& json, Message* message) {
  if (!json.hasObject(kV2Config)) {
    return false;
  }
  std::string v2_str = json.getObject(kV2Config)->asJsonString();
  Status status =
      ::google::protobuf::util::JsonStringToMessage(v2_str, message);
  auto& logger = Logger::Registry::getLog(Logger::Id::config);
  if (status.ok()) {
    ENVOY_LOG_TO_LOGGER(logger, info, "V2 mixer client config: {}",
                        message->DebugString());
    return true;
  }
  ENVOY_LOG_TO_LOGGER(
      logger, error,
      "Failed to convert mixer V2 client config, error: {}, data: {}",
      status.ToString(), v2_str);
  return false;
}

}  // namespace

void HttpMixerConfig::Load(const Json::Object& json) {
  ReadStringMap(json, kMixerAttributes, http_config.mutable_mixer_attributes());
  ReadStringMap(json, kForwardAttributes,
                http_config.mutable_forward_attributes());

  if (json.hasObject(kQuotaName)) {
    int64_t amount = 1;
    if (json.hasObject(kQuotaAmount)) {
      amount = std::stoi(json.getString(kQuotaAmount));
    }
    legacy_quotas.push_back({json.getString(kQuotaName), amount});
  }

  ReadTransportConfig(json, http_config.mutable_transport());

  has_v2_config = ReadV2Config(json, &http_config);
  if (has_v2_config) {
    // If v2 config is valid, clear v1 legacy_quotas.
    legacy_quotas.clear();
  }
}

void HttpMixerConfig::CreateLegacyRouteConfig(
    bool disable_check, bool disable_report,
    const std::map<std::string, std::string>& attributes,
    ServiceConfig* config) {
  config->set_disable_check_calls(disable_check);
  config->set_disable_report_calls(disable_report);

  AttributesBuilder builder(config->mutable_mixer_attributes());
  for (const auto& it : attributes) {
    builder.AddIpOrString(it.first, it.second);
  }
}

void TcpMixerConfig::Load(const Json::Object& json) {
  ReadStringMap(json, kMixerAttributes, tcp_config.mutable_mixer_attributes());

  ReadTransportConfig(json, tcp_config.mutable_transport());

  tcp_config.set_disable_check_calls(
      json.getBoolean(kDisableTcpCheckCalls, false));

  ReadV2Config(json, &tcp_config);
}

}  // namespace Mixer
}  // namespace Http
}  // namespace Envoy
<commit_msg>Revert "Not to send legacy quota for v2 config." (#725)<commit_after>/* Copyright 2017 Istio Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/envoy/mixer/config.h"
#include "google/protobuf/stubs/status.h"
#include "google/protobuf/util/json_util.h"
#include "include/attributes_builder.h"

using ::google::protobuf::Message;
using ::google::protobuf::util::Status;
using ::istio::mixer::v1::Attributes;
using ::istio::mixer_client::AttributesBuilder;
using ::istio::mixer::v1::config::client::ServiceConfig;
using ::istio::mixer::v1::config::client::TransportConfig;

namespace Envoy {
namespace Http {
namespace Mixer {
namespace {

// The Json object name for static attributes.
const std::string kMixerAttributes("mixer_attributes");

// The Json object name to specify attributes which will be forwarded
// to the upstream istio proxy.
const std::string kForwardAttributes("forward_attributes");

// The Json object name for quota name and amount.
const std::string kQuotaName("quota_name");
const std::string kQuotaAmount("quota_amount");

// The Json object name to disable check cache, quota cache and report batch
const std::string kDisableCheckCache("disable_check_cache");
const std::string kDisableQuotaCache("disable_quota_cache");
const std::string kDisableReportBatch("disable_report_batch");

const std::string kNetworkFailPolicy("network_fail_policy");
const std::string kDisableTcpCheckCalls("disable_tcp_check_calls");

const std::string kV2Config("v2");

void ReadStringMap(const Json::Object& json, const std::string& name,
                   Attributes* attributes) {
  if (json.hasObject(name)) {
    json.getObject(name)->iterate(
        [attributes](const std::string& key, const Json::Object& obj) -> bool {
          AttributesBuilder(attributes).AddIpOrString(key, obj.asString());
          return true;
        });
  }
}

void ReadTransportConfig(const Json::Object& json, TransportConfig* config) {
  // Default is open, unless it specifically set to "close"
  config->set_network_fail_policy(TransportConfig::FAIL_OPEN);
  if (json.hasObject(kNetworkFailPolicy) &&
      json.getString(kNetworkFailPolicy) == "close") {
    config->set_network_fail_policy(TransportConfig::FAIL_CLOSE);
  }

  config->set_disable_check_cache(json.getBoolean(kDisableCheckCache, false));
  config->set_disable_quota_cache(json.getBoolean(kDisableQuotaCache, false));
  config->set_disable_report_batch(json.getBoolean(kDisableReportBatch, false));
}

bool ReadV2Config(const Json::Object& json, Message* message) {
  if (!json.hasObject(kV2Config)) {
    return false;
  }
  std::string v2_str = json.getObject(kV2Config)->asJsonString();
  Status status =
      ::google::protobuf::util::JsonStringToMessage(v2_str, message);
  auto& logger = Logger::Registry::getLog(Logger::Id::config);
  if (status.ok()) {
    ENVOY_LOG_TO_LOGGER(logger, info, "V2 mixer client config: {}",
                        message->DebugString());
    return true;
  }
  ENVOY_LOG_TO_LOGGER(
      logger, error,
      "Failed to convert mixer V2 client config, error: {}, data: {}",
      status.ToString(), v2_str);
  return false;
}

}  // namespace

void HttpMixerConfig::Load(const Json::Object& json) {
  ReadStringMap(json, kMixerAttributes, http_config.mutable_mixer_attributes());
  ReadStringMap(json, kForwardAttributes,
                http_config.mutable_forward_attributes());

  if (json.hasObject(kQuotaName)) {
    int64_t amount = 1;
    if (json.hasObject(kQuotaAmount)) {
      amount = std::stoi(json.getString(kQuotaAmount));
    }
    legacy_quotas.push_back({json.getString(kQuotaName), amount});
  }

  ReadTransportConfig(json, http_config.mutable_transport());

  has_v2_config = ReadV2Config(json, &http_config);
}

void HttpMixerConfig::CreateLegacyRouteConfig(
    bool disable_check, bool disable_report,
    const std::map<std::string, std::string>& attributes,
    ServiceConfig* config) {
  config->set_disable_check_calls(disable_check);
  config->set_disable_report_calls(disable_report);

  AttributesBuilder builder(config->mutable_mixer_attributes());
  for (const auto& it : attributes) {
    builder.AddIpOrString(it.first, it.second);
  }
}

void TcpMixerConfig::Load(const Json::Object& json) {
  ReadStringMap(json, kMixerAttributes, tcp_config.mutable_mixer_attributes());

  ReadTransportConfig(json, tcp_config.mutable_transport());

  tcp_config.set_disable_check_calls(
      json.getBoolean(kDisableTcpCheckCalls, false));

  ReadV2Config(json, &tcp_config);
}

}  // namespace Mixer
}  // namespace Http
}  // namespace Envoy
<|endoftext|>


<commit_before>#include <epoller/jsepoller.h>
#include <fcntl.h>
#include <iostream>

#define DBG_PREFIX "jsepoller: "

bool jsepoller::open(const std::string &pathname, size_t evbuff)
{
	if (!fdepoller::open(pathname,
	                     O_RDONLY,
	                     evbuff * sizeof(struct js_event), /* rxsize */
	                     0,                                /* txsize */
	                     true,                             /* rxen   */
	                     false,                            /* txen   */
	                     true)) {                          /* en     */
		std::cerr << DBG_PREFIX"opening " << pathname << " failed" << std::endl;
		return false;
	}

	return true;
}

size_t jsepoller::get_axes()
{
	char num;
	ioctl(fd, JSIOCGAXES, &num);
	return num;
}

size_t jsepoller::get_buttons()
{
	char num;
	ioctl(fd, JSIOCGBUTTONS, &num);
	return num;
}

int jsepoller::get_version()
{
	int ver;
	ioctl(fd, JSIOCGVERSION, &ver);
	return ver;
}

std::string jsepoller::get_name()
{
	char name[128];
	return ioctl(fd, JSIOCGNAME(sizeof(name)), name) < 0 ? "<unknown>" : name;
}

int jsepoller::get_corr(struct js_corr *corr)
{
	return ioctl(fd, JSIOCGCORR, corr);
}

int jsepoller::set_corr(const struct js_corr *corr)
{
	return ioctl(fd, JSIOCSCORR, corr);
}

int jsepoller::rx(int len)
{
	int ret;

	if (len < 0) {
		return -1;

	} else if (len == 0) {
		return -1;

	} else {

		while (linbuff_tord(&rxbuff) >= sizeof(struct js_event)) {

			struct js_event *event = (struct js_event*)LINBUFF_RD_PTR(&rxbuff);

			if (ret = jshandler(event))
				return ret;

			linbuff_skip(&rxbuff, sizeof(struct js_event));
		}

		linbuff_compact(&rxbuff);
		return 0;
	}
}

int jsepoller::jshandler(struct js_event *event)
{
	return _jshandler ? _jshandler(this, event) : 0;
}

<commit_msg>Satisfy compiler's suggestion concerning parentheses around assignment<commit_after>#include <epoller/jsepoller.h>
#include <fcntl.h>
#include <iostream>

#define DBG_PREFIX "jsepoller: "

bool jsepoller::open(const std::string &pathname, size_t evbuff)
{
	if (!fdepoller::open(pathname,
	                     O_RDONLY,
	                     evbuff * sizeof(struct js_event), /* rxsize */
	                     0,                                /* txsize */
	                     true,                             /* rxen   */
	                     false,                            /* txen   */
	                     true)) {                          /* en     */
		std::cerr << DBG_PREFIX"opening " << pathname << " failed" << std::endl;
		return false;
	}

	return true;
}

size_t jsepoller::get_axes()
{
	char num;
	ioctl(fd, JSIOCGAXES, &num);
	return num;
}

size_t jsepoller::get_buttons()
{
	char num;
	ioctl(fd, JSIOCGBUTTONS, &num);
	return num;
}

int jsepoller::get_version()
{
	int ver;
	ioctl(fd, JSIOCGVERSION, &ver);
	return ver;
}

std::string jsepoller::get_name()
{
	char name[128];
	return ioctl(fd, JSIOCGNAME(sizeof(name)), name) < 0 ? "<unknown>" : name;
}

int jsepoller::get_corr(struct js_corr *corr)
{
	return ioctl(fd, JSIOCGCORR, corr);
}

int jsepoller::set_corr(const struct js_corr *corr)
{
	return ioctl(fd, JSIOCSCORR, corr);
}

int jsepoller::rx(int len)
{
	int ret;

	if (len < 0) {
		return -1;

	} else if (len == 0) {
		return -1;

	} else {

		while (linbuff_tord(&rxbuff) >= sizeof(struct js_event)) {

			struct js_event *event = (struct js_event*)LINBUFF_RD_PTR(&rxbuff);

			if ((ret = jshandler(event)))
				return ret;

			linbuff_skip(&rxbuff, sizeof(struct js_event));
		}

		linbuff_compact(&rxbuff);
		return 0;
	}
}

int jsepoller::jshandler(struct js_event *event)
{
	return _jshandler ? _jshandler(this, event) : 0;
}

<|endoftext|>


<commit_before>
<commit_msg>Update spacelinecollide.cpp<commit_after>#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;

Point3d two_space_linear_collision_get_nearest_point(double A_0e, double B_0e, double C_0e, double D_0e, double A_0f, double B_0f, double C_0f, double D_0f,
													double A_1e, double B_1e, double C_1e, double D_1e, double A_1f, double B_1f, double C_1f, double D_1f)
{
	//直线0的A面的D,A,B,C
	double line0_flatE_d = D_0e;

	Mat line0_flatE = (Mat_<double>(1, 3) << A_0e, B_0e, C_0e);

	//直线0的B面的D,A,B,C
	double line0_flatF_d = D_0f;
	Mat line0_flatF = (Mat_<double>(1, 3) << A_0f, B_0f, C_0f);

	//直线1的A面的D,A,B,C
	double line1_flatE_d = D_1e;
	Mat line1_flatE = (Mat_<double>(1, 3) << A_1e, B_1e, C_1e);

	//直线1的B面的D,A,B,C
	double line1_flatF_d = D_1f;
	Mat line1_flatF = (Mat_<double>(1, 3) << A_1f, B_1f, C_1f);

	//两条直线0，1的direction vector（raws = 1, cols = 3）
	Mat direction_line0 = line0_flatE.cross(line0_flatF);

	Mat direction_line1 = line1_flatE.cross(line1_flatF);

	//line0的randpoint
	Point3d randPoint0(0.0, 0.0, 0.0);
	randPoint0.z = 800;
	Mat randPoint0_in = (Mat_<double>(2, 2) << line0_flatE.at<double>(0, 0), line0_flatE.at<double>(0, 1),
		line0_flatF.at<double>(0, 0), line0_flatF.at<double>(0, 1));

	Mat randPoint0_out = randPoint0_in.inv()*(Mat_<double>(2, 1) << -line0_flatE_d - randPoint0.z*line0_flatE.at<double>(0, 2),
		-line0_flatF_d - randPoint0.z*line0_flatF.at<double>(0, 2));
	randPoint0.x = randPoint0_out.at<double>(0, 0);
	randPoint0.y = randPoint0_out.at<double>(1, 0);

	//line1上randpoint
	Point3d randPoint1(0.0, 0.0, 0.0);
	randPoint1.z = 800;
	Mat randPoint1_in = (Mat_<double>(2, 2) << line1_flatE.at<double>(0, 0), line1_flatE.at<double>(0, 1),
		line1_flatF.at<double>(0, 0), line1_flatF.at<double>(0, 1));

	Mat randPoint1_out = randPoint1_in.inv()*(Mat_<double>(2, 1) << -line1_flatE_d - randPoint1.z*line1_flatE.at<double>(0, 2),
		-line1_flatF_d - randPoint1.z*line1_flatF.at<double>(0, 2));
	randPoint1.x = randPoint1_out.at<double>(0, 0);
	randPoint1.y = randPoint1_out.at<double>(1, 0);

	//Public vertical vector(rows=1,cols=3)
	Mat publicVerticalRay = direction_line0.cross(direction_line1);

	//任选点的方向向量
	Mat randRay = (Mat_<double>(3, 1) << randPoint0.x - randPoint1.x, randPoint0.y - randPoint1.y, randPoint0.z - randPoint1.z);

	Mat cross_rand_mult = publicVerticalRay*randRay;

	//公垂线的模
	double public_vertical_vector_length = sqrtf(publicVerticalRay.at<double>(0, 0)*publicVerticalRay.at<double>(0, 0)
		+ publicVerticalRay.at<double>(0, 1)*publicVerticalRay.at<double>(0, 1)
		+ publicVerticalRay.at<double>(0, 2)*publicVerticalRay.at<double>(0, 2));

	//两直线的最小距离d=|公向量*任选向量|/|公向量|
	double minDistance = std::abs(cross_rand_mult.at<double>(0, 0)) / public_vertical_vector_length;

	Point3d point_3d(0.0,0.0,0.0);

	if (minDistance<50)
	{

		Mat two_line_t_in = (Mat_<double>(3, 3) << publicVerticalRay.at<double>(0, 0), -direction_line0.at<double>(0, 0), direction_line1.at<double>(0, 0),
			publicVerticalRay.at<double>(0, 1), -direction_line0.at<double>(0, 1), direction_line1.at<double>(0, 1),
			publicVerticalRay.at<double>(0, 2), -direction_line0.at<double>(0, 2), direction_line1.at<double>(0, 2));

		Mat two_line_t = two_line_t_in.inv()*randRay;

		Point3d node0, node1;

		node0.x = two_line_t.at<double>(1, 0)*direction_line0.at<double>(0, 0) + randPoint0.x;
		node0.y = two_line_t.at<double>(1, 0)*direction_line0.at<double>(0, 1) + randPoint0.y;
		node0.z = two_line_t.at<double>(1, 0)*direction_line0.at<double>(0, 2) + randPoint0.z;

		node1.x = two_line_t.at<double>(2, 0)*direction_line1.at<double>(0, 0) + randPoint1.x;
		node1.y = two_line_t.at<double>(2, 0)*direction_line1.at<double>(0, 1) + randPoint1.y;
		node1.z = two_line_t.at<double>(2, 0)*direction_line1.at<double>(0, 2) + randPoint1.z;

		point_3d = (node0 + node1) / 2;

	}
	else
	{
		point_3d = Point3d(0.0,0.0,0.0);
	}

	return point_3d;

}
<|endoftext|>


<commit_before>#include <hayai/hayai.hpp>
#include <uuid/uuid.h>
#include <libcouchbase/couchbase.h>

#include "include/factory/writeable.h"

#include "include/factory/couchbase_interface.h"
#include "include/factory/logging_interface.h"

#include "include/factory.h"

//Test Data Class with to_json method
class TestData: public Writeable
{
std::string key;
int i;
int j;
public:
  TestData(int a, int b) {i=a;j=b;}
  std::string get_key() {return key;}
  bool set_key(std::string new_key) {key=new_key; return true;}
  int get_i() {return i;}
  int get_j() {return j;}
  bool set_i(int new_i) {i = new_i; return true;}
  bool set_j(int new_j) {j = new_j; return true;}
  std::string to_json()
  {
    std::string json_str = "{key:";
    std::string istr = std::to_string(i);
    std::string jstr = std::to_string(j);
    json_str = json_str.append(key);
    json_str = json_str.append(", i:");
    json_str = json_str.append(istr);
    json_str = json_str.append(", j:");
    json_str = json_str.append(jstr);
    json_str = json_str.append("}");
    return json_str;
  }
};

TestData *obj;
CouchbaseInterface *cb;
std::vector<std::string> uuid_list;
int savecounter = 0;
int getcounter = 0;
int delcounter = 0;
int loadcounter = 0;

//Couchbase Callbacks
std::string my_storage_callback (Request *r)
{
  if (r->req_err->err_code == NOERROR)
  {
    std::cout << "stored: " << r->req_addr << std::endl;
  }
  else
  {
    std::cout << "Failed to Store: " << r->req_addr << std::endl;
    std::cout << r->req_err->err_message << std::endl;
  }
  return r->req_addr;
}

std::string my_retrieval_callback (Request *r)
{
  if (r->req_err->err_code == NOERROR)
  {
    std::cout << "retrieved: " << r->req_addr << std::endl;
    std::cout << "value: " << r->req_data << std::endl;
  }
  else
  {
    std::cout << "Failed to Store: " << r->req_addr << std::endl;
    std::cout << r->req_err->err_message << std::endl;
  }
  return r->req_addr;
}

std::string my_delete_callback (Request *r)
{
  if (r->req_err->err_code == NOERROR)
  {
    std::cout << "removed: " << r->req_addr << std::endl;
  }
  else
  {
    std::cout << "Failed to Delete: " << r->req_addr << std::endl;
    std::cout << r->req_err->err_message << std::endl;
  }
  return r->req_addr;
}

//----------------------------------------------------------------------------//
//------------------------------Benchmarks------------------------------------//
//----------------------------------------------------------------------------//

BENCHMARK(Couchbase, Save, 10, 100)
{
  std::string uuid_str = uuid_list[savecounter];
  obj->set_key( uuid_str );

  cb->create_object ( obj );
  cb->wait();

  savecounter=savecounter+1;
}

BENCHMARK(Couchbase, Get, 10, 100)
{
  std::string uuid_str = uuid_list[getcounter];
  cb->load_object ( uuid_str.c_str() );
  cb->wait();

  getcounter=getcounter+1;
}

BENCHMARK(Couchbase, Update, 10, 100)
{
  std::string uuid_str = uuid_list[loadcounter];
  obj->set_key( uuid_str );

  cb->save_object ( obj );
  cb->wait();

  loadcounter=loadcounter+1;
}

BENCHMARK(Couchbase, Delete, 10, 100)
{
  std::string uuid_str = uuid_list[delcounter];
  cb->delete_object ( uuid_str.c_str() );
  cb->wait();

  delcounter=delcounter+1;
}

//----------------------------------------------------------------------------//
//------------------------------Main Method-----------------------------------//
//----------------------------------------------------------------------------//

int main()
{

ServiceComponentFactory factory;

//Application Setup

std::string initFileName = "test/log4cpp_test.properties";
logging = factory.get_logging_interface(initFileName);

//Generate the UUID's for the benchmarks
int i=0;
int uuid_gen_result;
uuid_t uuid;
for (i=0; i< 1001; i++) {
  //Generate a new key for the object
  std::string uuid_str = std::to_string(i);
  uuid_list.push_back(uuid_str);
}

//Generate an object to use for the benchmarks

obj = new TestData (0, 1);

//Set up the Couchbase Admin
//Build the Couchbase Admin (which will automatically connect to the DB)
cb = factory.get_couchbase_interface("couchbase://localhost/default");

//Supports both password authentication and clustering
printf("Connected to Couchbase");
//Bind callbacks
cb->bind_storage_callback(my_storage_callback);
cb->bind_get_callback(my_retrieval_callback);
cb->bind_delete_callback(my_delete_callback);

//------------------------------Run Tests-------------------------------------//
//----------------------------------------------------------------------------//

hayai::ConsoleOutputter consoleOutputter;

hayai::Benchmarker::AddOutputter(consoleOutputter);
hayai::Benchmarker::RunAllTests();

//-------------------------Post-Test Teardown---------------------------------//
//----------------------------------------------------------------------------//

delete obj;
delete cb;
delete logging;

return 0;

}
<commit_msg>Couchbase Updates to bring onto Universal Callback Interface<commit_after>#include <hayai/hayai.hpp>
#include <uuid/uuid.h>
#include <libcouchbase/couchbase.h>

#include "include/factory/writeable.h"

#include "include/factory/couchbase_interface.h"
#include "include/factory/logging_interface.h"

#include "include/factory.h"

//Test Data Class with to_json method
class TestData: public Writeable
{
std::string key;
int i;
int j;
public:
  TestData(int a, int b) {i=a;j=b;}
  std::string get_key() {return key;}
  bool set_key(std::string new_key) {key=new_key; return true;}
  int get_i() {return i;}
  int get_j() {return j;}
  bool set_i(int new_i) {i = new_i; return true;}
  bool set_j(int new_j) {j = new_j; return true;}
  std::string to_json()
  {
    std::string json_str = "{key:";
    std::string istr = std::to_string(i);
    std::string jstr = std::to_string(j);
    json_str = json_str.append(key);
    json_str = json_str.append(", i:");
    json_str = json_str.append(istr);
    json_str = json_str.append(", j:");
    json_str = json_str.append(jstr);
    json_str = json_str.append("}");
    return json_str;
  }
};

TestData *obj;
CouchbaseInterface *cb;
std::vector<std::string> uuid_list;
int savecounter = 0;
int getcounter = 0;
int delcounter = 0;
int loadcounter = 0;

//Couchbase Callbacks
std::string my_storage_callback (Request *r)
{
  if (r->req_err->err_code != NOERROR)
  {
    std::cout << "Failed to Store: " << r->req_addr << std::endl;
    std::cout << r->req_err->err_message << std::endl;
  }
  return r->req_addr;
}

std::string my_retrieval_callback (Request *r)
{
  if (r->req_err->err_code != NOERROR)
  {
    std::cout << "Failed to Store: " << r->req_addr << std::endl;
    std::cout << r->req_err->err_message << std::endl;
  }
  return r->req_addr;
}

std::string my_delete_callback (Request *r)
{
  if (r->req_err->err_code != NOERROR)
  {
    std::cout << "Failed to Delete: " << r->req_addr << std::endl;
    std::cout << r->req_err->err_message << std::endl;
  }
  return r->req_addr;
}

//----------------------------------------------------------------------------//
//------------------------------Benchmarks------------------------------------//
//----------------------------------------------------------------------------//

BENCHMARK(Couchbase, Save, 10, 100)
{
  std::string uuid_str = uuid_list[savecounter];
  obj->set_key( uuid_str );

  cb->create_object ( obj );
  cb->wait();

  savecounter=savecounter+1;
}

BENCHMARK(Couchbase, Get, 10, 100)
{
  std::string uuid_str = uuid_list[getcounter];
  cb->load_object ( uuid_str.c_str() );
  cb->wait();

  getcounter=getcounter+1;
}

BENCHMARK(Couchbase, Update, 10, 100)
{
  std::string uuid_str = uuid_list[loadcounter];
  obj->set_key( uuid_str );

  cb->save_object ( obj );
  cb->wait();

  loadcounter=loadcounter+1;
}

BENCHMARK(Couchbase, Delete, 10, 100)
{
  std::string uuid_str = uuid_list[delcounter];
  cb->delete_object ( uuid_str.c_str() );
  cb->wait();

  delcounter=delcounter+1;
}

//----------------------------------------------------------------------------//
//------------------------------Main Method-----------------------------------//
//----------------------------------------------------------------------------//

int main()
{

ServiceComponentFactory factory;

//Application Setup

std::string initFileName = "test/log4cpp_test.properties";
logging = factory.get_logging_interface(initFileName);

//Generate the UUID's for the benchmarks
int i=0;
int uuid_gen_result;
uuid_t uuid;
for (i=0; i< 1001; i++) {
  //Generate a new key for the object
  std::string uuid_str = std::to_string(i);
  uuid_list.push_back(uuid_str);
}

//Generate an object to use for the benchmarks

obj = new TestData (0, 1);

//Set up the Couchbase Admin
//Build the Couchbase Admin (which will automatically connect to the DB)
cb = factory.get_couchbase_interface("couchbase://localhost/default");

//Supports both password authentication and clustering
printf("Connected to Couchbase");
//Bind callbacks
cb->bind_storage_callback(my_storage_callback);
cb->bind_get_callback(my_retrieval_callback);
cb->bind_delete_callback(my_delete_callback);

//------------------------------Run Tests-------------------------------------//
//----------------------------------------------------------------------------//

hayai::ConsoleOutputter consoleOutputter;

hayai::Benchmarker::AddOutputter(consoleOutputter);
hayai::Benchmarker::RunAllTests();

//-------------------------Post-Test Teardown---------------------------------//
//----------------------------------------------------------------------------//

delete obj;
delete cb;
delete logging;

return 0;

}
<|endoftext|>