<commit_before>/*
 * (C) Copyright 2013 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */
#include <libsoup/soup.h>
#include "KmsHttpPost.h"

#define OBJECT_NAME "HttpPost"
#define MIME_MULTIPART_FORM_DATA "multipart/form-data"

#define GST_CAT_DEFAULT kms_http_post_debug_category
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

#define KMS_HTTP_POST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KMS_TYPE_HTTP_POST, KmsHttpPostPrivate))
typedef struct _KmsHttpPostMultipart {
  gchar *boundary;
  gboolean got_boundary;
  gboolean got_last_boundary;
} KmsHttpPostMultipart;

struct _KmsHttpPostPrivate {
  KmsHttpPostMultipart *multipart;
  SoupMessage *msg;
  gulong handler_id;
};

/* class initialization */

G_DEFINE_TYPE_WITH_CODE (KmsHttpPost, kms_http_post,
                         G_TYPE_OBJECT,
                         GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, OBJECT_NAME,
                             0, "debug category for " OBJECT_NAME " element") )
/* properties */
enum {
  PROP_0,

  PROP_MESSAGE,
  N_PROPERTIES
};

#define KMS_HTTP_PORT_DEFAULT_MESSAGE NULL

static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };

/* signals */
enum {
  GOT_DATA,
  LAST_SIGNAL
};

static guint obj_signals[LAST_SIGNAL] = { 0 };

static void
got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, gpointer data)
{
  GST_DEBUG ("TODO: Process data");
}

static void
kms_http_post_destroy_multipart (KmsHttpPost *self)
{
  if (self->priv->multipart == NULL)
    return;

  if (self->priv->multipart->boundary != NULL)
    g_free (self->priv->multipart->boundary);

  g_slice_free (KmsHttpPostMultipart, self->priv->multipart);
  self->priv->multipart = NULL;
}

static void
kms_http_post_init_multipart (KmsHttpPost *self)
{
  if (self->priv->multipart != NULL) {
    GST_WARNING ("Multipart data is already initialized");
    kms_http_post_destroy_multipart (self);
  }

  self->priv->multipart = g_slice_new0 (KmsHttpPostMultipart);
}

static void
kms_http_post_configure_msg (KmsHttpPost *self)
{
  const gchar *content_type;
  GHashTable *params = NULL;

  content_type =
    soup_message_headers_get_content_type (self->priv->msg->request_headers,
        &params);

  if (content_type == NULL) {
    GST_WARNING ("Content-type header is not present in request");
    soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE);
    goto end;
  }

  if (g_strcmp0 (content_type, MIME_MULTIPART_FORM_DATA) == 0) {
    kms_http_post_init_multipart (self);
    self->priv->multipart->boundary = g_strdup ( (gchar *) g_hash_table_lookup (params,
                                      "boundary") );

    if (self->priv->multipart->boundary == NULL) {
      GST_WARNING ("Malformed multipart POST request");
      kms_http_post_destroy_multipart (self);
      soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE);
      goto end;
    }
  }

  soup_message_set_status (self->priv->msg, SOUP_STATUS_OK);

  /* Get chunks without filling-in body's data field after */
  /* the body is fully sent/received */
  soup_message_body_set_accumulate (self->priv->msg->request_body, FALSE);

  self->priv->handler_id = g_signal_connect (self->priv->msg, "got-chunk",
                           G_CALLBACK (got_chunk_cb), self);
end:

  if (params != NULL)
    g_hash_table_destroy (params);
}

static void
kms_http_post_release_message (KmsHttpPost *self)
{
  if (self->priv->msg == NULL)
    return;

  if (self->priv->handler_id != 0L) {
    g_signal_handler_disconnect (self->priv->msg, self->priv->handler_id);
    self->priv->handler_id = 0L;
  }

  g_object_unref (self->priv->msg);
  self->priv->msg = NULL;
}

static void
kms_http_post_set_property (GObject *obj, guint prop_id,
                            const GValue *value, GParamSpec *pspec)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  switch (prop_id) {
  case PROP_MESSAGE:
    kms_http_post_release_message (self);
    kms_http_post_destroy_multipart (self);
    self->priv->msg = SOUP_MESSAGE (g_object_ref (g_value_get_object (value) ) );
    kms_http_post_configure_msg (self);
    break;

  default:
    /* We don't have any other property... */
    G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
    break;
  }
}

static void
kms_http_post_get_property (GObject *obj, guint prop_id, GValue *value,
                            GParamSpec *pspec)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  switch (prop_id) {
  case PROP_MESSAGE:
    g_value_set_object (value, self->priv->msg);
    break;

  default:
    /* We don't have any other property... */
    G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
    break;
  }
}

static void
kms_http_post_dispose (GObject *obj)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  kms_http_post_release_message (self);

  /* Chain up to the parent class */
  G_OBJECT_CLASS (kms_http_post_parent_class)->dispose (obj);
}

static void
kms_http_post_finalize (GObject *obj)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  kms_http_post_destroy_multipart (self);

  /* Chain up to the parent class */
  G_OBJECT_CLASS (kms_http_post_parent_class)->finalize (obj);
}

static void
kms_http_post_class_init (KmsHttpPostClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->set_property = kms_http_post_set_property;
  gobject_class->get_property = kms_http_post_get_property;
  gobject_class->dispose = kms_http_post_dispose;
  gobject_class->finalize = kms_http_post_finalize;

  obj_properties[PROP_MESSAGE] =
    g_param_spec_object ("soup-message",
                         "Soup message object",
                         "Message to get data from",
                         SOUP_TYPE_MESSAGE,
                         (GParamFlags) (G_PARAM_READWRITE) );

  g_object_class_install_properties (gobject_class,
                                     N_PROPERTIES,
                                     obj_properties);

  obj_signals[GOT_DATA] =
    g_signal_new ("got-data",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (KmsHttpPostClass, got_data), NULL, NULL,
                  g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);

  /* Registers a private structure for an instantiatable type */
  g_type_class_add_private (klass, sizeof (KmsHttpPostPrivate) );
}

static void
kms_http_post_init (KmsHttpPost *self)
{
  self->priv = KMS_HTTP_POST_GET_PRIVATE (self);
  self->priv->handler_id = 0L;
}<commit_msg>KmsHttpPost: Read boundary<commit_after>/*
 * (C) Copyright 2013 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * 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.
 *
 */
#include <string.h>
#include <libsoup/soup.h>
#include "KmsHttpPost.h"

#define OBJECT_NAME "HttpPost"
#define MIME_MULTIPART_FORM_DATA "multipart/form-data"

#define GST_CAT_DEFAULT kms_http_post_debug_category
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);

#define KMS_HTTP_POST_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), KMS_TYPE_HTTP_POST, KmsHttpPostPrivate))

typedef enum {
  MULTIPART_FIND_BOUNDARY,
  MULTIPART_READ_HEADERS
} ParseState;

typedef struct _KmsHttpPostMultipart {
  gchar *boundary;
  ParseState state;
  gchar *tmp_buff;
  guint len;
} KmsHttpPostMultipart;

struct _KmsHttpPostPrivate {
  KmsHttpPostMultipart *multipart;
  SoupMessage *msg;
  gulong handler_id;
};

/* class initialization */

G_DEFINE_TYPE_WITH_CODE (KmsHttpPost, kms_http_post,
                         G_TYPE_OBJECT,
                         GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, OBJECT_NAME,
                             0, "debug category for " OBJECT_NAME " element") )
/* properties */
enum {
  PROP_0,

  PROP_MESSAGE,
  N_PROPERTIES
};

#define KMS_HTTP_PORT_DEFAULT_MESSAGE NULL

static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };

/* signals */
enum {
  GOT_DATA,
  LAST_SIGNAL
};

static guint obj_signals[LAST_SIGNAL] = { 0 };

static void
kms_http_post_concat_previous_buffer (KmsHttpPost *self, const char **start,
                                      const char **end)
{
  if (self->priv->multipart->tmp_buff == NULL)
    return;

  self->priv->multipart->tmp_buff = (char *) g_realloc (
                                      self->priv->multipart->tmp_buff,
                                      self->priv->multipart->len + (*end - *start) );
  memmove (self->priv->multipart->tmp_buff + self->priv->multipart->len,
           *start, *end - *start);
  self->priv->multipart->len += (*end - *start);

  *start = self->priv->multipart->tmp_buff;
  *end = self->priv->multipart->tmp_buff + self->priv->multipart->len;
}

static void
kms_http_post_find_boundary (KmsHttpPost *self, const char **start,
                             const char **end, const char *boundary, int boundary_len)
{
  const char *b;

  if (self->priv->multipart->tmp_buff != NULL)
    kms_http_post_concat_previous_buffer (self, start, end);

  for (b = (const char *) memchr (*start, '-', *end - *start); b != NULL;
       b = (const char *) memchr (b + 2, '-', *end - (b + 2) ) ) {

    if (b + boundary_len + 4 > *end) {
      /* boundary does not fit in this buffer */
      gchar *mem = NULL;

      if (self->priv->multipart->tmp_buff != NULL)
        mem = self->priv->multipart->tmp_buff;

      self->priv->multipart->tmp_buff = (gchar *) g_memdup (b, *end - b);
      self->priv->multipart->len = *end - b;

      if (mem != NULL)
        g_free (mem);

      return;
    }

    /* Check for "--boundary" */
    if (b[1] != '-' ||
        memcmp (b + 2, boundary, boundary_len) != 0)
      continue;

    /* Check for "--" or "\r\n" after boundary */
    if ( (b[boundary_len + 2] == '-' && b[boundary_len + 3] == '-') ||
         (b[boundary_len + 2] == '\r' && b[boundary_len + 3] == '\n') ) {
      self->priv->multipart->state = MULTIPART_READ_HEADERS;

      if (*end <= b + boundary_len + 4) {
        /* Free temporal buffer */
        break;
      }

      *start = b + boundary_len + 4;
      return;
    }
  }

  if (self->priv->multipart->tmp_buff != NULL) {
    g_free (self->priv->multipart->tmp_buff);
    self->priv->multipart->tmp_buff = NULL;
  }
}

static void
kms_http_post_parse_multipart_data (KmsHttpPost *self, const char *data,
                                    const char *end)
{
  switch (self->priv->multipart->state) {
  case MULTIPART_FIND_BOUNDARY:
    /* skip preamble */
    kms_http_post_find_boundary (self, &data, &end,
                                 self->priv->multipart->boundary,
                                 strlen (self->priv->multipart->boundary) );

    if (self->priv->multipart->state == MULTIPART_FIND_BOUNDARY)
      break;

  case MULTIPART_READ_HEADERS:
    /* TODO: Read headers */
    ;
  }
}

static void
got_chunk_cb (SoupMessage *msg, SoupBuffer *chunk, gpointer data)
{
  KmsHttpPost *self = KMS_HTTP_POST (data);

  if (self->priv->multipart == NULL)
    GST_DEBUG ("Process raw data");
  else
    kms_http_post_parse_multipart_data (self, chunk->data,
                                        chunk->data + chunk->length);
}

static void
kms_http_post_destroy_multipart (KmsHttpPost *self)
{
  if (self->priv->multipart == NULL)
    return;

  if (self->priv->multipart->boundary != NULL)
    g_free (self->priv->multipart->boundary);

  if (self->priv->multipart->tmp_buff != NULL)
    g_free (self->priv->multipart->tmp_buff);

  g_slice_free (KmsHttpPostMultipart, self->priv->multipart);
  self->priv->multipart = NULL;
}

static void
kms_http_post_init_multipart (KmsHttpPost *self)
{
  if (self->priv->multipart != NULL) {
    GST_WARNING ("Multipart data is already initialized");
    kms_http_post_destroy_multipart (self);
  }

  self->priv->multipart = g_slice_new0 (KmsHttpPostMultipart);
}

static void
kms_http_post_configure_msg (KmsHttpPost *self)
{
  const gchar *content_type;
  GHashTable *params = NULL;

  content_type =
    soup_message_headers_get_content_type (self->priv->msg->request_headers,
        &params);

  if (content_type == NULL) {
    GST_WARNING ("Content-type header is not present in request");
    soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE);
    goto end;
  }

  if (g_strcmp0 (content_type, MIME_MULTIPART_FORM_DATA) == 0) {
    kms_http_post_init_multipart (self);
    self->priv->multipart->boundary = g_strdup ( (gchar *) g_hash_table_lookup (params,
                                      "boundary") );

    if (self->priv->multipart->boundary == NULL) {
      GST_WARNING ("Malformed multipart POST request");
      kms_http_post_destroy_multipart (self);
      soup_message_set_status (self->priv->msg, SOUP_STATUS_NOT_ACCEPTABLE);
      goto end;
    }
  }

  soup_message_set_status (self->priv->msg, SOUP_STATUS_OK);

  /* Get chunks without filling-in body's data field after */
  /* the body is fully sent/received */
  soup_message_body_set_accumulate (self->priv->msg->request_body, FALSE);

  self->priv->handler_id = g_signal_connect (self->priv->msg, "got-chunk",
                           G_CALLBACK (got_chunk_cb), self);
end:

  if (params != NULL)
    g_hash_table_destroy (params);
}

static void
kms_http_post_release_message (KmsHttpPost *self)
{
  if (self->priv->msg == NULL)
    return;

  if (self->priv->handler_id != 0L) {
    g_signal_handler_disconnect (self->priv->msg, self->priv->handler_id);
    self->priv->handler_id = 0L;
  }

  g_object_unref (self->priv->msg);
  self->priv->msg = NULL;
}

static void
kms_http_post_set_property (GObject *obj, guint prop_id,
                            const GValue *value, GParamSpec *pspec)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  switch (prop_id) {
  case PROP_MESSAGE:
    kms_http_post_release_message (self);
    kms_http_post_destroy_multipart (self);
    self->priv->msg = SOUP_MESSAGE (g_object_ref (g_value_get_object (value) ) );
    kms_http_post_configure_msg (self);
    break;

  default:
    /* We don't have any other property... */
    G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
    break;
  }
}

static void
kms_http_post_get_property (GObject *obj, guint prop_id, GValue *value,
                            GParamSpec *pspec)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  switch (prop_id) {
  case PROP_MESSAGE:
    g_value_set_object (value, self->priv->msg);
    break;

  default:
    /* We don't have any other property... */
    G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec);
    break;
  }
}

static void
kms_http_post_dispose (GObject *obj)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  kms_http_post_release_message (self);

  /* Chain up to the parent class */
  G_OBJECT_CLASS (kms_http_post_parent_class)->dispose (obj);
}

static void
kms_http_post_finalize (GObject *obj)
{
  KmsHttpPost *self = KMS_HTTP_POST (obj);

  kms_http_post_destroy_multipart (self);

  /* Chain up to the parent class */
  G_OBJECT_CLASS (kms_http_post_parent_class)->finalize (obj);
}

static void
kms_http_post_class_init (KmsHttpPostClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->set_property = kms_http_post_set_property;
  gobject_class->get_property = kms_http_post_get_property;
  gobject_class->dispose = kms_http_post_dispose;
  gobject_class->finalize = kms_http_post_finalize;

  obj_properties[PROP_MESSAGE] =
    g_param_spec_object ("soup-message",
                         "Soup message object",
                         "Message to get data from",
                         SOUP_TYPE_MESSAGE,
                         (GParamFlags) (G_PARAM_READWRITE) );

  g_object_class_install_properties (gobject_class,
                                     N_PROPERTIES,
                                     obj_properties);

  obj_signals[GOT_DATA] =
    g_signal_new ("got-data",
                  G_TYPE_FROM_CLASS (klass),
                  G_SIGNAL_RUN_LAST,
                  G_STRUCT_OFFSET (KmsHttpPostClass, got_data), NULL, NULL,
                  g_cclosure_marshal_VOID__VOID, G_TYPE_NONE, 0);

  /* Registers a private structure for an instantiatable type */
  g_type_class_add_private (klass, sizeof (KmsHttpPostPrivate) );
}

static void
kms_http_post_init (KmsHttpPost *self)
{
  self->priv = KMS_HTTP_POST_GET_PRIVATE (self);
  self->priv->handler_id = 0L;
}<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

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

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

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

#include "ltac/Statement.hpp"

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

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

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

//The data-flow problems
#include "mtac/GlobalOptimizations.hpp"
#include "mtac/ConstantPropagationProblem.hpp"
#include "mtac/OffsetConstantPropagationProblem.hpp"
#include "mtac/CommonSubexpressionElimination.hpp"

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

using namespace eddic;

namespace eddic {
namespace mtac {

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

struct all_basic_optimizations {};

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

    typedef basic_passes sub_passes;
};

typedef boost::mpl::vector<
        mtac::ArithmeticIdentities*,
        mtac::ReduceInStrength*,
        mtac::ConstantFolding*,
        mtac::conditional_propagation*,
        mtac::ConstantPropagationProblem*,
        mtac::OffsetConstantPropagationProblem*,
        mtac::CommonSubexpressionElimination*,
        mtac::PointerPropagation*,
        mtac::MathPropagation*,
        mtac::optimize_branches*,
        mtac::remove_dead_basic_blocks*,
        mtac::merge_basic_blocks*,
        mtac::dead_code_elimination*,
        mtac::remove_aliases*,
        mtac::loop_analysis*,
        mtac::loop_invariant_code_motion*,
        mtac::loop_induction_variables_optimization*,
        mtac::remove_empty_loops*,
        mtac::complete_loop_peeling*,
        mtac::loop_unrolling*,
        mtac::clean_variables*
    > passes;

struct all_optimizations {};

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

    typedef passes sub_passes;
};

}
}

namespace {

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

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

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

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

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

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

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

template <bool B, typename T = void>
struct disable_if {
    typedef T type;
};

template <typename T>
struct disable_if<true,T> {
    //SFINAE
};

struct pass_runner {
    bool optimized = false;

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

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

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

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){
        for(auto& block : *function){
            auto it = iterate(block->statements);

            while(it.has_next()){
                if(it->op == mtac::Operator::NOP){
                    it.erase();
                    continue;
                }

                ++it;
            }
        }
    }

    template<typename Pass>
    inline typename std::enable_if<!(mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP), void>::type remove_nop(){
        //NOP
    }

    template<typename Pass>
    inline void apply_todo(){
        remove_nop<Pass>();
    }

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

    template<typename Pass>
    inline typename disable_if<need_pool<Pass>::value, void>::type set_pool(Pass&){
        //NOP
    }

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

    template<typename Pass>
    inline typename disable_if<need_platform<Pass>::value, void>::type set_platform(Pass&){
        //NOP
    }

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

    template<typename Pass>
    inline typename disable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass&){
        //NOP
    }

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

    template<typename Pass>
    inline typename disable_if<need_program<Pass>::value, Pass>::type construct(){
        return Pass();
    }

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

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

        return pass;
    }

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

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

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

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

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

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

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

        return false;
    }

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

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

        return visitor.optimized;
    }

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

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

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

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

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

            optimized |= visitor.optimized;
        }

        return optimized;
    }

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

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

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

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

            optimized |= visitor.optimized;
        }

        return optimized;
    }

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

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

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

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

        if(has_to_be_run(pass)){
            bool local = false;
            {
                PerfsTimer perfs_timer(mtac::pass_traits<Pass>::name());
                timing_timer timer(system, mtac::pass_traits<Pass>::name());

                local = apply<Pass>(pass);
            }

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

            debug_local<Pass>(local);

            optimized |= local;
        }
    }
};

} //end of anonymous namespace

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

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

    if(configuration->option_defined("fglobal-optimization")){
        //Apply Interprocedural Optimizations
        pass_runner runner(program, string_pool, configuration, platform, program.context->timing());
        do{
            runner.optimized = false;
            boost::mpl::for_each<ipa_passes>(boost::ref(runner));
        } while(runner.optimized);
    } else {
        //Even if global optimizations are disabled, perform basic optimization (only constant folding)
        pass_runner runner(program, string_pool, configuration, platform, program.context->timing());
        boost::mpl::for_each<ipa_basic_passes>(boost::ref(runner));
    }
}
<commit_msg>Include TODO in the timing of the passes<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

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

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

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

#include "ltac/Statement.hpp"

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

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

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

//The data-flow problems
#include "mtac/GlobalOptimizations.hpp"
#include "mtac/ConstantPropagationProblem.hpp"
#include "mtac/OffsetConstantPropagationProblem.hpp"
#include "mtac/CommonSubexpressionElimination.hpp"

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

using namespace eddic;

namespace eddic {
namespace mtac {

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

struct all_basic_optimizations {};

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

    typedef basic_passes sub_passes;
};

typedef boost::mpl::vector<
        mtac::ArithmeticIdentities*,
        mtac::ReduceInStrength*,
        mtac::ConstantFolding*,
        mtac::conditional_propagation*,
        mtac::ConstantPropagationProblem*,
        mtac::OffsetConstantPropagationProblem*,
        mtac::CommonSubexpressionElimination*,
        mtac::PointerPropagation*,
        mtac::MathPropagation*,
        mtac::optimize_branches*,
        mtac::remove_dead_basic_blocks*,
        mtac::merge_basic_blocks*,
        mtac::dead_code_elimination*,
        mtac::remove_aliases*,
        mtac::loop_analysis*,
        mtac::loop_invariant_code_motion*,
        mtac::loop_induction_variables_optimization*,
        mtac::remove_empty_loops*,
        mtac::complete_loop_peeling*,
        mtac::loop_unrolling*,
        mtac::clean_variables*
    > passes;

struct all_optimizations {};

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

    typedef passes sub_passes;
};

}
}

namespace {

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

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

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

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

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

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

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

template <bool B, typename T = void>
struct disable_if {
    typedef T type;
};

template <typename T>
struct disable_if<true,T> {
    //SFINAE
};

struct pass_runner {
    bool optimized = false;

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

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

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

    template<typename Pass>
    inline typename std::enable_if<mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP, void>::type remove_nop(){
        for(auto& block : *function){
            auto it = iterate(block->statements);

            while(it.has_next()){
                if(it->op == mtac::Operator::NOP){
                    it.erase();
                    continue;
                }

                ++it;
            }
        }
    }

    template<typename Pass>
    inline typename std::enable_if<!(mtac::pass_traits<Pass>::todo_after_flags & mtac::TODO_REMOVE_NOP), void>::type remove_nop(){
        //NOP
    }

    template<typename Pass>
    inline void apply_todo(){
        remove_nop<Pass>();
    }

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

    template<typename Pass>
    inline typename disable_if<need_pool<Pass>::value, void>::type set_pool(Pass&){
        //NOP
    }

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

    template<typename Pass>
    inline typename disable_if<need_platform<Pass>::value, void>::type set_platform(Pass&){
        //NOP
    }

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

    template<typename Pass>
    inline typename disable_if<need_configuration<Pass>::value, void>::type set_configuration(Pass&){
        //NOP
    }

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

    template<typename Pass>
    inline typename disable_if<need_program<Pass>::value, Pass>::type construct(){
        return Pass();
    }

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

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

        return pass;
    }

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

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

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

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

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

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

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

        return false;
    }

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

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

        return visitor.optimized;
    }

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

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

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

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

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

            optimized |= visitor.optimized;
        }

        return optimized;
    }

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

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

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

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

            optimized |= visitor.optimized;
        }

        return optimized;
    }

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

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

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

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

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

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

            debug_local<Pass>(local);

            optimized |= local;
        }
    }
};

} //end of anonymous namespace

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

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

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


<commit_before><commit_msg>something<commit_after><|endoftext|>


<commit_before>#include "ospray/common/OSPCommon.h"
#include "ospray/common/Thread.h"
#include "common/sys/sync/barrier.h"

namespace ospray {

  using namespace std;

  volatile size_t sum = 0;
  volatile int nextFreeID = 0;
  volatile bool done = 0;
  double timeToRun = 1.f;
  embree::MutexSys mutex;
  embree::BarrierSys barrier;

  struct MyThread : public Thread {
    MyThread(int numThreads)
    {
    }

    virtual void run()
    {
      mutex.lock();
      int myID = nextFreeID++;
      mutex.unlock();

      barrier.wait();
      double t0 = getSysTime();
      int lastPing = 0;
      while (1) {
        barrier.wait();
        if (done) {
          break;
        }
        mutex.lock();
        sum += 1;
        mutex.unlock();
        barrier.wait();

        double t1 = getSysTime();

        if (myID == 0) {
          int numSecs = int(t1-t0);
          if (numSecs > lastPing) {
            printf("after t=%5.f2s: num ops =%8li, that's %f ops/sec\n",
                   t1-t0,sum,sum/(t1-t0));
          }
        }
        if (myID == 0 && (t1 - t0) >= timeToRun)
          done = true;
      }

      if (myID == 0)
        cout << "total number of OPs: " << sum << endl;
    }

  };

  extern "C" int main(int ac, char **av)
  {
    int numThreads = 10;
    int firstThreadID = 1;

    for (int i=1;i<ac;i++) {
      const std::string arg = av[i];
      if (arg == "-nt")
        numThreads = atoi(av[++i]);
      else if (arg == "-ft")
        firstThreadID = atoi(av[++i]);
      else if (arg == "-ns")
        timeToRun = atof(av[++i]);
      else
        throw std::runtime_error("unknown parameter '"+arg+"'");
    }

    barrier.init(numThreads);
    MyThread **thread = new MyThread *[numThreads];
    for (int i=0;i<numThreads;i++) {
      thread[i] = new MyThread(numThreads);
      thread[i]->start(firstThreadID+i);
    }

    for (int i=0;i<numThreads;i++)
      thread[i]->join();
    return 0;
  }

}
<commit_msg>bugfix in output<commit_after>#include "ospray/common/OSPCommon.h"
#include "ospray/common/Thread.h"
#include "common/sys/sync/barrier.h"

namespace ospray {

  using namespace std;

  volatile size_t sum = 0;
  volatile int nextFreeID = 0;
  volatile bool done = 0;
  double timeToRun = 1.f;
  embree::MutexSys mutex;
  embree::BarrierSys barrier;

  struct MyThread : public Thread {
    MyThread(int numThreads)
    {
    }

    virtual void run()
    {
      mutex.lock();
      int myID = nextFreeID++;
      mutex.unlock();

      barrier.wait();
      double t0 = getSysTime();
      int lastPing = 0;
      while (1) {
        barrier.wait();
        if (done) {
          break;
        }
        mutex.lock();
        sum += 1;
        mutex.unlock();
        barrier.wait();

        double t1 = getSysTime();

        if (myID == 0) {
          int numSecs = int(t1-t0);
          if (numSecs > lastPing) {
            printf("after t=%5.f2s: num ops =%8li, that's %f ops/sec\n",
                   t1-t0,sum,sum/(t1-t0));
            lastPing = numSecs;
          }
        }
        if (myID == 0 && (t1 - t0) >= timeToRun)
          done = true;
      }

      if (myID == 0)
        cout << "total number of OPs: " << sum << endl;
    }

  };

  extern "C" int main(int ac, char **av)
  {
    int numThreads = 10;
    int firstThreadID = 1;

    for (int i=1;i<ac;i++) {
      const std::string arg = av[i];
      if (arg == "-nt")
        numThreads = atoi(av[++i]);
      else if (arg == "-ft")
        firstThreadID = atoi(av[++i]);
      else if (arg == "-ns")
        timeToRun = atof(av[++i]);
      else
        throw std::runtime_error("unknown parameter '"+arg+"'");
    }

    barrier.init(numThreads);
    MyThread **thread = new MyThread *[numThreads];
    for (int i=0;i<numThreads;i++) {
      thread[i] = new MyThread(numThreads);
      thread[i]->start(firstThreadID+i);
    }

    for (int i=0;i<numThreads;i++)
      thread[i]->join();
    return 0;
  }

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: regexp.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 15:19:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _UCB_REGEXP_HXX_
#include <regexp.hxx>
#endif

#include <cstddef>

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _VOS_DIAGNOSE_H_
#include <vos/diagnose.hxx>
#endif

namespace unnamed_ucb_regexp {} using namespace unnamed_ucb_regexp;
    // unnamed namespaces don't work well yet...

using namespace com::sun::star;
using namespace ucb;

//============================================================================
//
//  Regexp
//
//============================================================================

inline Regexp::Regexp(Kind eTheKind, rtl::OUString const & rThePrefix,
                      bool bTheEmptyDomain, rtl::OUString const & rTheInfix,
                      bool bTheTranslation,
                      rtl::OUString const & rTheReversePrefix):
    m_eKind(eTheKind),
    m_aPrefix(rThePrefix),
    m_aInfix(rTheInfix),
    m_aReversePrefix(rTheReversePrefix),
    m_bEmptyDomain(bTheEmptyDomain),
    m_bTranslation(bTheTranslation)
{
    VOS_ASSERT(m_eKind == KIND_DOMAIN
               || !m_bEmptyDomain && m_aInfix.getLength() == 0);
    VOS_ASSERT(m_bTranslation || m_aReversePrefix.getLength() == 0);
}

//============================================================================
namespace unnamed_ucb_regexp {

bool matchStringIgnoreCase(sal_Unicode const ** pBegin,
                           sal_Unicode const * pEnd,
                           rtl::OUString const & rString)
{
    sal_Unicode const * p = *pBegin;

    sal_Unicode const * q = rString.getStr();
    sal_Unicode const * qEnd = q + rString.getLength();

    if (pEnd - p < qEnd - q)
        return false;

    while (q != qEnd)
    {
        sal_Unicode c1 = *p++;
        sal_Unicode c2 = *q++;
        if (c1 >= 'a' && c1 <= 'z')
            c1 -= 'a' - 'A';
        if (c2 >= 'a' && c2 <= 'z')
            c2 -= 'a' - 'A';
        if (c1 != c2)
            return false;
    }

    *pBegin = p;
    return true;
}

}

bool Regexp::matches(rtl::OUString const & rString,
                     rtl::OUString * pTranslation, bool * pTranslated) const
{
    sal_Unicode const * pBegin = rString.getStr();
    sal_Unicode const * pEnd = pBegin + rString.getLength();

    bool bMatches = false;

    sal_Unicode const * p = pBegin;
    if (matchStringIgnoreCase(&p, pEnd, m_aPrefix))
    {
        sal_Unicode const * pBlock1Begin = p;
        sal_Unicode const * pBlock1End = pEnd;

        sal_Unicode const * pBlock2Begin = 0;
        sal_Unicode const * pBlock2End = 0;

        switch (m_eKind)
        {
            case KIND_PREFIX:
                bMatches = true;
                break;

            case KIND_AUTHORITY:
                bMatches = p == pEnd || *p == '/' || *p == '?' || *p == '#';
                break;

            case KIND_DOMAIN:
                if (!m_bEmptyDomain)
                {
                    if (p == pEnd || *p == '/' || *p == '?' || *p == '#')
                        break;
                    ++p;
                }
                for (;;)
                {
                    sal_Unicode const * q = p;
                    if (matchStringIgnoreCase(&q, pEnd, m_aInfix)
                        && (q == pEnd || *q == '/' || *q == '?' || *q == '#'))
                    {
                        bMatches = true;
                        pBlock1End = p;
                        pBlock2Begin = q;
                        pBlock2End = pEnd;
                        break;
                    }

                    if (p == pEnd)
                        break;

                    sal_Unicode c = *p++;
                    if (c == '/' || c == '?' || c == '#')
                        break;
                }
                break;
        }

        if (bMatches)
            if (m_bTranslation)
            {
                if (pTranslation)
                {
                    rtl::OUStringBuffer aBuffer(m_aReversePrefix);
                    aBuffer.append(pBlock1Begin, pBlock1End - pBlock1Begin);
                    aBuffer.append(m_aInfix);
                    aBuffer.append(pBlock2Begin, pBlock2End - pBlock2Begin);
                    *pTranslation = aBuffer.makeStringAndClear();
                }
                if (pTranslated)
                    *pTranslated = true;
            }
            else
            {
                if (pTranslation)
                    *pTranslation = rString;
                if (pTranslated)
                    *pTranslated = false;
            }
    }

    return bMatches;
}

//============================================================================
namespace unnamed_ucb_regexp {

inline bool isAlpha(sal_Unicode c)
{
    return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}

inline bool isDigit(sal_Unicode c)
{
    return c >= '0' && c <= '9';
}

bool isScheme(rtl::OUString const & rString, bool bColon)
{
    // Return true if rString matches <scheme> (plus a trailing ":" if bColon
    // is true) from RFC 2396:
    sal_Unicode const * p = rString.getStr();
    sal_Unicode const * pEnd = p + rString.getLength();
    if (p != pEnd && isAlpha(*p))
        for (++p;;)
        {
            if (p == pEnd)
                return !bColon;
            sal_Unicode c = *p++;
            if (!(isAlpha(c) || isDigit(c)
                  || c == '+' || c == '-' || c == '.'))
                return bColon && c == ':' && p == pEnd;
        }
    return false;
}

void appendStringLiteral(rtl::OUStringBuffer * pBuffer,
                         rtl::OUString const & rString)
{
    VOS_ASSERT(pBuffer);

    pBuffer->append(sal_Unicode('"'));
    sal_Unicode const * p = rString.getStr();
    sal_Unicode const * pEnd = p + rString.getLength();
    while (p != pEnd)
    {
        sal_Unicode c = *p++;
        if (c == '"' || c == '\\')
            pBuffer->append(sal_Unicode('\\'));
        pBuffer->append(c);
    }
    pBuffer->append(sal_Unicode('"'));
}

}

rtl::OUString Regexp::getRegexp(bool bReverse) const
{
    if (m_bTranslation)
    {
        rtl::OUStringBuffer aBuffer;
        if (bReverse)
        {
            if (m_aReversePrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aReversePrefix);
        }
        else
        {
            if (m_aPrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aPrefix);
        }
        switch (m_eKind)
        {
            case KIND_PREFIX:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("(.*)"));
                break;

            case KIND_AUTHORITY:
                aBuffer.
                    appendAscii(RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)"));
                break;

            case KIND_DOMAIN:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([^/?#]"));
                aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+'));
                if (m_aInfix.getLength() != 0)
                    appendStringLiteral(&aBuffer, m_aInfix);
                aBuffer.
                    appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?)"));
                break;
        }
        aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("->"));
        if (bReverse)
        {
            if (m_aPrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aPrefix);
        }
        else
        {
            if (m_aReversePrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aReversePrefix);
        }
        aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\\1"));
        return aBuffer.makeStringAndClear();
    }
    else if (m_eKind == KIND_PREFIX && isScheme(m_aPrefix, true))
        return m_aPrefix.copy(0, m_aPrefix.getLength() - 1);
    else
    {
        rtl::OUStringBuffer aBuffer;
        if (m_aPrefix.getLength() != 0)
            appendStringLiteral(&aBuffer, m_aPrefix);
        switch (m_eKind)
        {
            case KIND_PREFIX:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM(".*"));
                break;

            case KIND_AUTHORITY:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"));
                break;

            case KIND_DOMAIN:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("[^/?#]"));
                aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+'));
                if (m_aInfix.getLength() != 0)
                    appendStringLiteral(&aBuffer, m_aInfix);
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"));
                break;
        }
        return aBuffer.makeStringAndClear();
    }
}

//============================================================================
namespace unnamed_ucb_regexp {

bool matchString(sal_Unicode const ** pBegin, sal_Unicode const * pEnd,
                 sal_Char const * pString, size_t nStringLength)
{
    sal_Unicode const * p = *pBegin;

    sal_uChar const * q = reinterpret_cast< sal_uChar const * >(pString);
    sal_uChar const * qEnd = q + nStringLength;

    if (pEnd - p < qEnd - q)
        return false;

    while (q != qEnd)
    {
        sal_Unicode c1 = *p++;
        sal_Unicode c2 = *q++;
        if (c1 != c2)
            return false;
    }

    *pBegin = p;
    return true;
}

bool scanStringLiteral(sal_Unicode const ** pBegin, sal_Unicode const * pEnd,
                       rtl::OUString * pString)
{
    sal_Unicode const * p = *pBegin;

    if (p == pEnd || *p++ != '"')
        return false;

    rtl::OUStringBuffer aBuffer;
    for (;;)
    {
        if (p == pEnd)
            return false;
        sal_Unicode c = *p++;
        if (c == '"')
            break;
        if (c == '\\')
        {
            if (p == pEnd)
                return false;
            c = *p++;
            if (c != '"' && c != '\\')
                return false;
        }
        aBuffer.append(c);
    }

    *pBegin = p;
    *pString = aBuffer.makeStringAndClear();
    return true;
}

}

Regexp Regexp::parse(rtl::OUString const & rRegexp)
{
    // Detect an input of '<scheme>' as an abbreviation of '"<scheme>:".*'
    // where <scheme> is as defined in RFC 2396:
    if (isScheme(rRegexp, false))
        return Regexp(Regexp::KIND_PREFIX,
                      rRegexp
                          + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":")),
                      false,
                      rtl::OUString(),
                      false,
                      rtl::OUString());

    sal_Unicode const * p = rRegexp.getStr();
    sal_Unicode const * pEnd = p + rRegexp.getLength();

    rtl::OUString aPrefix;
    scanStringLiteral(&p, pEnd, &aPrefix);

    if (p == pEnd)
        throw lang::IllegalArgumentException();

    if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(".*")))
    {
        if (p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(),
                      false, rtl::OUString());
    }
    else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("(.*)->")))
    {
        rtl::OUString aReversePrefix;
        scanStringLiteral(&p, pEnd, &aReversePrefix);

        if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1"))
            || p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(),
                      true, aReversePrefix);
    }
    else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")))
    {
        if (p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(),
                      false, rtl::OUString());
    }
    else if (matchString(&p, pEnd,
                         RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)->")))
    {
        rtl::OUString aReversePrefix;
        if (!(scanStringLiteral(&p, pEnd, &aReversePrefix)
              && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1"))
              && p == pEnd))
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(),
                      true, aReversePrefix);
    }
    else
    {
        bool bOpen = false;
        if (p != pEnd && *p == '(')
        {
            ++p;
            bOpen = true;
        }

        if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("[^/?#]")))
            throw lang::IllegalArgumentException();

        if (p == pEnd || *p != '*' && *p != '+')
            throw lang::IllegalArgumentException();
        bool bEmptyDomain = *p++ == '*';

        rtl::OUString aInfix;
        scanStringLiteral(&p, pEnd, &aInfix);

        if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")))
            throw lang::IllegalArgumentException();

        rtl::OUString aReversePrefix;
        if (bOpen
            && !(matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(")->"))
                 && scanStringLiteral(&p, pEnd, &aReversePrefix)
                 && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1"))))
            throw lang::IllegalArgumentException();

        if (p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_DOMAIN, aPrefix, bEmptyDomain, aInfix,
                      bOpen, aReversePrefix);
    }

    throw lang::IllegalArgumentException();
}

<commit_msg>INTEGRATION: CWS warnings01 (1.4.10); FILE MERGED 2005/11/09 21:01:42 sb 1.4.10.1: #i53898# Made code warning-free.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: regexp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:17:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

#ifndef _UCB_REGEXP_HXX_
#include <regexp.hxx>
#endif

#include <cstddef>

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _VOS_DIAGNOSE_H_
#include <vos/diagnose.hxx>
#endif

namespace unnamed_ucb_regexp {} using namespace unnamed_ucb_regexp;
    // unnamed namespaces don't work well yet...

using namespace com::sun::star;
using namespace ucb;

//============================================================================
//
//  Regexp
//
//============================================================================

inline Regexp::Regexp(Kind eTheKind, rtl::OUString const & rThePrefix,
                      bool bTheEmptyDomain, rtl::OUString const & rTheInfix,
                      bool bTheTranslation,
                      rtl::OUString const & rTheReversePrefix):
    m_eKind(eTheKind),
    m_aPrefix(rThePrefix),
    m_aInfix(rTheInfix),
    m_aReversePrefix(rTheReversePrefix),
    m_bEmptyDomain(bTheEmptyDomain),
    m_bTranslation(bTheTranslation)
{
    VOS_ASSERT(m_eKind == KIND_DOMAIN
               || !m_bEmptyDomain && m_aInfix.getLength() == 0);
    VOS_ASSERT(m_bTranslation || m_aReversePrefix.getLength() == 0);
}

//============================================================================
namespace unnamed_ucb_regexp {

bool matchStringIgnoreCase(sal_Unicode const ** pBegin,
                           sal_Unicode const * pEnd,
                           rtl::OUString const & rString)
{
    sal_Unicode const * p = *pBegin;

    sal_Unicode const * q = rString.getStr();
    sal_Unicode const * qEnd = q + rString.getLength();

    if (pEnd - p < qEnd - q)
        return false;

    while (q != qEnd)
    {
        sal_Unicode c1 = *p++;
        sal_Unicode c2 = *q++;
        if (c1 >= 'a' && c1 <= 'z')
            c1 -= 'a' - 'A';
        if (c2 >= 'a' && c2 <= 'z')
            c2 -= 'a' - 'A';
        if (c1 != c2)
            return false;
    }

    *pBegin = p;
    return true;
}

}

bool Regexp::matches(rtl::OUString const & rString,
                     rtl::OUString * pTranslation, bool * pTranslated) const
{
    sal_Unicode const * pBegin = rString.getStr();
    sal_Unicode const * pEnd = pBegin + rString.getLength();

    bool bMatches = false;

    sal_Unicode const * p = pBegin;
    if (matchStringIgnoreCase(&p, pEnd, m_aPrefix))
    {
        sal_Unicode const * pBlock1Begin = p;
        sal_Unicode const * pBlock1End = pEnd;

        sal_Unicode const * pBlock2Begin = 0;
        sal_Unicode const * pBlock2End = 0;

        switch (m_eKind)
        {
            case KIND_PREFIX:
                bMatches = true;
                break;

            case KIND_AUTHORITY:
                bMatches = p == pEnd || *p == '/' || *p == '?' || *p == '#';
                break;

            case KIND_DOMAIN:
                if (!m_bEmptyDomain)
                {
                    if (p == pEnd || *p == '/' || *p == '?' || *p == '#')
                        break;
                    ++p;
                }
                for (;;)
                {
                    sal_Unicode const * q = p;
                    if (matchStringIgnoreCase(&q, pEnd, m_aInfix)
                        && (q == pEnd || *q == '/' || *q == '?' || *q == '#'))
                    {
                        bMatches = true;
                        pBlock1End = p;
                        pBlock2Begin = q;
                        pBlock2End = pEnd;
                        break;
                    }

                    if (p == pEnd)
                        break;

                    sal_Unicode c = *p++;
                    if (c == '/' || c == '?' || c == '#')
                        break;
                }
                break;
        }

        if (bMatches)
            if (m_bTranslation)
            {
                if (pTranslation)
                {
                    rtl::OUStringBuffer aBuffer(m_aReversePrefix);
                    aBuffer.append(pBlock1Begin, pBlock1End - pBlock1Begin);
                    aBuffer.append(m_aInfix);
                    aBuffer.append(pBlock2Begin, pBlock2End - pBlock2Begin);
                    *pTranslation = aBuffer.makeStringAndClear();
                }
                if (pTranslated)
                    *pTranslated = true;
            }
            else
            {
                if (pTranslation)
                    *pTranslation = rString;
                if (pTranslated)
                    *pTranslated = false;
            }
    }

    return bMatches;
}

//============================================================================
namespace unnamed_ucb_regexp {

inline bool isAlpha(sal_Unicode c)
{
    return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
}

inline bool isDigit(sal_Unicode c)
{
    return c >= '0' && c <= '9';
}

bool isScheme(rtl::OUString const & rString, bool bColon)
{
    // Return true if rString matches <scheme> (plus a trailing ":" if bColon
    // is true) from RFC 2396:
    sal_Unicode const * p = rString.getStr();
    sal_Unicode const * pEnd = p + rString.getLength();
    if (p != pEnd && isAlpha(*p))
        for (++p;;)
        {
            if (p == pEnd)
                return !bColon;
            sal_Unicode c = *p++;
            if (!(isAlpha(c) || isDigit(c)
                  || c == '+' || c == '-' || c == '.'))
                return bColon && c == ':' && p == pEnd;
        }
    return false;
}

void appendStringLiteral(rtl::OUStringBuffer * pBuffer,
                         rtl::OUString const & rString)
{
    VOS_ASSERT(pBuffer);

    pBuffer->append(sal_Unicode('"'));
    sal_Unicode const * p = rString.getStr();
    sal_Unicode const * pEnd = p + rString.getLength();
    while (p != pEnd)
    {
        sal_Unicode c = *p++;
        if (c == '"' || c == '\\')
            pBuffer->append(sal_Unicode('\\'));
        pBuffer->append(c);
    }
    pBuffer->append(sal_Unicode('"'));
}

}

rtl::OUString Regexp::getRegexp(bool bReverse) const
{
    if (m_bTranslation)
    {
        rtl::OUStringBuffer aBuffer;
        if (bReverse)
        {
            if (m_aReversePrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aReversePrefix);
        }
        else
        {
            if (m_aPrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aPrefix);
        }
        switch (m_eKind)
        {
            case KIND_PREFIX:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("(.*)"));
                break;

            case KIND_AUTHORITY:
                aBuffer.
                    appendAscii(RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)"));
                break;

            case KIND_DOMAIN:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([^/?#]"));
                aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+'));
                if (m_aInfix.getLength() != 0)
                    appendStringLiteral(&aBuffer, m_aInfix);
                aBuffer.
                    appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?)"));
                break;
        }
        aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("->"));
        if (bReverse)
        {
            if (m_aPrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aPrefix);
        }
        else
        {
            if (m_aReversePrefix.getLength() != 0)
                appendStringLiteral(&aBuffer, m_aReversePrefix);
        }
        aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("\\1"));
        return aBuffer.makeStringAndClear();
    }
    else if (m_eKind == KIND_PREFIX && isScheme(m_aPrefix, true))
        return m_aPrefix.copy(0, m_aPrefix.getLength() - 1);
    else
    {
        rtl::OUStringBuffer aBuffer;
        if (m_aPrefix.getLength() != 0)
            appendStringLiteral(&aBuffer, m_aPrefix);
        switch (m_eKind)
        {
            case KIND_PREFIX:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM(".*"));
                break;

            case KIND_AUTHORITY:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"));
                break;

            case KIND_DOMAIN:
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("[^/?#]"));
                aBuffer.append(sal_Unicode(m_bEmptyDomain ? '*' : '+'));
                if (m_aInfix.getLength() != 0)
                    appendStringLiteral(&aBuffer, m_aInfix);
                aBuffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("([/?#].*)?"));
                break;
        }
        return aBuffer.makeStringAndClear();
    }
}

//============================================================================
namespace unnamed_ucb_regexp {

bool matchString(sal_Unicode const ** pBegin, sal_Unicode const * pEnd,
                 sal_Char const * pString, size_t nStringLength)
{
    sal_Unicode const * p = *pBegin;

    sal_uChar const * q = reinterpret_cast< sal_uChar const * >(pString);
    sal_uChar const * qEnd = q + nStringLength;

    if (pEnd - p < qEnd - q)
        return false;

    while (q != qEnd)
    {
        sal_Unicode c1 = *p++;
        sal_Unicode c2 = *q++;
        if (c1 != c2)
            return false;
    }

    *pBegin = p;
    return true;
}

bool scanStringLiteral(sal_Unicode const ** pBegin, sal_Unicode const * pEnd,
                       rtl::OUString * pString)
{
    sal_Unicode const * p = *pBegin;

    if (p == pEnd || *p++ != '"')
        return false;

    rtl::OUStringBuffer aBuffer;
    for (;;)
    {
        if (p == pEnd)
            return false;
        sal_Unicode c = *p++;
        if (c == '"')
            break;
        if (c == '\\')
        {
            if (p == pEnd)
                return false;
            c = *p++;
            if (c != '"' && c != '\\')
                return false;
        }
        aBuffer.append(c);
    }

    *pBegin = p;
    *pString = aBuffer.makeStringAndClear();
    return true;
}

}

Regexp Regexp::parse(rtl::OUString const & rRegexp)
{
    // Detect an input of '<scheme>' as an abbreviation of '"<scheme>:".*'
    // where <scheme> is as defined in RFC 2396:
    if (isScheme(rRegexp, false))
        return Regexp(Regexp::KIND_PREFIX,
                      rRegexp
                          + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(":")),
                      false,
                      rtl::OUString(),
                      false,
                      rtl::OUString());

    sal_Unicode const * p = rRegexp.getStr();
    sal_Unicode const * pEnd = p + rRegexp.getLength();

    rtl::OUString aPrefix;
    scanStringLiteral(&p, pEnd, &aPrefix);

    if (p == pEnd)
        throw lang::IllegalArgumentException();

    if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(".*")))
    {
        if (p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(),
                      false, rtl::OUString());
    }
    else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("(.*)->")))
    {
        rtl::OUString aReversePrefix;
        scanStringLiteral(&p, pEnd, &aReversePrefix);

        if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1"))
            || p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_PREFIX, aPrefix, false, rtl::OUString(),
                      true, aReversePrefix);
    }
    else if (matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")))
    {
        if (p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(),
                      false, rtl::OUString());
    }
    else if (matchString(&p, pEnd,
                         RTL_CONSTASCII_STRINGPARAM("(([/?#].*)?)->")))
    {
        rtl::OUString aReversePrefix;
        if (!(scanStringLiteral(&p, pEnd, &aReversePrefix)
              && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1"))
              && p == pEnd))
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_AUTHORITY, aPrefix, false, rtl::OUString(),
                      true, aReversePrefix);
    }
    else
    {
        bool bOpen = false;
        if (p != pEnd && *p == '(')
        {
            ++p;
            bOpen = true;
        }

        if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("[^/?#]")))
            throw lang::IllegalArgumentException();

        if (p == pEnd || *p != '*' && *p != '+')
            throw lang::IllegalArgumentException();
        bool bEmptyDomain = *p++ == '*';

        rtl::OUString aInfix;
        scanStringLiteral(&p, pEnd, &aInfix);

        if (!matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("([/?#].*)?")))
            throw lang::IllegalArgumentException();

        rtl::OUString aReversePrefix;
        if (bOpen
            && !(matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM(")->"))
                 && scanStringLiteral(&p, pEnd, &aReversePrefix)
                 && matchString(&p, pEnd, RTL_CONSTASCII_STRINGPARAM("\\1"))))
            throw lang::IllegalArgumentException();

        if (p != pEnd)
            throw lang::IllegalArgumentException();

        return Regexp(Regexp::KIND_DOMAIN, aPrefix, bEmptyDomain, aInfix,
                      bOpen, aReversePrefix);
    }
}

<|endoftext|>


<commit_before>#include <string.h>
#include <Wire.h>
#include "MPU6050.h"
#include "nt.h"

int main(void)
{
	tNTBusGetImuData imuData;
	memset(&imuData, 0, sizeof(imuData));
	imuData.ImuStatus = NTBUS_IMU_IMUSTATUS_BASE | NTBUS_IMU_IMUSTATUS_GYRODATA_OK | NTBUS_IMU_IMUSTATUS_ACCDATA_OK;

	Wire.begin();

	MPU6050 imu = MPU6050();
	imu.initialize();
	imu.setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
	imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000);
	imu.setExternalFrameSync(MPU6050_EXT_SYNC_DISABLED);
	imu.setDLPFMode(MPU6050_DLPF_BW_256);
	imu.setRate(0);    // sample at full speed

	NtNodeImu ntNode = NtNodeImu::getNodeWithNtBuffer(NTBUS_ID_IMU1, "ArduNT IMU", &imuData, NTBUS_IMU_CONFIG_MPU6000);

	for (;;)
	{
		imu.getMotion6(&imuData.AccX, &imuData.AccY, &imuData.AccZ, &imuData.GyroX, &imuData.GyroY, &imuData.GyroZ);
		imuData.Temp = imu.getTemperature();
		uint8_t recv;
		ntNode.processBusData(&recv);
	}

	sei();

	return 0;
}
<commit_msg>Interrupts start before starting I2C library.<commit_after>#include <string.h>
#include <Wire.h>
#include "MPU6050.h"
#include "nt.h"

int main(void)
{
	tNTBusGetImuData imuData;
	memset(&imuData, 0, sizeof(imuData));
	imuData.ImuStatus = NTBUS_IMU_IMUSTATUS_BASE | NTBUS_IMU_IMUSTATUS_GYRODATA_OK | NTBUS_IMU_IMUSTATUS_ACCDATA_OK;

	sei();

	Wire.begin();

	MPU6050 imu = MPU6050();
	imu.initialize();
	imu.setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
	imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000);
	imu.setExternalFrameSync(MPU6050_EXT_SYNC_DISABLED);
	imu.setDLPFMode(MPU6050_DLPF_BW_256);
	imu.setRate(0);    // sample at full speed

	NtNodeImu ntNode = NtNodeImu::getNodeWithNtBuffer(NTBUS_ID_IMU1, "ArduNT IMU", &imuData, NTBUS_IMU_CONFIG_MPU6000);

	for (;;)
	{
		imu.getMotion6(&imuData.AccX, &imuData.AccY, &imuData.AccZ, &imuData.GyroX, &imuData.GyroY, &imuData.GyroZ);
		imuData.Temp = imu.getTemperature();
		uint8_t recv;
		ntNode.processBusData(&recv);
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) ICG. All rights reserved.
 *
 * Institute for Computer Graphics and Vision
 * Graz University of Technology / Austria
 *
 *
 * This software is distributed WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the above copyright notices for more information.
 *
 *
 * Project     : ImageUtilities
 * Module      : Core
 * Class       : ImagePyramid
 * Language    : C++
 * Description : Implementation of multiresolution imagepyramid
 *
 * Author     : Manuel Werlberger
 * EMail      : werlberger@icg.tugraz.at
 *
 */

#include <math.h>
#include "coredefs.h"
#include "memorydefs.h"
#include "iutransform/reduce.h"
#include "copy.h"
#include "imagepyramid.h"

namespace iu {

//---------------------------------------------------------------------------
ImagePyramid::ImagePyramid() :
  images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0),
  max_num_levels_(0), scale_factor_(0.0f), size_bound_(0)
{
}

//---------------------------------------------------------------------------
ImagePyramid::ImagePyramid(unsigned int& max_num_levels, const IuSize& size, const float& scale_factor,
             unsigned int size_bound) :
  images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0),
  max_num_levels_(0), scale_factor_(0.0f), size_bound_(0)
{
  max_num_levels = this->init(max_num_levels, size, scale_factor, size_bound);
  printf("max_num_levels = %d, num_levels_ = %d\n", max_num_levels, num_levels_);
}

//---------------------------------------------------------------------------
ImagePyramid::~ImagePyramid()
{
  this->reset();
}

//---------------------------------------------------------------------------
unsigned int ImagePyramid::init(unsigned int max_num_levels, const IuSize& size,
                                const float& scale_factor, unsigned int size_bound)
{
  if ((scale_factor <= 0) || (scale_factor >=1))
  {
    fprintf(stderr, "ImagePyramid::init: scale_factor must be in the interval (0,1). Init failed.");
    return 0;
  }

  if (images_ != 0)
    this->reset();

  max_num_levels_ = IUMAX(1u, max_num_levels);
  num_levels_ = max_num_levels_;
  size_bound_ = IUMAX(1u, size_bound);

  // calculate the maximum number of levels
  unsigned int shorter_side = (size.width<size.height) ? size.width : size.height;
  float ratio = static_cast<float>(shorter_side)/static_cast<float>(size_bound_);
  // +1 because the original size is level 0
  unsigned int possible_num_levels = static_cast<int>(
        -logf(ratio)/logf(scale_factor)) + 1;
  if(num_levels_ > possible_num_levels)
    num_levels_ = possible_num_levels;

  // init rate for each level
  scale_factors_ = new float[num_levels_];
  for (unsigned int i=0; i<num_levels_; i++)
  {
    scale_factors_[i] = pow(scale_factor, static_cast<float>(i));
    printf("scale_factors[%d]=%f\n", i, scale_factors_[i]);
  }

  return num_levels_;
}

//---------------------------------------------------------------------------
/** Resets the image pyramid. Deletes all the data.
   */
void ImagePyramid::reset()
{
  printf("reset\n");
  if(images_ != 0)
  {
    printf("delete images[i]\n");
    // delete all arrays and hold elements!
    for (unsigned int i=0; i<num_levels_; i++)
    {
      delete(images_[i]);
      images_[i] = 0;
    }
  }

  delete[] images_;
  images_ = 0;
  pixel_type_ = IU_UNKNOWN_PIXEL_TYPE;
  delete[] scale_factors_;
  scale_factors_ = 0;
  num_levels_ = 0;
}

//---------------------------------------------------------------------------
unsigned int ImagePyramid::setImage(iu::Image* image,
                                    IuInterpolationType interp_type)
{
  if (image == 0)
  {
    fprintf(stderr, "ImagePyramid::setImage: input image is 0.");
    return 0;
  }
  if (!image->onDevice())
  {
    fprintf(stderr, "ImagePyramid::setImage: currently only device images supported.");
    return 0;
  }

  if ((images_ != 0) && (
        (images_[0]->size() != image->size()) ||
        (images_[0]->pixelType() != image->pixelType()) ))
  {
    this->reset();
    this->init(max_num_levels_, image->size(), scale_factor_, size_bound_);
  }

  pixel_type_ = image->pixelType();
  printf("ImagePyramid::setImage: image pixel_type = %d\n", image->pixelType());
  printf("ImagePyramid::setImage: pyr pixel_type = %d\n", pixel_type_);
  printf("ImagePyramid::setImage: pyr pixel_type = %d\n", this->pixelType());

  switch (pixel_type_)
  {
  case IU_32F_C1:
  {
    printf("32f_C1\n");
    printf("images=%p\n", images_);
    iu::ImageGpu_32f_C1** cur_images = 0;
    printf("cur_images=%p\n", cur_images);
    if (images_ == 0)
    {
      printf("create array\n");
      cur_images = new iu::ImageGpu_32f_C1*[num_levels_];
    }
    else
      cur_images = reinterpret_cast<iu::ImageGpu_32f_C1**>(images_);
    images_ = reinterpret_cast<iu::Image**>(cur_images);
    printf("cur_images=%p\n", cur_images);
    printf("images=%p\n", images_);
    cur_images[0] = new iu::ImageGpu_32f_C1(image->size());
    iuprivate::copy(reinterpret_cast<iu::ImageGpu_32f_C1*>(image), cur_images[0]);
    printf("1\n");

    for (unsigned int i=1; i<num_levels_; i++)
    {
      IuSize sz(static_cast<int>(floor(0.5+static_cast<double>(image->width())*static_cast<double>(scale_factors_[i]))),
                static_cast<int>(floor(0.5+static_cast<double>(image->height())*static_cast<double>(scale_factors_[i]))));
      printf("i=%d: sz=%d/%d\n", i, sz.width, sz.height);

      cur_images[i] = new iu::ImageGpu_32f_C1(sz);
      iuprivate::reduce(reinterpret_cast<iu::ImageGpu_32f_C1*>(cur_images[i-1]),
                        reinterpret_cast<iu::ImageGpu_32f_C1*>(cur_images[i]),
                        interp_type, 1, 0);
    }
    printf("2\n");
    break;
  }
  default:
    fprintf(stderr, "ImagePyramid::setImage: unsupported pixel type (currently only 32F_C1 supported)\n");
    return 0;
  }

  return num_levels_;
}

} // namespace iu

<commit_msg><commit_after>/*
 * Copyright (c) ICG. All rights reserved.
 *
 * Institute for Computer Graphics and Vision
 * Graz University of Technology / Austria
 *
 *
 * This software is distributed WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the above copyright notices for more information.
 *
 *
 * Project     : ImageUtilities
 * Module      : Core
 * Class       : ImagePyramid
 * Language    : C++
 * Description : Implementation of multiresolution imagepyramid
 *
 * Author     : Manuel Werlberger
 * EMail      : werlberger@icg.tugraz.at
 *
 */

#include <math.h>
#include "coredefs.h"
#include "memorydefs.h"
#include "iutransform/reduce.h"
#include "copy.h"
#include "imagepyramid.h"

namespace iu {

//---------------------------------------------------------------------------
ImagePyramid::ImagePyramid() :
  images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0),
  max_num_levels_(0), scale_factor_(0.0f), size_bound_(0)
{
}

//---------------------------------------------------------------------------
ImagePyramid::ImagePyramid(unsigned int& max_num_levels, const IuSize& size, const float& scale_factor,
             unsigned int size_bound) :
  images_(0), pixel_type_(IU_UNKNOWN_PIXEL_TYPE), scale_factors_(0), num_levels_(0),
  max_num_levels_(0), scale_factor_(0.0f), size_bound_(0)
{
  max_num_levels = this->init(max_num_levels, size, scale_factor, size_bound);
  printf("max_num_levels = %d, num_levels_ = %d\n", max_num_levels, num_levels_);
}

//---------------------------------------------------------------------------
ImagePyramid::~ImagePyramid()
{
  this->reset();
}

//---------------------------------------------------------------------------
unsigned int ImagePyramid::init(unsigned int max_num_levels, const IuSize& size,
                                const float& scale_factor, unsigned int size_bound)
{
  if ((scale_factor <= 0) || (scale_factor >=1))
  {
    fprintf(stderr, "ImagePyramid::init: scale_factor must be in the interval (0,1). Init failed.");
    return 0;
  }

  if (images_ != 0)
    this->reset();

  max_num_levels_ = IUMAX(1u, max_num_levels);
  num_levels_ = max_num_levels_;
  size_bound_ = IUMAX(1u, size_bound);

  // calculate the maximum number of levels
  unsigned int shorter_side = (size.width<size.height) ? size.width : size.height;
  float ratio = static_cast<float>(shorter_side)/static_cast<float>(size_bound_);
  // +1 because the original size is level 0
  unsigned int possible_num_levels = static_cast<int>(
        -logf(ratio)/logf(scale_factor)) + 1;
  if(num_levels_ > possible_num_levels)
    num_levels_ = possible_num_levels;

  // init rate for each level
  scale_factors_ = new float[num_levels_];
  for (unsigned int i=0; i<num_levels_; i++)
  {
    scale_factors_[i] = pow(scale_factor, static_cast<float>(i));
    printf("scale_factors[%d]=%f\n", i, scale_factors_[i]);
  }

  return num_levels_;
}

//---------------------------------------------------------------------------
/** Resets the image pyramid. Deletes all the data.
   */
void ImagePyramid::reset()
{
  printf("reset\n");
  if(images_ != 0)
  {
    printf("delete images[i]\n");
    // delete all arrays and hold elements!
    for (unsigned int i=0; i<num_levels_; i++)
    {
      delete(images_[i]);
      images_[i] = 0;
    }
  }

  delete[] images_;
  images_ = 0;
  pixel_type_ = IU_UNKNOWN_PIXEL_TYPE;
  delete[] scale_factors_;
  scale_factors_ = 0;
  num_levels_ = 0;
}

//---------------------------------------------------------------------------
unsigned int ImagePyramid::setImage(iu::Image* image,
                                    IuInterpolationType interp_type)
{
  if (image == 0)
  {
    fprintf(stderr, "ImagePyramid::setImage: input image is 0.");
    return 0;
  }
  if (!image->onDevice())
  {
    fprintf(stderr, "ImagePyramid::setImage: currently only device images supported.");
    return 0;
  }

  if ((images_ != 0) && (
        (images_[0]->size() != image->size()) ||
        (images_[0]->pixelType() != image->pixelType()) ))
  {
    this->reset();
    this->init(max_num_levels_, image->size(), scale_factor_, size_bound_);
  }

  pixel_type_ = image->pixelType();
  printf("ImagePyramid::setImage: image pixel_type = %d\n", image->pixelType());
  printf("ImagePyramid::setImage: pyr pixel_type = %d\n", pixel_type_);
  printf("ImagePyramid::setImage: pyr pixel_type = %d\n", this->pixelType());

  switch (pixel_type_)
  {
  case IU_32F_C1:
  {
    printf("32f_C1\n");
    printf("images=%p\n", images_);
    iu::ImageGpu_32f_C1*** cur_images = reinterpret_cast<iu::ImageGpu_32f_C1***>(&images_); // *** needed so that always the same mem is used.
    printf("cur_images=%p\n", *cur_images);
    if (images_ == 0)
    {
      printf("create array\n");
      (*cur_images) = new iu::ImageGpu_32f_C1*[num_levels_];
      for (unsigned int i=0; i<num_levels_; i++)
      {
        IuSize sz(static_cast<int>(floor(0.5+static_cast<double>(image->width())*static_cast<double>(scale_factors_[i]))),
                  static_cast<int>(floor(0.5+static_cast<double>(image->height())*static_cast<double>(scale_factors_[i]))));
        printf("i=%d: sz=%d/%d\n", i, sz.width, sz.height);
        (*cur_images)[i] = new iu::ImageGpu_32f_C1(sz);
      }
    }
    printf("cur_images=%p\n", (*cur_images));
    printf("images=%p\n", images_);

    printf("i=0: sz=%d/%d\n", image->size().width, image->size().height);
    iuprivate::copy(reinterpret_cast<iu::ImageGpu_32f_C1*>(image), (*cur_images)[0]);
    for (unsigned int i=1; i<num_levels_; i++)
    {
      printf("i=%d, reduction\n", i);
      iuprivate::reduce((*cur_images)[i-1], (*cur_images)[i], interp_type, 1, 0);
    }
    printf("2\n");
    break;
  }
  default:
    fprintf(stderr, "ImagePyramid::setImage: unsupported pixel type (currently only 32F_C1 supported)\n");
    return 0;
  }

  return num_levels_;
}

} // namespace iu

<|endoftext|>


<commit_before>/*

Copyright (c) 2017 Maksim Galkin

This file is subject to the terms and conditions of the MIT license,
distributed with this code package in the LICENSE file, also available at:
https://github.com/yacoder/allo-cpp/blob/master/LICENSE

*/

#pragma once

#include "allo_private_allocator.hpp"
#include "allocation_strategies/allo_never_look_back_strategy.hpp"

namespace allo
{

template <typename T, typename TInnerAllocator = std::allocator>
using never_look_back_allocator = private_allocator<T, strategies::never_look_back_strategy, TInnerAllocator>;

} // namespace allo
<commit_msg>Fix a build problem on OS X, wrong template syntax in never_look_back_allocator<commit_after>/*

Copyright (c) 2017 Maksim Galkin

This file is subject to the terms and conditions of the MIT license,
distributed with this code package in the LICENSE file, also available at:
https://github.com/yacoder/allo-cpp/blob/master/LICENSE

*/

#pragma once

#include "allo_private_allocator.hpp"
#include "allocation_strategies/allo_never_look_back_strategy.hpp"

namespace allo
{

template <typename T, typename TInnerAllocator = std::allocator<T>>
using never_look_back_allocator = private_allocator<T, strategies::never_look_back_strategy, TInnerAllocator>;

} // namespace allo
<|endoftext|>