<commit_before>#pragma once

#include <ostream>
#include "athena/Types.hpp"

#define FMT_STRING_ALIAS 1
#define FMT_ENFORCE_COMPILE_STRING 1
#define FMT_USE_GRISU 0
#include <fmt/format.h>

#ifdef _MSC_VER
#pragma warning(disable : 4996)

#if defined(WINAPI_FAMILY) && WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP
#define WINDOWS_STORE 1
#else
#define WINDOWS_STORE 0
#endif

#include <sys/stat.h>

#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)
#endif

#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
#endif

#if !defined(S_ISLNK)
#define S_ISLNK(m) 0
#endif

#define PRISize "Iu"

#else

#define PRISize "zu"

#endif
// clang-format off
#ifndef AT_PRETTY_FUNCTION
#   if defined(__PRETTY_FUNCTION__) || defined(__GNUC__)
#       define AT_PRETTY_FUNCTION __PRETTY_FUNCTION__
#   elif defined(__FUNCSIG__)
#       define AT_PRETTY_FUNCTION __FUNCSIG__
#   elif defined(__FUNCTION__)
#       define AT_PRETTY_FUNCTION __FUNCTION__
#   elif defined(__FUNC__)
#       define AT_PRETTY_FUNCTION __FUNC__
#   elif defined(__func__)
#       define AT_PRETTY_FUNCTION __func__
#   else
#       define AT_PRETTY_FUNCTION "<unknown>"
#   endif
#endif
// clang-format on

#if defined(GEKKO) || defined(__SWITCH__)
#include "gekko_support.h"
typedef struct stat atStat64_t;
#define atStat64 stat
#elif _WIN32
typedef struct _stat64 atStat64_t;
#define atStat64 _stat64
#elif __APPLE__ || __FreeBSD__
typedef struct stat atStat64_t;
#define atStat64 stat
#else
typedef struct stat64 atStat64_t;
#define atStat64 stat64
#endif

#ifndef BLOCKSZ
#define BLOCKSZ 512
#endif

#define ROUND_UP_256(val) (((val) + 255) & ~255)
#define ROUND_UP_64(val) (((val) + 63) & ~63)
#define ROUND_UP_32(val) (((val) + 31) & ~31)
#define ROUND_UP_16(val) (((val) + 15) & ~15)
#define ROUND_UP_8(val) (((val) + 7) & ~7)
#define ROUND_UP_4(val) (((val) + 3) & ~3)

#define _XSTR(s) _STR(s)
#define _STR(s) #s

#ifndef ENABLE_BITWISE_ENUM
#define ENABLE_BITWISE_ENUM(type)                                                                                \
  constexpr type operator|(type a, type b) noexcept {                                                                  \
    using T = std::underlying_type_t<type>;                                                                            \
    return type(static_cast<T>(a) | static_cast<T>(b));                                                                \
  }                                                                                \
  constexpr type operator&(type a, type b) noexcept {                                                                  \
    using T = std::underlying_type_t<type>;                                                                            \
    return type(static_cast<T>(a) & static_cast<T>(b));                                                                \
  }                                                                                \
  constexpr type& operator|=(type& a, type b) noexcept {                                                               \
    using T = std::underlying_type_t<type>;                                                                            \
    a = type(static_cast<T>(a) | static_cast<T>(b));                                                                   \
    return a;                                                                                \
  }                                                                                \
  constexpr type& operator&=(type& a, type b) noexcept {                                                               \
    using T = std::underlying_type_t<type>;                                                                            \
    a = type(static_cast<T>(a) & static_cast<T>(b));                                                                   \
    return a;                                                                                \
  }                                                                                \
  constexpr type operator~(type key) noexcept {                                                                        \
    using T = std::underlying_type_t<type>;                                                                            \
    return type(~static_cast<T>(key));                                                                                \
  }                                                                                \
  constexpr bool True(type key) noexcept {                                                                             \
    using T = std::underlying_type_t<type>;                                                                            \
    return static_cast<T>(key) != 0;                                                                                \
  }                                                                                \
  constexpr bool False(type key) noexcept {                                                                            \
    using T = std::underlying_type_t<type>;                                                                            \
    return static_cast<T>(key) == 0;                                                                                \
  }
#endif

namespace athena {
namespace error {
enum class Level { Message, Warning, Error, Fatal };
}
enum class SeekOrigin { Begin, Current, End };

enum class Endian { Little, Big };

namespace io {
template <Endian DNAE>
struct DNA;
template <Endian DNAE>
struct DNAV;

template <class T>
using __IsDNARecord = std::disjunction<std::is_base_of<DNA<Endian::Big>, T>, std::is_base_of<DNA<Endian::Little>, T>>;
template <class T>
constexpr bool __IsDNARecord_v = __IsDNARecord<T>::value;

template <class T>
using __IsDNAVRecord =
    std::disjunction<std::is_base_of<DNAV<Endian::Big>, T>, std::is_base_of<DNAV<Endian::Little>, T>>;
template <class T>
constexpr bool __IsDNAVRecord_v = __IsDNAVRecord<T>::value;
} // namespace io
} // namespace athena

typedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* /*file*/, const char*, int /*line*/,
                                    fmt::string_view fmt, fmt::format_args args);

atEXCEPTION_HANDLER atGetExceptionHandler();
/**
 * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,
 * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.
 */
void atSetExceptionHandler(atEXCEPTION_HANDLER func);

std::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);
std::ostream& operator<<(std::ostream& os, const athena::Endian& endian);

template <typename First, typename... Rest>
constexpr auto __FIRST_ARG__(First first, Rest...) { return first; }
template <typename S, typename... Args>
auto __make_args_checked__(const S& format_str, Args&&... args) {
  return fmt::internal::make_args_checked<Args...>(format_str, std::forward<Args>(args)...);
}

#ifndef NDEBUG
#define atDebug(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),     \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)
#else
#define atDebug(...)
#endif

#define atMessage(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),     \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)

#define atWarning(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler) {                                                                                \
      __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),     \
                __make_args_checked__(__VA_ARGS__));                                                                   \
    }                                                                                \
  } while (0)

#define atError(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),       \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)

#define atFatal(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),       \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)
<commit_msg>Global: Remove compatibility formatting define for size_t<commit_after>#pragma once

#include <ostream>
#include "athena/Types.hpp"

#define FMT_STRING_ALIAS 1
#define FMT_ENFORCE_COMPILE_STRING 1
#define FMT_USE_GRISU 0
#include <fmt/format.h>

#ifdef _MSC_VER
#pragma warning(disable : 4996)

#if defined(WINAPI_FAMILY) && WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP
#define WINDOWS_STORE 1
#else
#define WINDOWS_STORE 0
#endif

#include <sys/stat.h>

#if !defined(S_ISREG) && defined(S_IFMT) && defined(S_IFREG)
#define S_ISREG(m) (((m)&S_IFMT) == S_IFREG)
#endif

#if !defined(S_ISDIR) && defined(S_IFMT) && defined(S_IFDIR)
#define S_ISDIR(m) (((m)&S_IFMT) == S_IFDIR)
#endif

#if !defined(S_ISLNK)
#define S_ISLNK(m) 0
#endif
#endif // _MSC_VER

// clang-format off
#ifndef AT_PRETTY_FUNCTION
#   if defined(__PRETTY_FUNCTION__) || defined(__GNUC__)
#       define AT_PRETTY_FUNCTION __PRETTY_FUNCTION__
#   elif defined(__FUNCSIG__)
#       define AT_PRETTY_FUNCTION __FUNCSIG__
#   elif defined(__FUNCTION__)
#       define AT_PRETTY_FUNCTION __FUNCTION__
#   elif defined(__FUNC__)
#       define AT_PRETTY_FUNCTION __FUNC__
#   elif defined(__func__)
#       define AT_PRETTY_FUNCTION __func__
#   else
#       define AT_PRETTY_FUNCTION "<unknown>"
#   endif
#endif
// clang-format on

#if defined(GEKKO) || defined(__SWITCH__)
#include "gekko_support.h"
typedef struct stat atStat64_t;
#define atStat64 stat
#elif _WIN32
typedef struct _stat64 atStat64_t;
#define atStat64 _stat64
#elif __APPLE__ || __FreeBSD__
typedef struct stat atStat64_t;
#define atStat64 stat
#else
typedef struct stat64 atStat64_t;
#define atStat64 stat64
#endif

#ifndef BLOCKSZ
#define BLOCKSZ 512
#endif

#define ROUND_UP_256(val) (((val) + 255) & ~255)
#define ROUND_UP_64(val) (((val) + 63) & ~63)
#define ROUND_UP_32(val) (((val) + 31) & ~31)
#define ROUND_UP_16(val) (((val) + 15) & ~15)
#define ROUND_UP_8(val) (((val) + 7) & ~7)
#define ROUND_UP_4(val) (((val) + 3) & ~3)

#define _XSTR(s) _STR(s)
#define _STR(s) #s

#ifndef ENABLE_BITWISE_ENUM
#define ENABLE_BITWISE_ENUM(type)                                                                                \
  constexpr type operator|(type a, type b) noexcept {                                                                  \
    using T = std::underlying_type_t<type>;                                                                            \
    return type(static_cast<T>(a) | static_cast<T>(b));                                                                \
  }                                                                                \
  constexpr type operator&(type a, type b) noexcept {                                                                  \
    using T = std::underlying_type_t<type>;                                                                            \
    return type(static_cast<T>(a) & static_cast<T>(b));                                                                \
  }                                                                                \
  constexpr type& operator|=(type& a, type b) noexcept {                                                               \
    using T = std::underlying_type_t<type>;                                                                            \
    a = type(static_cast<T>(a) | static_cast<T>(b));                                                                   \
    return a;                                                                                \
  }                                                                                \
  constexpr type& operator&=(type& a, type b) noexcept {                                                               \
    using T = std::underlying_type_t<type>;                                                                            \
    a = type(static_cast<T>(a) & static_cast<T>(b));                                                                   \
    return a;                                                                                \
  }                                                                                \
  constexpr type operator~(type key) noexcept {                                                                        \
    using T = std::underlying_type_t<type>;                                                                            \
    return type(~static_cast<T>(key));                                                                                \
  }                                                                                \
  constexpr bool True(type key) noexcept {                                                                             \
    using T = std::underlying_type_t<type>;                                                                            \
    return static_cast<T>(key) != 0;                                                                                \
  }                                                                                \
  constexpr bool False(type key) noexcept {                                                                            \
    using T = std::underlying_type_t<type>;                                                                            \
    return static_cast<T>(key) == 0;                                                                                \
  }
#endif

namespace athena {
namespace error {
enum class Level { Message, Warning, Error, Fatal };
}
enum class SeekOrigin { Begin, Current, End };

enum class Endian { Little, Big };

namespace io {
template <Endian DNAE>
struct DNA;
template <Endian DNAE>
struct DNAV;

template <class T>
using __IsDNARecord = std::disjunction<std::is_base_of<DNA<Endian::Big>, T>, std::is_base_of<DNA<Endian::Little>, T>>;
template <class T>
constexpr bool __IsDNARecord_v = __IsDNARecord<T>::value;

template <class T>
using __IsDNAVRecord =
    std::disjunction<std::is_base_of<DNAV<Endian::Big>, T>, std::is_base_of<DNAV<Endian::Little>, T>>;
template <class T>
constexpr bool __IsDNAVRecord_v = __IsDNAVRecord<T>::value;
} // namespace io
} // namespace athena

typedef void (*atEXCEPTION_HANDLER)(athena::error::Level level, const char* /*file*/, const char*, int /*line*/,
                                    fmt::string_view fmt, fmt::format_args args);

atEXCEPTION_HANDLER atGetExceptionHandler();
/**
 * atSetExceptionHandler is only meant to be used a the start and end of an application's lifetime,
 * this function cannot be considered thread-safe, therefore modifying during runtime is not recommended.
 */
void atSetExceptionHandler(atEXCEPTION_HANDLER func);

std::ostream& operator<<(std::ostream& os, const athena::SeekOrigin& origin);
std::ostream& operator<<(std::ostream& os, const athena::Endian& endian);

template <typename First, typename... Rest>
constexpr auto __FIRST_ARG__(First first, Rest...) { return first; }
template <typename S, typename... Args>
auto __make_args_checked__(const S& format_str, Args&&... args) {
  return fmt::internal::make_args_checked<Args...>(format_str, std::forward<Args>(args)...);
}

#ifndef NDEBUG
#define atDebug(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),     \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)
#else
#define atDebug(...)
#endif

#define atMessage(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Message, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),     \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)

#define atWarning(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler) {                                                                                \
      __handler(athena::error::Level::Warning, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),     \
                __make_args_checked__(__VA_ARGS__));                                                                   \
    }                                                                                \
  } while (0)

#define atError(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Error, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),       \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)

#define atFatal(...)                                                                                \
  do {                                                                                \
    atEXCEPTION_HANDLER __handler = atGetExceptionHandler();                                                           \
    if (__handler)                                                                                \
      __handler(athena::error::Level::Fatal, __FILE__, AT_PRETTY_FUNCTION, __LINE__, __FIRST_ARG__(__VA_ARGS__),       \
                __make_args_checked__(__VA_ARGS__));                                                                   \
  } while (0)
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/defaults.h"

namespace browser_defaults {

#if defined(OS_CHROMEOS)

// Make the regular omnibox text two points larger than the nine-point font
// used in the tab strip (11pt / 72pt/in * 96px/in = 14.667px).
const int kAutocompleteEditFontPixelSize = 15;

const int kAutocompleteEditFontPixelSizeInPopup = 10;

const SessionStartupPref::Type kDefaultSessionStartupType =
    SessionStartupPref::LAST;
const int kMiniTabWidth = 64;
const bool kCanToggleSystemTitleBar = false;
const bool kRestorePopups = true;
const bool kShowImportOnBookmarkBar = false;
const bool kShowExitMenuItem = true;
const bool kOSSupportsOtherBrowsers = false;
const bool kDownloadPageHasShowInFolder = true;
const bool kSizeTabButtonToTopOfTabStrip = true;
const bool kBootstrapSyncAuthentication = true;
const bool kShowOtherBrowsersInAboutMemory = false;
const bool kAlwaysOpenIncognitoWindow = true;
const bool kShowCancelButtonInTaskManager = true;

#elif defined(TOOLKIT_USES_GTK)

// 14px = 10.5pt @ 96dpi.
const int kAutocompleteEditFontPixelSize = 14;

// On Windows, popup windows' location text uses a font 5/6 the size of
// that in a regular window, which we duplicate here for GTK.
const int kAutocompleteEditFontPixelSizeInPopup =
    kAutocompleteEditFontPixelSize * 5.0 / 6.0;

#if defined(TOOLKIT_VIEWS)
const bool kCanToggleSystemTitleBar = false;
#else
const bool kCanToggleSystemTitleBar = true;
#endif

#endif

#if !defined(OS_CHROMEOS)

const SessionStartupPref::Type kDefaultSessionStartupType =
    SessionStartupPref::DEFAULT;
const int kMiniTabWidth = 56;
const bool kRestorePopups = false;
const bool kShowImportOnBookmarkBar = true;
const bool kDownloadPageHasShowInFolder = true;
#if defined(OS_MACOSX)
const bool kShowExitMenuItem = false;
#else
const bool kShowExitMenuItem = true;
#endif
const bool kOSSupportsOtherBrowsers = true;
const bool kSizeTabButtonToTopOfTabStrip = false;
const bool kBootstrapSyncAuthentication = false;
const bool kShowOtherBrowsersInAboutMemory = true;
const bool kAlwaysOpenIncognitoWindow = false;
const bool kShowCancelButtonInTaskManager = false;
#endif

#if defined(OS_MACOSX)
const bool kBrowserAliveWithNoWindows = true;
#else
const bool kBrowserAliveWithNoWindows = false;
#endif

#ifdef TOUCH_UI
const int kBookmarkBarHeight = 50;
const int kNewtabBookmarkBarHeight = 72;
#else
const int kBookmarkBarHeight = 28;
const int kNewtabBookmarkBarHeight = 57;
#endif

#ifdef TOUCH_UI
const ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =
    ui::ResourceBundle::LargeBoldFont;
#else
const ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =
    ui::ResourceBundle::BoldFont;
#endif

#ifdef TOUCH_UI
const int kInfoBarBorderPaddingVertical = 12;
#else
const int kInfoBarBorderPaddingVertical = 5;
#endif

bool bookmarks_enabled = true;

bool skip_restore = false;

bool enable_help_app = true;

}  // namespace browser_defaults
<commit_msg>Do not restore popups on ChromeOS<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/defaults.h"

namespace browser_defaults {

#if defined(OS_CHROMEOS)

// Make the regular omnibox text two points larger than the nine-point font
// used in the tab strip (11pt / 72pt/in * 96px/in = 14.667px).
const int kAutocompleteEditFontPixelSize = 15;

const int kAutocompleteEditFontPixelSizeInPopup = 10;

const SessionStartupPref::Type kDefaultSessionStartupType =
    SessionStartupPref::LAST;
const int kMiniTabWidth = 64;
const bool kCanToggleSystemTitleBar = false;
const bool kRestorePopups = false;
const bool kShowImportOnBookmarkBar = false;
const bool kShowExitMenuItem = true;
const bool kOSSupportsOtherBrowsers = false;
const bool kDownloadPageHasShowInFolder = true;
const bool kSizeTabButtonToTopOfTabStrip = true;
const bool kBootstrapSyncAuthentication = true;
const bool kShowOtherBrowsersInAboutMemory = false;
const bool kAlwaysOpenIncognitoWindow = true;
const bool kShowCancelButtonInTaskManager = true;

#elif defined(TOOLKIT_USES_GTK)

// 14px = 10.5pt @ 96dpi.
const int kAutocompleteEditFontPixelSize = 14;

// On Windows, popup windows' location text uses a font 5/6 the size of
// that in a regular window, which we duplicate here for GTK.
const int kAutocompleteEditFontPixelSizeInPopup =
    kAutocompleteEditFontPixelSize * 5.0 / 6.0;

#if defined(TOOLKIT_VIEWS)
const bool kCanToggleSystemTitleBar = false;
#else
const bool kCanToggleSystemTitleBar = true;
#endif

#endif

#if !defined(OS_CHROMEOS)

const SessionStartupPref::Type kDefaultSessionStartupType =
    SessionStartupPref::DEFAULT;
const int kMiniTabWidth = 56;
const bool kRestorePopups = false;
const bool kShowImportOnBookmarkBar = true;
const bool kDownloadPageHasShowInFolder = true;
#if defined(OS_MACOSX)
const bool kShowExitMenuItem = false;
#else
const bool kShowExitMenuItem = true;
#endif
const bool kOSSupportsOtherBrowsers = true;
const bool kSizeTabButtonToTopOfTabStrip = false;
const bool kBootstrapSyncAuthentication = false;
const bool kShowOtherBrowsersInAboutMemory = true;
const bool kAlwaysOpenIncognitoWindow = false;
const bool kShowCancelButtonInTaskManager = false;
#endif

#if defined(OS_MACOSX)
const bool kBrowserAliveWithNoWindows = true;
#else
const bool kBrowserAliveWithNoWindows = false;
#endif

#ifdef TOUCH_UI
const int kBookmarkBarHeight = 50;
const int kNewtabBookmarkBarHeight = 72;
#else
const int kBookmarkBarHeight = 28;
const int kNewtabBookmarkBarHeight = 57;
#endif

#ifdef TOUCH_UI
const ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =
    ui::ResourceBundle::LargeBoldFont;
#else
const ui::ResourceBundle::FontStyle kAssociatedNetworkFontStyle =
    ui::ResourceBundle::BoldFont;
#endif

#ifdef TOUCH_UI
const int kInfoBarBorderPaddingVertical = 12;
#else
const int kInfoBarBorderPaddingVertical = 5;
#endif

bool bookmarks_enabled = true;

bool skip_restore = false;

bool enable_help_app = true;

}  // namespace browser_defaults
<|endoftext|>


<commit_before>#ifndef OSRM_BASE64_HPP
#define OSRM_BASE64_HPP

#include <string>
#include <vector>
#include <iterator>
#include <type_traits>

#include <cstddef>
#include <climits>

#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/range/algorithm/copy.hpp>

// RFC 4648 "The Base16, Base32, and Base64 Data Encodings"
// See: https://tools.ietf.org/html/rfc4648

namespace detail
{
// The C++ standard guarantees none of this by default, but we need it in the following.
static_assert(CHAR_BIT == 8u, "we assume a byte holds 8 bits");
static_assert(sizeof(char) == 1u, "we assume a char is one byte large");

using Base64FromBinary = boost::archive::iterators::base64_from_binary<
    boost::archive::iterators::transform_width<const char *, // sequence of chars
                                               6,            // get view of 6 bit
                                               8             // from sequence of 8 bit
                                               >>;

using BinaryFromBase64 = boost::archive::iterators::transform_width<
    boost::archive::iterators::binary_from_base64<std::string::const_iterator>,
    8, // get a view of 8 bit
    6  // from a sequence of 6 bit
    >;
} // ns detail

namespace osrm
{
namespace engine
{

// Encoding Implementation

// Encodes a chunk of memory to Base64.
inline std::string encodeBase64(const unsigned char *first, std::size_t size)
{
    std::vector<unsigned char> bytes{first, first + size};
    BOOST_ASSERT(!bytes.empty());

    std::size_t bytes_to_pad{0};

    while (bytes.size() % 3 != 0)
    {
        bytes_to_pad += 1;
        bytes.push_back(0);
    }

    BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2);
    BOOST_ASSERT_MSG(0 == bytes.size() % 3, "base64 input data size is not a multiple of 3");

    std::string encoded{detail::Base64FromBinary{bytes.data()},
                        detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}};

    return encoded.append(bytes_to_pad, '=');
}

// C++11 standard 3.9.1/1: Plain char, signed char, and unsigned char are three distinct types

// Overload for signed char catches (not only but also) C-string literals.
inline std::string encodeBase64(const signed char *first, std::size_t size)
{
    return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);
}

// Overload for char catches (not only but also) C-string literals.
inline std::string encodeBase64(const char *first, std::size_t size)
{
    return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);
}

// Convenience specialization, encoding from string instead of byte-dumping it.
inline std::string encodeBase64(const std::string &x) { return encodeBase64(x.data(), x.size()); }

// Encode any sufficiently trivial object to Base64.
template <typename T> std::string encodeBase64Bytewise(const T &x)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    return encodeBase64(reinterpret_cast<const unsigned char *>(&x), sizeof(T));
}

// Decoding Implementation

// Decodes into a chunk of memory that is at least as large as the input.
template <typename OutputIter> void decodeBase64(const std::string &encoded, OutputIter out)
{
    auto unpadded = encoded;

    const auto num_padded = std::count(begin(encoded), end(encoded), '=');
    std::replace(begin(unpadded), end(unpadded), '=', 'A'); // A_64 == \0

    std::string decoded{detail::BinaryFromBase64{begin(unpadded)},
                        detail::BinaryFromBase64{begin(unpadded) + unpadded.length()}};

    decoded.erase(end(decoded) - num_padded, end(decoded));
    std::copy(begin(decoded), end(decoded), out);
}

// Convenience specialization, filling string instead of byte-dumping into it.
inline std::string decodeBase64(const std::string &encoded)
{
    std::string rv;

    decodeBase64(encoded, std::back_inserter(rv));

    return rv;
}

// Decodes from Base 64 to any sufficiently trivial object.
template <typename T> T decodeBase64Bytewise(const std::string &encoded)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    T x;

    decodeBase64(encoded, reinterpret_cast<unsigned char *>(&x));

    return x;
}

} // ns engine
} // ns osrm

#endif /* OSRM_BASE64_HPP */
<commit_msg>Move detail:: to osrm::detail::<commit_after>#ifndef OSRM_BASE64_HPP
#define OSRM_BASE64_HPP

#include <string>
#include <vector>
#include <iterator>
#include <type_traits>

#include <cstddef>
#include <climits>

#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/range/algorithm/copy.hpp>

namespace osrm
{

// RFC 4648 "The Base16, Base32, and Base64 Data Encodings"
// See: https://tools.ietf.org/html/rfc4648

namespace detail
{
// The C++ standard guarantees none of this by default, but we need it in the following.
static_assert(CHAR_BIT == 8u, "we assume a byte holds 8 bits");
static_assert(sizeof(char) == 1u, "we assume a char is one byte large");

using Base64FromBinary = boost::archive::iterators::base64_from_binary<
    boost::archive::iterators::transform_width<const char *, // sequence of chars
                                               6,            // get view of 6 bit
                                               8             // from sequence of 8 bit
                                               >>;

using BinaryFromBase64 = boost::archive::iterators::transform_width<
    boost::archive::iterators::binary_from_base64<std::string::const_iterator>,
    8, // get a view of 8 bit
    6  // from a sequence of 6 bit
    >;
} // ns detail
namespace engine
{

// Encoding Implementation

// Encodes a chunk of memory to Base64.
inline std::string encodeBase64(const unsigned char *first, std::size_t size)
{
    std::vector<unsigned char> bytes{first, first + size};
    BOOST_ASSERT(!bytes.empty());

    std::size_t bytes_to_pad{0};

    while (bytes.size() % 3 != 0)
    {
        bytes_to_pad += 1;
        bytes.push_back(0);
    }

    BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2);
    BOOST_ASSERT_MSG(0 == bytes.size() % 3, "base64 input data size is not a multiple of 3");

    std::string encoded{detail::Base64FromBinary{bytes.data()},
                        detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}};

    return encoded.append(bytes_to_pad, '=');
}

// C++11 standard 3.9.1/1: Plain char, signed char, and unsigned char are three distinct types

// Overload for signed char catches (not only but also) C-string literals.
inline std::string encodeBase64(const signed char *first, std::size_t size)
{
    return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);
}

// Overload for char catches (not only but also) C-string literals.
inline std::string encodeBase64(const char *first, std::size_t size)
{
    return encodeBase64(reinterpret_cast<const unsigned char *>(first), size);
}

// Convenience specialization, encoding from string instead of byte-dumping it.
inline std::string encodeBase64(const std::string &x) { return encodeBase64(x.data(), x.size()); }

// Encode any sufficiently trivial object to Base64.
template <typename T> std::string encodeBase64Bytewise(const T &x)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    return encodeBase64(reinterpret_cast<const unsigned char *>(&x), sizeof(T));
}

// Decoding Implementation

// Decodes into a chunk of memory that is at least as large as the input.
template <typename OutputIter> void decodeBase64(const std::string &encoded, OutputIter out)
{
    auto unpadded = encoded;

    const auto num_padded = std::count(begin(encoded), end(encoded), '=');
    std::replace(begin(unpadded), end(unpadded), '=', 'A'); // A_64 == \0

    std::string decoded{detail::BinaryFromBase64{begin(unpadded)},
                        detail::BinaryFromBase64{begin(unpadded) + unpadded.length()}};

    decoded.erase(end(decoded) - num_padded, end(decoded));
    std::copy(begin(decoded), end(decoded), out);
}

// Convenience specialization, filling string instead of byte-dumping into it.
inline std::string decodeBase64(const std::string &encoded)
{
    std::string rv;

    decodeBase64(encoded, std::back_inserter(rv));

    return rv;
}

// Decodes from Base 64 to any sufficiently trivial object.
template <typename T> T decodeBase64Bytewise(const std::string &encoded)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    T x;

    decodeBase64(encoded, reinterpret_cast<unsigned char *>(&x));

    return x;
}

} // ns engine
} // ns osrm

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


<commit_before>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include <algorithm>

#include "../config.hpp"
#include "../traits_lite.hpp"

#include "std/mmul.hpp"
#include "std/strassen_mmul.hpp"
#include "blas/gemm.hpp"
#include "eblas/gemm.hpp"

namespace etl {

namespace detail {

template<typename A, typename B, typename C, typename Enable = void>
struct mm_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct is_fast_dgemm : cpp::and_c<cpp::not_c<is_cblas_enabled>, all_double_precision<A, B, C>, all_dma<A, B, C>> {};

template<typename A, typename B, typename C>
struct is_fast_sgemm : cpp::and_c<cpp::not_c<is_cblas_enabled>, all_single_precision<A, B, C>, all_dma<A, B, C>> {};

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::eblas::fast_dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::eblas::fast_sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct is_blas_dgemm : cpp::and_c<is_cblas_enabled, all_double_precision<A, B, C>, all_dma<A, B, C>> {};

template<typename A, typename B, typename C>
struct is_blas_sgemm : cpp::and_c<is_cblas_enabled, all_single_precision<A, B, C>, all_dma<A, B, C>> {};

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C, typename Enable = void>
struct strassen_mm_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::strassen_mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C, typename Enable = void>
struct vm_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::vm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::dgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::sgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C, typename Enable = void>
struct mv_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::mv_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::dgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::sgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

} //end of namespace detail

} //end of namespace etl
<commit_msg>Refactorings<commit_after>//=======================================================================
// Copyright (c) 2014-2015 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#pragma once

#include <algorithm>

#include "../config.hpp"
#include "../traits_lite.hpp"

#include "std/mmul.hpp"
#include "std/strassen_mmul.hpp"
#include "blas/gemm.hpp"
#include "eblas/gemm.hpp"

namespace etl {

namespace detail {

template<typename A, typename B, typename C, typename Enable = void>
struct mm_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
using is_fast_dgemm = cpp::and_c<cpp::not_c<is_cblas_enabled>, all_double_precision<A, B, C>, all_dma<A, B, C>>;

template<typename A, typename B, typename C>
using is_fast_sgemm = cpp::and_c<cpp::not_c<is_cblas_enabled>, all_single_precision<A, B, C>, all_dma<A, B, C>>;

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::eblas::fast_dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_fast_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::eblas::fast_sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
using is_blas_dgemm = cpp::and_c<is_cblas_enabled, all_double_precision<A, B, C>, all_dma<A, B, C>>;

template<typename A, typename B, typename C>
using is_blas_sgemm = cpp::and_c<is_cblas_enabled, all_single_precision<A, B, C>, all_dma<A, B, C>>;

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::dgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::sgemm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C, typename Enable = void>
struct strassen_mm_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::strassen_mm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C, typename Enable = void>
struct vm_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::vm_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::dgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct vm_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::sgevm(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C, typename Enable = void>
struct mv_mul_impl {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::standard::mv_mul(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_dgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::dgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

template<typename A, typename B, typename C>
struct mv_mul_impl<A, B, C, std::enable_if_t<is_blas_sgemm<A,B,C>::value>> {
    static void apply(A&& a, B&& b, C&& c){
        etl::impl::blas::sgemv(std::forward<A>(a), std::forward<B>(b), std::forward<C>(c));
    }
};

} //end of namespace detail

} //end of namespace etl
<|endoftext|>


<commit_before>#ifndef INFO_ITERATOR_HPP
#define INFO_ITERATOR_HPP

#include <cstddef>
#include <iterator>

namespace shadow
{
class reflection_manager;

template <class InfoType, class ProxyType>
class indexed_info_iterator_
{
public:
    typedef ProxyType value_type;
    typedef std::ptrdiff_t difference_type;
    typedef ProxyType reference;
    typedef ProxyType pointer;
    typedef std::random_access_iterator_tag iterator_category;

public:
    indexed_info_iterator_()
        : current_index_(0), index_buffer_(nullptr), data_buffer_(nullptr)
    {
    }

    indexed_info_iterator_(std::size_t current_index,
                           const std::size_t* index_buffer,
                           InfoType* data_buffer,
                           const reflection_manager* manager)
        : current_index_(current_index),
          index_buffer_(index_buffer),
          data_buffer_(data_buffer),
          manager_(manager)
    {
    }

public:
    ProxyType operator*() const
    {
        return ProxyType(data_buffer_ + index_buffer_[current_index_],
                         manager_);
    }

    ProxyType operator->() const
    {
        return ProxyType(data_buffer_ + index_buffer_[current_index_],
                         manager_);
    }

    ProxyType operator[](difference_type n) const
    {
        return ProxyType(data_buffer_ + index_buffer_[current_index_ + n],
                         manager_);
    }

    indexed_info_iterator_& operator++()
    {
        ++current_index_;
        return *this;
    }

    indexed_info_iterator_ operator++(int)
    {
        auto temp = *this;
        ++(*this);
        return temp;
    }

    indexed_info_iterator_& operator--()
    {
        --current_index_;
        return *this;
    }

    indexed_info_iterator_ operator--(int)
    {
        auto temp = *this;
        --(*this);
        return temp;
    }

    indexed_info_iterator_&
    operator+=(difference_type n)
    {
        current_index_ += n;
        return *this;
    }

    indexed_info_iterator_&
    operator-=(difference_type n)
    {
        current_index_ -= n;
        return *this;
    }

    indexed_info_iterator_
    operator+(difference_type n) const
    {
        return indexed_info_iterator_(
            current_index_ + n, index_buffer_, data_buffer_, manager_);
    }

    indexed_info_iterator_
    operator-(difference_type n) const
    {
        return indexed_info_iterator_(
            current_index_ - n, index_buffer_, data_buffer_, manager_);
    }

    difference_type
    operator-(const indexed_info_iterator_& other) const
    {
        return current_index_ - other.current_index_;
    }

    friend indexed_info_iterator_
    operator+(difference_type lhs, const indexed_info_iterator_& rhs)
    {
        return rhs + lhs;
    }

    bool
    operator==(const indexed_info_iterator_& other) const
    {
        return current_index_ == other.current_index_;
    }

    bool
    operator!=(const indexed_info_iterator_& other) const
    {
        return current_index_ != other.current_index_;
    }

    bool
    operator<(const indexed_info_iterator_& other) const
    {
        return current_index_ < other.current_index_;
    }

    bool
    operator>(const indexed_info_iterator_& other) const
    {
        return current_index_ > other.current_index_;
    }

    bool
    operator<=(const indexed_info_iterator_& other) const
    {
        return current_index_ <= other.current_index_;
    }

    bool
    operator>=(const indexed_info_iterator_& other) const
    {
        return current_index_ >= other.current_index_;
    }

private:
    std::size_t current_index_;
    const std::size_t* index_buffer_;
    InfoType* data_buffer_;
    const reflection_manager* manager_;
};

template <class InfoType, class ProxyType>
class info_iterator_
{
public:
    typedef ProxyType value_type;
    typedef typename std::iterator_traits<const InfoType*>::difference_type
        difference_type;
    typedef ProxyType reference;
    typedef ProxyType pointer;
    typedef typename std::iterator_traits<const InfoType*>::iterator_category
        iterator_category;

public:
    info_iterator_() = default;

    info_iterator_(const InfoType* current, const reflection_manager* manager)
        : current_(current), manager_(manager)
    {
    }

public:
    ProxyType operator*() const
    {
        return ProxyType(current_, manager_);
    }

    ProxyType operator->() const
    {
        return ProxyType(current_, manager_);
    }

    ProxyType operator[](difference_type n) const
    {
        return ProxyType(current_ + n, manager_);
    }

    info_iterator_& operator++()
    {
        ++current_;
        return *this;
    }

    info_iterator_ operator++(int)
    {
        auto temp = *this;
        ++(*this);
        return temp;
    }

    info_iterator_& operator--()
    {
        --current_;
        return *this;
    }

    info_iterator_ operator--(int)
    {
        auto temp = *this;
        --(*this);
        return temp;
    }

    info_iterator_&
    operator+=(difference_type n)
    {
        current_ += n;
        return *this;
    }

    info_iterator_&
    operator-=(difference_type n)
    {
        current_ -= n;
        return *this;
    }

    info_iterator_
    operator+(difference_type n) const
    {
        return info_iterator_(current_ + n, manager_);
    }

    info_iterator_
    operator-(difference_type n) const
    {
        return info_iterator_(current_ - n, manager_);
    }

    difference_type
    operator-(const info_iterator_& other) const
    {
        return current_ - other.current_;
    }

    friend info_iterator_
    operator+(difference_type lhs, const info_iterator_& rhs)
    {
        return rhs + lhs;
    }

    bool
    operator==(const info_iterator_& other) const
    {
        return current_ == other.current_;
    }

    bool
    operator!=(const info_iterator_& other) const
    {
        return current_ != other.current_;
    }

    bool
    operator<(const info_iterator_& other) const
    {
        return current_ < other.current_;
    }

    bool
    operator>(const info_iterator_& other) const
    {
        return current_ > other.current_;
    }

    bool
    operator<=(const info_iterator_& other) const
    {
        return current_ <= other.current_;
    }

    bool
    operator>=(const info_iterator_& other) const
    {
        return current_ >= other.current_;
    }

private:
    InfoType* current_;
    const reflection_manager* manager_;
};
} // namespace shadow

namespace std
{
// specialize std::iterator_traits for info_iterator_

template <class InfoType, class ProxyType>
struct iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>
{
    typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type
        value_type;
    typedef
        typename shadow::info_iterator_<InfoType, ProxyType>::difference_type
            difference_type;
    typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference
        reference;
    typedef
        typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;
    typedef
        typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category
            iterator_category;
};

template <class InfoType, class ProxyType>
struct iterator_traits<shadow::indexed_info_iterator_<InfoType, ProxyType>>
{
    typedef
        typename shadow::indexed_info_iterator_<InfoType, ProxyType>::value_type
            value_type;

    typedef typename shadow::indexed_info_iterator_<InfoType,
                                                    ProxyType>::difference_type
        difference_type;

    typedef
        typename shadow::indexed_info_iterator_<InfoType, ProxyType>::reference
            reference;

    typedef
        typename shadow::indexed_info_iterator_<InfoType, ProxyType>::pointer
            pointer;

    typedef
        typename shadow::indexed_info_iterator_<InfoType,
                                                ProxyType>::iterator_category
            iterator_category;
};
} // namespace std

#endif
<commit_msg>Fix missing initialization of field manager_ in indexed_info_iterator_. 	modified:   include/info_iterator.hpp<commit_after>#ifndef INFO_ITERATOR_HPP
#define INFO_ITERATOR_HPP

#include <cstddef>
#include <iterator>

namespace shadow
{
class reflection_manager;

template <class InfoType, class ProxyType>
class indexed_info_iterator_
{
public:
    typedef ProxyType value_type;
    typedef std::ptrdiff_t difference_type;
    typedef ProxyType reference;
    typedef ProxyType pointer;
    typedef std::random_access_iterator_tag iterator_category;

public:
    indexed_info_iterator_()
        : current_index_(0),
          index_buffer_(nullptr),
          data_buffer_(nullptr),
          manager_(nullptr)
    {
    }

    indexed_info_iterator_(std::size_t current_index,
                           const std::size_t* index_buffer,
                           InfoType* data_buffer,
                           const reflection_manager* manager)
        : current_index_(current_index),
          index_buffer_(index_buffer),
          data_buffer_(data_buffer),
          manager_(manager)
    {
    }

public:
    ProxyType operator*() const
    {
        return ProxyType(data_buffer_ + index_buffer_[current_index_],
                         manager_);
    }

    ProxyType operator->() const
    {
        return ProxyType(data_buffer_ + index_buffer_[current_index_],
                         manager_);
    }

    ProxyType operator[](difference_type n) const
    {
        return ProxyType(data_buffer_ + index_buffer_[current_index_ + n],
                         manager_);
    }

    indexed_info_iterator_& operator++()
    {
        ++current_index_;
        return *this;
    }

    indexed_info_iterator_ operator++(int)
    {
        auto temp = *this;
        ++(*this);
        return temp;
    }

    indexed_info_iterator_& operator--()
    {
        --current_index_;
        return *this;
    }

    indexed_info_iterator_ operator--(int)
    {
        auto temp = *this;
        --(*this);
        return temp;
    }

    indexed_info_iterator_&
    operator+=(difference_type n)
    {
        current_index_ += n;
        return *this;
    }

    indexed_info_iterator_&
    operator-=(difference_type n)
    {
        current_index_ -= n;
        return *this;
    }

    indexed_info_iterator_
    operator+(difference_type n) const
    {
        return indexed_info_iterator_(
            current_index_ + n, index_buffer_, data_buffer_, manager_);
    }

    indexed_info_iterator_
    operator-(difference_type n) const
    {
        return indexed_info_iterator_(
            current_index_ - n, index_buffer_, data_buffer_, manager_);
    }

    difference_type
    operator-(const indexed_info_iterator_& other) const
    {
        return current_index_ - other.current_index_;
    }

    friend indexed_info_iterator_
    operator+(difference_type lhs, const indexed_info_iterator_& rhs)
    {
        return rhs + lhs;
    }

    bool
    operator==(const indexed_info_iterator_& other) const
    {
        return current_index_ == other.current_index_;
    }

    bool
    operator!=(const indexed_info_iterator_& other) const
    {
        return current_index_ != other.current_index_;
    }

    bool
    operator<(const indexed_info_iterator_& other) const
    {
        return current_index_ < other.current_index_;
    }

    bool
    operator>(const indexed_info_iterator_& other) const
    {
        return current_index_ > other.current_index_;
    }

    bool
    operator<=(const indexed_info_iterator_& other) const
    {
        return current_index_ <= other.current_index_;
    }

    bool
    operator>=(const indexed_info_iterator_& other) const
    {
        return current_index_ >= other.current_index_;
    }

private:
    std::size_t current_index_;
    const std::size_t* index_buffer_;
    InfoType* data_buffer_;
    const reflection_manager* manager_;
};

template <class InfoType, class ProxyType>
class info_iterator_
{
public:
    typedef ProxyType value_type;
    typedef typename std::iterator_traits<const InfoType*>::difference_type
        difference_type;
    typedef ProxyType reference;
    typedef ProxyType pointer;
    typedef typename std::iterator_traits<const InfoType*>::iterator_category
        iterator_category;

public:
    info_iterator_() = default;

    info_iterator_(const InfoType* current, const reflection_manager* manager)
        : current_(current), manager_(manager)
    {
    }

public:
    ProxyType operator*() const
    {
        return ProxyType(current_, manager_);
    }

    ProxyType operator->() const
    {
        return ProxyType(current_, manager_);
    }

    ProxyType operator[](difference_type n) const
    {
        return ProxyType(current_ + n, manager_);
    }

    info_iterator_& operator++()
    {
        ++current_;
        return *this;
    }

    info_iterator_ operator++(int)
    {
        auto temp = *this;
        ++(*this);
        return temp;
    }

    info_iterator_& operator--()
    {
        --current_;
        return *this;
    }

    info_iterator_ operator--(int)
    {
        auto temp = *this;
        --(*this);
        return temp;
    }

    info_iterator_&
    operator+=(difference_type n)
    {
        current_ += n;
        return *this;
    }

    info_iterator_&
    operator-=(difference_type n)
    {
        current_ -= n;
        return *this;
    }

    info_iterator_
    operator+(difference_type n) const
    {
        return info_iterator_(current_ + n, manager_);
    }

    info_iterator_
    operator-(difference_type n) const
    {
        return info_iterator_(current_ - n, manager_);
    }

    difference_type
    operator-(const info_iterator_& other) const
    {
        return current_ - other.current_;
    }

    friend info_iterator_
    operator+(difference_type lhs, const info_iterator_& rhs)
    {
        return rhs + lhs;
    }

    bool
    operator==(const info_iterator_& other) const
    {
        return current_ == other.current_;
    }

    bool
    operator!=(const info_iterator_& other) const
    {
        return current_ != other.current_;
    }

    bool
    operator<(const info_iterator_& other) const
    {
        return current_ < other.current_;
    }

    bool
    operator>(const info_iterator_& other) const
    {
        return current_ > other.current_;
    }

    bool
    operator<=(const info_iterator_& other) const
    {
        return current_ <= other.current_;
    }

    bool
    operator>=(const info_iterator_& other) const
    {
        return current_ >= other.current_;
    }

private:
    InfoType* current_;
    const reflection_manager* manager_;
};
} // namespace shadow

namespace std
{
// specialize std::iterator_traits for info_iterator_

template <class InfoType, class ProxyType>
struct iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>
{
    typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type
        value_type;
    typedef
        typename shadow::info_iterator_<InfoType, ProxyType>::difference_type
            difference_type;
    typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference
        reference;
    typedef
        typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;
    typedef
        typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category
            iterator_category;
};

template <class InfoType, class ProxyType>
struct iterator_traits<shadow::indexed_info_iterator_<InfoType, ProxyType>>
{
    typedef
        typename shadow::indexed_info_iterator_<InfoType, ProxyType>::value_type
            value_type;

    typedef typename shadow::indexed_info_iterator_<InfoType,
                                                    ProxyType>::difference_type
        difference_type;

    typedef
        typename shadow::indexed_info_iterator_<InfoType, ProxyType>::reference
            reference;

    typedef
        typename shadow::indexed_info_iterator_<InfoType, ProxyType>::pointer
            pointer;

    typedef
        typename shadow::indexed_info_iterator_<InfoType,
                                                ProxyType>::iterator_category
            iterator_category;
};
} // namespace std

#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qversitresourcehandler.h"
#include "qversitproperty.h"
#include "qversitdefaultresourcehandler_p.h"
#include "qversitdefs_p.h"
#include <QFile>

QTM_USE_NAMESPACE

/*!
 * \class QVersitResourceHandler
 *
 * \brief The QVersitResourceHandler class is an interface for clients wishing to implement custom
 * behaviour for loading and saving files to disk when exporting and importing, respectively.
 *
 * \ingroup versit
 *
 * \sa QVersitContactImporter
 * \sa QVersitContactExporter
 *
 * \fn virtual bool QVersitResourceHandler::saveResource(const QByteArray& contents, const QVersitProperty& property, QString* location) = 0;
 * Saves the binary data \a contents to a file on a persistent storage medium.
 *
 * \a property holds the QVersitProperty which is the context in which the binary is coming from.
 * The QVersitResourceHandler can use this, for example, to determine file extension it should choose.
 * \a *filename is filled with the contents of the file.
 * Returns true on success, false on failure.
 *
 *
 * \fn virtual bool QVersitResourceHandler::loadResource(const QString& location, QByteArray* contents, QString* mimeType) = 0;
 * Loads a file from \a location.
 *
 * \a *contents is filled with the contents of the file and \a *mimeType is set to the MIME
 * type that it is determined to be.
 * Returns true on success, false on failure.
*/

QVersitDefaultResourceHandler::QVersitDefaultResourceHandler()
    : d(new QVersitDefaultResourceHandlerPrivate)
{
    // File extension mappings
    int fileExtensionCount = sizeof(versitFileExtensionMappings)/sizeof(VersitMapping);
    for (int i = 0; i < fileExtensionCount; i++) {
        d->mFileExtensionMapping.insert(
            QLatin1String(versitFileExtensionMappings[i].contactString),
            QLatin1String(versitFileExtensionMappings[i].versitString));
    }
}

QVersitDefaultResourceHandler::~QVersitDefaultResourceHandler()
{
    delete d;
}

/*!
 * Default resource loader.
 * Loads file from given \a location into \a contents and returns true if successful.
 * Does not set \a mimeType.
 */
bool QVersitDefaultResourceHandler::loadResource(const QString& location,
                                                 QByteArray* contents,
                                                 QString* mimeType)
{
    QString extension = location.split(QLatin1Char('.')).last().toLower();
    *mimeType = d->mFileExtensionMapping.value(extension);
    if (location.isEmpty())
        return false;
    QFile file(location);
    file.open(QIODevice::ReadOnly);
    if (!file.isReadable())
        return false;
    *contents = file.readAll();
    return contents->size() > 0;
}

/*!
 * Default resource saver.
 * Does nothing and returns false.  By default, resources aren't persisted because we don't know
 * when it is safe to remove them.
 */
bool QVersitDefaultResourceHandler::saveResource(const QByteArray& contents,
                                                 const QVersitProperty& property,
                                                 QString* location)
{
    Q_UNUSED(contents)
    Q_UNUSED(property)
    Q_UNUSED(location)
    return false;
}
<commit_msg>Add back documentation to refer to the after-freeze API change.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qversitresourcehandler.h"
#include "qversitproperty.h"
#include "qversitdefaultresourcehandler_p.h"
#include "qversitdefs_p.h"
#include <QFile>

QTM_USE_NAMESPACE

/*!
 * \class QVersitResourceHandler
 *
 * \brief The QVersitResourceHandler class is an interface for clients wishing to implement custom
 * behaviour for loading and saving files to disk when exporting and importing, respectively.
 *
 * \ingroup versit
 *
 * \sa QVersitContactImporter
 * \sa QVersitContactExporter
 *
 * \fn virtual bool QVersitResourceHandler::saveResource(const QByteArray& contents, const QVersitProperty& property, QString* location) = 0;
 * Saves the binary data \a contents to a file on a persistent storage medium.
 *
 * \a property holds the QVersitProperty which is the context in which the binary is coming from.
 * The QVersitResourceHandler can use this, for example, to determine file extension it should choose.
 * \a *filename is filled with the contents of the file.
 * Returns true on success, false on failure.
 *
 *
 * \fn virtual bool QVersitResourceHandler::loadResource(const QString& location, QByteArray* contents, QString* mimeType) = 0;
 * Loads a file from \a location.
 *
 * \a *contents is filled with the contents of the file and \a *mimeType is set to the MIME
 * type that it is determined to be.
 * Returns true on success, false on failure.
*/

QVersitDefaultResourceHandler::QVersitDefaultResourceHandler()
    : d(new QVersitDefaultResourceHandlerPrivate)
{
    // File extension mappings
    int fileExtensionCount = sizeof(versitFileExtensionMappings)/sizeof(VersitMapping);
    for (int i = 0; i < fileExtensionCount; i++) {
        d->mFileExtensionMapping.insert(
            QLatin1String(versitFileExtensionMappings[i].contactString),
            QLatin1String(versitFileExtensionMappings[i].versitString));
    }
}

QVersitDefaultResourceHandler::~QVersitDefaultResourceHandler()
{
    delete d;
}

/*!
 * Default resource loader.
 * Loads file from given \a location into \a contents and returns true if successful.
 * Sets the \a mimeType based on the file extension.
 */
bool QVersitDefaultResourceHandler::loadResource(const QString& location,
                                                 QByteArray* contents,
                                                 QString* mimeType)
{
    QString extension = location.split(QLatin1Char('.')).last().toLower();
    *mimeType = d->mFileExtensionMapping.value(extension);
    if (location.isEmpty())
        return false;
    QFile file(location);
    file.open(QIODevice::ReadOnly);
    if (!file.isReadable())
        return false;
    *contents = file.readAll();
    return contents->size() > 0;
}

/*!
 * Default resource saver.
 * Does nothing and returns false.  By default, resources aren't persisted because we don't know
 * when it is safe to remove them.
 */
bool QVersitDefaultResourceHandler::saveResource(const QByteArray& contents,
                                                 const QVersitProperty& property,
                                                 QString* location)
{
    Q_UNUSED(contents)
    Q_UNUSED(property)
    Q_UNUSED(location)
    return false;
}
<|endoftext|>


<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Claire Xenia Wolf <claire@yosyshq.com>
 *  Copyright (C) 2020  Pepijn de Vos <pepijn@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifdef MAIN_EXECUTABLE

#include <fstream>
#include <regex>
#include "command.h"
#include "design_utils.h"
#include "log.h"
#include "timing.h"

USING_NEXTPNR_NAMESPACE

class GowinCommandHandler : public CommandHandler
{
  public:
    GowinCommandHandler(int argc, char **argv);
    virtual ~GowinCommandHandler(){};
    std::unique_ptr<Context> createContext(dict<std::string, Property> &values) override;
    void setupArchContext(Context *ctx) override{};
    void customAfterLoad(Context *ctx) override;

  protected:
    po::options_description getArchOptions() override;
};

GowinCommandHandler::GowinCommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}

po::options_description GowinCommandHandler::getArchOptions()
{
    po::options_description specific("Architecture specific options");
    specific.add_options()("device", po::value<std::string>(), "device name");
    specific.add_options()("cst", po::value<std::string>(), "physical constraints file");
    return specific;
}

std::unique_ptr<Context> GowinCommandHandler::createContext(dict<std::string, Property> &values)
{
    std::regex devicere = std::regex("GW1N([A-Z]*)-(LV|UV|UX)([0-9])(C?)([A-Z]{2}[0-9]+)(C[0-9]/I[0-9])");
    std::smatch match;
    std::string device = vm["device"].as<std::string>();
    if (!std::regex_match(device, match, devicere)) {
        log_error("Invalid device %s\n", device.c_str());
    }
    ArchArgs chipArgs;
    char buf[36];
    snprintf(buf, 36, "GW1N%s-%s%s", match[1].str().c_str(), match[3].str().c_str(), match[4].str().c_str());
    chipArgs.device = buf;
    // GW1N and GW1NR variants share the same database.
    // Most Gowin devices are a System in Package with some SDRAM wirebonded to a GPIO bank.
    // However, it appears that the S series with embedded ARM core are unique silicon.
    if(match[1].str() == "S") {
        snprintf(buf, 36, "GW1NS-%s", match[3].str().c_str());
    } else {
        snprintf(buf, 36, "GW1N-%s", match[3].str().c_str());
    }
    chipArgs.family = buf;
    chipArgs.package = match[5];
    chipArgs.speed = match[6];
    return std::unique_ptr<Context>(new Context(chipArgs));
}

void GowinCommandHandler::customAfterLoad(Context *ctx)
{
    if (vm.count("cst")) {
        std::string filename = vm["cst"].as<std::string>();
        std::ifstream in(filename);
        if (!in)
            log_error("Failed to open input CST file %s.\n", filename.c_str());
        ctx->read_cst(in);
    }
}

int main(int argc, char *argv[])
{
    GowinCommandHandler handler(argc, argv);
    return handler.exec();
}
#endif
<commit_msg>clangformat<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  Claire Xenia Wolf <claire@yosyshq.com>
 *  Copyright (C) 2020  Pepijn de Vos <pepijn@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#ifdef MAIN_EXECUTABLE

#include <fstream>
#include <regex>
#include "command.h"
#include "design_utils.h"
#include "log.h"
#include "timing.h"

USING_NEXTPNR_NAMESPACE

class GowinCommandHandler : public CommandHandler
{
  public:
    GowinCommandHandler(int argc, char **argv);
    virtual ~GowinCommandHandler(){};
    std::unique_ptr<Context> createContext(dict<std::string, Property> &values) override;
    void setupArchContext(Context *ctx) override{};
    void customAfterLoad(Context *ctx) override;

  protected:
    po::options_description getArchOptions() override;
};

GowinCommandHandler::GowinCommandHandler(int argc, char **argv) : CommandHandler(argc, argv) {}

po::options_description GowinCommandHandler::getArchOptions()
{
    po::options_description specific("Architecture specific options");
    specific.add_options()("device", po::value<std::string>(), "device name");
    specific.add_options()("cst", po::value<std::string>(), "physical constraints file");
    return specific;
}

std::unique_ptr<Context> GowinCommandHandler::createContext(dict<std::string, Property> &values)
{
    std::regex devicere = std::regex("GW1N([A-Z]*)-(LV|UV|UX)([0-9])(C?)([A-Z]{2}[0-9]+)(C[0-9]/I[0-9])");
    std::smatch match;
    std::string device = vm["device"].as<std::string>();
    if (!std::regex_match(device, match, devicere)) {
        log_error("Invalid device %s\n", device.c_str());
    }
    ArchArgs chipArgs;
    char buf[36];
    snprintf(buf, 36, "GW1N%s-%s%s", match[1].str().c_str(), match[3].str().c_str(), match[4].str().c_str());
    chipArgs.device = buf;
    // GW1N and GW1NR variants share the same database.
    // Most Gowin devices are a System in Package with some SDRAM wirebonded to a GPIO bank.
    // However, it appears that the S series with embedded ARM core are unique silicon.
    if (match[1].str() == "S") {
        snprintf(buf, 36, "GW1NS-%s", match[3].str().c_str());
    } else {
        snprintf(buf, 36, "GW1N-%s", match[3].str().c_str());
    }
    chipArgs.family = buf;
    chipArgs.package = match[5];
    chipArgs.speed = match[6];
    return std::unique_ptr<Context>(new Context(chipArgs));
}

void GowinCommandHandler::customAfterLoad(Context *ctx)
{
    if (vm.count("cst")) {
        std::string filename = vm["cst"].as<std::string>();
        std::ifstream in(filename);
        if (!in)
            log_error("Failed to open input CST file %s.\n", filename.c_str());
        ctx->read_cst(in);
    }
}

int main(int argc, char *argv[])
{
    GowinCommandHandler handler(argc, argv);
    return handler.exec();
}
#endif
<|endoftext|>


<commit_before>/*
Copyright (c) 2014, Peter G. Baum
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

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

#include "gpio.h"
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <string>
#include <stdexcept>
#include <map>
#include <cstring>
#include <cassert>

#define SYSFS_GPIO_DIR "/sys/class/gpio/"

namespace
{
   struct Comp
   {
      bool operator()( const char *a, const char *b ) const
      {
         return strcmp( a, b ) < 0;
      }
   };

   const std::map<const char *,int, Comp> nameMap =
   {
      { "P8.3", 32 + 6 },
      { "P8.4", 32 + 7 },
      { "P8.5", 32 + 2 },
      { "P8.6", 32 + 3 },
      { "P8.7", 64 + 2 },
      { "P8.8", 64 + 3 },
      { "P8.9", 64 + 5 },
      { "P8.10", 64 + 4 },
      { "P8.11", 32 + 13 },
      { "P8.12", 32 + 12 },
      { "P8.13", 0 + 23 },
      { "P8.14", 0 + 26 },
      { "P8.15", 32 + 15 },
      { "P8.16", 32 + 14 },
      { "P8.17", 0 + 27 },
      { "P8.18", 64 + 1 },
      { "P8.19", 0 + 22 },
      { "P8.20", 32 + 31 },
      { "P8.21", 32 + 30 },
      { "P8.22", 32 + 5 },
      { "P8.23", 32 + 4 },
      { "P8.24", 32 + 1 },
      { "P8.25", 32 + 0 },
      { "P8.26", 32 + 29 },
      { "P8.27", 64 + 22 },
      { "P8.28", 64 + 24 },
      { "P8.29", 64 + 23 },
      { "P8.30", 64 + 25 },
      { "P8.31", 0 + 10 },
      { "P8.32", 0 + 11 },
      { "P8.33", 0 + 9 },
      { "P8.34", 64 + 17 },
      { "P8.35", 0 + 8 },
      { "P8.36", 64 + 16 },
      { "P8.37", 64 + 14 },
      { "P8.38", 64 + 15 },
      { "P8.39", 64 + 12 },
      { "P8.40", 64 + 13 },
      { "P8.41", 64 + 10 },
      { "P8.42", 64 + 11 },
      { "P8.43", 64 + 8 },
      { "P8.44", 64 + 9 },
      { "P8.45", 64 + 6 },
      { "P8.46", 64 + 7 },
      { "P9.11", 0 + 30 },
      { "P9.12", 32 + 28 },
      { "P9.13", 0 + 31 },
      { "P9.14", 32 + 18 },
      { "P9.15", 32 + 16 },
      { "P9.16", 32 + 19 },
      { "P9.17", 0 + 5 },
      { "P9.18", 0 + 4 },
      { "P9.19", 0 + 13 },
      { "P9.20", 0 + 12 },
      { "P9.21", 0 + 3 },
      { "P9.22", 0 + 2 },
      { "P9.23", 32 + 17 },
      { "P9.24", 0 + 15 },
      { "P9.25", 96 + 21 },
      { "P9.26", 0 + 14 },
      { "P9.27", 96 + 19 },
      { "P9.28", 96 + 17 },
      { "P9.29", 96 + 15 },
      { "P9.30", 96 + 16 },
      { "P9.31", 96 + 14 },
      // LEDs
      { "USR0", 32 + 21 },
      { "USR1", 32 + 22 },
      { "USR2", 32 + 23 },
      { "USR3", 32 + 24 },
   };

   int getNumberFromName( const char *name )
   {
      if( strncmp( name, "GPIO", 4 ) == 0 )
      {
         const int bank = atoi( name + 4 );
         const char *p = strchr( name, '_' );
         if( p == nullptr )
            throw std::invalid_argument( "Invalid GPIO name" );
         const int num = atoi( p + 1 );
         return bank * 32 + num;
      }
      auto p( nameMap.find( name ) );
      if( p == nameMap.end() )
         throw std::invalid_argument( "Invalid header name" );
      return p->second;
   }
}

GPIO::GPIO( int gpio_, int direction ) : gpio( gpio_ )
{
   int fd = open( SYSFS_GPIO_DIR "export", O_WRONLY );
   if( fd < 0 )
      throw std::invalid_argument( strerror( errno ) );
   std::string str = std::to_string( gpio );
   write( fd, str.c_str(), str.size() + 1 );
   ::close( fd );

   fd = open( ( std::string( SYSFS_GPIO_DIR "gpio" )
         + std::to_string( gpio ) + "/direction").c_str(), O_WRONLY );
   if( fd < 0 )
   {
      close();
      throw std::invalid_argument( strerror( errno ) );
   }
   switch( direction )
   {
      case LOW:  write( fd, "low", 4 ); break;
      case HIGH: write( fd, "high", 5 ); break;
      case IN:   write( fd, "in", 3 ); break;
      case OUT:  write( fd, "out", 4 ); break;
      default: throw std::invalid_argument( "GPIO direction" );
   }
   ::close( fd );
}

int GPIO::getNum( ) const
{
   return gpio;
}

void GPIO::close( )
{
   int fd = open( SYSFS_GPIO_DIR "unexport", O_WRONLY );
   std::string str = std::to_string( gpio );
   write( fd, str.c_str(), str.size() + 1 );
   ::close( fd );
}

GPIO::~GPIO( )
{
   try
   {
      close();
   }
   catch( ... )
   {
   }
}

GPO::GPO( int gpio_, bool val ) : gpio( gpio_, val ? GPIO::HIGH : GPIO::LOW )
{
   const std::string path( SYSFS_GPIO_DIR "gpio"  );
   fd = open( (path + std::to_string( gpio_ ) + "/value").c_str(),
         O_WRONLY );
   if( fd < 0 )
      throw std::invalid_argument( strerror( errno ) );
}

GPO::GPO( const char *name, bool val ) : GPO( getNumberFromName( name ), val )
{
}

GPO::~GPO( )
{
   if( fd > 0 )
      close();
}

void GPO::set( bool val )
{
   write( fd, val ? "1": "0", 2 );
}

void GPO::close( )
{
   ::close( fd );
   fd = 0;
   gpio.close();
}

GPI::GPI( int gpio_ ) : gpio( gpio_, GPIO::IN )
{
   const std::string path( std::string( SYSFS_GPIO_DIR "gpio"  )
         + std::to_string( gpio_ ) + "/value");
   fd = open( path.c_str(), O_RDONLY );
   if( fd < 0 )
      throw std::invalid_argument( strerror( errno ) );
}

GPI::GPI( const char *name ) : GPI( getNumberFromName( name ) )
{
}

GPI::~GPI( )
{
   if( fd > 0 )
      close();
}

void GPI::setEdge( int edge )
{
   const int ff = open( ( std::string( SYSFS_GPIO_DIR "gpio" )
         + std::to_string( gpio.getNum() ) + "/edge" ).c_str(), O_WRONLY );
   if( ff < 0 )
      throw std::invalid_argument( strerror( errno ) );
   switch( edge )
   {
      case NONE:    write( ff, "none", 5 ); break;
      case RISING:  write( ff, "rising", 7 ); break;
      case FALLING: write( ff, "falling", 8 ); break;
      case BOTH:    write( ff, "both", 5 ); break;
      default: ::close( ff );
               throw std::invalid_argument( "GPI::setEdge()" );
   }
   ::close( ff );
}

bool GPI::wait( )
{
   struct pollfd fdset[1];
   fdset[0].fd = fd;
   fdset[0].events = POLLPRI;

   switch( poll( fdset, 1, -1 ) )
   {
      case 1:  assert( fdset[0].revents & POLLPRI );
               return get();
      default:
               throw std::runtime_error( "poll failed" );
   }
}

bool GPI::get( )
{
   char buf;
   if( lseek( fd, 0, SEEK_SET ) != 0
         || read( fd, &buf, 1 ) != 1 )
      throw std::invalid_argument( strerror( errno ) );
   return buf == '1';
}

void GPI::close( )
{
   ::close( fd );
   fd = 0;
   gpio.close();
}
<commit_msg>GPIO: use unnamed tmp variable<commit_after>/*
Copyright (c) 2014, Peter G. Baum
All rights reserved.

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

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

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

#include "gpio.h"
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <string>
#include <stdexcept>
#include <map>
#include <cstring>
#include <cassert>

#define SYSFS_GPIO_DIR "/sys/class/gpio/"

namespace
{
   struct Comp
   {
      bool operator()( const char *a, const char *b ) const
      {
         return strcmp( a, b ) < 0;
      }
   };

   const std::map<const char *,int, Comp> nameMap =
   {
      { "P8.3", 32 + 6 },
      { "P8.4", 32 + 7 },
      { "P8.5", 32 + 2 },
      { "P8.6", 32 + 3 },
      { "P8.7", 64 + 2 },
      { "P8.8", 64 + 3 },
      { "P8.9", 64 + 5 },
      { "P8.10", 64 + 4 },
      { "P8.11", 32 + 13 },
      { "P8.12", 32 + 12 },
      { "P8.13", 0 + 23 },
      { "P8.14", 0 + 26 },
      { "P8.15", 32 + 15 },
      { "P8.16", 32 + 14 },
      { "P8.17", 0 + 27 },
      { "P8.18", 64 + 1 },
      { "P8.19", 0 + 22 },
      { "P8.20", 32 + 31 },
      { "P8.21", 32 + 30 },
      { "P8.22", 32 + 5 },
      { "P8.23", 32 + 4 },
      { "P8.24", 32 + 1 },
      { "P8.25", 32 + 0 },
      { "P8.26", 32 + 29 },
      { "P8.27", 64 + 22 },
      { "P8.28", 64 + 24 },
      { "P8.29", 64 + 23 },
      { "P8.30", 64 + 25 },
      { "P8.31", 0 + 10 },
      { "P8.32", 0 + 11 },
      { "P8.33", 0 + 9 },
      { "P8.34", 64 + 17 },
      { "P8.35", 0 + 8 },
      { "P8.36", 64 + 16 },
      { "P8.37", 64 + 14 },
      { "P8.38", 64 + 15 },
      { "P8.39", 64 + 12 },
      { "P8.40", 64 + 13 },
      { "P8.41", 64 + 10 },
      { "P8.42", 64 + 11 },
      { "P8.43", 64 + 8 },
      { "P8.44", 64 + 9 },
      { "P8.45", 64 + 6 },
      { "P8.46", 64 + 7 },
      { "P9.11", 0 + 30 },
      { "P9.12", 32 + 28 },
      { "P9.13", 0 + 31 },
      { "P9.14", 32 + 18 },
      { "P9.15", 32 + 16 },
      { "P9.16", 32 + 19 },
      { "P9.17", 0 + 5 },
      { "P9.18", 0 + 4 },
      { "P9.19", 0 + 13 },
      { "P9.20", 0 + 12 },
      { "P9.21", 0 + 3 },
      { "P9.22", 0 + 2 },
      { "P9.23", 32 + 17 },
      { "P9.24", 0 + 15 },
      { "P9.25", 96 + 21 },
      { "P9.26", 0 + 14 },
      { "P9.27", 96 + 19 },
      { "P9.28", 96 + 17 },
      { "P9.29", 96 + 15 },
      { "P9.30", 96 + 16 },
      { "P9.31", 96 + 14 },
      // LEDs
      { "USR0", 32 + 21 },
      { "USR1", 32 + 22 },
      { "USR2", 32 + 23 },
      { "USR3", 32 + 24 },
   };

   int getNumberFromName( const char *name )
   {
      if( strncmp( name, "GPIO", 4 ) == 0 )
      {
         const int bank = atoi( name + 4 );
         const char *p = strchr( name, '_' );
         if( p == nullptr )
            throw std::invalid_argument( "Invalid GPIO name" );
         const int num = atoi( p + 1 );
         return bank * 32 + num;
      }
      auto p( nameMap.find( name ) );
      if( p == nameMap.end() )
         throw std::invalid_argument( "Invalid header name" );
      return p->second;
   }
}

GPIO::GPIO( int gpio_, int direction ) : gpio( gpio_ )
{
   int fd = open( SYSFS_GPIO_DIR "export", O_WRONLY );
   if( fd < 0 )
      throw std::invalid_argument( strerror( errno ) );
   std::string str = std::to_string( gpio );
   write( fd, str.c_str(), str.size() + 1 );
   ::close( fd );

   fd = open( ( std::string( SYSFS_GPIO_DIR "gpio" )
         + std::to_string( gpio ) + "/direction").c_str(), O_WRONLY );
   if( fd < 0 )
   {
      close();
      throw std::invalid_argument( strerror( errno ) );
   }
   switch( direction )
   {
      case LOW:  write( fd, "low", 4 ); break;
      case HIGH: write( fd, "high", 5 ); break;
      case IN:   write( fd, "in", 3 ); break;
      case OUT:  write( fd, "out", 4 ); break;
      default: throw std::invalid_argument( "GPIO direction" );
   }
   ::close( fd );
}

int GPIO::getNum( ) const
{
   return gpio;
}

void GPIO::close( )
{
   int fd = open( SYSFS_GPIO_DIR "unexport", O_WRONLY );
   std::string str = std::to_string( gpio );
   write( fd, str.c_str(), str.size() + 1 );
   ::close( fd );
}

GPIO::~GPIO( )
{
   try
   {
      close();
   }
   catch( ... )
   {
   }
}

GPO::GPO( int gpio_, bool val ) : gpio( gpio_, val ? GPIO::HIGH : GPIO::LOW )
{
   fd = open( ( std::string( SYSFS_GPIO_DIR "gpio"  )
         + std::to_string( gpio_ ) + "/value" ).c_str(), O_WRONLY );
   if( fd < 0 )
      throw std::invalid_argument( strerror( errno ) );
}

GPO::GPO( const char *name, bool val ) : GPO( getNumberFromName( name ), val )
{
}

GPO::~GPO( )
{
   if( fd > 0 )
      close();
}

void GPO::set( bool val )
{
   write( fd, val ? "1": "0", 2 );
}

void GPO::close( )
{
   ::close( fd );
   fd = 0;
   gpio.close();
}

GPI::GPI( int gpio_ ) : gpio( gpio_, GPIO::IN )
{
   fd = open( ( std::string( SYSFS_GPIO_DIR "gpio"  )
         + std::to_string( gpio_ ) + "/value" ).c_str(), O_RDONLY );
   if( fd < 0 )
      throw std::invalid_argument( strerror( errno ) );
}

GPI::GPI( const char *name ) : GPI( getNumberFromName( name ) )
{
}

GPI::~GPI( )
{
   if( fd > 0 )
      close();
}

void GPI::setEdge( int edge )
{
   const int ff = open( ( std::string( SYSFS_GPIO_DIR "gpio" )
         + std::to_string( gpio.getNum() ) + "/edge" ).c_str(), O_WRONLY );
   if( ff < 0 )
      throw std::invalid_argument( strerror( errno ) );
   switch( edge )
   {
      case NONE:    write( ff, "none", 5 ); break;
      case RISING:  write( ff, "rising", 7 ); break;
      case FALLING: write( ff, "falling", 8 ); break;
      case BOTH:    write( ff, "both", 5 ); break;
      default: ::close( ff );
               throw std::invalid_argument( "GPI::setEdge()" );
   }
   ::close( ff );
}

bool GPI::wait( )
{
   struct pollfd fdset[1];
   fdset[0].fd = fd;
   fdset[0].events = POLLPRI;

   switch( poll( fdset, 1, -1 ) )
   {
      case 1:  assert( fdset[0].revents & POLLPRI );
               return get();
      default:
               throw std::runtime_error( "poll failed" );
   }
}

bool GPI::get( )
{
   char buf;
   if( lseek( fd, 0, SEEK_SET ) != 0
         || read( fd, &buf, 1 ) != 1 )
      throw std::invalid_argument( strerror( errno ) );
   return buf == '1';
}

void GPI::close( )
{
   ::close( fd );
   fd = 0;
   gpio.close();
}
<|endoftext|>