<commit_before>#pragma once

#include <cstdint>
#include <type_traits>
#include <vector>
#include <zmq.h>
#include "helpers.hpp"

namespace boost {
namespace asio {
namespace zmq {
namespace socket_option {

std::size_t const max_buff_size = 255;

template <int option, typename T> struct socket_option_impl {
    static int const id = option;
    typedef T option_value_type;

    socket_option_impl(option_value_type value) : value_(value) {}

    option_value_type value() const { return value_; }

    option_value_type& value() { return value_; }

private:
    option_value_type value_;
};

template <int option> struct socket_option_impl<option, void*> {
    static int const id = option;
    typedef void* option_value_type;

    socket_option_impl() {}

    socket_option_impl(void const* value, std::size_t size)
        : value_(static_cast<std::uint8_t const*>(value),
                 static_cast<std::uint8_t const*>(value) + size)
    {
    }

    void const* value() const { return static_cast<void const*>(value_.data()); }

    void* value() { return static_cast<void*>(value_.data()); }

    std::size_t size() const { return value_.size(); }

private:
    std::vector<std::uint8_t> value_;
};

struct events : public socket_option_impl<ZMQ_EVENTS, int> {
    static int const default_value = -1;
    explicit events(int v = default_value) : socket_option_impl<ZMQ_EVENTS, int>(v) {}
};

struct send_buff_hwm : public socket_option_impl<ZMQ_SNDHWM, int> {
    static int const default_value = 1000;
    explicit send_buff_hwm(int v = default_value) : socket_option_impl<ZMQ_SNDHWM, int>(v) {}
};

struct recv_more : public socket_option_impl<ZMQ_RCVMORE, bool> {
    static bool const default_value = false;
    explicit recv_more(int v = default_value) : socket_option_impl<ZMQ_RCVMORE, bool>(v) {}
};

struct identity : public socket_option_impl<ZMQ_IDENTITY, void*> {
    identity() {}
    identity(void const* value, std::size_t size)
        : socket_option_impl<ZMQ_IDENTITY, void*>(value, size)
    {
    }
};

struct fd : public socket_option_impl<ZMQ_FD, native_handle_type> {
    static native_handle_type const default_value = -1;
    explicit fd(native_handle_type v = default_value)
        : socket_option_impl<ZMQ_FD, native_handle_type>(v)
    {
    }
};

struct linger : public socket_option_impl<ZMQ_LINGER, int> {
    static int const default_value = -1;
    explicit linger(int v = default_value) : socket_option_impl<ZMQ_LINGER, int>(v) {}
};

template <typename OptionType>
struct is_binary_option
    : public std::is_base_of<socket_option_impl<OptionType::id, void*>, OptionType> {
};

template <typename OptionType>
struct enable_if_binary : public std::enable_if<is_binary_option<OptionType>::value> {
};

template <typename OptionType>
struct is_bool_option
    : public std::is_base_of<socket_option_impl<OptionType::id, bool>, OptionType> {
};

template <typename OptionType>
struct enable_if_bool : public std::enable_if<is_bool_option<OptionType>::value> {
};

template <typename OptionType>
struct is_raw_option
    : public std::integral_constant<
          bool, std::is_base_of<
                    socket_option_impl<OptionType::id, typename OptionType::option_value_type>,
                    OptionType>::value &&
                    !is_bool_option<OptionType>::value && !is_binary_option<OptionType>::value> {
};

template <typename OptionType>
struct enable_if_raw : public std::enable_if<is_raw_option<OptionType>::value> {
};

}  // namespace socket_option
}  // namespace zmq
}  // namespace asio
}  // namespace boost
<commit_msg>Added additional constructor for class boost::asio::zmq::socket_option::identity accepting a std::string.<commit_after>#pragma once

#include <cstdint>
#include <string>
#include <type_traits>
#include <vector>
#include <zmq.h>
#include "helpers.hpp"

namespace boost {
namespace asio {
namespace zmq {
namespace socket_option {

std::size_t const max_buff_size = 255;

template <int option, typename T> struct socket_option_impl {
    static int const id = option;
    typedef T option_value_type;

    socket_option_impl(option_value_type value) : value_(value) {}

    option_value_type value() const { return value_; }

    option_value_type& value() { return value_; }

private:
    option_value_type value_;
};

template <int option> struct socket_option_impl<option, void*> {
    static int const id = option;
    typedef void* option_value_type;

    socket_option_impl() {}

    socket_option_impl(void const* value, std::size_t size)
        : value_(static_cast<std::uint8_t const*>(value),
                 static_cast<std::uint8_t const*>(value) + size)
    {
    }

    void const* value() const { return static_cast<void const*>(value_.data()); }

    void* value() { return static_cast<void*>(value_.data()); }

    std::size_t size() const { return value_.size(); }

private:
    std::vector<std::uint8_t> value_;
};

struct events : public socket_option_impl<ZMQ_EVENTS, int> {
    static int const default_value = -1;
    explicit events(int v = default_value) : socket_option_impl<ZMQ_EVENTS, int>(v) {}
};

struct send_buff_hwm : public socket_option_impl<ZMQ_SNDHWM, int> {
    static int const default_value = 1000;
    explicit send_buff_hwm(int v = default_value) : socket_option_impl<ZMQ_SNDHWM, int>(v) {}
};

struct recv_more : public socket_option_impl<ZMQ_RCVMORE, bool> {
    static bool const default_value = false;
    explicit recv_more(int v = default_value) : socket_option_impl<ZMQ_RCVMORE, bool>(v) {}
};

struct identity : public socket_option_impl<ZMQ_IDENTITY, void*> {
    identity() {}
    identity(void const* value, std::size_t size)
        : socket_option_impl<ZMQ_IDENTITY, void*>(value, size)
    {
    }
    identity(const std::string& value)
        : socket_option_impl<ZMQ_IDENTITY, void*>(value.c_str(),value.size())
    {
    }
};

struct fd : public socket_option_impl<ZMQ_FD, native_handle_type> {
    static native_handle_type const default_value = -1;
    explicit fd(native_handle_type v = default_value)
        : socket_option_impl<ZMQ_FD, native_handle_type>(v)
    {
    }
};

struct linger : public socket_option_impl<ZMQ_LINGER, int> {
    static int const default_value = -1;
    explicit linger(int v = default_value) : socket_option_impl<ZMQ_LINGER, int>(v) {}
};

template <typename OptionType>
struct is_binary_option
    : public std::is_base_of<socket_option_impl<OptionType::id, void*>, OptionType> {
};

template <typename OptionType>
struct enable_if_binary : public std::enable_if<is_binary_option<OptionType>::value> {
};

template <typename OptionType>
struct is_bool_option
    : public std::is_base_of<socket_option_impl<OptionType::id, bool>, OptionType> {
};

template <typename OptionType>
struct enable_if_bool : public std::enable_if<is_bool_option<OptionType>::value> {
};

template <typename OptionType>
struct is_raw_option
    : public std::integral_constant<
          bool, std::is_base_of<
                    socket_option_impl<OptionType::id, typename OptionType::option_value_type>,
                    OptionType>::value &&
                    !is_bool_option<OptionType>::value && !is_binary_option<OptionType>::value> {
};

template <typename OptionType>
struct enable_if_raw : public std::enable_if<is_raw_option<OptionType>::value> {
};

}  // namespace socket_option
}  // namespace zmq
}  // namespace asio
}  // namespace boost
<|endoftext|>


<commit_before>/// Communicator.hpp
/// Shaun Harker
/// 2011

#ifndef CLUSTER_DELEGATOR_COMMUNICATOR_HPP
#define CLUSTER_DELEGATOR_COMMUNICATOR_HPP

#ifndef INLINE_IF_HEADER_ONLY
#define INLINE_IF_HEADER_ONLY
#endif

#ifndef CLUSTER_DELEGATOR_IS_AMALGAMATION
#include "Communicator.h"
#endif

#include <iostream>
#include <mpi.h>
#include <chrono>
#include <stdexcept>
#include <exception>
#include <cstdint>
#include <algorithm>
#include <thread>
#include <string>

#ifndef CD_MAX_MESSAGE_SIZE
#define CD_MAX_MESSAGE_SIZE 1073741824L
#endif

#define DEBUG if(0)

#ifndef CD_SLEEP_TIME
#define CD_SLEEP_TIME std::chrono::microseconds(10)
#endif

#ifndef CD_TICKTIME
#define CD_TICKTIME ((double)(std::chrono::system_clock::now().time_since_epoch().count()%1000000000LL))/1000000.0
#endif

INLINE_IF_HEADER_ONLY void Communicator::
initialize ( void ) {
	MPI_Comm_rank(MPI_COMM_WORLD, &SELF);
  DIRECTOR = 0;
}

INLINE_IF_HEADER_ONLY void Communicator::
finalize ( void ) {
  // Shut-down message
  int numtasks;
  MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
  int RETIRE = 0;
  for ( Channel channel = 1; channel < numtasks; ++ channel ) {
    MPI_Send ( NULL,0,MPI_CHAR,channel,RETIRE,MPI_COMM_WORLD );
  }
}

INLINE_IF_HEADER_ONLY void Communicator::
daemon ( void ) {
  daemon_on . store ( true );
  while ( 1 ) {
    if ( not daemon_on . load () ) return;

    // Determine action
    int action = 0; // sleep (default)
    // Check if there is a message to receive
    MPI_Status status;
    int flag = 0;
    MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
    if ( flag ) action = 1; // receive
#ifdef CD_COMM_LOGGING
    if ( flag ) std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receive flag\n";
#endif
    // Check if there is a message to send
    mtx . lock ();
    if ( not outbox . empty () ) action = 2; // send (overrides receive)
    mtx . unlock ();

    // Dispatch on chosen action
    switch ( action ) {
      case 0: // sleep
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") Sleep begin\n";
        mtx . unlock ();
#endif
        std::this_thread::sleep_for(CD_SLEEP_TIME);
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") Sleep end\n";
        mtx . unlock ();
#endif
        break;
      case 1: // receive
      {
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receive begin\n";
        mtx . unlock ();
#endif
        /* Get the length of the message */
        int buffer_length;
        int error_code = MPI_Get_count(&status, MPI_CHAR, &buffer_length);
        if ( error_code != 0 ) throw std::runtime_error("Communicator::receive Problem with message size");
        int tag = status . MPI_TAG;
        Channel channel = status . MPI_SOURCE;
        mtx . lock ();
        std::string & text = incoming [ channel ];
        if ( buffer_length == 0 ) {
          /* Edge case: message is integer multiple of GB size */
#ifdef CD_COMM_LOGGING
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receiving packet (stub)\n";
#endif
          MPI_Recv ( NULL, 0, MPI_CHAR, channel, tag, MPI_COMM_WORLD, &status );
        } else {
          /* Allocate space for the message */
          uint64_t N = text . size ();
          text . resize ( N + (uint64_t) buffer_length );
          char * buffer = &text[N];
          /* Receive the message */
#ifdef CD_COMM_LOGGING
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receiving packet\n";
#endif
          MPI_Recv ( buffer, buffer_length, MPI_CHAR, channel, tag, MPI_COMM_WORLD, &status );
        }
        if ( buffer_length < CD_MAX_MESSAGE_SIZE ) {
#ifdef CD_COMM_LOGGING
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") last packet; creating message\n";
#endif
          Message message;
          message . str ( text );
          message . tag = tag;
          inbox . push ( std::make_pair ( channel, message ) );
          text . clear ();
        }
#ifdef CD_COMM_LOGGING
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receive end\n";
#endif
        mtx . unlock ();
        break;
      }
      case 2: // send message
      {
        // Retrieve the message
        mtx . lock ();
#ifdef CD_COMM_LOGGING
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") send begin\n";
#endif
        std::pair<Channel, Message> pair = outbox . front ();
        outbox . pop ();
        mtx . unlock ();
        Channel channel = pair . first;
        std::string text = pair . second . str ();
        int tag = pair . second . tag;
        uint64_t begin = 0;
        uint64_t N = text . size ();
        bool edge_case = false;
        if ( N == 0 ) edge_case = true;
        while ( N > 0 ) {
          int submessage_length = std::min ( (uint64_t) CD_MAX_MESSAGE_SIZE, N );
#ifdef CD_COMM_LOGGING
          mtx . lock ();
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") sending packet of length " << submessage_length << "\n";
          mtx . unlock ();
#endif
          MPI_Send ( const_cast<char *> ( text . data () + begin ),
                     submessage_length,
                     MPI_CHAR,
                     channel,
                     tag,
                     MPI_COMM_WORLD );
#ifdef CD_COMM_LOGGING
          mtx . lock ();
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") finished sending packet of length " << submessage_length << "\n";
          mtx . unlock ();
#endif
          begin += submessage_length;
          N -= submessage_length;
          if ( submessage_length == CD_MAX_MESSAGE_SIZE && N == 0 ) {
            edge_case = true; // Message is integer GB in length
          }
        }
        /* Edge case must send addition zero-length message */
        if ( edge_case ) {
#ifdef CD_COMM_LOGGING
          mtx . lock ();
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") sending packet (stub)\n";
          mtx . unlock ();
#endif
          MPI_Send ( NULL,
                     0,
                     MPI_CHAR,
                     channel,
                     tag,
                     MPI_COMM_WORLD );
        }
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") send end\n";
        mtx . unlock ();
#endif
        break;
      }
    }
  }
}

INLINE_IF_HEADER_ONLY void Communicator::
send ( const Message & message,
       const Channel & channel ) {
  mtx . lock ();
  outbox . push ( std::make_pair ( channel, message ) );
#ifdef CD_COMM_LOGGING
  std::cout << CD_TICKTIME << " : Communicator::send (" << SELF << ") Pushing to outbox a message with tag " << message.tag << "\n";
  std::cout << CD_TICKTIME << " : Communicator::send (" << SELF << ") Outbox is now non-empty (" << outbox.size() << " messages)\n";
#endif
  mtx . unlock ();
}

INLINE_IF_HEADER_ONLY void Communicator::
receive ( Message * message,
          Channel * channel ) {
  while ( 1 ) {
    mtx . lock ();
    if ( inbox . empty () ) {
      mtx . unlock ();
      std::this_thread::sleep_for(CD_SLEEP_TIME);
      continue;
    }
    std::pair<Channel, Message> pair = inbox . front ();
#ifdef CD_COMM_LOGGING
    std::cout << CD_TICKTIME << " : Communicator::receive (" << SELF << ") Inbox non-empty (" << inbox.size() << " messages)\n";
    std::cout << CD_TICKTIME << " : Communicator::receive (" << SELF << ") Popping from inbox a message with tag " << pair.second.tag << "\n";
#endif
    inbox . pop ();
    mtx . unlock ();
    *channel = pair . first;
    *message = pair . second;
    return;
  }
}

INLINE_IF_HEADER_ONLY bool Communicator::
coordinating ( void ) {
  return ( SELF == DIRECTOR );
}

INLINE_IF_HEADER_ONLY void Communicator::
halt ( void ) {
  daemon_on . store ( false );
}

#endif
<commit_msg>Fixed an issue preventing programs from halting in some MPI implementations<commit_after>/// Communicator.hpp
/// Shaun Harker
/// 2011

#ifndef CLUSTER_DELEGATOR_COMMUNICATOR_HPP
#define CLUSTER_DELEGATOR_COMMUNICATOR_HPP

#ifndef INLINE_IF_HEADER_ONLY
#define INLINE_IF_HEADER_ONLY
#endif

#ifndef CLUSTER_DELEGATOR_IS_AMALGAMATION
#include "Communicator.h"
#endif

#include <iostream>
#include <mpi.h>
#include <chrono>
#include <stdexcept>
#include <exception>
#include <cstdint>
#include <algorithm>
#include <thread>
#include <string>

#ifndef CD_MAX_MESSAGE_SIZE
#define CD_MAX_MESSAGE_SIZE 1073741824L
#endif

#define DEBUG if(0)

#ifndef CD_SLEEP_TIME
#define CD_SLEEP_TIME std::chrono::microseconds(10)
#endif

#ifndef CD_TICKTIME
#define CD_TICKTIME ((double)(std::chrono::system_clock::now().time_since_epoch().count()%1000000000LL))/1000000.0
#endif

INLINE_IF_HEADER_ONLY void Communicator::
initialize ( void ) {
	MPI_Comm_rank(MPI_COMM_WORLD, &SELF);
  DIRECTOR = 0;
}

INLINE_IF_HEADER_ONLY void Communicator::
finalize ( void ) {
  if ( not coordinating () ) return;
  // Shut-down message
  int numtasks;
  MPI_Comm_size(MPI_COMM_WORLD,&numtasks);
  int RETIRE = 0;
  for ( Channel channel = 1; channel < numtasks; ++ channel ) {
    MPI_Send ( NULL,0,MPI_CHAR,channel,RETIRE,MPI_COMM_WORLD );
  }
}

INLINE_IF_HEADER_ONLY void Communicator::
daemon ( void ) {
  daemon_on . store ( true );
  while ( 1 ) {
    if ( not daemon_on . load () ) return;

    // Determine action
    int action = 0; // sleep (default)
    // Check if there is a message to receive
    MPI_Status status;
    int flag = 0;
    MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);
    if ( flag ) action = 1; // receive
#ifdef CD_COMM_LOGGING
    if ( flag ) std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receive flag\n";
#endif
    // Check if there is a message to send
    mtx . lock ();
    if ( not outbox . empty () ) action = 2; // send (overrides receive)
    mtx . unlock ();

    // Dispatch on chosen action
    switch ( action ) {
      case 0: // sleep
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") Sleep begin\n";
        mtx . unlock ();
#endif
        std::this_thread::sleep_for(CD_SLEEP_TIME);
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") Sleep end\n";
        mtx . unlock ();
#endif
        break;
      case 1: // receive
      {
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receive begin\n";
        mtx . unlock ();
#endif
        /* Get the length of the message */
        int buffer_length;
        int error_code = MPI_Get_count(&status, MPI_CHAR, &buffer_length);
        if ( error_code != 0 ) throw std::runtime_error("Communicator::receive Problem with message size");
        int tag = status . MPI_TAG;
        Channel channel = status . MPI_SOURCE;
        mtx . lock ();
        std::string & text = incoming [ channel ];
        if ( buffer_length == 0 ) {
          /* Edge case: message is integer multiple of GB size */
#ifdef CD_COMM_LOGGING
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receiving packet (stub)\n";
#endif
          MPI_Recv ( NULL, 0, MPI_CHAR, channel, tag, MPI_COMM_WORLD, &status );
        } else {
          /* Allocate space for the message */
          uint64_t N = text . size ();
          text . resize ( N + (uint64_t) buffer_length );
          char * buffer = &text[N];
          /* Receive the message */
#ifdef CD_COMM_LOGGING
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receiving packet\n";
#endif
          MPI_Recv ( buffer, buffer_length, MPI_CHAR, channel, tag, MPI_COMM_WORLD, &status );
        }
        if ( buffer_length < CD_MAX_MESSAGE_SIZE ) {
#ifdef CD_COMM_LOGGING
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") last packet; creating message\n";
#endif
          Message message;
          message . str ( text );
          message . tag = tag;
          inbox . push ( std::make_pair ( channel, message ) );
          text . clear ();
        }
#ifdef CD_COMM_LOGGING
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") receive end\n";
#endif
        mtx . unlock ();
        break;
      }
      case 2: // send message
      {
        // Retrieve the message
        mtx . lock ();
#ifdef CD_COMM_LOGGING
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") send begin\n";
#endif
        std::pair<Channel, Message> pair = outbox . front ();
        outbox . pop ();
        mtx . unlock ();
        Channel channel = pair . first;
        std::string text = pair . second . str ();
        int tag = pair . second . tag;
        uint64_t begin = 0;
        uint64_t N = text . size ();
        bool edge_case = false;
        if ( N == 0 ) edge_case = true;
        while ( N > 0 ) {
          int submessage_length = std::min ( (uint64_t) CD_MAX_MESSAGE_SIZE, N );
#ifdef CD_COMM_LOGGING
          mtx . lock ();
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") sending packet of length " << submessage_length << "\n";
          mtx . unlock ();
#endif
          MPI_Send ( const_cast<char *> ( text . data () + begin ),
                     submessage_length,
                     MPI_CHAR,
                     channel,
                     tag,
                     MPI_COMM_WORLD );
#ifdef CD_COMM_LOGGING
          mtx . lock ();
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") finished sending packet of length " << submessage_length << "\n";
          mtx . unlock ();
#endif
          begin += submessage_length;
          N -= submessage_length;
          if ( submessage_length == CD_MAX_MESSAGE_SIZE && N == 0 ) {
            edge_case = true; // Message is integer GB in length
          }
        }
        /* Edge case must send addition zero-length message */
        if ( edge_case ) {
#ifdef CD_COMM_LOGGING
          mtx . lock ();
          std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") sending packet (stub)\n";
          mtx . unlock ();
#endif
          MPI_Send ( NULL,
                     0,
                     MPI_CHAR,
                     channel,
                     tag,
                     MPI_COMM_WORLD );
        }
#ifdef CD_COMM_LOGGING
        mtx . lock ();
        std::cout << CD_TICKTIME << " : Communicator::daemon (" << SELF << ") send end\n";
        mtx . unlock ();
#endif
        break;
      }
    }
  }
}

INLINE_IF_HEADER_ONLY void Communicator::
send ( const Message & message,
       const Channel & channel ) {
  mtx . lock ();
  outbox . push ( std::make_pair ( channel, message ) );
#ifdef CD_COMM_LOGGING
  std::cout << CD_TICKTIME << " : Communicator::send (" << SELF << ") Pushing to outbox a message with tag " << message.tag << "\n";
  std::cout << CD_TICKTIME << " : Communicator::send (" << SELF << ") Outbox is now non-empty (" << outbox.size() << " messages)\n";
#endif
  mtx . unlock ();
}

INLINE_IF_HEADER_ONLY void Communicator::
receive ( Message * message,
          Channel * channel ) {
  while ( 1 ) {
    mtx . lock ();
    if ( inbox . empty () ) {
      mtx . unlock ();
      std::this_thread::sleep_for(CD_SLEEP_TIME);
      continue;
    }
    std::pair<Channel, Message> pair = inbox . front ();
#ifdef CD_COMM_LOGGING
    std::cout << CD_TICKTIME << " : Communicator::receive (" << SELF << ") Inbox non-empty (" << inbox.size() << " messages)\n";
    std::cout << CD_TICKTIME << " : Communicator::receive (" << SELF << ") Popping from inbox a message with tag " << pair.second.tag << "\n";
#endif
    inbox . pop ();
    mtx . unlock ();
    *channel = pair . first;
    *message = pair . second;
    return;
  }
}

INLINE_IF_HEADER_ONLY bool Communicator::
coordinating ( void ) {
  return ( SELF == DIRECTOR );
}

INLINE_IF_HEADER_ONLY void Communicator::
halt ( void ) {
  daemon_on . store ( false );
}

#endif
<|endoftext|>


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

#ifndef INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_

#include "distortos/scheduler/FifoQueueBase.hpp"

namespace distortos
{

/// RawFifoQueue class is very similar to FifoQueue, but optimized for binary serializable types (like POD types). Type
/// T can be used with both RawFifoQueue and FifoQueue<T> only when std::is_trivially_copyable<T>::value == true,
/// otherwise only FifoQueue<T> use is safe, while using RawFifoQueue results in undefined behavior.
class RawFifoQueue
{
public:

	/**
	 * \brief RawFifoQueue's constructor
	 *
	 * \param [in] storage is a memory block for elements, sufficiently large for \a maxElements, each \a elementSize
	 * bytes long
	 * \param [in] elementSize is the size of single queue element, bytes
	 * \param [in] maxElements is the number of elements in storage memory block
	 */

	RawFifoQueue(void* storage, size_t elementSize, size_t maxElements);

	/**
	 * \brief Pops the oldest (first) element from the queue.
	 *
	 * \param [out] buffer is a pointer to buffer for popped element
	 * \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	int pop(void* buffer, size_t size);

	/**
	 * \brief Pops the oldest (first) element from the queue.
	 *
	 * \param T is the type of data popped from the queue
	 *
	 * \param [out] buffer is a reference to object that will be used to return popped value
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int pop(T& buffer)
	{
		return pop(&buffer, sizeof(buffer));
	}

	/**
	 * \brief Pushes the element to the queue.
	 *
	 * \param [in] data is a pointer to data that will be pushed to RawFifoQueue
	 * \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	int push(const void* data, size_t size);

	/**
	 * \brief Pushes the element to the queue.
	 *
	 * \param T is the type of data pushed to the queue
	 *
	 * \param [in] data is a reference to data that will be pushed to RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int push(const T& data)
	{
		return push(&data, sizeof(data));
	}

	/**
	 * \brief Tries to pop the oldest (first) element from the queue.
	 *
	 * \param [out] buffer is a pointer to buffer for popped element
	 * \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	int tryPop(void* buffer, size_t size);

	/**
	 * \brief Tries to push the element to the queue.
	 *
	 * \param [in] data is a pointer to data that will be pushed to RawFifoQueue
	 * \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	int tryPush(const void* data, size_t size);

	/**
	 * \brief Tries to push the element to the queue.
	 *
	 * \param T is the type of data pushed to the queue
	 *
	 * \param [in] data is a reference to data that will be pushed to RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int tryPush(const T& data)
	{
		return tryPush(&data, sizeof(data));
	}

private:

	/**
	 * \brief Pops the oldest (first) element from the queue.
	 *
	 * Internal version - builds the Functor object.
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
	 * \param [out] buffer is a pointer to buffer for popped element
	 * \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int popInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, void* buffer, size_t size);

	/**
	 * \brief Pushes the element to the queue.
	 *
	 * Internal version - builds the Functor object.
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
	 * \param [in] data is a pointer to data that will be pushed to RawFifoQueue
	 * \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int pushInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, const void* data, size_t size);

	/// contained scheduler::FifoQueueBase object which implements base functionality
	scheduler::FifoQueueBase fifoQueueBase_;

	/// size of single queue element, bytes
	const size_t elementSize_;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
<commit_msg>RawFifoQueue: add RawFifoQueue::tryPop() template variant<commit_after>/**
 * \file
 * \brief RawFifoQueue class header
 *
 * \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-01-01
 */

#ifndef INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
#define INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_

#include "distortos/scheduler/FifoQueueBase.hpp"

namespace distortos
{

/// RawFifoQueue class is very similar to FifoQueue, but optimized for binary serializable types (like POD types). Type
/// T can be used with both RawFifoQueue and FifoQueue<T> only when std::is_trivially_copyable<T>::value == true,
/// otherwise only FifoQueue<T> use is safe, while using RawFifoQueue results in undefined behavior.
class RawFifoQueue
{
public:

	/**
	 * \brief RawFifoQueue's constructor
	 *
	 * \param [in] storage is a memory block for elements, sufficiently large for \a maxElements, each \a elementSize
	 * bytes long
	 * \param [in] elementSize is the size of single queue element, bytes
	 * \param [in] maxElements is the number of elements in storage memory block
	 */

	RawFifoQueue(void* storage, size_t elementSize, size_t maxElements);

	/**
	 * \brief Pops the oldest (first) element from the queue.
	 *
	 * \param [out] buffer is a pointer to buffer for popped element
	 * \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	int pop(void* buffer, size_t size);

	/**
	 * \brief Pops the oldest (first) element from the queue.
	 *
	 * \param T is the type of data popped from the queue
	 *
	 * \param [out] buffer is a reference to object that will be used to return popped value
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int pop(T& buffer)
	{
		return pop(&buffer, sizeof(buffer));
	}

	/**
	 * \brief Pushes the element to the queue.
	 *
	 * \param [in] data is a pointer to data that will be pushed to RawFifoQueue
	 * \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	int push(const void* data, size_t size);

	/**
	 * \brief Pushes the element to the queue.
	 *
	 * \param T is the type of data pushed to the queue
	 *
	 * \param [in] data is a reference to data that will be pushed to RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::wait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int push(const T& data)
	{
		return push(&data, sizeof(data));
	}

	/**
	 * \brief Tries to pop the oldest (first) element from the queue.
	 *
	 * \param [out] buffer is a pointer to buffer for popped element
	 * \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	int tryPop(void* buffer, size_t size);

	/**
	 * \brief Tries to pop the oldest (first) element from the queue.
	 *
	 * \param T is the type of data popped from the queue
	 *
	 * \param [out] buffer is a reference to object that will be used to return popped value
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int tryPop(T& buffer)
	{
		return tryPop(&buffer, sizeof(buffer));
	}

	/**
	 * \brief Tries to push the element to the queue.
	 *
	 * \param [in] data is a pointer to data that will be pushed to RawFifoQueue
	 * \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	int tryPush(const void* data, size_t size);

	/**
	 * \brief Tries to push the element to the queue.
	 *
	 * \param T is the type of data pushed to the queue
	 *
	 * \param [in] data is a reference to data that will be pushed to RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - sizeof(T) doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by Semaphore::tryWait();
	 * - error codes returned by Semaphore::post();
	 */

	template<typename T>
	int tryPush(const T& data)
	{
		return tryPush(&data, sizeof(data));
	}

private:

	/**
	 * \brief Pops the oldest (first) element from the queue.
	 *
	 * Internal version - builds the Functor object.
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a popSemaphore_
	 * \param [out] buffer is a pointer to buffer for popped element
	 * \param [in] size is the size of \a buffer, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was popped successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int popInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, void* buffer, size_t size);

	/**
	 * \brief Pushes the element to the queue.
	 *
	 * Internal version - builds the Functor object.
	 *
	 * \param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \a pushSemaphore_
	 * \param [in] data is a pointer to data that will be pushed to RawFifoQueue
	 * \param [in] size is the size of \a data, bytes - must be equal to the \a elementSize attribute of RawFifoQueue
	 *
	 * \return zero if element was pushed successfully, error code otherwise:
	 * - EMSGSIZE - \a size doesn't match the \a elementSize attribute of RawFifoQueue;
	 * - error codes returned by \a waitSemaphoreFunctor's operator() call;
	 * - error codes returned by Semaphore::post();
	 */

	int pushInternal(const scheduler::SemaphoreFunctor& waitSemaphoreFunctor, const void* data, size_t size);

	/// contained scheduler::FifoQueueBase object which implements base functionality
	scheduler::FifoQueueBase fifoQueueBase_;

	/// size of single queue element, bytes
	const size_t elementSize_;
};

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_RAWFIFOQUEUE_HPP_
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: searchdemo.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: abi $ $Date: 2001-05-10 15:26:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <rtl/string.hxx>
#include <osl/file.hxx>
#include <db/Block.hxx>
#include <db/Schema.hxx>
#include <db/BtreeDictParameters.hxx>
#include <db/BtreeDict.hxx>
#include <util/RandomAccessStream.hxx>
#include <db/DBEnv.hxx>
#include <qe/QueryProcessor.hxx>

#ifdef ABIDEBUG
#include <abidebug.hxx>
#endif

using namespace xmlsearch::util;
using namespace xmlsearch::db;
using namespace xmlsearch::qe;

extern RandomAccessStream* theFile();

void print_rtl_OUString( const rtl::OUString bla )
{
    rtl::OString bluber = rtl::OString( bla.getStr(),bla.getLength(),RTL_TEXTENCODING_UTF8 );
    char* bluberChr = new char[ 1+bluber.getLength() ];
    const sal_Char* jux = bluber.getStr();

    for( int i = 0; i < bluber.getLength(); ++i )
        bluberChr[i] = jux[i];

    bluberChr[ bluber.getLength() ] = 0;
    printf( "%s\n",bluberChr );
    delete[] bluberChr;
}

extern void bla();
extern void blu();

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

    QueryResults* queryResults = 0;

    try
    {
        rtl::OUString installDir = rtl::OUString::createFromAscii( "//./e|/index/" );
        QueryProcessor queryProcessor( installDir );

        std::vector<rtl::OUString> Query(1);
        Query[0] = ( rtl::OUString::createFromAscii( "text*" ) );
        rtl::OUString Scope = rtl::OUString::createFromAscii( "" );
        int HitCount = 10;

        QueryStatement queryStatement( HitCount,Query,Scope );
        queryResults = queryProcessor.processQuery( queryStatement );

        rtl::OUString translations[2];
        translations[0] = rtl::OUString::createFromAscii( "#HLP#" );
        translations[1] = rtl::OUString::createFromAscii( "vnd.sun.star.help://" );

        PrefixTranslator* translator =  PrefixTranslator::makePrefixTranslator( translations,2 );

        QueryHitIterator* it = queryResults->makeQueryHitIterator();
        sal_Int32 j = 0;
        while( it->next() )
        {
            printf( "Ergebnis %2d    ",j );
            QueryHitData* qhd = it->getHit( translator );
            printf( "Penalty = %10.4f    ",qhd->getPenalty() );
            print_rtl_OUString( qhd->getDocument() );
            ++j;
        }

        delete it;
    }
    catch( ... )
    {
        printf( "catched exception" );
        throw;
    }
    return 0;
}

// This is the main line of programming

//    Indexccessor indexAcc( rtl::OUString::createFromAscii( "/home/ab106281/work/index" ) );
//    Schema schema( indexAcc,false );
//    BtreeDictParameters params( schema,
//                    rtl::OUString::createFromAscii( "DICTIONARY" ) );

//    blu();

//    std::vector< rtl::OUString > terms( 1 );
//    terms[0] = rtl::OUString::createFromAscii( "text" );
//    QueryStatement statement( 100,terms,rtl::OUString::createFromAscii( "" ) );
//    QueryProcessor queryProcessor( 0 );
//    QueryResults* results = queryProcessor.processQuery( statement );

  // rtl::OString bluber = rtl::OString( bla.getStr(),bla.getLength(),RTL_TEXTENCODING_UTF8 );
  // cout << bluber.getStr() << endl;

/*
  public static void main(String[] args) {
  try {
  Schema schema = new Schema( new IndexAccessor( args[0] ), false);
  BtreeDictParameters params = new BtreeDictParameters(schema, "DICTIONARY");
  BtreeDict source = new BtreeDict(params);
  source.test();
  }
  catch (Exception e) {
  System.err.println(e);
  e.printStackTrace();
  }
  }
*/
<commit_msg>More testing<commit_after>/*************************************************************************
 *
 *  $RCSfile: searchdemo.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: abi $ $Date: 2001-05-11 12:39:37 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <rtl/string.hxx>
#include <osl/file.hxx>
#include <db/Block.hxx>
#include <db/Schema.hxx>
#include <db/BtreeDictParameters.hxx>
#include <db/BtreeDict.hxx>
#include <util/RandomAccessStream.hxx>
#include <db/DBEnv.hxx>
#include <qe/QueryProcessor.hxx>

#ifdef ABIDEBUG
#include <abidebug.hxx>
#endif

using namespace xmlsearch::util;
using namespace xmlsearch::db;
using namespace xmlsearch::qe;

extern RandomAccessStream* theFile();

void print_rtl_OUString( const rtl::OUString bla )
{
    rtl::OString bluber = rtl::OString( bla.getStr(),bla.getLength(),RTL_TEXTENCODING_UTF8 );
    char* bluberChr = new char[ 1+bluber.getLength() ];
    const sal_Char* jux = bluber.getStr();

    for( int i = 0; i < bluber.getLength(); ++i )
        bluberChr[i] = jux[i];

    bluberChr[ bluber.getLength() ] = 0;
    printf( "%s\n",bluberChr );
    delete[] bluberChr;
}

extern void bla();
extern void blu();

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

    QueryResults* queryResults = 0;

    try
    {
        rtl::OUString installDir = rtl::OUString::createFromAscii( "//./e|/index/" );
        QueryProcessor queryProcessor( installDir );

        std::vector<rtl::OUString> Query(2);
        Query[0] = rtl::OUString::createFromAscii( "text*" );
        Query[1] = rtl::OUString::createFromAscii( "abbildung" );
        rtl::OUString Scope = rtl::OUString::createFromAscii( "" );
        int HitCount = 40;

        QueryStatement queryStatement( HitCount,Query,Scope );
        queryResults = queryProcessor.processQuery( queryStatement );

        rtl::OUString translations[2];
        translations[0] = rtl::OUString::createFromAscii( "#HLP#" );
        translations[1] = rtl::OUString::createFromAscii( "vnd.sun.star.help://" );

        PrefixTranslator* translator =  PrefixTranslator::makePrefixTranslator( translations,2 );

        QueryHitIterator* it = queryResults->makeQueryHitIterator();
        sal_Int32 j = 0;
        while( j < 10 && it->next() )
        {
            printf( "Ergebnis %2d    ",j );
            QueryHitData* qhd = it->getHit( translator );
            printf( "Penalty = %10.4f    ",qhd->getPenalty() );
            print_rtl_OUString( qhd->getDocument() );
            ++j;
        }

        delete it;
    }
    catch( ... )
    {
        printf( "catched exception" );
        throw;
    }
    return 0;
}

// This is the main line of programming

//    Indexccessor indexAcc( rtl::OUString::createFromAscii( "/home/ab106281/work/index" ) );
//    Schema schema( indexAcc,false );
//    BtreeDictParameters params( schema,
//                    rtl::OUString::createFromAscii( "DICTIONARY" ) );

//    blu();

//    std::vector< rtl::OUString > terms( 1 );
//    terms[0] = rtl::OUString::createFromAscii( "text" );
//    QueryStatement statement( 100,terms,rtl::OUString::createFromAscii( "" ) );
//    QueryProcessor queryProcessor( 0 );
//    QueryResults* results = queryProcessor.processQuery( statement );

  // rtl::OString bluber = rtl::OString( bla.getStr(),bla.getLength(),RTL_TEXTENCODING_UTF8 );
  // cout << bluber.getStr() << endl;

/*
  public static void main(String[] args) {
  try {
  Schema schema = new Schema( new IndexAccessor( args[0] ), false);
  BtreeDictParameters params = new BtreeDictParameters(schema, "DICTIONARY");
  BtreeDict source = new BtreeDict(params);
  source.test();
  }
  catch (Exception e) {
  System.err.println(e);
  e.printStackTrace();
  }
  }
*/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLTextFrameContext.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 10:48:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLTEXTFRAMECONTEXT_HXX
#define _XMLTEXTFRAMECONTEXT_HXX

#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextCursor; class XTextContent; }
} } }

class SvXMLAttributeList;
class XMLTextFrameContextHyperlink_Impl;

class XMLTextFrameContext : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XAttributeList > m_xAttrList;

    SvXMLImportContextRef m_xImplContext;
    SvXMLAttributeList *m_pAttrList;

    XMLTextFrameContextHyperlink_Impl   *m_pHyperlink;
    ::rtl::OUString m_sDesc;

    ::com::sun::star::text::TextContentAnchorType   m_eDefaultAnchorType;

    sal_Bool m_bHasName;

    sal_Bool CreateIfNotThere();
    sal_Bool CreateIfNotThere( ::com::sun::star::uno::Reference <
        ::com::sun::star::beans::XPropertySet >& rPropSet );

public:

    TYPEINFO();

    XMLTextFrameContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            ::com::sun::star::text::TextContentAnchorType eDfltAnchorType );
    virtual ~XMLTextFrameContext();

    virtual void EndElement();

    SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    void SetHyperlink( const ::rtl::OUString& rHRef,
                       const ::rtl::OUString& rName,
                       const ::rtl::OUString& rTargetFrameName,
                       sal_Bool bMap );

    ::com::sun::star::text::TextContentAnchorType GetAnchorType() const;

    ::com::sun::star::uno::Reference <
        ::com::sun::star::text::XTextContent > GetTextContent() const;
    // --> OD 2004-08-24 #i33242#
    ::com::sun::star::uno::Reference <
        ::com::sun::star::drawing::XShape > GetShape() const;
    // <--
};

#endif
<commit_msg>INTEGRATION: CWS oasisbf2 (1.20.42); FILE MERGED 2004/11/02 17:26:02 mib 1.20.42.1: #i35133#: replacement image for embedded objects<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLTextFrameContext.hxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: rt $ $Date: 2004-11-26 13:05:22 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLTEXTFRAMECONTEXT_HXX
#define _XMLTEXTFRAMECONTEXT_HXX

#ifndef _COM_SUN_STAR_TEXT_TEXTCONTENTANCHORTYPE_HPP
#include <com/sun/star/text/TextContentAnchorType.hpp>
#endif

#ifndef _XMLOFF_XMLICTXT_HXX
#include "xmlictxt.hxx"
#endif

namespace com { namespace sun { namespace star {
    namespace text { class XTextCursor; class XTextContent; }
} } }

class SvXMLAttributeList;
class XMLTextFrameContextHyperlink_Impl;

class XMLTextFrameContext : public SvXMLImportContext
{
    ::com::sun::star::uno::Reference<
        ::com::sun::star::xml::sax::XAttributeList > m_xAttrList;

    SvXMLImportContextRef m_xImplContext;
    SvXMLImportContextRef m_xReplImplContext;
    SvXMLAttributeList *m_pAttrList;

    XMLTextFrameContextHyperlink_Impl   *m_pHyperlink;
    ::rtl::OUString m_sDesc;

    ::com::sun::star::text::TextContentAnchorType   m_eDefaultAnchorType;

    sal_Bool m_bHasName;
    sal_Bool m_bSupportsReplacement;

    sal_Bool CreateIfNotThere();
    sal_Bool CreateIfNotThere( ::com::sun::star::uno::Reference <
        ::com::sun::star::beans::XPropertySet >& rPropSet );

public:

    TYPEINFO();

    XMLTextFrameContext( SvXMLImport& rImport,
            sal_uInt16 nPrfx,
            const ::rtl::OUString& rLName,
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::xml::sax::XAttributeList > & xAttrList,
            ::com::sun::star::text::TextContentAnchorType eDfltAnchorType );
    virtual ~XMLTextFrameContext();

    virtual void EndElement();

    SvXMLImportContext *CreateChildContext( sal_uInt16 nPrefix,
                const ::rtl::OUString& rLocalName,
                 const ::com::sun::star::uno::Reference<
                    ::com::sun::star::xml::sax::XAttributeList > & xAttrList );

    void SetHyperlink( const ::rtl::OUString& rHRef,
                       const ::rtl::OUString& rName,
                       const ::rtl::OUString& rTargetFrameName,
                       sal_Bool bMap );

    ::com::sun::star::text::TextContentAnchorType GetAnchorType() const;

    ::com::sun::star::uno::Reference <
        ::com::sun::star::text::XTextContent > GetTextContent() const;
    // --> OD 2004-08-24 #i33242#
    ::com::sun::star::uno::Reference <
        ::com::sun::star::drawing::XShape > GetShape() const;
    // <--
};

#endif
<|endoftext|>


<commit_before>#if !defined __GNUC__
#pragma warning( disable: 4571 4820 4514 4987 4710 4309 4986 4548)
// relative include path contains '..'
// (function) selected for automatic inline expansion
#pragma warning( disable: 4464 4711 )
#else
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif

#include <iostream>
#include "../SafeInt.hpp"

enum class Foo
{
	Foo1 = 0,
	Foo2
};

template <typename T, typename U>
void CompiledMixedType()
{
	// Mixed constructors
	U u = 0;
	T t = 0;
	bool b = false;
	SafeInt<T> st(u);
	SafeInt<U> su(u);
	SafeInt<T> st2(su);

	// Shut up the compiler
	b = !b;

	// Assignment
	st = t;
	st = u;
	st = su;
	st = st2;

	// Casting
	U u2 = (U)st;

	// Modulus, modulus assignment
	u = 1;
	t = st % u;
	st2 = 1;
	t = st % st2;
	t = u % st;

	st %= u;
	st %= su;

	// Multiplication
	t = st * u;
	t = st * st2;
	t = u * st;
	st *= u;
	st *= su;

	// Division
	u = 1;
	st2 = 1;
	st = 1;
	t = st / u;
	t = st / st2;
	t = u / st;
	st /= u;
	st /= su;

	// Addition
	t = st + u;
	t = st + st2;
	t = u + st;
	st += u;
	st += su;

	// Subtraction
	t = st - u;
	t = st - st2;
	t = u - st;
	st -= u;
	st -= su;

	// Shift operators
	u = 1;
	su = 1;
	// Left
	t = st << u;
	t = st << su;
	t = t << su;

	st <<= u;
	st <<= su;

	// Right
	t = st >> u;
	t = st >> su;
	t = t >> su;

	st >>= u;
	st >>= su;

	// Binary operations
	// And
	t = st & st2;
	t = st & u;
	t = t & su;

	st &= st2;
	st &= u;
	st &= su;

	// Or
	t = st | st2;
	t = st | u;
	t = t | su;

	st |= st2;
	st |= u;
	st |= su;

	// Xor
	t = st ^ st2;
	t = st ^ u;
	t = t ^ su;

	st ^= st2;
	st ^= u;
	st ^= su;

	// Comparisons
	// Less than
	b = st < su;
	b = st < u;
	b = u < st;
	b = st < su;

	// Less than or equal
	b = st <= su;
	b = st <= u;
	b = u <= st;
	b = st <= su;

	// Greater than
	b = st > su;
	b = st > u;
	b = u > st;
	b = st > su;

	// Greater than or equal
	b = st >= su;
	b = st >= u;
	b = u >= st;
	b = st >= su;

	// Equals
	b = st == su;
	b = st == u;
	b = u == st;
	b = st == su;
}

template <typename T>
void CompileSigned()
{
	SafeInt<T> st;
	T t = -st;
}

template <typename T>
void CompileType()
{
	// Test constructors
	SafeInt<T> s;
	SafeInt<T> i(Foo::Foo1);
	T t = 0;
	SafeInt<T> st(t);
	SafeInt<T> sb(false);

	// Special case casts
	bool b = (bool)s;
	wchar_t w = (wchar_t)s;
	size_t size = (size_t)s;
	float f = (float)s;
	double d = (double)s;
	long double ld = (long double)s;

	// Pointer operations
	T* p1 = s.Ptr();
	const T* p2 = s.Ptr();
	const T& r = s.Ref();
	T* p3 = &s;
	const T* p4 = &s;

	// Unary operators
	bool b2 = !st;
	t = +st;

	st++;
	++st;
	st--;
	--st;
	t = ~st;

	// Mixed operations
	CompiledMixedType<T, char>();
	CompiledMixedType<T, signed char>();
	CompiledMixedType<T, unsigned char>();
	CompiledMixedType<T, short>();
	CompiledMixedType<T, unsigned short>();
	CompiledMixedType<T, int>();
	CompiledMixedType<T, unsigned int>();
	CompiledMixedType<T, long>();
	CompiledMixedType<T, unsigned long>();
	CompiledMixedType<T, long long>();
	CompiledMixedType<T, unsigned long long>();
}

void CompileMe()
{
	CompileType<char>();
	CompileType<unsigned char>();
	CompileType<signed char>();

	CompileType<unsigned short>();
	CompileType<signed short>();
	CompileType<unsigned int>();
	CompileType<signed int>();
	CompileType<unsigned long>();
	CompileType<signed long>();
	CompileType<unsigned long long>();
	CompileType<signed long long>();

	CompileSigned<signed char>();
	CompileSigned<signed short>();
	CompileSigned<signed int>();
	CompileSigned<signed long>();
	CompileSigned<signed long long>();

}

/*
	Need to add tests for the miscellaneous helper functions
	Min, Max, Align, Swap
	Also need the pointer functions
*/
int main(int, char**)
{
	CompileMe();
  std::cout << "It compiles!\n";
  return 0;
}
<commit_msg>Add compile test coverage for constexpr functions covered by the C++11 standard<commit_after>#if !defined __GNUC__
#pragma warning( disable: 4571 4820 4514 4987 4710 4309 4986 4548)
// relative include path contains '..'
// (function) selected for automatic inline expansion
#pragma warning( disable: 4464 4711 )
#else
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif

#include <iostream>
#include "../SafeInt.hpp"

enum class Foo
{
	Foo1 = 0,
	Foo2
};

template <typename T, typename U>
void CompiledMixedType()
{
	// Mixed constructors
	U u = 0;
	T t = 0;
	bool b = false;
	SafeInt<T> st(u);
	SafeInt<U> su(u);
	SafeInt<T> st2(su);

	// Shut up the compiler
	b = !b;

	// Assignment
	st = t;
	st = u;
	st = su;
	st = st2;

	// Casting
	U u2 = (U)st;

	// Modulus, modulus assignment
	u = 1;
	t = st % u;
	st2 = 1;
	t = st % st2;
	t = u % st;

	st %= u;
	st %= su;

	// Multiplication
	t = st * u;
	t = st * st2;
	t = u * st;
	st *= u;
	st *= su;

	// Division
	u = 1;
	st2 = 1;
	st = 1;
	t = st / u;
	t = st / st2;
	t = u / st;
	st /= u;
	st /= su;

	// Addition
	t = st + u;
	t = st + st2;
	t = u + st;
	st += u;
	st += su;

	// Subtraction
	t = st - u;
	t = st - st2;
	t = u - st;
	st -= u;
	st -= su;

	// Shift operators
	u = 1;
	su = 1;
	// Left
	t = st << u;
	t = st << su;
	t = t << su;

	st <<= u;
	st <<= su;

	// Right
	t = st >> u;
	t = st >> su;
	t = t >> su;

	st >>= u;
	st >>= su;

	// Binary operations
	// And
	t = st & st2;
	t = st & u;
	t = t & su;

	st &= st2;
	st &= u;
	st &= su;

	// Or
	t = st | st2;
	t = st | u;
	t = t | su;

	st |= st2;
	st |= u;
	st |= su;

	// Xor
	t = st ^ st2;
	t = st ^ u;
	t = t ^ su;

	st ^= st2;
	st ^= u;
	st ^= su;

	// Comparisons
	// Less than
	b = st < su;
	b = st < u;
	b = u < st;
	b = st < su;

	// Less than or equal
	b = st <= su;
	b = st <= u;
	b = u <= st;
	b = st <= su;

	// Greater than
	b = st > su;
	b = st > u;
	b = u > st;
	b = st > su;

	// Greater than or equal
	b = st >= su;
	b = st >= u;
	b = u >= st;
	b = st >= su;

	// Equals
	b = st == su;
	b = st == u;
	b = u == st;
	b = st == su;
}

template <typename T>
void CompileSigned()
{
	SafeInt<T> st;
	T t = -st;
}

template <typename T>
void CompileType()
{
	// Test constructors
	SafeInt<T> s;
	SafeInt<T> i(Foo::Foo1);
	T t = 0;
	SafeInt<T> st(t);
	SafeInt<T> sb(false);

	// Special case casts
	bool b = (bool)s;
	wchar_t w = (wchar_t)s;
	size_t size = (size_t)s;
	float f = (float)s;
	double d = (double)s;
	long double ld = (long double)s;

	// Pointer operations
	T* p1 = s.Ptr();
	const T* p2 = s.Ptr();
	const T& r = s.Ref();
	T* p3 = &s;
	const T* p4 = &s;

	// Unary operators
	bool b2 = !st;
	t = +st;

	st++;
	++st;
	st--;
	--st;
	t = ~st;

	// Mixed operations
	CompiledMixedType<T, char>();
	CompiledMixedType<T, signed char>();
	CompiledMixedType<T, unsigned char>();
	CompiledMixedType<T, short>();
	CompiledMixedType<T, unsigned short>();
	CompiledMixedType<T, int>();
	CompiledMixedType<T, unsigned int>();
	CompiledMixedType<T, long>();
	CompiledMixedType<T, unsigned long>();
	CompiledMixedType<T, long long>();
	CompiledMixedType<T, unsigned long long>();
}

void CompileMe()
{
	CompileType<char>();
	CompileType<unsigned char>();
	CompileType<signed char>();

	CompileType<unsigned short>();
	CompileType<signed short>();
	CompileType<unsigned int>();
	CompileType<signed int>();
	CompileType<unsigned long>();
	CompileType<signed long>();
	CompileType<unsigned long long>();
	CompileType<signed long long>();

	CompileSigned<signed char>();
	CompileSigned<signed short>();
	CompileSigned<signed int>();
	CompileSigned<signed long>();
	CompileSigned<signed long long>();

}

namespace TestConstExpr
{
	template <typename T, typename U>
	_CONSTEXPR11 bool LessThanTest()
	{
		return
			(U)2 < SafeInt<T>(3) &&
			SafeInt<T>(4) < (U)5 &&
			SafeInt<T>(6) < SafeInt<U>(7);
	}

	template <typename T, typename U>
	_CONSTEXPR11 bool GreaterThanTest()
	{
		return
			(U)2 > SafeInt<T>(3) &&
			SafeInt<T>(4) > (U)5 &&
			SafeInt<T>(6) > SafeInt<U>(7);
	}

	template <typename T, typename U>
	_CONSTEXPR11 bool LessThanEqualTest()
	{
		return
			(U)2 <= SafeInt<T>(3) &&
			SafeInt<T>(4) <= (U)5 &&
			SafeInt<T>(6) <= SafeInt<U>(7);
	}

	template <typename T, typename U>
	_CONSTEXPR11 bool GreaterThanEqualTest()
	{
		return
			(U)2 >= SafeInt<T>(3) &&
			SafeInt<T>(4) >= (U)5 &&
			SafeInt<T>(6) >= SafeInt<U>(7);
	}

	template <typename T, typename U>
	_CONSTEXPR11 bool EqualTest()
	{
		return
			(U)2 == SafeInt<T>(3) &&
			SafeInt<T>(4) == (U)5 &&
			SafeInt<T>(6) == SafeInt<U>(7) &&
			true == SafeInt<T>(1) &&
			false == SafeInt<T>(0);
	}

	template <typename T, typename U>
	_CONSTEXPR11 bool NotEqualTest()
	{
		return
			(U)2 != SafeInt<T>(3) &&
			SafeInt<T>(4) != (U)5 &&
			SafeInt<T>(6) != SafeInt<U>(7) &&
			true != SafeInt<T>(1) &&
			false != SafeInt<T>(0);
	}

	template <typename T, typename U>
	void ComparisonTestTU()
	{
		static bool b1 = LessThanTest<T, U>();
		static bool b2 = LessThanEqualTest<T, U>();
		static bool b3 = GreaterThanTest<T, U>();
		static bool b4 = GreaterThanEqualTest<T, U>();
		static bool b5 = EqualTest<T, U>();
		static bool b6 = NotEqualTest<T, U>();
	}

	template <typename T> void ComparisonTestT()
	{
		ComparisonTestTU<T, char>();
		ComparisonTestTU<T, signed char>();
		ComparisonTestTU<T, unsigned char>();
		ComparisonTestTU<T, signed short>();
		ComparisonTestTU<T, unsigned short>();
		ComparisonTestTU<T, signed int>();
		ComparisonTestTU<T, unsigned int>();
		ComparisonTestTU<T, signed long>();
		ComparisonTestTU<T, unsigned long>();
		ComparisonTestTU<T, signed long long>();
		ComparisonTestTU<T, unsigned long long>();
	}

	template <typename T>
	_CONSTEXPR11 T ConstConstructor()
	{
		// Constructors, also add in the useless unary + operator
		return SafeInt<T>() + SafeInt<T>(1) + SafeInt<T>(false) + (+SafeInt<T>(3));
	}

	template <typename T>
	_CONSTEXPR11 bool ConstBool()
	{
		return (bool)SafeInt<T>(2) && !SafeInt<T>(0);
	}

	template <typename T>
	void ConstTestT()
	{
		static const T t = ConstConstructor<T>();
		static const bool b = ConstBool<T>();
	}

	void ConstExprTest()
	{
		ConstTestT<char>();
		ConstTestT<signed char>();
		ConstTestT<unsigned char>();
		ConstTestT<signed short>();
		ConstTestT<unsigned short>();
		ConstTestT<signed int>();
		ConstTestT<unsigned int>();
		ConstTestT<signed long>();
		ConstTestT<unsigned long>();
		ConstTestT<signed long long>();
		ConstTestT<unsigned long long>();

		// Catch the SafePtrDiff function, since it is marked. Can't think of a scenario for this being constexpr, though.
		const char* p1 = (char*)1;
		const char* p2 = nullptr;

		static const SafeInt<ptrdiff_t> pt = SafePtrDiff(p1, p2);

		// Now the comparison test ComparisonTestT
		ComparisonTestT<char>();
		ComparisonTestT<signed char>();
		ComparisonTestT<unsigned char>();
		ComparisonTestT<signed short>();
		ComparisonTestT<unsigned short>();
		ComparisonTestT<signed int>();
		ComparisonTestT<unsigned int>();
		ComparisonTestT<signed long>();
		ComparisonTestT<unsigned long>();
		ComparisonTestT<signed long long>();
		ComparisonTestT<unsigned long long>();

	}

}

/*
	Need to add tests for the miscellaneous helper functions
	Min, Max, Align, Swap
	Also need the pointer functions
*/
int main(int, char**)
{
	CompileMe();
	TestConstExpr::ConstExprTest();
	std::cout << "It compiles!\n";
	return 0;
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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 "bvh_intersector_stream_filters.h"
#include "bvh_intersector_stream.h"

namespace embree
{
  namespace isa
  {
    MAYBE_UNUSED static const size_t MAX_PACKET_STREAM_SIZE = MAX_INTERNAL_STREAM_SIZE / VSIZEX;

    __forceinline void RayStreamFilter::filterAOS(Scene* scene, RTCRay* _rayN, size_t N, size_t stride, IntersectContext* context, bool intersect)
    {
      RayStreamAOS rayN(_rayN);

      /* use fast path for coherent ray mode */
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
      /* all valid accels need to have a intersectN/occludedN */
      if (unlikely(isCoherent(context->user->flags) && scene->accels.validIsecN() ))
      {
        __aligned(64) RayK<VSIZEX> rays[MAX_PACKET_STREAM_SIZE];
        __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_PACKET_STREAM_SIZE];

        for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
        {
          const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);

          /* convert from AOS to SOA */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const vintx offset = vij * int(stride);
            const size_t packetIndex = j / VSIZEX;

            RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
            ray.tnear = select(valid, ray.tnear, zero);
            ray.tfar  = select(valid, ray.tfar,  neg_inf);

            rays[packetIndex] = ray;
            rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
          }

          /* trace stream */
          if (intersect)
            scene->intersectors.intersectN(rayPtrs, size, context);
          else
            scene->intersectors.occludedN(rayPtrs, size, context);

          /* convert from SOA to AOS */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const vintx offset = vij * int(stride);
            const size_t packetIndex = j / VSIZEX;
            rayN.setHitByOffset(valid, offset, rays[packetIndex], intersect);
          }
        }
      }
      else
#endif
      {
        /* fallback to packets */
        for (size_t i=0; i<N; i+=VSIZEX)
        {
          const vintx vi = vintx(int(i)) + vintx(step);
          vboolx valid = vi < vintx(int(N));
          const vintx offset = vi * int(stride);

          RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
          valid &= ray.tnear <= ray.tfar;

          if (intersect)
            scene->intersectors.intersect(valid, ray, context);
          else
            scene->intersectors.occluded(valid, ray, context);

          rayN.setHitByOffset(valid, offset, ray, intersect);
        }
      }
    }

    __forceinline void RayStreamFilter::filterAOP(Scene* scene, RTCRay** _rayN, size_t N, IntersectContext* context, bool intersect)
    {
      RayStreamAOP rayN(_rayN);

      /* use fast path for coherent ray mode */
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
      /* all valid accels need to have a intersectN/occludedN */
      if (unlikely(isCoherent(context->user->flags)  && scene->accels.validIsecN() ))
      {
        __aligned(64) RayK<VSIZEX> rays[MAX_PACKET_STREAM_SIZE];
        __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_PACKET_STREAM_SIZE];

        for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
        {
          const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);

          /* convert from AOP to SOA */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t packetIndex = j / VSIZEX;

            RayK<VSIZEX> ray = rayN.getRayByIndex(valid, i+j);
            ray.tnear = select(valid, ray.tnear, zero);
            ray.tfar  = select(valid, ray.tfar,  neg_inf);

            rays[packetIndex] = ray;
            rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
          }

          /* trace stream */
          if (intersect)
            scene->intersectors.intersectN(rayPtrs, size, context);
          else
            scene->intersectors.occludedN(rayPtrs, size, context);

          /* convert from SOA to AOP */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t packetIndex = j / VSIZEX;

            rayN.setHitByIndex(valid, i+j, rays[packetIndex], intersect);
          }
        }
      }
      else
#endif
      {
        /* fallback to packets */
        for (size_t i = 0; i < N; i += VSIZEX)
        {
          const vintx vi = vintx(int(i)) + vintx(step);
          vboolx valid = vi < vintx(int(N));

          RayK<VSIZEX> ray = rayN.getRayByIndex(valid, i);
          valid &= ray.tnear <= ray.tfar;

          if (intersect)
            scene->intersectors.intersect(valid, ray, context);
          else
            scene->intersectors.occluded(valid, ray, context);

          rayN.setHitByIndex(valid, i, ray, intersect);
        }
      }
    }

    __forceinline void RayStreamFilter::filterSOA(Scene* scene, char* rayData, size_t N, size_t numPackets, size_t stride, IntersectContext* context, bool intersect)
    {
      const size_t rayDataAlignment = (size_t)rayData % (VSIZEX*sizeof(float));
      const size_t offsetAlignment  = (size_t)stride  % (VSIZEX*sizeof(float));

      /* fast path for packets with the correct width and data alignment */
      if (likely(N == VSIZEX &&
                 !rayDataAlignment &&
                 !offsetAlignment))
      {
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
        /* all valid accels need to have a intersectN/occludedN */
        if (unlikely(isCoherent(context->user->flags) && scene->accels.validIsecN()))
        {
          __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / VSIZEX];

          size_t packetIndex = 0;
          for (size_t i = 0; i < numPackets; i++)
          {
            const size_t offset = i * stride;
            RayK<VSIZEX>& ray = *(RayK<VSIZEX>*)(rayData + offset);
            rayPtrs[packetIndex++] = &ray;

            /* trace as stream */
            if (unlikely(packetIndex == MAX_PACKET_STREAM_SIZE))
            {
              const size_t size = packetIndex*VSIZEX;
              if (intersect)
                scene->intersectors.intersectN(rayPtrs, size, context);
              else
                scene->intersectors.occludedN(rayPtrs, size, context);
              packetIndex = 0;
            }
          }

          /* flush remaining packets */
          if (unlikely(packetIndex > 0))
          {
            const size_t size = packetIndex*VSIZEX;
            if (intersect)
              scene->intersectors.intersectN(rayPtrs, size, context);
            else
              scene->intersectors.occludedN(rayPtrs, size, context);
          }
        }
        else
#endif
        {
          /* fallback to packets */
          for (size_t i = 0; i < numPackets; i++)
          {
            const size_t offset = i * stride;
            RayK<VSIZEX>& ray = *(RayK<VSIZEX>*)(rayData + offset);
            const vboolx valid = ray.tnear <= ray.tfar;

            if (intersect)
              scene->intersectors.intersect(valid, ray, context);
            else
              scene->intersectors.occluded(valid, ray, context);
          }
        }
      }
      else
      {
        /* fallback to packets for arbitrary packet size and alignment */
        for (size_t i = 0; i < numPackets; i++)
        {
          const size_t offsetN = i * stride;
          RayPacketSOA rayN(rayData + offsetN, N);

          for (size_t j = 0; j < N; j += VSIZEX)
          {
            const size_t offset = j * sizeof(float);
            vboolx valid = (vintx(int(j)) + vintx(step)) < vintx(N);

            RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
            valid &= ray.tnear <= ray.tfar;

            if (intersect)
              scene->intersectors.intersect(valid, ray, context);
            else
              scene->intersectors.occluded(valid, ray, context);

            rayN.setHitByOffset(valid, offset, ray, intersect);
          }
        }
      }
    }

    void RayStreamFilter::filterSOP(Scene* scene, const RTCRayNp& _rayN, size_t N, IntersectContext* context, bool intersect)
    {
      RayStreamSOP& rayN = *(RayStreamSOP*)&_rayN;

      /* use fast path for coherent ray mode */
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
      /* all valid accels need to have a intersectN/occludedN */
      if (unlikely(isCoherent(context->user->flags) && scene->accels.validIsecN()))
      {
        __aligned(64) RayK<VSIZEX> rays[MAX_PACKET_STREAM_SIZE];
        __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_PACKET_STREAM_SIZE];

        for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
        {
          const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);

          /* convert from SOP to SOA */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t offset = (i+j) * sizeof(float);
            const size_t packetIndex = j / VSIZEX;

            RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
            ray.tnear = select(valid, ray.tnear, zero);
            ray.tfar  = select(valid, ray.tfar,  neg_inf);

            rays[packetIndex] = ray;
            rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
          }

          /* trace stream */
          if (intersect)
            scene->intersectors.intersectN(rayPtrs, size, context);
          else
            scene->intersectors.occludedN(rayPtrs, size, context);

          /* convert from SOA to SOP */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t offset = (i+j) * sizeof(float);
            const size_t packetIndex = j / VSIZEX;

            rayN.setHitByOffset(valid, offset, rays[packetIndex], intersect);
          }
        }
      }
      else
#endif
      {
        /* fallback to packets */
        for (size_t i = 0; i < N; i += VSIZEX)
        {
          const vintx vi = vintx(int(i)) + vintx(step);
          vboolx valid = vi < vintx(int(N));
          const size_t offset = i * sizeof(float);

          RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
          valid &= ray.tnear <= ray.tfar;

          if (intersect)
            scene->intersectors.intersect(valid, ray, context);
          else
            scene->intersectors.occluded(valid, ray, context);

          rayN.setHitByOffset(valid, offset, ray, intersect);
        }
      }
    }

    RayStreamFilterFuncs rayStreamFilterFuncs() {
      return RayStreamFilterFuncs(RayStreamFilter::filterAOS, RayStreamFilter::filterAOP, RayStreamFilter::filterSOA, RayStreamFilter::filterSOP);
    }
  };
};
<commit_msg>removed validIsec checks in stream filters<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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 "bvh_intersector_stream_filters.h"
#include "bvh_intersector_stream.h"

namespace embree
{
  namespace isa
  {
    MAYBE_UNUSED static const size_t MAX_PACKET_STREAM_SIZE = MAX_INTERNAL_STREAM_SIZE / VSIZEX;

    __forceinline void RayStreamFilter::filterAOS(Scene* scene, RTCRay* _rayN, size_t N, size_t stride, IntersectContext* context, bool intersect)
    {
      RayStreamAOS rayN(_rayN);

      /* use fast path for coherent ray mode */
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
      /* all valid accels need to have a intersectN/occludedN */
      if (unlikely(isCoherent(context->user->flags)))
      {
        __aligned(64) RayK<VSIZEX> rays[MAX_PACKET_STREAM_SIZE];
        __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_PACKET_STREAM_SIZE];

        for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
        {
          const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);

          /* convert from AOS to SOA */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const vintx offset = vij * int(stride);
            const size_t packetIndex = j / VSIZEX;

            RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
            ray.tnear = select(valid, ray.tnear, zero);
            ray.tfar  = select(valid, ray.tfar,  neg_inf);

            rays[packetIndex] = ray;
            rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
          }

          /* trace stream */
          if (intersect)
            scene->intersectors.intersectN(rayPtrs, size, context);
          else
            scene->intersectors.occludedN(rayPtrs, size, context);

          /* convert from SOA to AOS */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const vintx offset = vij * int(stride);
            const size_t packetIndex = j / VSIZEX;
            rayN.setHitByOffset(valid, offset, rays[packetIndex], intersect);
          }
        }
      }
      else
#endif
      {
        /* fallback to packets */
        for (size_t i=0; i<N; i+=VSIZEX)
        {
          const vintx vi = vintx(int(i)) + vintx(step);
          vboolx valid = vi < vintx(int(N));
          const vintx offset = vi * int(stride);

          RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
          valid &= ray.tnear <= ray.tfar;

          if (intersect)
            scene->intersectors.intersect(valid, ray, context);
          else
            scene->intersectors.occluded(valid, ray, context);

          rayN.setHitByOffset(valid, offset, ray, intersect);
        }
      }
    }

    __forceinline void RayStreamFilter::filterAOP(Scene* scene, RTCRay** _rayN, size_t N, IntersectContext* context, bool intersect)
    {
      RayStreamAOP rayN(_rayN);

      /* use fast path for coherent ray mode */
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
      /* all valid accels need to have a intersectN/occludedN */
      if (unlikely(isCoherent(context->user->flags)))
      {
        __aligned(64) RayK<VSIZEX> rays[MAX_PACKET_STREAM_SIZE];
        __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_PACKET_STREAM_SIZE];

        for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
        {
          const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);

          /* convert from AOP to SOA */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t packetIndex = j / VSIZEX;

            RayK<VSIZEX> ray = rayN.getRayByIndex(valid, i+j);
            ray.tnear = select(valid, ray.tnear, zero);
            ray.tfar  = select(valid, ray.tfar,  neg_inf);

            rays[packetIndex] = ray;
            rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
          }

          /* trace stream */
          if (intersect)
            scene->intersectors.intersectN(rayPtrs, size, context);
          else
            scene->intersectors.occludedN(rayPtrs, size, context);

          /* convert from SOA to AOP */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t packetIndex = j / VSIZEX;

            rayN.setHitByIndex(valid, i+j, rays[packetIndex], intersect);
          }
        }
      }
      else
#endif
      {
        /* fallback to packets */
        for (size_t i = 0; i < N; i += VSIZEX)
        {
          const vintx vi = vintx(int(i)) + vintx(step);
          vboolx valid = vi < vintx(int(N));

          RayK<VSIZEX> ray = rayN.getRayByIndex(valid, i);
          valid &= ray.tnear <= ray.tfar;

          if (intersect)
            scene->intersectors.intersect(valid, ray, context);
          else
            scene->intersectors.occluded(valid, ray, context);

          rayN.setHitByIndex(valid, i, ray, intersect);
        }
      }
    }

    __forceinline void RayStreamFilter::filterSOA(Scene* scene, char* rayData, size_t N, size_t numPackets, size_t stride, IntersectContext* context, bool intersect)
    {
      const size_t rayDataAlignment = (size_t)rayData % (VSIZEX*sizeof(float));
      const size_t offsetAlignment  = (size_t)stride  % (VSIZEX*sizeof(float));

      /* fast path for packets with the correct width and data alignment */
      if (likely(N == VSIZEX &&
                 !rayDataAlignment &&
                 !offsetAlignment))
      {
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
        /* all valid accels need to have a intersectN/occludedN */
        if (unlikely(isCoherent(context->user->flags)))
        {
          __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_INTERNAL_STREAM_SIZE / VSIZEX];

          size_t packetIndex = 0;
          for (size_t i = 0; i < numPackets; i++)
          {
            const size_t offset = i * stride;
            RayK<VSIZEX>& ray = *(RayK<VSIZEX>*)(rayData + offset);
            rayPtrs[packetIndex++] = &ray;

            /* trace as stream */
            if (unlikely(packetIndex == MAX_PACKET_STREAM_SIZE))
            {
              const size_t size = packetIndex*VSIZEX;
              if (intersect)
                scene->intersectors.intersectN(rayPtrs, size, context);
              else
                scene->intersectors.occludedN(rayPtrs, size, context);
              packetIndex = 0;
            }
          }

          /* flush remaining packets */
          if (unlikely(packetIndex > 0))
          {
            const size_t size = packetIndex*VSIZEX;
            if (intersect)
              scene->intersectors.intersectN(rayPtrs, size, context);
            else
              scene->intersectors.occludedN(rayPtrs, size, context);
          }
        }
        else
#endif
        {
          /* fallback to packets */
          for (size_t i = 0; i < numPackets; i++)
          {
            const size_t offset = i * stride;
            RayK<VSIZEX>& ray = *(RayK<VSIZEX>*)(rayData + offset);
            const vboolx valid = ray.tnear <= ray.tfar;

            if (intersect)
              scene->intersectors.intersect(valid, ray, context);
            else
              scene->intersectors.occluded(valid, ray, context);
          }
        }
      }
      else
      {
        /* fallback to packets for arbitrary packet size and alignment */
        for (size_t i = 0; i < numPackets; i++)
        {
          const size_t offsetN = i * stride;
          RayPacketSOA rayN(rayData + offsetN, N);

          for (size_t j = 0; j < N; j += VSIZEX)
          {
            const size_t offset = j * sizeof(float);
            vboolx valid = (vintx(int(j)) + vintx(step)) < vintx(N);

            RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
            valid &= ray.tnear <= ray.tfar;

            if (intersect)
              scene->intersectors.intersect(valid, ray, context);
            else
              scene->intersectors.occluded(valid, ray, context);

            rayN.setHitByOffset(valid, offset, ray, intersect);
          }
        }
      }
    }

    void RayStreamFilter::filterSOP(Scene* scene, const RTCRayNp& _rayN, size_t N, IntersectContext* context, bool intersect)
    {
      RayStreamSOP& rayN = *(RayStreamSOP*)&_rayN;

      /* use fast path for coherent ray mode */
#if defined(__AVX__) && ENABLE_COHERENT_STREAM_PATH == 1
      /* all valid accels need to have a intersectN/occludedN */
      if (unlikely(isCoherent(context->user->flags)))
      {
        __aligned(64) RayK<VSIZEX> rays[MAX_PACKET_STREAM_SIZE];
        __aligned(64) RayK<VSIZEX>* rayPtrs[MAX_PACKET_STREAM_SIZE];

        for (size_t i = 0; i < N; i += MAX_INTERNAL_STREAM_SIZE)
        {
          const size_t size = min(N - i, MAX_INTERNAL_STREAM_SIZE);

          /* convert from SOP to SOA */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t offset = (i+j) * sizeof(float);
            const size_t packetIndex = j / VSIZEX;

            RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
            ray.tnear = select(valid, ray.tnear, zero);
            ray.tfar  = select(valid, ray.tfar,  neg_inf);

            rays[packetIndex] = ray;
            rayPtrs[packetIndex] = &rays[packetIndex]; // rayPtrs might get reordered for occludedN
          }

          /* trace stream */
          if (intersect)
            scene->intersectors.intersectN(rayPtrs, size, context);
          else
            scene->intersectors.occludedN(rayPtrs, size, context);

          /* convert from SOA to SOP */
          for (size_t j = 0; j < size; j += VSIZEX)
          {
            const vintx vij = vintx(int(i+j)) + vintx(step);
            const vboolx valid = vij < vintx(int(N));
            const size_t offset = (i+j) * sizeof(float);
            const size_t packetIndex = j / VSIZEX;

            rayN.setHitByOffset(valid, offset, rays[packetIndex], intersect);
          }
        }
      }
      else
#endif
      {
        /* fallback to packets */
        for (size_t i = 0; i < N; i += VSIZEX)
        {
          const vintx vi = vintx(int(i)) + vintx(step);
          vboolx valid = vi < vintx(int(N));
          const size_t offset = i * sizeof(float);

          RayK<VSIZEX> ray = rayN.getRayByOffset(valid, offset);
          valid &= ray.tnear <= ray.tfar;

          if (intersect)
            scene->intersectors.intersect(valid, ray, context);
          else
            scene->intersectors.occluded(valid, ray, context);

          rayN.setHitByOffset(valid, offset, ray, intersect);
        }
      }
    }

    RayStreamFilterFuncs rayStreamFilterFuncs() {
      return RayStreamFilterFuncs(RayStreamFilter::filterAOS, RayStreamFilter::filterAOP, RayStreamFilter::filterSOA, RayStreamFilter::filterSOP);
    }
  };
};
<|endoftext|>


<commit_before>/*
  Copyright © 2014 Jesse 'Jeaye' Wilkerson
  See licensing at:
    http://opensource.org/licenses/BSD-3-Clause

  File: detail/escape.hpp
  Author: Jesse 'Jeaye' Wilkerson
*/

#pragma once

#include <string>
#include <algorithm>

namespace jeayeson
{
  namespace detail
  {
    inline bool should_escape(char const c)
    {
      return c == '\"' || c == '\\' || c == '/' ||
             c == '\b' || c == '\f' || c == '\n' ||
             c == '\r' || c == '\t';
    }

    inline std::string escape(std::string str)
    {
      for(std::size_t i{}; i < str.size(); )
      {
        auto const found(std::find_if(std::next(str.begin(), i),
                                      str.end(), &should_escape));
        if(found == str.end())
        { break; }

        auto const dist(std::distance(str.begin(), found));
        str.replace(dist, 1, "\\\"");
        i = dist + 2;
      }
      return str;
    }
  }
}
<commit_msg>Consolidate string replacement #9<commit_after>/*
  Copyright © 2014 Jesse 'Jeaye' Wilkerson
  See licensing at:
    http://opensource.org/licenses/BSD-3-Clause

  File: detail/escape.hpp
  Author: Jesse 'Jeaye' Wilkerson
*/

#pragma once

#include <string>
#include <algorithm>

namespace jeayeson
{
  namespace detail
  {
    inline bool should_escape(char const c)
    {
      return c == '\"' || c == '\\' || c == '/' ||
             c == '\b' || c == '\f' || c == '\n' ||
             c == '\r' || c == '\t';
    }

    inline std::string escape(std::string str)
    {
      for(std::size_t i{}; i < str.size(); )
      {
        auto const found(std::find_if(std::next(str.begin(), i),
                                      str.end(), &should_escape));
        if(found == str.end())
        { break; }

        str.replace(found, std::next(found), "\\\"");
        i = std::distance(str.begin(), found) + 2;
      }
      return str;
    }
  }
}
<|endoftext|>