<commit_before>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass uses the top-down data structure graphs to implement a simple
// context sensitive alias analysis.
//
//===----------------------------------------------------------------------===//

#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/DataStructure/DataStructure.h"
#include "llvm/Analysis/DataStructure/DSGraph.h"
using namespace llvm;

namespace {
  class DSAA : public ModulePass, public AliasAnalysis {
    TDDataStructures *TD;
    BUDataStructures *BU;
  public:
    DSAA() : TD(0) {}

    //------------------------------------------------
    // Implement the Pass API
    //

    // run - Build up the result graph, representing the pointer graph for the
    // program.
    //
    bool runOnModule(Module &M) {
      InitializeAliasAnalysis(this);
      TD = &getAnalysis<TDDataStructures>();
      BU = &getAnalysis<BUDataStructures>();
      return false;
    }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AliasAnalysis::getAnalysisUsage(AU);
      AU.setPreservesAll();                         // Does not transform code
      AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures
      AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures
    }

    //------------------------------------------------
    // Implement the AliasAnalysis API
    //

    AliasResult alias(const Value *V1, unsigned V1Size,
                      const Value *V2, unsigned V2Size);

    void getMustAliases(Value *P, std::vector<Value*> &RetVals);

    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
    ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
      return AliasAnalysis::getModRefInfo(CS1,CS2);
    }

    virtual void deleteValue(Value *V) {
      BU->deleteValue(V);
      TD->deleteValue(V);
    }

    virtual void copyValue(Value *From, Value *To) {
      if (From == To) return;
      BU->copyValue(From, To);
      TD->copyValue(From, To);
    }

  private:
    DSGraph *getGraphForValue(const Value *V);
  };

  // Register the pass...
  RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis");

  // Register as an implementation of AliasAnalysis
  RegisterAnalysisGroup<AliasAnalysis, DSAA> Y;
}

ModulePass *llvm::createDSAAPass() { return new DSAA(); }

// getGraphForValue - Return the DSGraph to use for queries about the specified
// value...
//
DSGraph *DSAA::getGraphForValue(const Value *V) {
  if (const Instruction *I = dyn_cast<Instruction>(V))
    return &TD->getDSGraph(*I->getParent()->getParent());
  else if (const Argument *A = dyn_cast<Argument>(V))
    return &TD->getDSGraph(*A->getParent());
  else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
    return &TD->getDSGraph(*BB->getParent());
  return 0;
}

// isSinglePhysicalObject - For now, the only case that we know that there is
// only one memory object in the node is when there is a single global in the
// node, and the only composition bit set is Global.
//
static bool isSinglePhysicalObject(DSNode *N) {
  assert(N->isComplete() && "Can only tell if this is a complete object!");
  return N->isGlobalNode() && N->getGlobals().size() == 1 &&
         !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode();
}

// alias - This is the only method here that does anything interesting...
AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size,
                                       const Value *V2, unsigned V2Size) {
  if (V1 == V2) return MustAlias;

  DSGraph *G1 = getGraphForValue(V1);
  DSGraph *G2 = getGraphForValue(V2);
  assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?");

  // Get the graph to use...
  DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph()));

  const DSGraph::ScalarMapTy &GSM = G.getScalarMap();
  DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1);
  if (I == GSM.end()) return NoAlias;

  DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2);
  if (J == GSM.end()) return NoAlias;

  DSNode  *N1 = I->second.getNode(),  *N2 = J->second.getNode();
  unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
  if (N1 == 0 || N2 == 0)
    return MayAlias;  // Can't tell whether anything aliases null.

  // We can only make a judgment of one of the nodes is complete...
  if (N1->isComplete() || N2->isComplete()) {
    if (N1 != N2)
      return NoAlias;   // Completely different nodes.

#if 0  // This does not correctly handle arrays!
    // Both point to the same node and same offset, and there is only one
    // physical memory object represented in the node, return must alias.
    //
    // FIXME: This isn't correct because we do not handle array indexing
    // correctly.

    if (O1 == O2 && isSinglePhysicalObject(N1))
      return MustAlias; // Exactly the same object & offset
#endif

    // See if they point to different offsets...  if so, we may be able to
    // determine that they do not alias...
    if (O1 != O2) {
      if (O2 < O1) {    // Ensure that O1 <= O2
        std::swap(V1, V2);
        std::swap(O1, O2);
        std::swap(V1Size, V2Size);
      }

      // FIXME: This is not correct because we do not handle array
      // indexing correctly with this check!
      //if (O1+V1Size <= O2) return NoAlias;
    }
  }

  // FIXME: we could improve on this by checking the globals graph for aliased
  // global queries...
  return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
}

/// getModRefInfo - does a callsite modify or reference a value?
///
AliasAnalysis::ModRefResult
DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
  AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size);
  Function *F = CS.getCalledFunction();

  if (!F || F->isExternal() || Result == NoModRef)
    return Result;

  // Get the graphs for the callee and caller.  Note that we want the BU graph
  // for the callee because we don't want all caller's effects incorporated!
  const Function *Caller = CS.getInstruction()->getParent()->getParent();
  DSGraph &CallerTDGraph = TD->getDSGraph(*Caller);
  DSGraph &CalleeBUGraph = BU->getDSGraph(*F);

  // Figure out which node in the TD graph this pointer corresponds to.
  DSScalarMap &CallerSM = CallerTDGraph.getScalarMap();
  DSScalarMap::iterator NI = CallerSM.find(P);
  if (NI == CallerSM.end()) {
    if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P))
      Result = NoModRef;                 // null is never modified :)
    else {
      assert(isa<GlobalVariable>(P) &&
    cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() &&
             "This isn't a global that DSA inconsiderately dropped "
             "from the graph?");
    }
    return Result;
  }

  const DSNode *N = NI->second.getNode();
  assert(N && "Null pointer in scalar map??");

  // Compute the mapping from nodes in the callee graph to the nodes in the
  // caller graph for this call site.
  DSGraph::NodeMapTy CalleeCallerMap;
  DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS);
  CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph,
                                           CalleeCallerMap);

  // Loop over all of the nodes in the callee that correspond to "N", keeping
  // track of aggregate mod/ref info.
  bool NeverReads = true, NeverWrites = true;
  for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(),
         E = CalleeCallerMap.end(); I != E; ++I)
    if (I->second.getNode() == N) {
      if (I->first->isModified())
        NeverWrites = false;
      if (I->first->isRead())
        NeverReads = false;
      if (NeverReads == false && NeverWrites == false)
        return Result;
    }

  if (NeverWrites)      // We proved it was not modified.
    Result = ModRefResult(Result & ~Mod);
  if (NeverReads)       // We proved it was not read.
    Result = ModRefResult(Result & ~Ref);

  return Result;
}

/// getMustAliases - If there are any pointers known that must alias this
/// pointer, return them now.  This allows alias-set based alias analyses to
/// perform a form a value numbering (which is exposed by load-vn).  If an alias
/// analysis supports this, it should ADD any must aliased pointers to the
/// specified vector.
///
void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
#if 0    // This does not correctly handle arrays!
  // Currently the only must alias information we can provide is to say that
  // something is equal to a global value. If we already have a global value,
  // don't get worked up about it.
  if (!isa<GlobalValue>(P)) {
    DSGraph *G = getGraphForValue(P);
    if (!G) G = &TD->getGlobalsGraph();

    // The only must alias information we can currently determine occurs when
    // the node for P is a global node with only one entry.
    DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P);
    if (I != G->getScalarMap().end()) {
      DSNode *N = I->second.getNode();
      if (N->isComplete() && isSinglePhysicalObject(N))
        RetVals.push_back(N->getGlobals()[0]);
    }
  }
#endif
  return AliasAnalysis::getMustAliases(P, RetVals);
}

<commit_msg>#ifdef out a function only used by #ifdef'd code.<commit_after>//===- DataStructureAA.cpp - Data Structure Based Alias Analysis ----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This pass uses the top-down data structure graphs to implement a simple
// context sensitive alias analysis.
//
//===----------------------------------------------------------------------===//

#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Analysis/DataStructure/DataStructure.h"
#include "llvm/Analysis/DataStructure/DSGraph.h"
using namespace llvm;

namespace {
  class DSAA : public ModulePass, public AliasAnalysis {
    TDDataStructures *TD;
    BUDataStructures *BU;
  public:
    DSAA() : TD(0) {}

    //------------------------------------------------
    // Implement the Pass API
    //

    // run - Build up the result graph, representing the pointer graph for the
    // program.
    //
    bool runOnModule(Module &M) {
      InitializeAliasAnalysis(this);
      TD = &getAnalysis<TDDataStructures>();
      BU = &getAnalysis<BUDataStructures>();
      return false;
    }

    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
      AliasAnalysis::getAnalysisUsage(AU);
      AU.setPreservesAll();                         // Does not transform code
      AU.addRequiredTransitive<TDDataStructures>(); // Uses TD Datastructures
      AU.addRequiredTransitive<BUDataStructures>(); // Uses BU Datastructures
    }

    //------------------------------------------------
    // Implement the AliasAnalysis API
    //

    AliasResult alias(const Value *V1, unsigned V1Size,
                      const Value *V2, unsigned V2Size);

    void getMustAliases(Value *P, std::vector<Value*> &RetVals);

    ModRefResult getModRefInfo(CallSite CS, Value *P, unsigned Size);
    ModRefResult getModRefInfo(CallSite CS1, CallSite CS2) {
      return AliasAnalysis::getModRefInfo(CS1,CS2);
    }

    virtual void deleteValue(Value *V) {
      BU->deleteValue(V);
      TD->deleteValue(V);
    }

    virtual void copyValue(Value *From, Value *To) {
      if (From == To) return;
      BU->copyValue(From, To);
      TD->copyValue(From, To);
    }

  private:
    DSGraph *getGraphForValue(const Value *V);
  };

  // Register the pass...
  RegisterOpt<DSAA> X("ds-aa", "Data Structure Graph Based Alias Analysis");

  // Register as an implementation of AliasAnalysis
  RegisterAnalysisGroup<AliasAnalysis, DSAA> Y;
}

ModulePass *llvm::createDSAAPass() { return new DSAA(); }

// getGraphForValue - Return the DSGraph to use for queries about the specified
// value...
//
DSGraph *DSAA::getGraphForValue(const Value *V) {
  if (const Instruction *I = dyn_cast<Instruction>(V))
    return &TD->getDSGraph(*I->getParent()->getParent());
  else if (const Argument *A = dyn_cast<Argument>(V))
    return &TD->getDSGraph(*A->getParent());
  else if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
    return &TD->getDSGraph(*BB->getParent());
  return 0;
}

#if 0
// isSinglePhysicalObject - For now, the only case that we know that there is
// only one memory object in the node is when there is a single global in the
// node, and the only composition bit set is Global.
//
static bool isSinglePhysicalObject(DSNode *N) {
  assert(N->isComplete() && "Can only tell if this is a complete object!");
  return N->isGlobalNode() && N->getGlobals().size() == 1 &&
         !N->isHeapNode() && !N->isAllocaNode() && !N->isUnknownNode();
}
#endif

// alias - This is the only method here that does anything interesting...
AliasAnalysis::AliasResult DSAA::alias(const Value *V1, unsigned V1Size,
                                       const Value *V2, unsigned V2Size) {
  if (V1 == V2) return MustAlias;

  DSGraph *G1 = getGraphForValue(V1);
  DSGraph *G2 = getGraphForValue(V2);
  assert((!G1 || !G2 || G1 == G2) && "Alias query for 2 different functions?");

  // Get the graph to use...
  DSGraph &G = *(G1 ? G1 : (G2 ? G2 : &TD->getGlobalsGraph()));

  const DSGraph::ScalarMapTy &GSM = G.getScalarMap();
  DSGraph::ScalarMapTy::const_iterator I = GSM.find((Value*)V1);
  if (I == GSM.end()) return NoAlias;

  DSGraph::ScalarMapTy::const_iterator J = GSM.find((Value*)V2);
  if (J == GSM.end()) return NoAlias;

  DSNode  *N1 = I->second.getNode(),  *N2 = J->second.getNode();
  unsigned O1 = I->second.getOffset(), O2 = J->second.getOffset();
  if (N1 == 0 || N2 == 0)
    return MayAlias;  // Can't tell whether anything aliases null.

  // We can only make a judgment of one of the nodes is complete...
  if (N1->isComplete() || N2->isComplete()) {
    if (N1 != N2)
      return NoAlias;   // Completely different nodes.

#if 0  // This does not correctly handle arrays!
    // Both point to the same node and same offset, and there is only one
    // physical memory object represented in the node, return must alias.
    //
    // FIXME: This isn't correct because we do not handle array indexing
    // correctly.

    if (O1 == O2 && isSinglePhysicalObject(N1))
      return MustAlias; // Exactly the same object & offset
#endif

    // See if they point to different offsets...  if so, we may be able to
    // determine that they do not alias...
    if (O1 != O2) {
      if (O2 < O1) {    // Ensure that O1 <= O2
        std::swap(V1, V2);
        std::swap(O1, O2);
        std::swap(V1Size, V2Size);
      }

      // FIXME: This is not correct because we do not handle array
      // indexing correctly with this check!
      //if (O1+V1Size <= O2) return NoAlias;
    }
  }

  // FIXME: we could improve on this by checking the globals graph for aliased
  // global queries...
  return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
}

/// getModRefInfo - does a callsite modify or reference a value?
///
AliasAnalysis::ModRefResult
DSAA::getModRefInfo(CallSite CS, Value *P, unsigned Size) {
  AliasAnalysis::ModRefResult Result =AliasAnalysis::getModRefInfo(CS, P, Size);
  Function *F = CS.getCalledFunction();

  if (!F || F->isExternal() || Result == NoModRef)
    return Result;

  // Get the graphs for the callee and caller.  Note that we want the BU graph
  // for the callee because we don't want all caller's effects incorporated!
  const Function *Caller = CS.getInstruction()->getParent()->getParent();
  DSGraph &CallerTDGraph = TD->getDSGraph(*Caller);
  DSGraph &CalleeBUGraph = BU->getDSGraph(*F);

  // Figure out which node in the TD graph this pointer corresponds to.
  DSScalarMap &CallerSM = CallerTDGraph.getScalarMap();
  DSScalarMap::iterator NI = CallerSM.find(P);
  if (NI == CallerSM.end()) {
    if (isa<ConstantPointerNull>(P) || isa<UndefValue>(P))
      Result = NoModRef;                 // null is never modified :)
    else {
      assert(isa<GlobalVariable>(P) &&
    cast<GlobalVariable>(P)->getType()->getElementType()->isFirstClassType() &&
             "This isn't a global that DSA inconsiderately dropped "
             "from the graph?");
    }
    return Result;
  }

  const DSNode *N = NI->second.getNode();
  assert(N && "Null pointer in scalar map??");

  // Compute the mapping from nodes in the callee graph to the nodes in the
  // caller graph for this call site.
  DSGraph::NodeMapTy CalleeCallerMap;
  DSCallSite DSCS = CallerTDGraph.getDSCallSiteForCallSite(CS);
  CallerTDGraph.computeCalleeCallerMapping(DSCS, *F, CalleeBUGraph,
                                           CalleeCallerMap);

  // Loop over all of the nodes in the callee that correspond to "N", keeping
  // track of aggregate mod/ref info.
  bool NeverReads = true, NeverWrites = true;
  for (DSGraph::NodeMapTy::iterator I = CalleeCallerMap.begin(),
         E = CalleeCallerMap.end(); I != E; ++I)
    if (I->second.getNode() == N) {
      if (I->first->isModified())
        NeverWrites = false;
      if (I->first->isRead())
        NeverReads = false;
      if (NeverReads == false && NeverWrites == false)
        return Result;
    }

  if (NeverWrites)      // We proved it was not modified.
    Result = ModRefResult(Result & ~Mod);
  if (NeverReads)       // We proved it was not read.
    Result = ModRefResult(Result & ~Ref);

  return Result;
}

/// getMustAliases - If there are any pointers known that must alias this
/// pointer, return them now.  This allows alias-set based alias analyses to
/// perform a form a value numbering (which is exposed by load-vn).  If an alias
/// analysis supports this, it should ADD any must aliased pointers to the
/// specified vector.
///
void DSAA::getMustAliases(Value *P, std::vector<Value*> &RetVals) {
#if 0    // This does not correctly handle arrays!
  // Currently the only must alias information we can provide is to say that
  // something is equal to a global value. If we already have a global value,
  // don't get worked up about it.
  if (!isa<GlobalValue>(P)) {
    DSGraph *G = getGraphForValue(P);
    if (!G) G = &TD->getGlobalsGraph();

    // The only must alias information we can currently determine occurs when
    // the node for P is a global node with only one entry.
    DSGraph::ScalarMapTy::const_iterator I = G->getScalarMap().find(P);
    if (I != G->getScalarMap().end()) {
      DSNode *N = I->second.getNode();
      if (N->isComplete() && isSinglePhysicalObject(N))
        RetVals.push_back(N->getGlobals()[0]);
    }
  }
#endif
  return AliasAnalysis::getMustAliases(P, RetVals);
}

<|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vprConfig.h>

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

#ifdef HAVE_BSTRING_H
#include <bstring.h>
#endif

#include <sys/time.h>
#include <errno.h>

#include <md/POSIX/SelectorImpBSD.h>
#include <Utils/Assert.h>

namespace vpr {

//: Add the given handle to the selector
//! PRE: handle is a valid handle
//! POST: handle is added to the handle set, and initialized to a mask of
//+       no-events
bool
SelectorImpBSD::addHandle (IOSys::Handle handle) {
   bool status;

   if ( getHandle(handle) == mPollDescs.end() ) {
      BSDPollDesc new_desc;
      new_desc.fd        = handle;
      new_desc.in_flags  = 0;
      new_desc.out_flags = 0;

      mPollDescs.push_back(new_desc);
      status = true;
   }
   else {
      status = false;
   }

   return status;
}

//: Remove a handle from the selector
//! PRE: handle is in the selector
//! POST: handle is removed from the set of valid handles
bool
SelectorImpBSD::removeHandle (IOSys::Handle handle) {
   bool status;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      status = false;
   }
   else {
      mPollDescs.erase(i);
      status = true;
   }

   return status;
}

//: Set the event flags going in to the select to mask
bool
SelectorImpBSD::setIn (IOSys::Handle handle, vpr::Uint16 mask) {
   bool status;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      status = false;
   }
   else {
      (*i).in_flags = mask;
      status = true;
   }

   return status;
}

//: Get the current in flag mask
vpr::Uint16
SelectorImpBSD::getIn (IOSys::Handle handle) {
   vpr::Uint16 flags;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      // XXX: This is VERY bad thing to do.  Need to have an error code instead
      flags = 0;
   }
   else {
      flags = (*i).in_flags;
   }

   return flags;
}

//: Get the current out flag mask
vpr::Uint16
SelectorImpBSD::getOut (IOSys::Handle handle) {
   vpr::Uint16 flags;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      // XXX: This is VERY bad thing to do.  Need to have an error code instead
      flags = 0;
   }
   else {
      flags = (*i).out_flags;
   }

   return flags;
}

//: Select
//! ARGS: numWithEvents - Upon completion, this holds the number of items that
//+                       have events
//! ARGS: timeout - The number of msecs to select for (0 - don't wait)
Status
SelectorImpBSD::select (vpr::Uint16& numWithEvents, vpr::Uint16 timeout) {
   vpr::Status ret_val;
   int result;
   fd_set read_set, write_set, exception_set;
   std::vector<BSDPollDesc>::iterator i;
   struct timeval timeout_obj;

   // Zero everything out before doing anything else.
   FD_ZERO(&read_set);
   FD_ZERO(&write_set);
   FD_ZERO(&exception_set);

   for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) {
      if ( (*i).in_flags & SelectorBase::VPR_READ ) {
         FD_SET((*i).fd, &read_set);
      }

      if ( (*i).in_flags & SelectorBase::VPR_WRITE ) {
         FD_SET((*i).fd, &write_set);
      }

      if ( (*i).in_flags & SelectorBase::VPR_EXCEPT ) {
         FD_SET((*i).fd, &exception_set);
      }
   }

   // Apparently select(2) doesn't like if the microsecond member has a time
   // larger than 1 second, so if timeout (given in milliseconds) is larger
   // than 1000, we have to split it up between the seconds and microseconds
   // members.
   if ( timeout >= 1000 ) {
      timeout_obj.tv_sec  = timeout / 1000;
      timeout_obj.tv_usec = (timeout % 1000) * 1000000;
   }
   else {
      timeout_obj.tv_sec  = 0;
      timeout_obj.tv_usec = timeout * 1000;
   }

   // If timeout is 0, this will be the same as polling the descriptors.  To
   // get no timeout, NULL must be passed to select(2).
   result = ::select(mPollDescs.size(), &read_set, &write_set, &exception_set,
                     (timeout > 0) ? &timeout_obj : NULL);

   // D'oh!
   if ( -1 == result ) {
      fprintf(stderr, "SelectorImpBSD::select: Error selecting: %s\n",
              strerror(errno));
      numWithEvents = 0;
      ret_val.setCode(Status::Failure);
   }
   // Timeout.
   else if ( 0 == result ) {
      numWithEvents = 0;
      ret_val.setCode(Status::Timeout);
   }
   // We got one!
   else {
      for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) {
         if ( FD_ISSET((*i).fd, &read_set) ) {
            (*i).out_flags |= SelectorBase::VPR_READ;
         }

         if ( FD_ISSET((*i).fd, &write_set) ) {
            (*i).out_flags |= SelectorBase::VPR_WRITE;
         }

         if ( FD_ISSET((*i).fd, &exception_set) ) {
            (*i).out_flags |= SelectorBase::VPR_EXCEPT;
         }
      }
   }

   numWithEvents = result;

   return ret_val;
}

// Get the index of the handle given
//! RETURNS: .end() - Not found, else the index to the handle in mPollDescs
std::vector<SelectorImpBSD::BSDPollDesc>::iterator
SelectorImpBSD::getHandle (int handle) {
   // XXX: Should probably be replaced by a map in the future for speed

   for(std::vector<BSDPollDesc>::iterator i=mPollDescs.begin();
          i != mPollDescs.end();i++)
   {
      if((*i).fd == handle)
         return i;
   }

   return mPollDescs.end();
}

}  // namespace vpr
<commit_msg>In select(), 'numWithEvents' was being set to the value of 'result' even when select(2) failed.  This assginment should only be made when one or more of the file descriptors is ready.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vprConfig.h>

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

#ifdef HAVE_BSTRING_H
#include <bstring.h>
#endif

#include <sys/time.h>
#include <errno.h>

#include <md/POSIX/SelectorImpBSD.h>
#include <Utils/Assert.h>

namespace vpr {

//: Add the given handle to the selector
//! PRE: handle is a valid handle
//! POST: handle is added to the handle set, and initialized to a mask of
//+       no-events
bool
SelectorImpBSD::addHandle (IOSys::Handle handle) {
   bool status;

   if ( getHandle(handle) == mPollDescs.end() ) {
      BSDPollDesc new_desc;
      new_desc.fd        = handle;
      new_desc.in_flags  = 0;
      new_desc.out_flags = 0;

      mPollDescs.push_back(new_desc);
      status = true;
   }
   else {
      status = false;
   }

   return status;
}

//: Remove a handle from the selector
//! PRE: handle is in the selector
//! POST: handle is removed from the set of valid handles
bool
SelectorImpBSD::removeHandle (IOSys::Handle handle) {
   bool status;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      status = false;
   }
   else {
      mPollDescs.erase(i);
      status = true;
   }

   return status;
}

//: Set the event flags going in to the select to mask
bool
SelectorImpBSD::setIn (IOSys::Handle handle, vpr::Uint16 mask) {
   bool status;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      status = false;
   }
   else {
      (*i).in_flags = mask;
      status = true;
   }

   return status;
}

//: Get the current in flag mask
vpr::Uint16
SelectorImpBSD::getIn (IOSys::Handle handle) {
   vpr::Uint16 flags;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      // XXX: This is VERY bad thing to do.  Need to have an error code instead
      flags = 0;
   }
   else {
      flags = (*i).in_flags;
   }

   return flags;
}

//: Get the current out flag mask
vpr::Uint16
SelectorImpBSD::getOut (IOSys::Handle handle) {
   vpr::Uint16 flags;
   std::vector<BSDPollDesc>::iterator i = getHandle(handle);

   if ( mPollDescs.end() == i ) {
      // XXX: This is VERY bad thing to do.  Need to have an error code instead
      flags = 0;
   }
   else {
      flags = (*i).out_flags;
   }

   return flags;
}

//: Select
//! ARGS: numWithEvents - Upon completion, this holds the number of items that
//+                       have events
//! ARGS: timeout - The number of msecs to select for (0 - don't wait)
Status
SelectorImpBSD::select (vpr::Uint16& numWithEvents, vpr::Uint16 timeout) {
   vpr::Status ret_val;
   int result;
   fd_set read_set, write_set, exception_set;
   std::vector<BSDPollDesc>::iterator i;
   struct timeval timeout_obj;

   // Zero everything out before doing anything else.
   FD_ZERO(&read_set);
   FD_ZERO(&write_set);
   FD_ZERO(&exception_set);

   for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) {
      if ( (*i).in_flags & SelectorBase::VPR_READ ) {
         FD_SET((*i).fd, &read_set);
      }

      if ( (*i).in_flags & SelectorBase::VPR_WRITE ) {
         FD_SET((*i).fd, &write_set);
      }

      if ( (*i).in_flags & SelectorBase::VPR_EXCEPT ) {
         FD_SET((*i).fd, &exception_set);
      }
   }

   // Apparently select(2) doesn't like if the microsecond member has a time
   // larger than 1 second, so if timeout (given in milliseconds) is larger
   // than 1000, we have to split it up between the seconds and microseconds
   // members.
   if ( timeout >= 1000 ) {
      timeout_obj.tv_sec  = timeout / 1000;
      timeout_obj.tv_usec = (timeout % 1000) * 1000000;
   }
   else {
      timeout_obj.tv_sec  = 0;
      timeout_obj.tv_usec = timeout * 1000;
   }

   // If timeout is 0, this will be the same as polling the descriptors.  To
   // get no timeout, NULL must be passed to select(2).
   result = ::select(mPollDescs.size(), &read_set, &write_set, &exception_set,
                     (timeout > 0) ? &timeout_obj : NULL);

   // D'oh!
   if ( -1 == result ) {
      fprintf(stderr, "SelectorImpBSD::select: Error selecting: %s\n",
              strerror(errno));
      numWithEvents = 0;
      ret_val.setCode(Status::Failure);
   }
   // Timeout.
   else if ( 0 == result ) {
      numWithEvents = 0;
      ret_val.setCode(Status::Timeout);
   }
   // We got one!
   else {
      for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) {
         if ( FD_ISSET((*i).fd, &read_set) ) {
            (*i).out_flags |= SelectorBase::VPR_READ;
         }

         if ( FD_ISSET((*i).fd, &write_set) ) {
            (*i).out_flags |= SelectorBase::VPR_WRITE;
         }

         if ( FD_ISSET((*i).fd, &exception_set) ) {
            (*i).out_flags |= SelectorBase::VPR_EXCEPT;
         }
      }

      numWithEvents = result;
   }

   return ret_val;
}

// Get the index of the handle given
//! RETURNS: .end() - Not found, else the index to the handle in mPollDescs
std::vector<SelectorImpBSD::BSDPollDesc>::iterator
SelectorImpBSD::getHandle (int handle) {
   // XXX: Should probably be replaced by a map in the future for speed

   for(std::vector<BSDPollDesc>::iterator i=mPollDescs.begin();
          i != mPollDescs.end();i++)
   {
      if((*i).fd == handle)
         return i;
   }

   return mPollDescs.end();
}

}  // namespace vpr
<|endoftext|>


<commit_before>/*
Algorithm Factory
(C) 2008 Jack Lloyd
*/

#include <botan/algo_factory.h>
#include <botan/stl_util.h>
#include <botan/engine.h>
#include <botan/exceptn.h>

#include <botan/block_cipher.h>
#include <botan/stream_cipher.h>
#include <botan/hash.h>
#include <botan/mac.h>

#include <algorithm>

namespace Botan {

namespace {

/**
* Template functions for the factory prototype/search algorithm
*/
template<typename T>
T* engine_get_algo(Engine* engine, const SCAN_Name& request,
                   Algorithm_Factory& af)
   { return 0; }

template<>
BlockCipher* engine_get_algo(Engine* engine, const SCAN_Name& request,
                             Algorithm_Factory& af)
   { return engine->find_block_cipher(request, af); }

template<>
StreamCipher* engine_get_algo(Engine* engine, const SCAN_Name& request,
                              Algorithm_Factory& af)
   { return engine->find_stream_cipher(request, af); }

template<>
HashFunction* engine_get_algo(Engine* engine, const SCAN_Name& request,
                              Algorithm_Factory& af)
   { return engine->find_hash(request, af); }

template<>
MessageAuthenticationCode* engine_get_algo(Engine* engine,
                                           const SCAN_Name& request,
                                           Algorithm_Factory& af)
   { return engine->find_mac(request, af); }

template<typename T>
const T* factory_prototype(const std::string& algo_spec,
                           const std::string& provider,
                           const std::vector<Engine*>& engines,
                           Algorithm_Factory& af,
                           Algorithm_Cache<T>& cache)
   {
   if(const T* cache_hit = cache.get(algo_spec, provider))
      return cache_hit;

   SCAN_Name scan_name(algo_spec);
   for(u32bit i = 0; i != engines.size(); ++i)
      {
      T* impl = engine_get_algo<T>(engines[i], scan_name, af);
      if(impl)
         cache.add(impl, algo_spec, engines[i]->provider_name());
      }

   return cache.get(algo_spec, provider);
   }

}

/**
* Setup caches
*/
Algorithm_Factory::Algorithm_Factory(const std::vector<Engine*>& engines_in,
                                     Mutex_Factory& mf) :
   engines(engines_in),
   block_cipher_cache(mf.make()),
   stream_cipher_cache(mf.make()),
   hash_cache(mf.make()),
   mac_cache(mf.make())
   {
   }

/**
* Delete all engines
*/
Algorithm_Factory::~Algorithm_Factory()
   {
   std::for_each(engines.begin(), engines.end(), del_fun<Engine>());
   engines.clear();
   }

/**
* Set the preferred provider for an algorithm
*/
void Algorithm_Factory::set_preferred_provider(const std::string& algo_spec,
                                               const std::string& provider)
   {
   if(prototype_block_cipher(algo_spec))
      block_cipher_cache.set_preferred_provider(algo_spec, provider);
   else if(prototype_stream_cipher(algo_spec))
      stream_cipher_cache.set_preferred_provider(algo_spec, provider);
   else if(prototype_hash_function(algo_spec))
      hash_cache.set_preferred_provider(algo_spec, provider);
   else if(prototype_mac(algo_spec))
      mac_cache.set_preferred_provider(algo_spec, provider);
   }

/**
* Get an engine out of the list
*/
Engine* Algorithm_Factory::get_engine_n(u32bit n) const
   {
   if(n >= engines.size())
      return 0;
   return engines[n];
   }

/**
* Return the possible providers of a request
* Note: assumes you don't have different types by the same name
*/
std::vector<std::string>
Algorithm_Factory::providers_of(const std::string& algo_spec)
   {
   if(prototype_block_cipher(algo_spec))
      return block_cipher_cache.providers_of(algo_spec);
   else if(prototype_stream_cipher(algo_spec))
      return stream_cipher_cache.providers_of(algo_spec);
   else if(prototype_hash_function(algo_spec))
      return hash_cache.providers_of(algo_spec);
   else if(prototype_mac(algo_spec))
      return mac_cache.providers_of(algo_spec);
   else
      return std::vector<std::string>();
   }

/**
* Return the prototypical block cipher cooresponding to this request
*/
const BlockCipher*
Algorithm_Factory::prototype_block_cipher(const std::string& algo_spec,
                                          const std::string& provider)
   {
   return factory_prototype<BlockCipher>(algo_spec, provider, engines,
                                          *this, block_cipher_cache);
   }

/**
* Return the prototypical stream cipher cooresponding to this request
*/
const StreamCipher*
Algorithm_Factory::prototype_stream_cipher(const std::string& algo_spec,
                                           const std::string& provider)
   {
   return factory_prototype<StreamCipher>(algo_spec, provider, engines,
                                          *this, stream_cipher_cache);
   }

/**
* Return the prototypical object cooresponding to this request (if found)
*/
const HashFunction*
Algorithm_Factory::prototype_hash_function(const std::string& algo_spec,
                                           const std::string& provider)
   {
   return factory_prototype<HashFunction>(algo_spec, provider, engines,
                                          *this, hash_cache);
   }

/**
* Return the prototypical object cooresponding to this request
*/
const MessageAuthenticationCode*
Algorithm_Factory::prototype_mac(const std::string& algo_spec,
                                 const std::string& provider)
   {
   return factory_prototype<MessageAuthenticationCode>(algo_spec, provider, engines,
                                                       *this, mac_cache);
   }

/**
* Return a new block cipher cooresponding to this request
*/
BlockCipher*
Algorithm_Factory::make_block_cipher(const std::string& algo_spec,
                                     const std::string& provider)
   {
   if(const BlockCipher* proto = prototype_block_cipher(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Return a new stream cipher cooresponding to this request
*/
StreamCipher*
Algorithm_Factory::make_stream_cipher(const std::string& algo_spec,
                                      const std::string& provider)
   {
   if(const StreamCipher* proto = prototype_stream_cipher(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Return a new object cooresponding to this request
*/
HashFunction*
Algorithm_Factory::make_hash_function(const std::string& algo_spec,
                                      const std::string& provider)
   {
   if(const HashFunction* proto = prototype_hash_function(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Return a new object cooresponding to this request
*/
MessageAuthenticationCode*
Algorithm_Factory::make_mac(const std::string& algo_spec,
                            const std::string& provider)
   {
   if(const MessageAuthenticationCode* proto = prototype_mac(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Add a new block cipher
*/
void Algorithm_Factory::add_block_cipher(BlockCipher* block_cipher,
                                         const std::string& provider)
   {
   block_cipher_cache.add(block_cipher, block_cipher->name(), provider);
   }

/**
* Add a new stream cipher
*/
void Algorithm_Factory::add_stream_cipher(StreamCipher* stream_cipher,
                                         const std::string& provider)
   {
   stream_cipher_cache.add(stream_cipher, stream_cipher->name(), provider);
   }

/**
* Add a new hash
*/
void Algorithm_Factory::add_hash_function(HashFunction* hash,
                                          const std::string& provider)
   {
   hash_cache.add(hash, hash->name(), provider);
   }

/**
* Add a new mac
*/
void Algorithm_Factory::add_mac(MessageAuthenticationCode* mac,
                                const std::string& provider)
   {
   mac_cache.add(mac, mac->name(), provider);
   }

}
<commit_msg>Add comment about non-obvious but vital side effect<commit_after>/*
Algorithm Factory
(C) 2008 Jack Lloyd
*/

#include <botan/algo_factory.h>
#include <botan/stl_util.h>
#include <botan/engine.h>
#include <botan/exceptn.h>

#include <botan/block_cipher.h>
#include <botan/stream_cipher.h>
#include <botan/hash.h>
#include <botan/mac.h>

#include <algorithm>

namespace Botan {

namespace {

/**
* Template functions for the factory prototype/search algorithm
*/
template<typename T>
T* engine_get_algo(Engine* engine, const SCAN_Name& request,
                   Algorithm_Factory& af)
   { return 0; }

template<>
BlockCipher* engine_get_algo(Engine* engine, const SCAN_Name& request,
                             Algorithm_Factory& af)
   { return engine->find_block_cipher(request, af); }

template<>
StreamCipher* engine_get_algo(Engine* engine, const SCAN_Name& request,
                              Algorithm_Factory& af)
   { return engine->find_stream_cipher(request, af); }

template<>
HashFunction* engine_get_algo(Engine* engine, const SCAN_Name& request,
                              Algorithm_Factory& af)
   { return engine->find_hash(request, af); }

template<>
MessageAuthenticationCode* engine_get_algo(Engine* engine,
                                           const SCAN_Name& request,
                                           Algorithm_Factory& af)
   { return engine->find_mac(request, af); }

template<typename T>
const T* factory_prototype(const std::string& algo_spec,
                           const std::string& provider,
                           const std::vector<Engine*>& engines,
                           Algorithm_Factory& af,
                           Algorithm_Cache<T>& cache)
   {
   if(const T* cache_hit = cache.get(algo_spec, provider))
      return cache_hit;

   SCAN_Name scan_name(algo_spec);
   for(u32bit i = 0; i != engines.size(); ++i)
      {
      T* impl = engine_get_algo<T>(engines[i], scan_name, af);
      if(impl)
         cache.add(impl, algo_spec, engines[i]->provider_name());
      }

   return cache.get(algo_spec, provider);
   }

}

/**
* Setup caches
*/
Algorithm_Factory::Algorithm_Factory(const std::vector<Engine*>& engines_in,
                                     Mutex_Factory& mf) :
   engines(engines_in),
   block_cipher_cache(mf.make()),
   stream_cipher_cache(mf.make()),
   hash_cache(mf.make()),
   mac_cache(mf.make())
   {
   }

/**
* Delete all engines
*/
Algorithm_Factory::~Algorithm_Factory()
   {
   std::for_each(engines.begin(), engines.end(), del_fun<Engine>());
   engines.clear();
   }

/**
* Set the preferred provider for an algorithm
*/
void Algorithm_Factory::set_preferred_provider(const std::string& algo_spec,
                                               const std::string& provider)
   {
   if(prototype_block_cipher(algo_spec))
      block_cipher_cache.set_preferred_provider(algo_spec, provider);
   else if(prototype_stream_cipher(algo_spec))
      stream_cipher_cache.set_preferred_provider(algo_spec, provider);
   else if(prototype_hash_function(algo_spec))
      hash_cache.set_preferred_provider(algo_spec, provider);
   else if(prototype_mac(algo_spec))
      mac_cache.set_preferred_provider(algo_spec, provider);
   }

/**
* Get an engine out of the list
*/
Engine* Algorithm_Factory::get_engine_n(u32bit n) const
   {
   if(n >= engines.size())
      return 0;
   return engines[n];
   }

/**
* Return the possible providers of a request
* Note: assumes you don't have different types by the same name
*/
std::vector<std::string>
Algorithm_Factory::providers_of(const std::string& algo_spec)
   {
   /* The checks with if(prototype_X(algo_spec)) have the effect of
      forcing a full search, since otherwise there might not be any
      providers at all in the cache.
   */

   if(prototype_block_cipher(algo_spec))
      return block_cipher_cache.providers_of(algo_spec);
   else if(prototype_stream_cipher(algo_spec))
      return stream_cipher_cache.providers_of(algo_spec);
   else if(prototype_hash_function(algo_spec))
      return hash_cache.providers_of(algo_spec);
   else if(prototype_mac(algo_spec))
      return mac_cache.providers_of(algo_spec);
   else
      return std::vector<std::string>();
   }

/**
* Return the prototypical block cipher cooresponding to this request
*/
const BlockCipher*
Algorithm_Factory::prototype_block_cipher(const std::string& algo_spec,
                                          const std::string& provider)
   {
   return factory_prototype<BlockCipher>(algo_spec, provider, engines,
                                          *this, block_cipher_cache);
   }

/**
* Return the prototypical stream cipher cooresponding to this request
*/
const StreamCipher*
Algorithm_Factory::prototype_stream_cipher(const std::string& algo_spec,
                                           const std::string& provider)
   {
   return factory_prototype<StreamCipher>(algo_spec, provider, engines,
                                          *this, stream_cipher_cache);
   }

/**
* Return the prototypical object cooresponding to this request (if found)
*/
const HashFunction*
Algorithm_Factory::prototype_hash_function(const std::string& algo_spec,
                                           const std::string& provider)
   {
   return factory_prototype<HashFunction>(algo_spec, provider, engines,
                                          *this, hash_cache);
   }

/**
* Return the prototypical object cooresponding to this request
*/
const MessageAuthenticationCode*
Algorithm_Factory::prototype_mac(const std::string& algo_spec,
                                 const std::string& provider)
   {
   return factory_prototype<MessageAuthenticationCode>(algo_spec, provider, engines,
                                                       *this, mac_cache);
   }

/**
* Return a new block cipher cooresponding to this request
*/
BlockCipher*
Algorithm_Factory::make_block_cipher(const std::string& algo_spec,
                                     const std::string& provider)
   {
   if(const BlockCipher* proto = prototype_block_cipher(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Return a new stream cipher cooresponding to this request
*/
StreamCipher*
Algorithm_Factory::make_stream_cipher(const std::string& algo_spec,
                                      const std::string& provider)
   {
   if(const StreamCipher* proto = prototype_stream_cipher(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Return a new object cooresponding to this request
*/
HashFunction*
Algorithm_Factory::make_hash_function(const std::string& algo_spec,
                                      const std::string& provider)
   {
   if(const HashFunction* proto = prototype_hash_function(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Return a new object cooresponding to this request
*/
MessageAuthenticationCode*
Algorithm_Factory::make_mac(const std::string& algo_spec,
                            const std::string& provider)
   {
   if(const MessageAuthenticationCode* proto = prototype_mac(algo_spec, provider))
      return proto->clone();
   throw Algorithm_Not_Found(algo_spec);
   }

/**
* Add a new block cipher
*/
void Algorithm_Factory::add_block_cipher(BlockCipher* block_cipher,
                                         const std::string& provider)
   {
   block_cipher_cache.add(block_cipher, block_cipher->name(), provider);
   }

/**
* Add a new stream cipher
*/
void Algorithm_Factory::add_stream_cipher(StreamCipher* stream_cipher,
                                         const std::string& provider)
   {
   stream_cipher_cache.add(stream_cipher, stream_cipher->name(), provider);
   }

/**
* Add a new hash
*/
void Algorithm_Factory::add_hash_function(HashFunction* hash,
                                          const std::string& provider)
   {
   hash_cache.add(hash, hash->name(), provider);
   }

/**
* Add a new mac
*/
void Algorithm_Factory::add_mac(MessageAuthenticationCode* mac,
                                const std::string& provider)
   {
   mac_cache.add(mac, mac->name(), provider);
   }

}
<|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2002 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>

#include <vrj/Display/SurfaceViewport.h>
#include <vrj/Display/WallProjection.h>
#include <vrj/Display/TrackedWallProjection.h>
#include <gmtl/Math.h>
//#include <vrj/Math/Coord.h>
#include <gmtl/Vec.h>
#include <jccl/Config/ConfigChunk.h>
#include <vrj/Kernel/User.h>

#include <gadget/Type/Position/PositionUnitConversion.h>

#include <gmtl/Matrix.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/Generate.h>
#include <gmtl/Xforms.h>

namespace vrj
{

void SurfaceViewport::config(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);
   vprASSERT(chunk->getDescToken() == std::string("surfaceViewport"));

   Viewport::config(chunk);     // Call base class config

   mType = SURFACE;

   // Read in the corners
   jccl::ConfigChunkPtr ll_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",0);
   jccl::ConfigChunkPtr lr_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",1);
   jccl::ConfigChunkPtr ur_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",2);
   jccl::ConfigChunkPtr ul_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",3);
   mLLCorner.set(ll_corner_chunk->getProperty<float>("x"),
                 ll_corner_chunk->getProperty<float>("y"),
                 ll_corner_chunk->getProperty<float>("z"));
   mLRCorner.set(lr_corner_chunk->getProperty<float>("x"),
                 lr_corner_chunk->getProperty<float>("y"),
                 lr_corner_chunk->getProperty<float>("z"));
   mURCorner.set(ur_corner_chunk->getProperty<float>("x"),
                 ur_corner_chunk->getProperty<float>("y"),
                 ur_corner_chunk->getProperty<float>("z"));
   mULCorner.set(ul_corner_chunk->getProperty<float>("x"),
                 ul_corner_chunk->getProperty<float>("y"),
                 ul_corner_chunk->getProperty<float>("z"));

   // Calculate the rotation and the pts
   calculateSurfaceRotation();
   calculateCornersInBaseFrame();

   // Get info about being tracked
   mTracked = chunk->getProperty<bool>("tracked");
   if(mTracked)
   {
      mTrackerProxyName = chunk->getProperty<std::string>("trackerproxy");
   }

   // Create Projection objects
   // NOTE: The -'s are because we are measuring distance to
   //  the left(bottom) which is opposite the normal axis direction
   //vjMatrix rot_inv;
   //rot_inv.invert(mSurfaceRotation);
   if(!mTracked)
   {
      mLeftProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]);
      mRightProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]);
   }
   else
   {
      mLeftProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt],
                                              mTrackerProxyName);
      mRightProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt],
                                               mTrackerProxyName);
   }
   // Configure the projections
   mLeftProj->config(chunk);
   mLeftProj->setEye(Projection::LEFT);
   mLeftProj->setViewport(this);

   mRightProj->config(chunk);
   mRightProj->setEye(Projection::RIGHT);
   mRightProj->setViewport(this);
}

void SurfaceViewport::updateProjections(const float positionScale)
{
   gmtl::Matrix44f left_eye_pos, right_eye_pos;     // NOTE: Eye coord system is -z forward, x-right, y-up

   // -- Calculate Eye Positions -- //
   gmtl::Matrix44f cur_head_pos = mUser->getHeadPosProxy()->getData(positionScale);
   /*
   Coord  head_coord(cur_head_pos);       // Create a user readable version

   vprDEBUG(vprDBG_ALL,5)
      << "vjDisplay::updateProjections: Getting head position" << std::endl
      << vprDEBUG_FLUSH;
   vprDEBUG(vprDBG_ALL,5) << "\tHeadPos:" << head_coord.pos << "\tHeadOr:"
                        << head_coord.orient << std::endl << vprDEBUG_FLUSH;
                        */

   // Compute location of left and right eyes
   //float interocularDist = 2.75f/12.0f;
   float interocular_dist = mUser->getInterocularDistance();
   interocular_dist *= positionScale;              // Scale eye separation
   float eye_offset = interocular_dist/2.0f;      // Distance to move eye

   left_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f( -eye_offset, 0, 0));
   right_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(eye_offset, 0, 0));

   mLeftProj->calcViewMatrix(left_eye_pos, positionScale);
   mRightProj->calcViewMatrix(right_eye_pos, positionScale);
}

void SurfaceViewport::calculateSurfaceRotation()
{
   assertPtsLegal();

   // Find the base vectors for the surface axiis (in terms of the base coord system)
   // With z out, x to the right, and y up
   gmtl::Vec3f x_base, y_base, z_base;
   x_base = (mLRCorner-mLLCorner);
   y_base = (mURCorner-mLRCorner);
   gmtl::cross( z_base, x_base, y_base);

   // They must be normalized
   gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base);

   // Calculate the surfaceRotMat using law of cosines
   mSurfaceRotation = gmtl::makeDirCos<gmtl::Matrix44f>(x_base, y_base, z_base );
   //mSurfaceRotation.makeDirCos(x_base,y_base,z_base);      // surfMbase
   //mSurfaceRotation.invert(mSurfRotInv);              // baseMsurf
}

void SurfaceViewport::calculateCornersInBaseFrame()
{
   mxLLCorner = mSurfaceRotation * mLLCorner;
   mxLRCorner = mSurfaceRotation * mLRCorner;
   mxURCorner = mSurfaceRotation * mURCorner;
   mxULCorner = mSurfaceRotation * mULCorner;

   // Verify that they are all in the same x,y plane
   vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << std::setprecision(10)
                                          << mxLLCorner[gmtl::Zelt] << " "
                                          << mxLRCorner[gmtl::Zelt] << " "
                                          << mxURCorner[gmtl::Zelt] << " "
                                          << mxULCorner[gmtl::Zelt] << "\n"
                                          << vprDEBUG_FLUSH;
#ifdef VJ_DEBUG
   const float epsilon = 1e-6;
#endif
   vprASSERT(gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Zelt], epsilon) &&
             gmtl::Math::isEqual(mxURCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon) &&
             gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon));
}

};
<commit_msg>Updated for bug fix in GMTL.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2002 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>

#include <vrj/Display/SurfaceViewport.h>
#include <vrj/Display/WallProjection.h>
#include <vrj/Display/TrackedWallProjection.h>
#include <gmtl/Math.h>
//#include <vrj/Math/Coord.h>
#include <gmtl/Vec.h>
#include <jccl/Config/ConfigChunk.h>
#include <vrj/Kernel/User.h>

#include <gadget/Type/Position/PositionUnitConversion.h>

#include <gmtl/Matrix.h>
#include <gmtl/MatrixOps.h>
#include <gmtl/Generate.h>
#include <gmtl/Xforms.h>

namespace vrj
{

void SurfaceViewport::config(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);
   vprASSERT(chunk->getDescToken() == std::string("surfaceViewport"));

   Viewport::config(chunk);     // Call base class config

   mType = SURFACE;

   // Read in the corners
   jccl::ConfigChunkPtr ll_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",0);
   jccl::ConfigChunkPtr lr_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",1);
   jccl::ConfigChunkPtr ur_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",2);
   jccl::ConfigChunkPtr ul_corner_chunk = chunk->getProperty<jccl::ConfigChunkPtr>("corners",3);
   mLLCorner.set(ll_corner_chunk->getProperty<float>("x"),
                 ll_corner_chunk->getProperty<float>("y"),
                 ll_corner_chunk->getProperty<float>("z"));
   mLRCorner.set(lr_corner_chunk->getProperty<float>("x"),
                 lr_corner_chunk->getProperty<float>("y"),
                 lr_corner_chunk->getProperty<float>("z"));
   mURCorner.set(ur_corner_chunk->getProperty<float>("x"),
                 ur_corner_chunk->getProperty<float>("y"),
                 ur_corner_chunk->getProperty<float>("z"));
   mULCorner.set(ul_corner_chunk->getProperty<float>("x"),
                 ul_corner_chunk->getProperty<float>("y"),
                 ul_corner_chunk->getProperty<float>("z"));

   // Calculate the rotation and the pts
   calculateSurfaceRotation();
   calculateCornersInBaseFrame();

   // Get info about being tracked
   mTracked = chunk->getProperty<bool>("tracked");
   if(mTracked)
   {
      mTrackerProxyName = chunk->getProperty<std::string>("trackerproxy");
   }

   // Create Projection objects
   // NOTE: The -'s are because we are measuring distance to
   //  the left(bottom) which is opposite the normal axis direction
   //vjMatrix rot_inv;
   //rot_inv.invert(mSurfaceRotation);
   if(!mTracked)
   {
      mLeftProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]);
      mRightProj = new WallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt]);
   }
   else
   {
      mLeftProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt],
                                              mTrackerProxyName);
      mRightProj = new TrackedWallProjection(mSurfaceRotation,-mxLLCorner[gmtl::Zelt],
                                    mxLRCorner[gmtl::Xelt],-mxLLCorner[gmtl::Xelt],
                                    mxURCorner[gmtl::Yelt],-mxLRCorner[gmtl::Yelt],
                                               mTrackerProxyName);
   }
   // Configure the projections
   mLeftProj->config(chunk);
   mLeftProj->setEye(Projection::LEFT);
   mLeftProj->setViewport(this);

   mRightProj->config(chunk);
   mRightProj->setEye(Projection::RIGHT);
   mRightProj->setViewport(this);
}

void SurfaceViewport::updateProjections(const float positionScale)
{
   gmtl::Matrix44f left_eye_pos, right_eye_pos;     // NOTE: Eye coord system is -z forward, x-right, y-up

   // -- Calculate Eye Positions -- //
   gmtl::Matrix44f cur_head_pos = mUser->getHeadPosProxy()->getData(positionScale);
   /*
   Coord  head_coord(cur_head_pos);       // Create a user readable version

   vprDEBUG(vprDBG_ALL,5)
      << "vjDisplay::updateProjections: Getting head position" << std::endl
      << vprDEBUG_FLUSH;
   vprDEBUG(vprDBG_ALL,5) << "\tHeadPos:" << head_coord.pos << "\tHeadOr:"
                        << head_coord.orient << std::endl << vprDEBUG_FLUSH;
                        */

   // Compute location of left and right eyes
   //float interocularDist = 2.75f/12.0f;
   float interocular_dist = mUser->getInterocularDistance();
   interocular_dist *= positionScale;              // Scale eye separation
   float eye_offset = interocular_dist/2.0f;      // Distance to move eye

   left_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f( -eye_offset, 0, 0));
   right_eye_pos = cur_head_pos * gmtl::makeTrans<gmtl::Matrix44f>(gmtl::Vec3f(eye_offset, 0, 0));

   mLeftProj->calcViewMatrix(left_eye_pos, positionScale);
   mRightProj->calcViewMatrix(right_eye_pos, positionScale);
}

void SurfaceViewport::calculateSurfaceRotation()
{
   assertPtsLegal();

   // Find the base vectors for the surface axiis (in terms of the base coord system)
   // With z out, x to the right, and y up
   gmtl::Vec3f x_base, y_base, z_base;
   x_base = (mLRCorner-mLLCorner);
   y_base = (mURCorner-mLRCorner);
   gmtl::cross( z_base, x_base, y_base);

   // They must be normalized
   gmtl::normalize(x_base); gmtl::normalize(y_base); gmtl::normalize(z_base);

   // Calculate the surfaceRotMat using law of cosines
   mSurfaceRotation = gmtl::makeDirCos<gmtl::Matrix44f>(x_base, y_base, z_base );
   gmtl::invert(mSurfaceRotation);

   //mSurfaceRotation.makeDirCos(x_base,y_base,z_base);      // surfMbase
   //mSurfaceRotation.invert(mSurfRotInv);              // baseMsurf
}

void SurfaceViewport::calculateCornersInBaseFrame()
{
   mxLLCorner = mSurfaceRotation * mLLCorner;
   mxLRCorner = mSurfaceRotation * mLRCorner;
   mxURCorner = mSurfaceRotation * mURCorner;
   mxULCorner = mSurfaceRotation * mULCorner;

   // Verify that they are all in the same x,y plane
   vprDEBUG(vprDBG_ALL, vprDBG_HVERB_LVL) << std::setprecision(10)
                                          << mxLLCorner[gmtl::Zelt] << " "
                                          << mxLRCorner[gmtl::Zelt] << " "
                                          << mxURCorner[gmtl::Zelt] << " "
                                          << mxULCorner[gmtl::Zelt] << "\n"
                                          << vprDEBUG_FLUSH;
#ifdef VJ_DEBUG
   const float epsilon = 1e-6;
#endif
   vprASSERT(gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxLRCorner[gmtl::Zelt], epsilon) &&
             gmtl::Math::isEqual(mxURCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon) &&
             gmtl::Math::isEqual(mxLLCorner[gmtl::Zelt], mxULCorner[gmtl::Zelt], epsilon));
}

};
<|endoftext|>


<commit_before>#include "main.h"
#include "im.h"

using namespace eigengo::akka;

Main::Main(const std::string queue, const std::string exchange, const std::string routingKey) :
RabbitRpcServer::RabbitRpcServer(queue, exchange, routingKey) {

}

std::string Main::handleMessage(const AmqpClient::BasicMessage::ptr_t message, const AmqpClient::Channel::ptr_t channel) {
	ImageMessage imageMessage(message);

	auto image = imageMessage.headImage();

	return "foo";
}

int main(int argc, char** argv) {
	Main main("recog", "amq.direct", "recog.key");
	main.runAndJoin(8);
	return 0;
}<commit_msg>Native processing<commit_after>#include "main.h"
#include "im.h"

using namespace eigengo::akka;

Main::Main(const std::string queue, const std::string exchange, const std::string routingKey) :
RabbitRpcServer::RabbitRpcServer(queue, exchange, routingKey) {

}

std::string Main::handleMessage(const AmqpClient::BasicMessage::ptr_t message, const AmqpClient::Channel::ptr_t channel) {
	ImageMessage imageMessage(message);

	auto image = imageMessage.headImage();
	Jzon::Object root;
	root.add("accepted", true);
	Jzon::Writer writer(root, Jzon::NoFormat);
	writer.Write();

	return writer.GetResult();
}

int main(int argc, char** argv) {
	Main main("recog", "amq.direct", "recog.key");
	main.runAndJoin(8);
	return 0;
}<|endoftext|>


<commit_before>/*******************************************************************************
 * tests/core/post_hash_table_test.cpp
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/core/reduce_post_table.hpp>
#include <gtest/gtest.h>

#include <string>
#include <utility>
#include <vector>
#include <c7a/net/manager.hpp>

using namespace c7a::data;
using namespace c7a::net;

struct PostTable : public::testing::Test {};

std::pair<int, int> pair(int ele) {
    return std::make_pair(ele, ele);
}

template <typename Key, typename HashFunction = std::hash<Key> >
class CustomKeyHashFunction
        : public c7a::core::PostReduceByHashKey<int> {
public:
    CustomKeyHashFunction(const HashFunction& hash_function = HashFunction())
            : hash_function_(hash_function)
    { }

    template <typename ReducePostTable>
    typename ReducePostTable::index_result
    operator () (Key v, ReducePostTable* ht) const {

        using index_result = typename ReducePostTable::index_result;

        size_t global_index =  v / 2;
        return index_result(global_index);
    }

private:
    HashFunction hash_function_;
};

TEST_F(PostTable, CustomHashFunction) {
    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    CustomKeyHashFunction<int> cust_hash;
    c7a::core::PostReduceFlushToDefault flush_func;

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn), false,
            c7a::core::PostReduceFlushToDefault, CustomKeyHashFunction<int>>
    table(key_ex, red_fn, emitters, cust_hash, flush_func);

    ASSERT_EQ(0u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());

    for (int i = 0; i < 16; i++) {
        table.Insert(std::move(pair(i)));
    }

    ASSERT_EQ(0u, writer1.size());
    ASSERT_EQ(16u, table.NumItems());

    table.Flush();

    ASSERT_EQ(16u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());
}

TEST_F(PostTable, AddIntegers) {
    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Insert(pair(2));

    ASSERT_EQ(3u, table.NumItems());
}

TEST_F(PostTable, CreateEmptyTable) {
    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    ASSERT_EQ(0u, table.NumItems());
}

TEST_F(PostTable, FlushIntegers) {
    auto key_ex = [](int in) {
                      return in;
                  };
    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Flush();

    ASSERT_EQ(3u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());

    table.Insert(pair(1));

    ASSERT_EQ(1u, table.NumItems());
}

TEST_F(PostTable, FlushIntegersInSequence) {
    auto key_ex = [](int in) {
                      return in;
                  };
    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Flush();

    ASSERT_EQ(3u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());

    table.Insert(pair(1));

    ASSERT_EQ(1u, table.NumItems());
}

TEST_F(PostTable, DISABLED_MultipleEmitters) {
    std::vector<int> vec1;

    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    std::vector<int> writer2;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });
    emitters.push_back([&writer2](const int value) { writer2.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Flush();

    ASSERT_EQ(0u, table.NumItems());
    ASSERT_EQ(3u, writer1.size());
    ASSERT_EQ(3u, writer2.size());

    table.Insert(pair(1));

    ASSERT_EQ(1u, table.NumItems());
}

TEST_F(PostTable, ComplexType) {
    using StringPair = std::pair<std::string, int>;

    auto key_ex = [](StringPair in) {
                      return in.first;
                  };

    auto red_fn = [](StringPair in1, StringPair in2) {
                      return std::make_pair(in1.first, in1.second + in2.second);
                  };

    typedef std::function<void (const StringPair&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<StringPair> writer1;
    emitters.push_back([&writer1](const StringPair value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<StringPair, std::string, StringPair, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(std::make_pair("hallo", std::make_pair("hallo", 1)));
    table.Insert(std::make_pair("hello", std::make_pair("hello", 2)));
    table.Insert(std::make_pair("bonjour", std::make_pair("bonjour", 3)));

    ASSERT_EQ(3u, table.NumItems());

    table.Insert(std::make_pair("hello", std::make_pair("hello", 5)));

    ASSERT_EQ(3u, table.NumItems());

    table.Insert(std::make_pair("baguette", std::make_pair("baguette", 42)));

    ASSERT_EQ(4u, table.NumItems());
}

// TODO(ms): add one test with a for loop inserting 10000 items. -> trigger

/******************************************************************************/
<commit_msg>enabled test<commit_after>/*******************************************************************************
 * tests/core/post_hash_table_test.cpp
 *
 * Part of Project c7a.
 *
 * Copyright (C) 2015 Matthias Stumpp <mstumpp@gmail.com>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/core/reduce_post_table.hpp>
#include <gtest/gtest.h>

#include <string>
#include <utility>
#include <vector>
#include <c7a/net/manager.hpp>

using namespace c7a::data;
using namespace c7a::net;

struct PostTable : public::testing::Test {};

std::pair<int, int> pair(int ele) {
    return std::make_pair(ele, ele);
}

template <typename Key, typename HashFunction = std::hash<Key> >
class CustomKeyHashFunction
        : public c7a::core::PostReduceByHashKey<int> {
public:
    CustomKeyHashFunction(const HashFunction& hash_function = HashFunction())
            : hash_function_(hash_function)
    { }

    template <typename ReducePostTable>
    typename ReducePostTable::index_result
    operator () (Key v, ReducePostTable* ht) const {

        using index_result = typename ReducePostTable::index_result;

        size_t global_index =  v / 2;
        return index_result(global_index);
    }

private:
    HashFunction hash_function_;
};

TEST_F(PostTable, CustomHashFunction) {
    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    CustomKeyHashFunction<int> cust_hash;
    c7a::core::PostReduceFlushToDefault flush_func;

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn), false,
            c7a::core::PostReduceFlushToDefault, CustomKeyHashFunction<int>>
    table(key_ex, red_fn, emitters, cust_hash, flush_func);

    ASSERT_EQ(0u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());

    for (int i = 0; i < 16; i++) {
        table.Insert(std::move(pair(i)));
    }

    ASSERT_EQ(0u, writer1.size());
    ASSERT_EQ(16u, table.NumItems());

    table.Flush();

    ASSERT_EQ(16u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());
}

TEST_F(PostTable, AddIntegers) {
    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Insert(pair(2));

    ASSERT_EQ(3u, table.NumItems());
}

TEST_F(PostTable, CreateEmptyTable) {
    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    ASSERT_EQ(0u, table.NumItems());
}

TEST_F(PostTable, FlushIntegers) {
    auto key_ex = [](int in) {
                      return in;
                  };
    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Flush();

    ASSERT_EQ(3u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());

    table.Insert(pair(1));

    ASSERT_EQ(1u, table.NumItems());
}

TEST_F(PostTable, FlushIntegersInSequence) {
    auto key_ex = [](int in) {
                      return in;
                  };
    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Flush();

    ASSERT_EQ(3u, writer1.size());
    ASSERT_EQ(0u, table.NumItems());

    table.Insert(pair(1));

    ASSERT_EQ(1u, table.NumItems());
}

TEST_F(PostTable, MultipleEmitters) {
    std::vector<int> vec1;

    auto key_ex = [](int in) {
                      return in;
                  };

    auto red_fn = [](int in1, int in2) {
                      return in1 + in2;
                  };

    typedef std::function<void (const int&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<int> writer1;
    std::vector<int> writer2;
    emitters.push_back([&writer1](const int value) { writer1.push_back(value); });
    emitters.push_back([&writer2](const int value) { writer2.push_back(value); });

    c7a::core::ReducePostTable<int, int, int, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(pair(1));
    table.Insert(pair(2));
    table.Insert(pair(3));

    ASSERT_EQ(3u, table.NumItems());

    table.Flush();

    ASSERT_EQ(0u, table.NumItems());
    ASSERT_EQ(3u, writer1.size());
    ASSERT_EQ(3u, writer2.size());

    table.Insert(pair(1));

    ASSERT_EQ(1u, table.NumItems());
}

TEST_F(PostTable, ComplexType) {
    using StringPair = std::pair<std::string, int>;

    auto key_ex = [](StringPair in) {
                      return in.first;
                  };

    auto red_fn = [](StringPair in1, StringPair in2) {
                      return std::make_pair(in1.first, in1.second + in2.second);
                  };

    typedef std::function<void (const StringPair&)> EmitterFunction;
    std::vector<EmitterFunction> emitters;
    std::vector<StringPair> writer1;
    emitters.push_back([&writer1](const StringPair value) { writer1.push_back(value); });

    c7a::core::ReducePostTable<StringPair, std::string, StringPair, decltype(key_ex), decltype(red_fn)>
    table(key_ex, red_fn, emitters);

    table.Insert(std::make_pair("hallo", std::make_pair("hallo", 1)));
    table.Insert(std::make_pair("hello", std::make_pair("hello", 2)));
    table.Insert(std::make_pair("bonjour", std::make_pair("bonjour", 3)));

    ASSERT_EQ(3u, table.NumItems());

    table.Insert(std::make_pair("hello", std::make_pair("hello", 5)));

    ASSERT_EQ(3u, table.NumItems());

    table.Insert(std::make_pair("baguette", std::make_pair("baguette", 42)));

    ASSERT_EQ(4u, table.NumItems());
}

// TODO(ms): add one test with a for loop inserting 10000 items. -> trigger

/******************************************************************************/
<|endoftext|>


<commit_before>#include <iostream>
#include "Cluster.h"
#include "utils.h"
#include "numerics.h"
#include "RandomNumberGenerator.h"

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

using namespace std;

bool is_almost(double val1, double val2, double precision) {
  return abs(val1-val2) < precision;
}

int main(int argc, char** argv) {
  cout << "Begin:: test_cluster" << endl;
  RandomNumberGenerator rng;

  double sum_sum_score_deltas;

  boost::numeric::ublas::matrix<double> Data;
  LoadData("SynData2.csv", Data);
  // std::cout << Data << std::endl;

  Cluster<double> cd(5); //hard code # columns
  std::cout << std::endl << "Init cluster" << std::endl;
  std::cout << cd << std::endl;

  sum_sum_score_deltas = 0;
  for(int i=0; i < 4; i++) {
    std::vector<double> V;
    for(int j=0;j < Data.size2(); j++) {
      V.push_back(Data(i,j));
    }
    sum_sum_score_deltas += cd.insert_row(V, i);
  }
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl;
  std::cout << std::endl << "logps" << std::endl;
  std::cout << cd.calc_logps() << std::endl;;
  std::cout << std::endl << "sum logp" << std::endl;
  std::cout << cd.calc_sum_logp() << std::endl;;
  //
  sum_sum_score_deltas = 0;
  for(int i=4; i < 8; i++) {
    std::vector<double> V;
    for(int j=0;j < Data.size2(); j++) {
      V.push_back(Data(i,j));
    }
    sum_sum_score_deltas += cd.insert_row(V, i);
  }
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl;
  std::cout << std::endl << "logps" << std::endl;
  std::cout << cd.calc_logps() << std::endl;;
  std::cout << std::endl << "sum logp" << std::endl;
  std::cout << cd.calc_sum_logp() << std::endl;;
  //
  int i = 8;
  std::vector<double> V;
  for(int j=0;j<Data.size2(); j++) {
    V.push_back(Data(i,j));
  }
  double vector_logp = cd.get_vector_logp(V);
  std::cout << "add vector with vector_logp" << std::endl;
  std::cout << vector_logp << std::endl;
  std::cout << "calc_data_logp() is result" << std::endl;
  std::cout << cd.calc_data_logp(V) << std::endl;

  cd.insert_row(V, i);
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  std::cout << "remove vector" << std::endl;
  cd.remove_row(V, i);
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  //
  std::cout << "calculate logps from scratch" << std::endl;
  std::cout << std::endl << "logps" << std::endl;
  std::cout << cd.calc_logps() << std::endl;;
  std::cout << std::endl << "sum logp" << std::endl;
  std::cout << cd.calc_sum_logp() << std::endl;;

  print_defaults();

  std::cout << "show use of underlying numerics functions" << std::endl;
  std::cout << "calc_continuous_logp(0, 1, 2, 2, 0)" << std::endl;
  std::cout << numerics::calc_continuous_logp(0, 1, 2, 2, 0) << std::endl;
  std::cout << "calc_cluster_crp_logp(10, 100, 10)" << std::endl;
  std::cout << numerics::calc_cluster_crp_logp(10, 100, 10) << std::endl;

  // std::cout << "numerics::calc_cluster_vector_joint_logp(cd, V)" << std::endl;
  // std::cout << numerics::calc_cluster_vector_joint_logp(cd, V) << std::endl;

  cout << "Stop:: test_cluster" << endl;
}
<commit_msg>add test of equivalence of a cluster with separate suffstats<commit_after>#include <iostream>
#include "Cluster.h"
#include "utils.h"
#include "numerics.h"
#include "RandomNumberGenerator.h"

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

using namespace std;

bool is_almost(double val1, double val2, double precision) {
  return abs(val1-val2) < precision;
}

int main(int argc, char** argv) {
  cout << "Begin:: test_cluster" << endl;
  RandomNumberGenerator rng;

  int max_value = 20;
  int num_rows = 3;
  int num_cols = 3;
  Cluster<double> cd(num_cols);
  vector<Suffstats<double> > sd_v;
  for(int row_idx=0; row_idx<num_rows; row_idx++) {
    Suffstats<double> sd;
    sd_v.push_back(sd);
  }
  for(int row_idx=0; row_idx<num_rows; row_idx++) {
    vector<double> row_data;
    for(int col_idx=0; col_idx<num_cols; col_idx++) {
      double new_value = (rng.nexti(max_value) + 1) * rng.next();
      sd_v[col_idx].insert_el(new_value);
      row_data.push_back(new_value);
    }
    cd.insert_row(row_data, row_idx);
  }
  vector<double> score_v;
  double sum_scores = 0;
  for(int col_idx=0; col_idx<num_cols; col_idx++) {
    double suff_score = sd_v[col_idx].get_score();
    score_v.push_back(suff_score);
    sum_scores += suff_score;
  }
  cout << "vector off separate suffstats scores: " << score_v << endl;
  cout << "sum separate scores: " << sum_scores << endl;
  cout << "Cluster score with same data: " << cd.get_score() << endl;
  cout << endl;
  //
  assert(is_almost(sum_scores, cd.get_score(), 1E-10));

  double sum_sum_score_deltas;

  boost::numeric::ublas::matrix<double> Data;
  LoadData("SynData2.csv", Data);
  // std::cout << Data << std::endl;

  cd = Cluster<double>(5); //hard code # columns
  std::cout << std::endl << "Init cluster" << std::endl;
  std::cout << cd << std::endl;

  sum_sum_score_deltas = 0;
  for(int i=0; i < 4; i++) {
    std::vector<double> V;
    for(int j=0;j < Data.size2(); j++) {
      V.push_back(Data(i,j));
    }
    sum_sum_score_deltas += cd.insert_row(V, i);
  }
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl;
  std::cout << std::endl << "logps" << std::endl;
  std::cout << cd.calc_logps() << std::endl;;
  std::cout << std::endl << "sum logp" << std::endl;
  std::cout << cd.calc_sum_logp() << std::endl;;
  //
  sum_sum_score_deltas = 0;
  for(int i=4; i < 8; i++) {
    std::vector<double> V;
    for(int j=0;j < Data.size2(); j++) {
      V.push_back(Data(i,j));
    }
    sum_sum_score_deltas += cd.insert_row(V, i);
  }
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  std::cout << "sum_sum_score_deltas: " << sum_sum_score_deltas << std::endl;
  std::cout << std::endl << "logps" << std::endl;
  std::cout << cd.calc_logps() << std::endl;;
  std::cout << std::endl << "sum logp" << std::endl;
  std::cout << cd.calc_sum_logp() << std::endl;;
  //
  int i = 8;
  std::vector<double> V;
  for(int j=0;j<Data.size2(); j++) {
    V.push_back(Data(i,j));
  }
  double vector_logp = cd.get_vector_logp(V);
  std::cout << "add vector with vector_logp" << std::endl;
  std::cout << vector_logp << std::endl;
  std::cout << "calc_data_logp() is result" << std::endl;
  std::cout << cd.calc_data_logp(V) << std::endl;

  cd.insert_row(V, i);
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  std::cout << "remove vector" << std::endl;
  cd.remove_row(V, i);
  std::cout << std::endl << "modified cluster" << std::endl;
  std::cout << cd << std::endl;
  //
  std::cout << "calculate logps from scratch" << std::endl;
  std::cout << std::endl << "logps" << std::endl;
  std::cout << cd.calc_logps() << std::endl;;
  std::cout << std::endl << "sum logp" << std::endl;
  std::cout << cd.calc_sum_logp() << std::endl;;

  print_defaults();

  std::cout << "show use of underlying numerics functions" << std::endl;
  std::cout << "calc_continuous_logp(0, 1, 2, 2, 0)" << std::endl;
  std::cout << numerics::calc_continuous_logp(0, 1, 2, 2, 0) << std::endl;
  std::cout << "calc_cluster_crp_logp(10, 100, 10)" << std::endl;
  std::cout << numerics::calc_cluster_crp_logp(10, 100, 10) << std::endl;

  // std::cout << "numerics::calc_cluster_vector_joint_logp(cd, V)" << std::endl;
  // std::cout << numerics::calc_cluster_vector_joint_logp(cd, V) << std::endl;

  cout << "Stop:: test_cluster" << endl;
}
<|endoftext|>