<commit_before>#ifndef __NOD_UTIL_HPP__
#define __NOD_UTIL_HPP__

#if _WIN32 && UNICODE
#include <wctype.h>
#include <direct.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#endif
#else
#include <ctype.h>
#endif
#include <sys/stat.h>

#include <string>
#include <algorithm>
#include <LogVisor/LogVisor.hpp>

namespace NOD
{

/* Log Module */
extern LogVisor::LogModule LogModule;

/* filesystem char type */
#if _WIN32 && UNICODE
#define NOD_UCS2 1
typedef struct _stat Sstat;
static inline int Mkdir(const wchar_t* path, int) {return _wmkdir(path);}
static inline int Stat(const wchar_t* path, Sstat* statout) {return _wstat(path, statout);}
#else
typedef struct stat Sstat;
static inline int Mkdir(const char* path, mode_t mode) {return mkdir(path, mode);}
static inline int Stat(const char* path, Sstat* statout) {return stat(path, statout);}
#endif

/* String-converting views */
#if NOD_UCS2
typedef wchar_t SystemChar;
typedef std::wstring SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towlower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towupper);}
class SystemUTF8View
{
    std::string m_utf8;
public:
    SystemUTF8View(const SystemString& str)
    {
        int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0, nullptr, nullptr);
        m_utf8.assign('\0', len);
        WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), &m_utf8[0], len, nullptr, nullptr);
    }
    inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
    std::wstring m_sys;
public:
    SystemStringView(const std::string& str)
    {
        int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0);
        m_sys.assign(L'\0', len);
        MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), &m_sys[0], len);
    }
    inline const std::wstring& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) L ## val
#endif
#else
typedef char SystemChar;
typedef std::string SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), tolower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), toupper);}
class SystemUTF8View
{
    const std::string& m_utf8;
public:
    SystemUTF8View(const SystemString& str)
    : m_utf8(str) {}
    inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
    const std::string& m_sys;
public:
    SystemStringView(const std::string& str)
    : m_sys(str) {}
    inline const std::string& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) val
#endif
#endif

/* Type-sensitive byte swappers */
template <typename T>
static inline T bswap16(T val)
{
#if __GNUC__
    return __builtin_bswap16(val);
#elif _WIN32
    return _byteswap_ushort(val);
#else
    return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif
}

template <typename T>
static inline T bswap32(T val)
{
#if __GNUC__
    return __builtin_bswap32(val);
#elif _WIN32
    return _byteswap_ulong(val);
#else
    val = (val & 0x0000FFFF) << 16 | (val & 0xFFFF0000) >> 16;
    val = (val & 0x00FF00FF) << 8 | (val & 0xFF00FF00) >> 8;
    return val;
#endif
}

template <typename T>
static inline T bswap64(T val)
{
#if __GNUC__
    return __builtin_bswap64(val);
#elif _WIN32
    return _byteswap_uint64(val);
#else
    return ((val & 0xFF00000000000000ULL) >> 56) |
           ((val & 0x00FF000000000000ULL) >> 40) |
           ((val & 0x0000FF0000000000ULL) >> 24) |
           ((val & 0x000000FF00000000ULL) >>  8) |
           ((val & 0x00000000FF000000ULL) <<  8) |
           ((val & 0x0000000000FF0000ULL) << 24) |
           ((val & 0x000000000000FF00ULL) << 40) |
           ((val & 0x00000000000000FFULL) << 56);
#endif
}

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static inline int16_t SBig(int16_t val) {return bswap16(val);}
static inline uint16_t SBig(uint16_t val) {return bswap16(val);}
static inline int32_t SBig(int32_t val) {return bswap32(val);}
static inline uint32_t SBig(uint32_t val) {return bswap32(val);}
static inline int64_t SBig(int64_t val) {return bswap64(val);}
static inline uint64_t SBig(uint64_t val) {return bswap64(val);}

static inline int16_t SLittle(int16_t val) {return val;}
static inline uint16_t SLittle(uint16_t val) {return val;}
static inline int32_t SLittle(int32_t val) {return val;}
static inline uint32_t SLittle(uint32_t val) {return val;}
static inline int64_t SLittle(int64_t val) {return val;}
static inline uint64_t SLittle(uint64_t val) {return val;}
#else
static inline int16_t SLittle(int16_t val) {return bswap16(val);}
static inline uint16_t SLittle(uint16_t val) {return bswap16(val);}
static inline int32_t SLittle(int32_t val) {return bswap32(val);}
static inline uint32_t SLittle(uint32_t val) {return bswap32(val);}
static inline int64_t SLittle(int64_t val) {return bswap64(val);}
static inline uint64_t SLittle(uint64_t val) {return bswap64(val);}

static inline int16_t SBig(int16_t val) {return val;}
static inline uint16_t SBig(uint16_t val) {return val;}
static inline int32_t SBig(int32_t val) {return val;}
static inline uint32_t SBig(uint32_t val) {return val;}
static inline int64_t SBig(int64_t val) {return val;}
static inline uint64_t SBig(uint64_t val) {return val;}
#endif

}

#endif // __NOD_UTIL_HPP__
<commit_msg>string conversion fix for windows<commit_after>#ifndef __NOD_UTIL_HPP__
#define __NOD_UTIL_HPP__

#if _WIN32 && UNICODE
#include <wctype.h>
#include <direct.h>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#include <windows.h>
#endif
#else
#include <ctype.h>
#endif
#include <sys/stat.h>

#include <string>
#include <algorithm>
#include <LogVisor/LogVisor.hpp>

namespace NOD
{

/* Log Module */
extern LogVisor::LogModule LogModule;

/* filesystem char type */
#if _WIN32 && UNICODE
#define NOD_UCS2 1
typedef struct _stat Sstat;
static inline int Mkdir(const wchar_t* path, int) {return _wmkdir(path);}
static inline int Stat(const wchar_t* path, Sstat* statout) {return _wstat(path, statout);}
#else
typedef struct stat Sstat;
static inline int Mkdir(const char* path, mode_t mode) {return mkdir(path, mode);}
static inline int Stat(const char* path, Sstat* statout) {return stat(path, statout);}
#endif

/* String-converting views */
#if NOD_UCS2
typedef wchar_t SystemChar;
typedef std::wstring SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towlower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), towupper);}
class SystemUTF8View
{
    std::string m_utf8;
public:
    SystemUTF8View(const SystemString& str)
    {
        int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0, nullptr, nullptr);
        m_utf8.assign(len, '\0');
        WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.size(), &m_utf8[0], len, nullptr, nullptr);
    }
    inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
    std::wstring m_sys;
public:
    SystemStringView(const std::string& str)
    {
        int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), nullptr, 0);
        m_sys.assign(len, L'\0');
        MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.size(), &m_sys[0], len);
    }
    inline const std::wstring& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) L ## val
#endif
#else
typedef char SystemChar;
typedef std::string SystemString;
static inline void ToLower(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), tolower);}
static inline void ToUpper(SystemString& str)
{std::transform(str.begin(), str.end(), str.begin(), toupper);}
class SystemUTF8View
{
    const std::string& m_utf8;
public:
    SystemUTF8View(const SystemString& str)
    : m_utf8(str) {}
    inline const std::string& utf8_str() {return m_utf8;}
};
class SystemStringView
{
    const std::string& m_sys;
public:
    SystemStringView(const std::string& str)
    : m_sys(str) {}
    inline const std::string& sys_str() {return m_sys;}
};
#ifndef _S
#define _S(val) val
#endif
#endif

/* Type-sensitive byte swappers */
template <typename T>
static inline T bswap16(T val)
{
#if __GNUC__
    return __builtin_bswap16(val);
#elif _WIN32
    return _byteswap_ushort(val);
#else
    return (val = (val << 8) | ((val >> 8) & 0xFF));
#endif
}

template <typename T>
static inline T bswap32(T val)
{
#if __GNUC__
    return __builtin_bswap32(val);
#elif _WIN32
    return _byteswap_ulong(val);
#else
    val = (val & 0x0000FFFF) << 16 | (val & 0xFFFF0000) >> 16;
    val = (val & 0x00FF00FF) << 8 | (val & 0xFF00FF00) >> 8;
    return val;
#endif
}

template <typename T>
static inline T bswap64(T val)
{
#if __GNUC__
    return __builtin_bswap64(val);
#elif _WIN32
    return _byteswap_uint64(val);
#else
    return ((val & 0xFF00000000000000ULL) >> 56) |
           ((val & 0x00FF000000000000ULL) >> 40) |
           ((val & 0x0000FF0000000000ULL) >> 24) |
           ((val & 0x000000FF00000000ULL) >>  8) |
           ((val & 0x00000000FF000000ULL) <<  8) |
           ((val & 0x0000000000FF0000ULL) << 24) |
           ((val & 0x000000000000FF00ULL) << 40) |
           ((val & 0x00000000000000FFULL) << 56);
#endif
}

#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
static inline int16_t SBig(int16_t val) {return bswap16(val);}
static inline uint16_t SBig(uint16_t val) {return bswap16(val);}
static inline int32_t SBig(int32_t val) {return bswap32(val);}
static inline uint32_t SBig(uint32_t val) {return bswap32(val);}
static inline int64_t SBig(int64_t val) {return bswap64(val);}
static inline uint64_t SBig(uint64_t val) {return bswap64(val);}

static inline int16_t SLittle(int16_t val) {return val;}
static inline uint16_t SLittle(uint16_t val) {return val;}
static inline int32_t SLittle(int32_t val) {return val;}
static inline uint32_t SLittle(uint32_t val) {return val;}
static inline int64_t SLittle(int64_t val) {return val;}
static inline uint64_t SLittle(uint64_t val) {return val;}
#else
static inline int16_t SLittle(int16_t val) {return bswap16(val);}
static inline uint16_t SLittle(uint16_t val) {return bswap16(val);}
static inline int32_t SLittle(int32_t val) {return bswap32(val);}
static inline uint32_t SLittle(uint32_t val) {return bswap32(val);}
static inline int64_t SLittle(int64_t val) {return bswap64(val);}
static inline uint64_t SLittle(uint64_t val) {return bswap64(val);}

static inline int16_t SBig(int16_t val) {return val;}
static inline uint16_t SBig(uint16_t val) {return val;}
static inline int32_t SBig(int32_t val) {return val;}
static inline uint32_t SBig(uint32_t val) {return val;}
static inline int64_t SBig(int64_t val) {return val;}
static inline uint64_t SBig(uint64_t val) {return val;}
#endif

}

#endif // __NOD_UTIL_HPP__
<|endoftext|>


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

#ifndef _aescrypt__aescrypt_hpp
#define _aescrypt__aescrypt_hpp

#include <cstdint>
#include <memory>

namespace aescrypt {

/***************************************************************************/

enum key_length {
	 AES128=128
	,AES192=192
	,AES256=256
};

/***************************************************************************/

struct cryptor {
	using buffer_type = std::unique_ptr<char[]>;

	cryptor(const char *key, const key_length klen);
	~cryptor();

	key_length get_key_length() const;

	void encrypt(char *dst, const char *src, const std::size_t len) const;
	void decrypt(char *dst, const char *src, const std::size_t len) const;

	buffer_type encrypt(const char *src, const std::size_t len) const;
	buffer_type decrypt(const char *src, const std::size_t len) const;

	std::string encrypt(const std::string &src) const;
	std::string decrypt(const std::string &src) const;

private:
	struct impl;
	impl *pimpl;
}; // struct cryptor

/***************************************************************************/

} // ns aesni

#endif // _aescrypt__aescrypt_hpp
<commit_msg>Update aescrypt.hpp<commit_after>
// Copyright (c) 2014-2015 niXman (i dotty nixman doggy gmail dotty com)
// All rights reserved.
//
// This file is part of aescrypt(https://github.com/niXman/aescrypt) project.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
//   Redistributions in binary form must reproduce the above copyright notice, this
//   list of conditions and the following disclaimer in the documentation and/or
//   other materials provided with the distribution.
//
//   Neither the name of the {organization} nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#ifndef _aescrypt__aescrypt_hpp
#define _aescrypt__aescrypt_hpp

#include <cstdint>
#include <memory>

namespace aescrypt {

/***************************************************************************/

enum key_length {
	 AES128=128
	,AES192=192
	,AES256=256
};

/***************************************************************************/

struct cryptor {
	using buffer_type = std::unique_ptr<char[]>;

	cryptor(const char *key, const key_length klen);
	~cryptor();

	key_length get_key_length() const;

	void encrypt(char *dst, const char *src, const std::size_t len) const;
	void decrypt(char *dst, const char *src, const std::size_t len) const;

	buffer_type encrypt(const char *src, const std::size_t len) const;
	buffer_type decrypt(const char *src, const std::size_t len) const;

	std::string encrypt(const std::string &src) const;
	std::string decrypt(const std::string &src) const;

private:
	struct impl;
	impl *pimpl;
}; // struct cryptor

/***************************************************************************/

} // ns aesni

#endif // _aescrypt__aescrypt_hpp
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015-2016 Nagisa Sekiguchi
 *
 * 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 AQUARIUS_CXX_AQUARIUS_HPP
#define AQUARIUS_CXX_AQUARIUS_HPP

#include "internal/expression.hpp"
#include "internal/mapper.hpp"
#include "internal/parser.hpp"
#include "internal/combinator.hpp"

// helper macro
#define aquarius_pattern_t constexpr auto

#define AQUARIUS_DEFINE_RULE(R, name, p) \
template <typename T> \
struct name ## __impl { \
    using name = name ## __impl<R>;\
    static_assert(std::is_same<T, std::remove_reference<decltype(p)>::type::retType>::value, "must be same type");\
    static constexpr auto pattern() { return p; }\
}; using name = name ## __impl<R>

#define AQUARIUS_DECL_RULE(R, name) \
template <typename T> struct name ## __impl; using name = name ## __impl<R>

#endif //AQUARIUS_CXX_AQUARIUS_HPP
<commit_msg>fix build error in older gcc<commit_after>/*
 * Copyright (C) 2015-2016 Nagisa Sekiguchi
 *
 * 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 AQUARIUS_CXX_AQUARIUS_HPP
#define AQUARIUS_CXX_AQUARIUS_HPP

#include "internal/expression.hpp"
#include "internal/mapper.hpp"
#include "internal/parser.hpp"
#include "internal/combinator.hpp"

// helper macro
#define aquarius_pattern_t constexpr auto

#define AQUARIUS_DEFINE_RULE(R, name, p) \
template <typename T> \
struct name ## __impl { \
    using name = name ## __impl<R>;\
    static_assert(std::is_same<T, std::remove_reference<decltype(p)>::type::retType>::value, "must be same type");\
    static constexpr auto pattern() std::remove_reference<decltype(p)>::type { return p; }\
}; using name = name ## __impl<R>

#define AQUARIUS_DECL_RULE(R, name) \
template <typename T> struct name ## __impl; using name = name ## __impl<R>

#endif //AQUARIUS_CXX_AQUARIUS_HPP
<|endoftext|>


<commit_before>// Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

#include "Variant.h"

/// Method to enable unit testing of C++ variant calls from pytest
Scalar testVariantCall(std::shared_ptr<Variant> t, uint64_t step)
    {
    return (*t)(step);
    }

/// Method to enable unit testing of C++ variant min class from pytest
Scalar testVariantMin(std::shared_ptr<Variant> t)
    {
    return t->min();
    }

/// Method to enable unit testing of C++ variant max class from pytest
Scalar testVariantMax(std::shared_ptr<Variant> t)
    {
    return t->max();
    }

//* Trampoline for classes inherited in python
class VariantPy : public Variant
    {
    public:
        // Inherit the constructors
        using Variant::Variant;

        // trampoline method
        Scalar operator()(uint64_t timestep) override
            {
            PYBIND11_OVERLOAD_NAME(Scalar,       // Return type
                                   Variant,      // Parent class
                                   "__call__",   // name of function in python
                                   operator(),   // Name of function in C++
                                   timestep      // Argument(s)
                              );
            }

        Scalar min() override
            {
            PYBIND11_OVERLOAD_PURE_NAME(Scalar,  // Return type
                                        Variant, // Parent class
                                        "_min",  // name of function in python
                                        min      // name of function
                    );
            }

        Scalar max() override
            {
            PYBIND11_OVERLOAD_PURE_NAME(Scalar,  // Return type
                                        Variant, // Parent class
                                        "_max",  // name of function in python
                                        max      // name of function
                    );
            }
    };

void export_Variant(pybind11::module& m)
    {
    pybind11::class_<Variant, VariantPy, std::shared_ptr<Variant> >(m,"Variant")
        .def(pybind11::init<>())
        .def("__call__", &Variant::operator())
        .def("_min", &Variant::min)
        .def("_max", &Variant::max)
        .def_property_readonly("range", &Variant::range)
        ;

    pybind11::class_<VariantConstant, Variant, std::shared_ptr<VariantConstant> >(m, "VariantConstant")
        .def(pybind11::init< Scalar >(), pybind11::arg("value"))
        .def_property("value", &VariantConstant::getValue, &VariantConstant::setValue)
        ;

    pybind11::class_<VariantRamp, Variant, std::shared_ptr<VariantRamp> >(m, "VariantRamp")
        .def(pybind11::init< Scalar, Scalar, uint64_t, uint64_t >(), pybind11::arg("A"),
                                                                     pybind11::arg("B"),
                                                                     pybind11::arg("t_start"),
                                                                     pybind11::arg("t_ramp"))
        .def_property("A", &VariantRamp::getA, &VariantRamp::setA)
        .def_property("B", &VariantRamp::getB, &VariantRamp::setB)
        .def_property("t_start", &VariantRamp::getTStart, &VariantRamp::setTStart)
        .def_property("t_ramp", &VariantRamp::getTRamp, &VariantRamp::setTRamp)
        ;

    pybind11::class_<VariantCycle, Variant, std::shared_ptr<VariantCycle> >(m, "VariantCycle")
        .def(pybind11::init< Scalar,
                             Scalar,
                             uint64_t,
                             uint64_t,
                             uint64_t,
                             uint64_t,
                             uint64_t >(),
            pybind11::arg("A"),
            pybind11::arg("B"),
            pybind11::arg("t_start"),
            pybind11::arg("t_A"),
            pybind11::arg("t_AB"),
            pybind11::arg("t_B"),
            pybind11::arg("t_BA"))

        .def_property("A", &VariantCycle::getA, &VariantCycle::setA)
        .def_property("B", &VariantCycle::getB, &VariantCycle::setB)
        .def_property("t_start", &VariantCycle::getTStart, &VariantCycle::setTStart)
        .def_property("t_A", &VariantCycle::getTA, &VariantCycle::setTA)
        .def_property("t_AB", &VariantCycle::getTAB, &VariantCycle::setTAB)
        .def_property("t_B", &VariantCycle::getTB, &VariantCycle::setTB)
        .def_property("t_BA", &VariantCycle::getTBA, &VariantCycle::setTBA)
        ;

    pybind11::class_<VariantPower, Variant,
                     std::shared_ptr<VariantPower> >(m, "VariantPower")
        .def(pybind11::init<Scalar, Scalar, double,
                            uint64_t, uint64_t>(),
             pybind11::arg("A"),
             pybind11::arg("B"),
             pybind11::arg("power"),
             pybind11::arg("t_start"),
             pybind11::arg("t_ramp")
             )
        .def_property("A", &VariantPower::getA, &VariantPower::setA)
        .def_property("B", &VariantPower::getB, &VariantPower::setB)
        .def_property("power", &VariantPower::getPower,
                      &VariantPower::setPower)
        .def_property("t_start", &VariantPower::getTStart,
                      &VariantPower::setTStart)
        .def_property("t_size", &VariantPower::getTSize,
                      &VariantPower::setTSize)
        ;

    m.def("_test_variant_call", &testVariantCall);
    m.def("_test_variant_min", &testVariantMin);
    m.def("_test_variant_max", &testVariantMax);
    }
<commit_msg>Add developer comments.<commit_after>// Copyright (c) 2009-2019 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.

#include "Variant.h"

// These testVariant{Method} functions allow us to test that Python custom
// variants work properly in C++. This ensures we can test that the function
// itself can be called in C++ when defined in Python.

/// Method to enable unit testing of C++ variant calls from pytest
Scalar testVariantCall(std::shared_ptr<Variant> t, uint64_t step)
    {
    return (*t)(step);
    }

/// Method to enable unit testing of C++ variant min class from pytest
Scalar testVariantMin(std::shared_ptr<Variant> t)
    {
    return t->min();
    }

/// Method to enable unit testing of C++ variant max class from pytest
Scalar testVariantMax(std::shared_ptr<Variant> t)
    {
    return t->max();
    }

//* Trampoline for classes inherited in python
class VariantPy : public Variant
    {
    public:
        // Inherit the constructors
        using Variant::Variant;

        // trampoline method
        Scalar operator()(uint64_t timestep) override
            {
            PYBIND11_OVERLOAD_NAME(Scalar,       // Return type
                                   Variant,      // Parent class
                                   "__call__",   // name of function in python
                                   operator(),   // Name of function in C++
                                   timestep      // Argument(s)
                              );
            }

        Scalar min() override
            {
            PYBIND11_OVERLOAD_PURE_NAME(Scalar,  // Return type
                                        Variant, // Parent class
                                        "_min",  // name of function in python
                                        min      // name of function
                    );
            }

        Scalar max() override
            {
            PYBIND11_OVERLOAD_PURE_NAME(Scalar,  // Return type
                                        Variant, // Parent class
                                        "_max",  // name of function in python
                                        max      // name of function
                    );
            }
    };

void export_Variant(pybind11::module& m)
    {
    pybind11::class_<Variant, VariantPy, std::shared_ptr<Variant> >(m,"Variant")
        .def(pybind11::init<>())
        .def("__call__", &Variant::operator())
        .def("_min", &Variant::min)
        .def("_max", &Variant::max)
        .def_property_readonly("range", &Variant::range)
        ;

    pybind11::class_<VariantConstant, Variant, std::shared_ptr<VariantConstant> >(m, "VariantConstant")
        .def(pybind11::init< Scalar >(), pybind11::arg("value"))
        .def_property("value", &VariantConstant::getValue, &VariantConstant::setValue)
        ;

    pybind11::class_<VariantRamp, Variant, std::shared_ptr<VariantRamp> >(m, "VariantRamp")
        .def(pybind11::init< Scalar, Scalar, uint64_t, uint64_t >(), pybind11::arg("A"),
                                                                     pybind11::arg("B"),
                                                                     pybind11::arg("t_start"),
                                                                     pybind11::arg("t_ramp"))
        .def_property("A", &VariantRamp::getA, &VariantRamp::setA)
        .def_property("B", &VariantRamp::getB, &VariantRamp::setB)
        .def_property("t_start", &VariantRamp::getTStart, &VariantRamp::setTStart)
        .def_property("t_ramp", &VariantRamp::getTRamp, &VariantRamp::setTRamp)
        ;

    pybind11::class_<VariantCycle, Variant, std::shared_ptr<VariantCycle> >(m, "VariantCycle")
        .def(pybind11::init< Scalar,
                             Scalar,
                             uint64_t,
                             uint64_t,
                             uint64_t,
                             uint64_t,
                             uint64_t >(),
            pybind11::arg("A"),
            pybind11::arg("B"),
            pybind11::arg("t_start"),
            pybind11::arg("t_A"),
            pybind11::arg("t_AB"),
            pybind11::arg("t_B"),
            pybind11::arg("t_BA"))

        .def_property("A", &VariantCycle::getA, &VariantCycle::setA)
        .def_property("B", &VariantCycle::getB, &VariantCycle::setB)
        .def_property("t_start", &VariantCycle::getTStart, &VariantCycle::setTStart)
        .def_property("t_A", &VariantCycle::getTA, &VariantCycle::setTA)
        .def_property("t_AB", &VariantCycle::getTAB, &VariantCycle::setTAB)
        .def_property("t_B", &VariantCycle::getTB, &VariantCycle::setTB)
        .def_property("t_BA", &VariantCycle::getTBA, &VariantCycle::setTBA)
        ;

    pybind11::class_<VariantPower, Variant,
                     std::shared_ptr<VariantPower> >(m, "VariantPower")
        .def(pybind11::init<Scalar, Scalar, double,
                            uint64_t, uint64_t>(),
             pybind11::arg("A"),
             pybind11::arg("B"),
             pybind11::arg("power"),
             pybind11::arg("t_start"),
             pybind11::arg("t_ramp")
             )
        .def_property("A", &VariantPower::getA, &VariantPower::setA)
        .def_property("B", &VariantPower::getB, &VariantPower::setB)
        .def_property("power", &VariantPower::getPower,
                      &VariantPower::setPower)
        .def_property("t_start", &VariantPower::getTStart,
                      &VariantPower::setTStart)
        .def_property("t_size", &VariantPower::getTSize,
                      &VariantPower::setTSize)
        ;

    m.def("_test_variant_call", &testVariantCall);
    m.def("_test_variant_min", &testVariantMin);
    m.def("_test_variant_max", &testVariantMax);
    }
<|endoftext|>


<commit_before>#include "OGLESGPGPUTest.h"

#include "ogles_gpgpu/common/gl/memtransfer_optimized.h"

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>

#define INITIAL_PROC_TYPE 1

_GATHERER_GRAPHICS_BEGIN

class MemTransferScopeLock
{
public:
    MemTransferScopeLock(ogles_gpgpu::MemTransferOptimized *transfer) : transfer(transfer)
    {
        ptr = transfer->lockBufferAndGetPtr(ogles_gpgpu::BUF_TYPE_OUTPUT);
    }
    ~MemTransferScopeLock()
    {
        transfer->unlockBuffer(ogles_gpgpu::BUF_TYPE_OUTPUT);
    }
    const void *data() const { return ptr; }
    operator const void *() const { return ptr; }
protected:
    const void *ptr = 0;
    ogles_gpgpu::MemTransferOptimized *transfer = 0;
};

OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const float resolution)
: glContext(glContext)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationStd)
{
    initCam();
    initOGLESGPGPU(glContext);
}

OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const cv::Size &screenSize, const float resolution)
: glContext(glContext)
, screenSize(screenSize)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored)
{
    initCam();
    initOGLESGPGPU(glContext);
}

OEGLGPGPUTest::~OEGLGPGPUTest()
{
    ogles_gpgpu::Core::destroy();
    gpgpuMngr = 0;
}

void OEGLGPGPUTest::initCam()
{
    /*
     * Some temporary code to test the optimized gpu to cpu frame handler.
     * This should be instantiated form a higher level (i.e., main.cpp)
     * but this class hasn't been allocated at that point yet.  This at
     * least supports testing of the concept.
     */

#define TEST_FRAME_HANDLER 0
#if TEST_FRAME_HANDLER
    frameHandler = [](const cv::Mat &frame)
    {
        std::stringstream ss;
        ss << getenv("HOME") << "/Documents/frame.png";
        cv::imwrite(ss.str(), frame);
    };
#endif
}

void OEGLGPGPUTest::initOGLESGPGPU(void* glContext)
{
    // get ogles_gpgpu::Core singleton instance
    gpgpuMngr = ogles_gpgpu::Core::getInstance();

    // enable iOS optimizations (fast texture access)
    ogles_gpgpu::Core::tryEnablePlatformOptimizations();

    // do not use mipmaps (will not work with NPOT images)
    gpgpuMngr->setUseMipmaps(false);

    // create the pipeline
    initGPUPipeline(5);

    outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);

    // initialize the pipeline (TODO)
    gpgpuMngr->init(glContext);
}

void OEGLGPGPUTest::setDisplaySize(int width, int height)
{
    outputDispRenderer->setOutputSize(width, height);
}

void OEGLGPGPUTest::initGPUPipeline(int type)
{
    if (selectedProcType == type) return;   // no change

    // reset the pipeline
    gpgpuMngr->reset();

    // create the pipeline
    if (type == 1)
    {
        gpgpuMngr->addProcToPipeline(&grayscaleProc);
        gpgpuMngr->addProcToPipeline(&adaptThreshProc);
    }
    else if (type == 2)
    {
        gpgpuMngr->addProcToPipeline(&grayscaleProc);
        gpgpuMngr->addProcToPipeline(&simpleThreshProc);
    }
    else if (type == 3)
    {
        gpgpuMngr->addProcToPipeline(&gaussProc);
    }
    else if (type == 4)
    {

#define USE_TRANSFORM1 1
#define USE_TRANSFORM2 0

#if USE_TRANSFORM1
        ogles_gpgpu::Mat44f transformMatrix =
        {{
            {1.f,0.f,0.f,0.f},
            {0.f,1.f,0.f,0.f},
            {0.f,0.f,0.f,0.f},
            {0.f,0.f,0.f,1.f}
        }};

        // Use this to place the texture upright for processing (object, detection, etc)
        transformProc1.setTransformMatrix(transformMatrix);
        transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
        transformProc1.setOutputSize(0.25);

        gpgpuMngr->addProcToPipeline(&transformProc1);
#endif

        gpgpuMngr->addProcToPipeline(&grayscaleProc);

#if USE_TRANSFORM2
        // Use this to place the texture back in the native orientation (and aspect ratio)
        // provided by the QML Camera since the QML VideoOutput object that displays the
        // frames is expecting that and I don't see a trivial way to work around that.
        // It seems we need to override either the VideoObject class or encapsulate this
        // native processing pipeline in some kind of ExtendedCamera qml object that
        // reports the size and orientation of the final processed texture.  Since this
        // is all on the GPU it may not matter much from a performance standpoint.
        //
        // TODO: investigate QT mechanism for avoiding this.
        transformProc2.setTransformMatrix(transformMatrix);
        transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
        transformProc2.setOutputSize(0.25);

        gpgpuMngr->addProcToPipeline(&transformProc2);
#endif
    }
    else if (type == 5) // upright transformation
    {
        auto interpolation = ogles_gpgpu::TransformProc::BICUBIC;

        transformProc1.setInterpolation(interpolation);
        float theta = 15.0 * M_PI / 180.0;
        float ct = std::cos(theta);
        float st = std::sin(theta);
        ogles_gpgpu::Mat44f transformMatrix1, transformMatrix2;

        transformMatrix1 = transformMatrix2 =
        {{
            {1.f,0.f,0.f,0.f},
            {0.f,1.f,0.f,0.f},
            {0.f,0.f,0.f,0.f},
            {0.f,0.f,0.f,1.f}
        }};

        transformMatrix2.data[0][0] = +ct;
        transformMatrix2.data[1][1] = +ct;
        transformMatrix2.data[1][0] = +st;
        transformMatrix2.data[0][1] = -st;

        // Use this to place the texture upright for processing (object, detection, etc)
        transformProc1.setTransformMatrix(transformMatrix1); // don't rotate
        transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
        transformProc1.setOutputSize(0.25);

        gpgpuMngr->addProcToPipeline(&transformProc1);

        transformProc2.setInterpolation(interpolation);
        transformProc2.setTransformMatrix(transformMatrix2); // rotate output
        transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
        transformProc2.setOutputSize(1.0);

        gpgpuMngr->addProcToPipeline(&transformProc2);
    }
    else
    {
        std::cout << "GPU pipeline definition #%d not supported" << type << std::endl;
    }

    // create the display renderer with which we can directly render the output
    // to the screen via OpenGL
    outputDispRenderer = gpgpuMngr->createRenderDisplay(screenSize.width, screenSize.height, dispRenderOrientation);
    outputDispRenderer->setDisplayResolution(resolution, resolution);

    // reset this to call prepareForFramesOfSize again
    firstFrame = true;
    if (prepared)
    {
        prepared = false;
    }
}

GLuint OEGLGPGPUTest::getDisplayTexture() const
{
    return outputDispRenderer->getOutputTexId();
}

GLuint OEGLGPGPUTest::getInputTexture() const
{
    return gpgpuInputHandler->getInputTexId();
}

GLuint OEGLGPGPUTest::getOutputTexture() const
{
    return gpgpuInputHandler->getOutputTexId();
}

GLuint OEGLGPGPUTest::getLastShaderOutputTexture() const
{
    return gpgpuMngr->getOutputTexId();
}

cv::Size OEGLGPGPUTest::getOutputSize() const
{
    return cv::Size(gpgpuMngr->getOutputFrameW(), gpgpuMngr->getOutputFrameH());
}

void OEGLGPGPUTest::captureOutput(cv::Size size, void* pixelBuffer, bool useRawPixels, GLuint inputTexture, GLenum inputPixFormat)
{
    // when we get the first frame, prepare the system for the size of the incoming frames
    if (firstFrame)
    {
        frameSize = size;
        if(!screenSize.area())
        {
            screenSize = frameSize;
        }
        prepareForFrameOfSize(frameSize);

        outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);

        // YUV:
        yuv2RgbProc.init(frameSize.width, frameSize.height, 0, true); // TODO: NEW
        yuv2RgbProc.createFBOTex(false);

        firstFrame = false;
    }

    gpgpuInputHandler->setUseRawPixels(useRawPixels);

    // on each new frame, this will release the input buffers and textures, and prepare new ones
    // texture format must be GL_BGRA because this is one of the native camera formats (see initCam)

    if(inputPixFormat == 0)
    {
        // YUV: Special case NV12=>BGR
        auto manager = yuv2RgbProc.getMemTransferObj();
        manager->setUseRawPixels(true);
        manager->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);

        yuv2RgbProc.setTextures(manager->getLuminanceTexId(), manager->getChrominanceTexId());
        yuv2RgbProc.render();
        glFinish();

        inputTexture = yuv2RgbProc.getOutputTexId(); // will be used below
        gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, GL_NONE, nullptr);
    }
    else
    {
        gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);
    }

    // set the input texture id - we do not copy any data, we use the camera frame directly as texture!
    if (inputTexture)
    {
      gpgpuMngr->setInputTexId(inputTexture);
    }
    else
    {
      gpgpuMngr->setInputTexId(gpgpuInputHandler->getInputTexId());
    }

    // run processing pipeline
    gpgpuMngr->process();

#if 1
    if(frameHandler)
    {
        auto transfer = dynamic_cast<ogles_gpgpu::MemTransferOptimized *>(gpgpuMngr->getOutputMemTransfer());
        if(transfer)
        {
            MemTransferScopeLock data(transfer);
            cv::Size outSize(transformProc1.getOutFrameW(), transformProc1.getOutFrameH());
            cv::Mat frame(outSize.height, outSize.width, CV_8UC4, (void *)data.data());
            frameHandler(frame);
        }
    }
#endif

    std::cerr << "Skipping render..." << std::endl;
    return;

    // update the GL view to display the output directly
    outputDispRenderer->render();
}

void OEGLGPGPUTest::prepareForFrameOfSize(const cv::Size &size)
{
    float frameAspectRatio = size.width / size.height;

    fprintf(stderr, "camera frames are of size %dx%d (aspect %f)\n", (int)size.width, (int)size.height, frameAspectRatio);

    // prepare ogles_gpgpu for the incoming frame size
    // GL_NONE means that the input memory transfer object is NOT prepared
    // this will be done in captureOutput: on each new frame
#if __ANDROID__
    gpgpuMngr->prepare(size.width, size.height, true ? GL_RGBA : GL_NONE);
#else
    gpgpuMngr->prepare(size.width, size.height, true ? GL_BGRA : GL_NONE);
#endif
    gpgpuInputHandler = gpgpuMngr->getInputMemTransfer();

    // everything prepared
    prepared = true;
}

_GATHERER_GRAPHICS_END
<commit_msg>useRawPixels may be false<commit_after>#include "OGLESGPGPUTest.h"

#include "ogles_gpgpu/common/gl/memtransfer_optimized.h"

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>

#define INITIAL_PROC_TYPE 1

_GATHERER_GRAPHICS_BEGIN

class MemTransferScopeLock
{
public:
    MemTransferScopeLock(ogles_gpgpu::MemTransferOptimized *transfer) : transfer(transfer)
    {
        ptr = transfer->lockBufferAndGetPtr(ogles_gpgpu::BUF_TYPE_OUTPUT);
    }
    ~MemTransferScopeLock()
    {
        transfer->unlockBuffer(ogles_gpgpu::BUF_TYPE_OUTPUT);
    }
    const void *data() const { return ptr; }
    operator const void *() const { return ptr; }
protected:
    const void *ptr = 0;
    ogles_gpgpu::MemTransferOptimized *transfer = 0;
};

OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const float resolution)
: glContext(glContext)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationStd)
{
    initCam();
    initOGLESGPGPU(glContext);
}

OEGLGPGPUTest::OEGLGPGPUTest(void *glContext, const cv::Size &screenSize, const float resolution)
: glContext(glContext)
, screenSize(screenSize)
, resolution(resolution)
, dispRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored)
{
    initCam();
    initOGLESGPGPU(glContext);
}

OEGLGPGPUTest::~OEGLGPGPUTest()
{
    ogles_gpgpu::Core::destroy();
    gpgpuMngr = 0;
}

void OEGLGPGPUTest::initCam()
{
    /*
     * Some temporary code to test the optimized gpu to cpu frame handler.
     * This should be instantiated form a higher level (i.e., main.cpp)
     * but this class hasn't been allocated at that point yet.  This at
     * least supports testing of the concept.
     */

#define TEST_FRAME_HANDLER 0
#if TEST_FRAME_HANDLER
    frameHandler = [](const cv::Mat &frame)
    {
        std::stringstream ss;
        ss << getenv("HOME") << "/Documents/frame.png";
        cv::imwrite(ss.str(), frame);
    };
#endif
}

void OEGLGPGPUTest::initOGLESGPGPU(void* glContext)
{
    // get ogles_gpgpu::Core singleton instance
    gpgpuMngr = ogles_gpgpu::Core::getInstance();

    // enable iOS optimizations (fast texture access)
    ogles_gpgpu::Core::tryEnablePlatformOptimizations();

    // do not use mipmaps (will not work with NPOT images)
    gpgpuMngr->setUseMipmaps(false);

    // create the pipeline
    initGPUPipeline(5);

    outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);

    // initialize the pipeline (TODO)
    gpgpuMngr->init(glContext);
}

void OEGLGPGPUTest::setDisplaySize(int width, int height)
{
    outputDispRenderer->setOutputSize(width, height);
}

void OEGLGPGPUTest::initGPUPipeline(int type)
{
    if (selectedProcType == type) return;   // no change

    // reset the pipeline
    gpgpuMngr->reset();

    // create the pipeline
    if (type == 1)
    {
        gpgpuMngr->addProcToPipeline(&grayscaleProc);
        gpgpuMngr->addProcToPipeline(&adaptThreshProc);
    }
    else if (type == 2)
    {
        gpgpuMngr->addProcToPipeline(&grayscaleProc);
        gpgpuMngr->addProcToPipeline(&simpleThreshProc);
    }
    else if (type == 3)
    {
        gpgpuMngr->addProcToPipeline(&gaussProc);
    }
    else if (type == 4)
    {

#define USE_TRANSFORM1 1
#define USE_TRANSFORM2 0

#if USE_TRANSFORM1
        ogles_gpgpu::Mat44f transformMatrix =
        {{
            {1.f,0.f,0.f,0.f},
            {0.f,1.f,0.f,0.f},
            {0.f,0.f,0.f,0.f},
            {0.f,0.f,0.f,1.f}
        }};

        // Use this to place the texture upright for processing (object, detection, etc)
        transformProc1.setTransformMatrix(transformMatrix);
        transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
        transformProc1.setOutputSize(0.25);

        gpgpuMngr->addProcToPipeline(&transformProc1);
#endif

        gpgpuMngr->addProcToPipeline(&grayscaleProc);

#if USE_TRANSFORM2
        // Use this to place the texture back in the native orientation (and aspect ratio)
        // provided by the QML Camera since the QML VideoOutput object that displays the
        // frames is expecting that and I don't see a trivial way to work around that.
        // It seems we need to override either the VideoObject class or encapsulate this
        // native processing pipeline in some kind of ExtendedCamera qml object that
        // reports the size and orientation of the final processed texture.  Since this
        // is all on the GPU it may not matter much from a performance standpoint.
        //
        // TODO: investigate QT mechanism for avoiding this.
        transformProc2.setTransformMatrix(transformMatrix);
        transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
        transformProc2.setOutputSize(0.25);

        gpgpuMngr->addProcToPipeline(&transformProc2);
#endif
    }
    else if (type == 5) // upright transformation
    {
        auto interpolation = ogles_gpgpu::TransformProc::BICUBIC;

        transformProc1.setInterpolation(interpolation);
        float theta = 15.0 * M_PI / 180.0;
        float ct = std::cos(theta);
        float st = std::sin(theta);
        ogles_gpgpu::Mat44f transformMatrix1, transformMatrix2;

        transformMatrix1 = transformMatrix2 =
        {{
            {1.f,0.f,0.f,0.f},
            {0.f,1.f,0.f,0.f},
            {0.f,0.f,0.f,0.f},
            {0.f,0.f,0.f,1.f}
        }};

        transformMatrix2.data[0][0] = +ct;
        transformMatrix2.data[1][1] = +ct;
        transformMatrix2.data[1][0] = +st;
        transformMatrix2.data[0][1] = -st;

        // Use this to place the texture upright for processing (object, detection, etc)
        transformProc1.setTransformMatrix(transformMatrix1); // don't rotate
        transformProc1.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalMirrored);
        transformProc1.setOutputSize(0.25);

        gpgpuMngr->addProcToPipeline(&transformProc1);

        transformProc2.setInterpolation(interpolation);
        transformProc2.setTransformMatrix(transformMatrix2); // rotate output
        transformProc2.setOutputRenderOrientation(ogles_gpgpu::RenderOrientationDiagonalFlipped);
        transformProc2.setOutputSize(1.0);

        gpgpuMngr->addProcToPipeline(&transformProc2);
    }
    else
    {
        std::cout << "GPU pipeline definition #%d not supported" << type << std::endl;
    }

    // create the display renderer with which we can directly render the output
    // to the screen via OpenGL
    outputDispRenderer = gpgpuMngr->createRenderDisplay(screenSize.width, screenSize.height, dispRenderOrientation);
    outputDispRenderer->setDisplayResolution(resolution, resolution);

    // reset this to call prepareForFramesOfSize again
    firstFrame = true;
    if (prepared)
    {
        prepared = false;
    }
}

GLuint OEGLGPGPUTest::getDisplayTexture() const
{
    return outputDispRenderer->getOutputTexId();
}

GLuint OEGLGPGPUTest::getInputTexture() const
{
    return gpgpuInputHandler->getInputTexId();
}

GLuint OEGLGPGPUTest::getOutputTexture() const
{
    return gpgpuInputHandler->getOutputTexId();
}

GLuint OEGLGPGPUTest::getLastShaderOutputTexture() const
{
    return gpgpuMngr->getOutputTexId();
}

cv::Size OEGLGPGPUTest::getOutputSize() const
{
    return cv::Size(gpgpuMngr->getOutputFrameW(), gpgpuMngr->getOutputFrameH());
}

void OEGLGPGPUTest::captureOutput(cv::Size size, void* pixelBuffer, bool useRawPixels, GLuint inputTexture, GLenum inputPixFormat)
{
    // when we get the first frame, prepare the system for the size of the incoming frames
    if (firstFrame)
    {
        frameSize = size;
        if(!screenSize.area())
        {
            screenSize = frameSize;
        }
        prepareForFrameOfSize(frameSize);

        outputDispRenderer->setOutputSize(screenSize.width, screenSize.height);

        // YUV:
        yuv2RgbProc.init(frameSize.width, frameSize.height, 0, true); // TODO: NEW
        yuv2RgbProc.createFBOTex(false);

        firstFrame = false;
    }

    gpgpuInputHandler->setUseRawPixels(useRawPixels);

    // on each new frame, this will release the input buffers and textures, and prepare new ones
    // texture format must be GL_BGRA because this is one of the native camera formats (see initCam)

    if(inputPixFormat == 0)
    {
        // YUV: Special case NV12=>BGR
        auto manager = yuv2RgbProc.getMemTransferObj();
        if (useRawPixels)
        {
            manager->setUseRawPixels(true);
        }
        manager->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);

        yuv2RgbProc.setTextures(manager->getLuminanceTexId(), manager->getChrominanceTexId());
        yuv2RgbProc.render();
        glFinish();

        inputTexture = yuv2RgbProc.getOutputTexId(); // will be used below
        gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, GL_NONE, nullptr);
    }
    else
    {
        gpgpuInputHandler->prepareInput(frameSize.width, frameSize.height, inputPixFormat, pixelBuffer);
    }

    // set the input texture id - we do not copy any data, we use the camera frame directly as texture!
    if (inputTexture)
    {
      gpgpuMngr->setInputTexId(inputTexture);
    }
    else
    {
      gpgpuMngr->setInputTexId(gpgpuInputHandler->getInputTexId());
    }

    // run processing pipeline
    gpgpuMngr->process();

#if 1
    if(frameHandler)
    {
        auto transfer = dynamic_cast<ogles_gpgpu::MemTransferOptimized *>(gpgpuMngr->getOutputMemTransfer());
        if(transfer)
        {
            MemTransferScopeLock data(transfer);
            cv::Size outSize(transformProc1.getOutFrameW(), transformProc1.getOutFrameH());
            cv::Mat frame(outSize.height, outSize.width, CV_8UC4, (void *)data.data());
            frameHandler(frame);
        }
    }
#endif

    std::cerr << "Skipping render..." << std::endl;
    return;

    // update the GL view to display the output directly
    outputDispRenderer->render();
}

void OEGLGPGPUTest::prepareForFrameOfSize(const cv::Size &size)
{
    float frameAspectRatio = size.width / size.height;

    fprintf(stderr, "camera frames are of size %dx%d (aspect %f)\n", (int)size.width, (int)size.height, frameAspectRatio);

    // prepare ogles_gpgpu for the incoming frame size
    // GL_NONE means that the input memory transfer object is NOT prepared
    // this will be done in captureOutput: on each new frame
#if __ANDROID__
    gpgpuMngr->prepare(size.width, size.height, true ? GL_RGBA : GL_NONE);
#else
    gpgpuMngr->prepare(size.width, size.height, true ? GL_BGRA : GL_NONE);
#endif
    gpgpuInputHandler = gpgpuMngr->getInputMemTransfer();

    // everything prepared
    prepared = true;
}

_GATHERER_GRAPHICS_END
<|endoftext|>


<commit_before>#pragma once

#include <tuple>
#include <type_traits>
#include <limits>
#include <algorithm>
#include <initializer_list>

namespace kl {

using std::index_sequence;
using std::make_index_sequence;

template <typename T>
using make_tuple_indices =
    make_index_sequence<std::tuple_size_v<std::remove_reference_t<T>>>;

namespace tuple {

// Applies a function to given tuple
struct apply_fn
{
private:
    template <typename Tup, typename Fun, std::size_t... Is>
    static auto impl(Tup&& tup, Fun&& fun, index_sequence<Is...>) -> decltype(
        std::forward<Fun>(fun)((std::get<Is>(std::forward<Tup>(tup)))...))
    {
        return std::forward<Fun>(fun)(
            (std::get<Is>(std::forward<Tup>(tup)))...);
    }

public:
    template <typename Tup, typename Fun>
    static auto call(Tup&& tup, Fun&& fun)
        -> decltype(apply_fn::impl(std::forward<Tup>(tup),
                                   std::forward<Fun>(fun),
                                   make_tuple_indices<Tup>{}))
    {
        return apply_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
                              make_tuple_indices<Tup>{});
    }
};

struct for_each_fn
{
private:
    template <typename Tup, typename Fun, std::size_t... Is>
    static void impl(Tup&& tup, Fun&& fun, kl::index_sequence<Is...>)
    {
        using swallow = std::initializer_list<int>;
        (void)swallow{(fun(std::get<Is>(std::forward<Tup>(tup))), 0)...};
    }

public:
    template <typename Tup, typename Fun>
    static void call(Tup&& tup, Fun&& fun)
    {
        for_each_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
                          kl::make_tuple_indices<Tup>{});
    }
};

// Transforms tuple of dereferencable to tuple of references:
//   tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
//   tuple<int&, double&, const short&>
struct transform_ref_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static auto impl(Tup&& tup, index_sequence<Is...>) -> decltype(
        std::tuple<decltype(*(std::get<Is>(std::forward<Tup>(tup))))...>{
            (*std::get<Is>(std::forward<Tup>(tup)))...})
    {
        return std::tuple<decltype(*(std::get<Is>(std::forward<Tup>(tup))))...>{
            (*std::get<Is>(std::forward<Tup>(tup)))...};
    }

public:
    template <typename Tup>
    static auto call(Tup&& tup)
        -> decltype(transform_ref_fn::impl(std::forward<Tup>(tup),
                                           make_tuple_indices<Tup>{}))
    {
        return transform_ref_fn::impl(std::forward<Tup>(tup),
                                      make_tuple_indices<Tup>{});
    }
};

// Transforms tuple of dereferencable to tuple of dereferenced values:
//   tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
//   tuple<int, double, short>
struct transform_deref_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static auto impl(Tup&& tup, index_sequence<Is...>)
        -> decltype(std::make_tuple(*std::get<Is>(std::forward<Tup>(tup))...))
    {
        return std::make_tuple(*std::get<Is>(std::forward<Tup>(tup))...);
    }

public:
    template <typename Tup>
    static auto call(Tup&& tup)
        -> decltype(transform_deref_fn::impl(std::forward<Tup>(tup),
                                             make_tuple_indices<Tup>{}))
    {
        return transform_deref_fn::impl(std::forward<Tup>(tup),
                                        make_tuple_indices<Tup>{});
    }
};

// Checks for inequality with two given tuples. We AND instead of OR to
// support zipping Sequences with different size.
struct not_equal_fn
{
private:
    template <typename Tup>
    static bool impl(Tup&&, Tup&&)
    {
        return true;
    }

    template <std::size_t I, std::size_t... Is, typename Tup>
    static bool impl(Tup&& tup0, Tup&& tup1)
    {
        return std::get<I>(std::forward<Tup>(tup0)) !=
                   std::get<I>(std::forward<Tup>(tup1)) &&
               not_equal_fn::template impl<Is...>(std::forward<Tup>(tup0),
                                                  std::forward<Tup>(tup1));
    }

    template <typename Tup, std::size_t... Is>
    static bool impl2(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
    {
        return not_equal_fn::impl<Is...>(std::forward<Tup>(tup0),
                                         std::forward<Tup>(tup1));
    }

public:
    template <typename Tup>
    static bool call(Tup&& tup0, Tup&& tup1)
    {
        return not_equal_fn::impl2(std::forward<Tup>(tup0),
                                   std::forward<Tup>(tup1),
                                   make_tuple_indices<Tup>{});
    }
};

// Calculates minimum value of std::distance's on each pair of the tuples
struct distance_fn
{
private:
#if defined(_MSC_VER)
    template <typename T>
    static const T& (min)(const T& arg)
    {
        return arg;
    }

    template <typename T0, typename T1, typename... Ts>
    static const std::common_type_t<T0, T1, Ts...>&
        (min)(const T0& arg1, const T1& arg2, const Ts&... args)
    {
        return (arg1 < arg2) ? (min)(arg1, args...) : (min)(arg2, args...);
    }

    // This is faster on MSVC2015 than foldl-like with an accumulator
    template <typename Tup, std::size_t... Is>
    static std::ptrdiff_t impl2(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
    {
        return (distance_fn::min)(
            std::distance(std::get<Is>(std::forward<Tup>(tup0)),
                          std::get<Is>(std::forward<Tup>(tup1)))...);
    }
#else
    template <typename Tup>
    static std::ptrdiff_t impl(Tup&&, Tup&&, std::ptrdiff_t acc)
    {
        return acc;
    }

    template <std::size_t I, std::size_t... Is, typename Tup>
    static std::ptrdiff_t impl(Tup&& tup0, Tup&& tup1, std::ptrdiff_t acc)
    {
        return distance_fn::template impl<Is...>(
            std::forward<Tup>(tup0), std::forward<Tup>(tup1),
            (std::min)(acc,
                       std::distance(std::get<I>(std::forward<Tup>(tup0)),
                                     std::get<I>(std::forward<Tup>(tup1)))));
    }

    template <typename Tup, std::size_t... Is>
    static std::ptrdiff_t impl2(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
    {
        return distance_fn::impl<Is...>(
            std::forward<Tup>(tup0), std::forward<Tup>(tup1),
            std::numeric_limits<std::ptrdiff_t>::max());
    }
#endif

public:
    template <typename Tup>
    static std::ptrdiff_t call(Tup&& tup0, Tup&& tup1)
    {
        return distance_fn::impl2(std::forward<Tup>(tup0),
                                  std::forward<Tup>(tup1),
                                  make_tuple_indices<Tup>{});
    }
};

// Checks if all tuple elements are convertible to true
struct all_true_fn
{
private:
    template <typename Tup>
    static bool impl(Tup&&)
    {
        return true;
    }

    template <std::size_t I, std::size_t... Is, typename Tup>
    static bool impl(Tup&& tup)
    {
        return !!(std::get<I>(std::forward<Tup>(tup))) &&
               all_true_fn::template impl<Is...>(std::forward<Tup>(tup));
    }

    template <typename Tup, std::size_t... Is>
    static bool impl2(Tup&& tup, index_sequence<Is...>)
    {
        return all_true_fn::impl<Is...>(std::forward<Tup>(tup));
    }

public:
    template <typename Tup>
    static bool call(Tup&& tup)
    {
        return all_true_fn::impl2(std::forward<Tup>(tup),
                                  make_tuple_indices<Tup>{});
    }
};
} // namespace tuple
} // namespace kl
<commit_msg>Simplify tuple-related utilities using fold expressions<commit_after>#pragma once

#include <iterator>
#include <limits>
#include <tuple>
#include <type_traits>

namespace kl {

using std::index_sequence;
using std::make_index_sequence;

template <typename T>
using make_tuple_indices =
    make_index_sequence<std::tuple_size_v<std::remove_reference_t<T>>>;

namespace tuple {

// Applies a function to given tuple
struct apply_fn
{
private:
    template <typename Tup, typename Fun, std::size_t... Is>
    static decltype(auto) impl(Tup&& tup, Fun&& fun, index_sequence<Is...>)
    {
        return std::forward<Fun>(fun)(
            (std::get<Is>(std::forward<Tup>(tup)))...);
    }

public:
    template <typename Tup, typename Fun>
    static decltype(auto) call(Tup&& tup, Fun&& fun)
    {
        return apply_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
                              make_tuple_indices<Tup>{});
    }
};

struct for_each_fn
{
private:
    template <typename Tup, typename Fun, std::size_t... Is>
    static void impl(Tup&& tup, Fun&& fun, index_sequence<Is...>)
    {
        (..., fun(std::get<Is>(std::forward<Tup>(tup))));
    }

public:
    template <typename Tup, typename Fun>
    static void call(Tup&& tup, Fun&& fun)
    {
        for_each_fn::impl(std::forward<Tup>(tup), std::forward<Fun>(fun),
                          make_tuple_indices<Tup>{});
    }
};

// Transforms tuple of dereferencable to tuple of references:
//   tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
//   tuple<int&, double&, const short&>
struct transform_ref_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static auto impl(Tup&& tup, index_sequence<Is...>)
    {
        return std::tuple<decltype(*(std::get<Is>(std::forward<Tup>(tup))))...>{
            (*std::get<Is>(std::forward<Tup>(tup)))...};
    }

public:
    template <typename Tup>
    static auto call(Tup&& tup)
    {
        return transform_ref_fn::impl(std::forward<Tup>(tup),
                                      make_tuple_indices<Tup>{});
    }
};

// Transforms tuple of dereferencable to tuple of dereferenced values:
//   tuple<int*, std::optional<double>, std::vector<short>::const_iterator> ->
//   tuple<int, double, short>
struct transform_deref_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static auto impl(Tup&& tup, index_sequence<Is...>)
    {
        return std::make_tuple(*std::get<Is>(std::forward<Tup>(tup))...);
    }

public:
    template <typename Tup>
    static auto call(Tup&& tup)
    {
        return transform_deref_fn::impl(std::forward<Tup>(tup),
                                        make_tuple_indices<Tup>{});
    }
};

// Checks for inequality with two given tuples. We AND instead of OR to
// support zipping Sequences with different size.
struct not_equal_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static bool impl(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
    {
        return (... && (std::get<Is>(std::forward<Tup>(tup0)) !=
                        std::get<Is>(std::forward<Tup>(tup1))));
    }

public:
    template <typename Tup>
    static bool call(Tup&& tup0, Tup&& tup1)
    {
        return not_equal_fn::impl(std::forward<Tup>(tup0),
                                  std::forward<Tup>(tup1),
                                  make_tuple_indices<Tup>{});
    }
};

// Calculates minimum value of std::distance's on each pair of the tuples
struct distance_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static std::ptrdiff_t impl(Tup&& tup0, Tup&& tup1, index_sequence<Is...>)
    {
        static_assert(sizeof...(Is) > 0);

        std::ptrdiff_t min{std::numeric_limits<std::ptrdiff_t>::max()}, dist{};

        return (
            (min = (dist = std::distance(std::get<Is>(std::forward<Tup>(tup0)),
                                         std::get<Is>(std::forward<Tup>(tup1))),
                    dist < min ? dist : min)),
            ...);
    }

public:
    template <typename Tup>
    static std::ptrdiff_t call(Tup&& tup0, Tup&& tup1)
    {
        return distance_fn::impl(std::forward<Tup>(tup0),
                                 std::forward<Tup>(tup1),
                                 make_tuple_indices<Tup>{});
    }
};

// Checks if all tuple elements are convertible to true
struct all_true_fn
{
private:
    template <typename Tup, std::size_t... Is>
    static bool impl(Tup&& tup, index_sequence<Is...>)
    {
        return (... && std::get<Is>(std::forward<Tup>(tup)));
    }

public:
    template <typename Tup>
    static bool call(Tup&& tup)
    {
        return all_true_fn::impl(std::forward<Tup>(tup),
                                 make_tuple_indices<Tup>{});
    }
};
} // namespace tuple
} // namespace kl
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.
//
// Author: nadavs@google.com <Nadav Samet>

#ifndef RPCZ_RPC_H
#define RPCZ_RPC_H

#include <stdexcept>
#include <string>

#include "rpcz/macros.hpp"
#include "rpcz/rpcz.pb.h"

#ifdef WIN32
// winerror.h contains #define NO_ERROR 0
#undef NO_ERROR
#endif

namespace rpcz {

typedef rpc_response_header::status_code status_code;
typedef rpc_response_header::application_error_code application_error_code;

namespace status {
static const status_code INACTIVE = rpc_response_header::INACTIVE;
static const status_code ACTIVE = rpc_response_header::ACTIVE;
static const status_code OK = rpc_response_header::OK;
static const status_code CANCELLED = rpc_response_header::CANCELLED;
static const status_code APPLICATION_ERROR = rpc_response_header::APPLICATION_ERROR;
static const status_code DEADLINE_EXCEEDED = rpc_response_header::DEADLINE_EXCEEDED;
static const status_code TERMINATED = rpc_response_header::TERMINATED;
}  // namespace status
namespace application_error {
static const application_error_code NO_ERROR = rpc_response_header::NO_ERROR;
static const application_error_code INVALID_HEADER = rpc_response_header::INVALID_HEADER;
static const application_error_code NO_SUCH_SERVICE = rpc_response_header::NO_SUCH_SERVICE;
static const application_error_code NO_SUCH_METHOD = rpc_response_header::NO_SUCH_METHOD;
static const application_error_code INVALID_MESSAGE = rpc_response_header::INVALID_MESSAGE;
static const application_error_code METHOD_NOT_IMPLEMENTED = rpc_response_header::METHOD_NOT_IMPLEMENTED;
}  // namespace application_error

class sync_event;

class rpc {
 public:
  rpc();

  ~rpc();

  inline bool ok() const {
    return get_status() == status::OK;
  }

  status_code get_status() const {
    return status_;
  }

  inline std::string get_error_message() const {
    return error_message_;
  }

  inline int get_application_error_code() const {
    return application_error_code_;
  }

  inline int64 get_deadline_ms() const {
    return deadline_ms_;
  }

  inline void set_deadline_ms(int deadline_ms) {
    deadline_ms_ = deadline_ms;
  }

  void set_failed(int application_error_code, const std::string& message);

  int wait();

  std::string to_string() const;

 private:
  void set_status(status_code status);

  status_code status_;
  std::string error_message_;
  int application_error_code_;
  int64 deadline_ms_;
  scoped_ptr<sync_event> sync_event_;

  friend class rpc_channel_impl;
  friend class server_channel_impl;
  DISALLOW_COPY_AND_ASSIGN(rpc);
};

class rpc_error : public std::runtime_error {
 public:
  explicit rpc_error(const rpc& rpc_)
      : std::runtime_error(rpc_.to_string()),
        status_(rpc_.get_status()),
        error_message_(rpc_.get_error_message()),
        application_error_code_(rpc_.get_application_error_code()) {}

  virtual ~rpc_error() throw() {}

  status_code get_status() const {
    return status_;
  }

  inline std::string get_error_message() const {
    return error_message_;
  }

  inline int get_application_error_code() const {
    return application_error_code_;
  }

 private:
  status_code status_;
  std::string error_message_;
  int application_error_code_;
};

class invalid_message_error : public std::runtime_error {
 public:
  explicit invalid_message_error(const std::string& message)
      : std::runtime_error(message) {}
};
}  // namespace
#endif
<commit_msg>resolve WIN32 compile errors cause by NO_ERROR conflict in pb.h file<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.
//
// Author: nadavs@google.com <Nadav Samet>

#ifndef RPCZ_RPC_H
#define RPCZ_RPC_H

#include <stdexcept>
#include <string>

#ifdef WIN32
// winerror.h contains #define NO_ERROR 0
#undef NO_ERROR
#endif

#include "rpcz/macros.hpp"
#include "rpcz/rpcz.pb.h"

namespace rpcz {

typedef rpc_response_header::status_code status_code;
typedef rpc_response_header::application_error_code application_error_code;

namespace status {
static const status_code INACTIVE = rpc_response_header::INACTIVE;
static const status_code ACTIVE = rpc_response_header::ACTIVE;
static const status_code OK = rpc_response_header::OK;
static const status_code CANCELLED = rpc_response_header::CANCELLED;
static const status_code APPLICATION_ERROR = rpc_response_header::APPLICATION_ERROR;
static const status_code DEADLINE_EXCEEDED = rpc_response_header::DEADLINE_EXCEEDED;
static const status_code TERMINATED = rpc_response_header::TERMINATED;
}  // namespace status
namespace application_error {
static const application_error_code NO_ERROR = rpc_response_header::NO_ERROR;
static const application_error_code INVALID_HEADER = rpc_response_header::INVALID_HEADER;
static const application_error_code NO_SUCH_SERVICE = rpc_response_header::NO_SUCH_SERVICE;
static const application_error_code NO_SUCH_METHOD = rpc_response_header::NO_SUCH_METHOD;
static const application_error_code INVALID_MESSAGE = rpc_response_header::INVALID_MESSAGE;
static const application_error_code METHOD_NOT_IMPLEMENTED = rpc_response_header::METHOD_NOT_IMPLEMENTED;
}  // namespace application_error

class sync_event;

class rpc {
 public:
  rpc();

  ~rpc();

  inline bool ok() const {
    return get_status() == status::OK;
  }

  status_code get_status() const {
    return status_;
  }

  inline std::string get_error_message() const {
    return error_message_;
  }

  inline int get_application_error_code() const {
    return application_error_code_;
  }

  inline int64 get_deadline_ms() const {
    return deadline_ms_;
  }

  inline void set_deadline_ms(int deadline_ms) {
    deadline_ms_ = deadline_ms;
  }

  void set_failed(int application_error_code, const std::string& message);

  int wait();

  std::string to_string() const;

 private:
  void set_status(status_code status);

  status_code status_;
  std::string error_message_;
  int application_error_code_;
  int64 deadline_ms_;
  scoped_ptr<sync_event> sync_event_;

  friend class rpc_channel_impl;
  friend class server_channel_impl;
  DISALLOW_COPY_AND_ASSIGN(rpc);
};

class rpc_error : public std::runtime_error {
 public:
  explicit rpc_error(const rpc& rpc_)
      : std::runtime_error(rpc_.to_string()),
        status_(rpc_.get_status()),
        error_message_(rpc_.get_error_message()),
        application_error_code_(rpc_.get_application_error_code()) {}

  virtual ~rpc_error() throw() {}

  status_code get_status() const {
    return status_;
  }

  inline std::string get_error_message() const {
    return error_message_;
  }

  inline int get_application_error_code() const {
    return application_error_code_;
  }

 private:
  status_code status_;
  std::string error_message_;
  int application_error_code_;
};

class invalid_message_error : public std::runtime_error {
 public:
  explicit invalid_message_error(const std::string& message)
      : std::runtime_error(message) {}
};
}  // namespace
#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2015] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP

#include <realm/column.hpp>

namespace realm {

struct Timestamp {
    Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
    {
        REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
    }
    explicit Timestamp(const null&) : m_is_null(true) { }
    Timestamp() : Timestamp(null()) { }

    bool is_null() const { return m_is_null; }

    // Note that nullability is handled by query system. These operators are only invoked for non-null dates.
    bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
    bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
    bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
    bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
    bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
    bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
    Timestamp& operator=(const Timestamp& rhs) = default;

    template<class Ch, class Tr>
    friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);

    int64_t m_seconds;
    uint32_t m_nanoseconds;
    bool m_is_null;

    static constexpr uint32_t nanoseconds_per_second = 1000000000;
};

template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
    out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
    return out;
}

// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple, public ColumnTemplate<Timestamp> {
public:
    TimestampColumn(Allocator& alloc, ref_type ref);
    ~TimestampColumn() noexcept override;

    static ref_type create(Allocator& alloc, size_t size = 0);

    /// Get the number of entries in this column. This operation is relatively
    /// slow.
    size_t size() const noexcept override;
    /// Whether or not this column is nullable.
    bool is_nullable() const noexcept override;
    /// Whether or not the value at \a row_ndx is NULL. If the column is not
    /// nullable, always returns false.
    bool is_null(size_t row_ndx) const noexcept override;
    /// Sets the value at \a row_ndx to be NULL.
    /// \throw LogicError Thrown if this column is not nullable.
    void set_null(size_t row_ndx) override;
    void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
    void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
                    bool broken_reciprocal_backlinks) override;
    void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
                            bool broken_reciprocal_backlinks) override;
    void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
    void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
    void destroy() noexcept override;

    bool has_search_index() const noexcept final { return bool(m_search_index); }
    StringIndex* get_search_index() noexcept final { return m_search_index.get(); }
    void destroy_search_index() noexcept override;
    void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
            bool allow_duplicate_values) final;
    void populate_search_index();
    StringIndex* create_search_index() override;

    StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
    ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
    void update_from_parent(size_t old_baseline) noexcept override;
    void set_ndx_in_parent(size_t ndx) noexcept override;
    void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
    void verify() const override;
    void to_dot(std::ostream&, StringData title = StringData()) const override;
    void do_dump_node_structure(std::ostream&, int level) const override;
    void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
    void add(const Timestamp& ts = Timestamp{});
    Timestamp get(size_t row_ndx) const noexcept;
    Timestamp get_val(size_t row_ndx) const noexcept override { return get(row_ndx); }
    void set(size_t row_ndx, const Timestamp& ts);
    bool compare(const TimestampColumn& c) const noexcept;

    Timestamp maximum(size_t& result_index) const;
    Timestamp minimum(size_t& result_index) const;
    size_t count(Timestamp) const;
    void erase(size_t row_ndx, bool is_last);

    template <class Condition> size_t find(Timestamp value, size_t begin, size_t end) const noexcept
    {
        // FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match check
        // nanoseconds, etc, etc, etc. Lots of possibilities. Below code is naive and slow but works.

        Condition cond;
        for (size_t t = begin; t < end; t++) {
            Timestamp ts = get(t);
            if (cond(ts, value, ts.is_null(), value.is_null()))
                return t;
        }
        return npos;
    }

    typedef Timestamp value_type;

private:
    std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
    std::unique_ptr<BpTree<int64_t>> m_nanoseconds;

    std::unique_ptr<StringIndex> m_search_index;

    template<class BT>
    class CreateHandler;

    template <class Condition> Timestamp minmax(size_t& result_index) const noexcept
    {
        // Condition is realm::Greater for maximum and realm::Less for minimum.
        Timestamp best;
        result_index = npos;

        if (size() > 0) {
            best = get(0);
            result_index = 0;
        }

        for (size_t i = 0; i < size(); ++i) {
            if (Condition()(get(i), best, get(i).is_null(), best.is_null())) {
                best = get(i);
                result_index = i;
            }
        }
        return best;
    }
};

} // namespace realm

#endif // REALM_COLUMN_TIMESTAMP_HPP
<commit_msg>Whitespace fixes<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2015] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_COLUMN_TIMESTAMP_HPP
#define REALM_COLUMN_TIMESTAMP_HPP

#include <realm/column.hpp>

namespace realm {

struct Timestamp {
    Timestamp(int64_t seconds, uint32_t nanoseconds) : m_seconds(seconds), m_nanoseconds(nanoseconds), m_is_null(false)
    {
        REALM_ASSERT_3(nanoseconds, <, nanoseconds_per_second);
    }
    explicit Timestamp(const null&) : m_is_null(true) { }
    Timestamp() : Timestamp(null()) { }

    bool is_null() const { return m_is_null; }

    // Note that nullability is handled by query system. These operators are only invoked for non-null dates.
    bool operator==(const Timestamp& rhs) const { return m_seconds == rhs.m_seconds && m_nanoseconds == rhs.m_nanoseconds; }
    bool operator!=(const Timestamp& rhs) const { return m_seconds != rhs.m_seconds || m_nanoseconds != rhs.m_nanoseconds; }
    bool operator>(const Timestamp& rhs) const { return (m_seconds > rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds > rhs.m_nanoseconds); }
    bool operator<(const Timestamp& rhs) const { return (m_seconds < rhs.m_seconds) || (m_seconds == rhs.m_seconds && m_nanoseconds < rhs.m_nanoseconds); }
    bool operator<=(const Timestamp& rhs) const { return *this < rhs || *this == rhs; }
    bool operator>=(const Timestamp& rhs) const { return *this > rhs || *this == rhs; }
    Timestamp& operator=(const Timestamp& rhs) = default;

    template<class Ch, class Tr>
    friend std::basic_ostream<Ch, Tr>& operator<<(std::basic_ostream<Ch, Tr>& out, const Timestamp&);

    int64_t m_seconds;
    uint32_t m_nanoseconds;
    bool m_is_null;

    static constexpr uint32_t nanoseconds_per_second = 1000000000;
};

template<class C, class T>
inline std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& out, const Timestamp& d)
{
    out << "Timestamp(" << d.m_seconds << ", " << d.m_nanoseconds << ")";
    return out;
}

// Inherits from ColumnTemplate to get a compare_values() that can be called without knowing the
// column type
class TimestampColumn : public ColumnBaseSimple, public ColumnTemplate<Timestamp> {
public:
    TimestampColumn(Allocator& alloc, ref_type ref);
    ~TimestampColumn() noexcept override;

    static ref_type create(Allocator& alloc, size_t size = 0);

    /// Get the number of entries in this column. This operation is relatively
    /// slow.
    size_t size() const noexcept override;
    /// Whether or not this column is nullable.
    bool is_nullable() const noexcept override;
    /// Whether or not the value at \a row_ndx is NULL. If the column is not
    /// nullable, always returns false.
    bool is_null(size_t row_ndx) const noexcept override;
    /// Sets the value at \a row_ndx to be NULL.
    /// \throw LogicError Thrown if this column is not nullable.
    void set_null(size_t row_ndx) override;
    void insert_rows(size_t row_ndx, size_t num_rows_to_insert, size_t prior_num_rows, bool nullable) override;
    void erase_rows(size_t row_ndx, size_t num_rows_to_erase, size_t prior_num_rows,
                    bool broken_reciprocal_backlinks) override;
    void move_last_row_over(size_t row_ndx, size_t prior_num_rows,
                            bool broken_reciprocal_backlinks) override;
    void clear(size_t num_rows, bool broken_reciprocal_backlinks) override;
    void swap_rows(size_t row_ndx_1, size_t row_ndx_2) override;
    void destroy() noexcept override;

    bool has_search_index() const noexcept final { return bool(m_search_index); }
    StringIndex* get_search_index() noexcept final { return m_search_index.get(); }
    void destroy_search_index() noexcept override;
    void set_search_index_ref(ref_type ref, ArrayParent* parent, size_t ndx_in_parent,
            bool allow_duplicate_values) final;
    void populate_search_index();
    StringIndex* create_search_index() override;

    StringData get_index_data(size_t, StringIndex::StringConversionBuffer& buffer) const noexcept override;
    ref_type write(size_t slice_offset, size_t slice_size, size_t table_size, _impl::OutputStream&) const override;
    void update_from_parent(size_t old_baseline) noexcept override;
    void set_ndx_in_parent(size_t ndx) noexcept override;
    void refresh_accessor_tree(size_t new_col_ndx, const Spec&) override;
#ifdef REALM_DEBUG
    void verify() const override;
    void to_dot(std::ostream&, StringData title = StringData()) const override;
    void do_dump_node_structure(std::ostream&, int level) const override;
    void leaf_to_dot(MemRef, ArrayParent*, size_t ndx_in_parent, std::ostream&) const override;
#endif
    void add(const Timestamp& ts = Timestamp{});
    Timestamp get(size_t row_ndx) const noexcept;
    Timestamp get_val(size_t row_ndx) const noexcept override { return get(row_ndx); }
    void set(size_t row_ndx, const Timestamp& ts);
    bool compare(const TimestampColumn& c) const noexcept;

    Timestamp maximum(size_t& result_index) const;
    Timestamp minimum(size_t& result_index) const;
    size_t count(Timestamp) const;
    void erase(size_t row_ndx, bool is_last);

    template <class Condition>
    size_t find(Timestamp value, size_t begin, size_t end) const noexcept
    {
        // FIXME: Here we can do all sorts of clever optimizations. Use bithack-search on seconds, then for each match check
        // nanoseconds, etc, etc, etc. Lots of possibilities. Below code is naive and slow but works.

        Condition cond;
        for (size_t t = begin; t < end; t++) {
            Timestamp ts = get(t);
            if (cond(ts, value, ts.is_null(), value.is_null()))
                return t;
        }
        return npos;
    }

    typedef Timestamp value_type;

private:
    std::unique_ptr<BpTree<util::Optional<int64_t>>> m_seconds;
    std::unique_ptr<BpTree<int64_t>> m_nanoseconds;

    std::unique_ptr<StringIndex> m_search_index;

    template<class BT>
    class CreateHandler;

    template <class Condition>
    Timestamp minmax(size_t& result_index) const noexcept
    {
        // Condition is realm::Greater for maximum and realm::Less for minimum.
        Timestamp best;
        result_index = npos;

        if (size() > 0) {
            best = get(0);
            result_index = 0;
        }

        for (size_t i = 0; i < size(); ++i) {
            if (Condition()(get(i), best, get(i).is_null(), best.is_null())) {
                best = get(i);
                result_index = i;
            }
        }
        return best;
    }
};

} // namespace realm

#endif // REALM_COLUMN_TIMESTAMP_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_UTIL_FILE_MAPPER_HPP
#define REALM_UTIL_FILE_MAPPER_HPP

#include <realm/util/file.hpp>

namespace realm {
namespace util {

void *mmap(int fd, size_t size, File::AccessMode access, std::size_t offset, const char *encryption_key);
void munmap(void *addr, size_t size) REALM_NOEXCEPT;
void* mremap(int fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size);
void msync(void *addr, size_t size);

File::SizeType encrypted_size_to_data_size(File::SizeType size) REALM_NOEXCEPT;
File::SizeType data_size_to_encrypted_size(File::SizeType size) REALM_NOEXCEPT;
size_t round_up_to_page_size(size_t size) REALM_NOEXCEPT;

}
}
#endif
<commit_msg>removed std::<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#ifndef REALM_UTIL_FILE_MAPPER_HPP
#define REALM_UTIL_FILE_MAPPER_HPP

#include <realm/util/file.hpp>

namespace realm {
namespace util {

void *mmap(int fd, size_t size, File::AccessMode access, size_t offset, const char *encryption_key);
void munmap(void *addr, size_t size) REALM_NOEXCEPT;
void* mremap(int fd, size_t file_offset, void* old_addr, size_t old_size, File::AccessMode a, size_t new_size);
void msync(void *addr, size_t size);

File::SizeType encrypted_size_to_data_size(File::SizeType size) REALM_NOEXCEPT;
File::SizeType data_size_to_encrypted_size(File::SizeType size) REALM_NOEXCEPT;
size_t round_up_to_page_size(size_t size) REALM_NOEXCEPT;

}
}
#endif
<|endoftext|>