text:
/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/
#include "itkTractsToRgbaImageFilter.h"

// VTK
#include <vtkPolyLine.h>
#include <vtkCellArray.h>
#include <vtkCellData.h>

// misc
#include <math.h>
#include <boost/progress.hpp>

namespace itk{

  template< class OutputImageType >
  TractsToRgbaImageFilter< OutputImageType >::TractsToRgbaImageFilter()
    : m_UpsamplingFactor(1)
    , m_InputImage(NULL)
    , m_UseImageGeometry(false)
  {

  }

  template< class OutputImageType >
  TractsToRgbaImageFilter< OutputImageType >::~TractsToRgbaImageFilter()
  {
  }

  template< class OutputImageType >
  itk::Point<float, 3> TractsToRgbaImageFilter< OutputImageType >::GetItkPoint(double point[3])
  {
    itk::Point<float, 3> itkPoint;
    itkPoint[0] = point[0];
    itkPoint[1] = point[1];
    itkPoint[2] = point[2];
    return itkPoint;
  }

  template< class OutputImageType >
  void TractsToRgbaImageFilter< OutputImageType >::GenerateData()
  {
    if(&typeid(OutPixelType) != &typeid(itk::RGBAPixel<unsigned char>))
      return;

    // generate upsampled image
    mitk::Geometry3D::Pointer geometry = m_FiberBundle->GetGeometry();
    typename OutputImageType::Pointer outImage = this->GetOutput();

    // calculate new image parameters
    itk::Vector<double,3> newSpacing;
    mitk::Point3D newOrigin;
    itk::Matrix<double, 3, 3> newDirection;
    ImageRegion<3> upsampledRegion;
    if (m_UseImageGeometry && !m_InputImage.IsNull())
    {
      newSpacing = m_InputImage->GetSpacing()/m_UpsamplingFactor;
      upsampledRegion = m_InputImage->GetLargestPossibleRegion();
      newOrigin = m_InputImage->GetOrigin();
      typename OutputImageType::RegionType::SizeType size = upsampledRegion.GetSize();
      size[0] *= m_UpsamplingFactor;
      size[1] *= m_UpsamplingFactor;
      size[2] *= m_UpsamplingFactor;
      upsampledRegion.SetSize(size);
      newDirection = m_InputImage->GetDirection();
    }
    else
    {
      newSpacing = geometry->GetSpacing()/m_UpsamplingFactor;
      newOrigin = geometry->GetOrigin();
      mitk::Geometry3D::BoundsArrayType bounds = geometry->GetBounds();
      newOrigin[0] += bounds.GetElement(0);
      newOrigin[1] += bounds.GetElement(2);
      newOrigin[2] += bounds.GetElement(4);

      for (int i=0; i<3; i++)
        for (int j=0; j<3; j++)
          newDirection[j][i] = geometry->GetMatrixColumn(i)[j];
      upsampledRegion.SetSize(0, geometry->GetExtent(0)*m_UpsamplingFactor);
      upsampledRegion.SetSize(1, geometry->GetExtent(1)*m_UpsamplingFactor);
      upsampledRegion.SetSize(2, geometry->GetExtent(2)*m_UpsamplingFactor);
    }
    typename OutputImageType::RegionType::SizeType upsampledSize = upsampledRegion.GetSize();

    // apply new image parameters
    outImage->SetSpacing( newSpacing );
    outImage->SetOrigin( newOrigin );
    outImage->SetDirection( newDirection );
    outImage->SetRegions( upsampledRegion );
    outImage->Allocate();

    int w = upsampledSize[0];
    int h = upsampledSize[1];
    int d = upsampledSize[2];

    // set/initialize output
    unsigned char* outImageBufferPointer = (unsigned char*)outImage->GetBufferPointer();
    float* buffer = new float[w*h*d*4];
    for (int i=0; i<w*h*d*4; i++)
      buffer[i] = 0;

    // resample fiber bundle
    float minSpacing = 1;
    if(newSpacing[0]<newSpacing[1] && newSpacing[0]<newSpacing[2])
        minSpacing = newSpacing[0];
    else if (newSpacing[1] < newSpacing[2])
        minSpacing = newSpacing[1];
    else
        minSpacing = newSpacing[2];

    m_FiberBundle = m_FiberBundle->GetDeepCopy();
    m_FiberBundle->ResampleFibers(minSpacing);

    vtkSmartPointer<vtkPolyData> fiberPolyData = m_FiberBundle->GetFiberPolyData();
    vtkSmartPointer<vtkCellArray> vLines = fiberPolyData->GetLines();
    vLines->InitTraversal();

    int numFibers = m_FiberBundle->GetNumFibers();
    boost::progress_display disp(numFibers);
    for( int i=0; i<numFibers; i++ )
    {
      ++disp;
      vtkIdType   numPoints(0);
      vtkIdType*  points(NULL);
      vLines->GetNextCell ( numPoints, points );

      // calc directions (which are used as weights)
      std::list< itk::Point<float, 3> > rgbweights;
      std::list<float> intensities;

      for( int j=0; j<numPoints-1; j++)
      {

        itk::Point<float, 3> vertex = GetItkPoint(fiberPolyData->GetPoint(points[j]));
        itk::Point<float, 3> vertexPost = GetItkPoint(fiberPolyData->GetPoint(points[j+1]));

        itk::Point<float, 3> dir;
        dir[0] = fabs((vertexPost[0] - vertex[0]) * outImage->GetSpacing()[0]);
        dir[1] = fabs((vertexPost[1] - vertex[1]) * outImage->GetSpacing()[1]);
        dir[2] = fabs((vertexPost[2] - vertex[2]) * outImage->GetSpacing()[2]);

        rgbweights.push_back(dir);

        float intensity = sqrt(dir[0]*dir[0]+dir[1]*dir[1]+dir[2]*dir[2]);
        intensities.push_back(intensity);

        // last point gets same as previous one
        if(j==numPoints-2)
        {
          rgbweights.push_back(dir);
          intensities.push_back(intensity);
        }
      }

      // fill output image
      for( int j=0; j<numPoints; j++)
      {
        itk::Point<float, 3> vertex = GetItkPoint(fiberPolyData->GetPoint(points[j]));
        itk::Index<3> index;
        itk::ContinuousIndex<float, 3> contIndex;
        outImage->TransformPhysicalPointToIndex(vertex, index);
        outImage->TransformPhysicalPointToContinuousIndex(vertex, contIndex);

        float frac_x = contIndex[0] - index[0];
        float frac_y = contIndex[1] - index[1];
        float frac_z = contIndex[2] - index[2];

        int px = index[0];
        if (frac_x<0)
        {
          px -= 1;
          frac_x += 1;
        }

        int py = index[1];
        if (frac_y<0)
        {
          py -= 1;
          frac_y += 1;
        }

        int pz = index[2];
        if (frac_z<0)
        {
          pz -= 1;
          frac_z += 1;
        }

        // int coordinates inside image?
        if (px < 0 || px >= w-1)
          continue;
        if (py < 0 || py >= h-1)
          continue;
        if (pz < 0 || pz >= d-1)
          continue;

        float scale = 100 * pow((float)m_UpsamplingFactor,3);
        itk::Point<float, 3> rgbweight = rgbweights.front();
        rgbweights.pop_front();
        float intweight = intensities.front();
        intensities.pop_front();

        // add to r-channel in output image
        buffer[0+4*( px   + w*(py  + h*pz  ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px   + w*(py+1+ h*pz  ))] += (1-frac_x)*(  frac_y)*(1-frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px   + w*(py  + h*pz+h))] += (1-frac_x)*(1-frac_y)*(  frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px   + w*(py+1+ h*pz+h))] += (1-frac_x)*(  frac_y)*(  frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px+1 + w*(py  + h*pz  ))] += (  frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px+1 + w*(py  + h*pz+h))] += (  frac_x)*(1-frac_y)*(  frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px+1 + w*(py+1+ h*pz  ))] += (  frac_x)*(  frac_y)*(1-frac_z) * rgbweight[0] * scale;
        buffer[0+4*( px+1 + w*(py+1+ h*pz+h))] += (  frac_x)*(  frac_y)*(  frac_z) * rgbweight[0] * scale;

        // add to g-channel in output image
        buffer[1+4*( px   + w*(py  + h*pz  ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px   + w*(py+1+ h*pz  ))] += (1-frac_x)*(  frac_y)*(1-frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px   + w*(py  + h*pz+h))] += (1-frac_x)*(1-frac_y)*(  frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px   + w*(py+1+ h*pz+h))] += (1-frac_x)*(  frac_y)*(  frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px+1 + w*(py  + h*pz  ))] += (  frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px+1 + w*(py  + h*pz+h))] += (  frac_x)*(1-frac_y)*(  frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px+1 + w*(py+1+ h*pz  ))] += (  frac_x)*(  frac_y)*(1-frac_z) * rgbweight[1] * scale;
        buffer[1+4*( px+1 + w*(py+1+ h*pz+h))] += (  frac_x)*(  frac_y)*(  frac_z) * rgbweight[1] * scale;

        // add to b-channel in output image
        buffer[2+4*( px   + w*(py  + h*pz  ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px   + w*(py+1+ h*pz  ))] += (1-frac_x)*(  frac_y)*(1-frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px   + w*(py  + h*pz+h))] += (1-frac_x)*(1-frac_y)*(  frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px   + w*(py+1+ h*pz+h))] += (1-frac_x)*(  frac_y)*(  frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px+1 + w*(py  + h*pz  ))] += (  frac_x)*(1-frac_y)*(1-frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px+1 + w*(py  + h*pz+h))] += (  frac_x)*(1-frac_y)*(  frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px+1 + w*(py+1+ h*pz  ))] += (  frac_x)*(  frac_y)*(1-frac_z) * rgbweight[2] * scale;
        buffer[2+4*( px+1 + w*(py+1+ h*pz+h))] += (  frac_x)*(  frac_y)*(  frac_z) * rgbweight[2] * scale;

        // add to a-channel in output image
        buffer[3+4*( px   + w*(py  + h*pz  ))] += (1-frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale;
        buffer[3+4*( px   + w*(py+1+ h*pz  ))] += (1-frac_x)*(  frac_y)*(1-frac_z) * intweight * scale;
        buffer[3+4*( px   + w*(py  + h*pz+h))] += (1-frac_x)*(1-frac_y)*(  frac_z) * intweight * scale;
        buffer[3+4*( px   + w*(py+1+ h*pz+h))] += (1-frac_x)*(  frac_y)*(  frac_z) * intweight * scale;
        buffer[3+4*( px+1 + w*(py  + h*pz  ))] += (  frac_x)*(1-frac_y)*(1-frac_z) * intweight * scale;
        buffer[3+4*( px+1 + w*(py  + h*pz+h))] += (  frac_x)*(1-frac_y)*(  frac_z) * intweight * scale;
        buffer[3+4*( px+1 + w*(py+1+ h*pz  ))] += (  frac_x)*(  frac_y)*(1-frac_z) * intweight * scale;
        buffer[3+4*( px+1 + w*(py+1+ h*pz+h))] += (  frac_x)*(  frac_y)*(  frac_z) * intweight * scale;
      }
    }
    float maxRgb = 0.000000001;
    float maxInt = 0.000000001;
    int numPix;

    numPix = w*h*d*4;
    // calc maxima
    for(int i=0; i<numPix; i++)
    {
      if((i-3)%4 != 0)
      {
        if(buffer[i] > maxRgb)
          maxRgb = buffer[i];
      }
      else
      {
        if(buffer[i] > maxInt)
          maxInt = buffer[i];
      }
    }

    // write output, normalized uchar 0..255
    for(int i=0; i<numPix; i++)
    {
      if((i-3)%4 != 0)
        outImageBufferPointer[i] = (unsigned char) (255.0 * buffer[i] / maxRgb);
      else
        outImageBufferPointer[i] = (unsigned char) (255.0 * buffer[i] / maxInt);
    }
  }
}

max_stars_repo_name: rfloca/MITK

max_issues_repo_name: rfloca/MITK

max_forks_repo_name: rfloca/MITK


text:
/*
* Copyright 2012-2013 Valentin Milea
*
* 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 "ConfigPrivate.h"
#include <CppAwait/AsioWrappers.h>
#include <CppAwait/impl/StringUtil.h>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>

namespace ut { namespace asio {

using namespace boost::asio;
using namespace boost::asio::ip;

void doAsyncHttpGetHeader(tcp::socket& socket, const std::string& host, const std::string& path, std::shared_ptr<streambuf> outResponse, size_t& outContentLength)
{
    Awaitable awt;

    tcp::resolver resolver(socket.get_io_service());
    tcp::resolver::query query(host, "http");

    // DNS resolve
    tcp::resolver::iterator itEndpoints;
    awt = asyncResolve(resolver, query, itEndpoints);
    awt.await();

    // connect
    tcp::resolver::iterator itConnected;
    awt = asyncConnect(socket, itEndpoints, itConnected);
    awt.await();

    if (!socket.is_open()) {
        throw std::runtime_error("failed to connect socket");
    }

    auto request = std::make_shared<streambuf>();

    // write HTTP request
    std::ostream requestStream(request.get());
    requestStream << "GET " << path << " HTTP/1.0\r\n";
    requestStream << "Host: " << host << "\r\n";
    requestStream << "Accept: */*\r\n";
    requestStream << "Connection: close\r\n\r\n";

    awt = asyncWrite(socket, request);
    awt.await();

    // read first response line
    awt = asyncReadUntil(socket, outResponse, std::string("\r\n"));
    awt.await();

    std::istream responseStream(outResponse.get());
    std::string httpVersion;
    responseStream >> httpVersion;
    int statusCode;
    responseStream >> statusCode;
    std::string statusMessage;
    std::getline(responseStream, statusMessage);

    if (!responseStream || !boost::starts_with(httpVersion, "HTTP/")) {
        throw std::runtime_error("invalid response");
    }
    if (statusCode != 200) {
        throw std::runtime_error(string_printf("bad status code: %d", statusCode));
    }

    // read response headers
    awt = asyncReadUntil(socket, outResponse, std::string("\r\n\r\n"));
    awt.await();

    // process headers
    std::string header;
    outContentLength = (size_t) -1;

    while (std::getline(responseStream, header) && header != "\r") {
        if (boost::starts_with(header, "Content-Length: ")) {
            auto l = header.substr(strlen("Content-Length: "));
            l.resize(l.size() - 1);
            outContentLength = boost::lexical_cast<size_t>(l);
        }
    }
}

Awaitable asyncHttpDownload(boost::asio::io_service& io, const std::string& host, const std::string& path, std::shared_ptr<streambuf> outResponse)
{
    static int id = 0;
    auto tag = string_printf("asyncHttpDownload-%d", id++);

    return startAsync(std::move(tag), [&io, host, path, outResponse]() {
        tcp::socket socket(io);

        size_t contentLength;
        doAsyncHttpGetHeader(socket, host, path, outResponse, contentLength);

        size_t numBytesTransferred;
        Awaitable awt = asyncRead(socket, outResponse, asio::transfer_exactly(contentLength - outResponse->size()), numBytesTransferred);
        awt.await();
    });
}

} }

ext: cpp

max_stars_repo_name: navrocky/CppAwait

max_issues_repo_name: navrocky/CppAwait

max_forks_repo_name: navrocky/CppAwait


text:
/// The MIT License
// (c) 2019 Daniel Williams

#include <fstream>
#include <iostream>
#include <random>
#include <chrono>

#include <sys/stat.h> // may not be standard

using std::cerr;

#include <cxxopts/cxxopts.hpp>

#include <Eigen/Geometry>

#include <nlohmann/json/json.hpp>
using nlohmann::json;

#include "grid/grid.hpp"
#include "quadtree/tree.hpp"
#include "terrain.hpp"
#include "io/readers.hpp"
#include "io/writers.hpp"

using namespace terrain::io;

using terrain::grid::Grid;
using terrain::quadtree::Tree;
using terrain::Terrain;

constexpr double boundary_width = 4096.;
constexpr double desired_precision = 1.0;
// =====
const json source = terrain::generate_diamond(  boundary_width, desired_precision);

constexpr size_t test_seed = 55;
static std::mt19937 generator;

cxxopts::Options command_line_options("TerrainProfile", "Run metrics and speed tests of the terrain library");

void configure_parser_options(cxxopts::Options& opts){
    // define command line options
    opts.add_options()
        // ("d,debug", "Enable debugging")
        ("i,input", "input json path", cxxopts::value<std::string>())
        ("c,count", "Iteration Count", cxxopts::value<size_t>())
        ("tree", "Use the QuadTree backend", cxxopts::value<bool>())
        ("grid", "Use the Grid backend", cxxopts::value<bool>())
        ("o,image", "Output image filen name", cxxopts::value<std::string>())
    ;
}

template <typename T>
void profile_terrain(T& terrain, const size_t iteration_limit){
    const double max = terrain.get_layout().get_x_max();
    const double min = terrain.get_layout().get_x_min();

    generator.seed(test_seed);

    std::cout << ">> Starting testing:\n";
    cell_value_t dump = 0;

    auto start = std::chrono::high_resolution_clock::now();
    size_t iteration = 0;
    for( iteration = 0; iteration < iteration_limit; ++iteration ){
        const double x = static_cast<double>(generator()) / generator.max() * max + min;

        const double y = static_cast<double>(generator()) / generator.max() * max + min;
        //std::cout << "random value: x: " << x << ", " << y << '\n';

        dump = terrain.classify({x,y});
        //std::cout << "             =>: " << static_cast<int>(value) << '\n';
    }
    auto stop = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start).count();

    std::cout.imbue(std::locale(""));
    std::cout << "<< Finished testing:\n";
    std::cout << "   Ran " << iteration << " iterations in " << duration << " \u03BCs \n\n";
}

int main(int argc, char* argv[]){
    std::string filename;
    std::unique_ptr<std::istream> document_stream;
    size_t trial_size = 10;

    configure_parser_options(command_line_options);
    auto result = command_line_options.parse(argc, argv);

    // configure input:
    if( 0 == result.count("input")){
        cerr << "  ## using default input.\n";
        // load default json source data
        filename = "<default>";
        document_stream.reset(new std::istringstream(source.dump()));
    }else if( 0 < result.count("input")){
        filename = result["opt"].as<std::string>();
        cerr << "  ## File input; with:  " << filename << endl;

        struct stat buf;
        if( stat(filename.c_str(), &buf) == -1){
            cerr << "!? could not find file!\n";
            return -1;
        }
        std::ifstream document_stream = std::ifstream(filename);
    }

    if( 0 < result.count("count")){
        trial_size = result["count"].as<size_t>();
        cerr << "    ## Selected Trial Size: " << trial_size << endl;
    }

    bool use_grid = false;
    Terrain<Grid> grid;
    Terrain<Tree> tree;
    if( 0 < result.count("grid")){
        use_grid = true;
        cerr << "  ## Using grid.\n";
    }else if( 0 < result.count("tree")){
        use_grid = false;
        cerr << "  ## Using tree.\n";
    }else{
        use_grid = false;
        cerr << "  ## default to tree.\n";
    }

    bool write_output = false;
    std::string output_path;
    if( 0 < result.count("image")){
        write_output = true;
        output_path = result["image"].as<std::string>();
        if( output_path.empty() ){
            output_path = "terrain.output.png";
        }
        cerr << "  ## Save output to: " << output_path << '\n';
    }

    // ^^^^ Configuration
    // vvvv Execution

    cerr << ">> loading terrain ... \n";
    const auto start_load = std::chrono::high_resolution_clock::now();

    bool load_success;
    if(use_grid){
        load_success = load_from_json_stream(grid, *document_stream);
    }else{
        load_success = load_from_json_stream(tree, *document_stream);
    }
    if(!load_success){
        cerr << "!!!! error while loading into the tree!!!!\n";
        cerr << tree.get_error();
        return -1;
    }
    const auto finish_load = std::chrono::high_resolution_clock::now();
    const auto load_duration = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(finish_load - start_load).count())/1000;
    cerr << "<< Loaded in:   " << load_duration << " s \n";

    if(use_grid){
        // grid.debug();
        cerr << grid.summary();
        profile_terrain(grid, trial_size);
    }else{
        // tree.debug();
        cerr << tree.summary();
        profile_terrain(tree, trial_size);
    }

    if(write_output){
        cerr << "##>> writing output...\n";
        if(use_grid){
            to_png(grid, output_path);
        }else{
            to_png(tree, output_path);
        }
    }

    return 0;
}

max_stars_repo_name: teyrana/quadtree

max_issues_repo_name: teyrana/quadtree

max_forks_repo_name: teyrana/quadtree


text:
//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <memory>
#include <thread>
#include <type_traits>

#include "boost_cfg.hpp"
#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>

#include "cpp_utils/tmp.hpp"

#include "Options.hpp"
#include "PerfsTimer.hpp"
#include "iterators.hpp"
#include "logging.hpp"
#include "timing.hpp"
#include "GlobalContext.hpp"

#include "mtac/pass_traits.hpp"
#include "mtac/Utils.hpp"
#include "mtac/Pass.hpp"
#include "mtac/Optimizer.hpp"
#include "mtac/Program.hpp"
#include "mtac/ControlFlowGraph.hpp"
#include "mtac/Quadruple.hpp"

//The custom optimizations
#include "mtac/conditional_propagation.hpp"
#include "mtac/remove_aliases.hpp"
#include "mtac/clean_variables.hpp"
#include "mtac/remove_unused_functions.hpp"
#include "mtac/remove_empty_functions.hpp"
#include "mtac/DeadCodeElimination.hpp"
#include "mtac/merge_basic_blocks.hpp"
#include "mtac/remove_dead_basic_blocks.hpp"
#include "mtac/BranchOptimizations.hpp"
#include "mtac/inlining.hpp"
#include "mtac/loop_analysis.hpp"
#include "mtac/induction_variable_optimizations.hpp"
#include "mtac/loop_unrolling.hpp"
#include "mtac/loop_unswitching.hpp"
#include "mtac/complete_loop_peeling.hpp"
#include "mtac/remove_empty_loops.hpp"
#include "mtac/loop_invariant_code_motion.hpp"
#include "mtac/parameter_propagation.hpp"
#include "mtac/pure_analysis.hpp"
#include "mtac/local_cse.hpp"

//The optimization visitors
#include "mtac/ArithmeticIdentities.hpp"
#include "mtac/ReduceInStrength.hpp"
#include "mtac/ConstantFolding.hpp"
#include "mtac/MathPropagation.hpp"
#include "mtac/PointerPropagation.hpp"

//The data-flow problems
#include "mtac/GlobalOptimizations.hpp"
#include "mtac/global_cp.hpp"
#include "mtac/global_offset_cp.hpp"
#include "mtac/global_cse.hpp"

#include "ltac/Register.hpp"
#include "ltac/FloatRegister.hpp"
#include "ltac/PseudoRegister.hpp"
#include "ltac/PseudoFloatRegister.hpp"
#include "ltac/Address.hpp"

using namespace eddic;

namespace eddic {
namespace mtac {

typedef boost::mpl::vector<
        mtac::ConstantFolding*
    > basic_passes;

struct all_basic_optimizations {};

template<>
struct pass_traits<all_basic_optimizations> {
    STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB);
    STATIC_STRING(name, "all_basic_optimizations");
    STATIC_CONSTANT(unsigned int, property_flags, 0);
    STATIC_CONSTANT(unsigned int, todo_after_flags, 0);

    typedef basic_passes sub_passes;
};

typedef boost::mpl::vector<
        mtac::ArithmeticIdentities*,
        mtac::ReduceInStrength*,
        mtac::ConstantFolding*,
        mtac::conditional_propagation*,
        mtac::ConstantPropagationProblem*,
        mtac::OffsetConstantPropagationProblem*,
        mtac::local_cse*,
        mtac::global_cse*,
        mtac::PointerPropagation*,
        mtac::MathPropagation*,
        mtac::optimize_branches*,
        mtac::remove_dead_basic_blocks*,
        mtac::merge_basic_blocks*,
        mtac::dead_code_elimination*,
        mtac::remove_aliases*,
        mtac::loop_analysis*,
        mtac::loop_invariant_code_motion*,
        mtac::loop_induction_variables_optimization*,
        mtac::remove_empty_loops*,
        mtac::loop_unrolling*,
        mtac::loop_unswitching*,
        mtac::complete_loop_peeling*, //Must be kept last since it can mess up the loop analysis
        mtac::clean_variables*
    > passes;

struct all_optimizations {};

template<>
struct pass_traits<all_optimizations> {
    STATIC_CONSTANT(pass_type, type, pass_type::IPA_SUB);
    STATIC_STRING(name, "all_optimizations");
    STATIC_CONSTANT(unsigned int, property_flags, 0);
    STATIC_CONSTANT(unsigned int, todo_after_flags, 0);

    typedef passes sub_passes;
};

}
}

namespace {

template<typename T, typename Sign>
struct has_gate {
    typedef char yes[1];
    typedef char no [2];
    template <typename U, U> struct type_check;
    template <typename _1> static yes &chk(type_check<Sign, &_1::gate> *);
    template <typename   > static no  &chk(...);
    static bool const value = sizeof(chk<T>(0)) == sizeof(yes);
};

typedef boost::mpl::vector<
        mtac::remove_unused_functions*,
        mtac::all_basic_optimizations*
    > ipa_basic_passes;

typedef boost::mpl::vector<
        mtac::remove_unused_functions*,
        mtac::pure_analysis*,
        mtac::all_optimizations*,
        mtac::remove_empty_functions*,
        mtac::inline_functions*,
        mtac::remove_unused_functions*,
        mtac::parameter_propagation*
    > ipa_passes;

template<typename Pass>
struct need_pool {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_POOL;
};

template<typename Pass>
struct need_platform {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PLATFORM;
};

template<typename Pass>
struct need_configuration {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_CONFIGURATION;
};

template<typename Pass>
struct need_program {
    static const bool value = mtac::pass_traits<Pass>::property_flags & mtac::PROPERTY_PROGRAM;
};

struct pass_runner {
    bool optimized = false;

    mtac::Program& program;
    mtac::Function* function;

    std::shared_ptr<StringPool> pool;
    std::shared_ptr<Configuration> configuration;
    Platform platform;
    timing_system& system;

    pass_runner(mtac::Program& program, std::shared_ptr<StringPool> pool, std::shared_ptr<Configuration> configuration, Platform platform, timing_system& system) :
            program(program), pool(pool), configuration(configuration), platform(platform), system(system) {};

    template<typename Pass>
    inline void apply_todo(){
        //No todo are implemented
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_pool<Pass>::value, void> set_pool(Pass& pass){
        pass.set_pool(pool);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_pool<Pass>::value, void> set_pool(Pass&){
        //NOP
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_platform<Pass>::value, void> set_platform(Pass& pass){
        pass.set_platform(platform);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_platform<Pass>::value, void> set_platform(Pass&){
        //NOP
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_configuration<Pass>::value, void> set_configuration(Pass& pass){
        pass.set_configuration(configuration);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_configuration<Pass>::value, void> set_configuration(Pass&){
        //NOP
    }

    template<typename Pass>
    inline typename std::enable_if_t<need_program<Pass>::value, Pass> construct(){
        return Pass(program);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!need_program<Pass>::value, Pass> construct(){
        return Pass();
    }

    template<typename Pass>
    Pass make_pass(){
        auto pass = construct<Pass>();

        set_pool(pass);
        set_platform(pass);
        set_configuration(pass);

        return pass;
    }

    template<typename Pass>
    inline typename std::enable_if_t<has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool> has_to_be_run(Pass& pass){
        return pass.gate(configuration);
    }

    template<typename Pass>
    inline typename std::enable_if_t<!has_gate<Pass, bool(Pass::*)(std::shared_ptr<Configuration>)>::value, bool> has_to_be_run(Pass&){
        return true;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, bool>::type apply(Pass& pass){
        return pass(program);
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB, bool>::type apply(Pass&){
        for(auto& function : program.functions){
            this->function = &function;

            if(log::enabled<Debug>()){
                LOG<Debug>("Optimizer") << "Start optimizations on " << function.get_name() << log::endl;

                std::cout << function << std::endl;
            }

            boost::mpl::for_each<typename mtac::pass_traits<Pass>::sub_passes>(boost::ref(*this));
        }

        return false;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::CUSTOM, bool>::type apply(Pass& pass){
        return pass(*function);
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::LOCAL, bool>::type apply(Pass& visitor){
        for(auto& block : *function){
            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }
        }

        return visitor.optimized;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::DATA_FLOW, bool>::type apply(Pass& problem){
        auto results = mtac::data_flow(*function, problem);

        //Once the data-flow problem is fixed, statements can be optimized
        return problem.optimize(*function, results);
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB, bool>::type apply(Pass& visitor){
        bool optimized = false;

        for(auto& block : *function){
            visitor.clear();

            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }

            optimized |= visitor.optimized;
        }

        return optimized;
    }

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::type == mtac::pass_type::BB_TWO_PASS, bool>::type apply(Pass& visitor){
        bool optimized = false;

        for(auto& block : *function){
            visitor.clear();

            visitor.pass = mtac::Pass::DATA_MINING;
            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }

            visitor.pass = mtac::Pass::OPTIMIZE;
            for(auto& quadruple : block->statements){
                visitor(quadruple);
            }

            optimized |= visitor.optimized;
        }

        return optimized;
    }

    template<typename Pass>
    inline typename std::enable_if<cpp::or_u<mtac::pass_traits<Pass>::type == mtac::pass_type::IPA, mtac::pass_traits<Pass>::type == mtac::pass_type::IPA_SUB>::value, void>::type
    debug_local(bool local){
        LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned " << local << log::endl;
    }

    template<typename Pass>
    inline typename std::enable_if<cpp::and_u<mtac::pass_traits<Pass>::type != mtac::pass_type::IPA, mtac::pass_traits<Pass>::type != mtac::pass_type::IPA_SUB>::value, void>::type
    debug_local(bool local){
        if(log::enabled<Debug>()){
            if(local){
                LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned true" << log::endl;

                //Print the function
                std::cout << *function << std::endl;
            } else {
                LOG<Debug>("Optimizer") << mtac::pass_traits<Pass>::name() << " returned false" << log::endl;
            }
        }
    }

    template<typename Pass>
    inline void operator()(Pass*){
        auto pass = make_pass<Pass>();

        if(has_to_be_run(pass)){
            timing_timer timer(system, mtac::pass_traits<Pass>::name());

            bool local = apply<Pass>(pass);
            if(local){
                program.context->stats().inc_counter(std::string(mtac::pass_traits<Pass>::name()) + "_true");
                apply_todo<Pass>();
            }

            debug_local<Pass>(local);

            optimized |= local;
        }
    }
};

} //end of anonymous namespace

void mtac::Optimizer::optimize(mtac::Program& program, std::shared_ptr<StringPool> string_pool, Platform platform, std::shared_ptr<Configuration> configuration) const {
    timing_timer timer(program.context->timing(), "whole_optimizations");

    //Build the CFG of each functions (also needed for register allocation)
    for(auto& function : program.functions){
        timing_timer timer(program.context->timing(), "build_cfg");
        mtac::build_control_flow_graph(function);
    }

    if(configuration->option_defined("fglobal-optimization")){
        //Apply Interprocedural Optimizations
        pass_runner runner(program, string_pool, configuration, platform, program.context->timing());
        do{
            runner.optimized = false;
            boost::mpl::for_each<ipa_passes>(boost::ref(runner));
        } while(runner.optimized);
    } else {
        //Even if global optimizations are disabled, perform basic optimization (only constant folding)
        pass_runner runner(program, string_pool, configuration, platform, program.context->timing());
        boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner));
    }
}

max_stars_repo_name: wichtounet/eddic

max_issues_repo_name: wichtounet/eddic

max_forks_repo_name: wichtounet/eddic


text:
#include "session.h"

#define BOOST_TEST_MODULE TestSession
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(test_session_create) {

}

ext: cc


text:
#include <pubkey.h>
#include <core_io.h>
#include <key_io.h>
#include <logging.h>
#include <contractdb.h>

#include <rpc/rawtransaction_util.h>
#include <rpc/util.h>
#include <rpc/server.h>
#include <script/script.h>
#include <script/script_error.h>
#include <script/standard.h>

#include <crypto/sha1.h>

#include <wallet/coincontrol.h>
#include <wallet/rpcwallet.h>
#include <wallet/wallet.h>
#include <util/translation.h>
#include <univalue.h>
#include <validation.h>
#include <boost/algorithm/string.hpp>

typedef std::vector<unsigned char> valtype;

static RPCHelpMan hashmessage()
{
    return RPCHelpMan{"hashmessage",
                "\nSign a message with the private key of an address\n",
                {
                    {"hashtype", RPCArg::Type::STR, RPCArg::Optional::NO, "The type of hash required. sha256, hash256, hash160, ripemd160, sha1."},
                    {"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to hash."},
                },
                RPCResult{
                    RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64"
                },
                RPCExamples{
            "\nCreate the signature\n"
            + HelpExampleCli("hashmessage", "\"hash type\" \"my message\"") +
            "\nAs a JSON-RPC call\n"
            + HelpExampleRpc("hashmessage", "\"hash type\", \"my message\"")
                },
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::string hashtype = request.params[0].get_str();
    std::string svch = request.params[1].get_str();
    valtype vch(svch.begin(), svch.end());

    valtype vchHash((hashtype == "ripemd160" || hashtype == "sha1" || hashtype == "hash160") ? 20 : 32);
    if (hashtype == "ripemd160")
        CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
    else if (hashtype == "sha1")
        CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
    else if (hashtype == "sha256")
        CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
    else if (hashtype == "hash160")
        CHash160().Write(vch).Finalize(vchHash);
    else if (hashtype =="hash256")
        CHash256().Write(vch).Finalize(vchHash);

    return HexStr(vchHash);
},
    };
}

static RPCHelpMan getcontract()
{
    return RPCHelpMan{"getcontract",
                "\n  Get Details of a contract \n",
                {
                    {"contract", RPCArg::Type::STR, RPCArg::Optional::NO, "The contract to retrieve"},
                },
                RPCResult{
                    RPCResult::Type::STR, "details", "The contract "
                },
                RPCExamples{
            "\nRetrieve a Contract\n"
            + HelpExampleCli("getcontract", "\"Contract Name\"") +
            "\nAs a JSON-RPC call\n"
            + HelpExampleRpc("getcontract", "\"Contract Name\"")
                },
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::string contractstring = request.params[0].get_str();
    CContract contract = GetContract(contractstring);
    UniValue result(UniValue::VOBJ);

    ContractToUniv(&contract,result);

    return result;
},
    };
}

static RPCHelpMan createcontract()
{
    return RPCHelpMan{"createcontract",
                "\n Create a smart contract \n",
                {
                    {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "Issuing address"},
                    {"name", RPCArg::Type::STR, RPCArg::Optional::NO, "Max 10 characters"},
                    {"short_name", RPCArg::Type::STR, RPCArg::Optional::NO, "Max 4 characters"},
					{"contract_url", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "contract location online"},
					{"website_url", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Issuer website online"},
					{"description", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "contract decription"},
					{"scriptcode", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "contract script in hex"},
                },
                RPCResult{
                    RPCResult::Type::STR, "signature", "The signature of the message encoded in base 64"
                },
                RPCExamples{
            "\nCreate the contract\n"
            + HelpExampleCli("createcontract", "\"hash type\" \"my message\"") +
            "\nAs a JSON-RPC call\n"
            + HelpExampleRpc("createcontract", "\"hash type\", \"my message\"")
                },
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();

    std::string address = request.params[0].get_str();
    std::string name = request.params[1].get_str();
    std::string shortname = request.params[2].get_str();
    std::string contract_url = request.params[3].get_str();
    std::string website_url = request.params[4].get_str();
    std::string description = request.params[5].get_str();
    std::string scriptcode = request.params[6].get_str();

    std::vector<unsigned char> scriptcodedata(ParseHex(scriptcode));
    CScript script(scriptcodedata.begin(), scriptcodedata.end());

    CContract contract;
    CTransactionRef tx;
    std::string strFailReason;
    if(!pwallet->CreateContract(contract, tx, address, contract_url, website_url, description, script, name, shortname, strFailReason))
        throw JSONRPCError(RPC_MISC_ERROR, strFailReason);

    CDataStream ssCt(SER_NETWORK, PROTOCOL_VERSION | RPCSerializationFlags());
    ssCt << contract;

    UniValue result(UniValue::VOBJ);

    result.pushKV("txid", tx->GetHash().GetHex());
    result.pushKV("hex", HexStr(ssCt));
    return result;
},
    };
}

static RPCHelpMan createasset()
{
    return RPCHelpMan{"createasset",
                "\ncreate a new asset\n",
                {
                    {"name", RPCArg::Type::STR, RPCArg::Optional::NO, "Max 10 characters"},
                    {"short_name", RPCArg::Type::STR, RPCArg::Optional::NO, "Max 4 characters"},
                    {"input_amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "In put amount in Crown. (minimum 1)"},
                    {"asset_amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "Amount of asset to generate. Note that the amount is Crown-like, with 8 decimal places."},
                    {"expiry", RPCArg::Type::NUM, RPCArg::Optional::NO, "Expiry date of asset"},
                    {"type", RPCArg::Type::NUM, RPCArg::Optional::NO, "asset type TOKEN = 1, UNIQUE = 2, EQUITY = 3, POINTS = 4, CREDITS = 5"},
                    {"transferable", RPCArg::Type::BOOL, RPCArg::Optional::NO, "asset can be transfered to other addresses after initial creation"},
                    {"convertable", RPCArg::Type::BOOL, RPCArg::Optional::NO, "asset can be converted to another asset (set false for NFTs)"},
                    {"restricted", RPCArg::Type::BOOL, RPCArg::Optional::NO, "asset can only be issued/reissued by creation address"},
                    {"limited", RPCArg::Type::BOOL, RPCArg::Optional::NO, "other assets cannot be converted to this one"},
                    {"contract", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "Contract to issue asset to"},
                },
                RPCResult{
                    RPCResult::Type::STR, "assetID", "The id of the asset encoded in hex"
                },
                RPCExamples{
            "\nCreate an asset\n"
            + HelpExampleCli("createasset", "\"hash type\" \"my message\"") +
            "\nAs a JSON-RPC call\n"
            + HelpExampleRpc("createasset", "\"hash type\", \"my message\"")
                },
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
    if (!wallet) return NullUniValue;
    CWallet* const pwallet = wallet.get();

    LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*wallet);

    LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);

    EnsureWalletIsUnlocked(pwallet);

    std::string name = request.params[0].get_str();
    std::string shortname = request.params[1].get_str();
    CAmount nAmount = AmountFromValue(request.params[2].get_int());

    if(nAmount < 10 * COIN)
        throw JSONRPCError(RPC_MISC_ERROR, "Input error, input amount must be greater than 10 Crown for asset creation");

    CAmount nAssetAmount = AmountFromValue(request.params[3].get_int());
    int64_t expiry = request.params[4].get_int();
    int type = request.params[5].get_int();
    bool transferable = request.params[6].get_bool();
    bool convertable = request.params[7].get_bool();
    bool restricted = request.params[8].get_bool();
    bool limited = request.params[9].get_bool();
    std::string contractstring = request.params[10].get_str();

    std::vector<unsigned char> contractData(ParseHex(contractstring));

    CContract contract;

    CDataStream ssCt(contractData, SER_NETWORK, PROTOCOL_VERSION);
    ssCt >> contract;

    CAsset asset;
    CTransactionRef tx;
    std::string strFailReason;

    if(!pwallet->CreateAsset(asset, tx, name, shortname, nAmount, nAssetAmount, expiry, type, contract, strFailReason, transferable, convertable, restricted, limited))
        throw JSONRPCError(RPC_MISC_ERROR, strFailReason);

    return tx->GetHash().GetHex();
},
    };
}

static RPCHelpMan getasset()
{
    return RPCHelpMan{"getasset",
                "\n  Get Details of an asset \n",
                {
                    {"asset", RPCArg::Type::STR, RPCArg::Optional::NO, "The asset to retrieve"},
                },
                RPCResult{
                    RPCResult::Type::STR, "details", "The asset "
                },
                RPCExamples{
            "\nRetrieve a asset\n"
            + HelpExampleCli("getasset", "\"Asset Name\"") +
            "\nAs a JSON-RPC call\n"
            + HelpExampleRpc("getasset", "\"Asset Name\"")
                },
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
{
    std::string assetstring = request.params[0].get_str();
    CAsset asset = GetAsset(assetstring);
    UniValue result(UniValue::VOBJ);

    AssetToUniv(asset,result);

    return result;
},
    };
}

void RegisterContractRPCCommands(CRPCTable &t)
{
// clang-format off
static const CRPCCommand commands[] =
{ //  category              actor (function)
  //  --------------------- ------------------------
    { "contracts",  "hashmessage",         &hashmessage,            {}    },
    { "contracts",  "getcontract",         &getcontract,            {}    },
    { "contracts",  "createcontract",      &createcontract,         {}    },
    { "contracts",  "createasset",         &createasset,            {}    },
    { "contracts",  "getasset",            &getasset,               {}    },

};

// clang-format on
    for (const auto& c : commands) {
        t.appendCommand(c.name, &c);
    }
}

max_stars_repo_name: Crowndev/crown

max_issues_repo_name: Crowndev/crown

max_forks_repo_name: Crowndev/crown


text:
///
/// Copyright (C) 2015, Dependable Systems Laboratory, EPFL
/// Copyright (C) 2015-2016, Cyberhaven
/// Copyright (C) 2020, TrussLab@University of California, Irvine.
///	Authors: Yingtong Liu <yingtong@uci.edu>
/// All rights reserved.
///
/// Licensed under the Cyberhaven Research License Agreement.
///

#include <s2e/cpu.h>

#include <boost/regex.hpp>
#include <s2e/ConfigFile.h>
#include <s2e/Plugins/OSMonitors/Linux/DecreeMonitor.h>
#include <s2e/S2E.h>
#include <s2e/S2EExecutor.h>
#include <s2e/Utils.h>

#include "PathSearcher.h"

namespace s2e {
namespace plugins {

S2E_DEFINE_PLUGIN(PathSearcher, "Choose fork branches that lead to desired state", "PathSearcher", //
                  "DecreeMonitor");

PathSearcher::PathSearcher(S2E *s2e) : Plugin(s2e) {
    m_chosenState = NULL;
    m_vulnPc = 0;
}

void PathSearcher::initialize() {
    s2e()->getExecutor()->setSearcher(this);

    CorePlugin *core = s2e()->getCorePlugin();
    core->onStateFork.connect_front(sigc::mem_fun(*this, &PathSearcher::onFork));
    core->onTranslateInstructionStart.connect(sigc::mem_fun(*this, &PathSearcher::onTranslateInstruction));
    s2e()->getPlugin<DecreeMonitor>()->onSegFault.connect(sigc::mem_fun(*this, &PathSearcher::onSegFault));

    ConfigFile *config = s2e()->getConfig();

    m_vulnPc = config->getInt(getConfigKey() + ".vulnPc", 0);

    const uint64_t originalDesiredStateId = config->getInt(getConfigKey() + ".stateId", 0);
    if (!originalDesiredStateId) {
        getWarningsStream() << "please specify stateId\n";
        exit(-1);
    }

    const ConfigFile::string_list logFiles = config->getStringList(getConfigKey() + ".logFiles");
    if (!logFiles.size()) {
        getWarningsStream() << "please specify logFiles\n";
        exit(-1);
    }

    const std::string executionTrace = config->getString(getConfigKey() + ".executionTrace", "");

    typedef struct {
        uint64_t pc;
        uint64_t parentStateId;
        uint64_t childStateId[2];
    } forkInfo;

#define FORKED_STATE_ID(fi) \
    ((fi)->parentStateId == (fi)->childStateId[0] ? (fi)->childStateId[1] : (fi)->childStateId[0])

    std::vector<forkInfo> forkData;

    foreach2 (it, logFiles.begin(), logFiles.end()) {
        std::ifstream file(it->c_str(), std::ios::in);
        if (!file.is_open()) {
            getWarningsStream() << "failed to open file \"" + *it + "\"\n";
            exit(-1);
        }

        const boost::regex forkRegex(".* Forking state ([[:digit:]]+) at pc = 0x([[:xdigit:]]+) .*");
        const boost::regex stateRegex("    state ([[:digit:]]+)");

        std::string line;
        while (std::getline(file, line)) {
            boost::smatch match;
            if (boost::regex_match(line, match, forkRegex)) {
                char *p;
                forkInfo fi;

                assert(match.size() == 3);
                fi.parentStateId = strtoull(((std::string) match[1]).c_str(), &p, 10);
                assert(*p == '\0');
                fi.pc = strtoull(((std::string) match[2]).c_str(), &p, 16);
                assert(*p == '\0');

                for (int i = 0; i < 2; i++) {
                    if (!std::getline(file, line) || !boost::regex_match(line, match, stateRegex)) {
                        getWarningsStream() << "no next line for forked state " << fi.parentStateId << "\n";
                        exit(-1);
                    }
                    assert(match.size() == 2);
                    fi.childStateId[i] = strtoull(((std::string) match[1]).c_str(), &p, 10);
                    assert(*p == '\0');
                }

                assert(fi.parentStateId == fi.childStateId[0] || fi.parentStateId == fi.childStateId[1]);

                forkData.push_back(fi);
            }
        }
    }
    assert(forkData.size());

    getWarningsStream() << "read " << forkData.size() << " fork points\n";

    std::vector<std::vector<forkInfo>::const_iterator> forkPoints;

    uint64_t desiredStateId = originalDesiredStateId;
    uint64_t prevStateId = UINT64_MAX;
    while (true) {
        uint64_t parentStateId;
        bool hasParentState = false;
        std::vector<std::vector<forkInfo>::const_iterator> tmpForkPoints;

        // Remember all points where desiredState has forked
        foreach2 (it, forkData.begin(), forkData.end()) {
            if (it->parentStateId == desiredStateId) {
                if (tmpForkPoints.size()) {
                    std::vector<forkInfo>::const_iterator prevIt = *(tmpForkPoints.end() - 1);
                    if (FORKED_STATE_ID(prevIt) >= FORKED_STATE_ID(it)) {
                        getWarningsStream() << "TODO: sort fork points by childId\n";
                        getWarningsStream() << "      " << prevIt->parentStateId << " (" << prevIt->childStateId[0]
                                            << ", " << prevIt->childStateId[1] << ")\n";
                        getWarningsStream() << "      " << it->parentStateId << " (" << it->childStateId[0] << ", "
                                            << it->childStateId[1] << ")\n";
                        exit(-1);
                    }
                }
                tmpForkPoints.push_back(it);
            } else if (it->childStateId[0] == desiredStateId || it->childStateId[1] == desiredStateId) {
                assert(!hasParentState);
                parentStateId = it->parentStateId;
                hasParentState = true;
            }
        }

        // Copy points until desiredState has forked into prevState
        foreach2 (it, tmpForkPoints.rbegin(), tmpForkPoints.rend()) {
            if ((*it)->childStateId[0] <= prevStateId && (*it)->childStateId[1] <= prevStateId) {
                forkPoints.push_back(*it);
            }
        }

        if (desiredStateId == 0) {
            break;
        }

        assert(hasParentState);
        prevStateId = desiredStateId;
        desiredStateId = parentStateId;
    }
    assert(forkPoints.size());

    getWarningsStream() << "path that leads to state " << originalDesiredStateId << ":\n";
    foreach2 (it, forkPoints.rbegin(), forkPoints.rend()) {
        const forkInfo &fi = **it;
        getWarningsStream() << "    fork state " << fi.parentStateId << " at " << hexval(fi.pc) << ": "
                            << fi.childStateId[0] << " " << fi.childStateId[1] << "\n";
    }

    foreach2 (it, forkPoints.rbegin(), forkPoints.rend()) {
        const forkInfo &fi = **it;
        uint64_t nextStateId;
        forkDirector fd;

        fd.pc = fi.pc;

        if (it != forkPoints.rend() - 1) {
            const forkInfo &nextFi = **(it + 1);
            nextStateId = nextFi.parentStateId;
        } else {
            nextStateId = originalDesiredStateId;
        }

        if (nextStateId == fi.childStateId[0]) {
            fd.id = 0;
        } else if (nextStateId == fi.childStateId[1]) {
            fd.id = 1;
        } else {
            getWarningsStream() << "invalid fork\n";
            exit(-1);
        }

        m_forkDirectors.push_back(fd);
    }

    getWarningsStream() << "branches to be chosen:\n";
    foreach2 (it, m_forkDirectors.begin(), m_forkDirectors.end()) {
        const forkDirector &fd = *it;
        getWarningsStream() << "    #" << it - m_forkDirectors.begin() << " at " << hexval(fd.pc) << ": " << fd.id
                            << "\n";
    }

    if (executionTrace.length()) {
        std::ifstream file(executionTrace.c_str(), std::ios::in);
        if (!file.is_open()) {
            getWarningsStream() << "failed to open file \"" + executionTrace + "\"\n";
            exit(-1);
        }

        const boost::regex forkRegex("Forked at 0x([[:xdigit:]]+) .*");
        unsigned forkN = 0;

        std::string line;
        while (std::getline(file, line)) {
            boost::smatch match;
            if (boost::regex_match(line, match, forkRegex)) {
                char *p;
                assert(match.size() == 2);
                uint64_t forkPc = strtoull(((std::string) match[1]).c_str(), &p, 16);
                assert(*p == '\0');

                assert(forkN < m_forkDirectors.size());
                if (m_forkDirectors[forkN].pc != forkPc) {
                    getWarningsStream() << "fork PC mismatch with execution trace\n";
                    exit(-1);
                }

                forkN++;
            }
        }

        if (forkN != m_forkDirectors.size()) {
            getWarningsStream() << "fork count mismatch with execution trace\n";
            exit(-1);
        }

        getWarningsStream() << "execution trace matched\n";
    }
}

/*
 *
 */

void PathSearcher::onTranslateInstruction(ExecutionSignal *signal, S2EExecutionState *state, TranslationBlock *tb,
                                          uint64_t pc) {
    if (m_vulnPc && pc == m_vulnPc) {
        signal->connect(sigc::mem_fun(*this, &PathSearcher::onInstructionExecution));
    }
}

void PathSearcher::onInstructionExecution(S2EExecutionState *state, uint64_t pc) {
	assert(false && "PathSearcher::onInstructionExecution failed\n");
}

void PathSearcher::onSegFault(S2EExecutionState *state, uint64_t pid, uint64_t pc) {
    getWarningsStream(state) << "SEGFAULT reached\n";
    exit(0);
}

void PathSearcher::onFork(S2EExecutionState *state, const std::vector<S2EExecutionState *> &newStates,
                          const std::vector<klee::ref<klee::Expr>> &newConditions) {
    assert(newStates.size() == 2);

    DECLARE_PLUGINSTATE(PathSearcherState, state);
    unsigned forkCount = plgState->getForkCount();

    getWarningsStream(state) << "fork #" << forkCount << " out of #" << m_forkDirectors.size() << "\n";

    assert(forkCount < m_forkDirectors.size());
    const forkDirector &fd = m_forkDirectors[forkCount];

    if (fd.pc != state->regs()->getPc()) {
        getWarningsStream(state) << "fork PC mismatch: " << hexval(fd.pc) << " != " << hexval(state->regs()->getPc())
                                 << "\n";
        exit(-1);
    }

    assert(fd.id == 0 || fd.id == 1);
    m_chosenState = newStates[fd.id];

    for (int i = 0; i < 2; i++) {
        DECLARE_PLUGINSTATE(PathSearcherState, newStates[i]);
        plgState->increaseForkCount();
    }

    s2e()->getExecutor()->yieldState(*state);
}

void PathSearcher::update(klee::ExecutionState *current, const klee::StateSet &addedStates,
                          const klee::StateSet &removedStates) {
    StateSet states;

    foreach2 (it, addedStates.begin(), addedStates.end()) {
        S2EExecutionState *state = static_cast<S2EExecutionState *>(*it);
        states.insert(state);
    }

    foreach2 (it, removedStates.begin(), removedStates.end()) {
        S2EExecutionState *state = static_cast<S2EExecutionState *>(*it);
        states.erase(state);
        m_states.erase(state);
    }

    foreach2 (it, states.begin(), states.end()) { m_states.insert(*it); }
}

klee::ExecutionState &PathSearcher::selectState() {
    if (m_states.size() == 1) {
        return **m_states.begin();
    }

    assert(m_states.find(m_chosenState) != m_states.end());
    return *m_chosenState;
}

bool PathSearcher::empty() {
    return m_states.empty();
}

/*
 *
 */

PathSearcherState::PathSearcherState() {
    m_forkCount = 0;
}

PathSearcherState::~PathSearcherState() {
}

PathSearcherState *PathSearcherState::clone() const {
    return new PathSearcherState(*this);
}

PluginState *PathSearcherState::factory(Plugin *p, S2EExecutionState *s) {
    return new PathSearcherState();
}

void PathSearcherState::increaseForkCount() {
    m_forkCount++;
}

unsigned PathSearcherState::getForkCount() const {
    return m_forkCount;
}

} // namespace plugins
} // namespace s2e

max_stars_repo_name: trusslab/mousse

max_issues_repo_name: trusslab/mousse

max_forks_repo_name: trusslab/mousse


text:
#include <utility>
#include <iostream>
#ifdef __MINGW32__
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif

int main()
{
    std::cout << fs::current_path() << '\n';
}

max_stars_repo_name: rubenvb/ci-playground

max_issues_repo_name: rubenvb/ci-playground

max_forks_repo_name: rubenvb/ci-playground


text:
/* Copyright 2020-present University of Pennsylvania
 *
 * 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 <unordered_map>
#include <vector>
#include <regex>
#include <boost/format.hpp>
#include <fstream>

#include "../../include/compile.h"
#include "../../include/find_nodes.h"
#include "../../include/helper.h"

#include "compile_const.h"
#include "compile_p4.h"
#include "compile_c.h"

static int ing_iso_opt = -1;
static int egr_iso_opt = -1;
static int num_init_mbls_ing = -1;
static int num_init_mbls_egr = -1;
static vector<ReactionArgBin> global_ing_bins;
static vector<ReactionArgBin> global_egr_bins;
static unordered_map<string, int> mblUsages;
static unordered_map<string, P4RMalleableValueNode*> mblValues;
static unordered_map<string, P4RMalleableFieldNode*> mblFields;
static unordered_map<string, P4RMalleableTableNode*> mblTables;
static unordered_map<string, vector<string>> tableMbls;
static unordered_map<string, vector<string>> actionMbls;

vector<AstNode*> compileP4Code(vector<AstNode*>* nodeArray) {

    ing_iso_opt = inferIsoOptForIng(nodeArray, true);
    egr_iso_opt = inferIsoOptForIng(nodeArray, false);

    transformPragma(nodeArray);

    findAndRemoveMalleables(&mblValues, &mblFields, &mblTables, *nodeArray);

    vector<MblRefNode*> mblRefs;
    findMalleableRefs(&mblRefs, *nodeArray);

    // Visitor pass to find the corresponding usage
    findMalleableUsage(mblRefs, mblValues, mblFields, nodeArray, &mblUsages);

    // Transform all references to mbls into references to the appropriate metadata
    transformMalleableRefs(&mblRefs, mblValues, mblFields, nodeArray);

    transformMalleableTables(&mblTables, *nodeArray, ing_iso_opt, egr_iso_opt);

    auto newNodes = vector<AstNode*>();

    generateMetadata(&newNodes, mblValues, mblFields, ing_iso_opt, egr_iso_opt);
    num_init_mbls_ing = generateInitTableForIng(&mblUsages, &newNodes, mblValues, mblFields, ing_iso_opt, true);
    num_init_mbls_egr = generateInitTableForIng(&mblUsages, &newNodes, mblValues, mblFields, egr_iso_opt, false);

    generateSetvarControl(&newNodes);

    // Measurement code
    HeaderDecsMap headerDecsMap = findHeaderDecs(*nodeArray);
    vector<ReactionArgNode*> reaction_args = findReactionArgs(*nodeArray);

    global_ing_bins = generateIngDigestPacking(&newNodes, reaction_args, headerDecsMap,
                    mblValues, mblFields, *nodeArray, &ing_iso_opt);
    global_egr_bins = generateEgrDigestPacking(&newNodes, reaction_args, headerDecsMap,
                    mblValues, mblFields, *nodeArray, &egr_iso_opt);

    // After packing, iso_opt is firm
    augmentRegisterArgProgForIng(&newNodes, nodeArray, reaction_args, ing_iso_opt, true);
    augmentRegisterArgProgForIng(&newNodes, nodeArray, reaction_args, egr_iso_opt, false);

    generateDupRegArgProg(&newNodes, nodeArray, reaction_args, ing_iso_opt, egr_iso_opt);

    generateRegArgGateControl(&newNodes, nodeArray, reaction_args, ing_iso_opt, egr_iso_opt);

    generateExportControl(&newNodes, global_ing_bins, global_egr_bins);

    // Finally, assemble ingress/egress
    augmentIngress(nodeArray);
    augmentEgress(nodeArray);

    return newNodes;
}

vector<UnanchoredNode *> compileCCode(std::vector<AstNode*> nodeArray, char * outFnBase) {
	vector<UnanchoredNode *> ret_vec = vector<UnanchoredNode *>();

    string out_fn_base_str = string(outFnBase);
    string base_fn = out_fn_base_str.substr(out_fn_base_str.find_last_of("/\\") + 1);
    PRINT_VERBOSE("Output filename base: %s\n", base_fn.c_str());
    string prefix_str = "p4_pd_" + string(base_fn) + "_mantis_";

    ostringstream oss_preprocessor;
    ostringstream oss_mbl_init;
    ostringstream oss_init_end;
    ostringstream oss_reaction_mirror;
    ostringstream oss_reaction_update;

    extractReactionMacro(nodeArray, oss_preprocessor, string(outFnBase));

    generateMacroNonMblTable(nodeArray, oss_preprocessor, prefix_str);

    generatePrologueEnd(nodeArray, oss_init_end, ing_iso_opt, egr_iso_opt);

    generateHdlPool(nodeArray, oss_mbl_init, ing_iso_opt, egr_iso_opt);

    generateMacroInitMblsForIng(nodeArray, &mblUsages, oss_mbl_init, oss_reaction_mirror, oss_preprocessor, num_init_mbls_ing, ing_iso_opt, prefix_str, true);
    generateMacroInitMblsForIng(nodeArray, &mblUsages, oss_mbl_init, oss_reaction_mirror, oss_preprocessor, num_init_mbls_egr, egr_iso_opt, prefix_str, false);

    generateMacroXorVersionBits(oss_reaction_mirror, oss_preprocessor, ing_iso_opt, egr_iso_opt);

    generateDialogueArgStart(oss_reaction_mirror, ing_iso_opt, egr_iso_opt);

    mirrorFieldArg(nodeArray, oss_reaction_mirror, oss_preprocessor, global_ing_bins, prefix_str, true);
    mirrorFieldArg(nodeArray, oss_reaction_mirror, oss_preprocessor, global_egr_bins, prefix_str, false);

    mirrorRegisterArgForIng(nodeArray, oss_reaction_mirror, ing_iso_opt, prefix_str, true);
    mirrorRegisterArgForIng(nodeArray, oss_reaction_mirror, egr_iso_opt, prefix_str, false);

    generateMacroMblTable(nodeArray, oss_preprocessor, prefix_str, ing_iso_opt, egr_iso_opt, oss_reaction_mirror);

    generateDialogueEnd(nodeArray, oss_reaction_update, ing_iso_opt, egr_iso_opt);

    ret_vec.push_back(generateMacroNode(oss_preprocessor));
    ret_vec.push_back(generatePrologueNode(nodeArray, oss_mbl_init, oss_init_end));
    ret_vec.push_back(generateDialogueNode(nodeArray, oss_reaction_mirror, oss_reaction_update));

	return ret_vec;
}

max_stars_repo_name: eniac/Mantis

max_issues_repo_name: eniac/Mantis

max_forks_repo_name: eniac/Mantis


text:
#ifndef _MODEL_ADJACENCY_HPP
#define _MODEL_ADJACENCY_HPP

#include <common.hpp>
#include <boost/multi_array.hpp>

namespace model {
	/**
	 * \brief An adjacency matrix with various helper functions.
	 */
	template <typename T> struct adjacency {
	 public:
		/**
		 * \brief Constructor takes an initial size of the square matrix.
		 */
		adjacency<T>(const std::size_t size)
				: _matrix(boost::extents[size][size]) {
		}

		/**
		 * \brief Copy constructor disabled.
		 */
		adjacency<T>(const adjacency<T>&) = delete;

		/**
		 * \brief Move constructor.
		 */
		adjacency<T>(adjacency<T>&& old)
				: _matrix(std::move(old._matrix)) {
		}

		/**
		 * \brief Copy Assignment operator disabled.
		 */
		adjacency<T>& operator=(const adjacency<T>&) = delete;

		/**
		 * \brief Move assignment operator.
		 */
		adjacency<T>& operator=(adjacency<T>& old) {
			_matrix = old._matrix;
		}

		/**
		 * \brief Virtual Destructor.
		 */
		virtual ~adjacency<T>() {
		}

		/**
		 * \brief Add an item at position (i,j). If an element is already at this position,
		 * overwrite it.
		 *
		 * The template parameter allowNull is a way to force us to think about what the
		 * effect allowing a null item pointer will have.
		 */
		template <bool allowNull>
				void add(const std::size_t i, const std::size_t j, T* const item) {
			#ifdef THROW
			if(UNLIKELY(i >= _matrix.size() || j >= _matrix.size())) {
				throw std::out_of_range(err_msg::_arybnds);
			}
			if(!allowNull && UNLIKELY(item == 0)) {
				throw std::invalid_argument(err_msg::_nllpntr);
			}
			#endif

			_matrix[i][j] = item;
		}

		/**
		 * \brief Remove an item at the position (i,j). If there is no item at this
		 * position, then this has no effect.
		 */
		void remove(const std::size_t i, const std::size_t j) {
			#ifdef THROW
			if(UNLIKELY(i >= _matrix.size() || j >= _matrix.size())) {
				throw std::out_of_range(err_msg::_arybnds);
			}
			#endif

			_matrix[i][j] = 0;
		}

		/**
		 * \brief Determine if there is an item at the position (i,j).
		 */
		inline bool is_empty(const std::size_t i, const std::size_t j) const {
			#ifdef THROW
			if(UNLIKELY(i >= _matrix.size() || j >= _matrix.size())) {
				throw std::out_of_range(err_msg::_arybnds);
			}
			#endif

			return (_matrix[i][j] == 0);
		}

		/**
		 * \brief Return a pointer to the element positioned at (i,j) within the matrix. If
		 * there is no item present, the pointer is equal to 0.
		 *
		 * \returns The pointer to the element at position (i,j).
		 */
		inline T* pget(const std::size_t i, const std::size_t j) const {
			#ifdef THROW
			if(UNLIKELY(i >= _matrix.size() || j >= _matrix.size())) {
				throw std::out_of_range(err_msg::_arybnds);
			}
			#endif

			return _matrix[i][j];
		}

		/**
		 * \brief Return a mutable reference to the item positioned at (i,j) within the
		 * matrix.
		 *
		 * \throws std::runtime_error if the element at the position is null.
		 */
		inline T& rget(const std::size_t i, const std::size_t j) {
			#ifdef THROW
			if(UNLIKELY(i >= _matrix.size() || j >= _matrix.size())) {
				throw std::out_of_range(err_msg::_arybnds);
			}
			#endif

			if(UNLIKELY(_matrix[i][j] == 0)) {
				throw std::runtime_error(err_msg::_arybnds);
			}

			return *_matrix[i][j];
		}

		/**
		 * \brief Resize the square matrix to a new size.
		 *
		 * If the new size is smaller than the current size, pointers outside the new size
		 * of the matrix are deleted. Their memory is not deallocated from this function.
		 * If the new size is bigger than the current size, the new positions are
		 * initialized to 0.
		 */
		void resize(const std::size_t size) {
			_matrix.resize(boost::extents[size][size]);
		}

		/**
		 * \brief Return the size of the square matrix.
		 */
		inline std::size_t size() const {
			return _matrix.size();
		}

		/**
		 * \brief Return a pointer to the next neighbor of an item.
		 *
		 * Since an item's connectivity is within a row, this retrieves the first non-null
		 * element in the row with a given offset. For example, if the offset is 0, this
		 * retrieves the first non-null element in the row. However, if the offset is 1,
		 * this retrieves the second non-null element in the row. If there is only one
		 * non-null element in the row, this retrieves the first non-null element in the
		 * row. If the offset is greater than the number of non-null elements in the row,
		 * this retrieves the last non-null element in the row. If there are no non-null
		 * elements in the row, then 0 is returned.
		 */
		T* next_neighbor(const std::size_t i, std::size_t offset = 0) const {
			#ifdef THROW
			if(UNLIKELY(i >= _matrix.size())) {
				throw std::out_of_range(err_msg::_arybnds);
			}
			#endif

			T* lastElement = 0;

			for(std::size_t j = 0; j < _matrix.size(); j++) {
				if(_matrix[i][j] != 0) {
					if(offset == 0) {
						lastElement = _matrix[i][j];
						break;
					} else {
						lastElement = _matrix[i][j];
						offset--;
					}
				}
			}

			return lastElement;
		}

	 private:
		/**
		 * \brief A square matrix.
		 */
		boost::multi_array<T*, 2> _matrix;
	};
}

#endif

ext: hpp

max_stars_repo_name: ORNL-QCI/eldispacho

max_issues_repo_name: ORNL-QCI/eldispacho

max_forks_repo_name: ORNL-QCI/eldispacho


text:
#ifndef BOOST_ARCHIVE_ARRAY_OARCHIVE_HPP
#define BOOST_ARCHIVE_ARRAY_OARCHIVE_HPP

// (C) Copyright 2005 Matthias Troyer and Dave Abrahams
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/archive/basic_archive.hpp>
#include <boost/archive/detail/common_oarchive.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/detail/get_data.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/pfto.hpp>

namespace boost { namespace archive { namespace array {

  // To conveniently array-optimize an output archive X:
  //
  //   * Derive it from oarchive<X, Impl>, where Impl is an
  //     archive implementation base class from
  //     Boost.Serialization
  //
  //   * add a member function template that implements the
  //     procedure for serializing arrays of T (for appropriate T)
  //
  //       template <class T>
  //       save_array(serialization::array<T> const &, unsigned int)
  //
  //   * add a unary MPL lambda expression member called
  //     use_array_optimization whose result is convertible to
  //     mpl::true_ iff array elements of type T can be serialized
  //     with the load_array member function, and to mpl::false_ if
  //     the unoptimized procedure must be used.

template <class Archive>
class oarchive
 : public archive::detail::common_oarchive<Archive>
{
  typedef archive::detail::common_oarchive<Archive> Base;
public:

  oarchive(unsigned int flags)
   : archive::detail::common_oarchive<Archive>(flags)
  {}

  // save_override for std::vector and serialization::array dispatches to
  // save_optimized with an additional argument.
  //
  // If that argument is of type mpl::true_, an optimized serialization is provided
  // If it is false, we just forward to the default serialization in the base class

  //the default version dispatches to the base class
  template<class T>
  void save_optimized(T const &t, unsigned int version, mpl::false_)
  {
    Base::save_override(t, version);
  }

  // the optimized implementation for vector uses serialization::array
//  template<class ValueType, class Allocator>
//  void save_optimized(
//    const std::vector<ValueType, Allocator> &t, unsigned int, mpl::true_)
//  {
//    const serialization::collection_size_type count(t.size());
//    * this->This() << BOOST_SERIALIZATION_NVP(count);
//    if (!t.empty())
//      * this->This() << serialization::make_array(serialization::detail::get_data(t),t.size());
//  }

  // the optimized implementation for serialization::array uses save_array
  template<class ValueType>
  void save_optimized(
    const serialization::array<ValueType> &t, unsigned int version, mpl::true_)
  {
    this->This()->save_array(t,version);
  }

  // to save a vector:
  // if the value type is trivially constructable or an optimized array save exists,
  // then we can use the optimized version

//  template<class ValueType, class Allocator>
//  void save_override(std::vector<ValueType,Allocator> const &x, unsigned int version)
//  {
//    typedef BOOST_DEDUCED_TYPENAME remove_const<ValueType>::type value_type;
//    typedef typename mpl::and_<
//      mpl::not_<is_same<value_type,bool> >,
//      mpl::apply1<
//        BOOST_DEDUCED_TYPENAME Archive::use_array_optimization
//      , value_type>
//    >::type use_optimized;
//    save_optimized(x,version,use_optimized() );
//  }

  // dispatch saving of arrays to the optimized version where supported
  template<class ValueType>
  void save_override(serialization::array<ValueType> const& x, unsigned int version)
  {
    typedef typename mpl::apply1<
        BOOST_DEDUCED_TYPENAME Archive::use_array_optimization
      , BOOST_DEDUCED_TYPENAME remove_const<ValueType>::type
    >::type use_optimized;
    save_optimized(x,version,use_optimized());
  }

  // Load everything else in the usual way, forwarding on to the
  // Base class
  template<class T>
  void save_override(T const& x, unsigned BOOST_PFTO int version)
  {
    Base::save_override(x, static_cast<unsigned int>(version));
  }
};

} } } // end namespace boost::archive::array

#endif // BOOST_ARCHIVE_ARRAY_OARCHIVE_HPP


text:
/* Copyright © 2017 Apple Inc. All rights reserved.
 *
 * Use of this source code is governed by a BSD-3-clause license that can
 * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
 */
#ifndef FAULT_QUERY_OBJECT_SERVER_PROCESS_HPP
#define FAULT_QUERY_OBJECT_SERVER_PROCESS_HPP
#include <string>
#include <boost/function.hpp>
#include <fault/query_object.hpp>
#include <fault/query_object_create_flags.hpp>
namespace libfault {
typedef boost::function<query_object*(std::string objectkey,
                                      std::vector<std::string> zk_hosts,
                                      std::string zk_prefix,
                                      uint64_t create_flags)>  query_object_factory_type;

int query_main(int argc, char** argv, const query_object_factory_type& factory);

} // namespace;
#endif


text:
#ifndef __SETUP_HPP__
#define __SETUP_HPP__

#include "text/exception/SyntaxError.hpp"
#include "text/expression/ExpressionParser.hpp"
#include "text/parsing/CommandParser.hpp"

#include <string>
#include <tuple>
#include <unordered_map>
#include <vector>

#include <mpfr.h>
#include <mpreal.h>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

using DefaultArithmeticType = mpfr::mpreal;
using DefaultValueType =
    Text::Expression::ValueToken<std::nullptr_t, DefaultArithmeticType, std::string, boost::posix_time::ptime, boost::posix_time::time_duration>;
using DefaultVariableType =
    Text::Expression::VariableToken<std::nullptr_t, DefaultArithmeticType, std::string, boost::posix_time::ptime, boost::posix_time::time_duration>;

using ChemArithmeticType = mpfr::mpreal;
using ChemValueType      = Text::Expression::ValueToken<ChemArithmeticType>;
using ChemVariableType   = Text::Expression::VariableToken<ChemArithmeticType>;

using Text::Expression::IValueToken;
using Text::Expression::IVariableToken;
using Text::Expression::IUnaryOperatorToken;
using Text::Expression::IBinaryOperatorToken;
using Text::Expression::IFunctionToken;
using Text::Expression::UnaryOperatorToken;
using Text::Expression::BinaryOperatorToken;
using Text::Expression::FunctionToken;

using Text::Expression::Associativity;

using Text::Expression::ExpressionParser;
using Text::Parsing::CommandParser;
using Text::Exception::SyntaxError;

inline std::unordered_map<char, std::unique_ptr<UnaryOperatorToken>> defaultUnaryOperatorCache;
inline std::unordered_map<char, IUnaryOperatorToken*> defaultUnaryOperators;

inline std::unordered_map<std::string, std::unique_ptr<BinaryOperatorToken>> defaultBinaryOperatorCache;
inline std::unordered_map<std::string, IBinaryOperatorToken*> defaultBinaryOperators;

inline std::unordered_map<std::string, std::unique_ptr<FunctionToken>> defaultFunctionCache;
inline std::unordered_map<std::string, IFunctionToken*> defaultFunctions;

inline std::unordered_map<std::string, std::unique_ptr<DefaultVariableType>> defaultUninitializedVariableCache;
inline std::unordered_map<std::string, std::unique_ptr<DefaultVariableType>> defaultInitializedVariableCache;
inline std::unordered_map<std::string, IVariableToken*> defaultVariables;

inline std::vector<DefaultValueType> results;

inline std::vector<std::tuple<const IUnaryOperatorToken*, std::string, std::string>> unaryOperatorInfoMap;
inline std::vector<std::tuple<const IBinaryOperatorToken*, std::string, std::string>> binaryOperatorInfoMap;
inline std::vector<std::tuple<const IFunctionToken*, std::string, std::string>> functionInfoMap;
inline std::vector<std::tuple<const IVariableToken*, std::string, std::string>> variableInfoMap;

inline bool quit = false;

struct kalk_options
{
  mpfr_prec_t precision;
  mpfr_rnd_t roundingMode;
  int digits;
  int output_base;
  int input_base;
  int jpo_precedence;
  std::string date_ofmt;
  unsigned int seed;
  bool interactive;
};

const inline kalk_options defaultOptions {128, mpfr_rnd_t::MPFR_RNDN, 30, 10, 10, -1, "%Y-%m-%d %H:%M:%S", 0u, false};
inline kalk_options options {};

mpfr_rnd_t strToRmode(const std::string value);
void printValue(const DefaultValueType& value);
const DefaultValueType* ans(int index = -1);
void list(const std::string& searchPattern = ".*");

void InitDefaultExpressionParser(ExpressionParser& instance);
void InitChemicalExpressionParser(ExpressionParser& instance);
void InitCommandParser(CommandParser& instance);

#endif // __SETUP_HPP__

max_stars_repo_name: albrdev/kalk

max_issues_repo_name: albrdev/kalk

max_forks_repo_name: albrdev/kalk


text:
#include <boost/python.hpp>
#include <corsika/RawParticleStream.h>
#include <iostream>

using namespace boost::python;
using std::cout;
using std::endl;

class RawParticleStream: public corsika::VRawParticleStream, public boost::python::wrapper<corsika::VRawParticleStream>
{
public:
  RawParticleStream(){}
  RawParticleStream(const corsika::VRawParticleStream& it):corsika::VRawParticleStream(it){}

  boost::optional<corsika::Particle> NextParticle()
  {
    return this->get_override("GetParticle")();
  }
  void Rewind()
  {
    this->Rewind();
  }
  bool IsValid() const
  {
    return this->get_override("IsValid")();
  }
};

inline object identity(object const& o) { return o; }

/*
  "ranges" do not make sense for this iterator, so I am doing the minimum necessary to provide a python iterator interface.
 */

template<typename Thinning>
const corsika::ParticleData<Thinning>&
next_particle(corsika::RawParticleStream<Thinning>& o)
{
    const corsika::ParticleData<Thinning>* result = o.GetOneParticle();
  if (!result) {
    PyErr_SetString(PyExc_StopIteration, "No more data.");
    boost::python::throw_error_already_set();
  }
  return *result;
}

template<typename Thinning>
const corsika::ParticleData<Thinning>&
next_particle_2(corsika::VRawParticleStream& o)
{
  corsika::RawParticleStream<Thinning>* ptr = dynamic_cast<corsika::RawParticleStream<Thinning>*>(&o);
  if (!ptr) {
    PyErr_SetString(PyExc_StopIteration, "Could not cast particle iterator.");
    boost::python::throw_error_already_set();
  }
    const corsika::ParticleData<Thinning>* result = ptr->GetOneParticle();
  if (!result) {
    PyErr_SetString(PyExc_StopIteration, "No more data.");
    boost::python::throw_error_already_set();
  }
  return *result;
}

template<typename Thinning>
void Rewind(corsika::VRawParticleStream& it)
{
  it.Rewind();
}

template <class Thinning>
void register_RawIterator(std::string name)
{
  typedef  corsika::RawParticleStream<Thinning> RawParticleStream;
    class_<RawParticleStream>(name.c_str(), init<corsika::RawStreamPtr, size_t>())
    // .def("next", next_particle<Thinning>,
    //      return_internal_reference<>())
    .def("__next__", next_particle_2<Thinning>,
         return_internal_reference<>())
    .def("__iter__", identity)
    // .def("rewind", &RawParticleIterator::Rewind)
    .def("rewind", Rewind<Thinning>)
    ;

  register_ptr_to_python<boost::shared_ptr<RawParticleStream> >();
}

void register_RawParticleIterator()
{
  class_<RawParticleStream,boost::noncopyable>("VRawIterator")
    .def("rewind", &RawParticleStream::Rewind)
    ;

  register_ptr_to_python<corsika::RawParticleStreamPtr>();

  register_RawIterator<corsika::NotThinned>("RawParticleIterator");
  register_RawIterator<corsika::Thinned>("RawParticleIterator_thin");
}

ext: cxx


text:
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/ext/boost/mpl/vector.hpp>
#include <boost/hana/ext/std/integral_constant.hpp>
#include <boost/hana/type.hpp>

#include <boost/mpl/vector.hpp>
#include <type_traits>
using namespace boost::hana;
namespace mpl = boost::mpl;

BOOST_HANA_CONSTANT_ASSERT(equal(
    cons(type<int>, mpl::vector<char>{}),
    mpl::vector<int, char>{}
));

// error: only Types can go in a MPL vector
// cons(1, mpl::vector<int>{});

BOOST_HANA_CONSTANT_ASSERT(equal(
    filter(mpl::vector<int, float, char, void>{}, trait<std::is_integral>),
    mpl::vector<int, char>{}
));

int main() { }

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
#include <iostream>
#include <cstdlib>
#include <memory>

#include <boost/asio/signal_set.hpp>

#include "listener.hpp"
#include "shared_state.hpp"

int main(int argc, char** argv)
{
    // Check command line arguments
    if (argc != 4) {
        std::cerr <<
            "  Usage: server <address> <port> <documentRoot>\n" <<
            "Example:\n" <<
            "         server 127.0.0.1 8080 .\n";
        return EXIT_FAILURE;
    }
    auto address = net::ip::make_address(argv[1]);
    auto port = static_cast<unsigned short>(std::atoi(argv[2]));
    auto documentRoot = argv[3];

    // The I/O context is required for all I/O
    net::io_context ioc;

    // Create and launch a listening port
    std::make_shared<Listener>(
        ioc,
        tcp::endpoint{address, port},
        std::make_shared<SharedState>(documentRoot))->run();

    // Capture SIGINT and SIGTERM to perform a clean shutdown
    net::signal_set signals(ioc, SIGINT, SIGTERM);
    signals.async_wait(
        [&ioc](error_code const& ec, int)
        {
            // Stop the io_context. This will cause run() to return
            // immediately, eventually destroying the io_context and any
            // remaining handlers in it.
            ioc.stop();
        });

    // Run the I/O service
    ioc.run();

    // If we get here, it means we got a SIGINT or SIGTERM

    return EXIT_SUCCESS;
}


text:
//
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/LeonineKing1199/foxy
//

#ifndef FOXY_DETAIL_RELAY_HPP_
#define FOXY_DETAIL_RELAY_HPP_

#include <foxy/session.hpp>
#include <foxy/type_traits.hpp>
#include <foxy/detail/export_connect_fields.hpp>
#include <foxy/detail/has_token.hpp>

#include <boost/beast/http/message.hpp>
#include <boost/beast/http/parser.hpp>
#include <boost/beast/http/serializer.hpp>
#include <boost/beast/http/fields.hpp>
#include <boost/beast/http/buffer_body.hpp>
#include <boost/beast/http/empty_body.hpp>
#include <boost/beast/http/error.hpp>

#include <boost/system/error_code.hpp>

#include <array>
#include <iostream>

namespace foxy
{
namespace detail
{
template <class Stream, class RelayHandler>
struct relay_op : boost::asio::coroutine
{
public:
  using executor_type = boost::asio::associated_executor_t<
    RelayHandler,
    decltype((std::declval<::foxy::basic_session<Stream>&>().get_executor()))>;

  using allocator_type = boost::asio::associated_allocator_t<RelayHandler>;

  template <bool isRequest, class Body, class Allocator>
  using parser = boost::beast::http::parser<isRequest, Body, Allocator>;

  template <bool isRequest, class Body, class Fields>
  using serializer = boost::beast::http::serializer<isRequest, Body, Fields>;

  using buffer_body = boost::beast::http::buffer_body;
  using empty_body  = boost::beast::http::empty_body;
  using fields      = boost::beast::http::basic_fields<allocator_type>;

  using request  = boost::beast::http::request<buffer_body, fields>;
  using response = boost::beast::http::response<buffer_body, fields>;

private:
  struct state
  {
    std::array<char, 2048> buffer;

    ::foxy::basic_session<Stream>& server;
    ::foxy::basic_session<Stream>& client;

    parser<true, buffer_body, allocator_type> req_parser;
    serializer<true, buffer_body, fields>     req_sr;
    fields                                    req_fields;
    request&                                  req;

    parser<false, buffer_body, allocator_type> res_parser;
    serializer<false, buffer_body, fields>     res_sr;
    fields                                     res_fields;
    response&                                  res;

    boost::system::error_code ec;

    bool close_tunnel;

    boost::asio::executor_work_guard<decltype(server.get_executor())> work;

    state(RelayHandler const&            handler,
          ::foxy::basic_session<Stream>& server_,
          ::foxy::basic_session<Stream>& client_)
      : server(server_)
      , client(client_)
      , req_parser(std::piecewise_construct,
                   std::make_tuple(),
                   std::make_tuple(boost::asio::get_associated_allocator(handler)))
      , req_sr(req_parser.get())
      , req_fields(boost::asio::get_associated_allocator(handler))
      , req(req_parser.get())
      , res_parser(std::piecewise_construct,
                   std::make_tuple(),
                   std::make_tuple(boost::asio::get_associated_allocator(handler)))
      , res_sr(res_parser.get())
      , res_fields(boost::asio::get_associated_allocator(handler))
      , res(res_parser.get())
      , close_tunnel{false}
      , work(server.get_executor())
    {
    }

    state(RelayHandler const&                        handler,
          ::foxy::basic_session<Stream>&             server_,
          ::foxy::basic_session<Stream>&             client_,
          parser<true, empty_body, allocator_type>&& req_parser_)
      : server(server_)
      , client(client_)
      , req_parser(std::move(req_parser_))
      , req_sr(req_parser.get())
      , req_fields(boost::asio::get_associated_allocator(handler))
      , req(req_parser.get())
      , res_parser(std::piecewise_construct,
                   std::make_tuple(),
                   std::make_tuple(boost::asio::get_associated_allocator(handler)))
      , res_sr(res_parser.get())
      , res_fields(boost::asio::get_associated_allocator(handler))
      , res(res_parser.get())
      , close_tunnel{false}
      , work(server.get_executor())
    {
    }
  };

  boost::beast::handler_ptr<state, RelayHandler> p_;

public:
  relay_op()                = delete;
  relay_op(relay_op const&) = default;
  relay_op(relay_op&&)      = default;

  template <class DeducedHandler>
  relay_op(::foxy::basic_session<Stream>& server,
           ::foxy::basic_session<Stream>& client,
           DeducedHandler&&               handler)
    : p_(std::forward<DeducedHandler>(handler), server, client)
  {
  }

  template <class DeducedHandler>
  relay_op(::foxy::basic_session<Stream>&             server,
           ::foxy::basic_session<Stream>&             client,
           parser<true, empty_body, allocator_type>&& req_parser,
           DeducedHandler&&                           handler)
    : p_(std::forward<DeducedHandler>(handler), server, client, std::move(req_parser))
  {
  }

  auto
  get_executor() const noexcept -> executor_type
  {
    return boost::asio::get_associated_executor(p_.handler(), p_->server.get_executor());
  }

  auto
  get_allocator() const noexcept -> allocator_type
  {
    return boost::asio::get_associated_allocator(p_.handler());
  }

  auto
  operator()(boost::system::error_code ec,
             std::size_t const         bytes_transferred,
             bool const                is_continuation = true) -> void;
};

template <class Stream, class RelayHandler>
auto
relay_op<Stream, RelayHandler>::operator()(boost::system::error_code ec,
                                           std::size_t const         bytes_transferred,
                                           bool const                is_continuation) -> void
{
  using namespace std::placeholders;
  using boost::beast::bind_handler;

  namespace http = boost::beast::http;

  auto& s = *p_;
  BOOST_ASIO_CORO_REENTER(*this)
  {
    if (!s.req_parser.is_header_done()) {
      BOOST_ASIO_CORO_YIELD
      s.server.async_read_header(s.req_parser, std::move(*this));
      if (ec) { goto upcall; }
    }

    // remove hop-by-hop headers here and then store them externally...
    // however, if the user is writing a Connection: close, they are communicating to our proxy that
    // they wish to terminate the connection and we want to empower users to gracefully close their
    // server sessions so we propagate the Connection: close field to convey to the remote that we
    // won't be needing to persist the connection beyond this current response cycle
    //
    BOOST_ASIO_CORO_YIELD
    {
      s.close_tunnel        = s.close_tunnel || !s.req.keep_alive();
      auto const is_chunked = s.req.chunked();

      if (::foxy::detail::has_foxy_via(s.req)) { goto upcall; }

      ::foxy::detail::export_connect_fields(s.req, s.req_fields);

      if (s.close_tunnel) { s.req.keep_alive(false); }
      if (is_chunked) { s.req.chunked(true); }

      s.req.insert(http::field::via, "1.1 foxy");

      s.client.async_write_header(s.req_sr, std::move(*this));
    }
    if (ec) { goto upcall; }

    do {
      s.ec = {};

      if (!s.req_parser.is_done()) {
        s.req.body().data = s.buffer.data();
        s.req.body().size = s.buffer.size();

        BOOST_ASIO_CORO_YIELD
        s.server.async_read(s.req_parser, std::move(*this));

        if (ec == http::error::need_buffer) { ec = {}; }
        if (ec) { s.ec = ec; }

        s.req.body().size = s.buffer.size() - s.req.body().size;
        s.req.body().data = s.buffer.data();
        s.req.body().more = !s.req_parser.is_done();

      } else {
        s.req.body().data = nullptr;
        s.req.body().size = 0;
      }

      BOOST_ASIO_CORO_YIELD
      s.client.async_write(s.req_sr, std::move(*this));

      if (ec == http::error::need_buffer) { ec = {}; }
      if (ec || s.ec) { goto upcall; }

    } while (!s.req_parser.is_done() && !s.req_sr.is_done());

    // TODO: if there's an actual here when reading the response header, send a 502 back to the
    // client; once the header is sent, it doesn't make sense to send a 502 on top of the already
    // serialized header
    //
    BOOST_ASIO_CORO_YIELD
    s.client.async_read_header(s.res_parser, std::move(*this));
    if (ec) { goto upcall; }

    BOOST_ASIO_CORO_YIELD
    {
      s.close_tunnel = s.close_tunnel || !s.res.keep_alive();

      if (::foxy::detail::has_foxy_via(s.res)) { goto upcall; }

      auto const is_chunked = s.res.chunked();

      ::foxy::detail::export_connect_fields(s.res, s.res_fields);

      if (s.close_tunnel) { s.res.keep_alive(false); }
      if (is_chunked) { s.res.chunked(true); }

      s.res.insert(http::field::via, "1.1 foxy");

      s.server.async_write_header(s.res_sr, std::move(*this));
    }
    if (ec) { goto upcall; }

    do {
      s.ec = {};

      if (!s.res_parser.is_done()) {
        s.res.body().data = s.buffer.data();
        s.res.body().size = s.buffer.size();

        BOOST_ASIO_CORO_YIELD
        s.client.async_read(s.res_parser, std::move(*this));

        if (ec == http::error::need_buffer) { ec = {}; }
        if (ec) { s.ec = ec; }

        s.res.body().size = s.buffer.size() - s.res.body().size;
        s.res.body().data = s.buffer.data();
        s.res.body().more = !s.res_parser.is_done();

      } else {
        s.res.body().data = nullptr;
        s.res.body().size = 0;
      }

      BOOST_ASIO_CORO_YIELD
      s.server.async_write(s.res_sr, std::move(*this));

      if (ec == http::error::need_buffer) { ec = {}; }
      if (ec || s.ec) { goto upcall; }

    } while (!s.res_parser.is_done() && !s.res_sr.is_done());

    {
      auto       work         = std::move(s.work);
      auto const close_tunnel = s.close_tunnel;
      return p_.invoke(boost::system::error_code(), close_tunnel);
    }

  upcall:
    if (!is_continuation) {
      BOOST_ASIO_CORO_YIELD
      boost::asio::post(bind_handler(std::move(*this), ec, 0));
    }
    auto work = std::move(s.work);
    p_.invoke(ec, true);
  }
}

template <class Stream, class RelayHandler>
auto
async_relay(::foxy::basic_session<Stream>& server,
            ::foxy::basic_session<Stream>& client,
            RelayHandler&&                 handler) ->
  typename boost::asio::async_result<std::decay_t<RelayHandler>,
                                     void(boost::system::error_code, bool)>::return_type
{
  boost::asio::async_completion<RelayHandler, void(boost::system::error_code, bool)> init(handler);

  relay_op<Stream, typename boost::asio::async_completion<
                     RelayHandler, void(boost::system::error_code, bool)>::completion_handler_type>(
    server, client, std::move(init.completion_handler))({}, 0, false);

  return init.result.get();
}

template <class Stream, class Parser, class RelayHandler>
auto
async_relay(::foxy::basic_session<Stream>& server,
            ::foxy::basic_session<Stream>& client,
            Parser&&                       parser,
            RelayHandler&&                 handler) ->
  typename boost::asio::async_result<std::decay_t<RelayHandler>,
                                     void(boost::system::error_code, bool)>::return_type
{
  boost::asio::async_completion<RelayHandler, void(boost::system::error_code, bool)> init(handler);

  relay_op<Stream, typename boost::asio::async_completion<
                     RelayHandler, void(boost::system::error_code, bool)>::completion_handler_type>(
    server, client, std::move(parser), std::move(init.completion_handler))({}, 0, false);

  return init.result.get();
}

} // namespace detail
} // namespace foxy

#endif // FOXY_DETAIL_RELAY_HPP_

max_stars_repo_name: djarek/foxy

max_issues_repo_name: djarek/foxy

max_forks_repo_name: djarek/foxy


text:
// Copyright (c) 2016-2020 Antony Polukhin
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_PFR_DETAIL_MAKE_FLAT_TUPLE_OF_REFERENCES_HPP
#define BOOST_PFR_DETAIL_MAKE_FLAT_TUPLE_OF_REFERENCES_HPP
#pragma once

#include <boost/pfr/detail/config.hpp>

#include <utility>      // metaprogramming stuff
#include <boost/pfr/detail/sequence_tuple.hpp>
#include <boost/pfr/detail/rvalue_t.hpp>
#include <boost/pfr/detail/make_integer_sequence.hpp>

namespace boost { namespace pfr { namespace detail {

template <std::size_t Index>
using size_t_ = std::integral_constant<std::size_t, Index >;

// Helper: Make a "getter" object corresponding to built-in tuple::get
// For user-defined structures, the getter should be "offset_based_getter"
struct sequence_tuple_getter {
  template <std::size_t idx, typename TupleOfReferences>
  decltype(auto) get(TupleOfReferences&& t, size_t_<idx>) const noexcept {
    return sequence_tuple::get<idx>(std::forward<TupleOfReferences>(t));
  }
};

template <class TupleOrUserType, class Getter, std::size_t Begin, std::size_t Size>
constexpr auto make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<Size>) noexcept;

template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr sequence_tuple::tuple<> make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<0>) noexcept;

template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr auto make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<1>) noexcept;

template <class... T>
constexpr auto tie_as_tuple_with_references(T&... args) noexcept {
    return sequence_tuple::tuple<T&...>{ args... };
}

template <class... T>
constexpr decltype(auto) tie_as_tuple_with_references(detail::sequence_tuple::tuple<T...>& t) noexcept {
    return detail::make_flat_tuple_of_references(t, sequence_tuple_getter{}, size_t_<0>{}, size_t_<sequence_tuple::tuple<T...>::size_v>{});
}

template <class... T>
constexpr decltype(auto) tie_as_tuple_with_references(const detail::sequence_tuple::tuple<T...>& t) noexcept {
    return detail::make_flat_tuple_of_references(t, sequence_tuple_getter{}, size_t_<0>{}, size_t_<sequence_tuple::tuple<T...>::size_v>{});
}

template <class Tuple1, std::size_t... I1, class Tuple2, std::size_t... I2>
constexpr auto my_tuple_cat_impl(const Tuple1& t1, std::index_sequence<I1...>, const Tuple2& t2, std::index_sequence<I2...>) noexcept {
    return detail::tie_as_tuple_with_references(
        sequence_tuple::get<I1>(t1)...,
        sequence_tuple::get<I2>(t2)...
    );
}

template <class Tuple1, class Tuple2>
constexpr auto my_tuple_cat(const Tuple1& t1, const Tuple2& t2) noexcept {
    return detail::my_tuple_cat_impl(
        t1, detail::make_index_sequence< Tuple1::size_v >{},
        t2, detail::make_index_sequence< Tuple2::size_v >{}
    );
}

template <class TupleOrUserType, class Getter, std::size_t Begin, std::size_t Size>
constexpr auto make_flat_tuple_of_references(TupleOrUserType& t, const Getter& g, size_t_<Begin>, size_t_<Size>) noexcept {
    constexpr std::size_t next_size = Size / 2;
    return detail::my_tuple_cat(
        detail::make_flat_tuple_of_references(t, g, size_t_<Begin>{}, size_t_<next_size>{}),
        detail::make_flat_tuple_of_references(t, g, size_t_<Begin + Size / 2>{}, size_t_<Size - next_size>{})
    );
}

template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr sequence_tuple::tuple<> make_flat_tuple_of_references(TupleOrUserType&, const Getter&, size_t_<Begin>, size_t_<0>) noexcept {
    return {};
}

template <class TupleOrUserType, class Getter, std::size_t Begin>
constexpr auto make_flat_tuple_of_references(TupleOrUserType& t, const Getter& g, size_t_<Begin>, size_t_<1>) noexcept {
    return detail::tie_as_tuple_with_references(
        g.get(t, size_t_<Begin>{})
    );
}

}}} // namespace boost::pfr::detail

#endif // BOOST_PFR_DETAIL_MAKE_FLAT_TUPLE_OF_REFERENCES_HPP

max_stars_repo_name: armdevvel/boost

max_issues_repo_name: armdevvel/boost