<commit_before>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// ============================================================================
// Copyright (c) 2017-2018, by Vitaly Grigoriev, <Vit.link420@gmail.com>.
// This file is part of ProtocolAnalyzer open source project under MIT License.
// ============================================================================

#ifndef PROTOCOL_ANALYZER_HOST_ADDRESS_HPP
#define PROTOCOL_ANALYZER_HOST_ADDRESS_HPP

#include <ostream>  // std::ostream.
#include <cstring>  // memset, memcmp, memcpy.
#include <arpa/inet.h>  // inet_ntop, inet_pton.
#include <netinet/in.h>  // struct in_addr, struct in6_addr.

namespace analyzer::framework::net
{
    class IpAddress
    {
    public:
        in_addr ipv4 = { };
        in6_addr ipv6 = { };
        bool isIPv6 = false;
        bool exist = false;

    public:

        IpAddress(void) noexcept
            : isIPv6(false), exist(false)
        {
            ipv4.s_addr = 0;
            memset(&ipv6.s6_addr, 0, sizeof(in6_addr));
        }

        IpAddress (const uint32_t ip) noexcept
            : isIPv6(false), exist(true)
        {
            ipv4.s_addr = ip;
        }

        IpAddress (const sockaddr_in& ip) noexcept
            : ipv4(ip.sin_addr), isIPv6(false), exist(true)
        { }

        IpAddress (const sockaddr_in6& ip) noexcept
            : ipv6(ip.sin6_addr), isIPv6(true), exist(true)
        { }

        IpAddress (const in_addr& ip) noexcept
            : ipv4(ip), isIPv6(false), exist(true)
        { }

        IpAddress (const in6_addr& ip) noexcept
            : ipv6(ip), isIPv6(true), exist(true)
        { }

        IpAddress (IpAddress&& other) noexcept
        {
            if (other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true)
                {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    memset(other.ipv6.s6_addr, 0, sizeof(struct in6_addr));
                    return;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
                memset(&other.ipv4.s_addr, 0, sizeof(struct in_addr));
            }
        }

        IpAddress (const IpAddress& other)
        {
            if (other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true) {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    return;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
            }
        }

        IpAddress& operator= (IpAddress&& other) noexcept
        {
            if (this != &other && other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true)
                {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    memset(other.ipv6.s6_addr, 0, sizeof(struct in6_addr));
                    return *this;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
                memset(&other.ipv4.s_addr, 0, sizeof(struct in_addr));
            }
            return *this;
        }

        IpAddress& operator= (const IpAddress& other)
        {
            if (this != &other && other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true) {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    return *this;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
            }
            return *this;
        }

        inline bool IsExist(void) const noexcept { return exist; }

        inline bool operator< (const IpAddress& other) const noexcept
        {
            if (isIPv6 != other.isIPv6) {
                return !isIPv6;
            }

            if (isIPv6 == true) {
                return (memcmp(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(ipv6)) < 0);
            }
            return (ipv4.s_addr < other.ipv4.s_addr);
        }

        inline bool operator> (const IpAddress& other) const noexcept
        {
            return !(*this < other) && !(*this == other);
        }

        inline bool operator== (const IpAddress & other) const noexcept
        {
            if (isIPv6 != other.isIPv6) {
                return false;
            }

            if (isIPv6 == true) {
                return (memcmp(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(ipv6)) == 0);
            }
            return (ipv4.s_addr == other.ipv4.s_addr);
        }

        friend std::ostream& operator<< (std::ostream& out, const IpAddress& ip) noexcept
        {
            out << ip.ToString();
            return out;
        }

        inline uint16_t GetFamily(void) const noexcept
        {
            if (isIPv6 == true) {
                return AF_INET6;
            }
            return AF_INET;
        }

        struct sockaddr_storage GetSockaddr(void) const noexcept
        {
            if (isIPv6 == true)
            {
                sockaddr_in6 sock = { };
                sock.sin6_family = AF_INET6;
                sock.sin6_addr = ipv6;
                return *reinterpret_cast<sockaddr_storage*>(&sock);
            }

            sockaddr_in sock = { };
            sock.sin_family = AF_INET;
            sock.sin_addr = ipv4;
            return *reinterpret_cast<sockaddr_storage*>(&sock);
        }

        std::string ToString(void) const noexcept
        {
            if (isIPv6 == true)
            {
                char str[INET6_ADDRSTRLEN];
                inet_ntop(AF_INET6, static_cast<const void*>(&ipv6), str, INET6_ADDRSTRLEN);
                return str;
            }
            char str[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, static_cast<const void*>(&ipv4), str, INET_ADDRSTRLEN);
            return str;
        }

        bool AssignFromString (const uint16_t family, const std::string& ip) noexcept
        {
            if (family == AF_INET)
            {
                isIPv6 = false;
                const int32_t ret = inet_pton(AF_INET, ip.c_str(), &ipv4);
                if (ret == 1) { return true; }
            }
            else if (family == AF_INET6)
            {
                isIPv6 = true;
                const int32_t ret = inet_pton(AF_INET6, ip.c_str(), &ipv6);
                if (ret == 1) { return true; }
            }
            return false;
        }

        ~IpAddress(void) = default;
    };

    class MacAddress
    {
    private:
        uint8_t address[6];

    public:

        MacAddress(void) noexcept
        {
            memset(&address, 0, sizeof(address));
        }

        explicit MacAddress (const std::string& addr) noexcept
        {
            if (addr.size() != 6) { return; }
            memcpy(&address, addr.data(), sizeof(address));
        }

        explicit MacAddress (const char addr[6]) noexcept
        {
            memcpy(&address, addr, sizeof(address));
        }

        MacAddress (const MacAddress& other) noexcept
        {
            memcpy(address, other.address, sizeof(address));
        }

        MacAddress (MacAddress&& other) noexcept
        {
            memcpy(address, other.address, sizeof(address));
            memset(other.address, 0, sizeof(other.address));
        }

        MacAddress& operator= (const MacAddress& other) noexcept
        {
            if (this != &other) {
                memcpy(address, other.address, sizeof(address));
            }
            return *this;
        }

        MacAddress& operator= (MacAddress&& other) noexcept
        {
            if (this != &other) {
                memcpy(address, other.address, sizeof(address));
                memset(other.address, 0, sizeof(other.address));
            }
            return *this;
        }

        std::string ToString(void) const noexcept
        {
            char out[18] = { };
            snprintf(out, 18, "%02x:%02x:%02x:%02x:%02x:%02x", address[0], address[1], address[2], address[3], address[4], address[5]);
            return std::string(out);
        }
    };

}

#endif  // PROTOCOL_ANALYZER_HOST_ADDRESS_HPP
<commit_msg>[FRAMEWORK/NETWORK] Add comments to IpAddress and MacAddress classes.<commit_after>// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

// ============================================================================
// Copyright (c) 2017-2018, by Vitaly Grigoriev, <Vit.link420@gmail.com>.
// This file is part of ProtocolAnalyzer open source project under MIT License.
// ============================================================================

#ifndef PROTOCOL_ANALYZER_NETWORK_ADDRESSES_HPP
#define PROTOCOL_ANALYZER_NETWORK_ADDRESSES_HPP

#include <string>  // std::string.
#include <cstdlib>  // std::strtoul.
#include <ostream>  // std::ostream.
#include <cstring>  // memset, memcmp, memcpy, strtok_r.
#include <limits.h>  // ULONG_MAX.
#include <arpa/inet.h>  // inet_ntop, inet_pton.
#include <netinet/in.h>  // struct in_addr, struct in6_addr, struct sockaddr_storage.

namespace analyzer::framework::net
{
    /**
     * @struct IpAddress   NetworkAddresses.hpp   "include/framework/NetworkAddresses.hpp"
     * @brief This structure defined the interface for work with network IPv4 and IPv6 addresses.
     */
    struct IpAddress
    {
    public:
        /**
         * @var in_addr ipv4;
         * @brief Variable which contains IPv4 address.
         */
        in_addr ipv4 = { };
        /**
         * @var in_addr6 ipv6;
         * @brief Variable which contains IPv6 address.
         */
        in6_addr ipv6 = { };
        /**
         * @var bool isIPv6;
         * @brief Boolean value that indicates about the type of stored IP address.
         */
        bool isIPv6 = false;
        /**
         * @var bool exist;
         * @brief Boolean value that indicates about the existence of IP address.
         */
        bool exist = false;

    public:
        IpAddress(void) = default;
        ~IpAddress(void) = default;

        /**
         * @fn explicit IpAddress::IpAddress (const uint32_t) noexcept;
         * @brief Constructor that initializes IPv4 address by 32-bit value.
         * @param [in] ip - IPv4 address.
         */
        explicit IpAddress (const uint32_t ip) noexcept
            : isIPv6(false), exist(true)
        {
            ipv4.s_addr = ip;
        }

        /**
         * @fn explicit IpAddress::IpAddress (const sockaddr_in &) noexcept;
         * @brief Constructor that initializes IPv4 address by 'sockaddr_in' structure.
         * @param [in] ip - IPv4 address in 'sockaddr_in' representation.
         */
        explicit IpAddress (const sockaddr_in& ip) noexcept
            : ipv4(ip.sin_addr), isIPv6(false), exist(true)
        { }

        /**
         * @fn explicit IpAddress::IpAddress (const sockaddr_in6 &) noexcept;
         * @brief Constructor that initializes IPv6 address by 'sockaddr_in6' structure.
         * @param [in] ip - IPv6 address in 'sockaddr_in6' representation.
         */
        explicit IpAddress (const sockaddr_in6& ip) noexcept
            : ipv6(ip.sin6_addr), isIPv6(true), exist(true)
        { }

        /**
         * @fn explicit IpAddress::IpAddress (const in_addr &) noexcept;
         * @brief Constructor that initializes IPv4 address by 'in_addr' structure.
         * @param [in] ip - IPv4 address in 'in_addr' representation.
         */
        explicit IpAddress (const in_addr& ip) noexcept
            : ipv4(ip), isIPv6(false), exist(true)
        { }

        /**
         * @fn explicit IpAddress::IpAddress (const in_addr6 &) noexcept;
         * @brief Constructor that initializes IPv6 address by 'in_addr6' structure.
         * @param [in] ip - IPv6 address in 'in_addr6' representation.
         */
        explicit IpAddress (const in6_addr& ip) noexcept
            : ipv6(ip), isIPv6(true), exist(true)
        { }

        /**
         * @fn IpAddress::IpAddress (const IpAddress &) noexcept;
         * @brief Copy assignment constructor of IpAddress class.
         * @param [in] other - Const lvalue reference of copied IpAddress class.
         */
        IpAddress (const IpAddress& other) noexcept
        {
            if (other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true) {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    return;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
            }
        }

        /**
         * @fn IpAddress::IpAddress (IpAddress &&) noexcept;
         * @brief Move assignment constructor of IpAddress class.
         * @param [in] other - Rvalue reference of moved IpAddress class.
         */
        IpAddress (IpAddress&& other) noexcept
        {
            if (other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true)
                {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    memset(other.ipv6.s6_addr, 0x00, sizeof(struct in6_addr));
                    return;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
                memset(&other.ipv4.s_addr, 0x00, sizeof(struct in_addr));
            }
        }

        /**
         * @fn IpAddress & IpAddress::operator= (const IpAddress &) noexcept;
         * @brief Copy assignment operator of IpAddress class.
         * @param [in] other - Const lvalue reference of copied IpAddress class.
         */
        IpAddress& operator= (const IpAddress& other) noexcept
        {
            if (this != &other && other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true) {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    return *this;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
            }
            return *this;
        }

        /**
         * @fn IpAddress & IpAddress::operator= (IpAddress &&) noexcept;
         * @brief Move assignment operator of IpAddress class.
         * @param [in] other - Rvalue reference of moved IpAddress class.
         */
        IpAddress& operator= (IpAddress&& other) noexcept
        {
            if (this != &other && other.exist == true)
            {
                exist = true;
                isIPv6 = other.isIPv6;
                if (isIPv6 == true)
                {
                    memcpy(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(struct in6_addr));
                    memset(other.ipv6.s6_addr, 0x00, sizeof(struct in6_addr));
                    return *this;
                }
                memcpy(&ipv4.s_addr, &other.ipv4.s_addr, sizeof(struct in_addr));
                memset(&other.ipv4.s_addr, 0x00, sizeof(struct in_addr));
            }
            return *this;
        }

        /**
         * @fn inline bool IpAddress::IsExist() const noexcept;
         * @brief Method that returns the indicator of existence of IP address.
         * @return TRUE - if IP address is exist, oterwise - FALSE.
         */
        inline bool IsExist(void) const noexcept { return exist; }

        /**
         * @fn inline bool IpAddress::operator< (const IpAddress &) const noexcept;
         * @brief Method that return the result of comparison of the two IP addresses.
         * @param [in] other - Const lvalue reference of other IpAddress class.
         * @return TRUE - if stored IP address less then other, otherwise - FALSE.
         */
        inline bool operator< (const IpAddress& other) const noexcept
        {
            if (isIPv6 != other.isIPv6) {
                return !isIPv6;
            }

            if (isIPv6 == true) {
                return (memcmp(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(ipv6)) < 0);
            }
            return (ipv4.s_addr < other.ipv4.s_addr);
        }

        /**
         * @fn inline bool IpAddress::operator> (const IpAddress &) const noexcept;
         * @brief Method that return the result of comparison of the two IP addresses.
         * @param [in] other - Const lvalue reference of other IpAddress class.
         * @return TRUE - if stored IP address more then other, otherwise - FALSE.
         */
        inline bool operator> (const IpAddress& other) const noexcept
        {
            return !(*this < other) && !(*this == other);
        }

        /**
         * @fn inline bool IpAddress::operator== (const IpAddress &) const noexcept;
         * @brief Method that return the result of comparison of the two IP addresses.
         * @param [in] other - Const lvalue reference of other IpAddress class.
         * @return TRUE - if stored IP address is equal with other, otherwise - FALSE.
         */
        inline bool operator== (const IpAddress & other) const noexcept
        {
            if (isIPv6 != other.isIPv6) {
                return false;
            }

            if (isIPv6 == true) {
                return (memcmp(ipv6.s6_addr, other.ipv6.s6_addr, sizeof(ipv6)) == 0);
            }
            return (ipv4.s_addr == other.ipv4.s_addr);
        }

        /**
         * @fn friend std::ostream & operator<< (std::ostream &, const IpAddress &) noexcept;
         * @brief Operator that outputs IP address in string format.
         * @param [in,out] stream - Reference of the output stream engine.
         * @param [in] ip - Const lvalue reference of IpAddress class.
         * @return Lvalue reference of the inputted STL std::ostream class.
         */
        friend std::ostream& operator<< (std::ostream& stream, const IpAddress& ip) noexcept
        {
            stream << ip.ToString();
            return stream;
        }

        /**
         * @fn inline uint16_t IpAddress::GetFamily() const noexcept;
         * @brief Method that returns the network family of stored IP address.
         * @return Network family of stored IP address.
         */
        inline uint16_t GetFamily(void) const noexcept
        {
            return static_cast<uint16_t>((isIPv6 == false) ? AF_INET : AF_INET6);
        }

        /**
         * @fn struct sockaddr_storage IpAddress::GetSockaddr() const noexcept;
         * @brief Method that returns stored IP address in 'sockaddr_storage' representation.
         * @return IP address in 'sockaddr_storage' representation.
         */
        struct sockaddr_storage GetSockaddr(void) const noexcept
        {
            if (isIPv6 == true)
            {
                sockaddr_in6 sock = { };
                sock.sin6_family = AF_INET6;
                sock.sin6_addr = ipv6;
                return *reinterpret_cast<sockaddr_storage*>(&sock);
            }

            sockaddr_in sock = { };
            sock.sin_family = AF_INET;
            sock.sin_addr = ipv4;
            return *reinterpret_cast<sockaddr_storage*>(&sock);
        }

        /**
         * @fn std::string IpAddress::ToString() const noexcept;
         * @brief Method that returns IP address in string format.
         * @return IP address in string format.
         */
        std::string ToString(void) const noexcept
        {
            if (isIPv6 == true)
            {
                char str[INET6_ADDRSTRLEN];
                inet_ntop(AF_INET6, static_cast<const void*>(&ipv6), str, INET6_ADDRSTRLEN);
                return str;
            }
            char str[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, static_cast<const void*>(&ipv4), str, INET_ADDRSTRLEN);
            return str;
        }

        /**
         * @fn bool IpAddress::FromString (const uint16_t, const std::string &) noexcept;
         * @brief Method that assigns IP address from string format.
         * @param [in] family - Network family of inputted IP address.
         * @param [in] ip - Value of the IP address in string representation.
         * @return Boolean value that indicates about the status of the assignment.
         */
        bool FromString (const uint16_t family, const std::string& ip) noexcept
        {
            exist = true;
            if (family == AF_INET) {
                isIPv6 = false;
                return (inet_pton(AF_INET, ip.c_str(), &ipv4) == 1);
            }

            isIPv6 = true;
            return (inet_pton(AF_INET6, ip.c_str(), &ipv6) == 1);
        }
    };

    /**
     * @struct MacAddress   NetworkAddresses.hpp   "include/framework/NetworkAddresses.hpp"
     * @brief This structure defined the interface for work with network MAC address.
     */
    struct MacAddress
    {
    public:
        /**
         * @var uint8_t address[6];
         * @brief Array that stores the bytes of MAC address.
         */
        uint8_t address[6] = { };

    public:
        MacAddress(void) = default;
        ~MacAddress(void) = default;

        /**
         * @fn explicit MacAddress::MacAddress (const char[6]) noexcept;
         * @brief Constructor that initializes MAC address.
         * @param [in] addr - MAC address in byte representation.
         */
        explicit MacAddress (const char addr[6]) noexcept
        {
            memcpy(&address, addr, sizeof(address));
        }

        /**
         * @fn MacAddress::MacAddress (const MacAddress &) noexcept;
         * @brief Copy assignment constructor of MacAddress class.
         * @param [in] other - Const lvalue reference of copied MacAddress class.
         */
        MacAddress (const MacAddress& other) noexcept
        {
            memcpy(address, other.address, sizeof(address));
        }

        /**
         * @fn MacAddress::MacAddress (MacAddress &&) noexcept;
         * @brief Move assignment constructor of MacAddress class.
         * @param [in] other - Rvalue reference of moved MacAddress class.
         */
        MacAddress (MacAddress&& other) noexcept
        {
            memcpy(address, other.address, sizeof(address));
            memset(other.address, 0x00, sizeof(other.address));
        }

        /**
         * @fn MacAddress & MacAddress::operator= (const MacAddress &) noexcept;
         * @brief Copy assignment operator of MacAddress class.
         * @param [in] other - Const lvalue reference of copied MacAddress class.
         */
        MacAddress& operator= (const MacAddress& other) noexcept
        {
            if (this != &other) {
                memcpy(address, other.address, sizeof(address));
            }
            return *this;
        }

        /**
         * @fn MacAddress & MacAddress::operator= (MacAddress &&) noexcept
         * @brief Move assignment operator of MacAddress class.
         * @param [in] other - Rvalue reference of moved MacAddress class.
         */
        MacAddress& operator= (MacAddress&& other) noexcept
        {
            if (this != &other) {
                memcpy(address, other.address, sizeof(address));
                memset(other.address, 0x00, sizeof(other.address));
            }
            return *this;
        }

        /**
         * @fn std::string MacAddress::ToString() const noexcept;
         * @brief Method that returns MAC address in string format.
         * @return MAC address in string format.
         */
        std::string ToString(void) const noexcept
        {
            char out[18] = { };
            snprintf(out, 18, "%02x:%02x:%02x:%02x:%02x:%02x", address[0], address[1], address[2], address[3], address[4], address[5]);
            return std::string(out);
        }

        /**
         * @fn bool MacAddress::FromString (const std::string &) noexcept;
         * @brief Method that assigns MAC address from string format.
         * @param [in] mac - Value of the MAC address in string representation.
         * @return Boolean value that indicates about the status of the assignment.
         */
        bool FromString (const std::string& mac) noexcept
        {
            uint16_t tokenCount = 0;
            char* ctx = nullptr;
            char* token = strtok_r(const_cast<char*>(mac.c_str()), "-:", &ctx);

            while (token != nullptr)
            {
                const uint64_t val = static_cast<uint64_t>(std::strtoul(token, nullptr, 16));
                if (val > 0xFF) { return false; }

                address[tokenCount++] = static_cast<uint8_t>(val);
                token = strtok_r(nullptr, "-:", &ctx);
            }
            return (tokenCount == 6);
        }
    };

}

#endif  // PROTOCOL_ANALYZER_NETWORK_ADDRESSES_HPP
<|endoftext|>


<commit_before>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2014 FURUHASHI Sadayuki and KONDO Takatoshi
//
//    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 MSGPACK_OBJECT_FWD_HPP
#define MSGPACK_OBJECT_FWD_HPP

#include "versioning.hpp"
#include "zone.hpp"
#   include "object_define.h"

#include <typeinfo>

namespace msgpack {

/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond

namespace type {
    enum object_type {
        NIL                 = MSGPACK_OBJECT_NIL,
        BOOLEAN             = MSGPACK_OBJECT_BOOLEAN,
        POSITIVE_INTEGER    = MSGPACK_OBJECT_POSITIVE_INTEGER,
        NEGATIVE_INTEGER    = MSGPACK_OBJECT_NEGATIVE_INTEGER,
        FLOAT               = MSGPACK_OBJECT_FLOAT,
#if defined(MSGPACK_USE_LEGACY_NAME_AS_FLOAT)
        DOUBLE              = MSGPACK_OBJECT_DOUBLE, // obsolete
#endif // MSGPACK_USE_LEGACY_NAME_AS_FLOAT
        STR                 = MSGPACK_OBJECT_STR,
        BIN                 = MSGPACK_OBJECT_BIN,
        ARRAY               = MSGPACK_OBJECT_ARRAY,
        MAP                 = MSGPACK_OBJECT_MAP,
        EXT                 = MSGPACK_OBJECT_EXT
    };
}

struct object;
struct object_kv;

struct object_array {
    uint32_t size;
    msgpack::object* ptr;
};

struct object_map {
    uint32_t size;
    msgpack::object_kv* ptr;
};

struct object_str {
    uint32_t size;
    const char* ptr;
};

struct object_bin {
    uint32_t size;
    const char* ptr;
};

struct object_ext {
    int8_t type() const { return ptr[0]; }
    const char* data() const { return &ptr[1]; }
    uint32_t size;
    const char* ptr;
};

#if !defined(MSGPACK_USE_CPP03)
struct object;

namespace adaptor {
template <typename T, typename Enabler = void>
struct as;
} // namespace adaptor

template <typename T>
struct has_as {
private:
    template <typename U>
    static auto check(U*) ->
        typename std::is_same<
            decltype(msgpack::adaptor::as<U>()(std::declval<msgpack::object>())),
            T>::type;
    template <typename>
    static std::false_type check(...);
public:
    using type = decltype(check<T>(nullptr));
    static constexpr bool value = type::value;
};

#endif // !defined(MSGPACK_USE_CPP03)

struct object {
    union union_type {
        bool boolean;
        uint64_t u64;
        int64_t  i64;
#if defined(MSGPACK_USE_LEGACY_NAME_AS_FLOAT)
        double   dec; // obsolete
#endif // MSGPACK_USE_LEGACY_NAME_AS_FLOAT
        double   f64;
        msgpack::object_array array;
        msgpack::object_map map;
        msgpack::object_str str;
        msgpack::object_bin bin;
        msgpack::object_ext ext;
    };

    msgpack::type::object_type type;
    union_type via;

    bool is_nil() const { return type == msgpack::type::NIL; }

#if defined(MSGPACK_USE_CPP03)

    template <typename T>
    T as() const;

#else  // defined(MSGPACK_USE_CPP03)

    template <typename T>
    typename std::enable_if<msgpack::has_as<T>::value, T>::type as() const;

    template <typename T>
    typename std::enable_if<!msgpack::has_as<T>::value, T>::type as() const;

#endif // defined(MSGPACK_USE_CPP03)

    template <typename T>
    T& convert(T& v) const;
    template <typename T>
    T* convert(T* v) const;

    template <typename T>
    bool convert_if_not_nil(T& v) const;

    object();

    object(const msgpack_object& o);

    template <typename T>
    explicit object(const T& v);

    template <typename T>
    object(const T& v, msgpack::zone& z);

    // obsolete
    template <typename T>
    object(const T& v, msgpack::zone* z);

    template <typename T>
    object& operator=(const T& v);

    operator msgpack_object() const;

    struct with_zone;

private:
    struct implicit_type;

public:
    implicit_type convert() const;
};

class type_error : public std::bad_cast { };

struct object_kv {
    msgpack::object key;
    msgpack::object val;
};

struct object::with_zone : object {
    with_zone(msgpack::zone& zone) : zone(zone) { }
    msgpack::zone& zone;
private:
    with_zone();
};

/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond

} // namespace msgpack

#endif // MSGPACK_OBJECT_FWD_HPP
<commit_msg>msgpack::object_array and map have m_alloc as parameter<commit_after>//
// MessagePack for C++ static resolution routine
//
// Copyright (C) 2008-2014 FURUHASHI Sadayuki and KONDO Takatoshi
//
//    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 MSGPACK_OBJECT_FWD_HPP
#define MSGPACK_OBJECT_FWD_HPP

#include "versioning.hpp"
#include "zone.hpp"
#   include "object_define.h"

#include <typeinfo>

namespace msgpack {

/// @cond
MSGPACK_API_VERSION_NAMESPACE(v1) {
/// @endcond

namespace type {
    enum object_type {
        NIL                 = MSGPACK_OBJECT_NIL,
        BOOLEAN             = MSGPACK_OBJECT_BOOLEAN,
        POSITIVE_INTEGER    = MSGPACK_OBJECT_POSITIVE_INTEGER,
        NEGATIVE_INTEGER    = MSGPACK_OBJECT_NEGATIVE_INTEGER,
        FLOAT               = MSGPACK_OBJECT_FLOAT,
#if defined(MSGPACK_USE_LEGACY_NAME_AS_FLOAT)
        DOUBLE              = MSGPACK_OBJECT_DOUBLE, // obsolete
#endif // MSGPACK_USE_LEGACY_NAME_AS_FLOAT
        STR                 = MSGPACK_OBJECT_STR,
        BIN                 = MSGPACK_OBJECT_BIN,
        ARRAY               = MSGPACK_OBJECT_ARRAY,
        MAP                 = MSGPACK_OBJECT_MAP,
        EXT                 = MSGPACK_OBJECT_EXT
    };
}

struct object;
struct object_kv;

struct object_array {
    uint32_t size;
    uint32_t m_alloc;
    msgpack::object* ptr;
};

struct object_map {
    uint32_t size;
    uint32_t m_alloc;
    msgpack::object_kv* ptr;
};

struct object_str {
    uint32_t size;
    const char* ptr;
};

struct object_bin {
    uint32_t size;
    const char* ptr;
};

struct object_ext {
    int8_t type() const { return ptr[0]; }
    const char* data() const { return &ptr[1]; }
    uint32_t size;
    const char* ptr;
};

#if !defined(MSGPACK_USE_CPP03)
struct object;

namespace adaptor {
template <typename T, typename Enabler = void>
struct as;
} // namespace adaptor

template <typename T>
struct has_as {
private:
    template <typename U>
    static auto check(U*) ->
        typename std::is_same<
            decltype(msgpack::adaptor::as<U>()(std::declval<msgpack::object>())),
            T>::type;
    template <typename>
    static std::false_type check(...);
public:
    using type = decltype(check<T>(nullptr));
    static constexpr bool value = type::value;
};

#endif // !defined(MSGPACK_USE_CPP03)

struct object {
    union union_type {
        bool boolean;
        uint64_t u64;
        int64_t  i64;
#if defined(MSGPACK_USE_LEGACY_NAME_AS_FLOAT)
        double   dec; // obsolete
#endif // MSGPACK_USE_LEGACY_NAME_AS_FLOAT
        double   f64;
        msgpack::object_array array;
        msgpack::object_map map;
        msgpack::object_str str;
        msgpack::object_bin bin;
        msgpack::object_ext ext;
    };

    msgpack::type::object_type type;
    union_type via;

    bool is_nil() const { return type == msgpack::type::NIL; }

#if defined(MSGPACK_USE_CPP03)

    template <typename T>
    T as() const;

#else  // defined(MSGPACK_USE_CPP03)

    template <typename T>
    typename std::enable_if<msgpack::has_as<T>::value, T>::type as() const;

    template <typename T>
    typename std::enable_if<!msgpack::has_as<T>::value, T>::type as() const;

#endif // defined(MSGPACK_USE_CPP03)

    template <typename T>
    T& convert(T& v) const;
    template <typename T>
    T* convert(T* v) const;

    template <typename T>
    bool convert_if_not_nil(T& v) const;

    object();

    object(const msgpack_object& o);

    template <typename T>
    explicit object(const T& v);

    template <typename T>
    object(const T& v, msgpack::zone& z);

    // obsolete
    template <typename T>
    object(const T& v, msgpack::zone* z);

    template <typename T>
    object& operator=(const T& v);

    operator msgpack_object() const;

    struct with_zone;

private:
    struct implicit_type;

public:
    implicit_type convert() const;
};

class type_error : public std::bad_cast { };

struct object_kv {
    msgpack::object key;
    msgpack::object val;
};

struct object::with_zone : object {
    with_zone(msgpack::zone& zone) : zone(zone) { }
    msgpack::zone& zone;
private:
    with_zone();
};

/// @cond
} // MSGPACK_API_VERSION_NAMESPACE(v1)
/// @endcond

} // namespace msgpack

#endif // MSGPACK_OBJECT_FWD_HPP
<|endoftext|>


<commit_before>//
// Copyright (c) 2020 CNRS
// Author: Joseph Mirabel
//
// This file is part of hpp-pinocchio
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_PINOCCHIO_SERIALIZATION_HH
# define HPP_PINOCCHIO_SERIALIZATION_HH

# include <set>
# include <type_traits>

# include <pinocchio/fwd.hpp>
# include <boost/serialization/split_free.hpp>
# include <boost/serialization/shared_ptr.hpp>
# include <boost/serialization/weak_ptr.hpp>

# include <pinocchio/serialization/eigen.hpp>
# include <hpp/util/serialization.hh>
# include <hpp/pinocchio/fwd.hh>
# include <hpp/pinocchio/device.hh>
# include <hpp/pinocchio/humanoid-robot.hh>

BOOST_SERIALIZATION_SPLIT_FREE(hpp::pinocchio::DevicePtr_t)
BOOST_SERIALIZATION_SPLIT_FREE(hpp::pinocchio::DeviceWkPtr_t)

namespace boost {
namespace serialization {
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::DevicePtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::Device> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  if (d && har && har->contains(d->name()))
    d = har->template get<hpp::pinocchio::Device>(d->name(), true)->self();
}
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::DeviceWkPtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::Device> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  std::string name (d.lock()->name());
  if (d.lock() && har && har->contains(name))
    d = har->template get<hpp::pinocchio::Device>(name, true)->self();
}
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::HumanoidRobotPtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::HumanoidRobot> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  if (d && har && har->contains(d->name()))
    d = har->template getChildClass<hpp::pinocchio::Device, hpp::pinocchio::HumanoidRobot>(d->name(), true)->self();
}
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::HumanoidRobotWkPtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::HumanoidRobot> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  std::string name (d.lock()->name());
  if (d.lock() && har && har->contains(name))
    d = har->template getChildClass<hpp::pinocchio::Device, hpp::pinocchio::HumanoidRobot>(name, true)->self();
}

template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
inline void serialize(Archive & ar, Eigen::Array<_Scalar,_Rows,_Cols,_Options,_MaxRows,_MaxCols> & m, const unsigned int version)
{
  (void) version;
  Eigen::DenseIndex rows(m.rows()), cols(m.cols());
  ar & BOOST_SERIALIZATION_NVP(rows);
  ar & BOOST_SERIALIZATION_NVP(cols);
  if (!Archive::is_saving::value)
    m.resize(rows,cols);
  if(m.size() > 0)
    ar & make_nvp("data",make_array(m.data(), (size_t)m.size()));
}

} // namespace serialization
} // namespace boost

namespace hpp {
namespace serialization {
namespace remove_duplicate {
template<typename Key, typename Compare = std::less<Key> >
struct ptr_less : Compare {
  inline bool operator() (Key const* t1, Key const* t2) { return Compare::operator() (*t1, *t2); }
};

template<typename Derived>
struct eigen_compare {
  bool operator() (const Eigen::PlainObjectBase<Derived>& a,
                   const Eigen::PlainObjectBase<Derived>& b)
  {
    if (a.size() < b.size()) return true;
    if (a.size() > b.size()) return false;
    for(Eigen::Index i = 0; i < a.size(); ++i) {
      if (a.derived().data()[i] < b.derived().data()[i]) return true;
      if (a.derived().data()[i] > b.derived().data()[i]) return false;
    }
    return false;
  }
};

template<typename Key, typename Compare = std::less<Key> >
struct archive {
  typedef Compare compare_type;
  typedef ptr_less<Key, Compare> ptr_compare_type;
  std::set<Key const*, ptr_compare_type > datas;
  int hitcount;

  archive() : hitcount(0) {}
};

typedef archive<::hpp::pinocchio::vector_t, eigen_compare<::hpp::pinocchio::vector_t> > vector_archive;

template<class Archive, typename Key>
inline void load_or_save_no_remove_duplicate_check (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  (void) version;
  Key* value = &key;
  ar & boost::serialization::make_nvp(name, value);
  if (!Archive::is_saving::value) key = *value;
}

template<class Archive, typename Key>
inline void save_impl (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  (void) version;
  Key const* value = &key;
  ar << boost::serialization::make_nvp(name, value);
}

template<class Archive, typename Key, typename Compare = std::less<Key>>
inline void save_impl (Archive& ar,
    std::set<Key const*, ptr_less<Key,Compare> >& set,
    int& hitcount,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  (void) version;
  if(!Archive::is_saving::value)
    throw std::logic_error("HPP serialization: cannot load into a const element. This should never happen.");
  auto result = set.insert(&key);
  bool inserted = result.second;
  Key const* k = (inserted ? &key : *result.first);
  ar & boost::serialization::make_nvp(name, k);
  if (!inserted) hitcount++;
}

template<class Archive, typename Key, typename Compare = std::less<Key>>
inline void serialize (Archive& ar,
    std::set<Key const*, ptr_less<Key,Compare> >& set,
    int& hitcount,
    const char* name,
    Key& key,
    const unsigned int version)
{
  if (Archive::is_saving::value) {
    save_impl(ar, set, hitcount, name, key, version);
  } else {
    load_or_save_no_remove_duplicate_check(ar, name, key, version);
  }
}

template <bool is_base>
struct serialiaze_impl {
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void run (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  archive<Key, Compare>& rda = dynamic_cast<archive<Key, Compare>&>(ar);
  serialize(ar, rda.datas, rda.hitcount, name, key, version);
}
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void save (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  archive<Key, Compare>& rda = dynamic_cast<archive<Key, Compare>&>(ar);
  save_impl(ar, rda.datas, rda.hitcount, name, key, version);
}
};

template <>
struct serialiaze_impl<false> {
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void run (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  if (dynamic_cast<archive<Key, Compare>*>(&ar) != NULL)
    serialiaze_impl<true>::run<Archive, Key, Compare>(ar, name, key, version);
  else
    load_or_save_no_remove_duplicate_check(ar, name, key, version);
}
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void save (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  if (dynamic_cast<archive<Key, Compare>*>(&ar) != NULL)
    serialiaze_impl<true>::save<Archive, Key, Compare>(ar, name, key, version);
  else
    save_impl(ar, name, key, version);
}
};

template<typename Archive, typename Key, typename Compare = std::less<Key>,
  bool is_base = std::is_base_of<archive<Key, Compare>, Archive>::value >
inline void serialize (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  serialiaze_impl<is_base>::template run<Archive, Key, Compare>(ar, name, key, version);
}

template<typename Archive, typename Key, typename Compare = std::less<Key>,
  bool is_base = std::is_base_of<archive<Key, Compare>, Archive>::value >
inline void save (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  serialiaze_impl<is_base>::template save<Archive, Key, Compare>(ar, name, key, version);
}

template<typename Archive>
inline void serialize_vector (Archive& ar,
    const char* name,
    ::hpp::pinocchio::vector_t& key,
    const unsigned int version)
{
  serialize<Archive, ::hpp::pinocchio::vector_t, vector_archive::compare_type>
    (ar, name, key, version);
}

template<typename Archive>
inline void save_vector (Archive& ar,
    const char* name,
    const ::hpp::pinocchio::vector_t& key,
    const unsigned int version)
{
  save<Archive, ::hpp::pinocchio::vector_t, vector_archive::compare_type>
    (ar, name, key, version);
}

} // namespace remove_duplicate
} // namespace pinocchio
} // namespace hpp

#endif // HPP_PINOCCHIO_SERIALIZATION_HH
<commit_msg>add required consts<commit_after>//
// Copyright (c) 2020 CNRS
// Author: Joseph Mirabel
//
// This file is part of hpp-pinocchio
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_PINOCCHIO_SERIALIZATION_HH
# define HPP_PINOCCHIO_SERIALIZATION_HH

# include <set>
# include <type_traits>

# include <pinocchio/fwd.hpp>
# include <boost/serialization/split_free.hpp>
# include <boost/serialization/shared_ptr.hpp>
# include <boost/serialization/weak_ptr.hpp>

# include <pinocchio/serialization/eigen.hpp>
# include <hpp/util/serialization.hh>
# include <hpp/pinocchio/fwd.hh>
# include <hpp/pinocchio/device.hh>
# include <hpp/pinocchio/humanoid-robot.hh>

BOOST_SERIALIZATION_SPLIT_FREE(hpp::pinocchio::DevicePtr_t)
BOOST_SERIALIZATION_SPLIT_FREE(hpp::pinocchio::DeviceWkPtr_t)

namespace boost {
namespace serialization {
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::DevicePtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::Device> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  if (d && har && har->contains(d->name()))
    d = har->template get<hpp::pinocchio::Device>(d->name(), true)->self();
}
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::DeviceWkPtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::Device> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  std::string name (d.lock()->name());
  if (d.lock() && har && har->contains(name))
    d = har->template get<hpp::pinocchio::Device>(name, true)->self();
}
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::HumanoidRobotPtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::HumanoidRobot> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  if (d && har && har->contains(d->name()))
    d = har->template getChildClass<hpp::pinocchio::Device, hpp::pinocchio::HumanoidRobot>(d->name(), true)->self();
}
template<class Archive>
inline void load (Archive& ar, hpp::pinocchio::HumanoidRobotWkPtr_t& d, const unsigned int version)
{
  load<Archive, hpp::pinocchio::HumanoidRobot> (ar, d, version);
  auto* har = hpp::serialization::cast(&ar);
  std::string name (d.lock()->name());
  if (d.lock() && har && har->contains(name))
    d = har->template getChildClass<hpp::pinocchio::Device, hpp::pinocchio::HumanoidRobot>(name, true)->self();
}

template <class Archive, typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
inline void serialize(Archive & ar, Eigen::Array<_Scalar,_Rows,_Cols,_Options,_MaxRows,_MaxCols> & m, const unsigned int version)
{
  (void) version;
  Eigen::DenseIndex rows(m.rows()), cols(m.cols());
  ar & BOOST_SERIALIZATION_NVP(rows);
  ar & BOOST_SERIALIZATION_NVP(cols);
  if (!Archive::is_saving::value)
    m.resize(rows,cols);
  if(m.size() > 0)
    ar & make_nvp("data",make_array(m.data(), (size_t)m.size()));
}

} // namespace serialization
} // namespace boost

namespace hpp {
namespace serialization {
namespace remove_duplicate {
template<typename Key, typename Compare = std::less<Key> >
struct ptr_less : Compare {
  inline bool operator() (Key const* t1, Key const* t2) const { return Compare::operator() (*t1, *t2); }
};

template<typename Derived>
struct eigen_compare {
  bool operator() (const Eigen::PlainObjectBase<Derived>& a,
                   const Eigen::PlainObjectBase<Derived>& b) const
  {
    if (a.size() < b.size()) return true;
    if (a.size() > b.size()) return false;
    for(Eigen::Index i = 0; i < a.size(); ++i) {
      if (a.derived().data()[i] < b.derived().data()[i]) return true;
      if (a.derived().data()[i] > b.derived().data()[i]) return false;
    }
    return false;
  }
};

template<typename Key, typename Compare = std::less<Key> >
struct archive {
  typedef Compare compare_type;
  typedef ptr_less<Key, Compare> ptr_compare_type;
  std::set<Key const*, ptr_compare_type > datas;
  int hitcount;

  archive() : hitcount(0) {}
};

typedef archive<::hpp::pinocchio::vector_t, eigen_compare<::hpp::pinocchio::vector_t> > vector_archive;

template<class Archive, typename Key>
inline void load_or_save_no_remove_duplicate_check (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  (void) version;
  Key* value = &key;
  ar & boost::serialization::make_nvp(name, value);
  if (!Archive::is_saving::value) key = *value;
}

template<class Archive, typename Key>
inline void save_impl (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  (void) version;
  Key const* value = &key;
  ar << boost::serialization::make_nvp(name, value);
}

template<class Archive, typename Key, typename Compare = std::less<Key>>
inline void save_impl (Archive& ar,
    std::set<Key const*, ptr_less<Key,Compare> >& set,
    int& hitcount,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  (void) version;
  if(!Archive::is_saving::value)
    throw std::logic_error("HPP serialization: cannot load into a const element. This should never happen.");
  auto result = set.insert(&key);
  bool inserted = result.second;
  Key const* k = (inserted ? &key : *result.first);
  ar & boost::serialization::make_nvp(name, k);
  if (!inserted) hitcount++;
}

template<class Archive, typename Key, typename Compare = std::less<Key>>
inline void serialize (Archive& ar,
    std::set<Key const*, ptr_less<Key,Compare> >& set,
    int& hitcount,
    const char* name,
    Key& key,
    const unsigned int version)
{
  if (Archive::is_saving::value) {
    save_impl(ar, set, hitcount, name, key, version);
  } else {
    load_or_save_no_remove_duplicate_check(ar, name, key, version);
  }
}

template <bool is_base>
struct serialiaze_impl {
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void run (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  archive<Key, Compare>& rda = dynamic_cast<archive<Key, Compare>&>(ar);
  serialize(ar, rda.datas, rda.hitcount, name, key, version);
}
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void save (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  archive<Key, Compare>& rda = dynamic_cast<archive<Key, Compare>&>(ar);
  save_impl(ar, rda.datas, rda.hitcount, name, key, version);
}
};

template <>
struct serialiaze_impl<false> {
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void run (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  if (dynamic_cast<archive<Key, Compare>*>(&ar) != NULL)
    serialiaze_impl<true>::run<Archive, Key, Compare>(ar, name, key, version);
  else
    load_or_save_no_remove_duplicate_check(ar, name, key, version);
}
template<typename Archive, typename Key, typename Compare = std::less<Key> >
static inline void save (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  if (dynamic_cast<archive<Key, Compare>*>(&ar) != NULL)
    serialiaze_impl<true>::save<Archive, Key, Compare>(ar, name, key, version);
  else
    save_impl(ar, name, key, version);
}
};

template<typename Archive, typename Key, typename Compare = std::less<Key>,
  bool is_base = std::is_base_of<archive<Key, Compare>, Archive>::value >
inline void serialize (Archive& ar,
    const char* name,
    Key& key,
    const unsigned int version)
{
  serialiaze_impl<is_base>::template run<Archive, Key, Compare>(ar, name, key, version);
}

template<typename Archive, typename Key, typename Compare = std::less<Key>,
  bool is_base = std::is_base_of<archive<Key, Compare>, Archive>::value >
inline void save (Archive& ar,
    const char* name,
    const Key& key,
    const unsigned int version)
{
  serialiaze_impl<is_base>::template save<Archive, Key, Compare>(ar, name, key, version);
}

template<typename Archive>
inline void serialize_vector (Archive& ar,
    const char* name,
    ::hpp::pinocchio::vector_t& key,
    const unsigned int version)
{
  serialize<Archive, ::hpp::pinocchio::vector_t, vector_archive::compare_type>
    (ar, name, key, version);
}

template<typename Archive>
inline void save_vector (Archive& ar,
    const char* name,
    const ::hpp::pinocchio::vector_t& key,
    const unsigned int version)
{
  save<Archive, ::hpp::pinocchio::vector_t, vector_archive::compare_type>
    (ar, name, key, version);
}

} // namespace remove_duplicate
} // namespace pinocchio
} // namespace hpp

#endif // HPP_PINOCCHIO_SERIALIZATION_HH
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \brief Turn off many warnings before including system headers
///        such as Boost headers.  Be sure to reenable warnings
///        afterards using libport/system-warning-pop.hh.

#ifdef _MSC_VER

# pragma warning( push )

# include <libport/warning-push.hh>

// boost/asio/detail/win_thread.hpp:100:
// warning C4365: 'argument' : conversion from 'DWORD' to 'int',
//                             signed/unsigned mismatch

# pragma warning(disable:                       \
                 4365                           \
  )

#endif
<commit_msg>MSVC.<commit_after>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

/// \brief Turn off many warnings before including system headers
///        such as Boost headers.  Be sure to reenable warnings
///        afterards using libport/system-warning-pop.hh.

#ifdef _MSC_VER

# pragma warning( push )

# include <libport/warning-push.hh>

// vcxx8/VC/PlatformSDK/Include/WSPiApi.h:893:
// warning C4191: 'type cast' : unsafe conversion from 'int
// (__stdcall *)(const char *,const char *,const addrinfo *,addrinfo **)'
// to 'FARPROC'
// Calling this function through the result pointer may cause your
// program to fail.

// boost/asio/detail/socket_ops.hpp:1274:
// warning C4242: '=' : conversion from 'int' to 'u_short',
//                possible loss of data

// boost/asio/detail/win_thread.hpp:100:
// warning C4365: 'argument' : conversion from 'DWORD' to 'int',
//                             signed/unsigned mismatch

// vcxx8/VC/include/xhash:657:
// warning C4628: digraphs not supported with -Ze.
// Character sequence '<:' not interpreted as alternate token for '['

// boost/system/error_code.hpp:486:
// warning C4640: 's' : construction of local static object is not thread-safe

// vcxx8/VC/PlatformSDK/Include/BaseTsd.h:363:
// warning C4826: Conversion from 'const void *' to 'void *'
//                is sign-extended. This may cause unexpected runtime behavior.

# pragma warning(disable:                       \
                 4191                           \
                 4242                           \
                 4365                           \
                 4628                           \
                 4640                           \
                 4826                           \
  )

#endif
<|endoftext|>


<commit_before>#pragma once
#include "util.cpp"

//util classes
/*struct Object {
	long long lon, lat;
	bool done;
	int collection_id;
};

struct Satellite {
	long long lon, lat, v, w, d;
	map<long long, Object> photos;
};*/

void compute_satellite_coordinates(pair<ll,ll> &coor, const Satellite &satellite, ll time)	{
	ll lat_max =  90ll*3600ll;
	ll lon_max = 180ll*3600ll;

	ll lat = (satellite.lat + lat_max + time*satellite.v) % (2ll*lat_max+1ll); // from -90 deg to 90 deg inclusive
	ll lon = (satellite.lon + lon_max + time*15ll) % (2ll*lon_max);

	lat -= lat_max;
	lon -= lon_max;

	coor.first = lat_max;
	coor.second = lon_max;
}

void compute_satellite_angles(pair<ll,ll> &angles, const pair<ll,ll> &coor, const Object &object)	{
	angles.first  =  coor.first - object.lat;
	angles.second = coor.second - object.lon;
}

void compute_satellite_angle_change(pair<ll,ll> &angle_change, const pair<ll,ll> &next_angle, const pair<ll,ll> &cur_angle){
	angle_change.first  = next_angle.first  - cur_angle.first;
	angle_change.second = next_angle.second - cur_angle.second;
}

bool check_angles(const pair<ll,ll> &angle_change, ll time, ll angular_speed)	{
	return (abs(angle_change.first) <= time*angular_speed) && (abs(angle_change.second) <= time*angular_speed);
}

//can the satellite take a photo of the given object at the given time with
//regard to the photos the satellite already takes
bool photo_fits_schedule(Input& input, Satellite& satellite, Object& object, ll time) {
	if (satellite.photos.empty())
		return true;

	pair <ll, ll> cur_coor, prev_coor, next_coor;
	pair <ll, ll> cur_angle, prev_angle, next_angle;
	pair <ll, ll> angle_change;

	compute_satellite_coordinates(cur_coor,satellite,time);
	compute_satellite_angles(cur_angle,cur_coor,object);

	map<ll,Object>::iterator ub;
	ub = satellite.photos.upper_bound(time);

	bool fits = true;

	if (ub != satellite.photos.begin())
	{
		ub--;

		compute_satellite_coordinates(prev_coor,satellite,ub->first);
		compute_satellite_angles(prev_angle,prev_coor,ub->second);

		compute_satellite_angle_change(angle_change,cur_angle,prev_angle);

		fits = fits & check_angles(angle_change,time - ub->first,satellite.w);

		ub++;
	}

	if (ub != satellite.photos.end())
	{
		compute_satellite_coordinates(next_coor,satellite,ub->first);
		compute_satellite_angles(next_angle,next_coor,ub->second);

		compute_satellite_angle_change(angle_change,next_angle,cur_angle);

		fits = fits & check_angles(angle_change,ub->first - time,satellite.w);
	}
	return fits;
}
<commit_msg>added checker in photo_fits_schedule.cpp<commit_after>#pragma once
#include "util.cpp"

//util classes
/*struct Object {
	long long lon, lat;
	bool done;
	int collection_id;
};

struct Satellite {
	long long lon, lat, v, w, d;
	map<long long, Object> photos;
};*/

void compute_satellite_coordinates(pair<ll,ll> &coor, const Satellite &satellite, ll time)	{
	ll lat_max =  90ll*3600ll;
	ll lon_max = 180ll*3600ll;

	ll lat = (satellite.lat + lat_max + time*satellite.v) % (2ll*lat_max+1ll); // from -90 deg to 90 deg inclusive
	ll lon = (satellite.lon + lon_max + time*15ll) % (2ll*lon_max);

	lat -= lat_max;
	lon -= lon_max;

	coor.first = lat_max;
	coor.second = lon_max;
}

void compute_satellite_angles(pair<ll,ll> &angles, const pair<ll,ll> &coor, const Object &object)	{
	angles.first  =  coor.first - object.lat;
	angles.second = coor.second - object.lon;
}

void compute_satellite_angle_change(pair<ll,ll> &angle_change, const pair<ll,ll> &next_angle, const pair<ll,ll> &cur_angle){
	angle_change.first  = next_angle.first  - cur_angle.first;
	angle_change.second = next_angle.second - cur_angle.second;
}

bool check_angular_speed(const pair<ll,ll> &angle_change, ll time, ll angular_speed)	{
	return (abs(angle_change.first) <= time*angular_speed) && (abs(angle_change.second) <= time*angular_speed);
}

bool check_angle(const pair<ll,ll> &angle, const ll max_angle)	{
	return (abs(angle.first) <= max_angle) && (abs(angle.second) <= max_angle);
}

//can the satellite take a photo of the given object at the given time with
//regard to the photos the satellite already takes
bool photo_fits_schedule(Input& input, Satellite& satellite, Object& object, ll time) {
	if (satellite.photos.empty())
		return true;

	pair <ll, ll> cur_coor, prev_coor, next_coor;
	pair <ll, ll> cur_angle, prev_angle, next_angle;
	pair <ll, ll> angle_change;

	compute_satellite_coordinates(cur_coor,satellite,time);
	compute_satellite_angles(cur_angle,cur_coor,object);

	map<ll,Object>::iterator ub;
	ub = satellite.photos.upper_bound(time);

	bool fits = check_angle(cur_angle,satellite.d);

	if (ub != satellite.photos.begin())
	{
		ub--;

		compute_satellite_coordinates(prev_coor,satellite,ub->first);
		compute_satellite_angles(prev_angle,prev_coor,ub->second);

		compute_satellite_angle_change(angle_change,cur_angle,prev_angle);

		fits = fits & check_angular_speed(angle_change,time - ub->first,satellite.w);

		ub++;
	}

	if (ub != satellite.photos.end())
	{
		compute_satellite_coordinates(next_coor,satellite,ub->first);
		compute_satellite_angles(next_angle,next_coor,ub->second);

		compute_satellite_angle_change(angle_change,next_angle,cur_angle);

		fits = fits & check_angular_speed(angle_change,ub->first - time,satellite.w);
	}
	return fits;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDED_SC_SOURCE_CORE_OPENCL_OPENCLWRAPPER_HXX
#define INCLUDED_SC_SOURCE_CORE_OPENCL_OPENCLWRAPPER_HXX

#include <config_features.h>
#include <formula/opcode.hxx>
#include <sal/detail/log.h>
#include <osl/file.hxx>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <cassert>
#include "platforminfo.hxx"

#include <rtl/string.hxx>

#include "clcc/clew.h"

#define MaxTextExtent 4096
//support AMD opencl
#define CL_QUEUE_THREAD_HANDLE_AMD 0x403E
#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2)

#define CHECK_OPENCL(status,name)    \
if( status != CL_SUCCESS )    \
{    \
    printf ("OpenCL error code is %d at " SAL_DETAIL_WHERE " when %s .\n", status, name);    \
    return false;    \
}

#define MAX_KERNEL_STRING_LEN 64
#define MAX_CLFILE_NUM 50
#define MAX_CLKERNEL_NUM 200
#define MAX_KERNEL_NAME_LEN 64

#if defined(_MSC_VER)
#ifndef strcasecmp
#define strcasecmp strcmp
#endif
#endif

#include <cstdio>

typedef struct _KernelEnv
{
    cl_context mpkContext;
    cl_command_queue mpkCmdQueue;
    cl_program mpkProgram;
} KernelEnv;

extern "C" {

// user defined, this is function wrapper which is used to set the input
// parameters, launch kernel and copy data from GPU to CPU or CPU to GPU.
typedef int ( *cl_kernel_function )( void **userdata, KernelEnv *kenv );

}

namespace sc { namespace opencl {

typedef unsigned int uint;

struct OpenCLEnv
{
    cl_platform_id mpOclPlatformID;
    cl_context mpOclContext;
    cl_device_id mpOclDevsID;
    cl_command_queue mpOclCmdQueue;
};

struct GPUEnv
{
    //share vb in all modules in hb library
    cl_platform_id mpPlatformID;
    cl_device_type mDevType;
    cl_context mpContext;
    cl_device_id *mpArryDevsID;
    cl_device_id mpDevID;
    cl_command_queue mpCmdQueue;
    cl_program mpArryPrograms[MAX_CLFILE_NUM]; //one program object maps one kernel source file
    int mnIsUserCreated; // 1: created , 0:no create and needed to create by opencl wrapper
    bool mnKhrFp64Flag;
    bool mnAmdFp64Flag;
};

struct SingleVectorFormula
{
    const double *mdpInputLeftData;
    const double *mdpInputRightData;
    size_t mnInputLeftDataSize;
    size_t mnInputRightDataSize;
    uint mnInputLeftStartPosition;
    uint mnInputRightStartPosition;
    int mnInputLeftOffset;
    int mnInputRightOffset;
};

struct DoubleVectorFormula
{
    const double *mdpInputData;
    size_t mnInputDataSize;
    uint mnInputStartPosition;
    uint mnInputEndPosition;
    int mnInputStartOffset;
    int mnInputEndOffset;
};

class OpenCLDevice
{
public:
    static GPUEnv gpuEnv;
    static bool bIsInited;
    static OString maCacheFolder;

    static void registerOpenCLKernel();
    static bool initOpenCLRunEnv( GPUEnv *gpu );
    static void releaseOpenCLEnv( GPUEnv *gpuInfo );
    static bool initOpenCLRunEnv( int argc );
    static bool generatBinFromKernelSource( cl_program program, const char * clFileName );
    static bool writeBinaryToFile( const OString& rName, const char* birary, size_t numBytes );
    static std::vector<boost::shared_ptr<osl::File> > binaryGenerated( const char * clFileName, cl_context context);
    static bool buildProgramFromBinary(const char* buildOption, GPUEnv* gpuEnv, const char* filename, int idx);

    static bool initOpenCLAttr( OpenCLEnv * env );
    static void setKernelEnv( KernelEnv *envInfo );
};

size_t getOpenCLPlatformCount();
const std::vector<OpenCLPlatformInfo>& fillOpenCLInfo();

/**
 * Used to set or switch between OpenCL devices.
 *
 * @param pDeviceId the id of the opencl device of type cl_device_id, NULL means use software calculation
 * @param bAutoSelect use the algorithm to select the best OpenCL device
 *
 * @return returns true if there is a valid opencl device that has been set up
 */
bool switchOpenCLDevice(const OUString* pDeviceId, bool bAutoSelect,
        bool bForceEvaluation);

void getOpenCLDeviceInfo(size_t& rDeviceId, size_t& rPlatformId);

}}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Bin unused macros<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#ifndef INCLUDED_SC_SOURCE_CORE_OPENCL_OPENCLWRAPPER_HXX
#define INCLUDED_SC_SOURCE_CORE_OPENCL_OPENCLWRAPPER_HXX

#include <config_features.h>
#include <formula/opcode.hxx>
#include <sal/detail/log.h>
#include <osl/file.hxx>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <cassert>
#include "platforminfo.hxx"

#include <rtl/string.hxx>

#include "clcc/clew.h"

#define CHECK_OPENCL(status,name)    \
if( status != CL_SUCCESS )    \
{    \
    printf ("OpenCL error code is %d at " SAL_DETAIL_WHERE " when %s .\n", status, name);    \
    return false;    \
}

#define MAX_KERNEL_STRING_LEN 64
#define MAX_CLFILE_NUM 50
#define MAX_CLKERNEL_NUM 200
#define MAX_KERNEL_NAME_LEN 64

#if defined(_MSC_VER)
#ifndef strcasecmp
#define strcasecmp strcmp
#endif
#endif

#include <cstdio>

typedef struct _KernelEnv
{
    cl_context mpkContext;
    cl_command_queue mpkCmdQueue;
    cl_program mpkProgram;
} KernelEnv;

extern "C" {

// user defined, this is function wrapper which is used to set the input
// parameters, launch kernel and copy data from GPU to CPU or CPU to GPU.
typedef int ( *cl_kernel_function )( void **userdata, KernelEnv *kenv );

}

namespace sc { namespace opencl {

typedef unsigned int uint;

struct OpenCLEnv
{
    cl_platform_id mpOclPlatformID;
    cl_context mpOclContext;
    cl_device_id mpOclDevsID;
    cl_command_queue mpOclCmdQueue;
};

struct GPUEnv
{
    //share vb in all modules in hb library
    cl_platform_id mpPlatformID;
    cl_device_type mDevType;
    cl_context mpContext;
    cl_device_id *mpArryDevsID;
    cl_device_id mpDevID;
    cl_command_queue mpCmdQueue;
    cl_program mpArryPrograms[MAX_CLFILE_NUM]; //one program object maps one kernel source file
    int mnIsUserCreated; // 1: created , 0:no create and needed to create by opencl wrapper
    bool mnKhrFp64Flag;
    bool mnAmdFp64Flag;
};

struct SingleVectorFormula
{
    const double *mdpInputLeftData;
    const double *mdpInputRightData;
    size_t mnInputLeftDataSize;
    size_t mnInputRightDataSize;
    uint mnInputLeftStartPosition;
    uint mnInputRightStartPosition;
    int mnInputLeftOffset;
    int mnInputRightOffset;
};

struct DoubleVectorFormula
{
    const double *mdpInputData;
    size_t mnInputDataSize;
    uint mnInputStartPosition;
    uint mnInputEndPosition;
    int mnInputStartOffset;
    int mnInputEndOffset;
};

class OpenCLDevice
{
public:
    static GPUEnv gpuEnv;
    static bool bIsInited;
    static OString maCacheFolder;

    static void registerOpenCLKernel();
    static bool initOpenCLRunEnv( GPUEnv *gpu );
    static void releaseOpenCLEnv( GPUEnv *gpuInfo );
    static bool initOpenCLRunEnv( int argc );
    static bool generatBinFromKernelSource( cl_program program, const char * clFileName );
    static bool writeBinaryToFile( const OString& rName, const char* birary, size_t numBytes );
    static std::vector<boost::shared_ptr<osl::File> > binaryGenerated( const char * clFileName, cl_context context);
    static bool buildProgramFromBinary(const char* buildOption, GPUEnv* gpuEnv, const char* filename, int idx);

    static bool initOpenCLAttr( OpenCLEnv * env );
    static void setKernelEnv( KernelEnv *envInfo );
};

size_t getOpenCLPlatformCount();
const std::vector<OpenCLPlatformInfo>& fillOpenCLInfo();

/**
 * Used to set or switch between OpenCL devices.
 *
 * @param pDeviceId the id of the opencl device of type cl_device_id, NULL means use software calculation
 * @param bAutoSelect use the algorithm to select the best OpenCL device
 *
 * @return returns true if there is a valid opencl device that has been set up
 */
bool switchOpenCLDevice(const OUString* pDeviceId, bool bAutoSelect,
        bool bForceEvaluation);

void getOpenCLDeviceInfo(size_t& rDeviceId, size_t& rPlatformId);

}}

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#define _SC_ACCESSIBLEDOCUMENT_HXX

#ifndef _SC_ACCESSIBLEDOCUMENTBASE_HXX
#include "AccessibleDocumentBase.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <drafts/com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif

class ScTabViewShell;
class ScAccessibleSpreadsheet;
class ScChildrenShapes;
class ScAccessibleEditObject;

namespace accessibility
{
    class AccessibleShape;
}
namespace utl
{
    class AccessibleRelationSetHelper;
}

/** @descr
        This base class provides an implementation of the
        AccessibleContext service.
*/

typedef cppu::ImplHelper2< ::drafts::com::sun::star::accessibility::XAccessibleSelection,
                            ::com::sun::star::view::XSelectionChangeListener >
                    ScAccessibleDocumentImpl;

class ScAccessibleDocument
    :   public ScAccessibleDocumentBase,
        public ScAccessibleDocumentImpl,
        public accessibility::IAccessibleViewForwarder
{
public:
    //=====  internal  ========================================================
    ScAccessibleDocument(
        const ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible>& rxParent,
        ScTabViewShell* pViewShell,
        ScSplitPos eSplitPos);

    virtual void Init();

    DECL_LINK( WindowChildEventListener, VclSimpleEvent* );
protected:
    virtual ~ScAccessibleDocument(void);
public:

     virtual void SAL_CALL disposing();

   ///=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAt(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    virtual long SAL_CALL
        getAccessibleChildCount(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(long nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::drafts::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleSelection  ===========================================

    virtual void SAL_CALL
        selectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL
        isAccessibleChildSelected( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        clearAccessibleSelection(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        selectAllAccessible(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL
        getSelectedAccessibleChildCount(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL
        getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        deselectSelectedAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    ///=====  XSelectionListener  =============================================

    virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ===================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  IAccessibleViewForwarder  ========================================

    /** This method informs you about the state of the forwarder.  Do not
        use it when the returned value is <false/>.

        @return
            Return <true/> if the view forwarder is valid and <false/> else.
     */
    virtual sal_Bool IsValid (void) const;

    /** Returns the area of the underlying document that is visible in the
    * corresponding window.

        @return
            The rectangle of the visible part of the document. The values
            are, contrary to the base class, in internal coordinates.
     */
    virtual Rectangle GetVisibleArea() const;

    /** Transform the specified point from internal coordinates to an
        absolute screen position.

        @param rPoint
            Point in internal coordinates.

        @return
            The same point but in screen coordinates relative to the upper
            left corner of the (current) screen.
     */
    virtual Point LogicToPixel (const Point& rPoint) const;

    /** Transform the specified size from internal coordinates to a screen
    * oriented pixel size.

        @param rSize
            Size in internal coordinates.

        @return
            The same size but in screen coordinates.
     */
    virtual Size LogicToPixel (const Size& rSize) const;

    /** Transform the specified point from absolute screen coordinates to
        internal coordinates.

        @param rPoint
            Point in screen coordinates relative to the upper left corner of
            the (current) screen.

        @return
            The same point but in internal coordinates.
     */
    virtual Point PixelToLogic (const Point& rPoint) const;

    /** Transform the specified size from screen coordinates to internal
        coordinates.

        @param rSize
            Size in screen coordinates.

        @return
            The same size but in internal coordinates.
     */
    virtual Size PixelToLogic (const Size& rSize) const;

    ///======== internal =====================================================

    utl::AccessibleRelationSetHelper* GetRelationSet(const ScAddress* pAddress) const;

    ::com::sun::star::uno::Reference
        < ::drafts::com::sun::star::accessibility::XAccessible >
        GetAccessibleSpreadsheet();

protected:
    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void) const
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void) const
        throw (::com::sun::star::uno::RuntimeException);

private:
    ScTabViewShell* mpViewShell;
    ScSplitPos      meSplitPos;
    ScAccessibleSpreadsheet* mpAccessibleSpreadsheet;
    ScChildrenShapes* mpChildrenShapes;
    ScAccessibleEditObject* mpTempAccEdit;
    com::sun::star::uno::Reference<drafts::com::sun::star::accessibility::XAccessible> mxTempAcc;
    Rectangle maVisArea;
    sal_Bool mbCompleteSheetSelected;

public:
    sal_uInt16 getVisibleTable() const; // use it in ScChildrenShapes

private:
    void FreeAccessibleSpreadsheet();

    sal_Bool IsTableSelected() const;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsEditable(
        const com::sun::star::uno::Reference<
        ::drafts::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);

    void AddChild(const com::sun::star::uno::Reference<drafts::com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
    void RemoveChild(const com::sun::star::uno::Reference<drafts::com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);

    rtl::OUString GetCurrentCellName() const;
    rtl::OUString GetCurrentCellDescription() const;

    Rectangle GetVisibleArea_Impl() const;
};

#endif
<commit_msg>INTEGRATION: CWS uaa02 (1.21.132); FILE MERGED 2003/04/22 08:14:59 mt 1.21.132.1: #108656# Moved Accessibility from drafts to final<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessibleDocument.hxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 17:14:18 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#define _SC_ACCESSIBLEDOCUMENT_HXX

#ifndef _SC_ACCESSIBLEDOCUMENTBASE_HXX
#include "AccessibleDocumentBase.hxx"
#endif
#ifndef SC_VIEWDATA_HXX
#include "viewdata.hxx"
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESELECTION_HPP_
#include <com/sun/star/accessibility/XAccessibleSelection.hpp>
#endif
#ifndef _COM_SUN_STAR_VIEW_XSELECTIONCHANGELISTENER_HPP_
#include <com/sun/star/view/XSelectionChangeListener.hpp>
#endif

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

#ifndef _SVX_ACCESSIBILITY_IACCESSIBLE_VIEW_FORWARDER_HXX
#include <svx/IAccessibleViewForwarder.hxx>
#endif

class ScTabViewShell;
class ScAccessibleSpreadsheet;
class ScChildrenShapes;
class ScAccessibleEditObject;

namespace accessibility
{
    class AccessibleShape;
}
namespace utl
{
    class AccessibleRelationSetHelper;
}

/** @descr
        This base class provides an implementation of the
        AccessibleContext service.
*/

typedef cppu::ImplHelper2< ::com::sun::star::accessibility::XAccessibleSelection,
                            ::com::sun::star::view::XSelectionChangeListener >
                    ScAccessibleDocumentImpl;

class ScAccessibleDocument
    :   public ScAccessibleDocumentBase,
        public ScAccessibleDocumentImpl,
        public accessibility::IAccessibleViewForwarder
{
public:
    //=====  internal  ========================================================
    ScAccessibleDocument(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible>& rxParent,
        ScTabViewShell* pViewShell,
        ScSplitPos eSplitPos);

    virtual void Init();

    DECL_LINK( WindowChildEventListener, VclSimpleEvent* );
protected:
    virtual ~ScAccessibleDocument(void);
public:

     virtual void SAL_CALL disposing();

   ///=====  SfxListener  =====================================================

    virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    ///=====  XInterface  =====================================================

    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
        ::com::sun::star::uno::Type const & rType )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL acquire() throw ();

    virtual void SAL_CALL release() throw ();

    ///=====  XAccessibleComponent  ============================================

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
        SAL_CALL getAccessibleAtPoint(
        const ::com::sun::star::awt::Point& rPoint )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL grabFocus(  )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleContext  ==============================================

    /// Return the number of currently visible children.
    virtual long SAL_CALL
        getAccessibleChildCount(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the specified child or NULL if index is invalid.
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible> SAL_CALL
        getAccessibleChild(long nIndex)
        throw (::com::sun::star::uno::RuntimeException,
                ::com::sun::star::lang::IndexOutOfBoundsException);

    /// Return the set of current states.
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessibleStateSet> SAL_CALL
        getAccessibleStateSet(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XAccessibleSelection  ===========================================

    virtual void SAL_CALL
        selectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL
        isAccessibleChildSelected( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        clearAccessibleSelection(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        selectAllAccessible(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL
        getSelectedAccessibleChildCount(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible > SAL_CALL
        getSelectedAccessibleChild( sal_Int32 nSelectedChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL
        deselectAccessibleChild( sal_Int32 nChildIndex )
        throw (::com::sun::star::lang::IndexOutOfBoundsException,
        ::com::sun::star::uno::RuntimeException);

    ///=====  XSelectionListener  =============================================

    virtual void SAL_CALL selectionChanged( const ::com::sun::star::lang::EventObject& aEvent )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XServiceInfo  ===================================================

    /** Returns an identifier for the implementation of this object.
    */
    virtual ::rtl::OUString SAL_CALL
        getImplementationName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a list of all supported services.
    */
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL
        getSupportedServiceNames(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  XTypeProvider  ===================================================

    /// returns the possible types
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL
        getTypes()
        throw (::com::sun::star::uno::RuntimeException);

    /** Returns a implementation id.
    */
    virtual ::com::sun::star::uno::Sequence<sal_Int8> SAL_CALL
        getImplementationId(void)
        throw (::com::sun::star::uno::RuntimeException);

    ///=====  IAccessibleViewForwarder  ========================================

    /** This method informs you about the state of the forwarder.  Do not
        use it when the returned value is <false/>.

        @return
            Return <true/> if the view forwarder is valid and <false/> else.
     */
    virtual sal_Bool IsValid (void) const;

    /** Returns the area of the underlying document that is visible in the
    * corresponding window.

        @return
            The rectangle of the visible part of the document. The values
            are, contrary to the base class, in internal coordinates.
     */
    virtual Rectangle GetVisibleArea() const;

    /** Transform the specified point from internal coordinates to an
        absolute screen position.

        @param rPoint
            Point in internal coordinates.

        @return
            The same point but in screen coordinates relative to the upper
            left corner of the (current) screen.
     */
    virtual Point LogicToPixel (const Point& rPoint) const;

    /** Transform the specified size from internal coordinates to a screen
    * oriented pixel size.

        @param rSize
            Size in internal coordinates.

        @return
            The same size but in screen coordinates.
     */
    virtual Size LogicToPixel (const Size& rSize) const;

    /** Transform the specified point from absolute screen coordinates to
        internal coordinates.

        @param rPoint
            Point in screen coordinates relative to the upper left corner of
            the (current) screen.

        @return
            The same point but in internal coordinates.
     */
    virtual Point PixelToLogic (const Point& rPoint) const;

    /** Transform the specified size from screen coordinates to internal
        coordinates.

        @param rSize
            Size in screen coordinates.

        @return
            The same size but in internal coordinates.
     */
    virtual Size PixelToLogic (const Size& rSize) const;

    ///======== internal =====================================================

    utl::AccessibleRelationSetHelper* GetRelationSet(const ScAddress* pAddress) const;

    ::com::sun::star::uno::Reference
        < ::com::sun::star::accessibility::XAccessible >
        GetAccessibleSpreadsheet();

protected:
    /// Return this object's description.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleDescription(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current name.
    virtual ::rtl::OUString SAL_CALL
        createAccessibleName(void)
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the desktop.
    virtual Rectangle GetBoundingBoxOnScreen(void) const
        throw (::com::sun::star::uno::RuntimeException);

    /// Return the object's current bounding box relative to the parent object.
    virtual Rectangle GetBoundingBox(void) const
        throw (::com::sun::star::uno::RuntimeException);

private:
    ScTabViewShell* mpViewShell;
    ScSplitPos      meSplitPos;
    ScAccessibleSpreadsheet* mpAccessibleSpreadsheet;
    ScChildrenShapes* mpChildrenShapes;
    ScAccessibleEditObject* mpTempAccEdit;
    com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible> mxTempAcc;
    Rectangle maVisArea;
    sal_Bool mbCompleteSheetSelected;

public:
    sal_uInt16 getVisibleTable() const; // use it in ScChildrenShapes

private:
    void FreeAccessibleSpreadsheet();

    sal_Bool IsTableSelected() const;

    sal_Bool IsDefunc(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);
    sal_Bool IsEditable(
        const com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessibleStateSet>& rxParentStates);

    void AddChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);
    void RemoveChild(const com::sun::star::uno::Reference<com::sun::star::accessibility::XAccessible>& xAcc, sal_Bool bFireEvent);

    rtl::OUString GetCurrentCellName() const;
    rtl::OUString GetCurrentCellDescription() const;

    Rectangle GetVisibleArea_Impl() const;
};

#endif
<|endoftext|>


<commit_before>//===- Util/TemplateSequence.hpp ------------------------------------ C++ -===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#ifndef SEEC_UTIL_TEMPLATESEQUENCE_HPP
#define SEEC_UTIL_TEMPLATESEQUENCE_HPP

namespace seec {

/// Compile-time utilities.
namespace ct {

/// \brief A compile-time sequence of ints.
template<int ...>
struct sequence_int {};

/// \brief Build a compile-time sequence of ints to cover a range.
/// Builds a sequence [Start, End) by recursively instantiating itself and
/// accumulating in the Sequence parameter pack.
template<int Start, int End, int ...Sequence>
struct generate_sequence_int
: public generate_sequence_int<Start, End - 1, End - 1, Sequence...> {};

/// \brief Build a compile-time sequence of ints to cover a range.
/// Base case of the recursion, create a sequence using all values that have
/// accumulated in the Sequence parameter pack.
template<int StartEnd, int ...Sequence>
struct generate_sequence_int<StartEnd, StartEnd, Sequence...> {
  typedef sequence_int<Sequence...> type;
};

/// Check whether a compile-time sequence of bools are all true.
/// From: http://stackoverflow.com/questions/13562823/parameter-pack-aware-stdis-base-of
template<bool... B> struct static_all_of;

template<bool... Tail>
struct static_all_of<true, Tail...> : static_all_of<Tail...> {};

template<bool... Tail>
struct static_all_of<false, Tail...> : std::false_type {};

template<>
struct static_all_of<> : std::true_type {};

} // namespace ct

} // namespace seec

#endif // SEEC_UTIL_TEMPLATESEQUENCE_HPP
<commit_msg>Add seec::ct::static_any_of, for checking if at least one of a compile time sequence of bools is true.<commit_after>//===- Util/TemplateSequence.hpp ------------------------------------ C++ -===//
//
//                                    SeeC
//
// This file is distributed under The MIT License (MIT). See LICENSE.TXT for
// details.
//
//===----------------------------------------------------------------------===//
///
/// \file
///
//===----------------------------------------------------------------------===//

#ifndef SEEC_UTIL_TEMPLATESEQUENCE_HPP
#define SEEC_UTIL_TEMPLATESEQUENCE_HPP

namespace seec {

/// Compile-time utilities.
namespace ct {

/// \brief A compile-time sequence of ints.
template<int ...>
struct sequence_int {};

/// \brief Build a compile-time sequence of ints to cover a range.
/// Builds a sequence [Start, End) by recursively instantiating itself and
/// accumulating in the Sequence parameter pack.
template<int Start, int End, int ...Sequence>
struct generate_sequence_int
: public generate_sequence_int<Start, End - 1, End - 1, Sequence...> {};

/// \brief Build a compile-time sequence of ints to cover a range.
/// Base case of the recursion, create a sequence using all values that have
/// accumulated in the Sequence parameter pack.
template<int StartEnd, int ...Sequence>
struct generate_sequence_int<StartEnd, StartEnd, Sequence...> {
  typedef sequence_int<Sequence...> type;
};

/// \brief Check whether a compile-time sequence of bools are all true.
/// From: http://stackoverflow.com/questions/13562823/parameter-pack-aware-stdis-base-of
template<bool... B> struct static_all_of;

template<bool... Tail>
struct static_all_of<true, Tail...> : static_all_of<Tail...> {};

template<bool... Tail>
struct static_all_of<false, Tail...> : std::false_type {};

template<>
struct static_all_of<> : std::true_type {};

/// \brief Check whether at least one of a compile time sequence of bools is
///        true.
template<bool... B> struct static_any_of;

template<bool... Tail>
struct static_any_of<true, Tail...> : std::true_type {};

template<bool... Tail>
struct static_any_of<false, Tail...> : static_any_of<Tail...> {};

template<>
struct static_any_of<> : std::false_type {};

} // namespace ct

} // namespace seec

#endif // SEEC_UTIL_TEMPLATESEQUENCE_HPP
<|endoftext|>