<commit_before>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_

// This file consists of utilities used for the generic nature of the
// iterable wrapper classes.  As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning.  This
// also applies to the name of the file.  No user code should include
// this file directly.

#include <utility>
#include <tuple>
#include <iterator>
#include <functional>
#include <memory>
#include <type_traits>
#include <cstddef>

namespace iter {

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using iterator_type =
        decltype(std::begin(std::declval<Container&>()));

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using iterator_deref =
        decltype(*std::declval<iterator_type<Container>&>());

    // const_iteator_deref is the type obtained through dereferencing
    // a const iterator& (note: not a const_iterator).  ie: the result
    // of Container::iterator::operator*() const
    template <typename Container>
    using const_iterator_deref =
        decltype(*std::declval<const iterator_type<Container>&>());

    template <typename Container>
    using iterator_traits_deref =
        std::remove_reference_t<iterator_deref<Container>>;

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using reverse_iterator_type =
        decltype(std::declval<Container&>().rbegin());

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using reverse_iterator_deref =
        decltype(*std::declval<reverse_iterator_type<Container>&>());

    template <typename, typename =void>
    struct is_random_access_iter : std::false_type { };

    template <typename T>
    struct is_random_access_iter<T,
        std::enable_if_t<
             std::is_same<
                 typename std::iterator_traits<T>::iterator_category,
              std::random_access_iterator_tag>::value
          >> : std::true_type { };

    template <typename T>
    using has_random_access_iter = is_random_access_iter<iterator_type<T>>;
    // because std::advance assumes a lot and is actually smart, I need a dumb

    // version that will work with most things
    template <typename InputIt, typename Distance =std::size_t>
    void dumb_advance(InputIt& iter, Distance distance=1) {
        for (Distance i(0); i < distance; ++i) {
            ++iter;
        }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(Iter& iter, const Iter& end,
            Distance distance, std::false_type) {
        for (Distance i(0); i < distance && iter != end; ++i) {
            ++iter;
        }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(Iter& iter, const Iter& end,
            Distance distance, std::true_type) {
        if (static_cast<Distance>(end - iter) < distance) {
            iter = end;
        } else {
            iter += distance;
        }
    }

    // iter will not be incremented past end
    template <typename Iter, typename Distance =std::size_t>
    void dumb_advance(Iter& iter, const Iter& end, Distance distance=1) {
        dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});
    }

    template <typename ForwardIt, typename Distance =std::size_t>
    ForwardIt dumb_next(ForwardIt it, Distance distance=1) {
        dumb_advance(it, distance);
        return it;
    }

    template <typename ForwardIt, typename Distance =std::size_t>
    ForwardIt dumb_next(
            ForwardIt it, const ForwardIt& end, Distance distance=1) {
        dumb_advance(it, end, distance);
        return it;
    }

    template <typename Container, typename Distance =std::size_t>
    Distance dumb_size(Container&& container) {
        Distance d{0};
        for (auto it = std::begin(container), end = std::end(container);
                it != end;
                ++it) {
            ++d;
        }
        return d;
    }

    template <typename... Ts>
    struct are_same : std::true_type { };

    template <typename T, typename U, typename... Ts>
    struct are_same<T, U, Ts...>
        : std::integral_constant<bool,
            std::is_same<T, U>::value && are_same<T, Ts...>::value> { };

    namespace detail {
        template <typename... Ts>
        std::tuple<iterator_type<Ts>...> iterator_tuple_type_helper(
                const std::tuple<Ts...>&);
    }
    // Given a tuple template argument, evaluates to a tuple of iterators
    // for the template argument's contained types.
    template <typename TupleType>
    using iterator_tuple_type =
        decltype(detail::iterator_tuple_type_helper(
                    std::declval<TupleType>()));

    namespace detail {
        template <typename... Ts>
        std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(
                const std::tuple<Ts...>&);
    }

    // Given a tuple template argument, evaluates to a tuple of
    // what the iterators for the template argument's contained types
    // dereference to
    template <typename TupleType>
    using iterator_deref_tuple =
        decltype(detail::iterator_tuple_deref_helper(
                    std::declval<TupleType>()));

    // ---- Tuple utilities ---- //

    // function absorbing all arguments passed to it. used when
    // applying a function to a parameter pack but not passing the evaluated
    // results anywhere
    template <typename... Ts>
    void absorb(Ts&&...) { }

    namespace detail {
        template <typename Func, typename TupleType, std::size_t... Is>
        decltype(auto) call_with_tuple_impl(Func&& mf, TupleType&& tup,
                std::index_sequence<Is...>) {
            return mf(std::forward<
                        std::tuple_element_t<
                            Is, std::remove_reference_t<TupleType>>
                        >(std::get<Is>(tup))...);
        }
    }

    // expand a TupleType into individual arguments when calling a Func
    template <typename Func, typename TupleType>
    decltype(auto) call_with_tuple(Func&& mf, TupleType&& tup) {
        constexpr auto TUP_SIZE = std::tuple_size<
            std::decay_t<TupleType>>::value;
        return detail::call_with_tuple_impl(
                std::forward<Func>(mf),
                std::forward<TupleType>(tup),
                std::make_index_sequence<TUP_SIZE>{});
    }

    // DerefHolder holds the value gotten from an iterator dereference
    // if the iterate dereferences to an lvalue references, a pointer to the
    //     element is stored
    // if it does not, a value is stored instead
    // get() returns a reference to the held item in either case
    // pull() should be used when the item is being "pulled out" of the
    //     DerefHolder.  after pull() is called, neither it nor get() can be
    //     safely called after
    // reset() replaces the currently held item and may be called after pull()

    template <typename T, typename =void>
    class DerefHolder {
        private:
            static_assert(!std::is_lvalue_reference<T>::value,
                    "Non-lvalue-ref specialization used for lvalue ref type");
            // it could still be an rvalue reference
            using TPlain = std::remove_reference_t<T>;

            std::unique_ptr<TPlain> item_p;

        public:
            DerefHolder() = default;

            DerefHolder(const DerefHolder& other)
                : item_p{other.item_p ? new TPlain(*other.item_p) : nullptr}
            { }

            DerefHolder& operator=(const DerefHolder& other) {
                this->item_p.reset(other.item_p
                        ? new TPlain(*other.item_p) : nullptr);
                return *this;
            }

            DerefHolder(DerefHolder&&) = default;
            DerefHolder& operator=(DerefHolder&&) = default;
            ~DerefHolder() = default;

            TPlain& get() {
                return *item_p;
            }

            T pull() {
                // NOTE should I reset the unique_ptr to nullptr here
                // since its held item is now invalid anyway?
                return std::move(*item_p);
            }

            void reset(T&& item) {
                item_p.reset(new TPlain(std::move(item)));
            }

            explicit operator bool() const {
                return this->item_p;
            }
    };

    // Specialization for when T is an lvalue ref.  Keep this in mind
    // wherever a T appears.
    template <typename T>
    class DerefHolder<T,
        typename std::enable_if<std::is_lvalue_reference<T>::value>::type>
    {
        private:
            static_assert(std::is_lvalue_reference<T>::value,
                    "lvalue specialization handling non-lvalue-ref type");

            std::remove_reference_t<T> *item_p =nullptr;
        public:
            DerefHolder() = default;

            T get() {
                return *this->item_p;
            }

            T pull() {
                return this->get();
            }

            void reset(T item) {
                this->item_p = &item;
            }

            explicit operator bool() const {
                return this->item_p != nullptr;
            }
    };

    template <typename T>
    struct type_is {
        using type = T;
    };

    // gcc CWG 1558
    template <typename...>
    struct void_t_help {
        using type = void;
    };
    template <typename... Ts>
    using void_t = typename void_t_help<Ts...>::type;
}

#endif
<commit_msg>adds reverse iter aliases<commit_after>#ifndef ITERBASE_HPP_
#define ITERBASE_HPP_

// This file consists of utilities used for the generic nature of the
// iterable wrapper classes.  As such, the contents of this file should be
// considered UNDOCUMENTED and is subject to change without warning.  This
// also applies to the name of the file.  No user code should include
// this file directly.

#include <utility>
#include <tuple>
#include <iterator>
#include <functional>
#include <memory>
#include <type_traits>
#include <cstddef>

namespace iter {

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using iterator_type =
        decltype(std::begin(std::declval<Container&>()));

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using iterator_deref =
        decltype(*std::declval<iterator_type<Container>&>());

    // const_iteator_deref is the type obtained through dereferencing
    // a const iterator& (note: not a const_iterator).  ie: the result
    // of Container::iterator::operator*() const
    template <typename Container>
    using const_iterator_deref =
        decltype(*std::declval<const iterator_type<Container>&>());

    template <typename Container>
    using iterator_traits_deref =
        std::remove_reference_t<iterator_deref<Container>>;

    // iterator_type<C> is the type of C's iterator
    template <typename Container>
    using reverse_iterator_type =
        decltype(std::rbegin(std::declval<Container&>()));

    // iterator_deref<C> is the type obtained by dereferencing an iterator
    // to an object of type C
    template <typename Container>
    using reverse_iterator_deref =
        decltype(*std::declval<reverse_iterator_type<Container>&>());

    template <typename Container>
    using reverse_iterator_traits_deref =
        std::remove_reference_t<reverse_iterator_deref<Container>>;

    template <typename, typename =void>
    struct is_random_access_iter : std::false_type { };

    template <typename T>
    struct is_random_access_iter<T,
        std::enable_if_t<
             std::is_same<
                 typename std::iterator_traits<T>::iterator_category,
              std::random_access_iterator_tag>::value
          >> : std::true_type { };

    template <typename T>
    using has_random_access_iter = is_random_access_iter<iterator_type<T>>;
    // because std::advance assumes a lot and is actually smart, I need a dumb

    // version that will work with most things
    template <typename InputIt, typename Distance =std::size_t>
    void dumb_advance(InputIt& iter, Distance distance=1) {
        for (Distance i(0); i < distance; ++i) {
            ++iter;
        }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(Iter& iter, const Iter& end,
            Distance distance, std::false_type) {
        for (Distance i(0); i < distance && iter != end; ++i) {
            ++iter;
        }
    }

    template <typename Iter, typename Distance>
    void dumb_advance_impl(Iter& iter, const Iter& end,
            Distance distance, std::true_type) {
        if (static_cast<Distance>(end - iter) < distance) {
            iter = end;
        } else {
            iter += distance;
        }
    }

    // iter will not be incremented past end
    template <typename Iter, typename Distance =std::size_t>
    void dumb_advance(Iter& iter, const Iter& end, Distance distance=1) {
        dumb_advance_impl(iter, end, distance, is_random_access_iter<Iter>{});
    }

    template <typename ForwardIt, typename Distance =std::size_t>
    ForwardIt dumb_next(ForwardIt it, Distance distance=1) {
        dumb_advance(it, distance);
        return it;
    }

    template <typename ForwardIt, typename Distance =std::size_t>
    ForwardIt dumb_next(
            ForwardIt it, const ForwardIt& end, Distance distance=1) {
        dumb_advance(it, end, distance);
        return it;
    }

    template <typename Container, typename Distance =std::size_t>
    Distance dumb_size(Container&& container) {
        Distance d{0};
        for (auto it = std::begin(container), end = std::end(container);
                it != end;
                ++it) {
            ++d;
        }
        return d;
    }

    template <typename... Ts>
    struct are_same : std::true_type { };

    template <typename T, typename U, typename... Ts>
    struct are_same<T, U, Ts...>
        : std::integral_constant<bool,
            std::is_same<T, U>::value && are_same<T, Ts...>::value> { };

    namespace detail {
        template <typename... Ts>
        std::tuple<iterator_type<Ts>...> iterator_tuple_type_helper(
                const std::tuple<Ts...>&);
    }
    // Given a tuple template argument, evaluates to a tuple of iterators
    // for the template argument's contained types.
    template <typename TupleType>
    using iterator_tuple_type =
        decltype(detail::iterator_tuple_type_helper(
                    std::declval<TupleType>()));

    namespace detail {
        template <typename... Ts>
        std::tuple<iterator_deref<Ts>...> iterator_tuple_deref_helper(
                const std::tuple<Ts...>&);
    }

    // Given a tuple template argument, evaluates to a tuple of
    // what the iterators for the template argument's contained types
    // dereference to
    template <typename TupleType>
    using iterator_deref_tuple =
        decltype(detail::iterator_tuple_deref_helper(
                    std::declval<TupleType>()));

    // ---- Tuple utilities ---- //

    // function absorbing all arguments passed to it. used when
    // applying a function to a parameter pack but not passing the evaluated
    // results anywhere
    template <typename... Ts>
    void absorb(Ts&&...) { }

    namespace detail {
        template <typename Func, typename TupleType, std::size_t... Is>
        decltype(auto) call_with_tuple_impl(Func&& mf, TupleType&& tup,
                std::index_sequence<Is...>) {
            return mf(std::forward<
                        std::tuple_element_t<
                            Is, std::remove_reference_t<TupleType>>
                        >(std::get<Is>(tup))...);
        }
    }

    // expand a TupleType into individual arguments when calling a Func
    template <typename Func, typename TupleType>
    decltype(auto) call_with_tuple(Func&& mf, TupleType&& tup) {
        constexpr auto TUP_SIZE = std::tuple_size<
            std::decay_t<TupleType>>::value;
        return detail::call_with_tuple_impl(
                std::forward<Func>(mf),
                std::forward<TupleType>(tup),
                std::make_index_sequence<TUP_SIZE>{});
    }

    // DerefHolder holds the value gotten from an iterator dereference
    // if the iterate dereferences to an lvalue references, a pointer to the
    //     element is stored
    // if it does not, a value is stored instead
    // get() returns a reference to the held item in either case
    // pull() should be used when the item is being "pulled out" of the
    //     DerefHolder.  after pull() is called, neither it nor get() can be
    //     safely called after
    // reset() replaces the currently held item and may be called after pull()

    template <typename T, typename =void>
    class DerefHolder {
        private:
            static_assert(!std::is_lvalue_reference<T>::value,
                    "Non-lvalue-ref specialization used for lvalue ref type");
            // it could still be an rvalue reference
            using TPlain = std::remove_reference_t<T>;

            std::unique_ptr<TPlain> item_p;

        public:
            DerefHolder() = default;

            DerefHolder(const DerefHolder& other)
                : item_p{other.item_p ? new TPlain(*other.item_p) : nullptr}
            { }

            DerefHolder& operator=(const DerefHolder& other) {
                this->item_p.reset(other.item_p
                        ? new TPlain(*other.item_p) : nullptr);
                return *this;
            }

            DerefHolder(DerefHolder&&) = default;
            DerefHolder& operator=(DerefHolder&&) = default;
            ~DerefHolder() = default;

            TPlain& get() {
                return *item_p;
            }

            T pull() {
                // NOTE should I reset the unique_ptr to nullptr here
                // since its held item is now invalid anyway?
                return std::move(*item_p);
            }

            void reset(T&& item) {
                item_p.reset(new TPlain(std::move(item)));
            }

            explicit operator bool() const {
                return this->item_p;
            }
    };

    // Specialization for when T is an lvalue ref.  Keep this in mind
    // wherever a T appears.
    template <typename T>
    class DerefHolder<T,
        typename std::enable_if<std::is_lvalue_reference<T>::value>::type>
    {
        private:
            static_assert(std::is_lvalue_reference<T>::value,
                    "lvalue specialization handling non-lvalue-ref type");

            std::remove_reference_t<T> *item_p =nullptr;
        public:
            DerefHolder() = default;

            T get() {
                return *this->item_p;
            }

            T pull() {
                return this->get();
            }

            void reset(T item) {
                this->item_p = &item;
            }

            explicit operator bool() const {
                return this->item_p != nullptr;
            }
    };

    template <typename T>
    struct type_is {
        using type = T;
    };

    // gcc CWG 1558
    template <typename...>
    struct void_t_help {
        using type = void;
    };
    template <typename... Ts>
    using void_t = typename void_t_help<Ts...>::type;
}

#endif
<|endoftext|>


<commit_before>/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "settings.h"
#include <QSettings>
#include <QDir>
#include "devicesettings.h"

#define PATH QString("%1%2.config%2/cameraplus.conf").arg(QDir::homePath()).arg(QDir::separator())

#define DEFAULT_MODE                    1
#define DEFAULT_USE_GPS                 true
#define DEFAULT_USE_GEOTAGS             true
#define DEFAULT_SOUND_ENABLED           true
#define DEFAULT_SHOW_TOOL_BAR           false
#define DEFAULT_VIDEO_MUTE              false
#define DEFAULT_GRID_ENABLED            false
#define DEFAULT_FACE_DETECTION_ENABLED  true
#define DEFAULT_ZOOM_AS_SHUTTER         false
#define DEFAULT_PROXIMITY_AS_SHUTTER    false
#define DEFAULT_DEVICE                  0
#define DEFAULT_ENABLE_PREVIEW          true
#define DEFAULT_NIGHT_MODE              false
#define DEFAULT_PLUGIN                  "org.foolab.cameraplus.image"
#define DEFAULT_CAPTURE_TIMER_DELAY     5

Settings::Settings(QObject *parent) :
  QObject(parent),
  m_settings(new QSettings(PATH, QSettings::IniFormat, this)) {

}

Settings::~Settings() {
  delete m_settings; m_settings = 0;
}

int Settings::mode() const {
  return m_settings->value("camera/mode", DEFAULT_MODE).toInt();
}

void Settings::setMode(int mode) {
  if (mode != Settings::mode()) {
    m_settings->setValue("camera/mode", mode);

    emit modeChanged();
  }
}

QString Settings::creatorName() const {
  return m_settings->value("camera/creatorName").toString();
}

void Settings::setCreatorName(const QString& name) {
  if (name != creatorName()) {
    m_settings->setValue("camera/creatorName", name);

    emit creatorNameChanged();
  }
}

bool Settings::useGps() const {
  return m_settings->value("camera/useGps", DEFAULT_USE_GPS).toBool();
}

void Settings::setUseGps(bool enable) {
  if (enable != useGps()) {
    m_settings->setValue("camera/useGps", enable);

    emit useGpsChanged();
  }
}

bool Settings::useGeotags() const {
  return m_settings->value("camera/useGeotags", DEFAULT_USE_GEOTAGS).toBool();
}

void Settings::setUseGeotags(bool enable) {
  if (enable != useGeotags()) {
    m_settings->setValue("camera/useGeotags", enable);

    emit useGeotagsChanged();
  }
}

bool Settings::isSoundEnabled() const {
  return m_settings->value("camera/soundEnabled", DEFAULT_SOUND_ENABLED).toBool();
}

void Settings::setSoundEnabled(bool enabled) {
  if (isSoundEnabled() != enabled) {
    m_settings->setValue("camera/soundEnabled", enabled);
    emit soundEnabledChanged();
  }
}

bool Settings::isToolBarShown() const {
  return m_settings->value("camera/showToolBar", DEFAULT_SHOW_TOOL_BAR).toBool();
}

void Settings::setToolBarShown(bool shown) {
  if (isToolBarShown() != shown) {
    m_settings->setValue("camera/showToolBar", shown);

    emit toolBarShownChanged();
  }
}

bool Settings::isGridEnabled() const {
  return m_settings->value("camera/gridEnabled", DEFAULT_GRID_ENABLED).toBool();
}

void Settings::setGridEnabled(bool enabled) {
  if (enabled != isGridEnabled()) {
    m_settings->setValue("camera/gridEnabled", enabled);
    emit gridEnabledChanged();
  }
}

bool Settings::isFaceDetectionEnabled() const {
  return m_settings->value("image/faceDetectionEnabled", DEFAULT_FACE_DETECTION_ENABLED).toBool();
}

void Settings::setFaceDetectionEnabled(bool enabled) {
  if (isFaceDetectionEnabled() != enabled) {
    m_settings->setValue("image/faceDetectionEnabled", enabled);
    emit faceDetectionEnabledChanged();
  }
}

bool Settings::isZoomAsShutterEnabled() const {
  return m_settings->value("camera/zoomAsShutter", DEFAULT_ZOOM_AS_SHUTTER).toBool();
}

void Settings::setZoomAsShutterEnabled(bool enabled) {
  if (isZoomAsShutterEnabled() != enabled) {
    m_settings->setValue("camera/zoomAsShutter", enabled);

    emit zoomAsShutterChanged();
  }
}

bool Settings::isProximityAsShutterEnabled() const {
  return m_settings->value("camera/proximityAsShutter", DEFAULT_PROXIMITY_AS_SHUTTER).toBool();
}

void Settings::setProximityAsShutterEnabled(bool enabled) {
  if (isProximityAsShutterEnabled() != enabled) {
    m_settings->setValue("camera/proximityAsShutter", enabled);

    emit proximityAsShutterChanged();
  }
}

int Settings::device() const {
  return m_settings->value("camera/device", DEFAULT_DEVICE).toInt();
}

void Settings::setDevice(int device) {
  if (device != Settings::device()) {
    m_settings->setValue("camera/device", device);
    emit deviceChanged();
  }
}

QVariant Settings::value(const QString& key, const QVariant& defaultValue) const {
  return m_settings->value(key, defaultValue);
}

void Settings::setValue(const QString& key, const QVariant& value)  {
  m_settings->setValue(key, value);
}

QString Settings::fileNamingStamp(const QString& id) const {
  QString key = QString("fileNaming/%1").arg(id);
  return m_settings->value(key).toString();
}

void Settings::setFileNamingStamp(const QString& id, const QString& stamp) {
  QString key = QString("fileNaming/%1").arg(id);
  m_settings->setValue(key, stamp);
}

int Settings::fileNamingCounter(const QString& id) const {
  QString key = QString("fileNaming/%1").arg(id);
  return m_settings->value(key).toInt();
}

void Settings::setFileNamingCounter(const QString& id, int counter) {
  QString key = QString("fileNaming/%1").arg(id);
  m_settings->setValue(key, counter);
}

bool Settings::isPreviewEnabled() const {
  return m_settings->value("camera/enablePreview", DEFAULT_ENABLE_PREVIEW).toBool();
}

void Settings::setPreviewEnabled(bool enabled) {
  if (enabled != isPreviewEnabled()) {
    m_settings->setValue("camera/enablePreview", enabled);

    emit previewEnabledChanged();
  }
}

bool Settings::isNightModeEnabled() const {
  return m_settings->value("camera/nightMode", DEFAULT_NIGHT_MODE).toBool();
}

void Settings::setNightModeEnabled(bool enabled) {
  if (isNightModeEnabled() != enabled) {
    m_settings->setValue("camera/nightMode", enabled);
    emit nightModeChanged();
  }
}

QString Settings::plugin() const {
  return m_settings->value("camera/plugin", DEFAULT_PLUGIN).toString();
}

void Settings::setPlugin(const QString& plugin) {
  if (Settings::plugin() != plugin) {
    m_settings->setValue("camera/plugin", plugin);
    emit pluginChanged();
  }
}

int Settings::captureTimerDelay() const {
  return m_settings->value("captureTimer/delay", DEFAULT_CAPTURE_TIMER_DELAY).toInt();
}

void Settings::setCaptureTimerDelay(int delay) {
  if (delay != captureTimerDelay()) {
    m_settings->setValue("captureTimer/delay", delay);
    emit captureTimerDelayChanged();
  }
}
<commit_msg>sailfish: adjust the settings path to be harbour compliant<commit_after>/*!
 * This file is part of CameraPlus.
 *
 * Copyright (C) 2012-2014 Mohammed Sameer <msameer@foolab.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "settings.h"
#include <QSettings>
#include <QDir>
#include "devicesettings.h"

#ifdef SAILFISH
#define PATH QString("%1%2.config%2harbour-cameraplus%2harbour-cameraplus.conf").arg(QDir::homePath()).arg(QDir::separator())
#else
#define PATH QString("%1%2.config%2cameraplus.conf").arg(QDir::homePath()).arg(QDir::separator())
#endif

#define DEFAULT_MODE                    1
#define DEFAULT_USE_GPS                 true
#define DEFAULT_USE_GEOTAGS             true
#define DEFAULT_SOUND_ENABLED           true
#define DEFAULT_SHOW_TOOL_BAR           false
#define DEFAULT_VIDEO_MUTE              false
#define DEFAULT_GRID_ENABLED            false
#define DEFAULT_FACE_DETECTION_ENABLED  true
#define DEFAULT_ZOOM_AS_SHUTTER         false
#define DEFAULT_PROXIMITY_AS_SHUTTER    false
#define DEFAULT_DEVICE                  0
#define DEFAULT_ENABLE_PREVIEW          true
#define DEFAULT_NIGHT_MODE              false
#define DEFAULT_PLUGIN                  "org.foolab.cameraplus.image"
#define DEFAULT_CAPTURE_TIMER_DELAY     5

Settings::Settings(QObject *parent) :
  QObject(parent),
  m_settings(new QSettings(PATH, QSettings::IniFormat, this)) {

}

Settings::~Settings() {
  delete m_settings; m_settings = 0;
}

int Settings::mode() const {
  return m_settings->value("camera/mode", DEFAULT_MODE).toInt();
}

void Settings::setMode(int mode) {
  if (mode != Settings::mode()) {
    m_settings->setValue("camera/mode", mode);

    emit modeChanged();
  }
}

QString Settings::creatorName() const {
  return m_settings->value("camera/creatorName").toString();
}

void Settings::setCreatorName(const QString& name) {
  if (name != creatorName()) {
    m_settings->setValue("camera/creatorName", name);

    emit creatorNameChanged();
  }
}

bool Settings::useGps() const {
  return m_settings->value("camera/useGps", DEFAULT_USE_GPS).toBool();
}

void Settings::setUseGps(bool enable) {
  if (enable != useGps()) {
    m_settings->setValue("camera/useGps", enable);

    emit useGpsChanged();
  }
}

bool Settings::useGeotags() const {
  return m_settings->value("camera/useGeotags", DEFAULT_USE_GEOTAGS).toBool();
}

void Settings::setUseGeotags(bool enable) {
  if (enable != useGeotags()) {
    m_settings->setValue("camera/useGeotags", enable);

    emit useGeotagsChanged();
  }
}

bool Settings::isSoundEnabled() const {
  return m_settings->value("camera/soundEnabled", DEFAULT_SOUND_ENABLED).toBool();
}

void Settings::setSoundEnabled(bool enabled) {
  if (isSoundEnabled() != enabled) {
    m_settings->setValue("camera/soundEnabled", enabled);
    emit soundEnabledChanged();
  }
}

bool Settings::isToolBarShown() const {
  return m_settings->value("camera/showToolBar", DEFAULT_SHOW_TOOL_BAR).toBool();
}

void Settings::setToolBarShown(bool shown) {
  if (isToolBarShown() != shown) {
    m_settings->setValue("camera/showToolBar", shown);

    emit toolBarShownChanged();
  }
}

bool Settings::isGridEnabled() const {
  return m_settings->value("camera/gridEnabled", DEFAULT_GRID_ENABLED).toBool();
}

void Settings::setGridEnabled(bool enabled) {
  if (enabled != isGridEnabled()) {
    m_settings->setValue("camera/gridEnabled", enabled);
    emit gridEnabledChanged();
  }
}

bool Settings::isFaceDetectionEnabled() const {
  return m_settings->value("image/faceDetectionEnabled", DEFAULT_FACE_DETECTION_ENABLED).toBool();
}

void Settings::setFaceDetectionEnabled(bool enabled) {
  if (isFaceDetectionEnabled() != enabled) {
    m_settings->setValue("image/faceDetectionEnabled", enabled);
    emit faceDetectionEnabledChanged();
  }
}

bool Settings::isZoomAsShutterEnabled() const {
  return m_settings->value("camera/zoomAsShutter", DEFAULT_ZOOM_AS_SHUTTER).toBool();
}

void Settings::setZoomAsShutterEnabled(bool enabled) {
  if (isZoomAsShutterEnabled() != enabled) {
    m_settings->setValue("camera/zoomAsShutter", enabled);

    emit zoomAsShutterChanged();
  }
}

bool Settings::isProximityAsShutterEnabled() const {
  return m_settings->value("camera/proximityAsShutter", DEFAULT_PROXIMITY_AS_SHUTTER).toBool();
}

void Settings::setProximityAsShutterEnabled(bool enabled) {
  if (isProximityAsShutterEnabled() != enabled) {
    m_settings->setValue("camera/proximityAsShutter", enabled);

    emit proximityAsShutterChanged();
  }
}

int Settings::device() const {
  return m_settings->value("camera/device", DEFAULT_DEVICE).toInt();
}

void Settings::setDevice(int device) {
  if (device != Settings::device()) {
    m_settings->setValue("camera/device", device);
    emit deviceChanged();
  }
}

QVariant Settings::value(const QString& key, const QVariant& defaultValue) const {
  return m_settings->value(key, defaultValue);
}

void Settings::setValue(const QString& key, const QVariant& value)  {
  m_settings->setValue(key, value);
}

QString Settings::fileNamingStamp(const QString& id) const {
  QString key = QString("fileNaming/%1").arg(id);
  return m_settings->value(key).toString();
}

void Settings::setFileNamingStamp(const QString& id, const QString& stamp) {
  QString key = QString("fileNaming/%1").arg(id);
  m_settings->setValue(key, stamp);
}

int Settings::fileNamingCounter(const QString& id) const {
  QString key = QString("fileNaming/%1").arg(id);
  return m_settings->value(key).toInt();
}

void Settings::setFileNamingCounter(const QString& id, int counter) {
  QString key = QString("fileNaming/%1").arg(id);
  m_settings->setValue(key, counter);
}

bool Settings::isPreviewEnabled() const {
  return m_settings->value("camera/enablePreview", DEFAULT_ENABLE_PREVIEW).toBool();
}

void Settings::setPreviewEnabled(bool enabled) {
  if (enabled != isPreviewEnabled()) {
    m_settings->setValue("camera/enablePreview", enabled);

    emit previewEnabledChanged();
  }
}

bool Settings::isNightModeEnabled() const {
  return m_settings->value("camera/nightMode", DEFAULT_NIGHT_MODE).toBool();
}

void Settings::setNightModeEnabled(bool enabled) {
  if (isNightModeEnabled() != enabled) {
    m_settings->setValue("camera/nightMode", enabled);
    emit nightModeChanged();
  }
}

QString Settings::plugin() const {
  return m_settings->value("camera/plugin", DEFAULT_PLUGIN).toString();
}

void Settings::setPlugin(const QString& plugin) {
  if (Settings::plugin() != plugin) {
    m_settings->setValue("camera/plugin", plugin);
    emit pluginChanged();
  }
}

int Settings::captureTimerDelay() const {
  return m_settings->value("captureTimer/delay", DEFAULT_CAPTURE_TIMER_DELAY).toInt();
}

void Settings::setCaptureTimerDelay(int delay) {
  if (delay != captureTimerDelay()) {
    m_settings->setValue("captureTimer/delay", delay);
    emit captureTimerDelayChanged();
  }
}
<|endoftext|>


<commit_before>#include <cctype>
#include <fstream>
#include <stdio.h>
#include <sstream> // ostringstream
#include "utils/logoutput.h"

#include "settings.h"
#include "settingRegistry.h"

//c++11 no longer defines M_PI, so add our own constant.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

SettingsBase::SettingsBase()
: parent(NULL)
{
}

SettingsBase::SettingsBase(SettingsBase* parent)
: parent(parent)
{
}

void SettingsBase::setSetting(std::string key, std::string value)
{
    if (SettingRegistry::getInstance()->settingExists(key))
    {
        setting_values[key] = value;
    }
    else
    {
        cura::logError("Warning: setting an unregistered setting %s\n", key.c_str() );
        setting_values[key] = value; // Handy when programmers are in the process of introducing a new setting
    }
}

std::string SettingsBase::getSettingString(std::string key)
{
    if (setting_values.find(key) != setting_values.end())
    {
        return setting_values[key];
    }
    if (parent)
    {
        return parent->getSettingString(key);
    }

    if (SettingRegistry::getInstance()->settingExists(key))
    {
        setting_values[key] = SettingRegistry::getInstance()->getSettingConfig(key)->getDefaultValue();
        //cura::logError("Using default for: %s = %s\n", key.c_str(), setting_values[key].c_str());
    }
    else
    {
        setting_values[key] = "";
        cura::logError("Unregistered setting %s\n", key.c_str());
    }
    return setting_values[key];
}

bool SettingsBase::hasSetting(std::string key)
{
    if (setting_values.find(key) != setting_values.end())
    {
        return true;
    }
    if (parent)
    {
        return parent->hasSetting(key);
    }

    return false;
}

int SettingsBase::getSettingAsIndex(std::string key)
{
    std::string value = getSettingString(key);
    return atoi(value.c_str());
}

int SettingsBase::getSettingAsCount(std::string key)
{
    std::string value = getSettingString(key);
    return atoi(value.c_str());
}

int SettingsBase::getSettingInMicrons(std::string key)
{
    std::string value = getSettingString(key);
    return atof(value.c_str()) * 1000.0;
}

double SettingsBase::getSettingInAngleRadians(std::string key)
{
    std::string value = getSettingString(key);
    return atof(value.c_str()) / 180.0 * M_PI;
}

bool SettingsBase::getSettingBoolean(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "on")
        return true;
    if (value == "yes")
        return true;
    if (value == "true")
        return true;
    return atoi(value.c_str()) != 0;
}

double SettingsBase::getSettingInDegreeCelsius(std::string key)
{
    std::string value = getSettingString(key);
    return atof(value.c_str());
}

double SettingsBase::getSettingInMillimetersPerSecond(std::string key)
{
    std::string value = getSettingString(key);
    return std::max(1.0, atof(value.c_str()));
}

double SettingsBase::getSettingInPercentage(std::string key)
{
    std::string value = getSettingString(key);
    return std::max(0.0, atof(value.c_str()));
}

double SettingsBase::getSettingInSeconds(std::string key)
{
    std::string value = getSettingString(key);
    return std::max(0.0, atof(value.c_str()));
}

EGCodeFlavor SettingsBase::getSettingAsGCodeFlavor(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "RepRap")
        return GCODE_FLAVOR_REPRAP;
    else if (value == "UltiGCode")
        return GCODE_FLAVOR_ULTIGCODE;
    else if (value == "Makerbot")
        return GCODE_FLAVOR_MAKERBOT;
    else if (value == "BFB")
        return GCODE_FLAVOR_BFB;
    else if (value == "MACH3")
        return GCODE_FLAVOR_MACH3;
    else if (value == "RepRap (Volumatric)")
        return GCODE_FLAVOR_REPRAP_VOLUMATRIC;
    return GCODE_FLAVOR_REPRAP;
}

EFillMethod SettingsBase::getSettingAsFillMethod(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "Lines")
        return Fill_Lines;
    if (value == "Grid")
        return Fill_Grid;
    if (value == "Triangles")
        return Fill_Triangles;
    if (value == "Concentric")
        return Fill_Concentric;
    if (value == "ZigZag")
        return Fill_ZigZag;
    return Fill_None;
}

EPlatformAdhesion SettingsBase::getSettingAsPlatformAdhesion(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "Brim")
        return Adhesion_Brim;
    if (value == "Raft")
        return Adhesion_Raft;
    return Adhesion_None;
}

ESupportType SettingsBase::getSettingAsSupportType(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "Everywhere")
        return Support_Everywhere;
    if (value == "Touching Buildplate")
        return Support_PlatformOnly;
    return Support_None;
}
<commit_msg>Fix support generation by making sure "True" is also recognised as true<commit_after>#include <cctype>
#include <fstream>
#include <stdio.h>
#include <sstream> // ostringstream
#include "utils/logoutput.h"

#include "settings.h"
#include "settingRegistry.h"

//c++11 no longer defines M_PI, so add our own constant.
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

SettingsBase::SettingsBase()
: parent(NULL)
{
}

SettingsBase::SettingsBase(SettingsBase* parent)
: parent(parent)
{
}

void SettingsBase::setSetting(std::string key, std::string value)
{
    if (SettingRegistry::getInstance()->settingExists(key))
    {
        setting_values[key] = value;
    }
    else
    {
        cura::logError("Warning: setting an unregistered setting %s\n", key.c_str() );
        setting_values[key] = value; // Handy when programmers are in the process of introducing a new setting
    }
}

std::string SettingsBase::getSettingString(std::string key)
{
    if (setting_values.find(key) != setting_values.end())
    {
        return setting_values[key];
    }
    if (parent)
    {
        return parent->getSettingString(key);
    }

    if (SettingRegistry::getInstance()->settingExists(key))
    {
        setting_values[key] = SettingRegistry::getInstance()->getSettingConfig(key)->getDefaultValue();
        //cura::logError("Using default for: %s = %s\n", key.c_str(), setting_values[key].c_str());
    }
    else
    {
        setting_values[key] = "";
        cura::logError("Unregistered setting %s\n", key.c_str());
    }
    return setting_values[key];
}

bool SettingsBase::hasSetting(std::string key)
{
    if (setting_values.find(key) != setting_values.end())
    {
        return true;
    }
    if (parent)
    {
        return parent->hasSetting(key);
    }

    return false;
}

int SettingsBase::getSettingAsIndex(std::string key)
{
    std::string value = getSettingString(key);
    return atoi(value.c_str());
}

int SettingsBase::getSettingAsCount(std::string key)
{
    std::string value = getSettingString(key);
    return atoi(value.c_str());
}

int SettingsBase::getSettingInMicrons(std::string key)
{
    std::string value = getSettingString(key);
    return atof(value.c_str()) * 1000.0;
}

double SettingsBase::getSettingInAngleRadians(std::string key)
{
    std::string value = getSettingString(key);
    return atof(value.c_str()) / 180.0 * M_PI;
}

bool SettingsBase::getSettingBoolean(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "on")
        return true;
    if (value == "yes")
        return true;
    if (value == "true" or value == "True") //Python uses "True"
        return true;
    return atoi(value.c_str()) != 0;
}

double SettingsBase::getSettingInDegreeCelsius(std::string key)
{
    std::string value = getSettingString(key);
    return atof(value.c_str());
}

double SettingsBase::getSettingInMillimetersPerSecond(std::string key)
{
    std::string value = getSettingString(key);
    return std::max(1.0, atof(value.c_str()));
}

double SettingsBase::getSettingInPercentage(std::string key)
{
    std::string value = getSettingString(key);
    return std::max(0.0, atof(value.c_str()));
}

double SettingsBase::getSettingInSeconds(std::string key)
{
    std::string value = getSettingString(key);
    return std::max(0.0, atof(value.c_str()));
}

EGCodeFlavor SettingsBase::getSettingAsGCodeFlavor(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "RepRap")
        return GCODE_FLAVOR_REPRAP;
    else if (value == "UltiGCode")
        return GCODE_FLAVOR_ULTIGCODE;
    else if (value == "Makerbot")
        return GCODE_FLAVOR_MAKERBOT;
    else if (value == "BFB")
        return GCODE_FLAVOR_BFB;
    else if (value == "MACH3")
        return GCODE_FLAVOR_MACH3;
    else if (value == "RepRap (Volumatric)")
        return GCODE_FLAVOR_REPRAP_VOLUMATRIC;
    return GCODE_FLAVOR_REPRAP;
}

EFillMethod SettingsBase::getSettingAsFillMethod(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "Lines")
        return Fill_Lines;
    if (value == "Grid")
        return Fill_Grid;
    if (value == "Triangles")
        return Fill_Triangles;
    if (value == "Concentric")
        return Fill_Concentric;
    if (value == "ZigZag")
        return Fill_ZigZag;
    return Fill_None;
}

EPlatformAdhesion SettingsBase::getSettingAsPlatformAdhesion(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "Brim")
        return Adhesion_Brim;
    if (value == "Raft")
        return Adhesion_Raft;
    return Adhesion_None;
}

ESupportType SettingsBase::getSettingAsSupportType(std::string key)
{
    std::string value = getSettingString(key);
    if (value == "Everywhere")
        return Support_Everywhere;
    if (value == "Touching Buildplate")
        return Support_PlatformOnly;
    return Support_None;
}
<|endoftext|>


<commit_before>///
/// @file   test.cpp
/// @brief  bool soe::test(); runs sieving tests to ensure that
///         ParallelPrimeSieve objects produce correct results.
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/soe/ParallelPrimeSieve.h>

#include <iostream>
#include <iomanip>
#include <exception>
#include <stdexcept>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <stdint.h>

using namespace std;

namespace soe {

/// Correct values to compare with test results
const unsigned int primeCounts[19] =
{
  4,           // pi(10^1)
  25,          // pi(10^2)
  168,         // pi(10^3)
  1229,        // pi(10^4)
  9592,        // pi(10^5)
  78498,       // pi(10^6)
  664579,      // pi(10^7)
  5761455,     // pi(10^8)
  50847534,    // pi(10^9)
  455052511,   // pi(10^10)
  155428406,   // pi[10^12, 10^12+2^32]
  143482916,   // pi[10^13, 10^13+2^32]
  133235063,   // pi[10^14, 10^14+2^32]
  124350420,   // pi[10^15, 10^15+2^32]
  116578809,   // pi[10^16, 10^16+2^32]
  109726486,   // pi[10^17, 10^17+2^32]
  103626726,   // pi[10^18, 10^18+2^32]
  98169972,    // pi[10^19, 10^19+2^32]
  2895317534U  // pi[10^15, 10^15+10^11]
};

/// Keeps the memory usage below 1GB
const int maxThreads[8] = { 32, 32, 32, 32, 32, 8, 4, 1 };

uint64_t ipow(uint64_t x, int n)
{
  uint64_t result = 1;
  while (n != 0)
  {
    if ((n & 1) != 0)
    {
      result *= x;
      n -= 1;
    }
    x *= x;
    n /= 2;
  }
  return result;
}

/// Get a random 64-bit integer < limit
uint64_t getRand64(uint64_t limit)
{
  uint64_t rand64 = 0;
  for (int i = 0; i < 4; i++)
    rand64 = rand() % (1 << 16) + (rand64 << (i * 16));
  return rand64 % limit;
}

void check(bool isCorrect)
{
  cout << (isCorrect ? "OK" : "ERROR") << endl;
  if (!isCorrect)
    throw runtime_error("test failed!");
}

/// Count the primes up to 10^10
void testPix()
{
  cout << "pi(x) : Prime-counting function test" << endl;
  ParallelPrimeSieve pps;
  pps.setStart(0);
  pps.setStop(0);
  uint64_t primeCount = 0;

  // pi(x) with x = 10^i for i = 1 to 10
  for (int i = 1; i <= 10; i++)
  {
    primeCount += pps.countPrimes(pps.getStop() + 1, ipow(10, i));
    cout << "pi(10^" << i << (i < 10 ? ")  = " : ") = ") << setw(12) << primeCount;
    check(primeCount == primeCounts[i - 1]);
  }
  cout << endl;
}

/// Count the primes within [10^i, 10^i+2^32] for i = 12 to 19
void testBigPrimes()
{
  ParallelPrimeSieve pps;
  pps.setFlags(pps.COUNT_PRIMES | pps.PRINT_STATUS);

  for (int i = 12; i <= 19; i++)
  {
    cout << "Sieving the primes within [10^" << i << ", 10^" << i << "+2^32]" << endl;
    pps.setStart(ipow(10, i));
    pps.setStop(pps.getStart() + ipow(2, 32));
    pps.setNumThreads(min(pps.getNumThreads(), maxThreads[i - 12]));
    pps.sieve();
    cout << "\rPrime count: " << setw(11) << pps.getPrimeCount();
    check(pps.getPrimeCount() == primeCounts[i - 2]);
  }
  cout << endl;
}

/// Sieve about 200 small random intervals until the interval
/// [10^15, 10^15+10^11] has been completed.
///
void testRandomIntervals()
{
  cout << "Sieving the primes within [10^15, 10^15+10^11] randomly" << endl;
  uint64_t maxInterval = ipow(10, 9);
  uint64_t lowerBound = ipow(10, 15);
  uint64_t upperBound = lowerBound + ipow(10, 11);
  uint64_t primeCount = 0;
  srand(static_cast<unsigned int>(time(0)));
  ParallelPrimeSieve pps;
  pps.setStart(lowerBound - 1);
  pps.setStop(lowerBound - 1);

  while (pps.getStop() < upperBound)
  {
    pps.setStart(pps.getStop() + 1);
    pps.setStop(min(pps.getStart() + getRand64(maxInterval), upperBound));
    pps.setSieveSize(1 << (rand() % 12));
    pps.sieve();
    primeCount += pps.getPrimeCount();
    cout << "\rRemaining chunk:             "
         << "\rRemaining chunk: "
         << upperBound - pps.getStop() << flush;
  }
  cout << endl << "Prime count: " << setw(11) << primeCount;
  check(primeCount == primeCounts[18]);
  cout << endl;
}

/// Run various sieving tests to ensure that ParallelPrimeSieve
/// (and PrimeSieve) objects produce correct results.
/// The tests use up to 1 GB of memory and take about 3 minutes to
/// complete on a dual core CPU from 2011.
/// @return true  If no error occurred else false.
///
bool test()
{
  cout << left;
  try
  {
    testPix();
    testBigPrimes();
    testRandomIntervals();
  }
  catch (exception& e)
  {
    cerr << endl << "Error: " << e.what() << endl;
    return false;
  }
  cout << "All tests passed successfully!" << endl;
  return true;
}

} // end namespace
<commit_msg>Comment<commit_after>///
/// @file   test.cpp
/// @brief  bool soe::test(); runs prime sieving tests to ensure that
///         ParallelPrimeSieve objects produce correct results.
///
/// Copyright (C) 2013 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primesieve/soe/ParallelPrimeSieve.h>

#include <iostream>
#include <iomanip>
#include <exception>
#include <stdexcept>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <stdint.h>

using namespace std;

namespace soe {

/// Correct values to compare with test results
const unsigned int primeCounts[19] =
{
  4,           // pi(10^1)
  25,          // pi(10^2)
  168,         // pi(10^3)
  1229,        // pi(10^4)
  9592,        // pi(10^5)
  78498,       // pi(10^6)
  664579,      // pi(10^7)
  5761455,     // pi(10^8)
  50847534,    // pi(10^9)
  455052511,   // pi(10^10)
  155428406,   // pi[10^12, 10^12+2^32]
  143482916,   // pi[10^13, 10^13+2^32]
  133235063,   // pi[10^14, 10^14+2^32]
  124350420,   // pi[10^15, 10^15+2^32]
  116578809,   // pi[10^16, 10^16+2^32]
  109726486,   // pi[10^17, 10^17+2^32]
  103626726,   // pi[10^18, 10^18+2^32]
  98169972,    // pi[10^19, 10^19+2^32]
  2895317534U  // pi[10^15, 10^15+10^11]
};

/// Keeps the memory usage below 1GB
const int maxThreads[8] = { 32, 32, 32, 32, 32, 8, 4, 1 };

uint64_t ipow(uint64_t x, int n)
{
  uint64_t result = 1;
  while (n != 0)
  {
    if ((n & 1) != 0)
    {
      result *= x;
      n -= 1;
    }
    x *= x;
    n /= 2;
  }
  return result;
}

/// Get a random 64-bit integer < limit
uint64_t getRand64(uint64_t limit)
{
  uint64_t rand64 = 0;
  for (int i = 0; i < 4; i++)
    rand64 = rand() % (1 << 16) + (rand64 << (i * 16));
  return rand64 % limit;
}

void check(bool isCorrect)
{
  cout << (isCorrect ? "OK" : "ERROR") << endl;
  if (!isCorrect)
    throw runtime_error("test failed!");
}

/// Count the primes up to 10^10
void testPix()
{
  cout << "pi(x) : Prime-counting function test" << endl;
  ParallelPrimeSieve pps;
  pps.setStart(0);
  pps.setStop(0);
  uint64_t primeCount = 0;

  // pi(x) with x = 10^i for i = 1 to 10
  for (int i = 1; i <= 10; i++)
  {
    primeCount += pps.countPrimes(pps.getStop() + 1, ipow(10, i));
    cout << "pi(10^" << i << (i < 10 ? ")  = " : ") = ") << setw(12) << primeCount;
    check(primeCount == primeCounts[i - 1]);
  }
  cout << endl;
}

/// Count the primes within [10^i, 10^i+2^32] for i = 12 to 19
void testBigPrimes()
{
  ParallelPrimeSieve pps;
  pps.setFlags(pps.COUNT_PRIMES | pps.PRINT_STATUS);

  for (int i = 12; i <= 19; i++)
  {
    cout << "Sieving the primes within [10^" << i << ", 10^" << i << "+2^32]" << endl;
    pps.setStart(ipow(10, i));
    pps.setStop(pps.getStart() + ipow(2, 32));
    pps.setNumThreads(min(pps.getNumThreads(), maxThreads[i - 12]));
    pps.sieve();
    cout << "\rPrime count: " << setw(11) << pps.getPrimeCount();
    check(pps.getPrimeCount() == primeCounts[i - 2]);
  }
  cout << endl;
}

/// Sieve about 200 small random intervals until the interval
/// [10^15, 10^15+10^11] has been completed.
///
void testRandomIntervals()
{
  cout << "Sieving the primes within [10^15, 10^15+10^11] randomly" << endl;
  uint64_t maxInterval = ipow(10, 9);
  uint64_t lowerBound = ipow(10, 15);
  uint64_t upperBound = lowerBound + ipow(10, 11);
  uint64_t primeCount = 0;
  srand(static_cast<unsigned int>(time(0)));
  ParallelPrimeSieve pps;
  pps.setStart(lowerBound - 1);
  pps.setStop(lowerBound - 1);

  while (pps.getStop() < upperBound)
  {
    pps.setStart(pps.getStop() + 1);
    pps.setStop(min(pps.getStart() + getRand64(maxInterval), upperBound));
    pps.setSieveSize(1 << (rand() % 12));
    pps.sieve();
    primeCount += pps.getPrimeCount();
    cout << "\rRemaining chunk:             "
         << "\rRemaining chunk: "
         << upperBound - pps.getStop() << flush;
  }
  cout << endl << "Prime count: " << setw(11) << primeCount;
  check(primeCount == primeCounts[18]);
  cout << endl;
}

/// Run various sieving tests to ensure that ParallelPrimeSieve
/// (and PrimeSieve) objects produce correct results.
/// The tests use up to 1 gigabyte of memory and take about
/// 1 minute to complete on a quad core CPU from 2013.
/// @return true  If no error occurred else false.
///
bool test()
{
  cout << left;
  try
  {
    testPix();
    testBigPrimes();
    testRandomIntervals();
  }
  catch (exception& e)
  {
    cerr << endl << "Error: " << e.what() << endl;
    return false;
  }
  cout << "All tests passed successfully!" << endl;
  return true;
}

} // end namespace
<|endoftext|>


<commit_before>///\file sourcery.cpp
///Utility program used for c-string dumping files.
#undef DEBUG
#define DEBUG -1
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include "../lib/url.h"
#include "../lib/url.cpp"
#include "../lib/encode.h"
#include "../lib/encode.cpp"

std::string getContents(const char * fileName){
  std::ifstream inFile(fileName);
  std::string fullText;
  if (inFile){
    std::ostringstream contents;
    contents << inFile.rdbuf();
    inFile.close();
    return contents.str();
  }
  return "";
}

int main(int argc, char* argv[]){

  if (argc < 4) {
    std::cerr << "Usage: " << argv[0] << " <inputFile> <variableName> <outputFile> [<splittext>]" << std::endl;
    return 42;
  }
  const char * splitText = 0;
  if (argc >= 5){splitText = argv[4];}

  char workDir[512];
  getcwd(workDir, 512);
  HTTP::URL inUri(std::string("file://") + workDir + "/");
  inUri = inUri.link(argv[1]);

  //Read the entire first argument into a string buffer
  std::string fullText = getContents(inUri.getFilePath().c_str());

  //replace every <script src="*"></script> with the contents of the file '*'
  while (fullText.find("<script src=\"") != std::string::npos){
    size_t locStart = fullText.find("<script src=\"");
    size_t locEnd = fullText.find("\"></script>", locStart);
    //Assume we should abort if the strlen of the filename is > 230 chars
    if (locEnd - locStart >= 230){break;}
    HTTP::URL fileName = inUri.link(fullText.substr(locStart+13, locEnd-locStart-13));
    std::string subText = getContents(fileName.getFilePath().c_str());
    fullText = fullText.substr(0, locStart) + "<script>" + subText + fullText.substr(locEnd+2);
  }

  //replace every <link rel="stylesheet" href="*"> with the contents of the file '*'
  while (fullText.find("<link rel=\"stylesheet\" href=\"") != std::string::npos){
    size_t locStart = fullText.find("<link rel=\"stylesheet\" href=\"");
    size_t locEnd = fullText.find("\">", locStart);
    //Assume we should abort if the strlen of the filename is > 230 chars
    if (locEnd - locStart >= 230){break;}
    HTTP::URL fileName = inUri.link(fullText.substr(locStart+29, locEnd-locStart-29));
    std::string subText = getContents(fileName.getFilePath().c_str());
    fullText = fullText.substr(0, locStart) + "<style>" + subText + "</style>" + fullText.substr(locEnd+2);
  }

  size_t splitPoint = std::string::npos;
  size_t splitLen = 0;
  if (splitText){
    splitPoint = fullText.find(splitText);
    if (splitPoint != std::string::npos){
      splitLen = strlen(splitText);
    }
  }

  std::ofstream tmp(argv[3]);
  //begin the first line
  if (!splitLen){
    tmp << "const char *" << argv[2] << " = " << std::endl << "  \"";
  }else{
    tmp << "const char *" << argv[2] << "_prefix = " << std::endl << "  \"";
  }
  uint32_t i = 0; //Current line byte counter
  uint32_t total = 0; //Finished lines so far byte counter
  bool sawQ = false;
  for (size_t pos = 0; pos < fullText.size(); ++pos){
    if (pos == splitPoint){
      tmp << "\";" << std::endl << "uint32_t " << argv[2] << "_prefix_len = " << i + total << ";" << std::endl;
      tmp << "const char *" << argv[2] << "_suffix = " << std::endl << "  \"";
      i = 0;
      total = 0;
      sawQ = false;
      pos += splitLen;
    }
    unsigned char thisChar = fullText.at(pos);
    switch (thisChar){
      //Filter special characters.
      case '\n': tmp << "\\n";  break;
      case '\r': tmp << "\\r";  break;
      case '\t': tmp << "\\t";  break;
      case '\\': tmp << "\\\\"; break;
      case '\"': tmp << "\\\""; break;
      case '?':
        if (sawQ){tmp << "\"\"";}
        tmp << "?";
        sawQ = true;
      break;
      default:
        if (thisChar < 32 || thisChar > 126){
          //Convert to octal.
          tmp << '\\' << std::oct << std::setw(3) << std::setfill('0') << (unsigned int)thisChar << std::dec;
        }else{
          tmp << thisChar;
        }
        sawQ = false;
    }
    ++i;
    // We print 80 bytes per line, regardless of special characters
    // (Mostly because calculating this correctly would double the lines of code for this utility -_-)
    if (i >= 80){
      tmp << "\" \\" << std::endl << "  \"";
      total += i;
      i = 0;
    }
  }
  //end the last line, plus length variable
  tmp << "\";" << std::endl << "uint32_t " << argv[2] << (splitLen?"_suffix":"") << "_len = " << i + total << ";" << std::endl;
  tmp.close();
  return 0;
}

<commit_msg>Fixed sourcery compile<commit_after>///\file sourcery.cpp
///Utility program used for c-string dumping files.
#undef DEBUG
#define DEBUG -1
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "../lib/url.h"
#include "../lib/url.cpp"
#include "../lib/encode.h"
#include "../lib/encode.cpp"

std::string getContents(const char * fileName){
  std::ifstream inFile(fileName);
  std::string fullText;
  if (inFile){
    std::stringstream contents;
    contents << inFile.rdbuf();
    inFile.close();
    return contents.str();
  }
  return "";
}

int main(int argc, char* argv[]){

  if (argc < 4) {
    std::cerr << "Usage: " << argv[0] << " <inputFile> <variableName> <outputFile> [<splittext>]" << std::endl;
    return 42;
  }
  const char * splitText = 0;
  if (argc >= 5){splitText = argv[4];}

  char workDir[512];
  getcwd(workDir, 512);
  HTTP::URL inUri(std::string("file://") + workDir + "/");
  inUri = inUri.link(argv[1]);

  //Read the entire first argument into a string buffer
  std::string fullText = getContents(inUri.getFilePath().c_str());

  //replace every <script src="*"></script> with the contents of the file '*'
  while (fullText.find("<script src=\"") != std::string::npos){
    size_t locStart = fullText.find("<script src=\"");
    size_t locEnd = fullText.find("\"></script>", locStart);
    //Assume we should abort if the strlen of the filename is > 230 chars
    if (locEnd - locStart >= 230){break;}
    HTTP::URL fileName = inUri.link(fullText.substr(locStart+13, locEnd-locStart-13));
    std::string subText = getContents(fileName.getFilePath().c_str());
    fullText = fullText.substr(0, locStart) + "<script>" + subText + fullText.substr(locEnd+2);
  }

  //replace every <link rel="stylesheet" href="*"> with the contents of the file '*'
  while (fullText.find("<link rel=\"stylesheet\" href=\"") != std::string::npos){
    size_t locStart = fullText.find("<link rel=\"stylesheet\" href=\"");
    size_t locEnd = fullText.find("\">", locStart);
    //Assume we should abort if the strlen of the filename is > 230 chars
    if (locEnd - locStart >= 230){break;}
    HTTP::URL fileName = inUri.link(fullText.substr(locStart+29, locEnd-locStart-29));
    std::string subText = getContents(fileName.getFilePath().c_str());
    fullText = fullText.substr(0, locStart) + "<style>" + subText + "</style>" + fullText.substr(locEnd+2);
  }

  size_t splitPoint = std::string::npos;
  size_t splitLen = 0;
  if (splitText){
    splitPoint = fullText.find(splitText);
    if (splitPoint != std::string::npos){
      splitLen = strlen(splitText);
    }
  }

  std::ofstream tmp(argv[3]);
  //begin the first line
  if (!splitLen){
    tmp << "const char *" << argv[2] << " = " << std::endl << "  \"";
  }else{
    tmp << "const char *" << argv[2] << "_prefix = " << std::endl << "  \"";
  }
  uint32_t i = 0; //Current line byte counter
  uint32_t total = 0; //Finished lines so far byte counter
  bool sawQ = false;
  for (size_t pos = 0; pos < fullText.size(); ++pos){
    if (pos == splitPoint){
      tmp << "\";" << std::endl << "uint32_t " << argv[2] << "_prefix_len = " << i + total << ";" << std::endl;
      tmp << "const char *" << argv[2] << "_suffix = " << std::endl << "  \"";
      i = 0;
      total = 0;
      sawQ = false;
      pos += splitLen;
    }
    unsigned char thisChar = fullText.at(pos);
    switch (thisChar){
      //Filter special characters.
      case '\n': tmp << "\\n";  break;
      case '\r': tmp << "\\r";  break;
      case '\t': tmp << "\\t";  break;
      case '\\': tmp << "\\\\"; break;
      case '\"': tmp << "\\\""; break;
      case '?':
        if (sawQ){tmp << "\"\"";}
        tmp << "?";
        sawQ = true;
      break;
      default:
        if (thisChar < 32 || thisChar > 126){
          //Convert to octal.
          tmp << '\\' << std::oct << std::setw(3) << std::setfill('0') << (unsigned int)thisChar << std::dec;
        }else{
          tmp << thisChar;
        }
        sawQ = false;
    }
    ++i;
    // We print 80 bytes per line, regardless of special characters
    // (Mostly because calculating this correctly would double the lines of code for this utility -_-)
    if (i >= 80){
      tmp << "\" \\" << std::endl << "  \"";
      total += i;
      i = 0;
    }
  }
  //end the last line, plus length variable
  tmp << "\";" << std::endl << "uint32_t " << argv[2] << (splitLen?"_suffix":"") << "_len = " << i + total << ";" << std::endl;
  tmp.close();
  return 0;
}

<|endoftext|>


<commit_before>#include <ostream>
#include <string>
#include <cassert>

#include "card.h"

using namespace DNRY;

Cards::Card::Card(const Suit& suit, const Value& value) {
    s = suit;
    v = value;
}

Cards::Suit Cards::Card::suit() const {
    return s;
}

Cards::Value Cards::Card::value() const {
    return v;
}

std::string Cards::make_string(Suit s) {
#ifdef _WIN32
    // workaround for VS2013's Windows-1252 code page format and lack
    // of u8 string literals
    const auto club = "C";
    const auto diamond = "D";
    const auto heart = "H";
    const auto spade = "S";
#else
    const auto club = u8"♣";
    const auto diamond = u8"♦";
    const auto heart = u8"♥";
    const auto spade = u8"♠";
#endif
    switch (s) {
    case Cards::Suit::club: {
        return std::string(club);
    }
    case Cards::Suit::diamond: {
        return std::string(diamond);
    }
    case Cards::Suit::heart: {
        return std::string(heart);
    }
    case Cards::Suit::spade: {
        return std::string(spade);
    }
    default: {
        assert(false);
        return "";
    }
    }
}

std::string Cards::make_string(Value v) {
    switch (v) {
    case Cards::Value::ace:
        return "A";
    case Cards::Value::two:
        return "2";
    case Cards::Value::three:
        return "3";
    case Cards::Value::four:
        return "4";
    case Cards::Value::five:
        return "5";
    case Cards::Value::six:
        return "6";
    case Cards::Value::seven:
        return "7";
    case Cards::Value::eight:
        return "8";
    case Cards::Value::nine:
        return "9";
    case Cards::Value::ten:
        return "10";
    case Cards::Value::jack:
        return "J";
    case Cards::Value::queen:
        return "Q";
    case Cards::Value::king:
        return "K";
    default: {
        assert(false);
        return "";
    }
    }
}

std::ostream& Cards::operator<<(std::ostream& os, const Cards::Card& c) {
    os << Cards::make_string(c.value()) << Cards::make_string(c.suit());
    return os;
}
<commit_msg>Add initializer list<commit_after>#include <ostream>
#include <string>
#include <cassert>

#include "card.h"

using namespace DNRY;

Cards::Card::Card(const Suit& suit, const Value& value) : s{suit}, v{value} {}

Cards::Suit Cards::Card::suit() const {
    return s;
}

Cards::Value Cards::Card::value() const {
    return v;
}

std::string Cards::make_string(Suit s) {
#ifdef _WIN32
    // workaround for VS2013's Windows-1252 code page format and lack
    // of u8 string literals
    const auto club = "C";
    const auto diamond = "D";
    const auto heart = "H";
    const auto spade = "S";
#else
    const auto club = u8"♣";
    const auto diamond = u8"♦";
    const auto heart = u8"♥";
    const auto spade = u8"♠";
#endif
    switch (s) {
    case Cards::Suit::club: {
        return std::string(club);
    }
    case Cards::Suit::diamond: {
        return std::string(diamond);
    }
    case Cards::Suit::heart: {
        return std::string(heart);
    }
    case Cards::Suit::spade: {
        return std::string(spade);
    }
    default: {
        assert(false);
        return "";
    }
    }
}

std::string Cards::make_string(Value v) {
    switch (v) {
    case Cards::Value::ace:
        return "A";
    case Cards::Value::two:
        return "2";
    case Cards::Value::three:
        return "3";
    case Cards::Value::four:
        return "4";
    case Cards::Value::five:
        return "5";
    case Cards::Value::six:
        return "6";
    case Cards::Value::seven:
        return "7";
    case Cards::Value::eight:
        return "8";
    case Cards::Value::nine:
        return "9";
    case Cards::Value::ten:
        return "10";
    case Cards::Value::jack:
        return "J";
    case Cards::Value::queen:
        return "Q";
    case Cards::Value::king:
        return "K";
    default: {
        assert(false);
        return "";
    }
    }
}

std::ostream& Cards::operator<<(std::ostream& os, const Cards::Card& c) {
    os << Cards::make_string(c.value()) << Cards::make_string(c.suit());
    return os;
}
<|endoftext|>


<commit_before>#include "node_info.h"

#include <cstddef>
#include <cstdlib>
#include <cstring>

#include "sixtracklib/common/definitions.h"
#include "sixtracklib/common/control/definitions.h"
#include "sixtracklib/common/control/node_info.hpp"

#if !defined( _GPUCODE )

namespace st = SIXTRL_CXX_NAMESPACE;

void NS(NodeInfo_delete)( ::NS(NodeInfoBase)* SIXTRL_RESTRICT node_info )
{
    if( node_info != nullptr ) delete node_info;
}

/* ------------------------------------------------------------------------- */

::NS(NodeId) const* NS(NodeInfo_get_ptr_const_node_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrNodeId() : nullptr;
}

::NS(NodeId)* NS(NodeInfo_get_ptr_node_id)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrNodeId() : nullptr;
}

::NS(node_platform_id_t) NS(NodeInfo_get_platform_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->platformId() : st::NODE_ILLEGAL_PATFORM_ID;
}

void NS(NodeInfo_set_platform_id)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    ::NS(node_platform_id_t) const platform_id )
{
    if( info != nullptr ) info->setPlatformId( platform_id );
}

::NS(node_device_id_t) NS(NodeInfo_get_device_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->deviceId() : st::NODE_ILLEGAL_DEVICE_ID;
}

void NS(NodeInfo_set_device_id)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    ::NS(node_device_id_t) const device_id )
{
    if( info != nullptr ) info->setDeviceId( device_id );
}

bool NS(NodeInfo_has_node_index)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasNodeIndex() ) );
}

::NS(node_index_t) NS(NodeInfo_get_node_index)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->nodeIndex() : st::NODE_UNDEFINED_INDEX;
}

void NS(NodeInfo_set_node_index)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    ::NS(node_index_t) node_index )
{
    if( info != nullptr ) info->setNodeIndex( node_index );
}

bool NS(NodeInfo_is_default_node)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->isDefaultNode() ) );
}

bool NS(NodeInfo_is_selected_node)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->isSelectedNode() ) );
}

void NS(NodeInfo_set_is_default_node)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    bool const is_default )
{
    if( info != nullptr ) info->setIsDefaultNode( is_default );
}

void NS(NodeInfo_set_is_selected_node)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    bool const is_selected )
{
    if( info != nullptr ) info->setIsSelectedNode( is_selected );
}

/* ------------------------------------------------------------------------- */

::NS(arch_id_t) NS(NodeInfo_get_arch_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->archId() : ::NS(ARCHITECTURE_ILLEGAL);
}

bool NS(NodeInfo_has_arch_string)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasArchStr() ) );
}

char const* NS(NodeInfo_get_arch_string)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrArchStr() : nullptr;
}

/* ------------------------------------------------------------------------- */

bool NS(NodeInfo_has_platform_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasPlatformName() ) );
}

char const* NS(NodeInfo_get_platform_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrPlatformNameStr() : nullptr;
}

void NS(NodeInfo_set_platform_name)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT platform_name )
{
    if( info != nullptr ) info->setPlatformName( platform_name );
}

bool NS(NodeInfo_has_device_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasDeviceName() ) );
}

char const* NS(NodeInfo_get_device_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrDeviceNameStr() : nullptr;
}

void NS(NodeInfo_set_device_name)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT device_name )
{
    if( info != nullptr ) info->setDeviceName( device_name );
}

bool NS(NodeInfo_has_description)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasDescription() ) );
}

char const* NS(NodeInfo_get_description)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrDescriptionStr() : nullptr;
}

void NS(NodeInfo_set_description)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT description )
{
    if( info != nullptr ) info->setPlatformName( description );
}

/* ------------------------------------------------------------------------- */

void NS(NodeInfo_print)( SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const
    SIXTRL_RESTRICT info, ::FILE* SIXTRL_RESTRICT output )
{
    if( ( info != nullptr ) && ( output != nullptr ) )
    {
        info->print( output );
    }
}

void NS(NodeInfo_print_out)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    if( info != nullptr ) info->printOut();
}

::NS(arch_size_t) NS(NodeInfo_get_required_output_str_length)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->requiredOutStringLength() : ::NS(arch_size_t){ 0 };
}

SIXTRL_EXTERN SIXTRL_HOST_FN NS(arch_status_t)
NS(NodeInfo_convert_to_string)(
    SIXTRL_ARGPTR_DEC const NS(NodeInfoBase) *const SIXTRL_RESTRICT info,
    NS(arch_size_t) const out_string_capacity,
    char* SIXTRL_RESTRICT out_string )
{
    return ( info != nullptr )
        ? info->toString( out_string_capacity, out_string )
        : st::ARCH_STATUS_GENERAL_FAILURE;
}

#endif /* !defined( _GPUCODE ) */

/* end: sixtracklib/common/control/node_info_c99.cpp */
<commit_msg>common: cosmetic changes<commit_after>#include "node_info.h"

#include <cstddef>
#include <cstdlib>
#include <cstring>

#include "sixtracklib/common/definitions.h"
#include "sixtracklib/common/control/definitions.h"
#include "sixtracklib/common/control/node_info.hpp"

#if !defined( _GPUCODE )

namespace st = SIXTRL_CXX_NAMESPACE;

void NS(NodeInfo_delete)( ::NS(NodeInfoBase)* SIXTRL_RESTRICT node_info )
{
    if( node_info != nullptr ) delete node_info;
}

/* ------------------------------------------------------------------------- */

::NS(NodeId) const* NS(NodeInfo_get_ptr_const_node_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrNodeId() : nullptr;
}

::NS(NodeId)* NS(NodeInfo_get_ptr_node_id)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrNodeId() : nullptr;
}

::NS(node_platform_id_t) NS(NodeInfo_get_platform_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->platformId() : st::NODE_ILLEGAL_PATFORM_ID;
}

void NS(NodeInfo_set_platform_id)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    ::NS(node_platform_id_t) const platform_id )
{
    if( info != nullptr ) info->setPlatformId( platform_id );
}

::NS(node_device_id_t) NS(NodeInfo_get_device_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->deviceId() : st::NODE_ILLEGAL_DEVICE_ID;
}

void NS(NodeInfo_set_device_id)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    ::NS(node_device_id_t) const device_id )
{
    if( info != nullptr ) info->setDeviceId( device_id );
}

bool NS(NodeInfo_has_node_index)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasNodeIndex() ) );
}

::NS(node_index_t) NS(NodeInfo_get_node_index)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->nodeIndex() : st::NODE_UNDEFINED_INDEX;
}

void NS(NodeInfo_set_node_index)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    ::NS(node_index_t) node_index )
{
    if( info != nullptr ) info->setNodeIndex( node_index );
}

bool NS(NodeInfo_is_default_node)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->isDefaultNode() ) );
}

bool NS(NodeInfo_is_selected_node)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->isSelectedNode() ) );
}

void NS(NodeInfo_set_is_default_node)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    bool const is_default )
{
    if( info != nullptr ) info->setIsDefaultNode( is_default );
}

void NS(NodeInfo_set_is_selected_node)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    bool const is_selected )
{
    if( info != nullptr ) info->setIsSelectedNode( is_selected );
}

/* ------------------------------------------------------------------------- */

::NS(arch_id_t) NS(NodeInfo_get_arch_id)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->archId() : st::ARCHITECTURE_ILLEGAL;
}

bool NS(NodeInfo_has_arch_string)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasArchStr() ) );
}

char const* NS(NodeInfo_get_arch_string)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrArchStr() : nullptr;
}

/* ------------------------------------------------------------------------- */

bool NS(NodeInfo_has_platform_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasPlatformName() ) );
}

char const* NS(NodeInfo_get_platform_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrPlatformNameStr() : nullptr;
}

void NS(NodeInfo_set_platform_name)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT platform_name )
{
    if( info != nullptr ) info->setPlatformName( platform_name );
}

bool NS(NodeInfo_has_device_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasDeviceName() ) );
}

char const* NS(NodeInfo_get_device_name)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrDeviceNameStr() : nullptr;
}

void NS(NodeInfo_set_device_name)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT device_name )
{
    if( info != nullptr ) info->setDeviceName( device_name );
}

bool NS(NodeInfo_has_description)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( ( info != nullptr ) && ( info->hasDescription() ) );
}

char const* NS(NodeInfo_get_description)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr ) ? info->ptrDescriptionStr() : nullptr;
}

void NS(NodeInfo_set_description)(
    SIXTRL_ARGPTR_DEC ::NS(NodeInfoBase)* SIXTRL_RESTRICT info,
    SIXTRL_ARGPTR_DEC const char *const SIXTRL_RESTRICT description )
{
    if( info != nullptr ) info->setPlatformName( description );
}

/* ------------------------------------------------------------------------- */

void NS(NodeInfo_print)( SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const
    SIXTRL_RESTRICT info, ::FILE* SIXTRL_RESTRICT output )
{
    if( ( info != nullptr ) && ( output != nullptr ) )
    {
        info->print( output );
    }
}

void NS(NodeInfo_print_out)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    if( info != nullptr ) info->printOut();
}

::NS(arch_size_t) NS(NodeInfo_get_required_output_str_length)(
    SIXTRL_ARGPTR_DEC const ::NS(NodeInfoBase) *const SIXTRL_RESTRICT info )
{
    return ( info != nullptr )
        ? info->requiredOutStringLength() : ::NS(arch_size_t){ 0 };
}

SIXTRL_EXTERN SIXTRL_HOST_FN NS(arch_status_t)
NS(NodeInfo_convert_to_string)(
    SIXTRL_ARGPTR_DEC const NS(NodeInfoBase) *const SIXTRL_RESTRICT info,
    NS(arch_size_t) const out_string_capacity,
    char* SIXTRL_RESTRICT out_string )
{
    return ( info != nullptr )
        ? info->toString( out_string_capacity, out_string )
        : st::ARCH_STATUS_GENERAL_FAILURE;
}

#endif /* !defined( _GPUCODE ) */

/* end: sixtracklib/common/control/node_info_c99.cpp */
<|endoftext|>


<commit_before>// This file is part of Poseidon.
// Copyleft 2022, LH_Mouse. All wrongs reserved.

#include "../precompiled.ipp"
#include "timer_driver.hpp"
#include "async_logger.hpp"
#include "../core/abstract_timer.hpp"
#include "../utils.hpp"
#include <time.h>

namespace poseidon {
namespace {

struct Queued_Timer
  {
    weak_ptr<Abstract_Timer> timer;
    uint64_t serial;
    int64_t next;
    int64_t period;
  };

struct Timer_Comparator
  {
    bool
    operator()(const Queued_Timer& lhs, const Queued_Timer& rhs) noexcept
      { return lhs.next > rhs.next;  }

    bool
    operator()(const Queued_Timer& lhs, int64_t rhs) noexcept
      { return lhs.next > rhs;  }

    bool
    operator()(int64_t lhs, const Queued_Timer& rhs) noexcept
      { return lhs > rhs.next;  }
  }
  constexpr timer_comparator;

int64_t
do_monotonic_now() noexcept
  {
    ::timespec ts;
    ::clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000 + (uint32_t) ts.tv_nsec / 1000000U;
  }

}  // namespace

POSEIDON_HIDDEN_STRUCT(Timer_Driver, Queued_Timer);

Timer_Driver::
Timer_Driver()
  {
    // Generate a random serial.
    this->m_serial = (uint64_t) do_monotonic_now();
  }

Timer_Driver::
~Timer_Driver()
  {
  }

void
Timer_Driver::
thread_loop()
  {
    // Await an element.
    plain_mutex::unique_lock lock(this->m_pq_mutex);
    while(this->m_pq.empty())
      this->m_pq_avail.wait(lock);

    const int64_t now = do_monotonic_now();
    int64_t delta = this->m_pq.front().next - now;
    if(delta > 0) {
      POSEIDON_LOG_TRACE(("Timer driver waiting: $1 millisecond(s) remaining"), delta);
      this->m_pq_avail.wait_for(lock, delta);
      return;
    }
    ::std::pop_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);
    auto elem = ::std::move(this->m_pq.back());
    this->m_pq.pop_back();

    auto timer = elem.timer.lock();
    if(!timer)
      return;
    else if(elem.serial != timer->m_serial)
      return;

    if(elem.period != 0) {
      // Update the next time point and insert the timer back.
      elem.next += elem.period;
      this->m_pq.emplace_back(::std::move(elem));
      ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);
    }
    lock.unlock();

    // Execute it.
    // Exceptions are ignored.
    POSEIDON_LOG_TRACE(("Executing timer `$1` (class `$2`)"), timer, typeid(*timer));
    timer->m_async_state.store(async_state_running);
    timer->m_count.xadd(1);

    try {
      timer->do_abstract_timer_on_tick(now);
    }
    catch(exception& stdex) {
      POSEIDON_LOG_WARN((
          "Timer error: $1",
          "[exception class `$2`]",
          "[timer class `$3`]"),
          stdex.what(), typeid(stdex), typeid(*timer));
    }

    timer->m_async_state.store(async_state_suspended);
  }

void
Timer_Driver::
insert(const shared_ptr<Abstract_Timer>& timer, int64_t delay, int64_t period)
  {
    // Validate arguments.
    if(!timer)
      POSEIDON_THROW(("Null timer pointer not valid"));

    if(delay < 0)
      POSEIDON_THROW(("Negative time delay not valid: $1"), delay);

    if(delay > INT32_MAX)
      POSEIDON_THROW(("Time delay too large: $1"), delay);

    if(period < 0)
      POSEIDON_THROW(("Negative timer period not valid: $1"), period);

    if(period > INT32_MAX)
      POSEIDON_THROW(("Timer period too large: $1"), period);

    // Calculate the end time point.
    Queued_Timer elem;
    elem.timer = timer;
    elem.next = do_monotonic_now() + delay;
    elem.period = period;

    // Insert the timer.
    plain_mutex::unique_lock lock(this->m_pq_mutex);
    elem.serial = ++ this->m_serial;
    timer->m_serial = elem.serial;
    this->m_pq.emplace_back(::std::move(elem));
    ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);
    this->m_pq_avail.notify_one();
  }

}  // namespace poseidon
<commit_msg>timer_driver: Add comments<commit_after>// This file is part of Poseidon.
// Copyleft 2022, LH_Mouse. All wrongs reserved.

#include "../precompiled.ipp"
#include "timer_driver.hpp"
#include "async_logger.hpp"
#include "../core/abstract_timer.hpp"
#include "../utils.hpp"
#include <time.h>

namespace poseidon {
namespace {

struct Queued_Timer
  {
    weak_ptr<Abstract_Timer> timer;
    uint64_t serial;
    int64_t next;
    int64_t period;
  };

struct Timer_Comparator
  {
    // We have to build a minheap here.
    bool
    operator()(const Queued_Timer& lhs, const Queued_Timer& rhs) noexcept
      { return lhs.next > rhs.next;  }

    bool
    operator()(const Queued_Timer& lhs, int64_t rhs) noexcept
      { return lhs.next > rhs;  }

    bool
    operator()(int64_t lhs, const Queued_Timer& rhs) noexcept
      { return lhs > rhs.next;  }
  }
  constexpr timer_comparator;

int64_t
do_monotonic_now() noexcept
  {
    ::timespec ts;
    ::clock_gettime(CLOCK_MONOTONIC, &ts);
    return ts.tv_sec * 1000 + (uint32_t) ts.tv_nsec / 1000000U;
  }

}  // namespace

POSEIDON_HIDDEN_STRUCT(Timer_Driver, Queued_Timer);

Timer_Driver::
Timer_Driver()
  {
    // Generate a random serial.
    this->m_serial = (uint64_t) do_monotonic_now();
  }

Timer_Driver::
~Timer_Driver()
  {
  }

void
Timer_Driver::
thread_loop()
  {
    // Await an element.
    plain_mutex::unique_lock lock(this->m_pq_mutex);
    while(this->m_pq.empty())
      this->m_pq_avail.wait(lock);

    const int64_t now = do_monotonic_now();
    int64_t delta = this->m_pq.front().next - now;
    if(delta > 0) {
      POSEIDON_LOG_TRACE(("Timer driver waiting: $1 millisecond(s) remaining"), delta);
      this->m_pq_avail.wait_for(lock, delta);
      return;
    }
    ::std::pop_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);
    auto elem = ::std::move(this->m_pq.back());
    this->m_pq.pop_back();

    auto timer = elem.timer.lock();
    if(!timer)
      return;
    else if(elem.serial != timer->m_serial)
      return;

    if(elem.period != 0) {
      // Update the next time point and insert the timer back.
      elem.next += elem.period;
      this->m_pq.emplace_back(::std::move(elem));
      ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);
    }
    lock.unlock();

    // Execute it.
    // Exceptions are ignored.
    POSEIDON_LOG_TRACE(("Executing timer `$1` (class `$2`)"), timer, typeid(*timer));
    timer->m_async_state.store(async_state_running);
    timer->m_count.xadd(1);

    try {
      timer->do_abstract_timer_on_tick(now);
    }
    catch(exception& stdex) {
      POSEIDON_LOG_WARN((
          "Timer error: $1",
          "[exception class `$2`]",
          "[timer class `$3`]"),
          stdex.what(), typeid(stdex), typeid(*timer));
    }

    timer->m_async_state.store(async_state_suspended);
  }

void
Timer_Driver::
insert(const shared_ptr<Abstract_Timer>& timer, int64_t delay, int64_t period)
  {
    // Validate arguments.
    if(!timer)
      POSEIDON_THROW(("Null timer pointer not valid"));

    if(delay < 0)
      POSEIDON_THROW(("Negative time delay not valid: $1"), delay);

    if(delay > INT32_MAX)
      POSEIDON_THROW(("Time delay too large: $1"), delay);

    if(period < 0)
      POSEIDON_THROW(("Negative timer period not valid: $1"), period);

    if(period > INT32_MAX)
      POSEIDON_THROW(("Timer period too large: $1"), period);

    // Calculate the end time point.
    Queued_Timer elem;
    elem.timer = timer;
    elem.next = do_monotonic_now() + delay;
    elem.period = period;

    // Insert the timer.
    plain_mutex::unique_lock lock(this->m_pq_mutex);
    elem.serial = ++ this->m_serial;
    timer->m_serial = elem.serial;
    this->m_pq.emplace_back(::std::move(elem));
    ::std::push_heap(this->m_pq.begin(), this->m_pq.end(), timer_comparator);
    this->m_pq_avail.notify_one();
  }

}  // namespace poseidon
<|endoftext|>


<commit_before>/**
 *   Copyright 2011-2015 Quickstep Technologies LLC.
 *   Copyright 2015-2016 Pivotal Software, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 **/

#ifndef QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_
#define QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_

#include <atomic>
#include <cstddef>

#include "storage/StorageBlockInfo.hpp"
#include "utility/Macros.hpp"

#include "glog/logging.h"

namespace quickstep {

/**
 * @brief Abstract base class which encompasses functionality common to
 *        StorageBlock and StorageBlob.
 **/
class StorageBlockBase {
 public:
  /**
   * @brief Virtual destructor.
   **/
  virtual ~StorageBlockBase() {
#ifdef QUICKSTEP_DEBUG
    CHECK_EQ(0, getRefCount())
        << "Nonzero ref_count_ when deleting block ("
        << BlockIdUtil::Domain(id_) << ", "
        << BlockIdUtil::Counter(id_) << ")";
#endif
  }

  /**
   * @brief Determine if this is a StorageBlob or StorageBlock.
   *
   * @return true if this is a StorageBlob, false if it is a StorageBlock.
   **/
  virtual bool isBlob() const = 0;

  /**
   * @brief Get this block's block_id.
   *
   * @return This block's ID.
   **/
  inline block_id getID() const {
    return id_;
  }

  /**
   * @brief Check whether this block is dirty (whether it has been changed
   *        since being written to disk).
   *
   * @return Whether the block is dirty.
   **/
  inline bool isDirty() const {
    return dirty_;
  }

  /**
   * @brief Clear the dirty bit for this block, marking it as clean.
   **/
  inline void markClean() {
    dirty_ = false;
  }

#ifdef QUICKSTEP_DEBUG
  /**
   * @brief Atomically increment the reference count for this StorageBlockBase.
   **/
  void ref() const {
    ++ref_count_;
  }

  /**
   * @brief Atomically decrement the reference count for this StorageBlockBase.
   **/
  void unref() const {
    CHECK_GE(--ref_count_, 0)
        << "unref() of block ("
        << BlockIdUtil::Domain(id_) << ", "
        << BlockIdUtil::Counter(id_) << ") "
        << "caused reference count to become negative.";
  }

  /**
   * @brief Atomically get the reference count of this block.
   * @return This block's reference count.
   **/
  int getRefCount() const {
    return ref_count_.load();
  }
#endif

 protected:
  StorageBlockBase(const block_id id,
                   void *block_memory,
                   const std::size_t block_memory_size)
      : id_(id),
        dirty_(false),
        block_memory_(block_memory),
        block_memory_size_(block_memory_size)
#ifdef QUICKSTEP_DEBUG
        , ref_count_(0)  // initialize the atomic using direct initialization
#endif
  {   // breaking the style guidelines to call atomic direct initialization only when compiled with QUICKSTEP_DEBUG defined
  }

  const block_id id_;
  bool dirty_;

  void *block_memory_;
  const std::size_t block_memory_size_;

 private:
#ifdef QUICKSTEP_DEBUG
  mutable std::atomic_int ref_count_;
#endif

  DISALLOW_COPY_AND_ASSIGN(StorageBlockBase);
};

}  // namespace quickstep

#endif  // QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_
<commit_msg>Send job back to Travis.<commit_after>/**
 *   Copyright 2011-2015 Quickstep Technologies LLC.
 *   Copyright 2015-2016 Pivotal Software, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 **/

#ifndef QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_
#define QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_

#include <atomic>
#include <cstddef>

#include "storage/StorageBlockInfo.hpp"
#include "utility/Macros.hpp"

#include "glog/logging.h"

namespace quickstep {

/**
 * @brief Abstract base class which encompasses functionality common to
 *        StorageBlock and StorageBlob.
 **/
class StorageBlockBase {
 public:
  /**
   * @brief Virtual destructor.
   **/
  virtual ~StorageBlockBase() {
#ifdef QUICKSTEP_DEBUG
    CHECK_EQ(0, getRefCount())
        << "Nonzero ref_count_ when deleting block ("
        << BlockIdUtil::Domain(id_) << ", "
        << BlockIdUtil::Counter(id_) << ")";
#endif
  }

  /**
   * @brief Determine if this is a StorageBlob or StorageBlock.
   *
   * @return true if this is a StorageBlob, false if it is a StorageBlock.
   **/
  virtual bool isBlob() const = 0;

  /**
   * @brief Get this block's block_id.
   *
   * @return This block's ID.
   **/
  inline block_id getID() const {
    return id_;
  }

  /**
   * @brief Check whether this block is dirty (whether it has been changed
   *        since being written to disk).
   *
   * @return Whether the block is dirty.
   **/
  inline bool isDirty() const {
    return dirty_;
  }

  /**
   * @brief Clear the dirty bit for this block, marking it as clean.
   **/
  inline void markClean() {
    dirty_ = false;
  }

#ifdef QUICKSTEP_DEBUG
  /**
   * @brief Atomically increment the reference count for this StorageBlockBase.
   **/
  void ref() const {
    ++ref_count_;
  }

  /**
   * @brief Atomically decrement the reference count for this StorageBlockBase.
   **/
  void unref() const {
    CHECK_GE(--ref_count_, 0)
        << "unref() of block ("
        << BlockIdUtil::Domain(id_) << ", "
        << BlockIdUtil::Counter(id_) << ") "
        << "caused reference count to become negative.";
  }

  /**
   * @brief Atomically get the reference count of this block.
   * @return This block's reference count.
   **/
  int getRefCount() const {
    return ref_count_.load();
  }
#endif

 protected:
  StorageBlockBase(const block_id id,
                   void *block_memory,
                   const std::size_t block_memory_size)
      : id_(id),
        dirty_(false),
        block_memory_(block_memory),
        block_memory_size_(block_memory_size)
#ifdef QUICKSTEP_DEBUG
        , ref_count_(0)  // Initialize the atomic using direct initialization.
#endif
  {   // We are breaking the style guidelines to call direct initialization
      // on the atomic variable only when compiled with QUICKSTEP_DEBUG defined.
  }

  const block_id id_;
  bool dirty_;

  void *block_memory_;
  const std::size_t block_memory_size_;

 private:
#ifdef QUICKSTEP_DEBUG
  mutable std::atomic_int ref_count_;
#endif

  DISALLOW_COPY_AND_ASSIGN(StorageBlockBase);
};

}  // namespace quickstep

#endif  // QUICKSTEP_STORAGE_STORAGE_BLOCK_BASE_HPP_
<|endoftext|>


<commit_before>
// External C++ / GLFW functionality for the 'util' module:

// Namespace(s):
namespace external_util
{
	// Functions:
	bool setClipboard(String input)
	{
		const char* source = input.ToCString<char>();

		// Set the system's clipboard-string.
		glfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), source);

		// Return the default response.
		return true;
	}

	String getClipboard()
	{
		// Grab the current state of the clipboard.
		const char* nativeString = glfwGetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow());

		// Convert the native clipboard-data into a Monkey 'String'.
		return String(nativeString, strlen(nativeString));
	}

	bool clearClipboard()
	{
		// Attempt to clear the clipboard (For some reason, I can't just supply 'NULL').
		glfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), "");

		// Return the default response.
		return true;
	}
}
<commit_msg>Fixed a UTF8-related bug with 'SetClipboard'. Special thanks to sereschkin for spotting that.<commit_after>
// External C++ / GLFW functionality for the 'util' module:

// Namespace(s):
namespace external_util
{
	// Functions:
	bool setClipboard(String input)
	{
		// Set the system's clipboard-string.
		glfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), input.ToUtf8()); // input.ToCString<char>();

		// Return the default response.
		return true;
	}

	String getClipboard()
	{
		// Grab the current state of the clipboard.
		const char* nativeString = glfwGetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow());

		// Convert the native clipboard-data into a Monkey 'String'.
		return String(nativeString, strlen(nativeString));
	}

	bool clearClipboard()
	{
		// Attempt to clear the clipboard (For some reason, I can't just supply 'NULL').
		glfwSetClipboardString(BBGlfwGame::GlfwGame()->GetGLFWwindow(), "");

		// Return the default response.
		return true;
	}
}
<|endoftext|>