<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief vocbase traversals
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Max Neunhoeffer
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Traverser.h"

#include "Basics/Thread.h"

using namespace std;
using namespace triagens::basics;

class Searcher : public Thread {

    Traverser* _traverser;
    Traverser::ThreadInfo& _myInfo;
    Traverser::ThreadInfo& _peerInfo;
    Traverser::VertexId _start;
    Traverser::ExpanderFunction _expander;
    string _id;

  public:

    Searcher (Traverser* traverser, Traverser::ThreadInfo& myInfo,
              Traverser::ThreadInfo& peerInfo, Traverser::VertexId start,
              Traverser::ExpanderFunction expander, string id)
      : Thread(id), _traverser(traverser), _myInfo(myInfo),
        _peerInfo(peerInfo), _start(start), _expander(expander), _id(id) {
    }

////////////////////////////////////////////////////////////////////////////////
/// @brief Insert a neighbor to the todo list.
////////////////////////////////////////////////////////////////////////////////

  private:

    void insertNeighbor (Traverser::VertexId& neighbor,
                         Traverser::VertexId& predecessor,
                         Traverser::EdgeId& edge,
                         Traverser::EdgeWeight weight) {

      std::lock_guard<std::mutex> guard(_myInfo._mutex);
      Traverser::Step* s = _myInfo._pq.find(neighbor);

      // Not found, so insert it:
      if (s == nullptr) {
        _myInfo._pq.insert(neighbor,
                           Traverser::Step(neighbor, predecessor,
                                           weight, edge));
        return;
      }
      if (s->_done) {
        return;
      }
      if (s->_weight > weight) {
        _myInfo._pq.lowerWeight(neighbor, weight);
      }
    }

////////////////////////////////////////////////////////////////////////////////
/// @brief Lookup our current vertex in the data of our peer.
////////////////////////////////////////////////////////////////////////////////

    void lookupPeer (Traverser::VertexId& vertex,
                     Traverser::EdgeWeight weight) {

      std::lock_guard<std::mutex> guard(_peerInfo._mutex);
      Traverser::Step* s = _peerInfo._pq.find(vertex);
      if (s == nullptr) {
        // Not found, nothing more to do
        return;
      }
      Traverser::EdgeWeight total = s->_weight + weight;

      // Update the highscore:
      std::lock_guard<std::mutex> guard2(_traverser->_resultMutex);
      if (!_traverser->_highscoreSet || total < _traverser->_highscore) {
        _traverser->_highscoreSet = true;
        _traverser->_highscore = total;
      }

      // Now the highscore is set!

      // Did we find a solution together with the other thread?
      if (s->_done) {
        if (total <= _traverser->_highscore) {
          _traverser->_intermediate = vertex;
          _traverser->_bingo = true;
        }
        // We found a way, but somebody else found a better way, so
        // this is not the shortest path
        return;
      }

      // Did we find a solution on our own? This is for the single thread
      // case and for the case that the other thread is too slow to even
      // finish its own start vertex!
      if (s->_weight == 0) {
        // We have found the target, we have finished all vertices with
        // a smaller weight than this one (and did not succeed), so this
        // must be a best solution:
        _traverser->_intermediate = vertex;
        _traverser->_bingo = true;
      }
    }

////////////////////////////////////////////////////////////////////////////////
/// @brief Search graph starting at Start following edges of the given
/// direction only
////////////////////////////////////////////////////////////////////////////////

  public:

    virtual void run () {

      Traverser::VertexId v;
      Traverser::Step s;
      bool b = _myInfo._pq.popMinimal(v, s, true);

      std::vector<Traverser::Step> neighbors;

      // Iterate while no bingo found and
      // there still is a vertex on the stack.
      while (!_traverser->_bingo && b) {
        neighbors.clear();
        _expander(v, neighbors);
        for (auto& neighbor : neighbors) {
          insertNeighbor(neighbor._vertex, v, neighbor._edge,
                         s._weight + neighbor._weight);
        }
        lookupPeer(v, s._weight);

        std::lock_guard<std::mutex> guard(_myInfo._mutex);
        Traverser::Step* s2 = _myInfo._pq.find(v);
        s2->_done = true;
        b = _myInfo._pq.popMinimal(v, s, true);
      }
    }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief return the shortest path between the start and target vertex.
////////////////////////////////////////////////////////////////////////////////

Traverser::Path* Traverser::shortestPath (VertexId const& start,
                                          VertexId const& target) {

  // For the result:
  std::deque<VertexId> r_vertices;
  std::deque<VertexId> r_edges;
  _highscoreSet = false;
  _highscore = 0;
  _bingo = false;

  // Forward with initialization:
  string empty;
  ThreadInfo forward;
  forward._pq.insert(start, Step(start, empty, 0, empty));

  // backward with initialization:
  ThreadInfo backward;
  backward._pq.insert(target, Step(target, empty, 0, empty));

  // Now the searcher threads:
  Searcher forwardSearcher(this, forward, backward, start,
                           _forwardExpander, "Forward");
  //Searcher backwardSearcher(this, backward, forward, target,
  //                          _backwardExpander, "Backward");
  forwardSearcher.start();
  //backwardSearcher.start();
  forwardSearcher.join();
  //backwardSearcher.join();

  if (!_bingo || _intermediate == "") {
    return nullptr;
  }

  Step* s = forward._pq.find(_intermediate);
  r_vertices.push_back(_intermediate);

  // FORWARD Go path back from intermediate -> start.
  // Insert all vertices and edges at front of vector
  // Do NOT! insert the intermediate vertex
  while (s->_predecessor != "") {
    r_edges.push_front(s->_edge);
    r_vertices.push_front(s->_predecessor);
    s = forward._pq.find(s->_predecessor);
  }

  // BACKWARD Go path back from intermediate -> target.
  // Insert all vertices and edges at back of vector
  // Also insert the intermediate vertex
  s = backward._pq.find(_intermediate);
  while (s->_predecessor != "") {
    r_edges.push_back(s->_edge);
    r_vertices.push_back(s->_predecessor);
    s = backward._pq.find(s->_predecessor);
  }
  return new Path(r_vertices, r_edges, _highscore);
};

<commit_msg>Switch on second thread.<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief vocbase traversals
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014-2015 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Max Neunhoeffer
/// @author Copyright 2014-2015, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2012-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Traverser.h"

#include "Basics/Thread.h"

using namespace std;
using namespace triagens::basics;

class Searcher : public Thread {

    Traverser* _traverser;
    Traverser::ThreadInfo& _myInfo;
    Traverser::ThreadInfo& _peerInfo;
    Traverser::VertexId _start;
    Traverser::ExpanderFunction _expander;
    string _id;

  public:

    Searcher (Traverser* traverser, Traverser::ThreadInfo& myInfo,
              Traverser::ThreadInfo& peerInfo, Traverser::VertexId start,
              Traverser::ExpanderFunction expander, string id)
      : Thread(id), _traverser(traverser), _myInfo(myInfo),
        _peerInfo(peerInfo), _start(start), _expander(expander), _id(id) {
    }

////////////////////////////////////////////////////////////////////////////////
/// @brief Insert a neighbor to the todo list.
////////////////////////////////////////////////////////////////////////////////

  private:

    void insertNeighbor (Traverser::VertexId& neighbor,
                         Traverser::VertexId& predecessor,
                         Traverser::EdgeId& edge,
                         Traverser::EdgeWeight weight) {

      std::lock_guard<std::mutex> guard(_myInfo._mutex);
      Traverser::Step* s = _myInfo._pq.find(neighbor);

      // Not found, so insert it:
      if (s == nullptr) {
        _myInfo._pq.insert(neighbor,
                           Traverser::Step(neighbor, predecessor,
                                           weight, edge));
        return;
      }
      if (s->_done) {
        return;
      }
      if (s->_weight > weight) {
        _myInfo._pq.lowerWeight(neighbor, weight);
      }
    }

////////////////////////////////////////////////////////////////////////////////
/// @brief Lookup our current vertex in the data of our peer.
////////////////////////////////////////////////////////////////////////////////

    void lookupPeer (Traverser::VertexId& vertex,
                     Traverser::EdgeWeight weight) {

      std::lock_guard<std::mutex> guard(_peerInfo._mutex);
      Traverser::Step* s = _peerInfo._pq.find(vertex);
      if (s == nullptr) {
        // Not found, nothing more to do
        return;
      }
      Traverser::EdgeWeight total = s->_weight + weight;

      // Update the highscore:
      std::lock_guard<std::mutex> guard2(_traverser->_resultMutex);
      if (!_traverser->_highscoreSet || total < _traverser->_highscore) {
        _traverser->_highscoreSet = true;
        _traverser->_highscore = total;
      }

      // Now the highscore is set!

      // Did we find a solution together with the other thread?
      if (s->_done) {
        if (total <= _traverser->_highscore) {
          _traverser->_intermediate = vertex;
          _traverser->_bingo = true;
        }
        // We found a way, but somebody else found a better way, so
        // this is not the shortest path
        return;
      }

      // Did we find a solution on our own? This is for the single thread
      // case and for the case that the other thread is too slow to even
      // finish its own start vertex!
      if (s->_weight == 0) {
        // We have found the target, we have finished all vertices with
        // a smaller weight than this one (and did not succeed), so this
        // must be a best solution:
        _traverser->_intermediate = vertex;
        _traverser->_bingo = true;
      }
    }

////////////////////////////////////////////////////////////////////////////////
/// @brief Search graph starting at Start following edges of the given
/// direction only
////////////////////////////////////////////////////////////////////////////////

  public:

    virtual void run () {

      Traverser::VertexId v;
      Traverser::Step s;
      bool b = _myInfo._pq.popMinimal(v, s, true);

      std::vector<Traverser::Step> neighbors;

      // Iterate while no bingo found and
      // there still is a vertex on the stack.
      while (!_traverser->_bingo && b) {
        neighbors.clear();
        _expander(v, neighbors);
        for (auto& neighbor : neighbors) {
          insertNeighbor(neighbor._vertex, v, neighbor._edge,
                         s._weight + neighbor._weight);
        }
        lookupPeer(v, s._weight);

        std::lock_guard<std::mutex> guard(_myInfo._mutex);
        Traverser::Step* s2 = _myInfo._pq.find(v);
        s2->_done = true;
        b = _myInfo._pq.popMinimal(v, s, true);
      }
    }
};

////////////////////////////////////////////////////////////////////////////////
/// @brief return the shortest path between the start and target vertex.
////////////////////////////////////////////////////////////////////////////////

Traverser::Path* Traverser::shortestPath (VertexId const& start,
                                          VertexId const& target) {

  // For the result:
  std::deque<VertexId> r_vertices;
  std::deque<VertexId> r_edges;
  _highscoreSet = false;
  _highscore = 0;
  _bingo = false;

  // Forward with initialization:
  string empty;
  ThreadInfo forward;
  forward._pq.insert(start, Step(start, empty, 0, empty));

  // backward with initialization:
  ThreadInfo backward;
  backward._pq.insert(target, Step(target, empty, 0, empty));

  // Now the searcher threads:
  Searcher forwardSearcher(this, forward, backward, start,
                           _forwardExpander, "Forward");
  Searcher backwardSearcher(this, backward, forward, target,
                            _backwardExpander, "Backward");
  forwardSearcher.start();
  backwardSearcher.start();
  forwardSearcher.join();
  backwardSearcher.join();

  if (!_bingo || _intermediate == "") {
    return nullptr;
  }

  Step* s = forward._pq.find(_intermediate);
  r_vertices.push_back(_intermediate);

  // FORWARD Go path back from intermediate -> start.
  // Insert all vertices and edges at front of vector
  // Do NOT! insert the intermediate vertex
  while (s->_predecessor != "") {
    r_edges.push_front(s->_edge);
    r_vertices.push_front(s->_predecessor);
    s = forward._pq.find(s->_predecessor);
  }

  // BACKWARD Go path back from intermediate -> target.
  // Insert all vertices and edges at back of vector
  // Also insert the intermediate vertex
  s = backward._pq.find(_intermediate);
  while (s->_predecessor != "") {
    r_edges.push_back(s->_edge);
    r_vertices.push_back(s->_predecessor);
    s = backward._pq.find(s->_predecessor);
  }
  return new Path(r_vertices, r_edges, _highscore);
};

<|endoftext|>


<commit_before>#include "unit-tests.h"
#include <src/MIDI.h>

BEGIN_MIDI_NAMESPACE

END_MIDI_NAMESPACE

// -----------------------------------------------------------------------------

BEGIN_UNNAMED_NAMESPACE

using namespace testing;

TEST(SysExCodec, Encoder)
{
    // ASCII content
    {
        const byte input[] = "Hello, World!";
        byte buffer[32];
        memset(buffer, 0, 32 * sizeof(byte));
        const unsigned encodedSize = midi::encodeSysEx(input, buffer, 13);
        EXPECT_EQ(encodedSize, 15);
        const byte expected[32] = {
            0, 'H', 'e', 'l', 'l', 'o', ',', ' ',
            0, 'W', 'o', 'r', 'l', 'd', '!', 0,
            0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0,
        };
        EXPECT_THAT(buffer, Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
    // Non-ASCII content
    {
        const byte input[] = {
            182, 236, 167, 177, 61, 91, 120,    // 01111000 -> 120
            107, 94, 209, 87, 94                // 000100xx -> 16
        };
        byte buffer[32];
        memset(buffer, 0, 32 * sizeof(byte));
        const unsigned encodedSize = midi::encodeSysEx(input, buffer, 12);
        EXPECT_EQ(encodedSize, 14);
        const byte expected[32] = {
        //  MSB    Data
            120,   54, 108, 39, 49, 61, 91, 120,
            16,    107, 94, 81, 87, 94, 0,  0,
            0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0,
        };
        EXPECT_THAT(buffer, Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
}

TEST(SysExCodec, Decoder)
{
    // ASCII content
    {
        const byte input[] = {
            0, 'H', 'e', 'l', 'l', 'o', ',', ' ',
            0, 'W', 'o', 'r', 'l', 'd', '!',
        };
        byte buffer[32];
        memset(buffer, 0, 32 * sizeof(byte));
        const unsigned decodedSize = midi::decodeSysEx(input, buffer, 15);
        EXPECT_EQ(decodedSize, 13);
        const byte expected[32] = {
            'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
            'o', 'r', 'l', 'd', '!', 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 0,
        };
        EXPECT_THAT(buffer, Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
    // Non-ASCII content
    {
        const byte input[] = {
        //  MSB    Data
            120,   54, 108, 39, 49, 61, 91, 120,
            16,    107, 94, 81, 87, 94,
        };
        byte buffer[32];
        memset(buffer, 0, 32 * sizeof(byte));
        const unsigned encodedSize = midi::decodeSysEx(input, buffer, 14);
        EXPECT_EQ(encodedSize, 12);
        const byte expected[32] = {
            182, 236, 167, 177, 61, 91, 120,
            107, 94, 209, 87, 94, 0, 0,
            0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0
        };
        EXPECT_THAT(input,  Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
}

TEST(SysExCodec, Codec)
{

}

END_UNNAMED_NAMESPACE
<commit_msg>Smaller buffers, added full codec test.<commit_after>#include "unit-tests.h"
#include <src/MIDI.h>

BEGIN_MIDI_NAMESPACE

END_MIDI_NAMESPACE

// -----------------------------------------------------------------------------

BEGIN_UNNAMED_NAMESPACE

using namespace testing;

TEST(SysExCodec, Encoder)
{
    // ASCII content
    {
        const byte input[] = "Hello, World!";
        byte buffer[16];
        memset(buffer, 0, 16 * sizeof(byte));
        const unsigned encodedSize = midi::encodeSysEx(input, buffer, 13);
        EXPECT_EQ(encodedSize, 15);
        const byte expected[16] = {
            0, 'H', 'e', 'l', 'l', 'o', ',', ' ',
            0, 'W', 'o', 'r', 'l', 'd', '!', 0,
        };
        EXPECT_THAT(buffer, Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
    // Non-ASCII content
    {
        const byte input[] = {
            182, 236, 167, 177, 61, 91, 120,    // 01111000 -> 120
            107, 94, 209, 87, 94                // 000100xx -> 16
        };
        byte buffer[16];
        memset(buffer, 0, 16 * sizeof(byte));
        const unsigned encodedSize = midi::encodeSysEx(input, buffer, 12);
        EXPECT_EQ(encodedSize, 14);
        const byte expected[16] = {
        //  MSB    Data
            120,   54, 108, 39, 49, 61, 91, 120,
            16,    107, 94, 81, 87, 94, 0,  0,
        };
        EXPECT_THAT(buffer, Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
}

TEST(SysExCodec, Decoder)
{
    // ASCII content
    {
        const byte input[] = {
            0, 'H', 'e', 'l', 'l', 'o', ',', ' ',
            0, 'W', 'o', 'r', 'l', 'd', '!',
        };
        byte buffer[16];
        memset(buffer, 0, 16 * sizeof(byte));
        const unsigned decodedSize = midi::decodeSysEx(input, buffer, 15);
        EXPECT_EQ(decodedSize, 13);
        const byte expected[16] = {
            'H', 'e', 'l', 'l', 'o', ',', ' ', 'W',
            'o', 'r', 'l', 'd', '!', 0, 0, 0,
        };
        EXPECT_THAT(buffer, Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
    // Non-ASCII content
    {
        const byte input[] = {
        //  MSB    Data
            120,   54, 108, 39, 49, 61, 91, 120,
            16,    107, 94, 81, 87, 94,
        };
        byte buffer[16];
        memset(buffer, 0, 16 * sizeof(byte));
        const unsigned encodedSize = midi::decodeSysEx(input, buffer, 14);
        EXPECT_EQ(encodedSize, 12);
        const byte expected[16] = {
            182, 236, 167, 177, 61, 91, 120,
            107, 94, 209, 87, 94, 0, 0,
            0, 0,
        };
        EXPECT_THAT(input,  Each(Le(0x7f))); // All elements are <= 127
        EXPECT_THAT(buffer, ContainerEq(expected));
    }
}

TEST(SysExCodec, Codec)
{
    // ASCII content
    {
        const byte input[] = "Hello, World!";
        byte buffer1[16];
        byte buffer2[16];
        memset(buffer1, 0, 16 * sizeof(byte));
        memset(buffer2, 0, 16 * sizeof(byte));
        const unsigned encodedSize = midi::encodeSysEx(input, buffer1, 13);
        EXPECT_EQ(encodedSize, 15);
        const unsigned decodedSize = midi::decodeSysEx(buffer1, buffer2, encodedSize);
        EXPECT_EQ(decodedSize, 13);
        EXPECT_STREQ(reinterpret_cast<const char*>(buffer2),
                     reinterpret_cast<const char*>(input));
    }
    // Non-ASCII content
    {
        const byte input[] = {
        //  MSB    Data
            182, 236, 167, 177, 61, 91, 120,
            107, 94, 209, 87, 94
        };
        byte buffer1[14];
        byte buffer2[12];
        memset(buffer1, 0, 14 * sizeof(byte));
        memset(buffer2, 0, 12 * sizeof(byte));
        const unsigned encodedSize = midi::encodeSysEx(input, buffer1, 12);
        EXPECT_EQ(encodedSize, 14);
        const unsigned decodedSize = midi::decodeSysEx(buffer1, buffer2, encodedSize);
        EXPECT_EQ(decodedSize, 12);
        EXPECT_THAT(buffer2, ContainerEq(input));
    }
}

END_UNNAMED_NAMESPACE
<|endoftext|>


<commit_before>#include "rtkTest.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkRegularizedConjugateGradientConeBeamReconstructionFilter.h"
#include <itkAdditiveGaussianNoiseImageFilter.h>

#ifdef USE_CUDA
  #include "itkCudaImage.h"
#endif

/**
 * \file rtkregularizedconjugategradienttest.cxx
 *
 * \brief Functional test for ADMMTotalVariation reconstruction
 *
 * This test generates the projections of an ellipsoid and reconstructs the CT
 * image using the ADMMTotalVariation algorithm with different backprojectors (Voxel-Based,
 * Joseph). The generated results are compared to the
 * expected results (analytical calculation).
 *
 * \author Cyril Mory
 */

int main(int, char** )
{
  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension >     OutputImageType;
#endif

#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 90;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -255.;
  origin[1] = -255.;
  origin[2] = -255.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 504.;
  spacing[1] = 504.;
  spacing[2] = 504.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages);

  // Create ellipsoid PROJECTIONS
  typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
  REIType::Pointer rei;

  rei = REIType::New();
  REIType::VectorType semiprincipalaxis, center;
  semiprincipalaxis.Fill(90.);
  center.Fill(0.);
  rei->SetAngle(0.);
  rei->SetDensity(1.);
  rei->SetCenter(center);
  rei->SetAxis(semiprincipalaxis);

  rei->SetInput( projectionsSource->GetOutput() );
  rei->SetGeometry( geometry );

  //Update
  TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() );

  // Create REFERENCE object (3D ellipsoid).
  typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
  DEType::Pointer dsl = DEType::New();
  dsl->SetInput( tomographySource->GetOutput() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )

  // Create the weights map
  ConstantImageSourceType::Pointer uniformWeightsSource = ConstantImageSourceType::New();
  uniformWeightsSource->SetInformationFromImage(projectionsSource->GetOutput());
  uniformWeightsSource->SetConstant(1.0);

  // Regularized CG reconstruction filter
  typedef rtk::RegularizedConjugateGradientConeBeamReconstructionFilter<OutputImageType>   RegularizedCGType;
  RegularizedCGType::Pointer regularizedConjugateGradient = RegularizedCGType::New();
  regularizedConjugateGradient->SetInputVolume(tomographySource->GetOutput() );
  regularizedConjugateGradient->SetInputProjectionStack(rei->GetOutput());
  regularizedConjugateGradient->SetInputWeights( uniformWeightsSource->GetOutput());
  regularizedConjugateGradient->SetPreconditioned(false);
  regularizedConjugateGradient->SetGeometry( geometry );
  regularizedConjugateGradient->SetMainLoop_iterations( 2 );
  regularizedConjugateGradient->SetCudaConjugateGradient(false);

  regularizedConjugateGradient->SetGammaTV(1);
  regularizedConjugateGradient->SetTV_iterations( 3 );

  regularizedConjugateGradient->SetSoftThresholdWavelets(0.1);
  regularizedConjugateGradient->SetOrder(3);
  regularizedConjugateGradient->SetNumberOfLevels(3);

  // In all cases except CUDA, use the Joseph forward projector and Voxel-based back projector
  regularizedConjugateGradient->SetForwardProjectionFilter(0);
  regularizedConjugateGradient->SetBackProjectionFilter( 0 );

  std::cout << "\n\n****** Case 1: Positivity + TV regularization ******" << std::endl;

  regularizedConjugateGradient->SetPerformPositivity(true);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 2: Wavelets ******" << std::endl;

  regularizedConjugateGradient->SetPerformPositivity(false);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;

#ifdef USE_CUDA
  std::cout << "\n\n****** Case 3: CUDA Voxel-Based Backprojector and CUDA Forward projector, all regularization steps on ******" << std::endl;

  regularizedConjugateGradient->SetForwardProjectionFilter( 2 );
  regularizedConjugateGradient->SetBackProjectionFilter( 2 );
  regularizedConjugateGradient->SetCudaConjugateGradient(true);
  regularizedConjugateGradient->SetPerformPositivity(true);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;
#endif

  std::cout << "\n\n****** Image-domain sparsity ******" << std::endl;

  // Replace the ellise with a very small one
  semiprincipalaxis.Fill(9.);
  rei->SetAxis(semiprincipalaxis);
  dsl->SetAxis(semiprincipalaxis);

  // Add gaussian noise on the projections
  typedef itk::AdditiveGaussianNoiseImageFilter<OutputImageType>      GaussianNoiseFilterType;
  GaussianNoiseFilterType::Pointer gaussian = GaussianNoiseFilterType::New();
  gaussian->SetStandardDeviation(1);
  gaussian->SetMean(0.);
  gaussian->SetInput(rei->GetOutput());

  regularizedConjugateGradient->SetInputProjectionStack(gaussian->GetOutput());
  regularizedConjugateGradient->SetPerformPositivity(false);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);
  regularizedConjugateGradient->SetPerformSoftThresholdOnImage(true);
  regularizedConjugateGradient->SetSoftThresholdOnImage(0.01);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.004, 47, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;

  return EXIT_SUCCESS;
}
<commit_msg>COMP: In rtkregularizedconjugategradienttest.cxx, ignore the last test if ITK is too old (AdditiveGaussianNoiseImageFilter was added around version 4.5)<commit_after>#include "rtkTest.h"
#include "rtkDrawEllipsoidImageFilter.h"
#include "rtkRayEllipsoidIntersectionImageFilter.h"
#include "rtkConstantImageSource.h"
#include "rtkRegularizedConjugateGradientConeBeamReconstructionFilter.h"

#if ITK_VERSION_MAJOR > 4 || (ITK_VERSION_MAJOR == 4 && ITK_VERSION_MINOR >= 6)
  #include <itkAdditiveGaussianNoiseImageFilter.h>
#endif

#ifdef USE_CUDA
  #include "itkCudaImage.h"
#endif

/**
 * \file rtkregularizedconjugategradienttest.cxx
 *
 * \brief Functional test for ADMMTotalVariation reconstruction
 *
 * This test generates the projections of an ellipsoid and reconstructs the CT
 * image using the ADMMTotalVariation algorithm with different backprojectors (Voxel-Based,
 * Joseph). The generated results are compared to the
 * expected results (analytical calculation).
 *
 * \author Cyril Mory
 */

int main(int, char** )
{
  typedef float OutputPixelType;
  const unsigned int Dimension = 3;

#ifdef USE_CUDA
  typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
#else
  typedef itk::Image< OutputPixelType, Dimension >     OutputImageType;
#endif

#if FAST_TESTS_NO_CHECKS
  const unsigned int NumberOfProjectionImages = 3;
#else
  const unsigned int NumberOfProjectionImages = 90;
#endif

  // Constant image sources
  typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType;
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SizeType size;
  ConstantImageSourceType::SpacingType spacing;

  ConstantImageSourceType::Pointer tomographySource  = ConstantImageSourceType::New();
  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;
  spacing[0] = 252.;
  spacing[1] = 252.;
  spacing[2] = 252.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = 64;
  spacing[0] = 4.;
  spacing[1] = 4.;
  spacing[2] = 4.;
#endif
  tomographySource->SetOrigin( origin );
  tomographySource->SetSpacing( spacing );
  tomographySource->SetSize( size );
  tomographySource->SetConstant( 0. );

  ConstantImageSourceType::Pointer projectionsSource = ConstantImageSourceType::New();
  origin[0] = -255.;
  origin[1] = -255.;
  origin[2] = -255.;
#if FAST_TESTS_NO_CHECKS
  size[0] = 2;
  size[1] = 2;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 504.;
  spacing[1] = 504.;
  spacing[2] = 504.;
#else
  size[0] = 64;
  size[1] = 64;
  size[2] = NumberOfProjectionImages;
  spacing[0] = 8.;
  spacing[1] = 8.;
  spacing[2] = 8.;
#endif
  projectionsSource->SetOrigin( origin );
  projectionsSource->SetSpacing( spacing );
  projectionsSource->SetSize( size );
  projectionsSource->SetConstant( 0. );

  // Geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();
  for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++)
    geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages);

  // Create ellipsoid PROJECTIONS
  typedef rtk::RayEllipsoidIntersectionImageFilter<OutputImageType, OutputImageType> REIType;
  REIType::Pointer rei;

  rei = REIType::New();
  REIType::VectorType semiprincipalaxis, center;
  semiprincipalaxis.Fill(90.);
  center.Fill(0.);
  rei->SetAngle(0.);
  rei->SetDensity(1.);
  rei->SetCenter(center);
  rei->SetAxis(semiprincipalaxis);

  rei->SetInput( projectionsSource->GetOutput() );
  rei->SetGeometry( geometry );

  //Update
  TRY_AND_EXIT_ON_ITK_EXCEPTION( rei->Update() );

  // Create REFERENCE object (3D ellipsoid).
  typedef rtk::DrawEllipsoidImageFilter<OutputImageType, OutputImageType> DEType;
  DEType::Pointer dsl = DEType::New();
  dsl->SetInput( tomographySource->GetOutput() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() )

  // Create the weights map
  ConstantImageSourceType::Pointer uniformWeightsSource = ConstantImageSourceType::New();
  uniformWeightsSource->SetInformationFromImage(projectionsSource->GetOutput());
  uniformWeightsSource->SetConstant(1.0);

  // Regularized CG reconstruction filter
  typedef rtk::RegularizedConjugateGradientConeBeamReconstructionFilter<OutputImageType>   RegularizedCGType;
  RegularizedCGType::Pointer regularizedConjugateGradient = RegularizedCGType::New();
  regularizedConjugateGradient->SetInputVolume(tomographySource->GetOutput() );
  regularizedConjugateGradient->SetInputProjectionStack(rei->GetOutput());
  regularizedConjugateGradient->SetInputWeights( uniformWeightsSource->GetOutput());
  regularizedConjugateGradient->SetPreconditioned(false);
  regularizedConjugateGradient->SetGeometry( geometry );
  regularizedConjugateGradient->SetMainLoop_iterations( 2 );
  regularizedConjugateGradient->SetCudaConjugateGradient(false);

  regularizedConjugateGradient->SetGammaTV(1);
  regularizedConjugateGradient->SetTV_iterations( 3 );

  regularizedConjugateGradient->SetSoftThresholdWavelets(0.1);
  regularizedConjugateGradient->SetOrder(3);
  regularizedConjugateGradient->SetNumberOfLevels(3);

  // In all cases except CUDA, use the Joseph forward projector and Voxel-based back projector
  regularizedConjugateGradient->SetForwardProjectionFilter(0);
  regularizedConjugateGradient->SetBackProjectionFilter( 0 );

  std::cout << "\n\n****** Case 1: Positivity + TV regularization ******" << std::endl;

  regularizedConjugateGradient->SetPerformPositivity(true);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;

  std::cout << "\n\n****** Case 2: Wavelets ******" << std::endl;

  regularizedConjugateGradient->SetPerformPositivity(false);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;

#ifdef USE_CUDA
  std::cout << "\n\n****** Case 3: CUDA Voxel-Based Backprojector and CUDA Forward projector, all regularization steps on ******" << std::endl;

  regularizedConjugateGradient->SetForwardProjectionFilter( 2 );
  regularizedConjugateGradient->SetBackProjectionFilter( 2 );
  regularizedConjugateGradient->SetCudaConjugateGradient(true);
  regularizedConjugateGradient->SetPerformPositivity(true);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(true);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(true);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.05, 23, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;
#endif

#if ITK_VERSION_MAJOR > 4 || (ITK_VERSION_MAJOR == 4 && ITK_VERSION_MINOR >= 6)
  std::cout << "\n\n****** Image-domain sparsity ******" << std::endl;

  // Replace the ellise with a very small one
  semiprincipalaxis.Fill(9.);
  rei->SetAxis(semiprincipalaxis);
  dsl->SetAxis(semiprincipalaxis);

  // Add gaussian noise on the projections
  typedef itk::AdditiveGaussianNoiseImageFilter<OutputImageType>      GaussianNoiseFilterType;
  GaussianNoiseFilterType::Pointer gaussian = GaussianNoiseFilterType::New();
  gaussian->SetStandardDeviation(1);
  gaussian->SetMean(0.);
  gaussian->SetInput(rei->GetOutput());

  regularizedConjugateGradient->SetInputProjectionStack(gaussian->GetOutput());
  regularizedConjugateGradient->SetPerformPositivity(false);
  regularizedConjugateGradient->SetPerformTVSpatialDenoising(false);
  regularizedConjugateGradient->SetPerformWaveletsSpatialDenoising(false);
  regularizedConjugateGradient->SetPerformSoftThresholdOnImage(true);
  regularizedConjugateGradient->SetSoftThresholdOnImage(0.01);

  TRY_AND_EXIT_ON_ITK_EXCEPTION( regularizedConjugateGradient->Update() );
  TRY_AND_EXIT_ON_ITK_EXCEPTION( dsl->Update() );

  CheckImageQuality<OutputImageType>(regularizedConjugateGradient->GetOutput(), dsl->GetOutput(), 0.004, 47, 2.0);
  std::cout << "\n\nTest PASSED! " << std::endl;
#endif

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "mpi.h"

int main(int argc, char **argv) {

  MPI_Init(&argc, &argv);

  MPI_Finalize();

  return 0;
}
<commit_msg>[BROKEN] Fix style in init_test<commit_after>#include "mpi.h"

int main(int argc, char **argv)
{
  MPI_Init(&argc, &argv);

  MPI_Finalize();

  return 0;
}
<|endoftext|>


<commit_before>#define START 0
#define ENTRY 0

#include "timings.h"
#include <inttypes.h>

#define START_NO 1000000000

#include <libcpu.h>
#include "arch/arm/arm_types.h"
#include "arch/m88k/m88k_isa.h"

#define RET_MAGIC 0x4D495354

static void
debug_function(cpu_t *cpu) {
	fprintf(stderr, "%s:%u\n", __FILE__, __LINE__);
}

int fib(int n)
{
    int f2=0;
    int f1=1;
    int fib=0;
    int i;

    if (n==0 || n==1)
        return n;
    for(i=2;i<=n;i++){
        fib=f1+f2; /*sum*/
        f2=f1;
        f1=fib;
    }
    return fib;
}

//////////////////////////////////////////////////////////////////////
#define SINGLESTEP_NONE	0
#define SINGLESTEP_STEP	1
#define SINGLESTEP_BB	2
//////////////////////////////////////////////////////////////////////

int
main(int argc, char **argv)
{
	char *s_arch;
	char *executable;
	cpu_arch_t arch;
	cpu_t *cpu;
	uint8_t *RAM;
	FILE *f;
	int ramsize;
	int r1, r2;
	uint64_t t1, t2, t3, t4;
	unsigned start_no = START_NO;

	int singlestep = SINGLESTEP_NONE;
	int log = 1;
	int print_ir = 1;

	/* parameter parsing */
	if (argc < 3) {
		printf("Usage: %s executable [arch] [itercount] [entries]\n", argv[0]);
		return 0;
	}
	s_arch = argv[1];
	executable = argv[2];
	if (argc >= 4)
		start_no = atoi(argv[3]);
	if (!strcmp("mips", s_arch))
		arch = CPU_ARCH_MIPS;
	else if (!strcmp("m88k", s_arch))
		arch = CPU_ARCH_M88K;
	else if (!strcmp("arm", s_arch))
		arch = CPU_ARCH_ARM;
	else if (!strcmp("fapra", s_arch))
		arch = CPU_ARCH_FAPRA;
	else {
		printf("unknown architecture '%s'!\n", s_arch);
		return 0;
	}

	ramsize = 5*1024*1024;
	RAM = (uint8_t*)malloc(ramsize);

	cpu = cpu_new(arch, 0, 0);

	cpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE);
	cpu_set_flags_debug(cpu, 0
		| (print_ir? CPU_DEBUG_PRINT_IR : 0)
		| (print_ir? CPU_DEBUG_PRINT_IR_OPTIMIZED : 0)
		| (log? CPU_DEBUG_LOG :0)
		| (singlestep == SINGLESTEP_STEP? CPU_DEBUG_SINGLESTEP    : 0)
		| (singlestep == SINGLESTEP_BB?   CPU_DEBUG_SINGLESTEP_BB : 0)
		);

	cpu_set_ram(cpu, RAM);

	/* load code */
	if (!(f = fopen(executable, "rb"))) {
		printf("Could not open %s!\n", executable);
		return 2;
	}
	cpu->code_start = START;
	cpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);
	fclose(f);
	cpu->code_entry = cpu->code_start + ENTRY;

	cpu_tag(cpu, cpu->code_entry);

	cpu_translate(cpu); /* force translation now */

	printf("\n*** Executing...\n");

	printf("number of iterations: %u\n", start_no);

	uint32_t *reg_pc, *reg_lr, *reg_param, *reg_result;
	switch (arch) {
		case CPU_ARCH_M88K:
			reg_pc = &((m88k_grf_t*)cpu->rf.grf)->sxip;
			reg_lr = &((m88k_grf_t*)cpu->rf.grf)->r[1];
			reg_param = &((m88k_grf_t*)cpu->rf.grf)->r[2];
			reg_result = &((m88k_grf_t*)cpu->rf.grf)->r[2];
			break;
		case CPU_ARCH_MIPS:
			reg_pc = &((reg_mips32_t*)cpu->rf.grf)->pc;
			reg_lr = &((reg_mips32_t*)cpu->rf.grf)->r[31];
			reg_param = &((reg_mips32_t*)cpu->rf.grf)->r[4];
			reg_result = &((reg_mips32_t*)cpu->rf.grf)->r[4];
			break;
		case CPU_ARCH_ARM:
			reg_pc = &((reg_arm_t*)cpu->rf.grf)->pc;
			reg_lr = &((reg_arm_t*)cpu->rf.grf)->r[14];
			reg_param = &((reg_arm_t*)cpu->rf.grf)->r[0];
			reg_result = &((reg_arm_t*)cpu->rf.grf)->r[0];
			break;
		case CPU_ARCH_FAPRA:
			reg_pc = &((reg_fapra32_t*)cpu->rf.grf)->pc;
			reg_lr = &((reg_fapra32_t*)cpu->rf.grf)->r[0];
			reg_param = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
			reg_result = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
			break;
		default:
			fprintf(stderr, "architecture %u not handled.\n", arch);
			exit(EXIT_FAILURE);
	}

	*reg_pc = cpu->code_entry;
	*reg_lr = RET_MAGIC;
	*reg_param = start_no;

	printf("GUEST run..."); fflush(stdout);

	t1 = abs_time();
	cpu_run(cpu, debug_function);
	t2 = abs_time();
	r1 = *reg_result;

	printf("done!\n");

	printf("HOST  run..."); fflush(stdout);
	t3 = abs_time();
	r2 = fib(start_no);
	t4 = abs_time();
	printf("done!\n");

  cpu_free(cpu);

	printf("Time GUEST: %"PRId64"\n", t2-t1);
	printf("Time HOST:  %"PRId64"\n", t4-t3);
	printf("Result HOST:  %d\n", r2);
	printf("Result GUEST: %d\n", r1);
	printf("GUEST required \033[1m%.2f%%\033[22m of HOST time.\n",  (float)(t2-t1)/(float)(t4-t3)*100);
	if (r1 == r2)
		printf("\033[1mSUCCESS!\033[22m\n\n");
	else
		printf("\033[1mFAILED!\033[22m\n\n");

	return 0;
}
//printf("%d\n", __LINE__);
<commit_msg>fix build<commit_after>#define START 0
#define ENTRY 0

#include "timings.h"
#include <inttypes.h>
#include <cinttypes>

#define START_NO 1000000000

#include <libcpu.h>
#include "arch/arm/arm_types.h"
#include "arch/m88k/m88k_isa.h"

#define RET_MAGIC 0x4D495354

static void
debug_function(cpu_t *cpu) {
	fprintf(stderr, "%s:%u\n", __FILE__, __LINE__);
}

int fib(int n)
{
    int f2=0;
    int f1=1;
    int fib=0;
    int i;

    if (n==0 || n==1)
        return n;
    for(i=2;i<=n;i++){
        fib=f1+f2; /*sum*/
        f2=f1;
        f1=fib;
    }
    return fib;
}

//////////////////////////////////////////////////////////////////////
#define SINGLESTEP_NONE	0
#define SINGLESTEP_STEP	1
#define SINGLESTEP_BB	2
//////////////////////////////////////////////////////////////////////

int
main(int argc, char **argv)
{
	char *s_arch;
	char *executable;
	cpu_arch_t arch;
	cpu_t *cpu;
	uint8_t *RAM;
	FILE *f;
	int ramsize;
	int r1, r2;
	uint64_t t1, t2, t3, t4;
	unsigned start_no = START_NO;

	int singlestep = SINGLESTEP_NONE;
	int log = 1;
	int print_ir = 1;

	/* parameter parsing */
	if (argc < 3) {
		printf("Usage: %s executable [arch] [itercount] [entries]\n", argv[0]);
		return 0;
	}
	s_arch = argv[1];
	executable = argv[2];
	if (argc >= 4)
		start_no = atoi(argv[3]);
	if (!strcmp("mips", s_arch))
		arch = CPU_ARCH_MIPS;
	else if (!strcmp("m88k", s_arch))
		arch = CPU_ARCH_M88K;
	else if (!strcmp("arm", s_arch))
		arch = CPU_ARCH_ARM;
	else if (!strcmp("fapra", s_arch))
		arch = CPU_ARCH_FAPRA;
	else {
		printf("unknown architecture '%s'!\n", s_arch);
		return 0;
	}

	ramsize = 5*1024*1024;
	RAM = (uint8_t*)malloc(ramsize);

	cpu = cpu_new(arch, 0, 0);

	cpu_set_flags_codegen(cpu, CPU_CODEGEN_OPTIMIZE);
	cpu_set_flags_debug(cpu, 0
		| (print_ir? CPU_DEBUG_PRINT_IR : 0)
		| (print_ir? CPU_DEBUG_PRINT_IR_OPTIMIZED : 0)
		| (log? CPU_DEBUG_LOG :0)
		| (singlestep == SINGLESTEP_STEP? CPU_DEBUG_SINGLESTEP    : 0)
		| (singlestep == SINGLESTEP_BB?   CPU_DEBUG_SINGLESTEP_BB : 0)
		);

	cpu_set_ram(cpu, RAM);

	/* load code */
	if (!(f = fopen(executable, "rb"))) {
		printf("Could not open %s!\n", executable);
		return 2;
	}
	cpu->code_start = START;
	cpu->code_end = cpu->code_start + fread(&RAM[cpu->code_start], 1, ramsize-cpu->code_start, f);
	fclose(f);
	cpu->code_entry = cpu->code_start + ENTRY;

	cpu_tag(cpu, cpu->code_entry);

	cpu_translate(cpu); /* force translation now */

	printf("\n*** Executing...\n");

	printf("number of iterations: %u\n", start_no);

	uint32_t *reg_pc, *reg_lr, *reg_param, *reg_result;
	switch (arch) {
		case CPU_ARCH_M88K:
			reg_pc = &((m88k_grf_t*)cpu->rf.grf)->sxip;
			reg_lr = &((m88k_grf_t*)cpu->rf.grf)->r[1];
			reg_param = &((m88k_grf_t*)cpu->rf.grf)->r[2];
			reg_result = &((m88k_grf_t*)cpu->rf.grf)->r[2];
			break;
		case CPU_ARCH_MIPS:
			reg_pc = &((reg_mips32_t*)cpu->rf.grf)->pc;
			reg_lr = &((reg_mips32_t*)cpu->rf.grf)->r[31];
			reg_param = &((reg_mips32_t*)cpu->rf.grf)->r[4];
			reg_result = &((reg_mips32_t*)cpu->rf.grf)->r[4];
			break;
		case CPU_ARCH_ARM:
			reg_pc = &((reg_arm_t*)cpu->rf.grf)->pc;
			reg_lr = &((reg_arm_t*)cpu->rf.grf)->r[14];
			reg_param = &((reg_arm_t*)cpu->rf.grf)->r[0];
			reg_result = &((reg_arm_t*)cpu->rf.grf)->r[0];
			break;
		case CPU_ARCH_FAPRA:
			reg_pc = &((reg_fapra32_t*)cpu->rf.grf)->pc;
			reg_lr = &((reg_fapra32_t*)cpu->rf.grf)->r[0];
			reg_param = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
			reg_result = &((reg_fapra32_t*)cpu->rf.grf)->r[3];
			break;
		default:
			fprintf(stderr, "architecture %u not handled.\n", arch);
			exit(EXIT_FAILURE);
	}

	*reg_pc = cpu->code_entry;
	*reg_lr = RET_MAGIC;
	*reg_param = start_no;

	printf("GUEST run..."); fflush(stdout);

	t1 = abs_time();
	cpu_run(cpu, debug_function);
	t2 = abs_time();
	r1 = *reg_result;

	printf("done!\n");

	printf("HOST  run..."); fflush(stdout);
	t3 = abs_time();
	r2 = fib(start_no);
	t4 = abs_time();
	printf("done!\n");

  cpu_free(cpu);

	printf("Time GUEST: %" PRId64 "\n", t2-t1);
	printf("Time HOST:  %" PRId64 "\n", t4-t3);
	printf("Result HOST:  %d\n", r2);
	printf("Result GUEST: %d\n", r1);
	printf("GUEST required \033[1m%.2f%%\033[22m of HOST time.\n",  (float)(t2-t1)/(float)(t4-t3)*100);
	if (r1 == r2)
		printf("\033[1mSUCCESS!\033[22m\n\n");
	else
		printf("\033[1mFAILED!\033[22m\n\n");

	return 0;
}
//printf("%d\n", __LINE__);
<|endoftext|>


<commit_before>#include <side.hh>

#include <gtest/gtest.h>

using namespace Rubik;

namespace SideData
{
  const Side::Data top =
    {
      1, 2, 3,
      4, 5, 6,
      7, 8, 9,
    };
  const Side::Data bottom =
    {
      9, 8, 7,
      6, 5, 4,
      3, 2, 1,
    };
  const Side::Data right =
    {
      3, 6, 9,
      2, 5, 8,
      1, 4, 7,
    };
  const Side::Data left =
    {
      7, 4, 1,
      8, 5, 2,
      9, 6, 3,
    };
}

TEST(Side, Initialize)
{
  Side::Data data = {0};
  Orientation orientation = top(1).left(2).bottom(3).right(4);

  Side::Ptr side = Side::create(data, orientation);

  EXPECT_EQ(data, side->data());
}

class PerspectiveData
{
public:
  Side::Data top;
  Side::Data bottom;
  Side::Data left;
  Side::Data right;

public:
  PerspectiveData(Side::Data const& top, Side::Data const& bottom, Side::Data const& left, Side::Data const& right)
    :top(top), bottom(bottom), left(left), right(right)
  {}
};

std::ostream& operator<<(std::ostream& os, PerspectiveData const& data)
{
  os << std::endl;
  os << "Top:    " << data.top ;
  os << "Bottom: " << data.bottom;
  os << "Left:   " << data.left;
  os << "Right:  " << data.right;
  return os;
}

class SidePerspective : public testing::TestWithParam<PerspectiveData>
{
protected:
  PerspectiveData const& data;
  Orientation const orientation;
  Side::Ptr const side;

public:
  SidePerspective()
    : data(GetParam()),
      orientation(top(1).left(2).bottom(3).right(4)),
      side(Side::create(data.top, orientation))
  {}
};

INSTANTIATE_TEST_CASE_P(Combinatorial, SidePerspective,
                        testing::Values(PerspectiveData(SideData::top, SideData::bottom, SideData::left, SideData::right),
                                        PerspectiveData(SideData::left, SideData::right, SideData::bottom, SideData::top)
                                        ));

TEST_P(SidePerspective, Top)
{
  EXPECT_EQ(data.top, side->data(orientation.top()));
}

TEST_P(SidePerspective, Bottom)
{
  EXPECT_EQ(data.bottom, side->data(orientation.bottom()));
}

TEST_P(SidePerspective, Right)
{
  EXPECT_EQ(data.right, side->data(orientation.right()));
}

TEST_P(SidePerspective, Left)
{
  EXPECT_EQ(data.left, side->data(orientation.left()));
}

<commit_msg>Refactor: Parametrize tests over Orientations<commit_after>#include <side.hh>

#include <tuple>

#include <gtest/gtest.h>

using namespace Rubik;

namespace SideData
{
  const Side::Data top =
    {
      1, 2, 3,
      4, 5, 6,
      7, 8, 9,
    };
  const Side::Data bottom =
    {
      9, 8, 7,
      6, 5, 4,
      3, 2, 1,
    };
  const Side::Data right =
    {
      3, 6, 9,
      2, 5, 8,
      1, 4, 7,
    };
  const Side::Data left =
    {
      7, 4, 1,
      8, 5, 2,
      9, 6, 3,
    };
}

TEST(Side, Initialize)
{
  Side::Data data = {0};
  Orientation orientation = top(1).left(2).bottom(3).right(4);

  Side::Ptr side = Side::create(data, orientation);

  EXPECT_EQ(data, side->data());
}

class PerspectiveData
{
public:
  Side::Data top;
  Side::Data bottom;
  Side::Data left;
  Side::Data right;

public:
  PerspectiveData()
  {}

  PerspectiveData(Side::Data const& top, Side::Data const& bottom, Side::Data const& left, Side::Data const& right)
    :top(top), bottom(bottom), left(left), right(right)
  {}
};

std::ostream& operator<<(std::ostream& os, PerspectiveData const& data)
{
  os << std::endl;
  os << "Top:    " << data.top ;
  os << "Bottom: " << data.bottom;
  os << "Left:   " << data.left;
  os << "Right:  " << data.right;
  return os;
}

class SidePerspective : public testing::TestWithParam<std::tr1::tuple<Orientation,PerspectiveData> >
{
protected:
  Orientation const orientation;
  PerspectiveData const data;
  Side::Ptr const side;

public:
  SidePerspective()
    : orientation(std::tr1::get<0>(GetParam())),
      data(std::tr1::get<1>(GetParam())),
      side(Side::create(data.top, orientation))
  {}
};

INSTANTIATE_TEST_CASE_P
(Combinatorial, SidePerspective,
 testing::Combine(
                  testing::Values(top(1).left(2).bottom(3).right(4)),
                  testing::Values(PerspectiveData(SideData::top, SideData::bottom, SideData::left, SideData::right),
                                  PerspectiveData(SideData::left, SideData::right, SideData::bottom, SideData::top)
                                  )));

TEST_P(SidePerspective, Top)
{
  EXPECT_EQ(data.top, side->data(orientation.top()));
}

TEST_P(SidePerspective, Bottom)
{
  EXPECT_EQ(data.bottom, side->data(orientation.bottom()));
}

TEST_P(SidePerspective, Right)
{
  EXPECT_EQ(data.right, side->data(orientation.right()));
}

TEST_P(SidePerspective, Left)
{
  EXPECT_EQ(data.left, side->data(orientation.left()));
}

<|endoftext|>


<commit_before>/*

Copyright (c) 2012, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/file.hpp"
#include "test.hpp"
#include <vector>
#include <set>

using namespace libtorrent;

int touch_file(std::string const& filename, int size)
{
	using namespace libtorrent;

	std::vector<char> v;
	v.resize(size);
	for (int i = 0; i < size; ++i)
		v[i] = i & 255;

	file f;
	error_code ec;
	if (!f.open(filename, file::write_only, ec)) return -1;
	if (ec) return -1;
	file::iovec_t b = {&v[0], v.size()};
	size_type written = f.writev(0, &b, 1, ec);
	if (written != int(v.size())) return -3;
	if (ec) return -3;
	return 0;
}

int test_main()
{
	error_code ec;

	create_directory("file_test_dir", ec);
	if (ec) fprintf(stderr, "create_directory: %s\n", ec.message().c_str());
	TEST_CHECK(!ec);

	std::string cwd = current_working_directory();

	touch_file(combine_path("file_test_dir", "abc"), 10);
	touch_file(combine_path("file_test_dir", "def"), 100);
	touch_file(combine_path("file_test_dir", "ghi"), 1000);

	std::set<std::string> files;
	for (directory i("file_test_dir", ec); !i.done(); i.next(ec))
	{
		std::string f = i.file();
		TEST_CHECK(files.count(f) == 0);
		files.insert(f);
		fprintf(stderr, " %s\n", f.c_str());
	}

	TEST_CHECK(files.count("abc") == 1);
	TEST_CHECK(files.count("def") == 1);
	TEST_CHECK(files.count("ghi") == 1);
	TEST_CHECK(files.count("..") == 1);
	TEST_CHECK(files.count(".") == 1);

	remove_all("file_test_dir", ec);
	if (ec) fprintf(stderr, "create_directory: %s\n", ec.message().c_str());

	return 0;
}

<commit_msg>expand file test<commit_after>/*

Copyright (c) 2012, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/file.hpp"
#include "test.hpp"
#include <vector>
#include <set>

using namespace libtorrent;

int touch_file(std::string const& filename, int size)
{
	using namespace libtorrent;

	std::vector<char> v;
	v.resize(size);
	for (int i = 0; i < size; ++i)
		v[i] = i & 255;

	file f;
	error_code ec;
	if (!f.open(filename, file::write_only, ec)) return -1;
	if (ec) return -1;
	file::iovec_t b = {&v[0], v.size()};
	size_type written = f.writev(0, &b, 1, ec);
	if (written != int(v.size())) return -3;
	if (ec) return -3;
	return 0;
}

int test_main()
{
	error_code ec;

	create_directory("file_test_dir", ec);
	if (ec) fprintf(stderr, "create_directory: %s\n", ec.message().c_str());
	TEST_CHECK(!ec);

	std::string cwd = current_working_directory();

	touch_file(combine_path("file_test_dir", "abc"), 10);
	touch_file(combine_path("file_test_dir", "def"), 100);
	touch_file(combine_path("file_test_dir", "ghi"), 1000);

	std::set<std::string> files;
	for (directory i("file_test_dir", ec); !i.done(); i.next(ec))
	{
		std::string f = i.file();
		TEST_CHECK(files.count(f) == 0);
		files.insert(f);
		fprintf(stderr, " %s\n", f.c_str());
	}

	TEST_CHECK(files.count("abc") == 1);
	TEST_CHECK(files.count("def") == 1);
	TEST_CHECK(files.count("ghi") == 1);
	TEST_CHECK(files.count("..") == 1);
	TEST_CHECK(files.count(".") == 1);
	files.clear();

	recursive_copy("file_test_dir", "file_test_dir2", ec);

	for (directory i("file_test_dir2", ec); !i.done(); i.next(ec))
	{
		std::string f = i.file();
		TEST_CHECK(files.count(f) == 0);
		files.insert(f);
		fprintf(stderr, " %s\n", f.c_str());
	}

	remove_all("file_test_dir", ec);
	if (ec) fprintf(stderr, "remove_all: %s\n", ec.message().c_str());
	remove_all("file_test_dir2", ec);
	if (ec) fprintf(stderr, "remove_all: %s\n", ec.message().c_str());

	return 0;
}

<|endoftext|>


<commit_before>/******************************************************************************
The MIT License(MIT)

Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com

Copyright(c) 2014 jwellbelove

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/

#include <UnitTest++/UnitTest++.h>

#include <iterator>
#include <string>
#include <vector>
#include <stdint.h>

#include "../hash.h"

namespace
{
  SUITE(test_hash)
  {
    //*************************************************************************
    TEST(test_hash_bool)
    {
      size_t hash = etl::hash<bool>()(false);
      CHECK_EQUAL(0, hash);

      hash = etl::hash<bool>()(true);
      CHECK_EQUAL(1, hash);
    }

    //*************************************************************************
    TEST(test_hash_char)
    {
      size_t hash = etl::hash<char>()((char)(0x5A));

      CHECK_EQUAL(0x5A, hash);
    }

    //*************************************************************************
    TEST(test_hash_signed_char)
    {
      size_t hash = etl::hash<signed char>()((signed char)(0x5A));

      CHECK_EQUAL(0x5A, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_char)
    {
      size_t hash = etl::hash<unsigned char>()((unsigned char)(0x5A));

      CHECK_EQUAL(0x5A, hash);
    }

    //*************************************************************************
    TEST(test_hash_short)
    {
      size_t hash = etl::hash<short>()((short)(0x5AA5));

      CHECK_EQUAL(0x5AA5, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_short)
    {
      size_t hash = etl::hash<unsigned short>()((unsigned short)(0x5AA5));

      CHECK_EQUAL(0x5AA5, hash);
    }

    //*************************************************************************
    TEST(test_hash_int)
    {
      size_t hash = etl::hash<int>()((int)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_int)
    {
      size_t hash = etl::hash<unsigned int>()((unsigned int)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_long)
    {
      size_t hash = etl::hash<long>()((long)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_long)
    {
      size_t hash = etl::hash<unsigned long>()((unsigned long)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_long_long)
    {
      size_t hash = etl::hash<long long>()((long long)(0x5AA555AA3CC333CC));

      CHECK_EQUAL(0xEC6A8D69, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_long_long)
    {
      size_t hash = etl::hash<unsigned long long>()((unsigned long long)(0x5AA555AA3CC333CC));

      CHECK_EQUAL(0xEC6A8D69, hash);
    }

    //*************************************************************************
    TEST(test_hash_float)
    {
      size_t hash = etl::hash<float>()((float)(1.2345));

      CHECK_EQUAL(0x3F9E0419, hash);
    }

    //*************************************************************************
    TEST(test_hash_double)
    {
      size_t hash = etl::hash<double>()((double)(1.2345));

      CHECK_EQUAL(0x86FBF224, hash);
    }

    //*************************************************************************
    TEST(test_hash_pointer)
    {
      int i;
      size_t hash = etl::hash<int*>()(&i);

      CHECK_EQUAL(size_t(&i), hash);
    }
  };
}

<commit_msg>Modified for 64 bit 'size_t' compatibilty<commit_after>/******************************************************************************
The MIT License(MIT)

Embedded Template Library.
https://github.com/ETLCPP/etl
http://www.etlcpp.com

Copyright(c) 2014 jwellbelove

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/

#include <UnitTest++/UnitTest++.h>

#include <iterator>
#include <string>
#include <vector>
#include <stdint.h>

#include "../hash.h"

namespace
{
  SUITE(test_hash)
  {
    //*************************************************************************
    TEST(test_hash_bool)
    {
      size_t hash = etl::hash<bool>()(false);
      CHECK_EQUAL(0, hash);

      hash = etl::hash<bool>()(true);
      CHECK_EQUAL(1, hash);
    }

    //*************************************************************************
    TEST(test_hash_char)
    {
      size_t hash = etl::hash<char>()((char)(0x5A));

      CHECK_EQUAL(0x5A, hash);
    }

    //*************************************************************************
    TEST(test_hash_signed_char)
    {
      size_t hash = etl::hash<signed char>()((signed char)(0x5A));

      CHECK_EQUAL(0x5A, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_char)
    {
      size_t hash = etl::hash<unsigned char>()((unsigned char)(0x5A));

      CHECK_EQUAL(0x5A, hash);
    }

    //*************************************************************************
    TEST(test_hash_short)
    {
      size_t hash = etl::hash<short>()((short)(0x5AA5));

      CHECK_EQUAL(0x5AA5, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_short)
    {
      size_t hash = etl::hash<unsigned short>()((unsigned short)(0x5AA5));

      CHECK_EQUAL(0x5AA5, hash);
    }

    //*************************************************************************
    TEST(test_hash_int)
    {
      size_t hash = etl::hash<int>()((int)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_int)
    {
      size_t hash = etl::hash<unsigned int>()((unsigned int)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_long)
    {
      size_t hash = etl::hash<long>()((long)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_long)
    {
      size_t hash = etl::hash<unsigned long>()((unsigned long)(0x5AA555AA));

      CHECK_EQUAL(0x5AA555AA, hash);
    }

    //*************************************************************************
    TEST(test_hash_long_long)
    {
      size_t hash = etl::hash<long long>()((long long)(0x5AA555AA3CC333CC));

      if (sizeof(size_t) == sizeof(long long))
        CHECK_EQUAL(0x5AA555AA3CC333CC, hash);
      else
        CHECK_EQUAL(0xEC6A8D69, hash);
    }

    //*************************************************************************
    TEST(test_hash_unsigned_long_long)
    {
      size_t hash = etl::hash<unsigned long long>()((unsigned long long)(0x5AA555AA3CC333CC));

      if (sizeof(size_t) == sizeof(unsigned long long))
        CHECK_EQUAL(0x5AA555AA3CC333CC, hash);
      else
        CHECK_EQUAL(0xEC6A8D69, hash);
    }

    //*************************************************************************
    TEST(test_hash_float)
    {
      size_t hash = etl::hash<float>()((float)(1.2345));

      if (sizeof(size_t) == sizeof(long long))
        CHECK_EQUAL(0x884B5E3F478AF88F, hash);
      else
        CHECK_EQUAL(0x3F9E0419, hash);
    }

    //*************************************************************************
    TEST(test_hash_double)
    {
      size_t hash = etl::hash<double>()((double)(1.2345));

      if (sizeof(size_t) == sizeof(long long))
        CHECK_EQUAL(0x3FF3C083126E978D, hash);
      else
        CHECK_EQUAL(0x86FBF224, hash);
    }

    //*************************************************************************
    TEST(test_hash_pointer)
    {
      int i;
      size_t hash = etl::hash<int*>()(&i);

      CHECK_EQUAL(size_t(&i), hash);
    }
  };
}

<|endoftext|>


<commit_before>#include "libtorrent/upnp.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/intrusive_ptr.hpp>

using namespace libtorrent;

void callback(int tcp, int udp, std::string const& err)
{
	std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n";
}

int main(int argc, char* argv[])
{
	io_service ios;
	std::string user_agent = "test agent";

	if (argc != 3)
	{
		std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl;
		return 1;
	}

	connection_queue cc(ios);
	boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback);

	deadline_timer timer(ios);
	timer.expires_from_now(seconds(2));
	timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));

	std::cerr << "broadcasting for UPnP device" << std::endl;

	ios.reset();
	ios.run();

	upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2]));
	timer.expires_from_now(seconds(5));
	timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));
	std::cerr << "mapping ports TCP: " << argv[1]
		<< " UDP: " << argv[2] << std::endl;

	ios.reset();
	ios.run();
	std::cerr << "removing mappings" << std::endl;
	upnp_handler->close();

	ios.reset();
	ios.run();
	std::cerr << "closing" << std::endl;
}

<commit_msg>fixed test_upnp<commit_after>#include "libtorrent/upnp.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/intrusive_ptr.hpp>

using namespace libtorrent;

void callback(int tcp, int udp, std::string const& err)
{
	std::cerr << "tcp: " << tcp << ", udp: " << udp << ", error: \"" << err << "\"\n";
}

int main(int argc, char* argv[])
{
	io_service ios;
	std::string user_agent = "test agent";

	if (argc != 3)
	{
		std::cerr << "usage: " << argv[0] << " tcp-port udp-port" << std::endl;
		return 1;
	}

	connection_queue cc(ios);
	boost::intrusive_ptr<upnp> upnp_handler = new upnp(ios, cc, address_v4(), user_agent, &callback);
	upnp_handler->discover_device();

	deadline_timer timer(ios);
	timer.expires_from_now(seconds(2));
	timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));

	std::cerr << "broadcasting for UPnP device" << std::endl;

	ios.reset();
	ios.run();

	upnp_handler->set_mappings(atoi(argv[1]), atoi(argv[2]));
	timer.expires_from_now(seconds(5));
	timer.async_wait(boost::bind(&io_service::stop, boost::ref(ios)));
	std::cerr << "mapping ports TCP: " << argv[1]
		<< " UDP: " << argv[2] << std::endl;

	ios.reset();
	ios.run();
	std::cerr << "router: " << upnp_handler->router_model() << std::endl;
	std::cerr << "removing mappings" << std::endl;
	upnp_handler->close();

	ios.reset();
	ios.run();
	std::cerr << "closing" << std::endl;
}

<|endoftext|>


<commit_before>
/*
    Filename:
        main.cpp
    Author:
        Vincent Heins / TheMysteriousVincent
    Description:
        Tests the functionality of the first layer for receiving input data.
*/

#include <iostream>
#include <string.h>
#include <map>
#include "handler.h"
#include <thread>
#include <chrono>
#include <ctime>

Handler *hndl = new Handler();

void makeRequest() {
    char *output = new char[8192];
    int outputSize = 8192;
    const char *function = "SENDRQ";
    const char *args[12];
    const char *tmp1 = "\"#url\"";
    const char *tmp2 = "\"https://httpbins.org/post\"";
    const char *tmp3 = "\"#postData\"";
    const char *tmp4 = "\"{\"test\":2}\"";
    const char *tmp5 = "\"\"";
    const char *tmp6 = "\"\"";
    const char *tmp7 = "\"#jsonToArray\"";
    const char *tmp8 = "\"#headers\"";
    const char *tmp9 = "\"Content-Type\"";
    const char *tmp10 = "\"application/json\"";
    const char *tmp11 = "\"#timeout\"";
    const char *tmp12 = "\"10\"";
    args[0] = tmp1;
    args[1] = tmp2;
    args[2] = tmp3;
    args[3] = tmp4;
    args[4] = tmp5;
    args[5] = tmp6;
    args[6] = tmp7;
    args[7] = tmp8;
    args[8] = tmp9;
    args[9] = tmp10;
    args[10] = tmp11;
    args[11] = tmp12;

    hndl->CallExtensionArgs(output, outputSize, function, args, 12);

    std::this_thread::sleep_for(std::chrono::seconds(1));

    auto start = std::chrono::high_resolution_clock::now();
    const char *args2[1];
    args2[0] = std::string(output).c_str();
    std::cout << args2[0] << std::endl;
    hndl->CallExtensionArgs(output, outputSize, "GETRQ", args2, 1);
    args2[0] = std::string(output).c_str();
    std::cout << args2[0] << std::endl;
    auto finish = std::chrono::high_resolution_clock::now();
    std::cout << "Time Results:" << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << std::endl << "---" << std::endl;

    std::cout << output << std::endl;
}

int main() {
    makeRequest();
    return 0;
}
<commit_msg>update test<commit_after>
/*
    Filename:
        main.cpp
    Author:
        Vincent Heins / TheMysteriousVincent
    Description:
        Tests the functionality of the first layer for receiving input data.
*/

#include <iostream>
#include <string.h>
#include <map>
#include "handler.h"
#include <thread>
#include <chrono>
#include <ctime>

Handler *hndl = new Handler();

void makeRequest() {
    char *output = new char[8192];
    int outputSize = 8192;
    const char *function = "SENDRQ";
    const char *args[12];
    const char *tmp1 = "\"#url\"";
    const char *tmp2 = "\"https://httpbins.org/delay/10\"";
    const char *tmp3 = "\"#postData\"";
    const char *tmp4 = "\"{\"test\":2}\"";
    const char *tmp5 = "\"\"";
    const char *tmp6 = "\"\"";
    const char *tmp7 = "\"#jsonToArray\"";
    const char *tmp8 = "\"#headers\"";
    const char *tmp9 = "\"Content-Type\"";
    const char *tmp10 = "\"application/json\"";
    const char *tmp11 = "\"#timeout\"";
    const char *tmp12 = "\"5\"";
    args[0] = tmp1;
    args[1] = tmp2;
    args[2] = tmp3;
    args[3] = tmp4;
    args[4] = tmp5;
    args[5] = tmp6;
    args[6] = tmp7;
    args[7] = tmp8;
    args[8] = tmp9;
    args[9] = tmp10;
    args[10] = tmp11;
    args[11] = tmp12;

    hndl->CallExtensionArgs(output, outputSize, function, args, 12);

    std::this_thread::sleep_for(std::chrono::seconds(1));

    auto start = std::chrono::high_resolution_clock::now();
    const char *args2[1];
    args2[0] = std::string(output).c_str();
    std::cout << args2[0] << std::endl;
    hndl->CallExtensionArgs(output, outputSize, "GETRQ", args2, 1);
    args2[0] = std::string(output).c_str();
    std::cout << args2[0] << std::endl;
    auto finish = std::chrono::high_resolution_clock::now();
    std::cout << "Time Results:" << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << std::endl << "---" << std::endl;

    std::cout << output << std::endl;
}

int main() {
    makeRequest();
    return 0;
}
<|endoftext|>


<commit_before>/*
   Copyright 2017 Cory Sherman

   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 "gtest/gtest.h"

#include "cgs/meta.hpp"
using cgs::is_constexpr;

constexpr int safe_v() { return 0; }
constexpr int safe_p(void*) { return 0; }
constexpr int safe_fi(float, int) { return 0; }

// constexpr if i != 0
constexpr int safe_if_nonzero(int i)
{
    if(i == 0) {
        throw i;
    }
    return i;
}

// constexpr if i == 0
constexpr int safe_if_zero(int i)
{
    if(i != 0) {
        throw i;
    }
    return i;
}

int unsafe_v()
{
    throw 0;
}

int unsafe_i(int i)
{
    throw 0;
}

TEST(Meta, IsConstexpr)
{
    EXPECT_TRUE( (is_constexpr<safe_v>()) );
    EXPECT_TRUE( (is_constexpr<safe_p>(nullptr)) );
    EXPECT_TRUE( (is_constexpr<safe_fi>(0.0f, 0)) );

    EXPECT_FALSE( (is_constexpr<unsafe_v>()) );
    EXPECT_FALSE( (is_constexpr<safe_if_nonzero>(0)) );

    // can also check at compile time
    static_assert(is_constexpr<safe_fi>(0.0f, 0));
    static_assert(!is_constexpr<unsafe_v>());
}

TEST(Meta, IsConstexprSafeIfZero)
{
    // false positive for is_constexpr<safe_if_zero>
    //
    // We pass default constructed arguments,
    // so we are testing if unsafe_inot(0), which IS constexpr,
    // even though unsafe_inot is not generally constexpr
    // see GitHub issue #1
    //
    // I don't think it is possible to test if a function is generally constexpr.
    //
    // It might be possible check if Func is constexpr with provided values.
    // I haven't figured it out yet.

    EXPECT_FALSE( (is_constexpr<safe_if_zero>(0)) );
}
<commit_msg>add direct test cases for issue #1<commit_after>/*
   Copyright 2017 Cory Sherman

   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 "gtest/gtest.h"

#include "cgs/meta.hpp"
using cgs::is_constexpr;

constexpr int safe_v() { return 0; }
constexpr int safe_p(void*) { return 0; }
constexpr int safe_fi(float, int) { return 0; }

// constexpr if i != 0
constexpr int safe_if_nonzero(int i)
{
    if(i == 0) {
        throw i;
    }
    return i;
}

// constexpr if i == 0
constexpr int safe_if_zero(int i)
{
    if(i != 0) {
        throw i;
    }
    return i;
}

int unsafe_v()
{
    throw 0;
}

int unsafe_i(int i)
{
    throw 0;
}

TEST(Meta, IsConstexpr)
{
    EXPECT_TRUE( (is_constexpr<safe_v>()) );
    EXPECT_TRUE( (is_constexpr<safe_p>(nullptr)) );
    EXPECT_TRUE( (is_constexpr<safe_fi>(0.0f, 0)) );

    EXPECT_FALSE( (is_constexpr<unsafe_v>()) );
    EXPECT_FALSE( (is_constexpr<safe_if_nonzero>(0)) );

    // can also check at compile time
    static_assert(is_constexpr<safe_fi>(0.0f, 0));
    static_assert(!is_constexpr<unsafe_v>());
}

TEST(Meta, IsConstexprNonDefault)
{
    // false results for is_constexpr, when the parameter values effect constexpr-ness
    //
    // We pass default constructed arguments,
    // so we are testing if unsafe_inot(0), which IS constexpr,
    // even though unsafe_inot is not generally constexpr
    // see GitHub issue #1
    //
    // I don't think it is possible to test if a function is generally constexpr.
    //
    // It might be possible check if Func is constexpr with provided values.
    // I haven't figured it out yet.

    EXPECT_TRUE( (is_constexpr<safe_if_nonzero>(5)) );
    EXPECT_FALSE( (is_constexpr<safe_if_zero>(5)) );
}
<|endoftext|>


<commit_before>/**
 * \file
 * \brief wasteTime() implementation
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-04
 */

#include "wasteTime.hpp"

namespace distortos
{

namespace test
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void wasteTime(const TickClock::duration duration)
{
	/// \todo implementat something more precise and reliable
	for (TickClock::duration d {}; d <= duration; ++d)
		wasteTime(TickClock::now() + decltype(duration){1});
}

void wasteTime(const TickClock::time_point timePoint)
{
	while (timePoint > TickClock::now());
}

}	// namespace test

}	// namespace distortos
<commit_msg>test: comment fix in wasteTime()<commit_after>/**
 * \file
 * \brief wasteTime() implementation
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2014-11-06
 */

#include "wasteTime.hpp"

namespace distortos
{

namespace test
{

/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/

void wasteTime(const TickClock::duration duration)
{
	/// \todo implement something more precise and reliable
	for (TickClock::duration d {}; d <= duration; ++d)
		wasteTime(TickClock::now() + decltype(duration){1});
}

void wasteTime(const TickClock::time_point timePoint)
{
	while (timePoint > TickClock::now());
}

}	// namespace test

}	// namespace distortos
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include "sslpkix/sslpkix.h"

#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

static void rsa_callback(int p, int n, void *arg) {
	(void)n;
	(void)arg;
	char c;
	switch (p) {
		default: c = 'B'; break;
		case 0: c = '.'; break;
		case 1: c = '+'; break;
		case 2: c = '*'; break;
		case 3: c = '\n'; break;
	}
	fputc(c, stderr);
}

TEST_CASE("certificate/creation/1", "Certificate creation")
{
	//
	// Create issuer
	//

	sslpkix::CertificateName issuer;
	REQUIRE(issuer.create());
	REQUIRE(issuer.set_common_name("janeroe.example.com"));
	REQUIRE(issuer.set_email("jane.roe@example.com"));
	REQUIRE(issuer.set_country("US"));
	REQUIRE(issuer.set_state("CA"));
	REQUIRE(issuer.set_locality("Palo Alto"));
	REQUIRE(issuer.set_organization("Jane Roe's CA Pty."));

	//
	// Create subject
	//

	sslpkix::CertificateName subject;
	REQUIRE(subject.create());
	REQUIRE(subject.set_common_name("johndoe.example.com"));
	REQUIRE(subject.set_email("john.doe@example.com"));
	REQUIRE(subject.set_country("BR"));
	REQUIRE(subject.set_state("RS"));
	REQUIRE(subject.set_locality("Porto Alegre"));
	REQUIRE(subject.set_organization("John Doe's Company Pty."));

	//
	// Add a custom extensions - This is not required.
	//

	int nid;
	const char *oid = "1.2.3.4.5.31";
	const char *short_name = "CTE";
	const char *long_name = "customTextEntry";
	const char *value = "Some value here";
	REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
	REQUIRE(subject.add_entry(short_name, value));
	REQUIRE(subject.entry_value(nid) == value);

	//
	// Generate the key pair
	//

	sslpkix::PrivateKey key;
	REQUIRE(key.create());
	RSA *rsa_key = RSA_generate_key(1024, RSA_F4, rsa_callback, NULL);
	REQUIRE(rsa_key != NULL);
	REQUIRE(key.copy(rsa_key));
	RSA_free(rsa_key);
	rsa_key = NULL;

	sslpkix::FileSink key_file;
	REQUIRE(key_file.open("JohnDoe.key", "wb"));
	REQUIRE(key.save(key_file));
	key_file.close();

	//
	// Create the certificate
	//

	sslpkix::Certificate cert;
	REQUIRE(cert.create());

	// Adjust version
	REQUIRE(cert.set_version(sslpkix::Certificate::Version::v3));

	// Adjust keys
	REQUIRE(cert.set_pubkey(key));

	// Use a hardcoded serial - Never do this in production code!
	REQUIRE(cert.set_serial(31337L));

	// Adjust issuer and subject
	REQUIRE(cert.set_issuer(issuer));
	REQUIRE(cert.set_subject(subject));

	// Valid for 5 days from now
	REQUIRE(cert.set_valid_since(0));
	REQUIRE(cert.set_valid_until(5));

	// Self-sign this certificate
	REQUIRE(cert.sign(key));

	// Save it
	sslpkix::FileSink cert_file;
	REQUIRE(cert_file.open("JohnDoe.crt", "wb"));
	REQUIRE(cert.save(cert_file));
	cert_file.close();
}

TEST_CASE("iosink/operators", "IoSink operators")
{
	sslpkix::FileSink cert_file;
	REQUIRE(cert_file.open("JohnDoe.crt", "rb"));
	std::string cert_string;
	cert_file >> cert_string; // IoSink to std::string
	//std::cout << cert_string << std::endl;
	cert_file.close();
	// TODO(jweyrich): Test whether operator>> was successful. How?

	std::stringstream sstream;

	sslpkix::MemorySink cert_mem;
	REQUIRE(cert_mem.open_rw());
	cert_mem << cert_string; // std::string to IoSink
	sstream << cert_mem; // IoSink to std::stringstream
	cert_mem.close();
	REQUIRE(sstream.str() == cert_string);

	// Reset the stringstream
	sstream.str(std::string());

	sslpkix::MemorySink key_mem;
	REQUIRE(key_mem.open_rw());
	std::filebuf fbuf;
	fbuf.open("JohnDoe.key", std::ios::in);
	std::istream istream(&fbuf);
	istream >> key_mem; // std::istream to IoSink
	std::string key_string;
	key_mem >> key_string; // IoSink to std::string
	//std::cout << key_string << std::endl;

	istream.clear(); // Clear EOF flag (required before C++11)
	istream.seekg(0); // Rewind the std::iostream
	sstream << istream.rdbuf(); // std::istream to std::stringstream
	//std::cout << sstream.str() << std::endl;

	REQUIRE(sstream.str() == key_string);

	fbuf.close();
	key_mem.close();
}

TEST_CASE("certificate_name/entries", "CertificateName entries")
{
	sslpkix::CertificateName name;
	REQUIRE(name.create());
	REQUIRE(name.set_common_name("John Doe"));
	REQUIRE(name.common_name() == "John Doe");
	REQUIRE(name.set_country("BR"));
	REQUIRE(name.country() == "BR");
	REQUIRE(name.set_email("john.doe@example.com"));
	REQUIRE(name.email() == "john.doe@example.com");
	REQUIRE(name.set_locality("Sao Paulo"));
	REQUIRE(name.locality() == "Sao Paulo");
	REQUIRE(name.set_organization("Independent"));
	REQUIRE(name.organization() == "Independent");
	REQUIRE(name.set_state("SP"));
	REQUIRE(name.state() == "SP");
}

TEST_CASE("key/generation/rsa", "RSA key generation")
{
	sslpkix::PrivateKey key;
	REQUIRE(key.create());
	RSA *rsa_key = RSA_generate_key(512, RSA_F4, rsa_callback, NULL);
	REQUIRE(rsa_key != NULL);
	REQUIRE(key.copy(rsa_key));
	RSA_free(rsa_key);
	rsa_key = NULL;
}

TEST_CASE("certificate_name/extensions", "CertificateName extension")
{
	int nid;
	const char *oid = "1.2.3.4.5.31";
	const char *short_name = "CTE";
	const char *long_name = "customTextEntry";
	const char *value = "Some value here";

	REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
	sslpkix::CertificateName name;
	REQUIRE(name.create());
	REQUIRE(name.add_entry(short_name, value));
	int index;
	REQUIRE((index = name.find_entry(nid)) != -1);
	REQUIRE(name.entry(index) != NULL);
	REQUIRE(name.entry_count() == 1);
	REQUIRE(name.entry_value(nid) == value);
}

int main(int argc, char *const argv[])
{
	bool success = sslpkix::startup();
	if (!success) {
		std::cerr << "ERROR: Failed to initialize SSLPKIX." << std::endl;
		exit(EXIT_FAILURE);
	}

	int result = Catch::Session().run(argc, argv);

	sslpkix::shutdown();

	return result;
}
<commit_msg>Replace deprecated RSA_generate_key by RSA_generate_key_ex.<commit_after>#include <cstdlib>
#include <iostream>
#include "sslpkix/sslpkix.h"

#define CATCH_CONFIG_RUNNER
#include "catch.hpp"

static void rsa_callback(int p, int n, void *arg) {
	(void)n;
	(void)arg;
	char c;
	switch (p) {
		default: c = 'B'; break;
		case 0: c = '.'; break;
		case 1: c = '+'; break;
		case 2: c = '*'; break;
		case 3: c = '\n'; break;
	}
	fputc(c, stderr);
}

TEST_CASE("certificate/creation/1", "Certificate creation")
{
	//
	// Create issuer
	//

	sslpkix::CertificateName issuer;
	REQUIRE(issuer.create());
	REQUIRE(issuer.set_common_name("janeroe.example.com"));
	REQUIRE(issuer.set_email("jane.roe@example.com"));
	REQUIRE(issuer.set_country("US"));
	REQUIRE(issuer.set_state("CA"));
	REQUIRE(issuer.set_locality("Palo Alto"));
	REQUIRE(issuer.set_organization("Jane Roe's CA Pty."));

	//
	// Create subject
	//

	sslpkix::CertificateName subject;
	REQUIRE(subject.create());
	REQUIRE(subject.set_common_name("johndoe.example.com"));
	REQUIRE(subject.set_email("john.doe@example.com"));
	REQUIRE(subject.set_country("BR"));
	REQUIRE(subject.set_state("RS"));
	REQUIRE(subject.set_locality("Porto Alegre"));
	REQUIRE(subject.set_organization("John Doe's Company Pty."));

	//
	// Add a custom extensions - This is not required.
	//

	int nid;
	const char *oid = "1.2.3.4.5.31";
	const char *short_name = "CTE";
	const char *long_name = "customTextEntry";
	const char *value = "Some value here";
	REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
	REQUIRE(subject.add_entry(short_name, value));
	REQUIRE(subject.entry_value(nid) == value);

	//
	// Generate the key pair
	//

	sslpkix::PrivateKey key;
	REQUIRE(key.create());
	RSA *rsa_keypair = RSA_new();
	REQUIRE(rsa_keypair != NULL);
	BIGNUM *f4 = BN_new();
	REQUIRE(f4 != NULL);
	REQUIRE(BN_set_word(f4, RSA_F4) != 0);
	REQUIRE(RSA_generate_key_ex(rsa_keypair, 1024, f4, NULL) != 0);
	REQUIRE(key.copy(rsa_keypair));
	BN_free(f4);
	f4 = NULL;
	RSA_free(rsa_keypair);
	rsa_keypair = NULL;

	sslpkix::FileSink key_file;
	REQUIRE(key_file.open("JohnDoe.key", "wb"));
	REQUIRE(key.save(key_file));
	key_file.close();

	//
	// Create the certificate
	//

	sslpkix::Certificate cert;
	REQUIRE(cert.create());

	// Adjust version
	REQUIRE(cert.set_version(sslpkix::Certificate::Version::v3));

	// Adjust keys
	REQUIRE(cert.set_pubkey(key));

	// Use a hardcoded serial - Never do this in production code!
	REQUIRE(cert.set_serial(31337L));

	// Adjust issuer and subject
	REQUIRE(cert.set_issuer(issuer));
	REQUIRE(cert.set_subject(subject));

	// Valid for 5 days from now
	REQUIRE(cert.set_valid_since(0));
	REQUIRE(cert.set_valid_until(5));

	// Self-sign this certificate
	REQUIRE(cert.sign(key));

	// Save it
	sslpkix::FileSink cert_file;
	REQUIRE(cert_file.open("JohnDoe.crt", "wb"));
	REQUIRE(cert.save(cert_file));
	cert_file.close();
}

TEST_CASE("iosink/operators", "IoSink operators")
{
	sslpkix::FileSink cert_file;
	REQUIRE(cert_file.open("JohnDoe.crt", "rb"));
	std::string cert_string;
	cert_file >> cert_string; // IoSink to std::string
	//std::cout << cert_string << std::endl;
	cert_file.close();
	// TODO(jweyrich): Test whether operator>> was successful. How?

	std::stringstream sstream;

	sslpkix::MemorySink cert_mem;
	REQUIRE(cert_mem.open_rw());
	cert_mem << cert_string; // std::string to IoSink
	sstream << cert_mem; // IoSink to std::stringstream
	cert_mem.close();
	REQUIRE(sstream.str() == cert_string);

	// Reset the stringstream
	sstream.str(std::string());

	sslpkix::MemorySink key_mem;
	REQUIRE(key_mem.open_rw());
	std::filebuf fbuf;
	fbuf.open("JohnDoe.key", std::ios::in);
	std::istream istream(&fbuf);
	istream >> key_mem; // std::istream to IoSink
	std::string key_string;
	key_mem >> key_string; // IoSink to std::string
	//std::cout << key_string << std::endl;

	istream.clear(); // Clear EOF flag (required before C++11)
	istream.seekg(0); // Rewind the std::iostream
	sstream << istream.rdbuf(); // std::istream to std::stringstream
	//std::cout << sstream.str() << std::endl;

	REQUIRE(sstream.str() == key_string);

	fbuf.close();
	key_mem.close();
}

TEST_CASE("certificate_name/entries", "CertificateName entries")
{
	sslpkix::CertificateName name;
	REQUIRE(name.create());
	REQUIRE(name.set_common_name("John Doe"));
	REQUIRE(name.common_name() == "John Doe");
	REQUIRE(name.set_country("BR"));
	REQUIRE(name.country() == "BR");
	REQUIRE(name.set_email("john.doe@example.com"));
	REQUIRE(name.email() == "john.doe@example.com");
	REQUIRE(name.set_locality("Sao Paulo"));
	REQUIRE(name.locality() == "Sao Paulo");
	REQUIRE(name.set_organization("Independent"));
	REQUIRE(name.organization() == "Independent");
	REQUIRE(name.set_state("SP"));
	REQUIRE(name.state() == "SP");
}

TEST_CASE("key/generation/rsa", "RSA key generation")
{
	sslpkix::PrivateKey key;
	REQUIRE(key.create());
	RSA *rsa_keypair = RSA_new();
	REQUIRE(rsa_keypair != NULL);
	BIGNUM *f4 = BN_new();
	REQUIRE(f4 != NULL);
	REQUIRE(BN_set_word(f4, RSA_F4) != 0);
	REQUIRE(RSA_generate_key_ex(rsa_keypair, 512, f4, NULL) != 0);
	REQUIRE(key.copy(rsa_keypair));
	BN_free(f4);
	f4 = NULL;
	RSA_free(rsa_keypair);
	rsa_keypair = NULL;
}

TEST_CASE("certificate_name/extensions", "CertificateName extension")
{
	int nid;
	const char *oid = "1.2.3.4.5.31";
	const char *short_name = "CTE";
	const char *long_name = "customTextEntry";
	const char *value = "Some value here";

	REQUIRE(sslpkix::add_custom_object(oid, short_name, long_name, &nid));
	sslpkix::CertificateName name;
	REQUIRE(name.create());
	REQUIRE(name.add_entry(short_name, value));
	int index;
	REQUIRE((index = name.find_entry(nid)) != -1);
	REQUIRE(name.entry(index) != NULL);
	REQUIRE(name.entry_count() == 1);
	REQUIRE(name.entry_value(nid) == value);
}

int main(int argc, char *const argv[])
{
	bool success = sslpkix::startup();
	if (!success) {
		std::cerr << "ERROR: Failed to initialize SSLPKIX." << std::endl;
		exit(EXIT_FAILURE);
	}

	int result = Catch::Session().run(argc, argv);

	sslpkix::shutdown();

	return result;
}
<|endoftext|>