<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef VALUE_HPP
#define VALUE_HPP

// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/variant.hpp>
#include <boost/scoped_array.hpp>
// stl
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// uci
#include <unicode/unistr.h>
#include <unicode/ustring.h>

namespace mapnik  {

   inline void to_utf8(UnicodeString const& input, std::string & target)
   {
      if (input.length() == 0) return;

      const int BUF_SIZE = 256;
      char  buf [BUF_SIZE];
      int len;

      UErrorCode err = U_ZERO_ERROR;
      u_strToUTF8(buf, BUF_SIZE, &len, input.getBuffer(), input.length(), &err);
      if (err == U_BUFFER_OVERFLOW_ERROR || err == U_STRING_NOT_TERMINATED_WARNING )
      {
         boost::scoped_array<char> buf_ptr(new char [len+1]);
         err = U_ZERO_ERROR;
         u_strToUTF8(buf_ptr.get() , len + 1, &len, input.getBuffer(), input.length(), &err);
         target.assign(buf_ptr.get() , len);
      }
      else
      {
         target.assign(buf, len);
      }
   }

   struct value_null
   {
   };

   typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base;

   namespace impl {
      struct equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs == rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct not_equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return true;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs != rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (value_null, const T &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (const T &, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs > rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs <= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs <= rhs;
	    }

            template <typename T>
            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      template <typename V>
      struct add : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs + rhs ;
	    }

            value_type operator() (UnicodeString const& lhs ,
                                   UnicodeString const& rhs ) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs + rhs;
	    }
      };
      template <typename V>
      struct sub : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T  lhs, T rhs) const
	    {
	       return lhs - rhs ;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs - rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs - rhs;
	    }
      };

      template <typename V>
      struct mult : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs , T2 const& ) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs * rhs;
	    }
      };

      template <typename V>
      struct div: public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const&) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs / rhs;
	    }
      };

      struct to_bool : public boost::static_visitor<bool>
      {

            template <typename T>
            bool operator() (T val) const
	    {
               throw config_error("Boolean value expected");
	    }

            bool operator() (bool val) const
            {
	       return val;
            }
      };

      struct to_string : public boost::static_visitor<std::string>
      {

            template <typename T>
            std::string operator() (T val) const
	    {
               std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }
            // specializations
            std::string operator() (UnicodeString const& val) const
	    {
               std::string utf8;
               to_utf8(val,utf8);
               return utf8;
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
            {
	       return "";
            }
       };

      struct to_unicode : public boost::static_visitor<UnicodeString>
      {

            template <typename T>
            UnicodeString operator() (T val) const
	    {
               std::basic_ostringstream<char> out;
	       out << val;
               return UnicodeString(out.str().c_str());
	    }

            // specializations
            UnicodeString const& operator() (UnicodeString const& val) const
	    {
               return val;
	    }

            UnicodeString operator() (double val) const
            {
               std::basic_ostringstream<char> out;
	       out << std::setprecision(16) << val;
               return UnicodeString(out.str().c_str());
            }

            UnicodeString operator() (value_null const& val) const
            {
	       return UnicodeString("");
            }
      };

      struct to_expression_string : public boost::static_visitor<std::string>
      {
            std::string operator() (UnicodeString const& val) const
	    {
               std::string utf8;
               to_utf8(val,utf8);
               return "'" + utf8 + "'";
	    }

            template <typename T>
            std::string operator() (T val) const
	    {
	       std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
	    {
               return "null";
            }
      };
   }

   class value
   {
	 value_base base_;
	 friend const value operator+(value const&,value const&);
	 friend const value operator-(value const&,value const&);
	 friend const value operator*(value const&,value const&);
	 friend const value operator/(value const&,value const&);

      public:
	 value ()
            : base_(value_null()) {}

	 template <typename T> value(T _val_)
            : base_(_val_) {}

	 bool operator==(value const& other) const
	 {
	    return boost::apply_visitor(impl::equals(),base_,other.base_);
	 }

	 bool operator!=(value const& other) const
	 {
	    return boost::apply_visitor(impl::not_equals(),base_,other.base_);
	 }

	 bool operator>(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_than(),base_,other.base_);
	 }

	 bool operator>=(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_);
	 }

	 bool operator<(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_than(),base_,other.base_);
	 }

	 bool operator<=(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_or_equal(),base_,other.base_);
	 }

	 value_base const& base() const
	 {
	    return base_;
	 }

	 bool to_bool() const
	 {
	    return boost::apply_visitor(impl::to_bool(),base_);
	 }

	 std::string to_expression_string() const
	 {
	    return boost::apply_visitor(impl::to_expression_string(),base_);
	 }

	 std::string to_string() const
	 {
	    return boost::apply_visitor(impl::to_string(),base_);
	 }

         UnicodeString to_unicode() const
         {
            return boost::apply_visitor(impl::to_unicode(),base_);
         }
   };

   inline const value operator+(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_));
   }

   inline const value operator-(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_));
   }

   inline const value operator*(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_));
   }

   inline const value operator/(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_));
   }

  template <typename charT, typename traits>
  inline std::basic_ostream<charT,traits>&
  operator << (std::basic_ostream<charT,traits>& out,
	       value const& v)
  {
    out << v.to_string();
    return out;
  }
}

#endif //VALUE_HPP
<commit_msg>+ fixed unused paramater warning <commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef VALUE_HPP
#define VALUE_HPP

// mapnik
#include <mapnik/unicode.hpp>
#include <mapnik/config_error.hpp>
// boost
#include <boost/variant.hpp>
#include <boost/scoped_array.hpp>
#include <boost/concept_check.hpp>
// stl
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
// uci
#include <unicode/unistr.h>
#include <unicode/ustring.h>

namespace mapnik  {

   inline void to_utf8(UnicodeString const& input, std::string & target)
   {
      if (input.length() == 0) return;

      const int BUF_SIZE = 256;
      char  buf [BUF_SIZE];
      int len;

      UErrorCode err = U_ZERO_ERROR;
      u_strToUTF8(buf, BUF_SIZE, &len, input.getBuffer(), input.length(), &err);
      if (err == U_BUFFER_OVERFLOW_ERROR || err == U_STRING_NOT_TERMINATED_WARNING )
      {
         boost::scoped_array<char> buf_ptr(new char [len+1]);
         err = U_ZERO_ERROR;
         u_strToUTF8(buf_ptr.get() , len + 1, &len, input.getBuffer(), input.length(), &err);
         target.assign(buf_ptr.get() , len);
      }
      else
      {
         target.assign(buf, len);
      }
   }

   struct value_null
   {
   };

   typedef boost::variant<value_null,bool,int,double,UnicodeString> value_base;

   namespace impl {
      struct equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs == rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs == rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct not_equals
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
	    bool operator() (const T &, const U &) const
	    {
	       return true;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs != rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (UnicodeString const& lhs,
                             UnicodeString const& rhs) const
	    {
	       return  lhs != rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (value_null, const T &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (const T &, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs > rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return  lhs > rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct greater_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator() (T lhs, T rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs >= rhs;
	    }

            bool operator() (UnicodeString const& lhs, UnicodeString const& rhs) const
	    {
	       return lhs >= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_than
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs < rhs;
	    }

            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs < rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      struct less_or_equal
	 : public boost::static_visitor<bool>
      {
            template <typename T, typename U>
            bool operator()(const T &, const U &) const
	    {
	       return false;
	    }

            template <typename T>
            bool operator()(T lhs, T rhs) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (int lhs, double rhs) const
	    {
	       return  lhs <= rhs;
	    }

            bool operator() (double lhs, int rhs) const
	    {
	       return  lhs <= rhs;
	    }

            template <typename T>
            bool operator()(UnicodeString const& lhs,
                            UnicodeString const& rhs ) const
	    {
	       return lhs <= rhs;
	    }

            bool operator() (value_null, value_null) const
	    {
	       return false;
	    }
      };

      template <typename V>
      struct add : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs + rhs ;
	    }

            value_type operator() (UnicodeString const& lhs ,
                                   UnicodeString const& rhs ) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs + rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs + rhs;
	    }
      };
      template <typename V>
      struct sub : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T  lhs, T rhs) const
	    {
	       return lhs - rhs ;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs - rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs - rhs;
	    }
      };

      template <typename V>
      struct mult : public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs , T2 const& ) const
	    {
	       return lhs;
	    }
            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const& ) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs * rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs * rhs;
	    }
      };

      template <typename V>
      struct div: public boost::static_visitor<V>
      {
            typedef V value_type;
            template <typename T1, typename T2>
            value_type operator() (T1 const& lhs, T2 const&) const
	    {
	       return lhs;
	    }

            template <typename T>
            value_type operator() (T lhs, T rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (UnicodeString const& lhs,
                                   UnicodeString const&) const
	    {
	       return lhs;
	    }

            value_type operator() (double lhs, int rhs) const
	    {
	       return lhs / rhs;
	    }

            value_type operator() (int lhs, double rhs) const
	    {
	       return lhs / rhs;
	    }
      };

      struct to_bool : public boost::static_visitor<bool>
      {

            template <typename T>
            bool operator() (T val) const
	    {
               boost::ignore_unused_variable_warning(val);
               throw config_error("Boolean value expected");
	    }

            bool operator() (bool val) const
            {
	       return val;
            }
      };

      struct to_string : public boost::static_visitor<std::string>
      {

            template <typename T>
            std::string operator() (T val) const
	    {
               std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }
            // specializations
            std::string operator() (UnicodeString const& val) const
	    {
               std::string utf8;
               to_utf8(val,utf8);
               return utf8;
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
            {
               boost::ignore_unused_variable_warning(val);
	       return "";
            }
       };

      struct to_unicode : public boost::static_visitor<UnicodeString>
      {

            template <typename T>
            UnicodeString operator() (T val) const
	    {
               std::basic_ostringstream<char> out;
	       out << val;
               return UnicodeString(out.str().c_str());
	    }

            // specializations
            UnicodeString const& operator() (UnicodeString const& val) const
	    {
               return val;
	    }

            UnicodeString operator() (double val) const
            {
               std::basic_ostringstream<char> out;
	       out << std::setprecision(16) << val;
               return UnicodeString(out.str().c_str());
            }

            UnicodeString operator() (value_null const& val) const
            {
               boost::ignore_unused_variable_warning(val);
	       return UnicodeString("");
            }
      };

      struct to_expression_string : public boost::static_visitor<std::string>
      {
            std::string operator() (UnicodeString const& val) const
	    {
               std::string utf8;
               to_utf8(val,utf8);
               return "'" + utf8 + "'";
	    }

            template <typename T>
            std::string operator() (T val) const
	    {
	       std::stringstream ss;
	       ss << val;
	       return ss.str();
	    }

            std::string operator() (double val) const
            {
               std::stringstream ss;
	       ss << std::setprecision(16) << val;
	       return ss.str();
            }

            std::string operator() (value_null const& val) const
	    {
               boost::ignore_unused_variable_warning(val);
               return "null";
            }
      };
   }

   class value
   {
	 value_base base_;
	 friend const value operator+(value const&,value const&);
	 friend const value operator-(value const&,value const&);
	 friend const value operator*(value const&,value const&);
	 friend const value operator/(value const&,value const&);

      public:
	 value ()
            : base_(value_null()) {}

	 template <typename T> value(T _val_)
            : base_(_val_) {}

	 bool operator==(value const& other) const
	 {
	    return boost::apply_visitor(impl::equals(),base_,other.base_);
	 }

	 bool operator!=(value const& other) const
	 {
	    return boost::apply_visitor(impl::not_equals(),base_,other.base_);
	 }

	 bool operator>(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_than(),base_,other.base_);
	 }

	 bool operator>=(value const& other) const
	 {
	    return boost::apply_visitor(impl::greater_or_equal(),base_,other.base_);
	 }

	 bool operator<(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_than(),base_,other.base_);
	 }

	 bool operator<=(value const& other) const
	 {
	    return boost::apply_visitor(impl::less_or_equal(),base_,other.base_);
	 }

	 value_base const& base() const
	 {
	    return base_;
	 }

	 bool to_bool() const
	 {
	    return boost::apply_visitor(impl::to_bool(),base_);
	 }

	 std::string to_expression_string() const
	 {
	    return boost::apply_visitor(impl::to_expression_string(),base_);
	 }

	 std::string to_string() const
	 {
	    return boost::apply_visitor(impl::to_string(),base_);
	 }

         UnicodeString to_unicode() const
         {
            return boost::apply_visitor(impl::to_unicode(),base_);
         }
   };

   inline const value operator+(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::add<value>(),p1.base_, p2.base_));
   }

   inline const value operator-(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::sub<value>(),p1.base_, p2.base_));
   }

   inline const value operator*(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::mult<value>(),p1.base_, p2.base_));
   }

   inline const value operator/(value const& p1,value const& p2)
   {

      return value(boost::apply_visitor(impl::div<value>(),p1.base_, p2.base_));
   }

  template <typename charT, typename traits>
  inline std::basic_ostream<charT,traits>&
  operator << (std::basic_ostream<charT,traits>& out,
	       value const& v)
  {
    out << v.to_string();
    return out;
  }
}

#endif //VALUE_HPP
<|endoftext|>


<commit_before>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_DATA_HPP
#define NDN_DATA_HPP

#include "common.hpp"
#include "name.hpp"
#include "encoding/block.hpp"

#include "signature.hpp"
#include "meta-info.hpp"
#include "key-locator.hpp"

namespace ndn {

class Data {
public:
  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };

  /**
   * @brief Create an empty Data object
   */
  inline
  Data();

  /**
   * @brief Create a new Data object with the given name
   * @param name A reference to the name which is copied.
   */
  inline
  Data(const Name& name);

  /**
   * @brief The virtual destructor.
   */
  inline virtual
  ~Data();

  /**
   * @brief Encode this Data for a wire format.
   * @return The encoded byte array.
   */
  const Block&
  wireEncode() const;

  /**
   * @brief Decode the input using a particular wire format and update this Data.
   * @param input The input byte array to be decoded.
   */
  void
  wireDecode(const Block &wire);

  inline const Name&
  getName() const;

  /**
   * @brief Set name to a copy of the given Name.
   *
   * @param name The Name which is copied.
   * @return This Data so that you can chain calls to update values.
   */
  inline void
  setName(const Name& name);

  inline const MetaInfo&
  getMetaInfo() const;

  /**
   * @brief Set metaInfo to a copy of the given MetaInfo.
   * @param metaInfo The MetaInfo which is copied.
   * @return This Data so that you can chain calls to update values.
   */
  inline void
  setMetaInfo(const MetaInfo& metaInfo);

  ///////////////////////////////////////////////////////////////
  // MetaInfo proxy methods
  inline uint32_t
  getContentType() const;

  inline void
  setContentType(uint32_t type);

  inline Milliseconds
  getFreshnessPeriod() const;

  inline void
  setFreshnessPeriod(Milliseconds freshnessPeriod);

  /**
   * @brief Get content Block
   *
   * To access content value, one can use value()/value_size() or
   * value_begin()/value_end() methods of the Block class
   */
  inline const Block&
  getContent() const;

  /**
   * @brief Set the content to a copy of the data in the vector.
   * @param content A vector whose contents are copied.
   * @return This Data so that you can chain calls to update values.
   */
  inline void
  setContent(const uint8_t* content, size_t contentLength);

  inline void
  setContent(const Block& content);

  inline void
  setContent(const ConstBufferPtr &contentValue);

  inline const Signature&
  getSignature() const;

  /**
   * @brief Set the signature to a copy of the given signature.
   * @param signature The signature object which is cloned.
   * @return This Data so that you can chain calls to update values.
   */
  inline Data&
  setSignature(const Signature& signature);

private:
  /**
   * @brief Clear the wire encoding.
   */
  inline void
  onChanged();

private:
  Name name_;
  MetaInfo metaInfo_;
  mutable Block content_;
  Signature signature_;

  mutable Block wire_;
};

inline
Data::Data()
{
}

inline
Data::Data(const Name& name)
  : name_(name)
{
}

inline
Data::~Data()
{
}

inline const Name&
Data::getName() const
{
  return name_;
}

inline void
Data::setName(const Name& name)
{
  onChanged();
  name_ = name;
}

inline const MetaInfo&
Data::getMetaInfo() const
{
  return metaInfo_;
}

inline void
Data::setMetaInfo(const MetaInfo& metaInfo)
{
  onChanged();
  metaInfo_ = metaInfo;
}

inline uint32_t
Data::getContentType() const
{
  return metaInfo_.getType();
}

inline void
Data::setContentType(uint32_t type)
{
  onChanged();
  metaInfo_.setType(type);
}

inline Milliseconds
Data::getFreshnessPeriod() const
{
  return metaInfo_.getFreshnessPeriod();
}

inline void
Data::setFreshnessPeriod(Milliseconds freshnessPeriod)
{
  onChanged();
  metaInfo_.setFreshnessPeriod(freshnessPeriod);
}

inline const Block&
Data::getContent() const
{
  if (!content_.hasWire())
      content_.encode();
  return content_;
}

inline void
Data::setContent(const uint8_t* content, size_t contentLength)
{
  onChanged();

  content_ = dataBlock(Tlv::Content, content, contentLength);
}

inline void
Data::setContent(const ConstBufferPtr &contentValue)
{
  onChanged();

  content_ = Block(Tlv::Content, contentValue); // not real a wire encoding yet
}

inline void
Data::setContent(const Block& content)
{
  onChanged();

  if (content.type() == Tlv::Content)
    content_ = content;
  else {
    content_ = Block(Tlv::Content, content);
  }
}

inline const Signature&
Data::getSignature() const
{
  return signature_;
}

inline Data&
Data::setSignature(const Signature& signature)
{
  onChanged();
  signature_ = signature;

  return *this;
}

inline void
Data::onChanged()
{
  // The values have changed, so the wire format is invalidated

  // !!!Note!!! Signature is not invalidated and it is responsibility of
  // the application to do proper re-signing if necessary

  wire_ = Block();
}

std::ostream&
operator << (std::ostream &os, const Data &data);

} // namespace ndn

#endif
<commit_msg>data: Small API to update SignatureValue directly, without replacing the whole Signature (both Info and Value block)<commit_after>/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (C) 2013 Regents of the University of California.
 * @author: Jeff Thompson <jefft0@remap.ucla.edu>
 * See COPYING for copyright and distribution information.
 */

#ifndef NDN_DATA_HPP
#define NDN_DATA_HPP

#include "common.hpp"
#include "name.hpp"
#include "encoding/block.hpp"

#include "signature.hpp"
#include "meta-info.hpp"
#include "key-locator.hpp"

namespace ndn {

class Data {
public:
  struct Error : public std::runtime_error { Error(const std::string &what) : std::runtime_error(what) {} };

  /**
   * @brief Create an empty Data object
   */
  inline
  Data();

  /**
   * @brief Create a new Data object with the given name
   * @param name A reference to the name which is copied.
   */
  inline
  Data(const Name& name);

  /**
   * @brief The virtual destructor.
   */
  inline virtual
  ~Data();

  /**
   * @brief Encode this Data for a wire format.
   * @return The encoded byte array.
   */
  const Block&
  wireEncode() const;

  /**
   * @brief Decode the input using a particular wire format and update this Data.
   * @param input The input byte array to be decoded.
   */
  void
  wireDecode(const Block &wire);

  inline const Name&
  getName() const;

  /**
   * @brief Set name to a copy of the given Name.
   *
   * @param name The Name which is copied.
   * @return This Data so that you can chain calls to update values.
   */
  inline void
  setName(const Name& name);

  inline const MetaInfo&
  getMetaInfo() const;

  /**
   * @brief Set metaInfo to a copy of the given MetaInfo.
   * @param metaInfo The MetaInfo which is copied.
   * @return This Data so that you can chain calls to update values.
   */
  inline void
  setMetaInfo(const MetaInfo& metaInfo);

  ///////////////////////////////////////////////////////////////
  // MetaInfo proxy methods
  inline uint32_t
  getContentType() const;

  inline void
  setContentType(uint32_t type);

  inline Milliseconds
  getFreshnessPeriod() const;

  inline void
  setFreshnessPeriod(Milliseconds freshnessPeriod);

  /**
   * @brief Get content Block
   *
   * To access content value, one can use value()/value_size() or
   * value_begin()/value_end() methods of the Block class
   */
  inline const Block&
  getContent() const;

  /**
   * @brief Set the content to a copy of the data in the vector.
   * @param content A vector whose contents are copied.
   * @return This Data so that you can chain calls to update values.
   */
  inline void
  setContent(const uint8_t* content, size_t contentLength);

  inline void
  setContent(const Block& content);

  inline void
  setContent(const ConstBufferPtr &contentValue);

  inline const Signature&
  getSignature() const;

  /**
   * @brief Set the signature to a copy of the given signature.
   * @param signature The signature object which is cloned.
   */
  inline void
  setSignature(const Signature& signature);

  inline void
  setSignatureValue(const Block &value);

private:
  /**
   * @brief Clear the wire encoding.
   */
  inline void
  onChanged();

private:
  Name name_;
  MetaInfo metaInfo_;
  mutable Block content_;
  Signature signature_;

  mutable Block wire_;
};

inline
Data::Data()
{
}

inline
Data::Data(const Name& name)
  : name_(name)
{
}

inline
Data::~Data()
{
}

inline const Name&
Data::getName() const
{
  return name_;
}

inline void
Data::setName(const Name& name)
{
  onChanged();
  name_ = name;
}

inline const MetaInfo&
Data::getMetaInfo() const
{
  return metaInfo_;
}

inline void
Data::setMetaInfo(const MetaInfo& metaInfo)
{
  onChanged();
  metaInfo_ = metaInfo;
}

inline uint32_t
Data::getContentType() const
{
  return metaInfo_.getType();
}

inline void
Data::setContentType(uint32_t type)
{
  onChanged();
  metaInfo_.setType(type);
}

inline Milliseconds
Data::getFreshnessPeriod() const
{
  return metaInfo_.getFreshnessPeriod();
}

inline void
Data::setFreshnessPeriod(Milliseconds freshnessPeriod)
{
  onChanged();
  metaInfo_.setFreshnessPeriod(freshnessPeriod);
}

inline const Block&
Data::getContent() const
{
  if (!content_.hasWire())
      content_.encode();
  return content_;
}

inline void
Data::setContent(const uint8_t* content, size_t contentLength)
{
  onChanged();

  content_ = dataBlock(Tlv::Content, content, contentLength);
}

inline void
Data::setContent(const ConstBufferPtr &contentValue)
{
  onChanged();

  content_ = Block(Tlv::Content, contentValue); // not real a wire encoding yet
}

inline void
Data::setContent(const Block& content)
{
  onChanged();

  if (content.type() == Tlv::Content)
    content_ = content;
  else {
    content_ = Block(Tlv::Content, content);
  }
}

inline const Signature&
Data::getSignature() const
{
  return signature_;
}

inline void
Data::setSignature(const Signature& signature)
{
  onChanged();
  signature_ = signature;
}

inline void
Data::setSignatureValue(const Block &value)
{
  onChanged();
  signature_.setValue(value);
}

inline void
Data::onChanged()
{
  // The values have changed, so the wire format is invalidated

  // !!!Note!!! Signature is not invalidated and it is responsibility of
  // the application to do proper re-signing if necessary

  wire_.reset();
}

std::ostream&
operator << (std::ostream &os, const Data &data);

} // namespace ndn

#endif
<|endoftext|>


<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. 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.

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

******************************************************************************/
#ifndef NOMLIB_TYPES_HEADERS
#define NOMLIB_TYPES_HEADERS

#include <cstdint>

// Portable fixed-size data types

#ifdef PATH_MAX
  #undef PATH_MAX
#endif

// Apparently determining a safe, portable maximum file path is a bit trickier
// than meets the eye -- for the time being, I am going to assume the POSIX
// standard of 256 bytes is sufficient for my needs. I have my doubts as to this
// working out well for us if nomlib ever sees the light of day on the Windows
// platform, but alas!
//
// See http://stackoverflow.com/questions/833291/is-there-an-equivalent-to-winapis-max-path-under-linux-unix
#define PATH_MAX 256

// 64-bit kernel
#define NOMLIB_64BIT

// Derives from stdint.h
namespace nom {

// 1-bit integer types
typedef bool bit;

// 8-bit integer types
typedef int8_t int8;
typedef uint8_t uint8;

// 16-bit integer types
typedef int16_t int16;
typedef uint16_t uint16;

// 32-bit integer types
typedef int32_t int32;
typedef uint32_t uint32;

// 64-bit integer types
#if defined NOMLIB_64BIT

  #if defined ( _MSC_VER ) // MSVC++
    typedef signed __int64 int64;
    typedef unsigned __int64 uint64;
  #else
    typedef int64_t int64;
    typedef uint64_t uint64;
  #endif

#else
  // We are compiling on a 32-bit system (we may not have int64 types defined)
  typedef signed long long int64;
  typedef unsigned long long uint64;

#endif // NOMLIB_64BIT defined

// Additional integer type definitions
typedef unsigned long ulong;

} // namespace nom

// Ensure our defined data types have the right sizes
// Thanks to SDL for the macro! :-)
#define NOMLIB_COMPILE_TIME_ASSERT(name, x) \
  typedef int NOMLIB_dummy_ ## name[(x) * 2 - 1]

NOMLIB_COMPILE_TIME_ASSERT(bit, sizeof(nom::bit) == 1);
NOMLIB_COMPILE_TIME_ASSERT(uint8, sizeof(nom::uint8) == 1);
NOMLIB_COMPILE_TIME_ASSERT(int8, sizeof(nom::int8) == 1);
NOMLIB_COMPILE_TIME_ASSERT(uint16, sizeof(nom::uint16) == 2);
NOMLIB_COMPILE_TIME_ASSERT(int16, sizeof(nom::int16) == 2);
NOMLIB_COMPILE_TIME_ASSERT(uint32, sizeof(nom::uint32) == 4);
NOMLIB_COMPILE_TIME_ASSERT(int32, sizeof(nom::int32) == 4);
NOMLIB_COMPILE_TIME_ASSERT(uint64, sizeof(nom::uint64) == 8);
NOMLIB_COMPILE_TIME_ASSERT(int64, sizeof(nom::int64) == 8);

#endif // NOMLIB_TYPES_HEADERS defined
<commit_msg>Replace C Macro static asserts with C++11 version<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. 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.

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

******************************************************************************/
#ifndef NOMLIB_TYPES_HEADERS
#define NOMLIB_TYPES_HEADERS

#include <cstdint>

// Portable fixed-size data types

#ifdef PATH_MAX
  #undef PATH_MAX
#endif

// Apparently determining a safe, portable maximum file path is a bit trickier
// than meets the eye -- for the time being, I am going to assume the POSIX
// standard of 256 bytes is sufficient for my needs. I have my doubts as to this
// working out well for us if nomlib ever sees the light of day on the Windows
// platform, but alas!
//
// See http://stackoverflow.com/questions/833291/is-there-an-equivalent-to-winapis-max-path-under-linux-unix
#define PATH_MAX 256

// 64-bit kernel
#define NOMLIB_64BIT

// Derives from stdint.h
namespace nom {

// 1-bit integer types
typedef bool bit;

// 8-bit integer types
typedef int8_t int8;
typedef uint8_t uint8;

// 16-bit integer types
typedef int16_t int16;
typedef uint16_t uint16;

// 32-bit integer types
typedef int32_t int32;
typedef uint32_t uint32;

// 64-bit integer types
#if defined NOMLIB_64BIT

  #if defined ( _MSC_VER ) // MSVC++
    typedef signed __int64 int64;
    typedef unsigned __int64 uint64;
  #else
    typedef int64_t int64;
    typedef uint64_t uint64;
  #endif

#else
  // We are compiling on a 32-bit system (we may not have int64 types defined)
  typedef signed long long int64;
  typedef unsigned long long uint64;

#endif // NOMLIB_64BIT defined

// Additional integer type definitions
typedef unsigned long ulong;

} // namespace nom

// Ensure our data types have the right sizes
static_assert ( sizeof ( nom::bit ) == 1, "nom::bit" );
static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" );
static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" );

static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" );
static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" );

static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" );
static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" );

static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" );
static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" );

#endif // NOMLIB_TYPES_HEADERS defined
<|endoftext|>


<commit_before>
#pragma once

#include <proxc/version.hpp>

////////////////////////////////////////////////////////////////////////////////
// Detect the compiler
////////////////////////////////////////////////////////////////////////////////

#if defined(_MSC_VER) && !defined(__clang__) // MSVC

#   pragma message("Warning: the native Microsoft compiler is not supported due to lack of proper C++14 support.")

#elif defined(__clang__) && defined(_MSC_VER) // Clang-cl (Clang for Windows)

#   define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
        __clang_major__, __clang_minor__, __clang_patchlevel__)

#   if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
#       warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
#   endif

#elif defined(__clang__) && defined(__apple_build_version__) // Apple's Clang

#   if __apple_build_version__ >= 6000051
#       define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION(3, 6, 0)
#   else
#       warning "Versions of Apple's Clang prior to the one shipped with XCode is not supported."
#   endif

#elif defined(__clang__) // Genuine Clang

#   define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
        __clang_major__, __clang_minor__, __clang_patchlevel__)

#   if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
#       warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
#   endif

#elif defined(__GNUC__) // GCC

#   define PROXC_CONFIC_GCC PROXC_CONFIG_VERSION(\
        __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)

#   if PROXC_CONFIC_GCC < PROXC_CONFIG_VERSION(5, 0, 0)
#       warning "Versions of GCC prior to 5.0.0 are not supported for lack of proper C++14 support."
#   endif

#else

#   warning "Your compiler was not detected properly and might not work for ProXC."

#endif

////////////////////////////////////////////////////////////////////////////////
// Detect the compiler for general C++14 capabilities
////////////////////////////////////////////////////////////////////////////////

#if (__cplusplus < 201400)
#   if defined(_MSC_VER)
#       pragma message("Warning: Your compiler doesn't provide C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or '-std=c++1y'.")
#   else
#       warning "Your compiler doesn't provde C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or 'std=c++1y'"
#   endif
#endif

////////////////////////////////////////////////////////////////////////////////
// Detect the standard library
////////////////////////////////////////////////////////////////////////////////

#include <cstddef>

#if defined(_LIBCPP_VERSION)

#   define PROXC_CONFIG_LIBCPP PROXC_CONFIG_VERSION( \
        ((_LIBCPP_VERSION) / 1000) % 10, 0, (_LIBCPP_VERSION) % 1000)

#   if PROXC_CONFIG_LIBCPP < PROXC_CONFIG_VERSION(1, 0, 101)
#       warning "Versions of libc++ prior to the one shipped with Clang 3.5.0 are not supported for lack of full C++14 support."
#   endif

#elif defined(__GLIBCXX__)

#   if __GLIBCXX__ < 20150422 // --> the libstdc++ shipped with GCC 5.1.0
#       warning "Versions of libstdc++ prior to the one shipped with GCC 5.1.0 are not supported for lack of full C++14 support."
#   endif

#   define PROXC_CONFIG_LIBSTDCXX

#elif defined(_MSC_VER)

#   define PROXC_CONFIG_LIBMSVCCXX

#else

#   warning "Your standard library was not detected properly and might not work for ProXC."

#endif

////////////////////////////////////////////////////////////////////////////////
// Detect 32- or 64-bit architecture
////////////////////////////////////////////////////////////////////////////////

#ifndef PROXC_ARCH

#if defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) /* PowerPC */

#   if defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
       defined(__64BIT__)     || defined(_LP64)     || defined(__LP64__) /* PowerPC 64-bit */

#       define PROXC_ARCH 64

#   else /* PowerPC 32-bit */

#       define PROXC_ARCH 32

#   endif

#elif defined(__x86_64__) || defined(_M_X64) /* x86 64-bit */

#   define PROXC_ARCH 64

#elif defined(__i386) || defined(_M_IX86) /* x86 32-bit */

#   define PROXC_ARCH 32

#elif defined(_WIN32) || defined(_WIN64) /* Windows */

#   if defined(_WIN64) /* Windows 64-bit */

#       define PROXC_ARCH 64

#   else /* Windows 32-bit */

#       define PROXC_ARCH 32

#   endif

#else /* Unknown architecture */

#   define PROXC_ARCH 64
#   warning "Architecture was neither correctly determined nor specified. Defaults to 64-bit. This can be set with -DPROXC_ARCH={32/64}, for 32-bit or 64-bit respectively."

#endif

#endif // PROXC_ARCH

static_assert(((PROXC_ARCH) == 32) || ((PROXC_ARCH) == 64), "Architecture specified by PROXC_ARCH only supports 32 or 64 value.");

// cache alignment and cachelines
static constexpr std::size_t cache_alignment{ PROXC_ARCH };
static constexpr std::size_t cacheline_length{ PROXC_ARCH };

////////////////////////////////////////////////////////////////////////////////
// Namespace macros
////////////////////////////////////////////////////////////////////////////////

#define PROXC_NAMESPACE_BEGIN namespace proxc {

#define PROXC_NAMESPACE_END }

<commit_msg>Added defines for compiler usage.<commit_after>
#pragma once

#include <proxc/version.hpp>

////////////////////////////////////////////////////////////////////////////////
// Detect the compiler
////////////////////////////////////////////////////////////////////////////////

#if defined(_MSC_VER) && !defined(__clang__) // MSVC

#   define PROXC_COMP_MSVC
#   pragma message("Warning: the native Microsoft compiler is not supported due to lack of proper C++14 support.")

#elif defined(__clang__) && defined(_MSC_VER) // Clang-cl (Clang for Windows)

#   define PROXC_COMP_CLANG
#   define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
        __clang_major__, __clang_minor__, __clang_patchlevel__)

#   if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
#       warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
#   endif

#elif defined(__clang__) && defined(__apple_build_version__) // Apple's Clang

#   define PROXC_COMP_CLANG
#   if __apple_build_version__ >= 6000051
#       define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION(3, 6, 0)
#   else
#       warning "Versions of Apple's Clang prior to the one shipped with XCode is not supported."
#   endif

#elif defined(__clang__) // Genuine Clang

#   define PROXC_COMP_CLANG
#   define PROXC_CONFIG_CLANG PROXC_CONFIG_VERSION( \
        __clang_major__, __clang_minor__, __clang_patchlevel__)

#   if PROXC_CONFIG_CLANG < PROXC_CONFIG_VERSION(3, 5, 0)
#       warning "Versions of Clang prior to 3.5.0 are not supported for lack of proper C++14 support."
#   endif

#elif defined(__GNUC__) // GCC

#   define PROXC_COMP_GCC
#   define PROXC_CONFIC_GCC PROXC_CONFIG_VERSION(\
        __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)

#   if PROXC_CONFIC_GCC < PROXC_CONFIG_VERSION(5, 0, 0)
#       warning "Versions of GCC prior to 5.0.0 are not supported for lack of proper C++14 support."
#   endif

#else

#   warning "Your compiler was not detected properly and might not work for ProXC."

#endif

////////////////////////////////////////////////////////////////////////////////
// Detect the compiler for general C++14 capabilities
////////////////////////////////////////////////////////////////////////////////

#if (__cplusplus < 201400)
#   if defined(_MSC_VER)
#       pragma message("Warning: Your compiler doesn't provide C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or '-std=c++1y'.")
#   else
#       warning "Your compiler doesn't provde C++14 or higher capabilities. Try adding the compiler flag 'std=c++14' or 'std=c++1y'"
#   endif
#endif

////////////////////////////////////////////////////////////////////////////////
// Detect the standard library
////////////////////////////////////////////////////////////////////////////////

#include <cstddef>

#if defined(_LIBCPP_VERSION)

#   define PROXC_CONFIG_LIBCPP PROXC_CONFIG_VERSION( \
        ((_LIBCPP_VERSION) / 1000) % 10, 0, (_LIBCPP_VERSION) % 1000)

#   if PROXC_CONFIG_LIBCPP < PROXC_CONFIG_VERSION(1, 0, 101)
#       warning "Versions of libc++ prior to the one shipped with Clang 3.5.0 are not supported for lack of full C++14 support."
#   endif

#elif defined(__GLIBCXX__)

#   if __GLIBCXX__ < 20150422 // --> the libstdc++ shipped with GCC 5.1.0
#       warning "Versions of libstdc++ prior to the one shipped with GCC 5.1.0 are not supported for lack of full C++14 support."
#   endif

#   define PROXC_CONFIG_LIBSTDCXX

#elif defined(_MSC_VER)

#   define PROXC_CONFIG_LIBMSVCCXX

#else

#   warning "Your standard library was not detected properly and might not work for ProXC."

#endif

////////////////////////////////////////////////////////////////////////////////
// Detect 32- or 64-bit architecture
////////////////////////////////////////////////////////////////////////////////

#ifndef PROXC_ARCH

#if defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) /* PowerPC */

#   if defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) || \
       defined(__64BIT__)     || defined(_LP64)     || defined(__LP64__) /* PowerPC 64-bit */

#       define PROXC_ARCH 64

#   else /* PowerPC 32-bit */

#       define PROXC_ARCH 32

#   endif

#elif defined(__x86_64__) || defined(_M_X64) /* x86 64-bit */

#   define PROXC_ARCH 64

#elif defined(__i386) || defined(_M_IX86) /* x86 32-bit */

#   define PROXC_ARCH 32

#elif defined(_WIN32) || defined(_WIN64) /* Windows */

#   if defined(_WIN64) /* Windows 64-bit */

#       define PROXC_ARCH 64

#   else /* Windows 32-bit */

#       define PROXC_ARCH 32

#   endif

#else /* Unknown architecture */

#   define PROXC_ARCH 64
#   warning "Architecture was neither correctly determined nor specified. Defaults to 64-bit. This can be set with -DPROXC_ARCH={32/64}, for 32-bit or 64-bit respectively."

#endif

#endif // PROXC_ARCH

static_assert(((PROXC_ARCH) == 32) || ((PROXC_ARCH) == 64), "Architecture specified by PROXC_ARCH only supports 32 or 64 value.");

// cache alignment and cachelines
static constexpr std::size_t cache_alignment{ PROXC_ARCH };
static constexpr std::size_t cacheline_length{ PROXC_ARCH };

////////////////////////////////////////////////////////////////////////////////
// Namespace macros
////////////////////////////////////////////////////////////////////////////////

#define PROXC_NAMESPACE_BEGIN namespace proxc {

#define PROXC_NAMESPACE_END }

<|endoftext|>


<commit_before>#ifndef TABLE_HPP
#define TABLE_HPP

#include <iostream>
#include <vector>
#include <limits>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <stdint.h>
#include <sstream>

#include "util.hpp"
#include "arpTable.hpp"

using nh_index = uint16_t;

/*! Abstract Routing Table class.
 * This class should be inherited from, when implementing a source of routing information.
 */
class RoutingTable {
public:
	/*! One route.
	 * This struct holds all the necessary information to decribe one specific route.
	 */
	struct route {
		uint32_t base; //!< base address of the route
		uint32_t next_hop; //!< next hop IPv4 address
		uint32_t prefix_length; //!< prefix length of the route
		uint16_t interface; //!< interface number
		nh_index index; //!< Index of the next Hop
		static constexpr nh_index NH_INVALID  = uint16_t_max;
		static constexpr nh_index NH_DIRECTLY_CONNECTED  = (uint16_t_max -1);

		route() :
			base(uint32_t_max),
			next_hop(uint32_t_max),
			prefix_length(uint32_t_max),
			interface(uint16_t_max) {};

		/*! Copy Constructor
		 */
		route(const route& route) :
			base(route.base),
			next_hop(route.next_hop),
			prefix_length(route.prefix_length),
			interface(route.interface),
	   		index(route.index) {};

		/*! Return if this route is valid
		 * Valid routes have a base address of not all 1s
		 */
		operator bool(){
			if(base == uint32_t_max){
				return false;
			} else {
				return true;
			}
		};
	};

	static const route invalidRoute; //!< invalid Route

protected:
	/*! All of the routing information is contained here
	 */
	std::shared_ptr<std::vector<std::vector<route>>>
		entries = std::make_shared<std::vector<std::vector<route>>>();

	/*! Mapping from next hop index to IPv4 addresses
	 */
	std::shared_ptr<std::vector<uint32_t>>
		nextHopMapping = std::make_shared<std::vector<uint32_t>>();

	/*! Update the underlying routing infomation
	 * Implementation is up to the child class
	 */
	virtual void updateInfo() {};

private:
	void buildNextHopList();
	void aggregate();
	std::unordered_set<uint16_t> interfaces;

public:
	/*! Print the routing table.
	 * Similiar to "ip r"
	 */
	void print_table();

	/*! Get the routes currently held inside the routing table
	 * \return routes sorted by prefix length (first index), and base address
	 */
	std::shared_ptr<std::vector<std::vector<route>>> getSortedRoutes();

	/*! From index to IPv4.
	 * Get a mapping from the next hop index to an IPv4 address
	 * \return mapping
	 */
	std::shared_ptr<std::vector<uint32_t>> getNextHopMapping(){
		return nextHopMapping;
	};

	/*! Get the set of used interfaces
	 * Return the set of used interface
	 * \return set of interfaces
	 */
	std::unordered_set<uint16_t> getInterfaceSet();

	/*! Update the routing information
	 * This function updates the routing information and preprocesses it for further usage.
	 */
	void update(){
		updateInfo();
		aggregate();
		buildNextHopList();
	};
};

#endif /* ROUTINGTABLE_HPP */
<commit_msg>clean up doxygen in routingTable.hpp<commit_after>#ifndef TABLE_HPP
#define TABLE_HPP

#include <iostream>
#include <vector>
#include <limits>
#include <memory>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <stdint.h>
#include <sstream>

#include "util.hpp"
#include "arpTable.hpp"

using nh_index = uint16_t;

/*! Abstract Routing Table class.
 * This class should be inherited from, when implementing a source of routing information.
 */
class RoutingTable {
public:
	/*! One route.
	 * This struct holds all the necessary information to decribe one specific route.
	 */
	struct route {
		uint32_t base; //!< base address of the route
		uint32_t next_hop; //!< next hop IPv4 address
		uint32_t prefix_length; //!< prefix length of the route
		uint16_t interface; //!< interface number
		nh_index index; //!< Index of the next Hop
		static constexpr nh_index NH_INVALID  = uint16_t_max;
		static constexpr nh_index NH_DIRECTLY_CONNECTED  = (uint16_t_max -1);

		route() :
			base(uint32_t_max),
			next_hop(uint32_t_max),
			prefix_length(uint32_t_max),
			interface(uint16_t_max) {};

		/*! Copy Constructor
		 */
		route(const route& route) :
			base(route.base),
			next_hop(route.next_hop),
			prefix_length(route.prefix_length),
			interface(route.interface),
	   		index(route.index) {};

		/*! Return if this route is valid
		 * Valid routes have a base address of not all 1s
		 */
		operator bool(){
			if(base == uint32_t_max){
				return false;
			} else {
				return true;
			}
		};
	};

	static const route invalidRoute; //!< invalid Route

protected:
	/*! All of the routing information is contained here.
	 */
	std::shared_ptr<std::vector<std::vector<route>>>
		entries = std::make_shared<std::vector<std::vector<route>>>();

	/*! Mapping from next hop index to IPv4 addresses.
	 */
	std::shared_ptr<std::vector<uint32_t>>
		nextHopMapping = std::make_shared<std::vector<uint32_t>>();

	/*! Update the underlying routing infomation.
	 * Implementation is up to the child class
	 */
	virtual void updateInfo() {};

private:
	void buildNextHopList();
	void aggregate();
	std::unordered_set<uint16_t> interfaces;

public:
	/*! Print the routing table.
	 * Similiar to "ip r"
	 */
	void print_table();

	/*! Get the routes currently held inside the routing table.
	 * \return routes sorted by prefix length (first index), and base address
	 */
	std::shared_ptr<std::vector<std::vector<route>>> getSortedRoutes();

	/*! From index to IPv4.
	 * Get a mapping from the next hop index to an IPv4 address
	 * \return mapping
	 */
	std::shared_ptr<std::vector<uint32_t>> getNextHopMapping(){
		return nextHopMapping;
	};

	/*! Get the set of used interfaces.
	 * Return the set of used interface
	 * \return set of interfaces
	 */
	std::unordered_set<uint16_t> getInterfaceSet();

	/*! Update the routing information.
	 * This function updates the routing information and preprocesses it for further usage.
	 */
	void update(){
		updateInfo();
		aggregate();
		buildNextHopList();
	};
};

#endif /* ROUTINGTABLE_HPP */
<|endoftext|>


<commit_before><commit_msg>Remove unused forward declaration<commit_after><|endoftext|>


<commit_before><commit_msg>these are not used in this .hxx<commit_after><|endoftext|>


<commit_before><commit_msg>Translated some German comments to English<commit_after><|endoftext|>


<commit_before><commit_msg>Unicode is Unocode on all platforms<commit_after><|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "termwise_search.h"
#include <vespa/vespalib/objects/visit.h>
#include <vespa/searchlib/common/bitvector.h>

namespace search {
namespace queryeval {

template <bool IS_STRICT>
struct TermwiseSearch : public SearchIterator {

    SearchIterator::UP search;
    BitVector::UP  result;

    TermwiseSearch(SearchIterator::UP search_in)
        : search(std::move(search_in)), result() {}

    Trinary is_strict() const override { return IS_STRICT ? Trinary::True : Trinary::False; }
    void initRange(uint32_t beginid, uint32_t endid) override {
        SearchIterator::initRange(beginid, endid);
        search->initRange(beginid, endid);
        setDocId(std::max(getDocId(), search->getDocId()));
        result = search->get_hits(beginid);
    }
    void doSeek(uint32_t docid) override {
        if (__builtin_expect(isAtEnd(docid), false)) {
            setAtEnd();
        } else if (IS_STRICT) {
            uint32_t nextid = result->getNextTrueBit(docid);
            if (__builtin_expect(isAtEnd(nextid), false)) {
                setAtEnd();
            } else {
                setDocId(nextid);
            }
        } else if (result->testBit(docid)) {
            setDocId(docid);
        }
    }
    void doUnpack(uint32_t) override {}
    void visitMembers(vespalib::ObjectVisitor &visitor) const override {
        visit(visitor, "search", *search);
        visit(visitor, "strict", IS_STRICT);
    }
};

SearchIterator::UP
make_termwise(SearchIterator::UP search, bool strict)
{
    if (strict) {
        return SearchIterator::UP(new TermwiseSearch<true>(std::move(search)));
    } else {
        return SearchIterator::UP(new TermwiseSearch<false>(std::move(search)));
    }
}

} // namespace queryeval
} // namespace search
<commit_msg>re-use bitvector if re-inited with same docid range<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "termwise_search.h"
#include <vespa/vespalib/objects/visit.h>
#include <vespa/searchlib/common/bitvector.h>

namespace search {
namespace queryeval {

template <bool IS_STRICT>
struct TermwiseSearch : public SearchIterator {

    SearchIterator::UP search;
    BitVector::UP      result;
    uint32_t           my_beginid;
    uint32_t           my_first_hit;

    bool same_range(uint32_t beginid, uint32_t endid) const {
        return ((beginid == my_beginid) && endid == getEndId());
    }

    TermwiseSearch(SearchIterator::UP search_in)
        : search(std::move(search_in)), result(), my_beginid(0), my_first_hit(0) {}

    Trinary is_strict() const override { return IS_STRICT ? Trinary::True : Trinary::False; }
    void initRange(uint32_t beginid, uint32_t endid) override {
        if (!same_range(beginid, endid)) {
            my_beginid = beginid;
            SearchIterator::initRange(beginid, endid);
            search->initRange(beginid, endid);
            my_first_hit = std::max(getDocId(), search->getDocId());
            result = search->get_hits(beginid);
        }
        setDocId(my_first_hit);
    }
    void doSeek(uint32_t docid) override {
        if (__builtin_expect(isAtEnd(docid), false)) {
            setAtEnd();
        } else if (IS_STRICT) {
            uint32_t nextid = result->getNextTrueBit(docid);
            if (__builtin_expect(isAtEnd(nextid), false)) {
                setAtEnd();
            } else {
                setDocId(nextid);
            }
        } else if (result->testBit(docid)) {
            setDocId(docid);
        }
    }
    void doUnpack(uint32_t) override {}
    void visitMembers(vespalib::ObjectVisitor &visitor) const override {
        visit(visitor, "search", *search);
        visit(visitor, "strict", IS_STRICT);
    }
};

SearchIterator::UP
make_termwise(SearchIterator::UP search, bool strict)
{
    if (strict) {
        return SearchIterator::UP(new TermwiseSearch<true>(std::move(search)));
    } else {
        return SearchIterator::UP(new TermwiseSearch<false>(std::move(search)));
    }
}

} // namespace queryeval
} // namespace search
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_META_BROADCAST_ARRAY_HPP
#define STAN_MATH_PRIM_META_BROADCAST_ARRAY_HPP

#include <stan/math/prim/meta/is_eigen.hpp>
#include <stan/math/prim/meta/promote_scalar_type.hpp>
#include <stan/math/prim/meta/ref_type.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <stdexcept>

namespace stan {
namespace math {
namespace internal {

template <typename T>
class broadcast_array {
 private:
  T& prim_;

 public:
  explicit broadcast_array(T& prim) : prim_(prim) {}

  T& operator[](int /*i*/) { return prim_; }

  /** \ingroup type_trait
   * We can assign any right hand side which allows for indexing to a
   * broadcast_array. The idea is that the argument is summed.
   */
  template <typename Y>
  void operator=(const Y& m) {
    prim_ = sum(m);
  }
};

template <typename T, typename S, typename Enable = void>
class empty_broadcast_array {
 public:
  empty_broadcast_array() {}
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& operator[](int /*i*/);

  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  template <typename Y>
  void operator=(const Y& /*A*/);
};

template <typename ViewElt, typename T>
class empty_broadcast_array<ViewElt, T, require_eigen_t<T>> {
  enum { R = T::RowsAtCompileTime, C = T::ColsAtCompileTime };
  using T_arg = promote_scalar_t<ViewElt, T>;

 public:
  empty_broadcast_array() {}
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  ViewElt& operator[](int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  ViewElt& operator()(int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator=(const T_arg& /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator+=(T_arg /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator-=(T_arg /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& row(int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& col(int /*i*/);
};
}  // namespace internal
}  // namespace math
}  // namespace stan
#endif
<commit_msg>fixed doc<commit_after>#ifndef STAN_MATH_PRIM_META_BROADCAST_ARRAY_HPP
#define STAN_MATH_PRIM_META_BROADCAST_ARRAY_HPP

#include <stan/math/prim/meta/is_eigen.hpp>
#include <stan/math/prim/meta/promote_scalar_type.hpp>
#include <stan/math/prim/meta/ref_type.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/sum.hpp>
#include <stdexcept>

namespace stan {
namespace math {
namespace internal {

template <typename T>
class broadcast_array {
 private:
  T& prim_;

 public:
  explicit broadcast_array(T& prim) : prim_(prim) {}

  T& operator[](int /*i*/) { return prim_; }

  /** \ingroup type_trait
   * Broadcast array can be assigned a scalar or a vector. If assigned a scalar,
   * it will be used directly. If assigned a vector, the argument will be summed
   * first.
   */
  template <typename Y>
  void operator=(const Y& m) {
    prim_ = sum(m);
  }
};

template <typename T, typename S, typename Enable = void>
class empty_broadcast_array {
 public:
  empty_broadcast_array() {}
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& operator[](int /*i*/);

  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  template <typename Y>
  void operator=(const Y& /*A*/);
};

template <typename ViewElt, typename T>
class empty_broadcast_array<ViewElt, T, require_eigen_t<T>> {
  enum { R = T::RowsAtCompileTime, C = T::ColsAtCompileTime };
  using T_arg = promote_scalar_t<ViewElt, T>;

 public:
  empty_broadcast_array() {}
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  ViewElt& operator[](int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  ViewElt& operator()(int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator=(const T_arg& /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator+=(T_arg /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  void operator-=(T_arg /*A*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& row(int /*i*/);
  /** \ingroup type_trait
   * Not implemented so cannot be called.
   */
  T& col(int /*i*/);
};
}  // namespace internal
}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>/*
    Kopete Yahoo Protocol
    Change our Status

    Copyright (c) 2005 André Duffeck <andre.duffeck@kdemail.net>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "changestatustask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <qstring.h>
#include <kdebug.h>

ChangeStatusTask::ChangeStatusTask(Task* parent) : Task(parent)
{
	kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}

ChangeStatusTask::~ChangeStatusTask()
{
}

void ChangeStatusTask::onGo()
{
	kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	YMSGTransfer *t = new YMSGTransfer( Yahoo::ServiceStatus );
	t->setId( client()->sessionID() );

	if( m_status == Yahoo::StatusInvisible )			// status --> Invisible
	{
		sendVisibility( Invisible );
	}
	else
	{
		if( !m_message.isEmpty() )
			m_status = Yahoo::StatusCustom;

		if( m_status == Yahoo::StatusCustom )
			t->setParam( 19, m_message.utf8() );
		t->setParam( 10, m_status );
		t->setParam( 47, m_type );
		t->setParam( 97, 1 );	// it's utf8

		send( t );

		if( client()->status() == Yahoo::StatusInvisible )	// Invisible --> Status
			sendVisibility( Visible );
	}
	setSuccess( true );
}

void ChangeStatusTask::sendVisibility( Visibility visible )
{
	YMSGTransfer *t = new YMSGTransfer( Yahoo::ServiceVisibility );
	t->setId( client()->sessionID() );
	t->setParam( 13, visible );
	send( t );
}

void ChangeStatusTask::setMessage( const QString &msg )
{
	m_message = msg;
}

void ChangeStatusTask::setStatus( Yahoo::Status status )
{
	m_status = status;
}

void ChangeStatusTask::setType( Yahoo::StatusType type )
{
	m_type = type;
}
<commit_msg>fix memory leak (CID 2126)<commit_after>/*
    Kopete Yahoo Protocol
    Change our Status

    Copyright (c) 2005 André Duffeck <andre.duffeck@kdemail.net>

    *************************************************************************
    *                                                                       *
    * This library is free software; you can redistribute it and/or         *
    * modify it under the terms of the GNU Lesser General Public            *
    * License as published by the Free Software Foundation; either          *
    * version 2 of the License, or (at your option) any later version.      *
    *                                                                       *
    *************************************************************************
*/

#include "changestatustask.h"
#include "transfer.h"
#include "ymsgtransfer.h"
#include "yahootypes.h"
#include "client.h"
#include <qstring.h>
#include <kdebug.h>

ChangeStatusTask::ChangeStatusTask(Task* parent) : Task(parent)
{
	kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;
}

ChangeStatusTask::~ChangeStatusTask()
{
}

void ChangeStatusTask::onGo()
{
	kdDebug(YAHOO_RAW_DEBUG) << k_funcinfo << endl;

	if( m_status == Yahoo::StatusInvisible )			// status --> Invisible
	{
		sendVisibility( Invisible );
	}
	else
	{
		YMSGTransfer *t = new YMSGTransfer( Yahoo::ServiceStatus );
		t->setId( client()->sessionID() );

		if( !m_message.isEmpty() )
			m_status = Yahoo::StatusCustom;

		if( m_status == Yahoo::StatusCustom )
			t->setParam( 19, m_message.utf8() );
		t->setParam( 10, m_status );
		t->setParam( 47, m_type );
		t->setParam( 97, 1 );	// it's utf8

		send( t );

		if( client()->status() == Yahoo::StatusInvisible )	// Invisible --> Status
			sendVisibility( Visible );
	}
	setSuccess( true );
}

void ChangeStatusTask::sendVisibility( Visibility visible )
{
	YMSGTransfer *t = new YMSGTransfer( Yahoo::ServiceVisibility );
	t->setId( client()->sessionID() );
	t->setParam( 13, visible );
	send( t );
}

void ChangeStatusTask::setMessage( const QString &msg )
{
	m_message = msg;
}

void ChangeStatusTask::setStatus( Yahoo::Status status )
{
	m_status = status;
}

void ChangeStatusTask::setType( Yahoo::StatusType type )
{
	m_type = type;
}
<|endoftext|>


<commit_before>#include "testing/testing.hpp"

#include "storage/country_tree.hpp"

namespace
{
template <class TNode>
struct Calculator
{
  size_t count;
  Calculator() : count(0) {}
  void operator()(TNode const &)
  {
    ++count;
  }
};
} // namespace

UNIT_TEST(CountryTree_Smoke)
{
  typedef CountryTree<int, int>::Node TTree;
  TTree tree;

  tree.AddAtDepth(0, 4);
  tree.AddAtDepth(0, 3);
  tree.AddAtDepth(0, 5);
  tree.AddAtDepth(0, 2);
  tree.AddAtDepth(0, 1);
  tree.AddAtDepth(1, 20);  // 1 is parent
  tree.AddAtDepth(1, 10);  // 1 is parent
  tree.AddAtDepth(1, 30);  // 1 is parent

  // children test
  TEST_EQUAL(tree.Child(0).Value(), 4, ());
  TEST_EQUAL(tree.Child(1).Value(), 3, ());
  TEST_EQUAL(tree.Child(2).Value(), 5, ());
  TEST_EQUAL(tree.Child(3).Value(), 2, ());
  TEST_EQUAL(tree.Child(4).Value(), 1, ());
  TEST_EQUAL(tree.Child(4).Child(0).Value(), 20, ());
  TEST_EQUAL(tree.Child(4).Child(1).Value(), 10, ());
  TEST_EQUAL(tree.Child(4).Child(2).Value(), 30, ());

  // parent test
  TEST(!tree.HasParent(), ());
  TEST(!tree.Child(0).Parent().HasParent(), ());
  TEST_EQUAL(tree.Child(4).Child(0).Parent().Value(), 1, ());
  TEST_EQUAL(tree.Child(4).Child(2).Parent().Value(), 1, ());

  Calculator<TTree> c1;
  tree.ForEachChild(c1);
  TEST_EQUAL(c1.count, 5, ());

  Calculator<TTree> c2;
  tree.ForEachDescendant(c2);
  TEST_EQUAL(c2.count, 8, ());

  Calculator<TTree> c3;
  tree.Child(4).Child(0).ForEachAncestorExceptForTheRoot(c3);
  TEST_EQUAL(c3.count, 1, ());

  tree.Clear();
  Calculator<TTree> c4;
  tree.ForEachDescendant(c4);
  TEST_EQUAL(c4.count, 0, ("Tree should be empty"));
}
<commit_msg>[new downloader] Fixing unit tests.<commit_after>#include "testing/testing.hpp"

#include "storage/country_tree.hpp"

namespace
{
template <class TNode>
struct Calculator
{
  size_t count;
  Calculator() : count(0) {}
  void operator()(TNode const &)
  {
    ++count;
  }
};
} // namespace

UNIT_TEST(CountryTree_Smoke)
{
  typedef CountryTree<int, int>::Node TTree;
  TTree tree(0, nullptr);

  tree.AddAtDepth(1, 4);
  tree.AddAtDepth(1, 3);
  tree.AddAtDepth(1, 5);
  tree.AddAtDepth(1, 2);
  tree.AddAtDepth(1, 1);
  tree.AddAtDepth(2, 20);
  tree.AddAtDepth(2, 10);
  tree.AddAtDepth(2, 30);

  // children test
  TEST_EQUAL(tree.Child(0).Value(), 4, ());
  TEST_EQUAL(tree.Child(1).Value(), 3, ());
  TEST_EQUAL(tree.Child(2).Value(), 5, ());
  TEST_EQUAL(tree.Child(3).Value(), 2, ());
  TEST_EQUAL(tree.Child(4).Value(), 1, ());
  TEST_EQUAL(tree.Child(4).Child(0).Value(), 20, ());
  TEST_EQUAL(tree.Child(4).Child(1).Value(), 10, ());
  TEST_EQUAL(tree.Child(4).Child(2).Value(), 30, ());

  // parent test
  TEST(!tree.HasParent(), ());
  TEST(!tree.Child(0).Parent().HasParent(), ());
  TEST_EQUAL(tree.Child(4).Child(0).Parent().Value(), 1, ());
  TEST_EQUAL(tree.Child(4).Child(2).Parent().Value(), 1, ());

  Calculator<TTree> c1;
  tree.ForEachChild(c1);
  TEST_EQUAL(c1.count, 5, ());

  Calculator<TTree> c2;
  tree.ForEachDescendant(c2);
  TEST_EQUAL(c2.count, 8, ());

  Calculator<TTree> c3;
  tree.Child(4).Child(0).ForEachAncestorExceptForTheRoot(c3);
  TEST_EQUAL(c3.count, 1, ());
}
<|endoftext|>


<commit_before>#include "WPILib.h"
#include "Commands/Command.h"
#include "Commands/ExampleCommand.h"
#include "CommandBase.h"

class Robot: public IterativeRobot
{
private:
	std::unique_ptr<Command> autonomousCommand;
	SendableChooser *chooser;

	Joystick *base_control;
	Joystick *action_control;

	CANTalon *intake_motor;
	CANTalon *holding_motor;
	CANTalon *trebuchet_top_motor;
	CANTalon *trebuchet_bot_motor;

	Talon *talon0;
	Talon *talon1;
	Talon *talon2;
	Talon *talon3;

	DoubleSolenoid *spearSolenoid;

	// Compressor *c;

	DigitalInput *intake_sensor;

	double speedL, speedR;
	double hold_val;
	double treb_top, treb_bot;
	double intake_val;

	bool is_intaking;

	void RobotInit()
	{
		CommandBase::init();
		chooser = new SendableChooser();
		chooser->AddDefault("Default Auto", new ExampleCommand());
		//chooser->AddObject("My Auto", new MyAutoCommand());
		SmartDashboard::PutData("Auto Modes", chooser);

		base_control = new Joystick(5);
		action_control = new Joystick(4);

		talon0 = new Talon(0);
		talon1 = new Talon(1);
		talon2 = new Talon(2);
		talon3 = new Talon(3);

		intake_motor = new CANTalon(0);
		holding_motor = new CANTalon(1);
		trebuchet_top_motor = new CANTalon(2);
		trebuchet_bot_motor = new CANTalon(3);

		intake_sensor = new DigitalInput(0);

		is_intaking = false;

		// c = new Compressor(0);
	}

	/**
     * This function is called once each time the robot enters Disabled mode.
     * You can use it to reset any subsystem information you want to clear when
	 * the robot is disabled.
     */
	void DisabledInit()
	{
	}

	void DisabledPeriodic()
	{
		Scheduler::GetInstance()->Run();
	}

	/**
	 * This autonomous (along with the chooser code above) shows how to select between different autonomous modes
	 * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
	 * Dashboard, remove all of the chooser code and uncomment the GetString code to get the auto name from the text box
	 * below the Gyro
	 *
	 * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
	 * or additional comparisons to the if-else structure below with additional strings & commands.
	 */
	void AutonomousInit()
	{
		/* std::string autoSelected = SmartDashboard::GetString("Auto Selector", "Default");
		if(autoSelected == "My Auto") {
			autonomousCommand.reset(new MyAutoCommand());
		} else {
			autonomousCommand.reset(new ExampleCommand());
		} */

		autonomousCommand.reset((Command *)chooser->GetSelected());

		if (autonomousCommand != NULL)
			autonomousCommand->Start();
	}

	void AutonomousPeriodic()
	{
		Scheduler::GetInstance()->Run();
	}

	void TeleopInit()
	{
		// This makes sure that the autonomous stops running when
		// teleop starts running. If you want the autonomous to
		// continue until interrupted by another command, remove
		// this line or comment it out.
		if (autonomousCommand != NULL)
			autonomousCommand->Cancel();
	}

	void TeleopPeriodic()
	{
		Scheduler::GetInstance()->Run();

		speedL = 0.0;
		speedR = 0.0;
		treb_top = 0.0;
		treb_bot = 0.0;
		hold_val = 0.0;
		intake_val = 0.0;

		double j_x = base_control->GetRawAxis(0);
		double j_y = base_control->GetRawAxis(1);

		if (action_control->GetRawButton(1)) {
			treb_top = 1.0;
			treb_bot = -1.0;
			hold_val = 1.0;
		}
		if (action_control->GetRawButton(6)) {
			treb_top = 0.5;
			treb_bot = -0.5;
			hold_val = 1.0;
		}
		if (action_control->GetRawButton(4)) {
			intake_val = -1.0;
			hold_val = -1.0;
		}
		if (action_control->GetRawButton(2)) {
			hold_val = 1.0;
			intake_val = 1.0;
		}

		speedL += -j_y - j_x;
		speedR += -j_y + j_x;

		if (base_control->GetRawButton(1)) {
			speedL /= 1.0;
			speedR /= 1.0;
		}
		else if (base_control->GetRawButton(2)) {
			speedL /= 3.0;
			speedR /= 3.0;
		}
		else {
			speedL /= 2.0;
			speedR /= 2.0;
		}

		if (action_control->GetRawButton(7)) {
			spearSolenoid->Set(DoubleSolenoid::kForward);
		} else if (action_control->GetRawButton(8)) {
			spearSolenoid->Set(DoubleSolenoid::kReverse);
		}
		if (action_control->GetRawButton(9)) {
			spearSolenoid->Set(DoubleSolenoid::kOff);
		}

		talon0->Set(speedR);
		talon1->Set(speedR);
		talon2->Set(-speedL);
		talon3->Set(-speedL);

		trebuchet_top_motor->Set(-treb_top);
		trebuchet_bot_motor->Set(-treb_bot);
		intake_motor->Set(-intake_val);
		holding_motor->Set(hold_val);

	}

	void TestPeriodic()
	{
		LiveWindow::GetInstance()->Run();
	}
};

START_ROBOT_CLASS(Robot)

<commit_msg>Compressor code and other pneumatics things<commit_after>
#include "WPILib.h"
#include "Commands/Command.h"
#include "Commands/ExampleCommand.h"
#include "CommandBase.h"

class Robot: public IterativeRobot
{
private:
	std::unique_ptr<Command> autonomousCommand;
	SendableChooser *chooser;

	Joystick *base_control;
	Joystick *action_control;

	CANTalon *intake_motor;
	CANTalon *holding_motor;
	CANTalon *trebuchet_top_motor;
	CANTalon *trebuchet_bot_motor;

	Talon *talon0;
	Talon *talon1;
	Talon *talon2;
	Talon *talon3;

	DoubleSolenoid *spearSolenoid;

	Compressor *c;

	DigitalInput *intake_sensor;

	double speedL, speedR;
	double hold_val;
	double treb_top, treb_bot;
	double intake_val;

	bool is_intaking;

	bool enabled;
	bool pressureSwitch;

	float current;

	void RobotInit()
	{
		CommandBase::init();
		chooser = new SendableChooser();
		chooser->AddDefault("Default Auto", new ExampleCommand());
		//chooser->AddObject("My Auto", new MyAutoCommand());
		SmartDashboard::PutData("Auto Modes", chooser);

		base_control = new Joystick(5);
		action_control = new Joystick(4);

		talon0 = new Talon(0);
		talon1 = new Talon(1);
		talon2 = new Talon(2);
		talon3 = new Talon(3);

		intake_motor = new CANTalon(0);
		holding_motor = new CANTalon(1);
		trebuchet_top_motor = new CANTalon(2);
		trebuchet_bot_motor = new CANTalon(3);

		intake_sensor = new DigitalInput(0);

		is_intaking = false;

		c = new Compressor(0);
	}

	/**
     * This function is called once each time the robot enters Disabled mode.
     * You can use it to reset any subsystem information you want to clear when
	 * the robot is disabled.
     */
	void DisabledInit()
	{
	}

	void DisabledPeriodic()
	{
		Scheduler::GetInstance()->Run();
	}

	/**
	 * This autonomous (along with the chooser code above) shows how to select between different autonomous modes
	 * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
	 * Dashboard, remove all of the chooser code and uncomment the GetString code to get the auto name from the text box
	 * below the Gyro
	 *
	 * You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
	 * or additional comparisons to the if-else structure below with additional strings & commands.
	 */
	void AutonomousInit()
	{
		/* std::string autoSelected = SmartDashboard::GetString("Auto Selector", "Default");
		if(autoSelected == "My Auto") {
			autonomousCommand.reset(new MyAutoCommand());
		} else {
			autonomousCommand.reset(new ExampleCommand());
		} */

		autonomousCommand.reset((Command *)chooser->GetSelected());

		if (autonomousCommand != NULL)
			autonomousCommand->Start();
	}

	void AutonomousPeriodic()
	{
		Scheduler::GetInstance()->Run();
	}

	void TeleopInit()
	{
		// This makes sure that the autonomous stops running when
		// teleop starts running. If you want the autonomous to
		// continue until interrupted by another command, remove
		// this line or comment it out.
		if (autonomousCommand != NULL)
			autonomousCommand->Cancel();
	}

	void TeleopPeriodic()
	{
		Scheduler::GetInstance()->Run();

		// Reset all values
		speedL = 0.0;
		speedR = 0.0;
		treb_top = 0.0;
		treb_bot = 0.0;
		hold_val = 0.0;
		intake_val = 0.0;

		double j_x = base_control->GetRawAxis(0);
		double j_y = base_control->GetRawAxis(1);

		// Shoot
		if (action_control->GetRawButton(1)) {
			treb_top = 1.0;
			treb_bot = -1.0;
			hold_val = 1.0;
		}
		// Lob the ball at low power from the shooter into the low goal
		if (action_control->GetRawButton(6)) {
			treb_top = 0.5;
			treb_bot = -0.5;
			hold_val = 1.0;
		}
		// Reverse the ball back out the intake part
		if (action_control->GetRawButton(4)) {
			intake_val = -1.0;
			hold_val = -1.0;
		}
		// Intake the ball
		if (action_control->GetRawButton(2)) {
			hold_val = 1.0;
			intake_val = 1.0;
		}

		// Driving
		speedL += -j_y - j_x;
		speedR += -j_y + j_x;

		// Maximum drive motor speed
		if (base_control->GetRawButton(1)) {
			speedL /= 1.0;
			speedR /= 1.0;
		}
		// Slow drive motor speed for little adjustments in robot position
		else if (base_control->GetRawButton(2)) {
			speedL /= 3.0;
			speedR /= 3.0;
		}
		// Regular speed of drive motors
		else {
			speedL /= 1.75;
			speedR /= 1.75;
		}

		// Pneumatics section

		enabled = c->Enabled();
		pressureSwitch = c->GetPressureSwitchValue();
		current = c->GetCompressorCurrent();

		// Spears
		if (action_control->GetRawButton(7)) {
			spearSolenoid->Set(DoubleSolenoid::kForward);
		} else if (action_control->GetRawButton(8)) {
			spearSolenoid->Set(DoubleSolenoid::kReverse);
		}
		if (action_control->GetRawButton(9)) {
			spearSolenoid->Set(DoubleSolenoid::kOff);
		}

		// Compressor
		if (action_control->GetRawButton(11)) {
			c->SetClosedLoopControl(true);
		} else if (action_control->GetRawButton(12)) {
			c->SetClosedLoopControl(false);
		}

		// Set driving talons
		talon0->Set(speedR);
		talon1->Set(speedR);
		talon2->Set(-speedL);
		talon3->Set(-speedL);

		// Set shooting and intake talons
		trebuchet_top_motor->Set(-treb_top);
		trebuchet_bot_motor->Set(-treb_bot);
		intake_motor->Set(-intake_val);
		holding_motor->Set(hold_val);

	}

	void TestPeriodic()
	{
		LiveWindow::GetInstance()->Run();
	}
};

START_ROBOT_CLASS(Robot)

<|endoftext|>


<commit_before><commit_msg>WaE: overriding virtual function declaration not marked 'override'<commit_after><|endoftext|>