<commit_before>#pragma once

#include <string>
#include <functional>
#include <unordered_map>
#include <map>
#include <vector>
#include <iomanip>

#include <boost/optional.hpp>
#include <boost/variant/get.hpp>
#include <boost/variant.hpp>
#include <boost/lexical_cast.hpp>

#include "config.h"
#include "Key.hpp"

namespace liquidpp {
enum class ValueTag {
   Object,
   Null,
   OutOfRange,
   SubValue
};

struct RangeDefinition
{
   size_t size;

   bool operator==(const RangeDefinition& other) const {
      return size == other.size;
   }
};

class Value {
private:
   boost::variant<string_view, std::string, std::intmax_t, double, bool, RangeDefinition, ValueTag> data{ValueTag::Null};

public:
   Value() = default;

   Value(const Value&) = default;

   Value(Value&&) = default;

   Value& operator=(const Value&) = default;

   Value& operator=(Value&&) = default;

   Value(ValueTag tag)
      : data(tag) {}

   Value(RangeDefinition rangeDef)
      : data(rangeDef) {}

   Value(const std::string& v)
      : data(v) {}

   Value(std::string&& v)
      : data(std::move(v)) {}

   static Value fromBool(bool b) {
      Value res;
      res.data = b;
      assert(res.isBool());
      return res;
   }

   template<typename T>
   static Value fromIntegral(T t) {
      Value res;
      res.data = static_cast<std::intmax_t>(t);
      assert(res.isIntegral());
      return res;
   }

   template<typename T>
   static Value fromFloatingPoint(T t) {
      Value res;
      res.data = static_cast<double>(t);
      assert(res.isFloatingPoint());
      return res;
   }

   static Value reference(string_view sv) {
      Value res;
      res.data = sv;
      return res;
   }

   bool isRange() const {
      return data.which() == 5;
   }

   size_t size() const {
      if (isRange())
         return boost::get<RangeDefinition>(data).size;
      if (isStringViewRepresentable())
      {
         string_view sv = **this;
         return sv.size();
      }

      // count of (printed) decimals of numbers
      return toString().size();
   }

   bool isValueTag() const {
      return data.which() == 6;
   }

   bool isSimpleValue() const {
      return !isValueTag() && !isRange();
   }

   bool isNil() const {
      if (isValueTag()) {
         auto tagVal = boost::get<ValueTag>(data);
         if (tagVal == ValueTag::Null || tagVal == ValueTag::OutOfRange)
            return true;
      }
      return false;
   }

   bool isBool() const {
      return data.which() == 4;
   }

   bool isTrue() const {
      return isBool() && boost::get<bool>(data);
   }

   bool isFalse() const {
      return isBool() && (boost::get<bool>(data) == false);
   }

   bool isIntegral() const {
      return data.which() == 2;
   }

   std::intmax_t integralValue() const {
      return boost::get<std::intmax_t>(data);
   }

   bool isFloatingPoint() const {
      return data.which() == 3;
   }

   double floatingPointValue() const {
      return boost::get<double>(data);
   }

   bool isNumber() const {
      return isIntegral() || isFloatingPoint();
   }

   bool isStringType() const {
      if (data.which() == 0 || data.which() == 1)
         return true;
      return false;
   }

   explicit operator bool() const {
      if (isFalse() || isNil())
         return false;
      return true;
   }

   bool operator!() const {
      if (*this)
         return false;
      return true;
   }

   bool isStringViewRepresentable() const {
      return !isNumber();
   }

   Value& operator|=(const Value& v) {
      if (!*this)
         *this = v;
      return *this;
   }

   Value& operator&=(const Value& v) {
      if (*this)
         *this = v;
      return *this;
   }

   std::string toString() const {
      if (isIntegral())
         return boost::lexical_cast<std::string>(boost::get<std::int64_t>(data));
      else if (isFloatingPoint())
      {
         std::ostringstream oss;
         oss << std::setprecision(16) << boost::get<double>(data);
         return oss.str();
      }
      else
         return (**this).to_string();
   }

   string_view operator*() const {
      // TODO: static_visitor
      if (data.which() == 0)
         return boost::get<string_view>(data);
      if (data.which() == 1)
         return boost::get<std::string>(data);
      if (isBool())
         return isTrue() ? "true" : "false";
      return string_view{};
   }

private:
   template<typename Comparsion>
   struct Compare : public boost::static_visitor<bool> {
      template<typename T, typename U>
      bool operator()(const T& left, const U& right) const {
         return false;
      }

      template<typename T>
      bool operator()(const T& left, const T& right) const {
         return Comparsion{}(left, right);
      }

      bool operator()(const string_view& left, const std::string& right) const {
         return Comparsion{}(left, string_view{right});
      }

      bool operator()(const std::string& left, const string_view& right) const {
         return Comparsion{}(string_view{left}, right);
      }

      bool operator()(const double& left, const std::intmax_t& right) const {
         return Comparsion{}(left, static_cast<double>(right));
      }

      bool operator()(const std::intmax_t& left, const double& right) const {
         return Comparsion{}(static_cast<double>(left), right);
      }

      bool operator()(const RangeDefinition& left, const RangeDefinition& right) const {
         return false;
      }
   };

   template<template <typename> class C>
   bool compareWith(const Value& other) const
   {
      Compare<C<void>> comp;
      return boost::apply_visitor(comp, this->data, other.data);
   }

public:
   bool operator==(const Value& other) const {
      return compareWith<std::equal_to>(other);
   }

   bool operator!=(const Value& other) const {
      return compareWith<std::not_equal_to>(other);
   }

   bool operator<(const Value& other) const {
      return compareWith<std::less>(other);
   }

   bool operator<=(const Value& other) const {
      return compareWith<std::less_equal>(other);
   }

   bool operator>(const Value& other) const {
      return compareWith<std::greater>(other);
   }

   bool operator>=(const Value& other) const {
      return compareWith<std::greater_equal>(other);
   }

   bool contains(const Value& other) const {
      if (!isStringType())
         return false;

      auto thisStr = **this;
      auto otherStr = other.toString();
      return thisStr.find(otherStr) != std::string::npos;
   }

   bool operator==(ValueTag tag) const {
      if (isValueTag())
         return boost::get<ValueTag>(data) == tag;
      return false;
   }

   bool operator!=(ValueTag tag) const {
      return !(*this == tag);
   }
};

using OptIndex = boost::optional<size_t>;
using ValueGetter = std::function<Value(OptIndex, string_view)>;

template<typename T>
struct ValueConverter : public std::false_type {
};

template<typename T>
constexpr bool hasValueConverter = ValueConverter<T>::value;

inline Value toValue(std::string v) {
   return Value(std::move(v));
}

inline Value toValue(const char* v) {
   return Value(std::string{v});
}

template<size_t Len>
Value toValue(const char (&v)[Len]) {
   return Value(std::string{v});
}

inline Value toValue(bool b) {
   return Value::fromBool(b);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_integral<T>::value, void**> = 0) {
   return Value::fromIntegral(t);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_floating_point<T>::value, void**> = 0) {
   return Value::fromFloatingPoint(t);
}

template<typename T>
std::string toValue(const T& value, std::enable_if_t<hasValueConverter<T>, void**> = 0) {
   return ValueConverter<T>::get(value);
}

namespace impl {
template<typename KeyT, typename ValueT>
struct AssociativeContainerConverter : public std::true_type {
   template<typename T>
   static auto get(T&& map, std::enable_if_t<!hasValueConverter<ValueT>, void**> = 0) {
      return [map = std::forward<T>(map)](OptIndex
      idx, string_view
      path) -> Value
      {
         auto key = popKey(path);
         auto itr = map.find(boost::lexical_cast<KeyT>(key.name));
         if (itr != map.end())
         {
            if (key.idx || !path.empty())
               return ValueTag::SubValue;
            return toValue(itr->second);
         }
         return ValueTag::Null;
      };
   }

   template<typename T>
   static auto get(T&& map, std::enable_if_t<hasValueConverter<ValueT>, void**> = 0) {
      return [map = std::forward<T>(map)](OptIndex idx, string_view path) -> Value
      {
         auto key = popKey(path);
         auto itr = map.find(boost::lexical_cast<KeyT>(key.name));
         if (itr != map.end())
            return ValueConverter<ValueT>::get(itr->second)(key.idx, path);
         return ValueTag::Null;
      };
   }
};
}

template<typename KeyT, typename ValueT>
struct ValueConverter<std::map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename KeyT, typename ValueT>
struct ValueConverter<std::unordered_map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename ValueT>
struct ValueConverter<std::vector<ValueT>> : public std::true_type {
   template<typename T>
   static auto get(T&& vec, std::enable_if_t<!hasValueConverter<ValueT>, void**> = 0) {
      return [vec = std::forward<T>(vec)](OptIndex idx, string_view path) -> Value
      {
         if (!idx)
            return RangeDefinition{vec.size()};
         if (*idx < vec.size())
         {
            if (!path.empty())
               return ValueTag::SubValue;
            return toValue(vec[*idx]);
         }
         return ValueTag::OutOfRange;
      };
   }

   template<typename T>
   static auto get(T&& vec, std::enable_if_t<hasValueConverter<ValueT>, void**> = 0) {
      return [vec = std::forward<T>(vec)](OptIndex idx, string_view path) -> Value
      {
         if (!idx)
            return RangeDefinition{vec.size()};
         if (*idx < vec.size())
            return ValueConverter<ValueT>::get(vec[*idx])(boost::none, path);
         return ValueTag::OutOfRange;
      };
   }
};
}
<commit_msg>Try to workaround msvc problem (I really need 'constexpr if')<commit_after>#pragma once

#include <string>
#include <functional>
#include <unordered_map>
#include <map>
#include <vector>
#include <iomanip>

#include <boost/optional.hpp>
#include <boost/variant/get.hpp>
#include <boost/variant.hpp>
#include <boost/lexical_cast.hpp>

#include "config.h"
#include "Key.hpp"

namespace liquidpp {
enum class ValueTag {
   Object,
   Null,
   OutOfRange,
   SubValue
};

struct RangeDefinition
{
   size_t size;

   bool operator==(const RangeDefinition& other) const {
      return size == other.size;
   }
};

class Value {
private:
   boost::variant<string_view, std::string, std::intmax_t, double, bool, RangeDefinition, ValueTag> data{ValueTag::Null};

public:
   Value() = default;

   Value(const Value&) = default;

   Value(Value&&) = default;

   Value& operator=(const Value&) = default;

   Value& operator=(Value&&) = default;

   Value(ValueTag tag)
      : data(tag) {}

   Value(RangeDefinition rangeDef)
      : data(rangeDef) {}

   Value(const std::string& v)
      : data(v) {}

   Value(std::string&& v)
      : data(std::move(v)) {}

   static Value fromBool(bool b) {
      Value res;
      res.data = b;
      assert(res.isBool());
      return res;
   }

   template<typename T>
   static Value fromIntegral(T t) {
      Value res;
      res.data = static_cast<std::intmax_t>(t);
      assert(res.isIntegral());
      return res;
   }

   template<typename T>
   static Value fromFloatingPoint(T t) {
      Value res;
      res.data = static_cast<double>(t);
      assert(res.isFloatingPoint());
      return res;
   }

   static Value reference(string_view sv) {
      Value res;
      res.data = sv;
      return res;
   }

   bool isRange() const {
      return data.which() == 5;
   }

   size_t size() const {
      if (isRange())
         return boost::get<RangeDefinition>(data).size;
      if (isStringViewRepresentable())
      {
         string_view sv = **this;
         return sv.size();
      }

      // count of (printed) decimals of numbers
      return toString().size();
   }

   bool isValueTag() const {
      return data.which() == 6;
   }

   bool isSimpleValue() const {
      return !isValueTag() && !isRange();
   }

   bool isNil() const {
      if (isValueTag()) {
         auto tagVal = boost::get<ValueTag>(data);
         if (tagVal == ValueTag::Null || tagVal == ValueTag::OutOfRange)
            return true;
      }
      return false;
   }

   bool isBool() const {
      return data.which() == 4;
   }

   bool isTrue() const {
      return isBool() && boost::get<bool>(data);
   }

   bool isFalse() const {
      return isBool() && (boost::get<bool>(data) == false);
   }

   bool isIntegral() const {
      return data.which() == 2;
   }

   std::intmax_t integralValue() const {
      return boost::get<std::intmax_t>(data);
   }

   bool isFloatingPoint() const {
      return data.which() == 3;
   }

   double floatingPointValue() const {
      return boost::get<double>(data);
   }

   bool isNumber() const {
      return isIntegral() || isFloatingPoint();
   }

   bool isStringType() const {
      if (data.which() == 0 || data.which() == 1)
         return true;
      return false;
   }

   explicit operator bool() const {
      if (isFalse() || isNil())
         return false;
      return true;
   }

   bool operator!() const {
      if (*this)
         return false;
      return true;
   }

   bool isStringViewRepresentable() const {
      return !isNumber();
   }

   Value& operator|=(const Value& v) {
      if (!*this)
         *this = v;
      return *this;
   }

   Value& operator&=(const Value& v) {
      if (*this)
         *this = v;
      return *this;
   }

   std::string toString() const {
      if (isIntegral())
         return boost::lexical_cast<std::string>(boost::get<std::int64_t>(data));
      else if (isFloatingPoint())
      {
         std::ostringstream oss;
         oss << std::setprecision(16) << boost::get<double>(data);
         return oss.str();
      }
      else
         return (**this).to_string();
   }

   string_view operator*() const {
      // TODO: static_visitor
      if (data.which() == 0)
         return boost::get<string_view>(data);
      if (data.which() == 1)
         return boost::get<std::string>(data);
      if (isBool())
         return isTrue() ? "true" : "false";
      return string_view{};
   }

private:
   template<typename Comparsion>
   struct Compare : public boost::static_visitor<bool> {
      template<typename T, typename U>
      bool operator()(const T& left, const U& right) const {
         return false;
      }

      template<typename T>
      bool operator()(const T& left, const T& right) const {
         return Comparsion{}(left, right);
      }

      bool operator()(const string_view& left, const std::string& right) const {
         return Comparsion{}(left, string_view{right});
      }

      bool operator()(const std::string& left, const string_view& right) const {
         return Comparsion{}(string_view{left}, right);
      }

      bool operator()(const double& left, const std::intmax_t& right) const {
         return Comparsion{}(left, static_cast<double>(right));
      }

      bool operator()(const std::intmax_t& left, const double& right) const {
         return Comparsion{}(static_cast<double>(left), right);
      }

      bool operator()(const RangeDefinition& left, const RangeDefinition& right) const {
         return false;
      }
   };

   template<template <typename> class C>
   bool compareWith(const Value& other) const
   {
      Compare<C<void>> comp;
      return boost::apply_visitor(comp, this->data, other.data);
   }

public:
   bool operator==(const Value& other) const {
      return compareWith<std::equal_to>(other);
   }

   bool operator!=(const Value& other) const {
      return compareWith<std::not_equal_to>(other);
   }

   bool operator<(const Value& other) const {
      return compareWith<std::less>(other);
   }

   bool operator<=(const Value& other) const {
      return compareWith<std::less_equal>(other);
   }

   bool operator>(const Value& other) const {
      return compareWith<std::greater>(other);
   }

   bool operator>=(const Value& other) const {
      return compareWith<std::greater_equal>(other);
   }

   bool contains(const Value& other) const {
      if (!isStringType())
         return false;

      auto thisStr = **this;
      auto otherStr = other.toString();
      return thisStr.find(otherStr) != std::string::npos;
   }

   bool operator==(ValueTag tag) const {
      if (isValueTag())
         return boost::get<ValueTag>(data) == tag;
      return false;
   }

   bool operator!=(ValueTag tag) const {
      return !(*this == tag);
   }
};

using OptIndex = boost::optional<size_t>;
using ValueGetter = std::function<Value(OptIndex, string_view)>;

template<typename T>
struct ValueConverter : public std::false_type {
};

template<typename T>
constexpr bool hasValueConverter = ValueConverter<T>::value;

inline Value toValue(std::string v) {
   return Value(std::move(v));
}

inline Value toValue(const char* v) {
   return Value(std::string{v});
}

template<size_t Len>
Value toValue(const char (&v)[Len]) {
   return Value(std::string{v});
}

inline Value toValue(bool b) {
   return Value::fromBool(b);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_integral<T>::value, void**> = 0) {
   return Value::fromIntegral(t);
}

template<typename T>
Value toValue(T t, std::enable_if_t<!hasValueConverter<T> && std::is_floating_point<T>::value, void**> = 0) {
   return Value::fromFloatingPoint(t);
}

template<typename T>
std::string toValue(const T& value, std::enable_if_t<hasValueConverter<T>, void**> = 0) {
   return ValueConverter<T>::get(value);
}

namespace impl {
template<typename KeyT, typename ValueT>
struct AssociativeContainerConverter : public std::true_type {
   template<typename T>
   static auto get(T&& map, std::enable_if_t<!hasValueConverter<typename std::decay_t<T>::value_type>, void**> = 0) {
      return [map = std::forward<T>(map)](OptIndex
      idx, string_view
      path) -> Value
      {
         auto key = popKey(path);
         auto itr = map.find(boost::lexical_cast<KeyT>(key.name));
         if (itr != map.end())
         {
            if (key.idx || !path.empty())
               return ValueTag::SubValue;
            return toValue(itr->second);
         }
         return ValueTag::Null;
      };
   }

   template<typename T>
   static auto get(T&& map, std::enable_if_t<hasValueConverter<typename std::decay_t<T>::value_type>, void**> = 0) {
      return [map = std::forward<T>(map)](OptIndex idx, string_view path) -> Value
      {
         auto key = popKey(path);
         auto itr = map.find(boost::lexical_cast<KeyT>(key.name));
         if (itr != map.end())
            return ValueConverter<ValueT>::get(itr->second)(key.idx, path);
         return ValueTag::Null;
      };
   }
};
}

template<typename KeyT, typename ValueT>
struct ValueConverter<std::map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename KeyT, typename ValueT>
struct ValueConverter<std::unordered_map<KeyT, ValueT>> : public impl::AssociativeContainerConverter<KeyT, ValueT> {
};

template<typename ValueT>
struct ValueConverter<std::vector<ValueT>> : public std::true_type {
   template<typename T>
   static auto get(T&& vec, std::enable_if_t<!hasValueConverter<typename std::decay_t<T>::value_type>, void**> = 0) {
      return [vec = std::forward<T>(vec)](OptIndex idx, string_view path) -> Value
      {
         if (!idx)
            return RangeDefinition{vec.size()};
         if (*idx < vec.size())
         {
            if (!path.empty())
               return ValueTag::SubValue;
            return toValue(vec[*idx]);
         }
         return ValueTag::OutOfRange;
      };
   }

   template<typename T>
   static auto get(T&& vec, std::enable_if_t<hasValueConverter<typename std::decay_t<T>::value_type>, void**> = 0) {
      return [vec = std::forward<T>(vec)](OptIndex idx, string_view path) -> Value
      {
         if (!idx)
            return RangeDefinition{vec.size()};
         if (*idx < vec.size())
            return ValueConverter<ValueT>::get(vec[*idx])(boost::none, path);
         return ValueTag::OutOfRange;
      };
   }
};
}
<|endoftext|>


<commit_before>/* Author: Matt Liberty */
/*
 * Copyright (c) 2021, The Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ord/OpenRoad.hh"

// Stubs out functions from OpenRoad that aren't needed by trTest but
// are referenced from TritonRoute.a or its dependencies.
char** cmd_argv;
int cmd_argc;
namespace ord {

OpenRoad::OpenRoad()
{
}

OpenRoad* OpenRoad::openRoad()
{
  return nullptr;
}

void OpenRoad::addObserver(Observer* observer)
{
}

void OpenRoad::removeObserver(Observer* observer)
{
}

int OpenRoad::getThreadCount()
{
  return 0;
}

OpenRoad::Observer::~Observer()
{
}

}  // namespace ord
int ord::tclAppInit(Tcl_Interp* interp)
{
  return -1;
}<commit_msg>drt: update stubs<commit_after>/* Author: Matt Liberty */
/*
 * Copyright (c) 2021, The Regents of the University of California
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "ord/OpenRoad.hh"

// Stubs out functions from OpenRoad that aren't needed by trTest but
// are referenced from TritonRoute.a or its dependencies.
char** cmd_argv;
int cmd_argc;
namespace ord {

OpenRoad::OpenRoad()
{
}

OpenRoad* OpenRoad::openRoad()
{
  return nullptr;
}

void OpenRoad::writeDb(const char *) {}

void OpenRoad::readDb(const char *) {}

void OpenRoad::addObserver(Observer* observer)
{
}

void OpenRoad::removeObserver(Observer* observer)
{
}

int OpenRoad::getThreadCount()
{
  return 0;
}

OpenRoad::Observer::~Observer()
{
}

}  // namespace ord
int ord::tclAppInit(Tcl_Interp* interp)
{
  return -1;
}<|endoftext|>


<commit_before>#ifndef ENTT_CORE_FLAG_HPP
#define ENTT_CORE_FLAG_HPP

#include <type_traits>
#include "../config/config.h"

namespace entt {

/**
 * @brief Enable bitmask support for enum classes.
 * @tparam Type The enum type for which to enable bitmask support.
 */
template<typename Type, typename = void>
struct enum_as_bitmask: std::false_type {};

/*! @copydoc enum_as_bitmask */
template<typename Type>
struct enum_as_bitmask<Type, std::void_t<decltype(Type::_entt_enum_as_bitmask)>>: std::true_type {};

/**
 * @brief Helper variable template.
 * @tparam Type The enum class type for which to enable bitmask support.
 */
template<typename Type>
inline constexpr bool enum_as_bitmask_v = enum_as_bitmask<Type>::value;

} // namespace entt

/**
 * @brief Operator available for enums for which bitmask support is enabled.
 * @tparam Type Enum class type.
 * @param lhs The first value to use.
 * @param rhs The second value to use.
 * @return The result of invoking the operator on the underlying types of the
 * two values provided.
 */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator|(const Type lhs, const Type rhs) ENTT_NOEXCEPT {
    return static_cast<Type>(static_cast<std::underlying_type_t<Type>>(lhs) | static_cast<std::underlying_type_t<Type>>(rhs));
}

/*! @copydoc operator| */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator&(const Type lhs, const Type rhs) ENTT_NOEXCEPT {
    return static_cast<Type>(static_cast<std::underlying_type_t<Type>>(lhs) & static_cast<std::underlying_type_t<Type>>(rhs));
}

/*! @copydoc operator| */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator^(const Type lhs, const Type rhs) ENTT_NOEXCEPT {
    return static_cast<Type>(static_cast<std::underlying_type_t<Type>>(lhs) ^ static_cast<std::underlying_type_t<Type>>(rhs));
}

/**
 * @brief Operator available for enums for which bitmask support is enabled.
 * @tparam Type Enum class type.
 * @param value The value to use.
 * @return The result of invoking the operator on the underlying types of the
 * value provided.
 */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator~(const Type value) ENTT_NOEXCEPT {
    return static_cast<Type>(~static_cast<std::underlying_type_t<Type>>(value));
}

/*! @copydoc operator~ */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, bool>
operator!(const Type value) ENTT_NOEXCEPT {
    return !static_cast<std::underlying_type_t<Type>>(value);
}

/*! @copydoc operator| */
template<typename Type>
constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type &>
operator|=(Type &lhs, const Type rhs) ENTT_NOEXCEPT {
    return (lhs = (lhs | rhs));
}

/*! @copydoc operator| */
template<typename Type>
constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type &>
operator&=(Type &lhs, const Type rhs) ENTT_NOEXCEPT {
    return (lhs = (lhs & rhs));
}

/*! @copydoc operator| */
template<typename Type>
constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type &>
operator^=(Type &lhs, const Type rhs) ENTT_NOEXCEPT {
    return (lhs = (lhs ^ rhs));
}

#endif
<commit_msg>enum: typo<commit_after>#ifndef ENTT_CORE_ENUM_HPP
#define ENTT_CORE_ENUM_HPP

#include <type_traits>
#include "../config/config.h"

namespace entt {

/**
 * @brief Enable bitmask support for enum classes.
 * @tparam Type The enum type for which to enable bitmask support.
 */
template<typename Type, typename = void>
struct enum_as_bitmask: std::false_type {};

/*! @copydoc enum_as_bitmask */
template<typename Type>
struct enum_as_bitmask<Type, std::void_t<decltype(Type::_entt_enum_as_bitmask)>>: std::true_type {};

/**
 * @brief Helper variable template.
 * @tparam Type The enum class type for which to enable bitmask support.
 */
template<typename Type>
inline constexpr bool enum_as_bitmask_v = enum_as_bitmask<Type>::value;

} // namespace entt

/**
 * @brief Operator available for enums for which bitmask support is enabled.
 * @tparam Type Enum class type.
 * @param lhs The first value to use.
 * @param rhs The second value to use.
 * @return The result of invoking the operator on the underlying types of the
 * two values provided.
 */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator|(const Type lhs, const Type rhs) ENTT_NOEXCEPT {
    return static_cast<Type>(static_cast<std::underlying_type_t<Type>>(lhs) | static_cast<std::underlying_type_t<Type>>(rhs));
}

/*! @copydoc operator| */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator&(const Type lhs, const Type rhs) ENTT_NOEXCEPT {
    return static_cast<Type>(static_cast<std::underlying_type_t<Type>>(lhs) & static_cast<std::underlying_type_t<Type>>(rhs));
}

/*! @copydoc operator| */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator^(const Type lhs, const Type rhs) ENTT_NOEXCEPT {
    return static_cast<Type>(static_cast<std::underlying_type_t<Type>>(lhs) ^ static_cast<std::underlying_type_t<Type>>(rhs));
}

/**
 * @brief Operator available for enums for which bitmask support is enabled.
 * @tparam Type Enum class type.
 * @param value The value to use.
 * @return The result of invoking the operator on the underlying types of the
 * value provided.
 */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type>
operator~(const Type value) ENTT_NOEXCEPT {
    return static_cast<Type>(~static_cast<std::underlying_type_t<Type>>(value));
}

/*! @copydoc operator~ */
template<typename Type>
[[nodiscard]] constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, bool>
operator!(const Type value) ENTT_NOEXCEPT {
    return !static_cast<std::underlying_type_t<Type>>(value);
}

/*! @copydoc operator| */
template<typename Type>
constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type &>
operator|=(Type &lhs, const Type rhs) ENTT_NOEXCEPT {
    return (lhs = (lhs | rhs));
}

/*! @copydoc operator| */
template<typename Type>
constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type &>
operator&=(Type &lhs, const Type rhs) ENTT_NOEXCEPT {
    return (lhs = (lhs & rhs));
}

/*! @copydoc operator| */
template<typename Type>
constexpr std::enable_if_t<std::is_enum_v<Type> && entt::enum_as_bitmask_v<Type>, Type &>
operator^=(Type &lhs, const Type rhs) ENTT_NOEXCEPT {
    return (lhs = (lhs ^ rhs));
}

#endif
<|endoftext|>


<commit_before>#include "faster-rnnlm/words.h"

#include <stdlib.h>
#include <string.h>

#include <algorithm>

namespace {
const char kEOSTag[] = "</s>";
const int kEOSSize = sizeof(kEOSTag);
const size_t kHashMinSize = 100000;
const double kHashMinFactor = 0.5;
const double kHashMaxFactor = 0.8;
};  // unnamed namespace

const WordIndex Vocabulary::kWordOOV;

// ============================================================================
// ============================== WordReader ==================================
// ============================================================================

inline bool IsSpace(char c) {
  return c == ' ' || c == '\r' || c == '\t' ||  c == '\n';
}

void FseekOrDie(FILE* stream, int offset, int whence, const std::string& fname) {
  if (fseek(stream, offset, whence) != 0) {
    fprintf(
        stderr, "ERROR: Failed to seek over file '%s'."
       " Make sure it is a regular file", fname.c_str());
    exit(1);
  }
}

// Read space-serated words from file; adds </s> to the end of each line
WordReader::WordReader(const std::string& fname)
    : file_(fname.empty() ? stdin : fopen(fname.c_str(), "rb"))
    , pointer_(NULL)
    , buffer_(new char[MAX_LINE_SIZE])
    , fname_(fname)
    , file_size_(0)
    , chunk_start_(0)
    , chunk_end_(-1)
{
  if (file_ == NULL) {
    fprintf(stderr, "ERROR failed to open %s\n", fname.c_str());
  }
  FseekOrDie(file_, 0, SEEK_END, fname_);
  file_size_ = ftell(file_);
  FseekOrDie(file_, 0, SEEK_SET, fname_);
}

bool WordReader::ReadWord(char* word) {
  if (pointer_ == NULL) {
    // loop until EOF or not-empty line
    for (; pointer_ == NULL || *pointer_ == 0;) {
      if (chunk_end_ != -1 && chunk_end_ < ftell(file_)) {
        return false;
      }

      if (fgets(buffer_, MAX_LINE_SIZE, file_) == NULL) {
        return false;
      }

      for (pointer_ = buffer_; IsSpace(*pointer_); ++pointer_) {}
    }
  }
  for (; IsSpace(*pointer_); ++pointer_) {}

  if (*pointer_ == 0) {
    strncpy(word, kEOSTag, MAX_STRING - 1);
    word[std::min(MAX_STRING, kEOSSize - 1)] = 0;
    pointer_ = NULL;
  } else {
    int i = 0;
    for (; !IsSpace(*pointer_) && i < MAX_STRING - 1; ++pointer_, ++i) {
      word[i] = *pointer_;
    }
    word[i] = 0;

    // drop reduntant characters
    for (; !IsSpace(*pointer_); ++pointer_) {}
  }

  return true;
}

void WordReader::SetChunk(int chunk, int chunk_count) {
  chunk_start_ = file_size_ / chunk_count * chunk;
  FseekOrDie(file_, chunk_start_, SEEK_SET, fname_);
  if (chunk + 1 == chunk_count) {
    chunk_end_ = -1;
  } else {
    chunk_end_ = file_size_ / chunk_count * (chunk + 1);
  }
  if (chunk != 0) {
    // skipping to the next newline
    for (char tmp[MAX_STRING]; ReadWord(tmp) && strcmp(tmp, kEOSTag) != 0; ) {}
  }
}

int64_t WordReader::GetDoneByteCount() const {
  return ftell(file_) - chunk_start_;
}

// ============================================================================
// ============================== Vocabulary ==================================
// ============================================================================

class Vocabulary::HashImpl {
 public:
  explicit HashImpl(const Vocabulary& vocabulary) : vocabulary(vocabulary) {
    Rebuild();
  }

  WordIndex Get(const char* word) const {
    return hash2index[Find(word)];
  }

  void Insert(const char* word, WordIndex idx) {
    size_t hash_idx = Find(word);
    if (hash2index[hash_idx] == Vocabulary::kWordOOV) {
      hash2index[hash_idx] = idx;
      if (hash2index.size() * kHashMaxFactor < vocabulary.size()) {
        Rebuild();
      }
    }
  }

  void Rebuild() {
    size_t size = std::max(kHashMinSize, static_cast<size_t>(vocabulary.size() / kHashMinFactor));
    hash2index.resize(size);
    std::fill(hash2index.begin(), hash2index.end(), Vocabulary::kWordOOV);
    for (int i = 0; i < vocabulary.size(); ++i) {
      Insert(vocabulary.GetWordByIndex(i), i);
    }
  }

 private:
  std::vector<WordIndex> hash2index;
  const Vocabulary& vocabulary;

  size_t Find(const char* word) const {
    size_t hash_index = CalculateHash(word) % hash2index.size();
    for (;; ++hash_index) {
      if (hash_index >= hash2index.size()) {
        hash_index = 0;
      }
      if (hash2index[hash_index] == Vocabulary::kWordOOV) {
        return hash_index;
      }
      WordIndex wid = hash2index[hash_index];
      if (strcmp(word, vocabulary.GetWordByIndex(wid)) == 0) {
        return hash_index;
      }
    }
  }

  static uint64_t CalculateHash(const char* word) {
    uint64_t hash = 42;
    const uint64_t p = 1000 * 1000 * 1000 + 7;
    for (; *word != 0; ++word) {
      hash = hash * p + *word;
    }
    return hash;
  }
};

Vocabulary::Vocabulary() : hash_impl_(new HashImpl(*this))
{
  // empty constructor
}

Vocabulary::~Vocabulary() {
  delete hash_impl_;
  for (int a = 0; a < size(); a++) {
    delete[] words_[a].word;
  }
}

WordIndex Vocabulary::GetIndexByWord(const char *word) const {
  return hash_impl_->Get(word);
}

const char* Vocabulary::GetWordByIndex(WordIndex index) const {
  if (static_cast<int>(index) >= 0 && static_cast<int>(index) < size()) {
    return words_[index].word;
  }
  return NULL;
}

WordIndex Vocabulary::AddWord(const char *word) {
  int length = std::min<int>(strlen(word) + 1, MAX_STRING);

  Vocabulary::Word vocab_word = {0, NULL};
  vocab_word.word = new char[length];
  strncpy(vocab_word.word, word, length - 1);
  vocab_word.word[length - 1] = 0;
  words_.push_back(vocab_word);

  hash_impl_->Insert(word, size() - 1);
  return size() - 1;
}

struct VocabularyWordComparator {
  const bool stable_sort;

  explicit VocabularyWordComparator(bool stable_sort) : stable_sort(stable_sort) {}

  bool operator()(const Vocabulary::Word& first, const Vocabulary::Word& second) const {
    int frequency_diff = first.freq - second.freq;
    if (stable_sort || frequency_diff != 0) {
        return frequency_diff > 0;
    }
    return strncmp(first.word, second.word, MAX_STRING) < 0;
  }
};

// Sorts all words (except for '</s>') by frequency
//
// To sorting mode are available
//   stable mode (stable=true), i.e. stable sort by frequency (desc)
//   non-stable mode (stable=false), i.e. sort by frequency (desc) and word (asc)
//
// Note that word '</s>' has index zero
void Vocabulary::Sort(bool stable) {
  std::stable_sort(words_.begin() + 1, words_.end(), VocabularyWordComparator(stable));
  hash_impl_->Rebuild();
}

void Vocabulary::BuildFromCorpus(const std::string& fpath, bool show_progress) {
  char buffer[MAX_STRING];
  AddWord(kEOSTag);

  WordReader reader(fpath.c_str());
  for (int64_t read_words = 0; reader.ReadWord(buffer); ++read_words) {
    if (show_progress && (read_words % 1000000 == 0)) {
      fprintf(stderr, "Reading train file: %.1lfKK words\r",
          static_cast<double>(read_words / 1000) / 1000);
    }
    WordIndex wid = GetIndexByWord(buffer);
    if (wid == kWordOOV) {
      wid = AddWord(buffer);
    }
    words_[wid].freq++;
  }
  Sort(false);
}

void Vocabulary::Dump(const std::string& fpath) const {
  FILE *file = fopen(fpath.c_str(), "wb");
  for (int i = 0; i < size(); i++) {
    fprintf(file, "%s %" PRId64 "\n", words_[i].word, words_[i].freq);
  }
  fclose(file);
}

void Vocabulary::Load(const std::string& fpath) {
  FILE *file = fopen(fpath.c_str(), "rb");
  if (file == NULL) {
    fprintf(stderr, "ERROR: Cannot find vocabulary file '%s'\n", fpath.c_str());
    exit(1);
  }

  for (int line_number = 0; !feof(file); ++line_number) {
    char buffer[MAX_STRING];
    uint64_t count;
    if (fscanf(file, "%s %" PRId64 " ", buffer, &count) != 2) {
      fprintf(stderr, "WARNING: Skipping ill-formed line #%d in the vocabulary\n", line_number);
      continue;
    }
    WordIndex wid = AddWord(buffer);
    words_[wid].freq = count;
  }
  Sort(true);
}

void Vocabulary::AdjustSizeForSoftmaxTree(int arity) {
  int imperfection_size = (size() - 1 + (arity - 1)) % (arity - 1);
  if (imperfection_size == 0) {
      return;
  }
  fprintf(stderr, "Have to add %d words\n", imperfection_size);
  const int kBufferSize = 100;
  char buffer[kBufferSize];
  for (int a = 0; a < arity - 1 - imperfection_size; ++a) {
      snprintf(static_cast<char*>(buffer), kBufferSize,  "__**FAKE_WORD%d", a);
      WordIndex wid = AddWord(buffer);
      words_[wid].freq = 0;
  }
  Sort(false);
}

// ============================================================================
// =========================== SentenceReader =================================
// ============================================================================

SentenceReader::SentenceReader(
        const Vocabulary& vocab, const std::string& filename, bool reverse, bool auto_insert_unk)
    : WordReader(filename)
    , sentence_length_(0)
    , sentence_id_(-1)
    , vocab_(vocab)
    , unk_word_(vocab.GetIndexByWord("<unk>"))
    , reverse_(reverse)
    , done_(false)
    , oov_occured_(false)
{
  if (auto_insert_unk && unk_word_ == Vocabulary::kWordOOV) {
    fprintf(stderr, "Cannot use auto_insert_unk as '<unk>' is not found in the vocabulary\n");
    exit(1);
  }
}

bool SentenceReader::ReadWordId(WordIndex* wid) {
  char buffer[MAX_STRING];
  if (!ReadWord(buffer)) {
    return false;
  }
  *wid = vocab_.GetIndexByWord(buffer);
  return true;
}

bool SentenceReader::Read() {
  if (done_)
    return false;

  ++sentence_id_;
  sen_[0] = 0;      // <s> token
  oov_occured_ = false;
  for (sentence_length_ = 1; sentence_length_ < MAX_SENTENCE_WORDS; ++sentence_length_) {
    WordIndex wid;
    if (!ReadWordId(&wid)) {
      done_ = true;
      return false;
    }
    if (wid == Vocabulary::kWordOOV) {
      oov_occured_ = true;
      wid = unk_word_;
    }
    sen_[sentence_length_] = wid;
    if (wid == 0) {
      break;
    }
  }

  if (sentence_length_ == MAX_SENTENCE_WORDS) {
    // too long sentence -> drop trailing words
    for (;;) {
      WordIndex wid;
      if (!ReadWordId(&wid)) {
        done_ = true;
        return false;
      }
      if (wid == 0) {
        break;
      }
    }
    --sentence_length_;
    sen_[sentence_length_] = 0;
  }

  if (reverse_) {
    for (int i = 1; i < sentence_length_ - i; ++i) {
      std::swap(sen_[i], sen_[sentence_length_ - i]);
    }
  }

  return true;
}

<commit_msg>Fix tiny bug with handling of big files<commit_after>#include "faster-rnnlm/words.h"

#include <stdlib.h>
#include <string.h>

#include <algorithm>

namespace {
const char kEOSTag[] = "</s>";
const int kEOSSize = sizeof(kEOSTag);
const size_t kHashMinSize = 100000;
const double kHashMinFactor = 0.5;
const double kHashMaxFactor = 0.8;
};  // unnamed namespace

const WordIndex Vocabulary::kWordOOV;

// ============================================================================
// ============================== WordReader ==================================
// ============================================================================

inline bool IsSpace(char c) {
  return c == ' ' || c == '\r' || c == '\t' ||  c == '\n';
}

void FseekOrDie(FILE* stream, long int offset, int whence, const std::string& fname) {
  if (fseek(stream, offset, whence) != 0) {
    fprintf(
        stderr, "ERROR: Failed to seek over file '%s'."
       " Make sure it is a regular file", fname.c_str());
    exit(1);
  }
}

// Read space-serated words from file; adds </s> to the end of each line
WordReader::WordReader(const std::string& fname)
    : file_(fname.empty() ? stdin : fopen(fname.c_str(), "rb"))
    , pointer_(NULL)
    , buffer_(new char[MAX_LINE_SIZE])
    , fname_(fname)
    , file_size_(0)
    , chunk_start_(0)
    , chunk_end_(-1)
{
  if (file_ == NULL) {
    fprintf(stderr, "ERROR failed to open %s\n", fname.c_str());
  }
  FseekOrDie(file_, 0, SEEK_END, fname_);
  file_size_ = ftell(file_);
  FseekOrDie(file_, 0, SEEK_SET, fname_);
}

bool WordReader::ReadWord(char* word) {
  if (pointer_ == NULL) {
    // loop until EOF or not-empty line
    for (; pointer_ == NULL || *pointer_ == 0;) {
      if (chunk_end_ != -1 && chunk_end_ < ftell(file_)) {
        return false;
      }

      if (fgets(buffer_, MAX_LINE_SIZE, file_) == NULL) {
        return false;
      }

      for (pointer_ = buffer_; IsSpace(*pointer_); ++pointer_) {}
    }
  }
  for (; IsSpace(*pointer_); ++pointer_) {}

  if (*pointer_ == 0) {
    strncpy(word, kEOSTag, MAX_STRING - 1);
    word[std::min(MAX_STRING, kEOSSize - 1)] = 0;
    pointer_ = NULL;
  } else {
    int i = 0;
    for (; !IsSpace(*pointer_) && i < MAX_STRING - 1; ++pointer_, ++i) {
      word[i] = *pointer_;
    }
    word[i] = 0;

    // drop reduntant characters
    for (; !IsSpace(*pointer_); ++pointer_) {}
  }

  return true;
}

void WordReader::SetChunk(int chunk, int chunk_count) {
  chunk_start_ = file_size_ / chunk_count * chunk;
  FseekOrDie(file_, chunk_start_, SEEK_SET, fname_);
  if (chunk + 1 == chunk_count) {
    chunk_end_ = -1;
  } else {
    chunk_end_ = file_size_ / chunk_count * (chunk + 1);
  }
  if (chunk != 0) {
    // skipping to the next newline
    for (char tmp[MAX_STRING]; ReadWord(tmp) && strcmp(tmp, kEOSTag) != 0; ) {}
  }
}

int64_t WordReader::GetDoneByteCount() const {
  return ftell(file_) - chunk_start_;
}

// ============================================================================
// ============================== Vocabulary ==================================
// ============================================================================

class Vocabulary::HashImpl {
 public:
  explicit HashImpl(const Vocabulary& vocabulary) : vocabulary(vocabulary) {
    Rebuild();
  }

  WordIndex Get(const char* word) const {
    return hash2index[Find(word)];
  }

  void Insert(const char* word, WordIndex idx) {
    size_t hash_idx = Find(word);
    if (hash2index[hash_idx] == Vocabulary::kWordOOV) {
      hash2index[hash_idx] = idx;
      if (hash2index.size() * kHashMaxFactor < vocabulary.size()) {
        Rebuild();
      }
    }
  }

  void Rebuild() {
    size_t size = std::max(kHashMinSize, static_cast<size_t>(vocabulary.size() / kHashMinFactor));
    hash2index.resize(size);
    std::fill(hash2index.begin(), hash2index.end(), Vocabulary::kWordOOV);
    for (int i = 0; i < vocabulary.size(); ++i) {
      Insert(vocabulary.GetWordByIndex(i), i);
    }
  }

 private:
  std::vector<WordIndex> hash2index;
  const Vocabulary& vocabulary;

  size_t Find(const char* word) const {
    size_t hash_index = CalculateHash(word) % hash2index.size();
    for (;; ++hash_index) {
      if (hash_index >= hash2index.size()) {
        hash_index = 0;
      }
      if (hash2index[hash_index] == Vocabulary::kWordOOV) {
        return hash_index;
      }
      WordIndex wid = hash2index[hash_index];
      if (strcmp(word, vocabulary.GetWordByIndex(wid)) == 0) {
        return hash_index;
      }
    }
  }

  static uint64_t CalculateHash(const char* word) {
    uint64_t hash = 42;
    const uint64_t p = 1000 * 1000 * 1000 + 7;
    for (; *word != 0; ++word) {
      hash = hash * p + *word;
    }
    return hash;
  }
};

Vocabulary::Vocabulary() : hash_impl_(new HashImpl(*this))
{
  // empty constructor
}

Vocabulary::~Vocabulary() {
  delete hash_impl_;
  for (int a = 0; a < size(); a++) {
    delete[] words_[a].word;
  }
}

WordIndex Vocabulary::GetIndexByWord(const char *word) const {
  return hash_impl_->Get(word);
}

const char* Vocabulary::GetWordByIndex(WordIndex index) const {
  if (static_cast<int>(index) >= 0 && static_cast<int>(index) < size()) {
    return words_[index].word;
  }
  return NULL;
}

WordIndex Vocabulary::AddWord(const char *word) {
  int length = std::min<int>(strlen(word) + 1, MAX_STRING);

  Vocabulary::Word vocab_word = {0, NULL};
  vocab_word.word = new char[length];
  strncpy(vocab_word.word, word, length - 1);
  vocab_word.word[length - 1] = 0;
  words_.push_back(vocab_word);

  hash_impl_->Insert(word, size() - 1);
  return size() - 1;
}

struct VocabularyWordComparator {
  const bool stable_sort;

  explicit VocabularyWordComparator(bool stable_sort) : stable_sort(stable_sort) {}

  bool operator()(const Vocabulary::Word& first, const Vocabulary::Word& second) const {
    int frequency_diff = first.freq - second.freq;
    if (stable_sort || frequency_diff != 0) {
        return frequency_diff > 0;
    }
    return strncmp(first.word, second.word, MAX_STRING) < 0;
  }
};

// Sorts all words (except for '</s>') by frequency
//
// To sorting mode are available
//   stable mode (stable=true), i.e. stable sort by frequency (desc)
//   non-stable mode (stable=false), i.e. sort by frequency (desc) and word (asc)
//
// Note that word '</s>' has index zero
void Vocabulary::Sort(bool stable) {
  std::stable_sort(words_.begin() + 1, words_.end(), VocabularyWordComparator(stable));
  hash_impl_->Rebuild();
}

void Vocabulary::BuildFromCorpus(const std::string& fpath, bool show_progress) {
  char buffer[MAX_STRING];
  AddWord(kEOSTag);

  WordReader reader(fpath.c_str());
  for (int64_t read_words = 0; reader.ReadWord(buffer); ++read_words) {
    if (show_progress && (read_words % 1000000 == 0)) {
      fprintf(stderr, "Reading train file: %.1lfKK words\r",
          static_cast<double>(read_words / 1000) / 1000);
    }
    WordIndex wid = GetIndexByWord(buffer);
    if (wid == kWordOOV) {
      wid = AddWord(buffer);
    }
    words_[wid].freq++;
  }
  Sort(false);
}

void Vocabulary::Dump(const std::string& fpath) const {
  FILE *file = fopen(fpath.c_str(), "wb");
  for (int i = 0; i < size(); i++) {
    fprintf(file, "%s %" PRId64 "\n", words_[i].word, words_[i].freq);
  }
  fclose(file);
}

void Vocabulary::Load(const std::string& fpath) {
  FILE *file = fopen(fpath.c_str(), "rb");
  if (file == NULL) {
    fprintf(stderr, "ERROR: Cannot find vocabulary file '%s'\n", fpath.c_str());
    exit(1);
  }

  for (int line_number = 0; !feof(file); ++line_number) {
    char buffer[MAX_STRING];
    uint64_t count;
    if (fscanf(file, "%s %" PRId64 " ", buffer, &count) != 2) {
      fprintf(stderr, "WARNING: Skipping ill-formed line #%d in the vocabulary\n", line_number);
      continue;
    }
    WordIndex wid = AddWord(buffer);
    words_[wid].freq = count;
  }
  Sort(true);
}

void Vocabulary::AdjustSizeForSoftmaxTree(int arity) {
  int imperfection_size = (size() - 1 + (arity - 1)) % (arity - 1);
  if (imperfection_size == 0) {
      return;
  }
  fprintf(stderr, "Have to add %d words\n", imperfection_size);
  const int kBufferSize = 100;
  char buffer[kBufferSize];
  for (int a = 0; a < arity - 1 - imperfection_size; ++a) {
      snprintf(static_cast<char*>(buffer), kBufferSize,  "__**FAKE_WORD%d", a);
      WordIndex wid = AddWord(buffer);
      words_[wid].freq = 0;
  }
  Sort(false);
}

// ============================================================================
// =========================== SentenceReader =================================
// ============================================================================

SentenceReader::SentenceReader(
        const Vocabulary& vocab, const std::string& filename, bool reverse, bool auto_insert_unk)
    : WordReader(filename)
    , sentence_length_(0)
    , sentence_id_(-1)
    , vocab_(vocab)
    , unk_word_(vocab.GetIndexByWord("<unk>"))
    , reverse_(reverse)
    , done_(false)
    , oov_occured_(false)
{
  if (auto_insert_unk && unk_word_ == Vocabulary::kWordOOV) {
    fprintf(stderr, "Cannot use auto_insert_unk as '<unk>' is not found in the vocabulary\n");
    exit(1);
  }
}

bool SentenceReader::ReadWordId(WordIndex* wid) {
  char buffer[MAX_STRING];
  if (!ReadWord(buffer)) {
    return false;
  }
  *wid = vocab_.GetIndexByWord(buffer);
  return true;
}

bool SentenceReader::Read() {
  if (done_)
    return false;

  ++sentence_id_;
  sen_[0] = 0;      // <s> token
  oov_occured_ = false;
  for (sentence_length_ = 1; sentence_length_ < MAX_SENTENCE_WORDS; ++sentence_length_) {
    WordIndex wid;
    if (!ReadWordId(&wid)) {
      done_ = true;
      return false;
    }
    if (wid == Vocabulary::kWordOOV) {
      oov_occured_ = true;
      wid = unk_word_;
    }
    sen_[sentence_length_] = wid;
    if (wid == 0) {
      break;
    }
  }

  if (sentence_length_ == MAX_SENTENCE_WORDS) {
    // too long sentence -> drop trailing words
    for (;;) {
      WordIndex wid;
      if (!ReadWordId(&wid)) {
        done_ = true;
        return false;
      }
      if (wid == 0) {
        break;
      }
    }
    --sentence_length_;
    sen_[sentence_length_] = 0;
  }

  if (reverse_) {
    for (int i = 1; i < sentence_length_ - i; ++i) {
      std::swap(sen_[i], sen_[sentence_length_ - i]);
    }
  }

  return true;
}

<|endoftext|>


<commit_before>#define SOFA_COMPONENT_MISC_ADDRESOURCEREPOSITORY_CPP

#include <SofaMisc/AddResourceRepository.h>

#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/core/ObjectFactory.h>

namespace sofa
{

namespace component
{

namespace misc
{

SOFA_DECL_CLASS(AddResourceRepository)

int AddResourceRepositoryClass = core::RegisterObject("Add a repository to the pool of resources")
.add< AddResourceRepository >();

AddResourceRepository::AddResourceRepository()
    : Inherit()
    , d_repositoryPath(initData(&d_repositoryPath, "path", "Path to add to the pool of resources"))
    , m_currentAddedPath()
{

}

AddResourceRepository::~AddResourceRepository()
{

}

void AddResourceRepository::parse(sofa::core::objectmodel::BaseObjectDescription* arg)
{
    Inherit::parse(arg);
    std::string tmpAddedPath;
    tmpAddedPath = d_repositoryPath.getValue();

    //first
    //if absolute, add directly in the list of paths
    //else prepend (absolute) current directory to the given path and add it
    if (!sofa::helper::system::FileSystem::isAbsolute(tmpAddedPath))
    {
        tmpAddedPath = sofa::helper::system::SetDirectory::GetCurrentDir() + "/" + tmpAddedPath;
    }
    //second, check if the path exists
    if (!sofa::helper::system::FileSystem::exists(tmpAddedPath))
    {
        msg_error(this) << tmpAddedPath + "does not exist !";
        return;
    }
    //third, check if it is really a directory
    if (!sofa::helper::system::FileSystem::isDirectory(tmpAddedPath))
    {
        msg_error(this) << tmpAddedPath + "is not a valid directory !";
        return;
    }

    m_currentAddedPath = tmpAddedPath;
    sofa::helper::system::DataRepository.addLastPath(m_currentAddedPath);

    if(this->f_printLog.getValue())
        sofa::helper::system::DataRepository.print();
}

void AddResourceRepository::cleanup()
{
    Inherit::cleanup();
    sofa::helper::system::DataRepository.removePath(m_currentAddedPath);

}

} // namespace misc

} // namespace component

} // namespace sofa
<commit_msg>[SofaMisc] fix print<commit_after>#define SOFA_COMPONENT_MISC_ADDRESOURCEREPOSITORY_CPP

#include <SofaMisc/AddResourceRepository.h>

#include <sofa/helper/system/SetDirectory.h>
#include <sofa/helper/system/FileSystem.h>
#include <sofa/core/ObjectFactory.h>

namespace sofa
{

namespace component
{

namespace misc
{

SOFA_DECL_CLASS(AddResourceRepository)

int AddResourceRepositoryClass = core::RegisterObject("Add a repository to the pool of resources")
.add< AddResourceRepository >();

AddResourceRepository::AddResourceRepository()
    : Inherit()
    , d_repositoryPath(initData(&d_repositoryPath, "path", "Path to add to the pool of resources"))
    , m_currentAddedPath()
{

}

AddResourceRepository::~AddResourceRepository()
{

}

void AddResourceRepository::parse(sofa::core::objectmodel::BaseObjectDescription* arg)
{
    Inherit::parse(arg);
    std::string tmpAddedPath;
    tmpAddedPath = d_repositoryPath.getValue();

    //first
    //if absolute, add directly in the list of paths
    //else prepend (absolute) current directory to the given path and add it
    if (!sofa::helper::system::FileSystem::isAbsolute(tmpAddedPath))
    {
        tmpAddedPath = sofa::helper::system::SetDirectory::GetCurrentDir() + "/" + tmpAddedPath;
    }
    //second, check if the path exists
    if (!sofa::helper::system::FileSystem::exists(tmpAddedPath))
    {
        msg_error(this) << tmpAddedPath + " does not exist !";
        return;
    }
    //third, check if it is really a directory
    if (!sofa::helper::system::FileSystem::isDirectory(tmpAddedPath))
    {
        msg_error(this) << tmpAddedPath + " is not a valid directory !";
        return;
    }

    m_currentAddedPath = tmpAddedPath;
    sofa::helper::system::DataRepository.addLastPath(m_currentAddedPath);

    if(this->f_printLog.getValue())
        sofa::helper::system::DataRepository.print();
}

void AddResourceRepository::cleanup()
{
    Inherit::cleanup();
    sofa::helper::system::DataRepository.removePath(m_currentAddedPath);

}

} // namespace misc

} // namespace component

} // namespace sofa
<|endoftext|>


<commit_before>// $Id$

void geom_ddip()
{
  using namespace std;

  gGeoManager = gReve->GetGeometry("$REVESYS/alice-data/alice_fullgeo.root");
  TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("DDIP_1");

  Reve::GeoTopNodeRnrEl* its_re =
    new Reve::GeoTopNodeRnrEl(gGeoManager, node);
  gReve->AddGlobalRenderElement(its_re);
  gReve->DrawRenderElement(its_re);
}
<commit_msg>Use node's global transformation.<commit_after>// $Id$

void geom_ddip()
{
  using namespace std;

  gGeoManager = gReve->GetGeometry("$REVESYS/alice-data/alice_fullgeo.root");
  TGeoNode* node = gGeoManager->GetTopVolume()->FindNode("DDIP_1");

  Reve::GeoTopNodeRnrEl* its_re =
    new Reve::GeoTopNodeRnrEl(gGeoManager, node);
  re->SetUseNodeTrans(kTRUE);
  gReve->AddGlobalRenderElement(its_re);
  gReve->DrawRenderElement(its_re);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: implbase.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 09:12:29 $
 *
 *  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 _CPPUHELPER_IMPLBASE_HXX_
#define _CPPUHELPER_IMPLBASE_HXX_

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef _CPPUHELPER_WEAKAGG_HXX_
#include <cppuhelper/weakagg.hxx>
#endif
#ifndef INCLUDED_RTL_INSTANCE_HXX
#include <rtl/instance.hxx>
#endif

#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

/* This header should not be used anymore.
   @deprecated
*/

namespace cppu
{

/** Struct used for inline template implementation helpers: type entries.
    Not for plublic use.
    @internal
*/
struct Type_Offset
{
    /** binary offset of vtable pointer from object base
    */
    sal_Int32 nOffset;
    /** interface type description of interface entry
    */
    typelib_InterfaceTypeDescription * pTD;
};
/** Struct used for inline template implementation helpers: class data of implementation.
    Not for plublic use.
    @internal
*/
struct ClassDataBase
{
    /** determines whether the class data has been statically initialized
    */
    sal_Bool  bOffsetsInit;
    /** length of static array ClassDataN
    */
    sal_Int32 nType2Offset;

    /** class code determines which standard types are supported (and returned on
        com.sun.star.lang.XTypeProvider::getTypes()) by the helper:

        - 1 -- com.sun.star.uno.XWeak
        - 2 -- com.sun.star.uno.XWeak, com.sun.star.uno.XAggregation
        - 3 -- com.sun.star.uno.XWeak, com.sun.star.uno.XAggregation, com.sun.star.lang.XComponent
        - 4 -- com.sun.star.uno.XWeak, com.sun.star.lang.XComponent
    */
    sal_Int32 nClassCode;

    /** pointer to types sequence (com.sun.star.lang.XTypeProvider)
    */
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > * pTypes;
    /** pointer to class id (com.sun.star.lang.XTypeProvider)
    */
    ::com::sun::star::uno::Sequence< sal_Int8 > * pId;

    /** def ctor
    */
    ClassDataBase() SAL_THROW( () );
    /** class code ctor

        @param nClassCode class code, see ClassDataBase::nClassCode
    */
    ClassDataBase( sal_Int32 nClassCode ) SAL_THROW( () );
    /** dtor
    */
    ~ClassDataBase() SAL_THROW( () );
};
/** Struct used for inline template implementation helpers:
    There will be versions of this struct with varying arType2Offset[] array sizes, each of which
    is binary compatible with this one to be casted and used uniform. The size of the varying array
    is set in ClassDataBase::nType2Offset (base class).
    Not for plublic use.
    @internal
*/
struct ClassData : public ClassDataBase
{
    /** type entries array
    */
    Type_Offset arType2Offset[1];

    /** init call for supporting com.sun.star.lang.XTypeProvider
    */
    void SAL_CALL initTypeProvider() SAL_THROW( () );
    /** initial writing type offsets for vtables

        @param rType type of interface
        @param nOffset offset to vtable entry
    */
    void SAL_CALL writeTypeOffset( const ::com::sun::star::uno::Type & rType, sal_Int32 nOffset )
        SAL_THROW( () );

    /** Queries for an interface.

        @param rType demanded interface type
        @pBase base this pointer related when writing type offsets (writeTypeOffset())
        @return demanded interface or empty any
    */
    ::com::sun::star::uno::Any SAL_CALL query(
        const ::com::sun::star::uno::Type & rType, ::com::sun::star::lang::XTypeProvider * pBase )
        SAL_THROW( () );
    /** Gets the types for supporting com.sun.star.lang.XTypeProvider

        @return sequence of types supported
    */
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes()
        SAL_THROW( () );
    /** Gets the class id of implemtation supporting com.sun.star.lang.XTypeProvider

        @return class identifier (sequence< byte >)
    */
    ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId()
        SAL_THROW( () );
};

/** Shared mutex for implementation helper initialization.
    Not for public use.
    @internal
*/
::osl::Mutex & SAL_CALL getImplHelperInitMutex(void) SAL_THROW( () );
}

//
// settle down beavis, here comes the macro template hell :]
//

//==================================================================================================

/** Implementation helper macros
    Not for common use. There are expanded forms of the macro usage in implbaseN.hxx/compbaseN.hxx.
    So there is commonly no need to use these macros. Though, you may need to implement more than
    12 interfaces. Then you have to declare something like the following in your headers
    (where N is your demanded number of interfaces):

    #define __IFC3 Ifc1, Ifc2, Ifc3, ... up to N
    #define __CLASS_IFC3 class Ifc1, class Ifc2, class Ifc3, ... up to N
    #define __PUBLIC_IFC3 public Ifc1, public Ifc2, public Ifc3, ... up to N
    __DEF_IMPLHELPER_PRE( N )
    __IFC_WRITEOFFSET( 1 ) __IFC_WRITEOFFSET( 2 ) __IFC_WRITEOFFSET( 3 ), ... up to N
    __DEF_IMPLHELPER_POST( N )

    @internal
*/
#define __DEF_IMPLHELPER_PRE( N ) \
namespace cppu \
{ \
struct ClassData##N : public ClassDataBase \
{ \
    Type_Offset arType2Offset[ N ]; \
    ClassData##N( sal_Int32 nClassCode ) SAL_THROW( () ) \
        : ClassDataBase( nClassCode ) \
        {} \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE ImplHelperBase##N \
    : public ::com::sun::star::lang::XTypeProvider \
    , __PUBLIC_IFC##N \
{ \
protected: \
    ClassData & SAL_CALL getClassData( ClassDataBase & s_aCD ) SAL_THROW( () ) \
    { \
        ClassData & rCD = * static_cast< ClassData * >( &s_aCD ); \
        if (! rCD.bOffsetsInit) \
        { \
            ::osl::MutexGuard aGuard( getImplHelperInitMutex() ); \
            if (! rCD.bOffsetsInit) \
            { \
                char * pBase = (char *)this;
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __IFC_WRITEOFFSET( N ) \
                rCD.writeTypeOffset( ::getCppuType( (const ::com::sun::star::uno::Reference< Ifc##N > *)0 ), \
                                     (char *)(Ifc##N *)this - pBase );
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST_A( N ) \
                rCD.bOffsetsInit = sal_True; \
            } \
        } \
        return rCD; \
    } \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE ImplHelper##N \
    : public ImplHelperBase##N< __IFC##N > \
{ \
    static ClassData##N s_aCD; \
public: \
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).query( rType, (ImplHelperBase##N< __IFC##N > *)this ); } \
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getTypes(); } \
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getImplementationId(); } \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE WeakImplHelper##N \
    : public ::cppu::OWeakObject \
    , public ImplHelperBase##N< __IFC##N > \
{ \
    static ClassData##N s_aCD; \
public: \
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
    { \
        ::com::sun::star::uno::Any aRet( this->getClassData( s_aCD ).query( rType, (ImplHelperBase##N< __IFC##N > *)this ) ); \
        return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); \
    } \
    virtual void SAL_CALL acquire() throw () \
        { OWeakObject::acquire(); } \
    virtual void SAL_CALL release() throw () \
        { OWeakObject::release(); } \
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getTypes(); } \
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getImplementationId(); } \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE WeakAggImplHelper##N \
    : public ::cppu::OWeakAggObject \
    , public ImplHelperBase##N< __IFC##N > \
{ \
    static ClassData##N s_aCD; \
public: \
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
        { return OWeakAggObject::queryInterface( rType ); } \
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
    { \
        ::com::sun::star::uno::Any aRet( this->getClassData( s_aCD ).query( rType, (ImplHelperBase##N< __IFC##N > *)this ) ); \
        return (aRet.hasValue() ? aRet : OWeakAggObject::queryAggregation( rType )); \
    } \
    virtual void SAL_CALL acquire() throw () \
        { OWeakAggObject::acquire(); } \
    virtual void SAL_CALL release() throw () \
        { OWeakAggObject::release(); } \
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getTypes(); } \
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getImplementationId(); } \
};

/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST_B( N ) \
template< __CLASS_IFC##N > \
ClassData##N ImplHelper##N< __IFC##N >::s_aCD = ClassData##N( 0 ); \
template< __CLASS_IFC##N > \
ClassData##N WeakImplHelper##N< __IFC##N >::s_aCD = ClassData##N( 1 ); \
template< __CLASS_IFC##N > \
ClassData##N WeakAggImplHelper##N< __IFC##N >::s_aCD = ClassData##N( 2 );
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST_C( N ) \
}
//==================================================================================================
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST( N ) \
__DEF_IMPLHELPER_POST_A( N ) \
__DEF_IMPLHELPER_POST_B( N ) \
__DEF_IMPLHELPER_POST_C( N )
#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.14.140); FILE MERGED 2008/04/01 15:10:51 thb 1.14.140.3: #i85898# Stripping all external header guards 2008/04/01 10:54:23 thb 1.14.140.2: #i85898# Stripping all external header guards 2008/03/28 15:25:20 rt 1.14.140.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: implbase.hxx,v $
 * $Revision: 1.15 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CPPUHELPER_IMPLBASE_HXX_
#define _CPPUHELPER_IMPLBASE_HXX_

#include <osl/mutex.hxx>
#include <cppuhelper/weak.hxx>
#include <cppuhelper/weakagg.hxx>
#include <rtl/instance.hxx>

#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

/* This header should not be used anymore.
   @deprecated
*/

namespace cppu
{

/** Struct used for inline template implementation helpers: type entries.
    Not for plublic use.
    @internal
*/
struct Type_Offset
{
    /** binary offset of vtable pointer from object base
    */
    sal_Int32 nOffset;
    /** interface type description of interface entry
    */
    typelib_InterfaceTypeDescription * pTD;
};
/** Struct used for inline template implementation helpers: class data of implementation.
    Not for plublic use.
    @internal
*/
struct ClassDataBase
{
    /** determines whether the class data has been statically initialized
    */
    sal_Bool  bOffsetsInit;
    /** length of static array ClassDataN
    */
    sal_Int32 nType2Offset;

    /** class code determines which standard types are supported (and returned on
        com.sun.star.lang.XTypeProvider::getTypes()) by the helper:

        - 1 -- com.sun.star.uno.XWeak
        - 2 -- com.sun.star.uno.XWeak, com.sun.star.uno.XAggregation
        - 3 -- com.sun.star.uno.XWeak, com.sun.star.uno.XAggregation, com.sun.star.lang.XComponent
        - 4 -- com.sun.star.uno.XWeak, com.sun.star.lang.XComponent
    */
    sal_Int32 nClassCode;

    /** pointer to types sequence (com.sun.star.lang.XTypeProvider)
    */
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > * pTypes;
    /** pointer to class id (com.sun.star.lang.XTypeProvider)
    */
    ::com::sun::star::uno::Sequence< sal_Int8 > * pId;

    /** def ctor
    */
    ClassDataBase() SAL_THROW( () );
    /** class code ctor

        @param nClassCode class code, see ClassDataBase::nClassCode
    */
    ClassDataBase( sal_Int32 nClassCode ) SAL_THROW( () );
    /** dtor
    */
    ~ClassDataBase() SAL_THROW( () );
};
/** Struct used for inline template implementation helpers:
    There will be versions of this struct with varying arType2Offset[] array sizes, each of which
    is binary compatible with this one to be casted and used uniform. The size of the varying array
    is set in ClassDataBase::nType2Offset (base class).
    Not for plublic use.
    @internal
*/
struct ClassData : public ClassDataBase
{
    /** type entries array
    */
    Type_Offset arType2Offset[1];

    /** init call for supporting com.sun.star.lang.XTypeProvider
    */
    void SAL_CALL initTypeProvider() SAL_THROW( () );
    /** initial writing type offsets for vtables

        @param rType type of interface
        @param nOffset offset to vtable entry
    */
    void SAL_CALL writeTypeOffset( const ::com::sun::star::uno::Type & rType, sal_Int32 nOffset )
        SAL_THROW( () );

    /** Queries for an interface.

        @param rType demanded interface type
        @pBase base this pointer related when writing type offsets (writeTypeOffset())
        @return demanded interface or empty any
    */
    ::com::sun::star::uno::Any SAL_CALL query(
        const ::com::sun::star::uno::Type & rType, ::com::sun::star::lang::XTypeProvider * pBase )
        SAL_THROW( () );
    /** Gets the types for supporting com.sun.star.lang.XTypeProvider

        @return sequence of types supported
    */
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes()
        SAL_THROW( () );
    /** Gets the class id of implemtation supporting com.sun.star.lang.XTypeProvider

        @return class identifier (sequence< byte >)
    */
    ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId()
        SAL_THROW( () );
};

/** Shared mutex for implementation helper initialization.
    Not for public use.
    @internal
*/
::osl::Mutex & SAL_CALL getImplHelperInitMutex(void) SAL_THROW( () );
}

//
// settle down beavis, here comes the macro template hell :]
//

//==================================================================================================

/** Implementation helper macros
    Not for common use. There are expanded forms of the macro usage in implbaseN.hxx/compbaseN.hxx.
    So there is commonly no need to use these macros. Though, you may need to implement more than
    12 interfaces. Then you have to declare something like the following in your headers
    (where N is your demanded number of interfaces):

    #define __IFC3 Ifc1, Ifc2, Ifc3, ... up to N
    #define __CLASS_IFC3 class Ifc1, class Ifc2, class Ifc3, ... up to N
    #define __PUBLIC_IFC3 public Ifc1, public Ifc2, public Ifc3, ... up to N
    __DEF_IMPLHELPER_PRE( N )
    __IFC_WRITEOFFSET( 1 ) __IFC_WRITEOFFSET( 2 ) __IFC_WRITEOFFSET( 3 ), ... up to N
    __DEF_IMPLHELPER_POST( N )

    @internal
*/
#define __DEF_IMPLHELPER_PRE( N ) \
namespace cppu \
{ \
struct ClassData##N : public ClassDataBase \
{ \
    Type_Offset arType2Offset[ N ]; \
    ClassData##N( sal_Int32 nClassCode ) SAL_THROW( () ) \
        : ClassDataBase( nClassCode ) \
        {} \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE ImplHelperBase##N \
    : public ::com::sun::star::lang::XTypeProvider \
    , __PUBLIC_IFC##N \
{ \
protected: \
    ClassData & SAL_CALL getClassData( ClassDataBase & s_aCD ) SAL_THROW( () ) \
    { \
        ClassData & rCD = * static_cast< ClassData * >( &s_aCD ); \
        if (! rCD.bOffsetsInit) \
        { \
            ::osl::MutexGuard aGuard( getImplHelperInitMutex() ); \
            if (! rCD.bOffsetsInit) \
            { \
                char * pBase = (char *)this;
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __IFC_WRITEOFFSET( N ) \
                rCD.writeTypeOffset( ::getCppuType( (const ::com::sun::star::uno::Reference< Ifc##N > *)0 ), \
                                     (char *)(Ifc##N *)this - pBase );
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST_A( N ) \
                rCD.bOffsetsInit = sal_True; \
            } \
        } \
        return rCD; \
    } \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE ImplHelper##N \
    : public ImplHelperBase##N< __IFC##N > \
{ \
    static ClassData##N s_aCD; \
public: \
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).query( rType, (ImplHelperBase##N< __IFC##N > *)this ); } \
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getTypes(); } \
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getImplementationId(); } \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE WeakImplHelper##N \
    : public ::cppu::OWeakObject \
    , public ImplHelperBase##N< __IFC##N > \
{ \
    static ClassData##N s_aCD; \
public: \
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
    { \
        ::com::sun::star::uno::Any aRet( this->getClassData( s_aCD ).query( rType, (ImplHelperBase##N< __IFC##N > *)this ) ); \
        return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); \
    } \
    virtual void SAL_CALL acquire() throw () \
        { OWeakObject::acquire(); } \
    virtual void SAL_CALL release() throw () \
        { OWeakObject::release(); } \
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getTypes(); } \
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getImplementationId(); } \
}; \
template< __CLASS_IFC##N > \
class SAL_NO_VTABLE WeakAggImplHelper##N \
    : public ::cppu::OWeakAggObject \
    , public ImplHelperBase##N< __IFC##N > \
{ \
    static ClassData##N s_aCD; \
public: \
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
        { return OWeakAggObject::queryInterface( rType ); } \
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw (::com::sun::star::uno::RuntimeException) \
    { \
        ::com::sun::star::uno::Any aRet( this->getClassData( s_aCD ).query( rType, (ImplHelperBase##N< __IFC##N > *)this ) ); \
        return (aRet.hasValue() ? aRet : OWeakAggObject::queryAggregation( rType )); \
    } \
    virtual void SAL_CALL acquire() throw () \
        { OWeakAggObject::acquire(); } \
    virtual void SAL_CALL release() throw () \
        { OWeakAggObject::release(); } \
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getTypes(); } \
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId() throw (::com::sun::star::uno::RuntimeException) \
        { return this->getClassData( s_aCD ).getImplementationId(); } \
};

/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST_B( N ) \
template< __CLASS_IFC##N > \
ClassData##N ImplHelper##N< __IFC##N >::s_aCD = ClassData##N( 0 ); \
template< __CLASS_IFC##N > \
ClassData##N WeakImplHelper##N< __IFC##N >::s_aCD = ClassData##N( 1 ); \
template< __CLASS_IFC##N > \
ClassData##N WeakAggImplHelper##N< __IFC##N >::s_aCD = ClassData##N( 2 );
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST_C( N ) \
}
//==================================================================================================
/** Implementation helper macro: have a look at __DEF_IMPLHELPER_PRE
    @internal
*/
#define __DEF_IMPLHELPER_POST( N ) \
__DEF_IMPLHELPER_POST_A( N ) \
__DEF_IMPLHELPER_POST_B( N ) \
__DEF_IMPLHELPER_POST_C( N )
#endif

<|endoftext|>