<commit_before>/* Copyright 2019 Axel Huebl, Benjamin Worpitz, Erik Zenker, Matthias Werner
 *
 * This file is part of Alpaka.
 *
 * 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/.
 */

#pragma once

#ifdef ALPAKA_ACC_CPU_BT_OMP4_ENABLED

#if _OPENMP < 201307
    #error If ALPAKA_ACC_CPU_BT_OMP4_ENABLED is set, the compiler has to support OpenMP 4.0 or higher!
#endif

#include <alpaka/queue/QueueOmp4Blocking.hpp>

#include <alpaka/dev/DevCpu.hpp>
#include <alpaka/dev/DevOmp4.hpp>
#include <alpaka/dim/DimIntegralConst.hpp>
#include <alpaka/extent/Traits.hpp>
#include <alpaka/mem/view/Traits.hpp>

#include <alpaka/core/Assert.hpp>
#include <alpaka/core/Omp4.hpp>

#include <set>
#include <tuple>

namespace alpaka
{
    namespace mem
    {
        namespace view
        {
            namespace omp4
            {
                namespace detail
                {
                    //#############################################################################
                    //! The Omp4 memory copy trait.
                    template<
                        typename TViewDst,
                        typename TViewSrc,
                        typename TExtent>
                    struct TaskCopyOmp4
                    {
                        static_assert(
                            !std::is_const<TViewDst>::value,
                            "The destination view can not be const!");

                        static_assert(
                            dim::Dim<TViewDst>::value == dim::Dim<TViewSrc>::value,
                            "The source and the destination view are required to have the same dimensionality!");
                        static_assert(
                            dim::Dim<TViewDst>::value == dim::Dim<TExtent>::value,
                            "The views and the extent are required to have the same dimensionality!");
                        // TODO: Maybe check for Idx of TViewDst and TViewSrc to have greater or equal range than TExtent.
                        static_assert(
                            std::is_same<elem::Elem<TViewDst>, typename std::remove_const<elem::Elem<TViewSrc>>::type>::value,
                            "The source and the destination view are required to have the same element type!");

                        using Idx = idx::Idx<TExtent>;

                        //-----------------------------------------------------------------------------
                        ALPAKA_FN_HOST TaskCopyOmp4(
                            TViewDst & viewDst,
                            TViewSrc const & viewSrc,
                            TExtent const & extent,
                            int const & iDstDevice,
                            int const & iSrcDevice) :
                                m_iDstDevice(iDstDevice),
                                m_iSrcDevice(iSrcDevice),
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                                m_extentWidth(extent::getWidth(extent)),
                                m_dstWidth(static_cast<Idx>(extent::getWidth(viewDst))),
                                m_srcWidth(static_cast<Idx>(extent::getWidth(viewSrc))),
#endif
                                m_extentWidthBytes(extent::getWidth(extent) * static_cast<Idx>(sizeof(elem::Elem<TViewDst>))),
                                m_dstMemNative(reinterpret_cast<void *>(mem::view::getPtrNative(viewDst))),
                                m_srcMemNative(reinterpret_cast<void const *>(mem::view::getPtrNative(viewSrc)))
                        {
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                            ALPAKA_ASSERT(m_extentWidth <= m_dstWidth);
                            ALPAKA_ASSERT(m_extentWidth <= m_srcWidth);
#endif
                        }

#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                        //-----------------------------------------------------------------------------
                        ALPAKA_FN_HOST auto printDebug() const
                        -> void
                        {
                            std::cout << __func__
                                << " ddev: " << m_iDstDevice
                                << " ew: " << m_extentWidth
                                << " ewb: " << m_extentWidthBytes
                                << " dw: " << m_dstWidth
                                << " dptr: " << m_dstMemNative
                                << " sdev: " << m_iSrcDevice
                                << " sw: " << m_srcWidth
                                << " sptr: " << m_srcMemNative
                                << std::endl;
                        }
#endif
                        int m_iDstDevice;
                        int m_iSrcDevice;
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                        Idx m_extentWidth;
                        Idx m_dstWidth;
                        Idx m_srcWidth;
#endif
                        Idx m_extentWidthBytes;
                        void * m_dstMemNative;
                        void const * m_srcMemNative;
                    };
                }
            }

            //-----------------------------------------------------------------------------
            // Trait specializations for CreateTaskCopy.
            namespace traits
            {
                namespace omp4
                {
                    namespace detail
                    {
                        //#############################################################################
                        //! The Omp4 memory copy task creation trait detail.
                        template<
                            typename TDim,
                            typename TDevDst,
                            typename TDevSrc>
                        struct CreateTaskCopyImpl
                        {
                            //-----------------------------------------------------------------------------
                            template<
                                typename TExtent,
                                typename TViewSrc,
                                typename TViewDst>
                            ALPAKA_FN_HOST static auto createTaskCopy(
                                TViewDst & viewDst,
                                TViewSrc const & viewSrc,
                                TExtent const & extent,
                                int iDeviceDst = 0,
                                int iDeviceSrc = 0
                                )
                            -> mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>
                            {
                                ALPAKA_DEBUG_FULL_LOG_SCOPE;

                                return
                                    mem::view::omp4::detail::TaskCopyOmp4<
                                        TViewDst,
                                        TViewSrc,
                                        TExtent>(
                                            viewDst,
                                            viewSrc,
                                            extent,
                                            iDeviceDst,
                                            iDeviceSrc);
                            }
                        };
                    }
                }

                //#############################################################################
                //! The CPU to Omp4 memory copy trait specialization.
                template<
                    typename TDim>
                struct CreateTaskCopy<
                    TDim,
                    dev::DevOmp4,
                    dev::DevCpu>
                {
                    //-----------------------------------------------------------------------------
                    template<
                        typename TExtent,
                        typename TViewSrc,
                        typename TViewDst>
                    ALPAKA_FN_HOST static auto createTaskCopy(
                        TViewDst & viewDst,
                        TViewSrc const & viewSrc,
                        TExtent const & extent)
                    -> mem::view::omp4::detail::TaskCopyOmp4<
                        TViewDst,
                        TViewSrc,
                        TExtent>
                    {
                        ALPAKA_DEBUG_FULL_LOG_SCOPE;

                        return
                            mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>(
                                    viewDst,
                                    viewSrc,
                                    extent,
                                    dev::getDev(viewDst).m_iDevice,
                                    0
                                    );
                    }
                };

                //#############################################################################
                //! The Omp4 to CPU memory copy trait specialization.
                template<
                    typename TDim>
                struct CreateTaskCopy<
                    TDim,
                    dev::DevCpu,
                    dev::DevOmp4>
                {
                    //-----------------------------------------------------------------------------
                    template<
                        typename TExtent,
                        typename TViewSrc,
                        typename TViewDst>
                    ALPAKA_FN_HOST static auto createTaskCopy(
                        TViewDst & viewDst,
                        TViewSrc const & viewSrc,
                        TExtent const & extent)
                    -> mem::view::omp4::detail::TaskCopyOmp4<
                        TViewDst,
                        TViewSrc,
                        TExtent>
                    {
                        ALPAKA_DEBUG_FULL_LOG_SCOPE;

                        return
                            mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>(
                                    viewDst,
                                    viewSrc,
                                    extent,
                                    0,
                                    dev::getDev(viewSrc).m_iDevice
                                    );
                    }
                };

                //#############################################################################
                //! The Omp4 to Omp4 memory copy trait specialization.
                template<
                    typename TDim>
                struct CreateTaskCopy<
                    TDim,
                    dev::DevOmp4,
                    dev::DevOmp4>
                {
                    //-----------------------------------------------------------------------------
                    template<
                        typename TExtent,
                        typename TViewSrc,
                        typename TViewDst>
                    ALPAKA_FN_HOST static auto createTaskCopy(
                        TViewDst & viewDst,
                        TViewSrc const & viewSrc,
                        TExtent const & extent)
                    -> mem::view::omp4::detail::TaskCopyOmp4<
                        TViewDst,
                        TViewSrc,
                        TExtent>
                    {
                        ALPAKA_DEBUG_FULL_LOG_SCOPE;

                        return
                            mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>(
                                    viewDst,
                                    viewSrc,
                                    extent,
                                    dev::getDev(viewDst).m_iDevice,
                                    dev::getDev(viewSrc).m_iDevice
                                    );
                    }
                };
            }
        }
    }
    namespace queue
    {
        namespace traits
        {
            //#############################################################################
            //! The Omp4 blocking device queue 1D copy enqueue trait specialization.
            template<
                typename TExtent,
                typename TViewSrc,
                typename TViewDst>
            struct Enqueue<
                queue::QueueOmp4Blocking,
                mem::view::omp4::detail::TaskCopyOmp4<TViewDst, TViewSrc, TExtent>>
            {
                //-----------------------------------------------------------------------------
                ALPAKA_FN_HOST static auto enqueue(
                    queue::QueueOmp4Blocking & queue,
                    mem::view::omp4::detail::TaskCopyOmp4<TViewDst, TViewSrc, TExtent> const & task)
                -> void
                {
                    ALPAKA_DEBUG_FULL_LOG_SCOPE;

#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                    task.printDebug();
#endif
                    if(task.m_extentWidthBytes == 0)
                    {
                        return;
                    }

                    auto const & iDstDev(task.m_iDstDevice);
                    auto const & iSrcDev(task.m_iSrcDevice);

                    auto const & extentWidthBytes(task.m_extentWidthBytes);

                    auto const & dstNativePtr(task.m_dstMemNative);
                    auto const & srcNativePtr(task.m_srcMemNative);

                    alpaka::ignore_unused(queue); //! \TODO

                    ALPAKA_OMP4_CHECK(
                        omp_target_memcpy(
                            dstNativePtr, const_cast<void*>(srcNativePtr), extentWidthBytes, 0,0, iDstDev, iSrcDev));
                }
            };
        }
    }
}

#endif
<commit_msg>buf/omp4/Copy: Fix copy host deviceID<commit_after>/* Copyright 2019 Axel Huebl, Benjamin Worpitz, Erik Zenker, Matthias Werner
 *
 * This file is part of Alpaka.
 *
 * 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/.
 */

#pragma once

#ifdef ALPAKA_ACC_CPU_BT_OMP4_ENABLED

#if _OPENMP < 201307
    #error If ALPAKA_ACC_CPU_BT_OMP4_ENABLED is set, the compiler has to support OpenMP 4.0 or higher!
#endif

#include <alpaka/queue/QueueOmp4Blocking.hpp>

#include <alpaka/dev/DevCpu.hpp>
#include <alpaka/dev/DevOmp4.hpp>
#include <alpaka/dim/DimIntegralConst.hpp>
#include <alpaka/extent/Traits.hpp>
#include <alpaka/mem/view/Traits.hpp>

#include <alpaka/core/Assert.hpp>
#include <alpaka/core/Omp4.hpp>

#include <set>
#include <tuple>

namespace alpaka
{
    namespace mem
    {
        namespace view
        {
            namespace omp4
            {
                namespace detail
                {
                    //#############################################################################
                    //! The Omp4 memory copy trait.
                    template<
                        typename TViewDst,
                        typename TViewSrc,
                        typename TExtent>
                    struct TaskCopyOmp4
                    {
                        static_assert(
                            !std::is_const<TViewDst>::value,
                            "The destination view can not be const!");

                        static_assert(
                            dim::Dim<TViewDst>::value == dim::Dim<TViewSrc>::value,
                            "The source and the destination view are required to have the same dimensionality!");
                        static_assert(
                            dim::Dim<TViewDst>::value == dim::Dim<TExtent>::value,
                            "The views and the extent are required to have the same dimensionality!");
                        // TODO: Maybe check for Idx of TViewDst and TViewSrc to have greater or equal range than TExtent.
                        static_assert(
                            std::is_same<elem::Elem<TViewDst>, typename std::remove_const<elem::Elem<TViewSrc>>::type>::value,
                            "The source and the destination view are required to have the same element type!");

                        using Idx = idx::Idx<TExtent>;

                        //-----------------------------------------------------------------------------
                        ALPAKA_FN_HOST TaskCopyOmp4(
                            TViewDst & viewDst,
                            TViewSrc const & viewSrc,
                            TExtent const & extent,
                            int const & iDstDevice,
                            int const & iSrcDevice) :
                                m_iDstDevice(iDstDevice),
                                m_iSrcDevice(iSrcDevice),
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                                m_extentWidth(extent::getWidth(extent)),
                                m_dstWidth(static_cast<Idx>(extent::getWidth(viewDst))),
                                m_srcWidth(static_cast<Idx>(extent::getWidth(viewSrc))),
#endif
                                m_extentWidthBytes(extent::getWidth(extent) * static_cast<Idx>(sizeof(elem::Elem<TViewDst>))),
                                m_dstMemNative(reinterpret_cast<void *>(mem::view::getPtrNative(viewDst))),
                                m_srcMemNative(reinterpret_cast<void const *>(mem::view::getPtrNative(viewSrc)))
                        {
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                            ALPAKA_ASSERT(m_extentWidth <= m_dstWidth);
                            ALPAKA_ASSERT(m_extentWidth <= m_srcWidth);
#endif
                        }

#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                        //-----------------------------------------------------------------------------
                        ALPAKA_FN_HOST auto printDebug() const
                        -> void
                        {
                            std::cout << __func__
                                << " ddev: " << m_iDstDevice
                                << " ew: " << m_extentWidth
                                << " ewb: " << m_extentWidthBytes
                                << " dw: " << m_dstWidth
                                << " dptr: " << m_dstMemNative
                                << " sdev: " << m_iSrcDevice
                                << " sw: " << m_srcWidth
                                << " sptr: " << m_srcMemNative
                                << std::endl;
                        }
#endif
                        int m_iDstDevice;
                        int m_iSrcDevice;
#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                        Idx m_extentWidth;
                        Idx m_dstWidth;
                        Idx m_srcWidth;
#endif
                        Idx m_extentWidthBytes;
                        void * m_dstMemNative;
                        void const * m_srcMemNative;
                    };
                }
            }

            //-----------------------------------------------------------------------------
            // Trait specializations for CreateTaskCopy.
            namespace traits
            {
                namespace omp4
                {
                    namespace detail
                    {
                        //#############################################################################
                        //! The Omp4 memory copy task creation trait detail.
                        template<
                            typename TDim,
                            typename TDevDst,
                            typename TDevSrc>
                        struct CreateTaskCopyImpl
                        {
                            //-----------------------------------------------------------------------------
                            template<
                                typename TExtent,
                                typename TViewSrc,
                                typename TViewDst>
                            ALPAKA_FN_HOST static auto createTaskCopy(
                                TViewDst & viewDst,
                                TViewSrc const & viewSrc,
                                TExtent const & extent,
                                int iDeviceDst = 0,
                                int iDeviceSrc = 0
                                )
                            -> mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>
                            {
                                ALPAKA_DEBUG_FULL_LOG_SCOPE;

                                return
                                    mem::view::omp4::detail::TaskCopyOmp4<
                                        TViewDst,
                                        TViewSrc,
                                        TExtent>(
                                            viewDst,
                                            viewSrc,
                                            extent,
                                            iDeviceDst,
                                            iDeviceSrc);
                            }
                        };
                    }
                }

                //#############################################################################
                //! The CPU to Omp4 memory copy trait specialization.
                template<
                    typename TDim>
                struct CreateTaskCopy<
                    TDim,
                    dev::DevOmp4,
                    dev::DevCpu>
                {
                    //-----------------------------------------------------------------------------
                    template<
                        typename TExtent,
                        typename TViewSrc,
                        typename TViewDst>
                    ALPAKA_FN_HOST static auto createTaskCopy(
                        TViewDst & viewDst,
                        TViewSrc const & viewSrc,
                        TExtent const & extent)
                    -> mem::view::omp4::detail::TaskCopyOmp4<
                        TViewDst,
                        TViewSrc,
                        TExtent>
                    {
                        ALPAKA_DEBUG_FULL_LOG_SCOPE;

                        return
                            mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>(
                                    viewDst,
                                    viewSrc,
                                    extent,
                                    dev::getDev(viewDst).m_iDevice,
                                    omp_get_initial_device()
                                    );
                    }
                };

                //#############################################################################
                //! The Omp4 to CPU memory copy trait specialization.
                template<
                    typename TDim>
                struct CreateTaskCopy<
                    TDim,
                    dev::DevCpu,
                    dev::DevOmp4>
                {
                    //-----------------------------------------------------------------------------
                    template<
                        typename TExtent,
                        typename TViewSrc,
                        typename TViewDst>
                    ALPAKA_FN_HOST static auto createTaskCopy(
                        TViewDst & viewDst,
                        TViewSrc const & viewSrc,
                        TExtent const & extent)
                    -> mem::view::omp4::detail::TaskCopyOmp4<
                        TViewDst,
                        TViewSrc,
                        TExtent>
                    {
                        ALPAKA_DEBUG_FULL_LOG_SCOPE;

                        return
                            mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>(
                                    viewDst,
                                    viewSrc,
                                    extent,
                                    omp_get_initial_device(),
                                    dev::getDev(viewSrc).m_iDevice
                                    );
                    }
                };

                //#############################################################################
                //! The Omp4 to Omp4 memory copy trait specialization.
                template<
                    typename TDim>
                struct CreateTaskCopy<
                    TDim,
                    dev::DevOmp4,
                    dev::DevOmp4>
                {
                    //-----------------------------------------------------------------------------
                    template<
                        typename TExtent,
                        typename TViewSrc,
                        typename TViewDst>
                    ALPAKA_FN_HOST static auto createTaskCopy(
                        TViewDst & viewDst,
                        TViewSrc const & viewSrc,
                        TExtent const & extent)
                    -> mem::view::omp4::detail::TaskCopyOmp4<
                        TViewDst,
                        TViewSrc,
                        TExtent>
                    {
                        ALPAKA_DEBUG_FULL_LOG_SCOPE;

                        return
                            mem::view::omp4::detail::TaskCopyOmp4<
                                TViewDst,
                                TViewSrc,
                                TExtent>(
                                    viewDst,
                                    viewSrc,
                                    extent,
                                    dev::getDev(viewDst).m_iDevice,
                                    dev::getDev(viewSrc).m_iDevice
                                    );
                    }
                };
            }
        }
    }
    namespace queue
    {
        namespace traits
        {
            //#############################################################################
            //! The Omp4 blocking device queue 1D copy enqueue trait specialization.
            template<
                typename TExtent,
                typename TViewSrc,
                typename TViewDst>
            struct Enqueue<
                queue::QueueOmp4Blocking,
                mem::view::omp4::detail::TaskCopyOmp4<TViewDst, TViewSrc, TExtent>>
            {
                //-----------------------------------------------------------------------------
                ALPAKA_FN_HOST static auto enqueue(
                    queue::QueueOmp4Blocking & queue,
                    mem::view::omp4::detail::TaskCopyOmp4<TViewDst, TViewSrc, TExtent> const & task)
                -> void
                {
                    ALPAKA_DEBUG_FULL_LOG_SCOPE;

#if ALPAKA_DEBUG >= ALPAKA_DEBUG_FULL
                    task.printDebug();
#endif
                    if(task.m_extentWidthBytes == 0)
                    {
                        return;
                    }

                    auto const & iDstDev(task.m_iDstDevice);
                    auto const & iSrcDev(task.m_iSrcDevice);

                    auto const & extentWidthBytes(task.m_extentWidthBytes);

                    auto const & dstNativePtr(task.m_dstMemNative);
                    auto const & srcNativePtr(task.m_srcMemNative);

                    alpaka::ignore_unused(queue); //! \TODO

                    ALPAKA_OMP4_CHECK(
                        omp_target_memcpy(
                            dstNativePtr, const_cast<void*>(srcNativePtr), extentWidthBytes, 0,0, iDstDev, iSrcDev));
                }
            };
        }
    }
}

#endif
<|endoftext|>


<commit_before>#ifndef FILESYSTEM_HPP
#define FILESYSTEM_HPP

#include <iostream>
#include <boost/filesystem.hpp>
#include "arc_utilities/arc_exceptions.hpp"

namespace arc_utilities
{
    inline void CreateDirectory(const boost::filesystem::path& p)
    {
        if (!boost::filesystem::is_directory(p))
        {
            std::cout << "\x1b[33;1m" << p << " does not exist! Creating ... ";

            // NOTE: create_directories should be able to return true in this case
            // however due to a bug related to a trailing '/' this is not currently
            // the case in my version of boost
            // https://svn.boost.org/trac/boost/ticket/7258
            boost::filesystem::create_directories(p);
            if (boost::filesystem::is_directory(p))
    //            if (boost::filesystem::create_directories(p))
            {
                std::cout << "Succeeded!\x1b[37m\n";
            }
            else
            {
                std::cout << "\x1b[31;1mFailed!\x1b[37m\n";
                throw_arc_exception(std::runtime_error, "Unable to create directory, likely a 'trailing slash' issue");
            }
        }
    }
}

#endif // FILESYSTEM_HPP
<commit_msg>Whitespace fix.<commit_after>#ifndef FILESYSTEM_HPP
#define FILESYSTEM_HPP

#include <iostream>
#include <boost/filesystem.hpp>
#include "arc_utilities/arc_exceptions.hpp"

namespace arc_utilities
{
    inline void CreateDirectory(const boost::filesystem::path& p)
    {
        if (!boost::filesystem::is_directory(p))
        {
            std::cout << "\x1b[33;1m" << p << " does not exist! Creating ... ";

            // NOTE: create_directories should be able to return true in this case
            // however due to a bug related to a trailing '/' this is not currently
            // the case in my version of boost
            // https://svn.boost.org/trac/boost/ticket/7258
            boost::filesystem::create_directories(p);
            if (boost::filesystem::is_directory(p))
//            if (boost::filesystem::create_directories(p))
            {
                std::cout << "Succeeded!\x1b[37m\n";
            }
            else
            {
                std::cout << "\x1b[31;1mFailed!\x1b[37m\n";
                throw_arc_exception(std::runtime_error, "Unable to create directory, likely a 'trailing slash' issue");
            }
        }
    }
}

#endif // FILESYSTEM_HPP
<|endoftext|>


<commit_before>#pragma once

#include <memory>
#include <string>
#include <vector>

#include "blackhole/formatter.hpp"

namespace blackhole {
namespace formatter {

// TODO: Add severity mapping support.
// TODO: Add timestamp mapping support.
// TODO: Take a doc from site.
class json_t : public formatter_t {
    class inner_t;
    class properties_t;

    std::unique_ptr<inner_t> inner;

public:
    /// Represents a JSON formatter object builder to ease its configuration.
    class builder_t;

    /// Constructs a defaultly configured JSON formatter, which will produce plain trees with no
    /// filtering without adding a separator character at the end.
    json_t();

    /// Copy constructing is explicitly prohibited.
    json_t(const json_t& other) = delete;

    /// Constructs a JSON formatter using the given other JSON formatter by moving its content.
    json_t(json_t&& other) noexcept;

    /// Destroys the current JSON formatter instance, freeing all its resources.
    ~json_t();

    /// Copy assignment is explicitly prohibited.
    auto operator=(const json_t& other) -> json_t& = delete;

    /// Assigns the given JSON formatter to the current one by moving its content.
    auto operator=(json_t&& other) noexcept -> json_t&;

    /// Formats the given record by constructing a JSON tree with further serializing into the
    /// specified writer.
    auto format(const record_t& record, writer_t& writer) -> void;

private:
    json_t(properties_t properties);
};

/// Represents a JSON formatter object builder to ease its configuration.
///
/// Exists mainly for both avoiding hundreds of formatter constructors and keep its semantics
/// immutable. It's quite convenient to build up different formatter objects just by chaining the
/// different "setters" – no need for default parameters, dealing with constructor bloat etc.
class json_t::builder_t {
    std::unique_ptr<json_t::properties_t> properties;

public:
    builder_t();
    ~builder_t();

    auto route(std::string route) -> builder_t&;
    auto route(std::string route, std::vector<std::string> attributes) -> builder_t&;
    auto rename(std::string from, std::string to) -> builder_t&;
    auto unique() -> builder_t&;
    auto newline() -> builder_t&;

    auto build() const -> json_t;
};

}  // namespace formatter
}  // namespace blackhole
<commit_msg>docs(formatter/json): add a large description<commit_after>#pragma once

#include <memory>
#include <string>
#include <vector>

#include "blackhole/formatter.hpp"

namespace blackhole {
namespace formatter {

/// The JSON formatter is responsible for effective converting the given log record into a
/// structured JSON tree with attributes routing and renaming features.
///
/// Briefly using JSON formatter allows to build fully dynamic JSON trees for its further processing
/// with various external tools, like logstash or rsyslog lefting it, however, in a human-readable
/// state.
///
/// Blackhole allows you to control of JSON tree building process using several predefined options.
///
/// Without options it will produce just a plain tree with zero level depth.
/// For example for a log record with a severity of 3, message "fatal error, please try again" and a
/// pair of attributes `{"key": 42, "ip": "[::]"}` the result string will look like:
/// {
///     "message": "fatal error, please try again",
///     "severity": 3,
///     "timestamp": 1449859055,
///     "process": 12345,
///     "thread": 0x0000dead,
///     "key": 42,
///     "ip": "[::]"
/// }
///
/// Using configuration parameters for this formatter you can:
/// - Rename parameters.
/// - Construct hierarchical tree using a standardized JSON pointer API. For more information please
///   follow \ref https://tools.ietf.org/html/rfc6901.
///
/// Attributes renaming acts so much transparently as it appears: it just renames the given
/// attribute name using the specified alternative.
///
/// Attributes routing specifies a location where the listed attributes will be placed at the tree
/// construction. Also you can specify a default location for all attributes, which is "/" meaning
/// root otherwise.
///
/// For example with routing `{"/fields": ["message", "severity"]}` and "/" as a default pointer the
/// mentioned JSON will look like:
/// {
///     "fields": {
///         "message": "fatal error, please try again",
///         "severity": 3
///     },
///     "timestamp": 1449859055,
///     "process": 12345,
///     "thread": 0x0000dead,
///     "key": 42,
///     "ip": "[::]"
/// }
///
/// Attribute renaming occurs after routing, so mapping "message" => "@message" just replaces the
/// old name with its new alternative.
///
/// To gain maximum speed at the tree construction no filtering occurs, so this formatter by default
/// allows duplicated keys, which means invalid JSON tree (but most of parsers are fine with it).
/// If you are really required to deal with unique keys, you can enable `unique` option, but it
/// involves heap allocation and may slow down formatting.
///
/// Also formatter allows to automatically append a newline character at the end of the tree, which
/// is strangely required by some consumers, like logstash.
///
/// Note, that JSON formatter formats the tree using compact style without excess spaces, tabs etc.
///
/// For convenient formatter construction a special builder class is implemented allowing to create
/// and configure instances of this class using streaming API. For example:
///     auto formatter = json_t::builder_t()
///         .route("/fields", {"message", "severity", "timestamp"})
///         .route("/other")
///         .rename("message", "@message")
///         .rename("timestamp", "@timestamp")
///         .newline()
///         .unique()
///         .build();
///
/// This allow to avoid hundreds of constructors and to make a formatter creation to look eye-candy.
// TODO: Add severity mapping support.
// TODO: Add timestamp mapping support.
class json_t : public formatter_t {
    class inner_t;
    class properties_t;

    std::unique_ptr<inner_t> inner;

public:
    /// Represents a JSON formatter object builder to ease its configuration.
    class builder_t;

    /// Constructs a defaultly configured JSON formatter, which will produce plain trees with no
    /// filtering without adding a separator character at the end.
    json_t();

    /// Copy constructing is explicitly prohibited.
    json_t(const json_t& other) = delete;

    /// Constructs a JSON formatter using the given other JSON formatter by moving its content.
    json_t(json_t&& other) noexcept;

    /// Destroys the current JSON formatter instance, freeing all its resources.
    ~json_t();

    /// Copy assignment is explicitly prohibited.
    auto operator=(const json_t& other) -> json_t& = delete;

    /// Assigns the given JSON formatter to the current one by moving its content.
    auto operator=(json_t&& other) noexcept -> json_t&;

    /// Formats the given record by constructing a JSON tree with further serializing into the
    /// specified writer.
    auto format(const record_t& record, writer_t& writer) -> void;

private:
    json_t(properties_t properties);
};

/// Represents a JSON formatter object builder to ease its configuration.
///
/// Exists mainly for both avoiding hundreds of formatter constructors and keep its semantics
/// immutable. It's quite convenient to build up different formatter objects just by chaining the
/// different "setters" – no need for default parameters, dealing with constructor bloat etc.
class json_t::builder_t {
    std::unique_ptr<json_t::properties_t> properties;

public:
    builder_t();
    ~builder_t();

    auto route(std::string route) -> builder_t&;
    auto route(std::string route, std::vector<std::string> attributes) -> builder_t&;
    auto rename(std::string from, std::string to) -> builder_t&;
    auto unique() -> builder_t&;
    auto newline() -> builder_t&;

    auto build() const -> json_t;
};

}  // namespace formatter
}  // namespace blackhole
<|endoftext|>


<commit_before>#pragma once

#include <brynet/base/Platform.hpp>

#ifdef BRYNET_PLATFORM_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winsock2.h>
#elif defined BRYNET_PLATFORM_LINUX
#include <linux/unistd.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#elif defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#endif

namespace brynet { namespace net { namespace current_thread {

#ifdef BRYNET_PLATFORM_WINDOWS
using THREAD_ID_TYPE = DWORD;
#elif defined BRYNET_PLATFORM_LINUX || defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
#  if defined BRYNET_PLATFORM_FREEBSD
using THREAD_ID_TYPE = pthread_t;
#  else
using THREAD_ID_TYPE = int;
#  endif
#endif

static THREAD_ID_TYPE& tid()
{
#ifdef BRYNET_PLATFORM_WINDOWS
    static __declspec(thread) THREAD_ID_TYPE cachedTid = 0;
#elif defined BRYNET_PLATFORM_LINUX || defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
    static __thread THREAD_ID_TYPE cachedTid = 0;
#endif

    if (cachedTid == 0)
    {
#ifdef BRYNET_PLATFORM_WINDOWS
        cachedTid = GetCurrentThreadId();
#elif defined BRYNET_PLATFORM_LINUX
        cachedTid = static_cast<pid_t>(::syscall(SYS_gettid));
#elif defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
#  if defined BRYNET_PLATFORM_FREEBSD
        cachedTid = pthread_self();
#  else
        // warning: 'syscall' is deprecated:
        // first deprecated in macOS 10.12 - syscall(2) is unsupported;
        // please switch to a supported interface.
        uint64_t tid64;
        pthread_threadid_np(NULL, &tid64);
        cachedTid = (pid_t) tid64;
#  endif
#endif
    }

    return cachedTid;
}

}}}// namespace brynet::net::current_thread
<commit_msg>fix clang-format (#134)<commit_after>#pragma once

#include <brynet/base/Platform.hpp>

#ifdef BRYNET_PLATFORM_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <winsock2.h>
#elif defined BRYNET_PLATFORM_LINUX
#include <linux/unistd.h>
#include <sys/prctl.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#elif defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#endif

namespace brynet { namespace net { namespace current_thread {

#ifdef BRYNET_PLATFORM_WINDOWS
using THREAD_ID_TYPE = DWORD;
#elif defined BRYNET_PLATFORM_LINUX || defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
#if defined BRYNET_PLATFORM_FREEBSD
using THREAD_ID_TYPE = pthread_t;
#else
using THREAD_ID_TYPE = int;
#endif
#endif

static THREAD_ID_TYPE& tid()
{
#ifdef BRYNET_PLATFORM_WINDOWS
    static __declspec(thread) THREAD_ID_TYPE cachedTid = 0;
#elif defined BRYNET_PLATFORM_LINUX || defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
    static __thread THREAD_ID_TYPE cachedTid = 0;
#endif

    if (cachedTid == 0)
    {
#ifdef BRYNET_PLATFORM_WINDOWS
        cachedTid = GetCurrentThreadId();
#elif defined BRYNET_PLATFORM_LINUX
        cachedTid = static_cast<pid_t>(::syscall(SYS_gettid));
#elif defined BRYNET_PLATFORM_DARWIN || defined BRYNET_PLATFORM_FREEBSD
#if defined BRYNET_PLATFORM_FREEBSD
        cachedTid = pthread_self();
#else
        // warning: 'syscall' is deprecated:
        // first deprecated in macOS 10.12 - syscall(2) is unsupported;
        // please switch to a supported interface.
        uint64_t tid64;
        pthread_threadid_np(NULL, &tid64);
        cachedTid = (pid_t) tid64;
#endif
#endif
    }

    return cachedTid;
}

}}}// namespace brynet::net::current_thread
<|endoftext|>


<commit_before>// Copyright (c) 2016, LAAS-CNRS
// Authors: Pierre Fernbach (pierre.fernbach@laas.fr)
//
// This file is part of hpp-core
// hpp-core 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-core 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-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_KINODYNAMIC_PATH_HH
# define HPP_CORE_KINODYNAMIC_PATH_HH

# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
# include <hpp/core/straight-path.hh>
# include <hpp/model/configuration.hh>

namespace hpp {
  namespace core {
    /// Path with 2 segment of constant acceleration or 3 segments with a constant velocity segment
    ///
    /// Degrees of freedom are interpolated depending on the type of
    /// \link hpp::model::Joint joint \endlink
    /// they parameterize:
    ///   \li linear interpolation for translation joints, bounded rotation
    ///       joints, and translation part of freeflyer joints,
    ///   \li angular interpolation for unbounded rotation joints,
    ///   \li constant angular velocity for SO(3) part of freeflyer joints.
    class HPP_CORE_DLLAPI KinodynamicPath : public StraightPath
    {
    public:
      typedef StraightPath parent_t;
      /// Destructor
      virtual ~KinodynamicPath () throw () {}

      /// Create instance and return shared pointer
      /// \param device Robot corresponding to configurations
      /// \param init, end Start and end configurations of the path
      /// \param length Distance between the configurations.
      static KinodynamicPathPtr_t create (const DevicePtr_t& device,
                                          ConfigurationIn_t init,
                                          ConfigurationIn_t end,
                                          value_type length,ConfigurationIn_t a1,ConfigurationIn_t t1,ConfigurationIn_t tv,ConfigurationIn_t t2,ConfigurationIn_t vLim)
      {
        KinodynamicPath* ptr = new KinodynamicPath (device, init, end, length,a1,t1,tv,t2,vLim);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Create instance and return shared pointer
      /// \param device Robot corresponding to configurations
      /// \param init, end Start and end configurations of the path
      /// \param length Distance between the configurations.
      /// \param constraints the path is subject to
      static KinodynamicPathPtr_t create (const DevicePtr_t& device,
                                          ConfigurationIn_t init,
                                          ConfigurationIn_t end,
                                          value_type length,ConfigurationIn_t a1,ConfigurationIn_t t1,ConfigurationIn_t tv,ConfigurationIn_t t2,ConfigurationIn_t vLim,
                                          ConstraintSetPtr_t constraints)
      {
        KinodynamicPath* ptr = new KinodynamicPath (device, init, end, length,a1,t1,tv,t2,vLim,
                                                    constraints);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Create copy and return shared pointer
      /// \param path path to copy
      static KinodynamicPathPtr_t createCopy (const KinodynamicPathPtr_t& path)
      {
        KinodynamicPath* ptr = new KinodynamicPath (*path);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Create copy and return shared pointer
      /// \param path path to copy
      /// \param constraints the path is subject to
      static KinodynamicPathPtr_t createCopy
      (const KinodynamicPathPtr_t& path, const ConstraintSetPtr_t& constraints)
      {
        KinodynamicPath* ptr = new KinodynamicPath (*path, constraints);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Return a shared pointer to this
      ///
      /// As StaightPath are immutable, and refered to by shared pointers,
      /// they do not need to be copied.
      virtual PathPtr_t copy () const
      {
        return createCopy (weak_.lock ());
      }

      /// Return a shared pointer to a copy of this and set constraints
      ///
      /// \param constraints constraints to apply to the copy
      /// \precond *this should not have constraints.
      virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
      {
        return createCopy (weak_.lock (), constraints);
      }

      /// Extraction/Reversion of a sub-path
      /// \param subInterval interval of definition of the extract path
      /// If upper bound of subInterval is smaller than lower bound,
      /// result is reversed.
      virtual PathPtr_t extract (const interval_t& subInterval) const
      throw (projection_error);

    protected:
      /// Print path in a stream
      virtual std::ostream& print (std::ostream &os) const
      {
        os << "KinodynamicPath:" << std::endl;
        os << "interval: [ " << timeRange ().first << ", "
           << timeRange ().second << " ]" << std::endl;
        os << "initial configuration: " << model::displayConfig(initial_ )<< std::endl;
        os << "final configuration:   " << model::displayConfig(end_) << std::endl;
        return os;
      }
      /// Constructor
      KinodynamicPath (const DevicePtr_t& robot, ConfigurationIn_t init,
                       ConfigurationIn_t end, value_type length, ConfigurationIn_t a1, ConfigurationIn_t t1, ConfigurationIn_t tv, ConfigurationIn_t t2, ConfigurationIn_t vLim);

      /// Constructor with constraints
      KinodynamicPath (const DevicePtr_t& robot, ConfigurationIn_t init,
                       ConfigurationIn_t end, value_type length,ConfigurationIn_t a1,ConfigurationIn_t t1,ConfigurationIn_t tv,ConfigurationIn_t t2,ConfigurationIn_t vLim,
                       ConstraintSetPtr_t constraints);

      /// Copy constructor
      KinodynamicPath (const KinodynamicPath& path);

      /// Copy constructor with constraints
      KinodynamicPath (const KinodynamicPath& path,
                       const ConstraintSetPtr_t& constraints);

      void init (KinodynamicPathPtr_t self)
      {
        parent_t::init (self);
        weak_ = self;
        checkPath ();
      }

      virtual bool impl_compute (ConfigurationOut_t result,
                                 value_type t) const;

      inline double sgnenum(double val) const{
        return ((0. < val ) - (val < 0.));
      }

      inline int sgn(double d) const {
        return d >= 0.0 ? 1 : -1;
      }

      inline double sgnf(double d) const {
        return d >= 0.0 ? 1.0 : -1.0;
      }

    private:
      KinodynamicPathWkPtr_t weak_;
      vector_t a1_;
      vector_t t1_,tv_,t2_,vLim_;
    }; // class KinodynamicPath
  } //   namespace core
} // namespace hpp
#endif // HPP_CORE_KINODYNAMIC_PATH_HH
<commit_msg>add accesseur to switch times in kinodynamic-path<commit_after>// Copyright (c) 2016, LAAS-CNRS
// Authors: Pierre Fernbach (pierre.fernbach@laas.fr)
//
// This file is part of hpp-core
// hpp-core 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-core 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-core  If not, see
// <http://www.gnu.org/licenses/>.

#ifndef HPP_CORE_KINODYNAMIC_PATH_HH
# define HPP_CORE_KINODYNAMIC_PATH_HH

# include <hpp/core/fwd.hh>
# include <hpp/core/config.hh>
# include <hpp/core/straight-path.hh>
# include <hpp/model/configuration.hh>

namespace hpp {
  namespace core {
    /// Path with 2 segment of constant acceleration or 3 segments with a constant velocity segment
    ///
    /// Degrees of freedom are interpolated depending on the type of
    /// \link hpp::model::Joint joint \endlink
    /// they parameterize:
    ///   \li linear interpolation for translation joints, bounded rotation
    ///       joints, and translation part of freeflyer joints,
    ///   \li angular interpolation for unbounded rotation joints,
    ///   \li constant angular velocity for SO(3) part of freeflyer joints.
    class HPP_CORE_DLLAPI KinodynamicPath : public StraightPath
    {
    public:
      typedef StraightPath parent_t;
      /// Destructor
      virtual ~KinodynamicPath () throw () {}

      /// Create instance and return shared pointer
      /// \param device Robot corresponding to configurations
      /// \param init, end Start and end configurations of the path
      /// \param length Distance between the configurations.
      static KinodynamicPathPtr_t create (const DevicePtr_t& device,
                                          ConfigurationIn_t init,
                                          ConfigurationIn_t end,
                                          value_type length,ConfigurationIn_t a1,ConfigurationIn_t t1,ConfigurationIn_t tv,ConfigurationIn_t t2,ConfigurationIn_t vLim)
      {
        KinodynamicPath* ptr = new KinodynamicPath (device, init, end, length,a1,t1,tv,t2,vLim);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Create instance and return shared pointer
      /// \param device Robot corresponding to configurations
      /// \param init, end Start and end configurations of the path
      /// \param length Distance between the configurations.
      /// \param constraints the path is subject to
      static KinodynamicPathPtr_t create (const DevicePtr_t& device,
                                          ConfigurationIn_t init,
                                          ConfigurationIn_t end,
                                          value_type length,ConfigurationIn_t a1,ConfigurationIn_t t1,ConfigurationIn_t tv,ConfigurationIn_t t2,ConfigurationIn_t vLim,
                                          ConstraintSetPtr_t constraints)
      {
        KinodynamicPath* ptr = new KinodynamicPath (device, init, end, length,a1,t1,tv,t2,vLim,
                                                    constraints);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Create copy and return shared pointer
      /// \param path path to copy
      static KinodynamicPathPtr_t createCopy (const KinodynamicPathPtr_t& path)
      {
        KinodynamicPath* ptr = new KinodynamicPath (*path);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Create copy and return shared pointer
      /// \param path path to copy
      /// \param constraints the path is subject to
      static KinodynamicPathPtr_t createCopy
      (const KinodynamicPathPtr_t& path, const ConstraintSetPtr_t& constraints)
      {
        KinodynamicPath* ptr = new KinodynamicPath (*path, constraints);
        KinodynamicPathPtr_t shPtr (ptr);
        ptr->init (shPtr);
        ptr->checkPath ();
        return shPtr;
      }

      /// Return a shared pointer to this
      ///
      /// As StaightPath are immutable, and refered to by shared pointers,
      /// they do not need to be copied.
      virtual PathPtr_t copy () const
      {
        return createCopy (weak_.lock ());
      }

      /// Return a shared pointer to a copy of this and set constraints
      ///
      /// \param constraints constraints to apply to the copy
      /// \precond *this should not have constraints.
      virtual PathPtr_t copy (const ConstraintSetPtr_t& constraints) const
      {
        return createCopy (weak_.lock (), constraints);
      }

      /// Extraction/Reversion of a sub-path
      /// \param subInterval interval of definition of the extract path
      /// If upper bound of subInterval is smaller than lower bound,
      /// result is reversed.
      virtual PathPtr_t extract (const interval_t& subInterval) const
      throw (projection_error);

      vector_t getT1(){return t1_;}

      vector_t getT2(){return t2_;}

      vector_t getTv(){return tv_;}

    protected:
      /// Print path in a stream
      virtual std::ostream& print (std::ostream &os) const
      {
        os << "KinodynamicPath:" << std::endl;
        os << "interval: [ " << timeRange ().first << ", "
           << timeRange ().second << " ]" << std::endl;
        os << "initial configuration: " << model::displayConfig(initial_ )<< std::endl;
        os << "final configuration:   " << model::displayConfig(end_) << std::endl;
        return os;
      }
      /// Constructor
      KinodynamicPath (const DevicePtr_t& robot, ConfigurationIn_t init,
                       ConfigurationIn_t end, value_type length, ConfigurationIn_t a1, ConfigurationIn_t t1, ConfigurationIn_t tv, ConfigurationIn_t t2, ConfigurationIn_t vLim);

      /// Constructor with constraints
      KinodynamicPath (const DevicePtr_t& robot, ConfigurationIn_t init,
                       ConfigurationIn_t end, value_type length,ConfigurationIn_t a1,ConfigurationIn_t t1,ConfigurationIn_t tv,ConfigurationIn_t t2,ConfigurationIn_t vLim,
                       ConstraintSetPtr_t constraints);

      /// Copy constructor
      KinodynamicPath (const KinodynamicPath& path);

      /// Copy constructor with constraints
      KinodynamicPath (const KinodynamicPath& path,
                       const ConstraintSetPtr_t& constraints);

      void init (KinodynamicPathPtr_t self)
      {
        parent_t::init (self);
        weak_ = self;
        checkPath ();
      }

      virtual bool impl_compute (ConfigurationOut_t result,
                                 value_type t) const;

      inline double sgnenum(double val) const{
        return ((0. < val ) - (val < 0.));
      }

      inline int sgn(double d) const {
        return d >= 0.0 ? 1 : -1;
      }

      inline double sgnf(double d) const {
        return d >= 0.0 ? 1.0 : -1.0;
      }

    private:
      KinodynamicPathWkPtr_t weak_;
      vector_t a1_;
      vector_t t1_,tv_,t2_,vLim_;
    }; // class KinodynamicPath
  } //   namespace core
} // namespace hpp
#endif // HPP_CORE_KINODYNAMIC_PATH_HH
<|endoftext|>


<commit_before>#ifndef RPTUI_REPORT_WINDOW_HXX
#define RPTUI_REPORT_WINDOW_HXX
/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ReportWindow.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2007-08-02 14:37:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_REPORT_XSECTION_HPP_
#include <com/sun/star/report/XSection.hpp>
#endif
#ifndef RPTUI_REPORT_DEFINES_HXX
#include "ReportDefines.hxx"
#endif
#ifndef RPTUI_STARTMARKER_HXX
#include "StartMarker.hxx"
#endif
#ifndef _RULER_HXX //autogen
#include <svtools/ruler.hxx>
#endif
#ifndef _SVDEDTV_HXX
#include <svx/svdedtv.hxx>
#endif

#include <vector>
#include <boost/shared_ptr.hpp>

#include <MarkedSection.hxx>

class Splitter;

namespace rptui
{
    class ODesignView;
    class OReportSection;
    class OScrollWindowHelper;
    class OSectionView;
    class OReportModel;
    class OEndMarker;
    class OReportPage;
    class DlgEdFunc;
    class OSectionsWindow;
    class OViewsWindow;
    class DlgEdFactory;

    class OReportWindow :    public Window, public IMarkedSection
    {
        Ruler                   m_aHRuler;

        ODesignView*            m_pView;
        OScrollWindowHelper*    m_pParent;
        OSectionsWindow*        m_pSections;
        OViewsWindow*           m_pViews;
        DlgEdFactory*           m_pObjFac;

        void ImplInitSettings();

        sal_Int32 GetTotalHeight() const;

        OReportWindow(OReportWindow&);
        void operator =(OReportWindow&);
    protected:
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
    public:
        OReportWindow(OScrollWindowHelper* _pParent,ODesignView* _pView);
        virtual ~OReportWindow();

        /** late ctor
        */
        void initialize();

        DECL_LINK(Collapsed,OStartMarker*);
        // WINDOW overloads
        virtual void Resize();

        inline ODesignView*         getReportView() const { return m_pView; }
        inline OScrollWindowHelper* getScrollWindow() const { return m_pParent; }

        void            SetMode( DlgEdMode m_eMode );
        void            SetInsertObj( USHORT eObj,const ::rtl::OUString& _sShapeType = ::rtl::OUString());
        rtl::OUString   GetInsertObjString() const;
        void            setGridSnap(BOOL bOn);
        void            setDragStripes(BOOL bOn);
        BOOL            isDragStripes() const;

        /** copies the current selection in this section
        */
        void Copy();

        /** returns if paste is allowed
        *
        * \return <TRUE/> if paste is allowed
        */
        BOOL IsPasteAllowed();

        /** paste a new control in this section
        */
        void Paste();

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll();

        /** returns <TRUE/> when a object is marked
        */
        BOOL HasSelection();

        Point           getScrollOffset() const;

        /** removes the section at the given position.
        *
        * \param _nPosition Zero based.
        */
        void            removeSection(USHORT _nPosition);

        /** adds a new section at position _nPosition.
            If the section is <NULL/> nothing happens.
            If the position is grater than the current elements, the section will be appended.
        */
        void            addSection(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection
                                    ,const ::rtl::OUString& _sColorEntry
                                    ,USHORT _nPosition = USHRT_MAX);

        USHORT          getSectionCount() const;

        /** turns the grid on or off
        *
        * \param _bVisible
        */
        void            toggleGrid(sal_Bool _bVisible);

        /** shows the ruler
        */
        void            showRuler(sal_Bool _bShow);

        inline sal_Int32 getRulerHeight() const { return m_aHRuler.GetSizePixel().Height(); }

        /** returns the total width of the first section
        */
        sal_Int32       GetTotalWidth() const;

        /** calculate the max width of the markers
        *
        * @param _bWithEnd  if <TRUE/> the end marker will be used for calculation as well otherwise not.
        * \return the max width
        */
        sal_Int32       getMaxMarkerWidth(sal_Bool _bWithEnd) const;

        /** returns the height of the first spliiter.
        */
        sal_Int32       getSplitterHeight() const;

        /** sets the total size of the scroll window
        */
        void            setTotalSize();

        /** returns the minimum height of the section
        *
        * \param _nPos
        * \return the height in pixel
        */
        sal_Int32       getMinHeight(USHORT _nPos) const;

        void            ScrollChildren(long nDeltaX, long nDeltaY);

        void            notifyHeightChanged();

        /** unmark all objects on the views without the given one.
        *
        * @param _pSectionView The view where the objects should not be unmarked.
        */
        void            unmarkAllObjects(OSectionView* _pSectionView);

        /** triggers the property browser with the report component or section
            @param  _xReportComponent
        */
        void            showProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xReportComponent);

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool        handleKeyEvent(const KeyEvent& _rEvent);

        /** the the section as marked or not marked
            @param  _pSectionView   the section where to set the marked flag
            @param  _bMark  the marked flag
        */
        void            setMarked(OSectionView* _pSectionView,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> >& _xShape,sal_Bool _bMark);

        // IMarkedSection
        ::boost::shared_ptr<OReportSection> getMarkedSection(NearSectionAccess nsa = CURRENT) const;
        virtual void markSection(const sal_uInt16 _nPos);

        /** fills the positions of all collapsed sections.
        *
        * \param _rCollapsedPositions Out parameter which holds afterwards all positions of the collapsed sections.
        */
        void fillCollapsedSections(::std::vector<sal_uInt16>& _rCollapsedPositions) const;

        /** collpase all sections given by their position
        *
        * \param _aCollpasedSections The position of the sections which should be collapsed.
        */
        void collapseSections(const com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _aCollpasedSections);

        /** align all marked objects in all sections
        *
        * \param eHor
        * \param eVert
        * \param bBoundRects
        */
        void alignMarkedObjects(sal_Int32 _nControlModification, bool _bAlignAtSection, bool bBoundRects = false);

        sal_uInt32 getMarkedObjectCount() const;
    };
//==================================================================
}   //rptui
//==================================================================
#endif // RPTUI_REPORT_WINDOW_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.96); FILE MERGED 2008/04/01 15:23:42 thb 1.3.96.3: #i85898# Stripping all external header guards 2008/04/01 12:33:14 thb 1.3.96.2: #i85898# Stripping all external header guards 2008/03/31 13:32:17 rt 1.3.96.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ReportWindow.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef RPTUI_REPORT_WINDOW_HXX
#define RPTUI_REPORT_WINDOW_HXX

#include <com/sun/star/report/XSection.hpp>
#include "ReportDefines.hxx"
#include "StartMarker.hxx"
#include <svtools/ruler.hxx>
#include <svx/svdedtv.hxx>

#include <vector>
#include <boost/shared_ptr.hpp>

#include <MarkedSection.hxx>

class Splitter;

namespace rptui
{
    class ODesignView;
    class OReportSection;
    class OScrollWindowHelper;
    class OSectionView;
    class OReportModel;
    class OEndMarker;
    class OReportPage;
    class DlgEdFunc;
    class OSectionsWindow;
    class OViewsWindow;
    class DlgEdFactory;

    class OReportWindow :    public Window, public IMarkedSection
    {
        Ruler                   m_aHRuler;

        ODesignView*            m_pView;
        OScrollWindowHelper*    m_pParent;
        OSectionsWindow*        m_pSections;
        OViewsWindow*           m_pViews;
        DlgEdFactory*           m_pObjFac;

        void ImplInitSettings();

        sal_Int32 GetTotalHeight() const;

        OReportWindow(OReportWindow&);
        void operator =(OReportWindow&);
    protected:
        virtual void DataChanged( const DataChangedEvent& rDCEvt );
    public:
        OReportWindow(OScrollWindowHelper* _pParent,ODesignView* _pView);
        virtual ~OReportWindow();

        /** late ctor
        */
        void initialize();

        DECL_LINK(Collapsed,OStartMarker*);
        // WINDOW overloads
        virtual void Resize();

        inline ODesignView*         getReportView() const { return m_pView; }
        inline OScrollWindowHelper* getScrollWindow() const { return m_pParent; }

        void            SetMode( DlgEdMode m_eMode );
        void            SetInsertObj( USHORT eObj,const ::rtl::OUString& _sShapeType = ::rtl::OUString());
        rtl::OUString   GetInsertObjString() const;
        void            setGridSnap(BOOL bOn);
        void            setDragStripes(BOOL bOn);
        BOOL            isDragStripes() const;

        /** copies the current selection in this section
        */
        void Copy();

        /** returns if paste is allowed
        *
        * \return <TRUE/> if paste is allowed
        */
        BOOL IsPasteAllowed();

        /** paste a new control in this section
        */
        void Paste();

        /** Deletes the current selection in this section
        *
        */
        void Delete();

        /** All objects will be marked.
        */
        void SelectAll();

        /** returns <TRUE/> when a object is marked
        */
        BOOL HasSelection();

        Point           getScrollOffset() const;

        /** removes the section at the given position.
        *
        * \param _nPosition Zero based.
        */
        void            removeSection(USHORT _nPosition);

        /** adds a new section at position _nPosition.
            If the section is <NULL/> nothing happens.
            If the position is grater than the current elements, the section will be appended.
        */
        void            addSection(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection >& _xSection
                                    ,const ::rtl::OUString& _sColorEntry
                                    ,USHORT _nPosition = USHRT_MAX);

        USHORT          getSectionCount() const;

        /** turns the grid on or off
        *
        * \param _bVisible
        */
        void            toggleGrid(sal_Bool _bVisible);

        /** shows the ruler
        */
        void            showRuler(sal_Bool _bShow);

        inline sal_Int32 getRulerHeight() const { return m_aHRuler.GetSizePixel().Height(); }

        /** returns the total width of the first section
        */
        sal_Int32       GetTotalWidth() const;

        /** calculate the max width of the markers
        *
        * @param _bWithEnd  if <TRUE/> the end marker will be used for calculation as well otherwise not.
        * \return the max width
        */
        sal_Int32       getMaxMarkerWidth(sal_Bool _bWithEnd) const;

        /** returns the height of the first spliiter.
        */
        sal_Int32       getSplitterHeight() const;

        /** sets the total size of the scroll window
        */
        void            setTotalSize();

        /** returns the minimum height of the section
        *
        * \param _nPos
        * \return the height in pixel
        */
        sal_Int32       getMinHeight(USHORT _nPos) const;

        void            ScrollChildren(long nDeltaX, long nDeltaY);

        void            notifyHeightChanged();

        /** unmark all objects on the views without the given one.
        *
        * @param _pSectionView The view where the objects should not be unmarked.
        */
        void            unmarkAllObjects(OSectionView* _pSectionView);

        /** triggers the property browser with the report component or section
            @param  _xReportComponent
        */
        void            showProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xReportComponent);

        /** checks if the keycode is known by the child windows
            @param  _rCode  the keycode
            @return <TRUE/> if the keycode is handled otherwise <FALSE/>
        */
        sal_Bool        handleKeyEvent(const KeyEvent& _rEvent);

        /** the the section as marked or not marked
            @param  _pSectionView   the section where to set the marked flag
            @param  _bMark  the marked flag
        */
        void            setMarked(OSectionView* _pSectionView,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Reference< ::com::sun::star::report::XSection>& _xSection,sal_Bool _bMark);
        void            setMarked(const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::report::XReportComponent> >& _xShape,sal_Bool _bMark);

        // IMarkedSection
        ::boost::shared_ptr<OReportSection> getMarkedSection(NearSectionAccess nsa = CURRENT) const;
        virtual void markSection(const sal_uInt16 _nPos);

        /** fills the positions of all collapsed sections.
        *
        * \param _rCollapsedPositions Out parameter which holds afterwards all positions of the collapsed sections.
        */
        void fillCollapsedSections(::std::vector<sal_uInt16>& _rCollapsedPositions) const;

        /** collpase all sections given by their position
        *
        * \param _aCollpasedSections The position of the sections which should be collapsed.
        */
        void collapseSections(const com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _aCollpasedSections);

        /** align all marked objects in all sections
        *
        * \param eHor
        * \param eVert
        * \param bBoundRects
        */
        void alignMarkedObjects(sal_Int32 _nControlModification, bool _bAlignAtSection, bool bBoundRects = false);

        sal_uInt32 getMarkedObjectCount() const;
    };
//==================================================================
}   //rptui
//==================================================================
#endif // RPTUI_REPORT_WINDOW_HXX

<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS swwarnings (1.2.6); FILE MERGED 2007/08/21 11:19:46 tl 1.2.6.3: RESYNC: (1.3-1.4); FILE MERGED 2007/05/29 19:45:16 os 1.2.6.2: RESYNC: (1.2-1.3); FILE MERGED 2007/04/17 07:51:30 tl 1.2.6.1: #i69287# warning-free code<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

#ifndef __IGN_TRANSPORT_SOCKET_HH_INCLUDED__
#define __IGN_TRANSPORT_SOCKET_HH_INCLUDED__

#include <exception>
#include <string>

namespace ignition
{
  namespace transport
  {
    /// \class SocketException Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief Exception class for sockets.
    class SocketException : public std::exception
    {
      /// \brief Class constructor.
      /// \param _message Exception message.
      /// \param _inclSysMsg True if system message (from strerror(errno))
      /// should be postfixed to the user provided message.
      public: SocketException(const std::string &_message,
                               bool _inclSysMsg = false);

      /// \brief Class destructor.
      public: ~SocketException() = default;

      /// \brief Get the exception message.
      /// \return Exception message.
      public: const char* what() const noexcept;

      /// \brief Exception message.
      private: std::string userMessage;
    };

    /// \class Socket Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief Socket base class.
    class Socket
    {
      /// \brief Class constructor.
      /// \param _type Socket type. See 'man socket' for all the types.
      /// \param _protocol Socket protocol (IPPROTO_UDP, IPPROTO_TCP).
      public: Socket(int _type,
                     int _protocol) throw(SocketException);

      /// \brief Class constructor.
      /// \param _sockDesc Socket descriptor.
      public: Socket(int _sockDesc);

      /// \brief Prevent the user from trying to use the copy constructor.
      public: Socket(const Socket &_sock) = delete;

      /// \brief Class destructor.
      public: ~Socket();

      /// \brief Set the local port to the specified port and the local address
      /// to any interface.
      /// \param _localPort local port.
      /// \exception SocketException thrown if setting local port fails.
      public: void SetLocalPort(uint16_t _localPort)
                                throw(SocketException);

      /// \brief Set the local port to the specified port and the local address
      /// to the specified address.  If you omit the port, a random port
      /// will be selected.
      /// \param _localAddress local address.
      /// \param _localPort local port.
      /// \exception SocketException thrown if setting local port/address fails.
      public: void SetLocalAddressAndPort(const std::string &_localAddress,
                                          uint16_t _localPort = 0)
                                          throw(SocketException);

      /// \brief Socket descriptor.
      public: int sockDesc;
    };

    /// \class CommunicatingSocket Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief Socket which is able to connect, send, and receive.
    class CommunicatingSocket : public Socket
    {
      /// \brief Class constructor. Documentation inherited.
      public: CommunicatingSocket(int _type,
                                  int _protocol) throw(SocketException);

      /// \brief Class constructor. Documentation inherited.
      public: CommunicatingSocket(int _newConnSD);

      /// \brief Establish a socket connection with the given foreign
      /// address and port.
      /// \param _foreignAddress Foreign address (IP address or name).
      /// \param _foreignPort Foreign port.
      /// \exception SocketException thrown if unable to establish connection.
      public: void Connect(const std::string &_foreignAddress,
                           uint16_t _foreignPort) throw(SocketException);

      /// \brief Write the given buffer to this socket. Call connect() before
      /// calling send().
      /// \param _buffer buffer to be written.
      /// \param _bufferLen number of bytes from buffer to be written.
      /// \exception SocketException thrown if unable to send data.
      public: void Send(const void *_buffer,
                        int _bufferLen) throw(SocketException);

      /// \brief Read into the given buffer up to bufferLen bytes data from this
      /// socket. Call connect() before calling recv().
      /// \param _buffer buffer to receive the data.
      /// \param _bufferLen maximum number of bytes to read into buffer.
      /// \return number of bytes read, 0 for EOF, and -1 for error.
      /// \exception SocketException thrown if unable to receive data.
      public: int Recv(void *_buffer,
                       int _bufferLen) throw(SocketException);
    };

    /// \class CommunicatingSocket Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief UDP Socket class.
    class UDPSocket : public CommunicatingSocket
    {
      /// \brief class constructor.
      /// \exception SocketException thrown if unable to create UDP socket.
      public: UDPSocket() throw(SocketException);

      /// \brief Construct a UDP socket with the given local port.
      /// \param _localPort Local port.
      /// \exception SocketException thrown if unable to create UDP socket.
      public: UDPSocket(uint16_t _localPort) throw(SocketException);

      /// \brief Construct a UDP socket with the given local port and address
      /// \param _localAddress local address.
      /// \param _localPort local port.
      /// \exception SocketException thrown if unable to create UDP socket.
      public: UDPSocket(const std::string &_localAddress,
                        uint16_t _localPort) throw(SocketException);

      /// \brief Unset foreign address and port.
      /// \return true if disassociation is successful.
      /// \exception SocketException thrown if unable to disconnect UDP socket.
      public: void Disconnect() throw(SocketException);

      /// \brief Send the given buffer as a UDP datagram to the
      /// specified address/port.
      /// \param _buffer buffer to be written
      /// \param _bufferLen number of bytes to write
      /// \param _foreignAddress address (IP address or name) to send to
      /// \param _foreignPort port number to send to
      /// \return true if send is successful
      /// \exception SocketException thrown if unable to send datagram
      public: void SendTo(const void *_buffer,
                          int _bufferLen,
                          const std::string &_foreignAddress,
                          uint16_t _foreignPort) throw(SocketException);

      /// \brief Read read up to bufferLen bytes data from this socket.
      /// The given buffer is where the data will be placed.
      /// \param _buffer buffer to receive data.
      /// \param _bufferLen maximum number of bytes to receive.
      /// \param _sourceAddress address of datagram source.
      /// \param _sourcePort port of data source.
      /// \return number of bytes received and -1 for error.
      /// \exception SocketException thrown if unable to receive datagram.
      public: int RecvFrom(void *_buffer,
                           int _bufferLen,
                           std::string &_sourceAddress,
                           uint16_t &_sourcePort) throw(SocketException);

      /// \brief Enable broadcast for this socket.
      private: void SetBroadcast();
    };
  }
}
#endif
<commit_msg>Adding reference into the Socket class.<commit_after>/*
 * Copyright (C) 2014 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

/* Reference:
http://cs.ecs.baylor.edu/~donahoo/practical/CSockets/practical/PracticalSocket.h
*/

#ifndef __IGN_TRANSPORT_SOCKET_HH_INCLUDED__
#define __IGN_TRANSPORT_SOCKET_HH_INCLUDED__

#include <exception>
#include <string>

namespace ignition
{
  namespace transport
  {
    /// \class SocketException Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief Exception class for sockets.
    class SocketException : public std::exception
    {
      /// \brief Class constructor.
      /// \param _message Exception message.
      /// \param _inclSysMsg True if system message (from strerror(errno))
      /// should be postfixed to the user provided message.
      public: SocketException(const std::string &_message,
                               bool _inclSysMsg = false);

      /// \brief Class destructor.
      public: ~SocketException() = default;

      /// \brief Get the exception message.
      /// \return Exception message.
      public: const char* what() const noexcept;

      /// \brief Exception message.
      private: std::string userMessage;
    };

    /// \class Socket Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief Socket base class.
    class Socket
    {
      /// \brief Class constructor.
      /// \param _type Socket type. See 'man socket' for all the types.
      /// \param _protocol Socket protocol (IPPROTO_UDP, IPPROTO_TCP).
      public: Socket(int _type,
                     int _protocol) throw(SocketException);

      /// \brief Class constructor.
      /// \param _sockDesc Socket descriptor.
      public: Socket(int _sockDesc);

      /// \brief Prevent the user from trying to use the copy constructor.
      public: Socket(const Socket &_sock) = delete;

      /// \brief Class destructor.
      public: ~Socket();

      /// \brief Set the local port to the specified port and the local address
      /// to any interface.
      /// \param _localPort local port.
      /// \exception SocketException thrown if setting local port fails.
      public: void SetLocalPort(uint16_t _localPort)
                                throw(SocketException);

      /// \brief Set the local port to the specified port and the local address
      /// to the specified address.  If you omit the port, a random port
      /// will be selected.
      /// \param _localAddress local address.
      /// \param _localPort local port.
      /// \exception SocketException thrown if setting local port/address fails.
      public: void SetLocalAddressAndPort(const std::string &_localAddress,
                                          uint16_t _localPort = 0)
                                          throw(SocketException);

      /// \brief Socket descriptor.
      public: int sockDesc;
    };

    /// \class CommunicatingSocket Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief Socket which is able to connect, send, and receive.
    class CommunicatingSocket : public Socket
    {
      /// \brief Class constructor. Documentation inherited.
      public: CommunicatingSocket(int _type,
                                  int _protocol) throw(SocketException);

      /// \brief Class constructor. Documentation inherited.
      public: CommunicatingSocket(int _newConnSD);

      /// \brief Establish a socket connection with the given foreign
      /// address and port.
      /// \param _foreignAddress Foreign address (IP address or name).
      /// \param _foreignPort Foreign port.
      /// \exception SocketException thrown if unable to establish connection.
      public: void Connect(const std::string &_foreignAddress,
                           uint16_t _foreignPort) throw(SocketException);

      /// \brief Write the given buffer to this socket. Call connect() before
      /// calling send().
      /// \param _buffer buffer to be written.
      /// \param _bufferLen number of bytes from buffer to be written.
      /// \exception SocketException thrown if unable to send data.
      public: void Send(const void *_buffer,
                        int _bufferLen) throw(SocketException);

      /// \brief Read into the given buffer up to bufferLen bytes data from this
      /// socket. Call connect() before calling recv().
      /// \param _buffer buffer to receive the data.
      /// \param _bufferLen maximum number of bytes to read into buffer.
      /// \return number of bytes read, 0 for EOF, and -1 for error.
      /// \exception SocketException thrown if unable to receive data.
      public: int Recv(void *_buffer,
                       int _bufferLen) throw(SocketException);
    };

    /// \class CommunicatingSocket Socket.hh
    /// ignition/transport/Socket.hh
    /// \brief UDP Socket class.
    class UDPSocket : public CommunicatingSocket
    {
      /// \brief class constructor.
      /// \exception SocketException thrown if unable to create UDP socket.
      public: UDPSocket() throw(SocketException);

      /// \brief Construct a UDP socket with the given local port.
      /// \param _localPort Local port.
      /// \exception SocketException thrown if unable to create UDP socket.
      public: UDPSocket(uint16_t _localPort) throw(SocketException);

      /// \brief Construct a UDP socket with the given local port and address
      /// \param _localAddress local address.
      /// \param _localPort local port.
      /// \exception SocketException thrown if unable to create UDP socket.
      public: UDPSocket(const std::string &_localAddress,
                        uint16_t _localPort) throw(SocketException);

      /// \brief Unset foreign address and port.
      /// \return true if disassociation is successful.
      /// \exception SocketException thrown if unable to disconnect UDP socket.
      public: void Disconnect() throw(SocketException);

      /// \brief Send the given buffer as a UDP datagram to the
      /// specified address/port.
      /// \param _buffer buffer to be written
      /// \param _bufferLen number of bytes to write
      /// \param _foreignAddress address (IP address or name) to send to
      /// \param _foreignPort port number to send to
      /// \return true if send is successful
      /// \exception SocketException thrown if unable to send datagram
      public: void SendTo(const void *_buffer,
                          int _bufferLen,
                          const std::string &_foreignAddress,
                          uint16_t _foreignPort) throw(SocketException);

      /// \brief Read read up to bufferLen bytes data from this socket.
      /// The given buffer is where the data will be placed.
      /// \param _buffer buffer to receive data.
      /// \param _bufferLen maximum number of bytes to receive.
      /// \param _sourceAddress address of datagram source.
      /// \param _sourcePort port of data source.
      /// \return number of bytes received and -1 for error.
      /// \exception SocketException thrown if unable to receive datagram.
      public: int RecvFrom(void *_buffer,
                           int _bufferLen,
                           std::string &_sourceAddress,
                           uint16_t &_sourcePort) throw(SocketException);

      /// \brief Enable broadcast for this socket.
      private: void SetBroadcast();
    };
  }
}
#endif
<|endoftext|>