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

#ifndef SPIRIT_LEXER_H
#define SPIRIT_LEXER_H

#include <fstream>
#include <string>
#include <utility>
#include <stack>

#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>

namespace eddic {

namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;

typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type, boost::mpl::vector<std::string, int>> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;

template<typename L>
class SimpleLexer : public lex::lexer<L> {
    private:

    public:
        SimpleLexer() {
            //Define keywords
            for_ = "for";
            while_ = "while";
            if_ = "if";
            else_ = "else";
            false_ = "false";
            true_ = "true";
            from_ = "from";
            to_ = "to";
            foreach_ = "foreach";
            in_ = "in";
            return_ = "return";
            const_ = "const";

            word = "[a-zA-Z]+";
            integer = "[0-9]+";
            litteral = "\\\"[^\\\"]*\\\"";

            left_parenth = '(';
            right_parenth = ')';
            left_brace = '{';
            right_brace = '}';
            left_bracket = '[';
            right_bracket = ']';

            stop = ';';
            comma = ',';

            swap = "<=>";
            assign = '=';
            addition = '+';
            subtraction = '-';
            multiplication = '*';
            division = '/';
            modulo = '%';

            equals = "==";
            not_equals = "!=";
            greater = ">";
            less = "<";
            greater_equals = ">=";
            less_equals = "<=";

            whitespaces = "[ \\t\\n]+";
            multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
            singleline_comment = "\\/\\/[^\n]*";

            //Ignore whitespaces
            this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];

            this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
            this->self += comma | stop;
            this->self += assign | swap | addition | subtraction | multiplication | division | modulo;
            this->self += for_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_;
            this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
            this->self += integer | word | litteral;

            //Ignore comments
            this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
            this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
        }

        typedef lex::token_def<lex::omit> ConsumedToken;
        typedef lex::token_def<std::string> StringToken;
        typedef lex::token_def<int> IntegerToken;
        typedef lex::token_def<char> CharToken;

        StringToken word, litteral;
        IntegerToken integer;

        CharToken addition, subtraction, multiplication, division, modulo;
        StringToken equals, not_equals, greater, less, greater_equals, less_equals;

        ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
        ConsumedToken stop, comma;
        ConsumedToken assign, swap;

        //Keywords
        ConsumedToken if_, else_, for_, while_, from_, in_, to_, foreach_, return_;
        ConsumedToken true_, false_;
        ConsumedToken const_;

        //Ignored tokens
        ConsumedToken whitespaces, singleline_comment, multiline_comment;
};

} //end of eddic

#endif
<commit_msg>Include the 'include' keyword into the lexer<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef SPIRIT_LEXER_H
#define SPIRIT_LEXER_H

#include <fstream>
#include <string>
#include <utility>
#include <stack>

#include <boost/spirit/include/classic_position_iterator.hpp>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/spirit/include/classic_core.hpp>
#include <boost/spirit/include/classic_functor_parser.hpp>
#include <boost/spirit/include/classic_attribute.hpp>
#include <boost/spirit/include/classic_symbols.hpp>

namespace eddic {

namespace spirit = boost::spirit;
namespace lex = boost::spirit::lex;

typedef std::string::iterator base_iterator_type;
typedef boost::spirit::classic::position_iterator2<base_iterator_type> pos_iterator_type;
typedef boost::spirit::lex::lexertl::token<pos_iterator_type, boost::mpl::vector<std::string, int>> Tok;
typedef lex::lexertl::actor_lexer<Tok> lexer_type;

template<typename L>
class SimpleLexer : public lex::lexer<L> {
    private:

    public:
        SimpleLexer() {
            //Define keywords
            for_ = "for";
            while_ = "while";
            if_ = "if";
            else_ = "else";
            false_ = "false";
            true_ = "true";
            from_ = "from";
            to_ = "to";
            foreach_ = "foreach";
            in_ = "in";
            return_ = "return";
            const_ = "const";
            include = "include";

            word = "[a-zA-Z]+";
            integer = "[0-9]+";
            litteral = "\\\"[^\\\"]*\\\"";

            left_parenth = '(';
            right_parenth = ')';
            left_brace = '{';
            right_brace = '}';
            left_bracket = '[';
            right_bracket = ']';

            stop = ';';
            comma = ',';

            swap = "<=>";
            assign = '=';
            addition = '+';
            subtraction = '-';
            multiplication = '*';
            division = '/';
            modulo = '%';

            equals = "==";
            not_equals = "!=";
            greater = ">";
            less = "<";
            greater_equals = ">=";
            less_equals = "<=";

            whitespaces = "[ \\t\\n]+";
            multiline_comment = "\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\/";
            singleline_comment = "\\/\\/[^\n]*";

            //Ignore whitespaces
            this->self += whitespaces [lex::_pass = lex::pass_flags::pass_ignore];

            this->self += left_parenth | right_parenth | left_brace | right_brace | left_bracket | right_bracket;
            this->self += comma | stop;
            this->self += assign | swap | addition | subtraction | multiplication | division | modulo;
            this->self += for_ | while_ | true_ | false_ | if_ | else_ | from_ | to_ | in_ | foreach_ | return_ | const_ | include;
            this->self += equals | not_equals | greater_equals | less_equals | greater | less ;
            this->self += integer | word | litteral;

            //Ignore comments
            this->self += multiline_comment [lex::_pass = lex::pass_flags::pass_ignore];
            this->self += singleline_comment [lex::_pass = lex::pass_flags::pass_ignore];
        }

        typedef lex::token_def<lex::omit> ConsumedToken;
        typedef lex::token_def<std::string> StringToken;
        typedef lex::token_def<int> IntegerToken;
        typedef lex::token_def<char> CharToken;

        StringToken word, litteral;
        IntegerToken integer;

        CharToken addition, subtraction, multiplication, division, modulo;
        StringToken equals, not_equals, greater, less, greater_equals, less_equals;

        ConsumedToken left_parenth, right_parenth, left_brace, right_brace, left_bracket, right_bracket;
        ConsumedToken stop, comma;
        ConsumedToken assign, swap;

        //Keywords
        ConsumedToken if_, else_, for_, while_, from_, in_, to_, foreach_, return_;
        ConsumedToken true_, false_;
        ConsumedToken const_, include;

        //Ignored tokens
        ConsumedToken whitespaces, singleline_comment, multiline_comment;
};

} //end of eddic

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE 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 TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _MSC_VER
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

// ======= GCC =========

#if defined __GNUC__

# if __GNUC__ >= 3
#  define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif

// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __attribute__ ((visibility("default")))
#  endif
# endif

// ======= SUNPRO =========

#elif defined __SUNPRO_CC

# if __SUNPRO_CC >= 0x550
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __global
#  endif
# endif

// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1

// ======= MSVC =========

#elif defined BOOST_MSVC

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif

#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)

#endif

// ======= PLATFORMS =========

// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif

// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1

// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0

// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_ICONV_ARG (const char**)
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1

// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0

// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1

// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif

// ==== GNU/Hurd ===
#elif defined __GNU__
#define TORRENT_HURD
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_IFCONF 1

#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif

// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows

// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX

// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH

// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH

// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX

// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255

#endif

#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW

#include <stdarg.h>

inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	int ret = _vsnprintf(buf, len, fmt, lp);
	va_end(lp);
	if (ret < 0) { buf[len-1] = 0; ret = len-1; }
	return ret;
}

#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
	&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif

#ifndef TORRENT_ICONV_ARG
#define TORRENT_ICONV_ARG (char**)
#endif

// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif

#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif

#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif

#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif

#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif

#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif

#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif

#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif

#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE

#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif

#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif

#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif

#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif

#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif

#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif

#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif

#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif

#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif

#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif

#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif

// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
	&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
	&& !defined TORRENT_USE_CLOCK_GETTIME \
	&& !defined TORRENT_USE_BOOST_DATE_TIME \
	&& !defined TORRENT_USE_ECLOCK \
	&& !defined TORRENT_USE_SYSTEM_TIME

#if defined __APPLE__ && defined __MACH__
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif

#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
	if (str == 0) return 0;
	char* tmp = (char*)malloc(strlen(str) + 1);
	if (tmp == 0) return 0;
	strcpy(tmp, str);
	return tmp;
}
#endif

// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS

#endif // TORRENT_CONFIG_HPP_INCLUDED

<commit_msg>fix PRId64 macro for mingw<commit_after>/*

Copyright (c) 2005, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE 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 TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
// MinGW uses microsofts runtime
#if defined _MSC_VER || defined __MINGW32__
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

// ======= GCC =========

#if defined __GNUC__

# if __GNUC__ >= 3
#  define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif

// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __attribute__ ((visibility("default")))
#  endif
# endif

// ======= SUNPRO =========

#elif defined __SUNPRO_CC

# if __SUNPRO_CC >= 0x550
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __global
#  endif
# endif

// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1

// ======= MSVC =========

#elif defined BOOST_MSVC

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)
// 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup
#pragma warning(disable: 4996)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif

#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)

#endif

// ======= PLATFORMS =========

// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif

// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 0
#endif
#endif
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_SYSCTL 1
#define TORRENT_USE_IFCONF 1

// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_NETLINK 1
#define TORRENT_USE_IFCONF 1
#define TORRENT_HAS_SALEN 0

// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_ICONV_ARG (const char**)
#define TORRENT_USE_RLIMIT 0
#define TORRENT_USE_NETLINK 0
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
#define TORRENT_USE_GETIPFORWARDTABLE 1

// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 1
#endif
#define TORRENT_USE_GETADAPTERSADDRESSES 1
#define TORRENT_HAS_SALEN 0
// windows has its own functions to convert
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_LOCALE 1
#endif
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0

// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1
#define TORRENT_USE_IFCONF 1

// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 0
#endif
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif

// ==== GNU/Hurd ===
#elif defined __GNU__
#define TORRENT_HURD
#define TORRENT_USE_IFADDRS 1
#define TORRENT_USE_IFCONF 1

#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif

// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows

// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX

// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH

// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH

// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX

// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255

#endif

#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW

#include <stdarg.h>

inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	int ret = _vsnprintf(buf, len, fmt, lp);
	va_end(lp);
	if (ret < 0) { buf[len-1] = 0; ret = len-1; }
	return ret;
}

#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
	&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif

#ifndef TORRENT_ICONV_ARG
#define TORRENT_ICONV_ARG (char**)
#endif

// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif

#ifndef TORRENT_HAS_SALEN
#define TORRENT_HAS_SALEN 1
#endif

#ifndef TORRENT_USE_GETADAPTERSADDRESSES
#define TORRENT_USE_GETADAPTERSADDRESSES 0
#endif

#ifndef TORRENT_USE_NETLINK
#define TORRENT_USE_NETLINK 0
#endif

#ifndef TORRENT_USE_SYSCTL
#define TORRENT_USE_SYSCTL 0
#endif

#ifndef TORRENT_USE_GETIPFORWARDTABLE
#define TORRENT_USE_GETIPFORWARDTABLE 0
#endif

#ifndef TORRENT_USE_LOCALE
#define TORRENT_USE_LOCALE 0
#endif

#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif

#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE

#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif

#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif

#ifndef TORRENT_USE_IFADDRS
#define TORRENT_USE_IFADDRS 0
#endif

#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif

#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif

#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif

#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif

#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif

#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif

#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif

#ifndef TORRENT_HAS_STRDUP
#define TORRENT_HAS_STRDUP 1
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif

// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
	&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
	&& !defined TORRENT_USE_CLOCK_GETTIME \
	&& !defined TORRENT_USE_BOOST_DATE_TIME \
	&& !defined TORRENT_USE_ECLOCK \
	&& !defined TORRENT_USE_SYSTEM_TIME

#if defined __APPLE__ && defined __MACH__
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif

#if !TORRENT_HAS_STRDUP
inline char* strdup(char const* str)
{
	if (str == 0) return 0;
	char* tmp = (char*)malloc(strlen(str) + 1);
	if (tmp == 0) return 0;
	strcpy(tmp, str);
	return tmp;
}
#endif

// for non-exception builds
#ifdef BOOST_NO_EXCEPTIONS
#define TORRENT_TRY if (true)
#define TORRENT_CATCH(x) else if (false)
#define TORRENT_DECLARE_DUMMY(x, y) x y
#else
#define TORRENT_TRY try
#define TORRENT_CATCH(x) catch(x)
#define TORRENT_DECLARE_DUMMY(x, y)
#endif // BOOST_NO_EXCEPTIONS

#endif // TORRENT_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>/*

Copyright (c) 2005-2014, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE 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 TORRENT_EXPORT_HPP_INCLUDED
#define TORRENT_EXPORT_HPP_INCLUDED

#include <boost/config.hpp>

// backwards compatibility with older versions of boost
#if !defined BOOST_SYMBOL_EXPORT && !defined BOOST_SYMBOL_IMPORT
# if defined _MSC_VER || defined __MINGW32__
#  define BOOST_SYMBOL_EXPORT __declspec(dllexport)
#  define BOOST_SYMBOL_IMPORT __declspec(dllimport)
# elif __GNU__ >= 4
#  define BOOST_SYMBOL_EXPORT __attribute__((visibility("default")))
#  define BOOST_SYMBOL_IMPORT __attribute__((visibility("default")))
# else
#  define BOOST_SYMBOL_EXPORT
#  define BOOST_SYMBOL_IMPORT
# endif
#endif

#if defined TORRENT_BUILDING_SHARED
# define TORRENT_EXPORT BOOST_SYMBOL_EXPORT
#elif defined TORRENT_LINKING_SHARED
# define TORRENT_EXPORT BOOST_SYMBOL_IMPORT
#endif

// when this is specified, export a bunch of extra
// symbols, mostly for the unit tests to reach
#if TORRENT_EXPORT_EXTRA
# if defined TORRENT_BUILDING_SHARED
#  define TORRENT_EXTRA_EXPORT BOOST_SYMBOL_EXPORT
# elif defined TORRENT_LINKING_SHARED
#  define TORRENT_EXTRA_EXPORT BOOST_SYMBOL_IMPORT
# endif
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_EXTRA_EXPORT
# define TORRENT_EXTRA_EXPORT
#endif

#endif

<commit_msg>another attempt to not have stdint.h leak into the ed25519 source (which causes build failures on BSD)<commit_after>/*

Copyright (c) 2005-2014, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE 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 TORRENT_EXPORT_HPP_INCLUDED
#define TORRENT_EXPORT_HPP_INCLUDED

#if !defined(BOOST_COMPILER_CONFIG) && !defined(BOOST_NO_COMPILER_CONFIG)
#  include <boost/config/select_compiler_config.hpp>
#endif
#ifdef BOOST_COMPILER_CONFIG
#  include BOOST_COMPILER_CONFIG
#endif

#if !defined(BOOST_PLATFORM_CONFIG) && !defined(BOOST_NO_PLATFORM_CONFIG)
#  include <boost/config/select_platform_config.hpp>
#endif
#ifdef BOOST_PLATFORM_CONFIG
#  include BOOST_PLATFORM_CONFIG
#endif

// backwards compatibility with older versions of boost
#if !defined BOOST_SYMBOL_EXPORT && !defined BOOST_SYMBOL_IMPORT
# if defined _MSC_VER || defined __MINGW32__
#  define BOOST_SYMBOL_EXPORT __declspec(dllexport)
#  define BOOST_SYMBOL_IMPORT __declspec(dllimport)
# elif __GNU__ >= 4
#  define BOOST_SYMBOL_EXPORT __attribute__((visibility("default")))
#  define BOOST_SYMBOL_IMPORT __attribute__((visibility("default")))
# else
#  define BOOST_SYMBOL_EXPORT
#  define BOOST_SYMBOL_IMPORT
# endif
#endif

#if defined TORRENT_BUILDING_SHARED
# define TORRENT_EXPORT BOOST_SYMBOL_EXPORT
#elif defined TORRENT_LINKING_SHARED
# define TORRENT_EXPORT BOOST_SYMBOL_IMPORT
#endif

// when this is specified, export a bunch of extra
// symbols, mostly for the unit tests to reach
#if TORRENT_EXPORT_EXTRA
# if defined TORRENT_BUILDING_SHARED
#  define TORRENT_EXTRA_EXPORT BOOST_SYMBOL_EXPORT
# elif defined TORRENT_LINKING_SHARED
#  define TORRENT_EXTRA_EXPORT BOOST_SYMBOL_IMPORT
# endif
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_EXTRA_EXPORT
# define TORRENT_EXTRA_EXPORT
#endif

#endif

<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#pragma once

#include <seastar/core/circular_buffer.hh>
#include <seastar/core/future.hh>
#include <queue>
#include <seastar/util/std-compat.hh>

namespace seastar {

/// Asynchronous single-producer single-consumer queue with limited capacity.
/// There can be at most one producer-side and at most one consumer-side operation active at any time.
/// Operations returning a future are considered to be active until the future resolves.
///
/// Note: queue requires the data type T to be nothrow move constructible as it's
/// returned as future<T> by \ref pop_eventually and seastar futurized data type
/// are required to be nothrow move-constructible.
template <typename T>
SEASTAR_CONCEPT(requires std::is_nothrow_move_constructible_v<T>)
class queue {
    std::queue<T, circular_buffer<T>> _q;
    size_t _max;
    std::optional<promise<>> _not_empty;
    std::optional<promise<>> _not_full;
    std::exception_ptr _ex = nullptr;
private:
    void notify_not_empty() noexcept;
    void notify_not_full() noexcept;
public:
    explicit queue(size_t size);

    /// \brief Push an item.
    ///
    /// Returns false if the queue was full and the item was not pushed.
    bool push(T&& a);

    /// \brief Pop an item.
    ///
    /// Popping from an empty queue will result in undefined behavior.
    T pop();

    /// \brief access the front element in the queue
    ///
    /// Accessing the front of an empty queue will result in undefined
    /// behaviour.
    T& front();

    /// Consumes items from the queue, passing them to \c func, until \c func
    /// returns false or the queue it empty
    ///
    /// Returns false if func returned false.
    template <typename Func>
    bool consume(Func&& func);

    /// Returns true when the queue is empty.
    bool empty() const;

    /// Returns true when the queue is full.
    bool full() const;

    /// Returns a future<> that becomes available when pop() or consume()
    /// can be called.
    /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
    future<> not_empty();

    /// Returns a future<> that becomes available when push() can be called.
    /// A producer-side operation. Cannot be called concurrently with other producer-side operations.
    future<> not_full();

    /// Pops element now or when there is some. Returns a future that becomes
    /// available when some element is available.
    /// If the queue is, or already was, abort()ed, the future resolves with
    /// the exception provided to abort().
    /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
    future<T> pop_eventually();

    /// Pushes the element now or when there is room. Returns a future<> which
    /// resolves when data was pushed.
    /// If the queue is, or already was, abort()ed, the future resolves with
    /// the exception provided to abort().
    /// A producer-side operation. Cannot be called concurrently with other producer-side operations.
    future<> push_eventually(T&& data);

    /// Returns the number of items currently in the queue.
    size_t size() const { return _q.size(); }

    /// Returns the size limit imposed on the queue during its construction
    /// or by a call to set_max_size(). If the queue contains max_size()
    /// items (or more), further items cannot be pushed until some are popped.
    size_t max_size() const noexcept { return _max; }

    /// Set the maximum size to a new value. If the queue's max size is reduced,
    /// items already in the queue will not be expunged and the queue will be temporarily
    /// bigger than its max_size.
    void set_max_size(size_t max) {
        _max = max;
        if (!full()) {
            notify_not_full();
        }
    }

    /// Destroy any items in the queue, and pass the provided exception to any
    /// waiting readers or writers - or to any later read or write attempts.
    void abort(std::exception_ptr ex) {
        while (!_q.empty()) {
            _q.pop();
        }
        _ex = ex;
        if (_not_full) {
            _not_full->set_exception(ex);
            _not_full= std::nullopt;
        }
        if (_not_empty) {
            _not_empty->set_exception(std::move(ex));
            _not_empty = std::nullopt;
        }
    }

    /// \brief Check if there is an active consumer
    ///
    /// Returns true if another fiber waits for an item to be pushed into the queue
    bool has_blocked_consumer() const noexcept {
        return bool(_not_empty);
    }
};

template <typename T>
inline
queue<T>::queue(size_t size)
    : _max(size) {
}

template <typename T>
inline
void queue<T>::notify_not_empty() noexcept {
    if (_not_empty) {
        _not_empty->set_value();
        _not_empty = std::optional<promise<>>();
    }
}

template <typename T>
inline
void queue<T>::notify_not_full() noexcept {
    if (_not_full) {
        _not_full->set_value();
        _not_full = std::optional<promise<>>();
    }
}

template <typename T>
inline
bool queue<T>::push(T&& data) {
    if (_q.size() < _max) {
        _q.push(std::move(data));
        notify_not_empty();
        return true;
    } else {
        return false;
    }
}

template <typename T>
inline
T& queue<T>::front() {
    return _q.front();
}

template <typename T>
inline
T queue<T>::pop() {
    if (_q.size() == _max) {
        notify_not_full();
    }
    T data = std::move(_q.front());
    _q.pop();
    return data;
}

template <typename T>
inline
future<T> queue<T>::pop_eventually() {
    // seastar allows only nothrow_move_constructible types
    // to be returned as future<T>
    static_assert(std::is_nothrow_move_constructible_v<T>,
                  "Queue element type must be no-throw move constructible");

    if (_ex) {
        return make_exception_future<T>(_ex);
    }
    if (empty()) {
        return not_empty().then([this] {
            if (_ex) {
                return make_exception_future<T>(_ex);
            } else {
                return make_ready_future<T>(pop());
            }
        });
    } else {
        return make_ready_future<T>(pop());
    }
}

template <typename T>
inline
future<> queue<T>::push_eventually(T&& data) {
    if (_ex) {
        return make_exception_future<>(_ex);
    }
    if (full()) {
        return not_full().then([this, data = std::move(data)] () mutable {
            _q.push(std::move(data));
            notify_not_empty();
        });
    } else {
        _q.push(std::move(data));
        notify_not_empty();
        return make_ready_future<>();
    }
}

template <typename T>
template <typename Func>
inline
bool queue<T>::consume(Func&& func) {
    if (_ex) {
        std::rethrow_exception(_ex);
    }
    bool running = true;
    while (!_q.empty() && running) {
        running = func(std::move(_q.front()));
        _q.pop();
    }
    if (!full()) {
        notify_not_full();
    }
    return running;
}

template <typename T>
inline
bool queue<T>::empty() const {
    return _q.empty();
}

template <typename T>
inline
bool queue<T>::full() const {
    return _q.size() >= _max;
}

template <typename T>
inline
future<> queue<T>::not_empty() {
    if (_ex) {
        return make_exception_future<>(_ex);
    }
    if (!empty()) {
        return make_ready_future<>();
    } else {
        _not_empty = promise<>();
        return _not_empty->get_future();
    }
}

template <typename T>
inline
future<> queue<T>::not_full() {
    if (_ex) {
        return make_exception_future<>(_ex);
    }
    if (!full()) {
        return make_ready_future<>();
    } else {
        _not_full = promise<>();
        return _not_full->get_future();
    }
}

}

<commit_msg>queue: mark methods depending on std::queue noexcept<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
/*
 * Copyright (C) 2014 Cloudius Systems, Ltd.
 */

#pragma once

#include <seastar/core/circular_buffer.hh>
#include <seastar/core/future.hh>
#include <queue>
#include <seastar/util/std-compat.hh>

namespace seastar {

/// Asynchronous single-producer single-consumer queue with limited capacity.
/// There can be at most one producer-side and at most one consumer-side operation active at any time.
/// Operations returning a future are considered to be active until the future resolves.
///
/// Note: queue requires the data type T to be nothrow move constructible as it's
/// returned as future<T> by \ref pop_eventually and seastar futurized data type
/// are required to be nothrow move-constructible.
template <typename T>
SEASTAR_CONCEPT(requires std::is_nothrow_move_constructible_v<T>)
class queue {
    std::queue<T, circular_buffer<T>> _q;
    size_t _max;
    std::optional<promise<>> _not_empty;
    std::optional<promise<>> _not_full;
    std::exception_ptr _ex = nullptr;
private:
    void notify_not_empty() noexcept;
    void notify_not_full() noexcept;
public:
    explicit queue(size_t size);

    /// \brief Push an item.
    ///
    /// Returns false if the queue was full and the item was not pushed.
    bool push(T&& a);

    /// \brief Pop an item.
    ///
    /// Popping from an empty queue will result in undefined behavior.
    T pop();

    /// \brief access the front element in the queue
    ///
    /// Accessing the front of an empty or aborted queue will result in undefined
    /// behaviour.
    T& front() noexcept;

    /// Consumes items from the queue, passing them to \c func, until \c func
    /// returns false or the queue it empty
    ///
    /// Returns false if func returned false.
    template <typename Func>
    bool consume(Func&& func);

    /// Returns true when the queue is empty.
    bool empty() const noexcept;

    /// Returns true when the queue is full.
    bool full() const noexcept;

    /// Returns a future<> that becomes available when pop() or consume()
    /// can be called.
    /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
    future<> not_empty();

    /// Returns a future<> that becomes available when push() can be called.
    /// A producer-side operation. Cannot be called concurrently with other producer-side operations.
    future<> not_full();

    /// Pops element now or when there is some. Returns a future that becomes
    /// available when some element is available.
    /// If the queue is, or already was, abort()ed, the future resolves with
    /// the exception provided to abort().
    /// A consumer-side operation. Cannot be called concurrently with other consumer-side operations.
    future<T> pop_eventually();

    /// Pushes the element now or when there is room. Returns a future<> which
    /// resolves when data was pushed.
    /// If the queue is, or already was, abort()ed, the future resolves with
    /// the exception provided to abort().
    /// A producer-side operation. Cannot be called concurrently with other producer-side operations.
    future<> push_eventually(T&& data);

    /// Returns the number of items currently in the queue.
    size_t size() const noexcept {
        // std::queue::size() has no reason to throw
        return _q.size();
    }

    /// Returns the size limit imposed on the queue during its construction
    /// or by a call to set_max_size(). If the queue contains max_size()
    /// items (or more), further items cannot be pushed until some are popped.
    size_t max_size() const noexcept { return _max; }

    /// Set the maximum size to a new value. If the queue's max size is reduced,
    /// items already in the queue will not be expunged and the queue will be temporarily
    /// bigger than its max_size.
    void set_max_size(size_t max) {
        _max = max;
        if (!full()) {
            notify_not_full();
        }
    }

    /// Destroy any items in the queue, and pass the provided exception to any
    /// waiting readers or writers - or to any later read or write attempts.
    void abort(std::exception_ptr ex) noexcept {
        // std::queue::empty() and pop() doesn't throw
        // since it just calls seastar::circular_buffer::pop_front
        // that is specified as noexcept.
        while (!_q.empty()) {
            _q.pop();
        }
        _ex = ex;
        if (_not_full) {
            _not_full->set_exception(ex);
            _not_full= std::nullopt;
        }
        if (_not_empty) {
            _not_empty->set_exception(std::move(ex));
            _not_empty = std::nullopt;
        }
    }

    /// \brief Check if there is an active consumer
    ///
    /// Returns true if another fiber waits for an item to be pushed into the queue
    bool has_blocked_consumer() const noexcept {
        return bool(_not_empty);
    }
};

template <typename T>
inline
queue<T>::queue(size_t size)
    : _max(size) {
}

template <typename T>
inline
void queue<T>::notify_not_empty() noexcept {
    if (_not_empty) {
        _not_empty->set_value();
        _not_empty = std::optional<promise<>>();
    }
}

template <typename T>
inline
void queue<T>::notify_not_full() noexcept {
    if (_not_full) {
        _not_full->set_value();
        _not_full = std::optional<promise<>>();
    }
}

template <typename T>
inline
bool queue<T>::push(T&& data) {
    if (_q.size() < _max) {
        _q.push(std::move(data));
        notify_not_empty();
        return true;
    } else {
        return false;
    }
}

template <typename T>
inline
T& queue<T>::front() noexcept {
    // std::queue::front() has no reason to throw
    return _q.front();
}

template <typename T>
inline
T queue<T>::pop() {
    if (_q.size() == _max) {
        notify_not_full();
    }
    T data = std::move(_q.front());
    _q.pop();
    return data;
}

template <typename T>
inline
future<T> queue<T>::pop_eventually() {
    // seastar allows only nothrow_move_constructible types
    // to be returned as future<T>
    static_assert(std::is_nothrow_move_constructible_v<T>,
                  "Queue element type must be no-throw move constructible");

    if (_ex) {
        return make_exception_future<T>(_ex);
    }
    if (empty()) {
        return not_empty().then([this] {
            if (_ex) {
                return make_exception_future<T>(_ex);
            } else {
                return make_ready_future<T>(pop());
            }
        });
    } else {
        return make_ready_future<T>(pop());
    }
}

template <typename T>
inline
future<> queue<T>::push_eventually(T&& data) {
    if (_ex) {
        return make_exception_future<>(_ex);
    }
    if (full()) {
        return not_full().then([this, data = std::move(data)] () mutable {
            _q.push(std::move(data));
            notify_not_empty();
        });
    } else {
        _q.push(std::move(data));
        notify_not_empty();
        return make_ready_future<>();
    }
}

template <typename T>
template <typename Func>
inline
bool queue<T>::consume(Func&& func) {
    if (_ex) {
        std::rethrow_exception(_ex);
    }
    bool running = true;
    while (!_q.empty() && running) {
        running = func(std::move(_q.front()));
        _q.pop();
    }
    if (!full()) {
        notify_not_full();
    }
    return running;
}

template <typename T>
inline
bool queue<T>::empty() const noexcept {
    // std::queue::empty() has no reason to throw
    return _q.empty();
}

template <typename T>
inline
bool queue<T>::full() const noexcept {
    // std::queue::size() has no reason to throw
    return _q.size() >= _max;
}

template <typename T>
inline
future<> queue<T>::not_empty() {
    if (_ex) {
        return make_exception_future<>(_ex);
    }
    if (!empty()) {
        return make_ready_future<>();
    } else {
        _not_empty = promise<>();
        return _not_empty->get_future();
    }
}

template <typename T>
inline
future<> queue<T>::not_full() {
    if (_ex) {
        return make_exception_future<>(_ex);
    }
    if (!full()) {
        return make_ready_future<>();
    } else {
        _not_full = promise<>();
        return _not_full->get_future();
    }
}

}

<|endoftext|>


<commit_before>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.

#ifndef TYPE_SAFE_VISITOR_HPP_INCLUDED
#define TYPE_SAFE_VISITOR_HPP_INCLUDED

#include <utility>

#include <type_safe/optional.hpp>
#include <type_safe/variant.hpp>

namespace type_safe
{
    /// \exclude
    namespace detail
    {
        // common type where void is wildcard
        template <typename A, typename B>
        struct common_type
        {
            using type = typename std::common_type<A, B>::type;
        };

        template <typename A>
        struct common_type<A, void>
        {
            using type = typename std::common_type<A>::type;
        };

        template <typename A>
        struct common_type<void, A>
        {
            using type = typename std::common_type<A>::type;
        };

        template <>
        struct common_type<void, void>
        {
            using type = void;
        };

        template <typename A, typename B>
        using common_type_t = typename common_type<A, B>::type;

        //=== visit optional ===//
        template <bool Save, typename Visitor, typename... Optional>
        struct visit_optional;

        template <bool Save, typename Visitor, typename Optional>
        struct visit_optional<Save, Visitor, Optional>
        {
            template <typename... Args>
            static auto call_visitor(int, Visitor&& visitor, Args&&... args)
                -> decltype(std::forward<Visitor>(visitor)(std::forward<Args>(args)...))
            {
                return std::forward<Visitor>(visitor)(std::forward<Args>(args)...);
            }

            template <typename... Args>
            static void call_visitor(short, Visitor&&, Args&&...)
            {
                static_assert(!Save, "call to visitor does not cover all possible combinations");
            }

            template <typename... Args>
            static auto call(Visitor&& visitor, Optional&& opt, Args&&... args) ->
                typename common_type<decltype(call_visitor(0, std::forward<Visitor>(visitor),
                                                           std::forward<Args>(args)..., nullopt)),
                                     decltype(
                                         call_visitor(0, std::forward<Visitor>(visitor),
                                                      std::forward<Args>(args)...,
                                                      std::forward<Optional>(opt).value()))>::type
            {
                return opt.has_value() ? call_visitor(0, std::forward<Visitor>(visitor),
                                                      std::forward<Args>(args)...,
                                                      std::forward<Optional>(opt).value()) :
                                         call_visitor(0, std::forward<Visitor>(visitor),
                                                      std::forward<Args>(args)..., nullopt);
            }
        };

        template <bool Save, typename Visitor, typename Optional, typename... Rest>
        struct visit_optional<Save, Visitor, Optional, Rest...>
        {
            template <typename... Args>
            static auto call(Visitor&& visitor, Optional&& opt, Rest&&... rest, Args&&... args) ->
                typename common_type<decltype(visit_optional<Save, Visitor, Rest...>::call(
                                         std::forward<Visitor>(visitor),
                                         std::forward<Rest>(rest)..., std::forward<Args>(args)...,
                                         std::forward<Optional>(opt).value())),
                                     decltype(visit_optional<Save, Visitor, Rest...>::call(
                                         std::forward<Visitor>(visitor),
                                         std::forward<Rest>(rest)..., std::forward<Args>(args)...,
                                         nullopt))>::type
            {
                return opt.has_value() ?
                           visit_optional<Save, Visitor,
                                          Rest...>::call(std::forward<Visitor>(visitor),
                                                         std::forward<Rest>(rest)...,
                                                         std::forward<Args>(args)...,
                                                         std::forward<Optional>(opt).value()) :
                           visit_optional<Save, Visitor, Rest...>::call(std::forward<Visitor>(
                                                                            visitor),
                                                                        std::forward<Rest>(rest)...,
                                                                        std::forward<Args>(args)...,
                                                                        nullopt);
            }
        };

        template <typename T>
        struct visitor_allow_incomplete
        {
            template <typename U, typename = typename U::incomplete_visitor>
            static std::true_type test(int);

            template <typename U>
            static std::true_type test(int, decltype(U::incomplete_visitor));

            template <typename U>
            static std::false_type test(short);

            static const bool value = decltype(test<typename std::decay<T>::type>(0))::value;
        };

        template <typename Visitor, class... Optionals>
        auto visit_optional_impl(Visitor&& visitor, Optionals&&... optionals)
            -> decltype(detail::visit_optional<!visitor_allow_incomplete<Visitor>::value,
                                               decltype(std::forward<Visitor>(visitor)),
                                               decltype(std::forward<Optionals>(optionals))...>::
                            call(std::forward<Visitor>(visitor),
                                 std::forward<Optionals>(optionals)...))
        {
            return detail::visit_optional<!visitor_allow_incomplete<Visitor>::value,
                                          decltype(std::forward<Visitor>(visitor)),
                                          decltype(std::forward<Optionals>(
                                              optionals))...>::call(std::forward<Visitor>(visitor),
                                                                    std::forward<Optionals>(
                                                                        optionals)...);
        }
    } // namespace detail

    /// Visits a [ts::basic_optional]().
    /// \effects Effectively calls `visitor((optionals.has_value() ? optionals.value() : nullopt)...)`,
    /// i.e. the `operator()` of `visitor` passing it `sizeof...(Optionals)` arguments,
    /// where the `i`th argument is the `value()` of the `i`th optional or `nullopt`, if it has none.
    /// If the particular combination of types is not overloaded,
    /// the program is ill-formed,
    /// unelss the `Visitor` provides a member named `incomplete_visitor`,
    /// then `visit()` does not do anything instead of the error.
    /// \returns The result of the chosen `operator()`,
    /// its the type is the common type of all possible combinations.
    /// \module optional
    /// \param 2
    /// \exclude
    template <
        typename Visitor, class... Optionals,
        typename std::enable_if<detail::all_of<detail::is_optional<Optionals>::value...>::value,
                                int>::type = 0>
    auto visit(Visitor&& visitor, Optionals&&... optionals)
        -> decltype(detail::visit_optional_impl(std::forward<Visitor>(visitor),
                                                std::forward<Optionals>(optionals)...))
    {
        return detail::visit_optional_impl(std::forward<Visitor>(visitor),
                                           std::forward<Optionals>(optionals)...);
    }

    /// \exclude
    namespace detail
    {
        template <bool AllowIncomplete, typename Visitor, class... Variants>
        class visit_variant_impl;

        template <bool AllowIncomplete, typename Visitor>
        class visit_variant_impl<AllowIncomplete, Visitor>
        {
            template <typename... Args>
            static auto call_impl(int, Visitor&& visitor, Args&&... args)
                -> decltype(std::forward<Visitor>(visitor)(std::forward<Args>(args)...))
            {
                return std::forward<Visitor>(visitor)(std::forward<Args>(args)...);
            }

            template <typename... Args>
            static void call_impl(short, Visitor&&, Args&&...)
            {
                static_assert(AllowIncomplete, "visitor does not cover all possible combinations");
            }

        public:
            template <typename... Args>
            static auto call(Visitor&& visitor, Args&&... args)
                -> decltype(call_impl(0, std::forward<Visitor>(visitor),
                                      std::forward<Args>(args)...))
            {
                return call_impl(0, std::forward<Visitor>(visitor), std::forward<Args>(args)...);
            }
        };

        template <bool AllowIncomplete, typename Visitor, class Variant>
        class visit_variant_impl<AllowIncomplete, Visitor, Variant>
        {
            template <typename, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<>, Variant&& variant,
                                  Args&&... args)
                -> decltype(visit_variant_impl<AllowIncomplete, Visitor>::call(
                    std::forward<Visitor>(visitor), std::forward<Args>(args)..., nullvar))
            {
                DEBUG_ASSERT(std::decay<Variant>::type::allow_empty::value && !variant.has_value(),
                             precondition_error_handler{}, "variant in invalid state for visitor");
                return visit_variant_impl<AllowIncomplete, Visitor>::call(std::forward<Visitor>(
                                                                              visitor),
                                                                          std::forward<Args>(
                                                                              args)...,
                                                                          nullvar);
            }

            template <typename RecursiveDecltype, typename Head, typename... Tail, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<Head, Tail...>,
                                  Variant&& variant, Args&&... args)
                -> common_type_t<decltype(visit_variant_impl<AllowIncomplete, Visitor>::call(
                                     std::forward<Visitor>(visitor), std::forward<Args>(args)...,
                                     std::forward<Variant>(variant).value(variant_type<Head>{}))),
                                 decltype(RecursiveDecltype::template call_type<RecursiveDecltype>(
                                     std::forward<Visitor>(visitor), variant_types<Tail...>{},
                                     std::forward<Variant>(variant), std::forward<Args>(args)...))>
            {
                if (variant.has_value(variant_type<Head>{}))
                    return visit_variant_impl<AllowIncomplete,
                                              Visitor>::call(std::forward<Visitor>(visitor),
                                                             std::forward<Args>(args)...,
                                                             std::forward<Variant>(variant).value(
                                                                 variant_type<Head>{}));
                else
                    return RecursiveDecltype::
                        template call_type<RecursiveDecltype>(std::forward<Visitor>(visitor),
                                                              variant_types<Tail...>{},
                                                              std::forward<Variant>(variant),
                                                              std::forward<Args>(args)...);
            }

        public:
            template <typename... Args>
            static auto call(Visitor&& visitor, Variant&& variant, Args&&... args)
                -> decltype(call_type<visit_variant_impl>(
                    std::forward<Visitor>(visitor), typename std::decay<Variant>::type::types{},
                    std::forward<Variant>(variant), std::forward<Args>(args)...))
            {
                return visit_variant_impl::
                    call_type<visit_variant_impl>(std::forward<Visitor>(visitor),
                                                  typename std::decay<Variant>::type::types{},
                                                  std::forward<Variant>(variant),
                                                  std::forward<Args>(args)...);
            }
        };

        template <bool AllowIncomplete, typename Visitor, class Variant, class... Rest>
        class visit_variant_impl<AllowIncomplete, Visitor, Variant, Rest...>
        {
            template <typename, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<>, Variant&& variant,
                                  Rest&&... rest, Args&&... args)
                -> decltype(visit_variant_impl<AllowIncomplete, Visitor, Rest...>::call(
                    std::forward<Visitor>(visitor), std::forward<Rest>(rest)...,
                    std::forward<Args>(args)..., nullvar))
            {
                DEBUG_ASSERT(std::decay<Variant>::type::allow_empty::value && !variant.has_value(),
                             precondition_error_handler{}, "variant in invalid state for visitor");
                return visit_variant_impl<AllowIncomplete, Visitor,
                                          Rest...>::call(std::forward<Visitor>(visitor),
                                                         std::forward<Rest>(rest)...,
                                                         std::forward<Args>(args)..., nullvar);
            }

            template <typename RecursiveDecltype, typename Head, typename... Tail, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<Head, Tail...>,
                                  Variant&& variant, Rest&&... rest, Args&&... args)
                -> common_type_t<decltype(
                                     visit_variant_impl<AllowIncomplete, Visitor, Rest...>::call(
                                         std::forward<Visitor>(visitor),
                                         std::forward<Rest>(rest)..., std::forward<Args>(args)...,
                                         std::forward<Variant>(variant).value(
                                             variant_type<Head>{}))),
                                 decltype(RecursiveDecltype::template call_type<RecursiveDecltype>(
                                     std::forward<Visitor>(visitor), variant_types<Tail...>{},
                                     std::forward<Variant>(variant), std::forward<Rest>(rest)...,
                                     std::forward<Args>(args)...))>
            {
                if (variant.has_value(variant_type<Head>{}))
                    return visit_variant_impl<AllowIncomplete, Visitor,
                                              Rest...>::call(std::forward<Visitor>(visitor),
                                                             std::forward<Rest>(rest)...,
                                                             std::forward<Args>(args)...,
                                                             std::forward<Variant>(variant).value(
                                                                 variant_type<Head>{}));
                else
                    return RecursiveDecltype::
                        template call_type<RecursiveDecltype>(std::forward<Visitor>(visitor),
                                                              variant_types<Tail...>{},
                                                              std::forward<Variant>(variant),
                                                              std::forward<Rest>(rest)...,
                                                              std::forward<Args>(args)...);
            }

        public:
            template <typename... Args>
            static auto call(Visitor&& visitor, Variant&& variant, Rest&&... rest, Args&&... args)
                -> decltype(call_type<visit_variant_impl>(
                    std::forward<Visitor>(visitor), typename std::decay<Variant>::type::types{},
                    std::forward<Variant>(variant), std::forward<Rest>(rest)...,
                    std::forward<Args>(args)...))
            {
                return visit_variant_impl::
                    call_type<visit_variant_impl>(std::forward<Visitor>(visitor),
                                                  typename std::decay<Variant>::type::types{},
                                                  std::forward<Variant>(variant),
                                                  std::forward<Rest>(rest)...,
                                                  std::forward<Args>(args)...);
            }
        };

        template <class Visitor, class... Variants>
        auto visit_variant(Visitor&& visitor, Variants&&... variants) -> decltype(
            visit_variant_impl<visitor_allow_incomplete<Visitor>::value, Visitor&&,
                               Variants&&...>::call(std::forward<Visitor>(visitor),
                                                    std::forward<Variants>(variants)...))
        {
            return visit_variant_impl<visitor_allow_incomplete<Visitor>::value, Visitor&&,
                                      Variants&&...>::call(std::forward<Visitor>(visitor),
                                                           std::forward<Variants>(variants)...);
        }
    } // namespace detail

    /// Visits a [ts::basic_variant]().
    /// \effects Effectively calls `visitor(variants.value(variant_type<Ts>{})...)`,
    /// where `Ts...` are the types of the currently active element in the variant,
    /// i.e. it calls the `operator()` of the `visitor` where the `i`th argument is the currently stored value in the `i`th variant,
    /// perfectly forwarded.
    /// If the `i`th variant is empty and it allows the empty state,
    /// it passes `nullvar` as parameter,
    /// otherwise the behavior is undefined.
    /// If the particular combination of types is not overloaded,
    /// the program is ill-formed,
    /// unelss the `Visitor` provides a member named `incomplete_visitor`,
    /// then `visit()` does not do anything instead of the error.
    /// \returns The result of the chosen `operator()`,
    /// its the type is the common type of all possible combinations.
    /// \module variant
    template <class Visitor, class... Variants,
              typename = typename std::
                  enable_if<detail::all_of<detail::is_variant<Variants>::value...>::value>::type>
    auto visit(Visitor&& visitor, Variants&&... variants)
        -> decltype(detail::visit_variant(std::forward<Visitor>(visitor),
                                          std::forward<Variants>(variants)...))
    {
        return detail::visit_variant(std::forward<Visitor>(visitor),
                                     std::forward<Variants>(variants)...);
    }
} // namespace type_safe

#endif // TYPE_SAFE_VISITOR_HPP_INCLUDED
<commit_msg>Update documentation of visitor.hpp<commit_after>// Copyright (C) 2016 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.

#ifndef TYPE_SAFE_VISITOR_HPP_INCLUDED
#define TYPE_SAFE_VISITOR_HPP_INCLUDED

#include <utility>

#include <type_safe/optional.hpp>
#include <type_safe/variant.hpp>

namespace type_safe
{
    /// \exclude
    namespace detail
    {
        // common type where void is wildcard
        template <typename A, typename B>
        struct common_type
        {
            using type = typename std::common_type<A, B>::type;
        };

        template <typename A>
        struct common_type<A, void>
        {
            using type = typename std::common_type<A>::type;
        };

        template <typename A>
        struct common_type<void, A>
        {
            using type = typename std::common_type<A>::type;
        };

        template <>
        struct common_type<void, void>
        {
            using type = void;
        };

        template <typename A, typename B>
        using common_type_t = typename common_type<A, B>::type;

        //=== visit optional ===//
        template <bool Save, typename Visitor, typename... Optional>
        struct visit_optional;

        template <bool Save, typename Visitor, typename Optional>
        struct visit_optional<Save, Visitor, Optional>
        {
            template <typename... Args>
            static auto call_visitor(int, Visitor&& visitor, Args&&... args)
                -> decltype(std::forward<Visitor>(visitor)(std::forward<Args>(args)...))
            {
                return std::forward<Visitor>(visitor)(std::forward<Args>(args)...);
            }

            template <typename... Args>
            static void call_visitor(short, Visitor&&, Args&&...)
            {
                static_assert(!Save, "call to visitor does not cover all possible combinations");
            }

            template <typename... Args>
            static auto call(Visitor&& visitor, Optional&& opt, Args&&... args) ->
                typename common_type<decltype(call_visitor(0, std::forward<Visitor>(visitor),
                                                           std::forward<Args>(args)..., nullopt)),
                                     decltype(
                                         call_visitor(0, std::forward<Visitor>(visitor),
                                                      std::forward<Args>(args)...,
                                                      std::forward<Optional>(opt).value()))>::type
            {
                return opt.has_value() ? call_visitor(0, std::forward<Visitor>(visitor),
                                                      std::forward<Args>(args)...,
                                                      std::forward<Optional>(opt).value()) :
                                         call_visitor(0, std::forward<Visitor>(visitor),
                                                      std::forward<Args>(args)..., nullopt);
            }
        };

        template <bool Save, typename Visitor, typename Optional, typename... Rest>
        struct visit_optional<Save, Visitor, Optional, Rest...>
        {
            template <typename... Args>
            static auto call(Visitor&& visitor, Optional&& opt, Rest&&... rest, Args&&... args) ->
                typename common_type<decltype(visit_optional<Save, Visitor, Rest...>::call(
                                         std::forward<Visitor>(visitor),
                                         std::forward<Rest>(rest)..., std::forward<Args>(args)...,
                                         std::forward<Optional>(opt).value())),
                                     decltype(visit_optional<Save, Visitor, Rest...>::call(
                                         std::forward<Visitor>(visitor),
                                         std::forward<Rest>(rest)..., std::forward<Args>(args)...,
                                         nullopt))>::type
            {
                return opt.has_value() ?
                           visit_optional<Save, Visitor,
                                          Rest...>::call(std::forward<Visitor>(visitor),
                                                         std::forward<Rest>(rest)...,
                                                         std::forward<Args>(args)...,
                                                         std::forward<Optional>(opt).value()) :
                           visit_optional<Save, Visitor, Rest...>::call(std::forward<Visitor>(
                                                                            visitor),
                                                                        std::forward<Rest>(rest)...,
                                                                        std::forward<Args>(args)...,
                                                                        nullopt);
            }
        };

        template <typename T>
        struct visitor_allow_incomplete
        {
            template <typename U, typename = typename U::incomplete_visitor>
            static std::true_type test(int);

            template <typename U>
            static std::true_type test(int, decltype(U::incomplete_visitor));

            template <typename U>
            static std::false_type test(short);

            static const bool value = decltype(test<typename std::decay<T>::type>(0))::value;
        };

        template <typename Visitor, class... Optionals>
        auto visit_optional_impl(Visitor&& visitor, Optionals&&... optionals)
            -> decltype(detail::visit_optional<!visitor_allow_incomplete<Visitor>::value,
                                               decltype(std::forward<Visitor>(visitor)),
                                               decltype(std::forward<Optionals>(optionals))...>::
                            call(std::forward<Visitor>(visitor),
                                 std::forward<Optionals>(optionals)...))
        {
            return detail::visit_optional<!visitor_allow_incomplete<Visitor>::value,
                                          decltype(std::forward<Visitor>(visitor)),
                                          decltype(std::forward<Optionals>(
                                              optionals))...>::call(std::forward<Visitor>(visitor),
                                                                    std::forward<Optionals>(
                                                                        optionals)...);
        }
    } // namespace detail

    /// Visits a [ts::basic_optional]().
    /// \effects Effectively calls `visitor((optionals.has_value() ? optionals.value() : nullopt)...)`,
    /// i.e. the `operator()` of `visitor` passing it `sizeof...(Optionals)` arguments,
    /// where the `i`th argument is the `value()` of the `i`th optional or `nullopt`, if it has none.
    /// If the particular combination of types is not overloaded,
    /// the program is ill-formed,
    /// unelss the `Visitor` provides a member named `incomplete_visitor`,
    /// then `visit()` does not do anything instead of the error.
    /// \returns The result of the chosen `operator()`,
    /// its the type is the common type of all possible combinations.
    /// \module optional
    /// \exclude return
    /// \param 2
    /// \exclude
    template <
        typename Visitor, class... Optionals,
        typename std::enable_if<detail::all_of<detail::is_optional<Optionals>::value...>::value,
                                int>::type = 0>
    auto visit(Visitor&& visitor, Optionals&&... optionals)
        -> decltype(detail::visit_optional_impl(std::forward<Visitor>(visitor),
                                                std::forward<Optionals>(optionals)...))
    {
        return detail::visit_optional_impl(std::forward<Visitor>(visitor),
                                           std::forward<Optionals>(optionals)...);
    }

    /// \exclude
    namespace detail
    {
        template <bool AllowIncomplete, typename Visitor, class... Variants>
        class visit_variant_impl;

        template <bool AllowIncomplete, typename Visitor>
        class visit_variant_impl<AllowIncomplete, Visitor>
        {
            template <typename... Args>
            static auto call_impl(int, Visitor&& visitor, Args&&... args)
                -> decltype(std::forward<Visitor>(visitor)(std::forward<Args>(args)...))
            {
                return std::forward<Visitor>(visitor)(std::forward<Args>(args)...);
            }

            template <typename... Args>
            static void call_impl(short, Visitor&&, Args&&...)
            {
                static_assert(AllowIncomplete, "visitor does not cover all possible combinations");
            }

        public:
            template <typename... Args>
            static auto call(Visitor&& visitor, Args&&... args)
                -> decltype(call_impl(0, std::forward<Visitor>(visitor),
                                      std::forward<Args>(args)...))
            {
                return call_impl(0, std::forward<Visitor>(visitor), std::forward<Args>(args)...);
            }
        };

        template <bool AllowIncomplete, typename Visitor, class Variant>
        class visit_variant_impl<AllowIncomplete, Visitor, Variant>
        {
            template <typename, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<>, Variant&& variant,
                                  Args&&... args)
                -> decltype(visit_variant_impl<AllowIncomplete, Visitor>::call(
                    std::forward<Visitor>(visitor), std::forward<Args>(args)..., nullvar))
            {
                DEBUG_ASSERT(std::decay<Variant>::type::allow_empty::value && !variant.has_value(),
                             precondition_error_handler{}, "variant in invalid state for visitor");
                return visit_variant_impl<AllowIncomplete, Visitor>::call(std::forward<Visitor>(
                                                                              visitor),
                                                                          std::forward<Args>(
                                                                              args)...,
                                                                          nullvar);
            }

            template <typename RecursiveDecltype, typename Head, typename... Tail, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<Head, Tail...>,
                                  Variant&& variant, Args&&... args)
                -> common_type_t<decltype(visit_variant_impl<AllowIncomplete, Visitor>::call(
                                     std::forward<Visitor>(visitor), std::forward<Args>(args)...,
                                     std::forward<Variant>(variant).value(variant_type<Head>{}))),
                                 decltype(RecursiveDecltype::template call_type<RecursiveDecltype>(
                                     std::forward<Visitor>(visitor), variant_types<Tail...>{},
                                     std::forward<Variant>(variant), std::forward<Args>(args)...))>
            {
                if (variant.has_value(variant_type<Head>{}))
                    return visit_variant_impl<AllowIncomplete,
                                              Visitor>::call(std::forward<Visitor>(visitor),
                                                             std::forward<Args>(args)...,
                                                             std::forward<Variant>(variant).value(
                                                                 variant_type<Head>{}));
                else
                    return RecursiveDecltype::
                        template call_type<RecursiveDecltype>(std::forward<Visitor>(visitor),
                                                              variant_types<Tail...>{},
                                                              std::forward<Variant>(variant),
                                                              std::forward<Args>(args)...);
            }

        public:
            template <typename... Args>
            static auto call(Visitor&& visitor, Variant&& variant, Args&&... args)
                -> decltype(call_type<visit_variant_impl>(
                    std::forward<Visitor>(visitor), typename std::decay<Variant>::type::types{},
                    std::forward<Variant>(variant), std::forward<Args>(args)...))
            {
                return visit_variant_impl::
                    call_type<visit_variant_impl>(std::forward<Visitor>(visitor),
                                                  typename std::decay<Variant>::type::types{},
                                                  std::forward<Variant>(variant),
                                                  std::forward<Args>(args)...);
            }
        };

        template <bool AllowIncomplete, typename Visitor, class Variant, class... Rest>
        class visit_variant_impl<AllowIncomplete, Visitor, Variant, Rest...>
        {
            template <typename, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<>, Variant&& variant,
                                  Rest&&... rest, Args&&... args)
                -> decltype(visit_variant_impl<AllowIncomplete, Visitor, Rest...>::call(
                    std::forward<Visitor>(visitor), std::forward<Rest>(rest)...,
                    std::forward<Args>(args)..., nullvar))
            {
                DEBUG_ASSERT(std::decay<Variant>::type::allow_empty::value && !variant.has_value(),
                             precondition_error_handler{}, "variant in invalid state for visitor");
                return visit_variant_impl<AllowIncomplete, Visitor,
                                          Rest...>::call(std::forward<Visitor>(visitor),
                                                         std::forward<Rest>(rest)...,
                                                         std::forward<Args>(args)..., nullvar);
            }

            template <typename RecursiveDecltype, typename Head, typename... Tail, typename... Args>
            static auto call_type(Visitor&& visitor, variant_types<Head, Tail...>,
                                  Variant&& variant, Rest&&... rest, Args&&... args)
                -> common_type_t<decltype(
                                     visit_variant_impl<AllowIncomplete, Visitor, Rest...>::call(
                                         std::forward<Visitor>(visitor),
                                         std::forward<Rest>(rest)..., std::forward<Args>(args)...,
                                         std::forward<Variant>(variant).value(
                                             variant_type<Head>{}))),
                                 decltype(RecursiveDecltype::template call_type<RecursiveDecltype>(
                                     std::forward<Visitor>(visitor), variant_types<Tail...>{},
                                     std::forward<Variant>(variant), std::forward<Rest>(rest)...,
                                     std::forward<Args>(args)...))>
            {
                if (variant.has_value(variant_type<Head>{}))
                    return visit_variant_impl<AllowIncomplete, Visitor,
                                              Rest...>::call(std::forward<Visitor>(visitor),
                                                             std::forward<Rest>(rest)...,
                                                             std::forward<Args>(args)...,
                                                             std::forward<Variant>(variant).value(
                                                                 variant_type<Head>{}));
                else
                    return RecursiveDecltype::
                        template call_type<RecursiveDecltype>(std::forward<Visitor>(visitor),
                                                              variant_types<Tail...>{},
                                                              std::forward<Variant>(variant),
                                                              std::forward<Rest>(rest)...,
                                                              std::forward<Args>(args)...);
            }

        public:
            template <typename... Args>
            static auto call(Visitor&& visitor, Variant&& variant, Rest&&... rest, Args&&... args)
                -> decltype(call_type<visit_variant_impl>(
                    std::forward<Visitor>(visitor), typename std::decay<Variant>::type::types{},
                    std::forward<Variant>(variant), std::forward<Rest>(rest)...,
                    std::forward<Args>(args)...))
            {
                return visit_variant_impl::
                    call_type<visit_variant_impl>(std::forward<Visitor>(visitor),
                                                  typename std::decay<Variant>::type::types{},
                                                  std::forward<Variant>(variant),
                                                  std::forward<Rest>(rest)...,
                                                  std::forward<Args>(args)...);
            }
        };

        template <class Visitor, class... Variants>
        auto visit_variant(Visitor&& visitor, Variants&&... variants) -> decltype(
            visit_variant_impl<visitor_allow_incomplete<Visitor>::value, Visitor&&,
                               Variants&&...>::call(std::forward<Visitor>(visitor),
                                                    std::forward<Variants>(variants)...))
        {
            return visit_variant_impl<visitor_allow_incomplete<Visitor>::value, Visitor&&,
                                      Variants&&...>::call(std::forward<Visitor>(visitor),
                                                           std::forward<Variants>(variants)...);
        }
    } // namespace detail

    /// Visits a [ts::basic_variant]().
    /// \effects Effectively calls `visitor(variants.value(variant_type<Ts>{})...)`,
    /// where `Ts...` are the types of the currently active element in the variant,
    /// i.e. it calls the `operator()` of the `visitor` where the `i`th argument is the currently stored value in the `i`th variant,
    /// perfectly forwarded.
    /// If the `i`th variant is empty and it allows the empty state,
    /// it passes `nullvar` as parameter,
    /// otherwise the behavior is undefined.
    /// If the particular combination of types is not overloaded,
    /// the program is ill-formed,
    /// unelss the `Visitor` provides a member named `incomplete_visitor`,
    /// then `visit()` does not do anything instead of the error.
    /// \returns The result of the chosen `operator()`,
    /// its the type is the common type of all possible combinations.
    /// \exclude return
    /// \module variant
    template <class Visitor, class... Variants,
              typename = typename std::
                  enable_if<detail::all_of<detail::is_variant<Variants>::value...>::value>::type>
    auto visit(Visitor&& visitor, Variants&&... variants)
        -> decltype(detail::visit_variant(std::forward<Visitor>(visitor),
                                          std::forward<Variants>(variants)...))
    {
        return detail::visit_variant(std::forward<Visitor>(visitor),
                                     std::forward<Variants>(variants)...);
    }
} // namespace type_safe

#endif // TYPE_SAFE_VISITOR_HPP_INCLUDED
<|endoftext|>