<commit_before>#include "clustering/administration/namespace_interface_repository.hpp"

#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_map.hpp>

#include "concurrency/cross_thread_signal.hpp"
#include "concurrency/cross_thread_watchable.hpp"

#define NAMESPACE_INTERFACE_EXPIRATION_MS (60 * 1000)

template <class protocol_t>
struct namespace_repo_t<protocol_t>::namespace_cache_t {
public:
    boost::ptr_map<namespace_id_t, namespace_cache_entry_t> entries;
    auto_drainer_t drainer;
};

template <class protocol_t>
namespace_repo_t<protocol_t>::namespace_repo_t(mailbox_manager_t *_mailbox_manager,
                                               clone_ptr_t<watchable_t<std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > > > _namespaces_directory_metadata,
                                               typename protocol_t::context_t *_ctx)
    : mailbox_manager(_mailbox_manager),
      namespaces_directory_metadata(_namespaces_directory_metadata),
      ctx(_ctx)
{ }

template <class protocol_t>
namespace_repo_t<protocol_t>::~namespace_repo_t() { }

template <class protocol_t>
std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > get_reactor_business_cards(
        const std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > &ns_directory_metadata, namespace_id_t n_id) {
    std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > res;
    for (typename std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> >::const_iterator it  = ns_directory_metadata.begin();
                                                                                it != ns_directory_metadata.end();
                                                                                it++) {
        typename namespaces_directory_metadata_t<protocol_t>::reactor_bcards_map_t::const_iterator jt =
            it->second.reactor_bcards.find(n_id);
        if (jt != it->second.reactor_bcards.end()) {
            res[it->first] = jt->second.internal;
        } else {
            res[it->first] = cow_ptr_t<reactor_business_card_t<protocol_t> >();
        }
    }

    return res;
}

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::access_t() :
    cache_entry(NULL),
    thread(INVALID_THREAD)
    { }

template<class protocol_t>
namespace_repo_t<protocol_t>::access_t::access_t(namespace_repo_t *parent, namespace_id_t namespace_id, signal_t *interruptor) :
    thread(get_thread_id())
{
    {
        ASSERT_FINITE_CORO_WAITING;
        namespace_cache_t *cache = parent->namespace_caches.get();
        if (cache->entries.find(namespace_id) == cache->entries.end()) {
            cache_entry = new namespace_cache_entry_t;
            cache_entry->ref_count = 0;
            cache_entry->pulse_when_ref_count_becomes_zero = NULL;
            cache_entry->pulse_when_ref_count_becomes_nonzero = NULL;
            ref_handler.init(cache_entry);
            cache->entries.insert(namespace_id, cache_entry);
            coro_t::spawn_sometime(boost::bind(
                &namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface, parent,
                cache, namespace_id,
                auto_drainer_t::lock_t(&cache->drainer)));
        } else {
            cache_entry = &cache->entries[namespace_id];
            ref_handler.init(cache_entry);
        }
    }
    wait_interruptible(cache_entry->namespace_if.get_ready_signal(), interruptor);
}

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::access_t(const access_t& access) :
    cache_entry(access.cache_entry),
    thread(access.thread)
{
    if (cache_entry) {
        rassert_unreviewed(get_thread_id() == thread);
        ref_handler.init(cache_entry);
    }
}

template <class protocol_t>
typename namespace_repo_t<protocol_t>::access_t &namespace_repo_t<protocol_t>::access_t::operator=(const access_t &access) {
    if (this != &access) {
        cache_entry = access.cache_entry;
        ref_handler.reset();
        if (access.cache_entry) {
            ref_handler.init(access.cache_entry);
        }
        thread = access.thread;
    }
    return *this;
}

template <class protocol_t>
namespace_interface_t<protocol_t> *namespace_repo_t<protocol_t>::access_t::get_namespace_if() {
    rassert_unreviewed(thread == get_thread_id());
    return cache_entry->namespace_if.get_value();
}

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::ref_handler_t::ref_handler_t() :
    ref_target(NULL) { }

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::ref_handler_t::~ref_handler_t() {
    reset();
}

template <class protocol_t>
void namespace_repo_t<protocol_t>::access_t::ref_handler_t::init(namespace_cache_entry_t *_ref_target) {
    ASSERT_NO_CORO_WAITING;
    rassert_unreviewed(ref_target == NULL);
    ref_target = _ref_target;
    ref_target->ref_count++;
    if (ref_target->ref_count == 1) {
        if (ref_target->pulse_when_ref_count_becomes_nonzero) {
            ref_target->pulse_when_ref_count_becomes_nonzero->pulse_if_not_already_pulsed();
        }
    }
}

template <class protocol_t>
void namespace_repo_t<protocol_t>::access_t::ref_handler_t::reset() {
    ASSERT_NO_CORO_WAITING;
    if (ref_target != NULL) {
        ref_target->ref_count--;
        if (ref_target->ref_count == 0) {
            if (ref_target->pulse_when_ref_count_becomes_zero) {
                ref_target->pulse_when_ref_count_becomes_zero->pulse_if_not_already_pulsed();
            }
        }
    }
}

template <class protocol_t>
void namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface(
            namespace_cache_t *cache,
            namespace_id_t namespace_id,
            auto_drainer_t::lock_t keepalive)
            THROWS_NOTHING{
    keepalive.assert_is_holding(&cache->drainer);
    int thread = get_thread_id();

    namespace_cache_entry_t *cache_entry = cache->entries.find(namespace_id)->second;
    rassert_unreviewed(!cache_entry->namespace_if.get_ready_signal()->is_pulsed());

    /* We need to switch to `home_thread()` to construct
    `cross_thread_watchable`, then switch back. In destruction we need to do the
    reverse. Fortunately RAII works really nicely here. */
    on_thread_t switch_to_home_thread(home_thread());
    clone_ptr_t<watchable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > > subview =
        namespaces_directory_metadata->subview(boost::bind(&get_reactor_business_cards<protocol_t>, _1, namespace_id));
    cross_thread_watchable_variable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > cross_thread_watchable(subview, thread);
    on_thread_t switch_back(thread);

    cluster_namespace_interface_t<protocol_t> namespace_interface(
        mailbox_manager,
        cross_thread_watchable.get_watchable(),
        ctx);

    try {
        wait_interruptible(namespace_interface.get_initial_ready_signal(),
            keepalive.get_drain_signal());

        /* Notify `access_t`s that the namespace is available now */
        cache_entry->namespace_if.pulse(&namespace_interface);

        /* Wait until it's time to shut down */
        while (true) {
            while (cache_entry->ref_count != 0) {
                cond_t ref_count_is_zero;
                assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_zero(
                    &cache_entry->pulse_when_ref_count_becomes_zero,
                    &ref_count_is_zero);
                wait_interruptible(&ref_count_is_zero, keepalive.get_drain_signal());
            }
            signal_timer_t expiration_timer(NAMESPACE_INTERFACE_EXPIRATION_MS);
            cond_t ref_count_is_nonzero;
            assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_nonzero(
                &cache_entry->pulse_when_ref_count_becomes_nonzero,
                &ref_count_is_nonzero);
            wait_any_t waiter(&expiration_timer, &ref_count_is_nonzero);
            wait_interruptible(&waiter, keepalive.get_drain_signal());
            if (!ref_count_is_nonzero.is_pulsed()) {
                rassert_unreviewed(cache_entry->ref_count == 0);
                /* We waited a whole `NAMESPACE_INTERFACE_EXPIRATION_MS` and
                nothing used us. So let's destroy ourselves. */
                break;
            }
        }

    } catch (interrupted_exc_t) {
        /* We got here because we were interrupted in the startup process. That
        means the `namespace_repo_t` destructor was called, which means there
        mustn't exist any `access_t` objects. So ref_count must be 0. */
        rassert_unreviewed(cache_entry->ref_count == 0);
    }

    ASSERT_NO_CORO_WAITING;
    cache->entries.erase(namespace_id);
}

#include "mock/dummy_protocol.hpp"
#include "memcached/protocol.hpp"
#include "rdb_protocol/protocol.hpp"

template class namespace_repo_t<mock::dummy_protocol_t>;
template class namespace_repo_t<memcached_protocol_t>;
template class namespace_repo_t<rdb_protocol_t>;
<commit_msg>Reviewed assertions in namespace_interface_repository.cc.<commit_after>#include "clustering/administration/namespace_interface_repository.hpp"

#include "errors.hpp"
#include <boost/bind.hpp>
#include <boost/ptr_container/ptr_map.hpp>

#include "concurrency/cross_thread_signal.hpp"
#include "concurrency/cross_thread_watchable.hpp"

#define NAMESPACE_INTERFACE_EXPIRATION_MS (60 * 1000)

template <class protocol_t>
struct namespace_repo_t<protocol_t>::namespace_cache_t {
public:
    boost::ptr_map<namespace_id_t, namespace_cache_entry_t> entries;
    auto_drainer_t drainer;
};

template <class protocol_t>
namespace_repo_t<protocol_t>::namespace_repo_t(mailbox_manager_t *_mailbox_manager,
                                               clone_ptr_t<watchable_t<std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > > > _namespaces_directory_metadata,
                                               typename protocol_t::context_t *_ctx)
    : mailbox_manager(_mailbox_manager),
      namespaces_directory_metadata(_namespaces_directory_metadata),
      ctx(_ctx)
{ }

template <class protocol_t>
namespace_repo_t<protocol_t>::~namespace_repo_t() { }

template <class protocol_t>
std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > get_reactor_business_cards(
        const std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> > &ns_directory_metadata, namespace_id_t n_id) {
    std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > res;
    for (typename std::map<peer_id_t, namespaces_directory_metadata_t<protocol_t> >::const_iterator it  = ns_directory_metadata.begin();
                                                                                it != ns_directory_metadata.end();
                                                                                it++) {
        typename namespaces_directory_metadata_t<protocol_t>::reactor_bcards_map_t::const_iterator jt =
            it->second.reactor_bcards.find(n_id);
        if (jt != it->second.reactor_bcards.end()) {
            res[it->first] = jt->second.internal;
        } else {
            res[it->first] = cow_ptr_t<reactor_business_card_t<protocol_t> >();
        }
    }

    return res;
}

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::access_t() :
    cache_entry(NULL),
    thread(INVALID_THREAD)
    { }

template<class protocol_t>
namespace_repo_t<protocol_t>::access_t::access_t(namespace_repo_t *parent, namespace_id_t namespace_id, signal_t *interruptor) :
    thread(get_thread_id())
{
    {
        ASSERT_FINITE_CORO_WAITING;
        namespace_cache_t *cache = parent->namespace_caches.get();
        if (cache->entries.find(namespace_id) == cache->entries.end()) {
            cache_entry = new namespace_cache_entry_t;
            cache_entry->ref_count = 0;
            cache_entry->pulse_when_ref_count_becomes_zero = NULL;
            cache_entry->pulse_when_ref_count_becomes_nonzero = NULL;
            ref_handler.init(cache_entry);
            cache->entries.insert(namespace_id, cache_entry);
            coro_t::spawn_sometime(boost::bind(
                &namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface, parent,
                cache, namespace_id,
                auto_drainer_t::lock_t(&cache->drainer)));
        } else {
            cache_entry = &cache->entries[namespace_id];
            ref_handler.init(cache_entry);
        }
    }
    wait_interruptible(cache_entry->namespace_if.get_ready_signal(), interruptor);
}

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::access_t(const access_t& access) :
    cache_entry(access.cache_entry),
    thread(access.thread)
{
    if (cache_entry) {
        rassert_reviewed(get_thread_id() == thread);
        ref_handler.init(cache_entry);
    }
}

template <class protocol_t>
typename namespace_repo_t<protocol_t>::access_t &namespace_repo_t<protocol_t>::access_t::operator=(const access_t &access) {
    if (this != &access) {
        cache_entry = access.cache_entry;
        ref_handler.reset();
        if (access.cache_entry) {
            ref_handler.init(access.cache_entry);
        }
        thread = access.thread;
    }
    return *this;
}

template <class protocol_t>
namespace_interface_t<protocol_t> *namespace_repo_t<protocol_t>::access_t::get_namespace_if() {
    rassert_reviewed(thread == get_thread_id());
    return cache_entry->namespace_if.get_value();
}

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::ref_handler_t::ref_handler_t() :
    ref_target(NULL) { }

template <class protocol_t>
namespace_repo_t<protocol_t>::access_t::ref_handler_t::~ref_handler_t() {
    reset();
}

template <class protocol_t>
void namespace_repo_t<protocol_t>::access_t::ref_handler_t::init(namespace_cache_entry_t *_ref_target) {
    ASSERT_NO_CORO_WAITING;
    guarantee_reviewed(ref_target == NULL);
    ref_target = _ref_target;
    ref_target->ref_count++;
    if (ref_target->ref_count == 1) {
        if (ref_target->pulse_when_ref_count_becomes_nonzero) {
            ref_target->pulse_when_ref_count_becomes_nonzero->pulse_if_not_already_pulsed();
        }
    }
}

template <class protocol_t>
void namespace_repo_t<protocol_t>::access_t::ref_handler_t::reset() {
    ASSERT_NO_CORO_WAITING;
    if (ref_target != NULL) {
        ref_target->ref_count--;
        if (ref_target->ref_count == 0) {
            if (ref_target->pulse_when_ref_count_becomes_zero) {
                ref_target->pulse_when_ref_count_becomes_zero->pulse_if_not_already_pulsed();
            }
        }
    }
}

template <class protocol_t>
void namespace_repo_t<protocol_t>::create_and_destroy_namespace_interface(
            namespace_cache_t *cache,
            namespace_id_t namespace_id,
            auto_drainer_t::lock_t keepalive)
            THROWS_NOTHING{
    keepalive.assert_is_holding(&cache->drainer);
    int thread = get_thread_id();

    namespace_cache_entry_t *cache_entry = cache->entries.find(namespace_id)->second;
    guarantee_reviewed(!cache_entry->namespace_if.get_ready_signal()->is_pulsed());

    /* We need to switch to `home_thread()` to construct
    `cross_thread_watchable`, then switch back. In destruction we need to do the
    reverse. Fortunately RAII works really nicely here. */
    on_thread_t switch_to_home_thread(home_thread());
    clone_ptr_t<watchable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > > subview =
        namespaces_directory_metadata->subview(boost::bind(&get_reactor_business_cards<protocol_t>, _1, namespace_id));
    cross_thread_watchable_variable_t<std::map<peer_id_t, cow_ptr_t<reactor_business_card_t<protocol_t> > > > cross_thread_watchable(subview, thread);
    on_thread_t switch_back(thread);

    cluster_namespace_interface_t<protocol_t> namespace_interface(
        mailbox_manager,
        cross_thread_watchable.get_watchable(),
        ctx);

    try {
        wait_interruptible(namespace_interface.get_initial_ready_signal(),
            keepalive.get_drain_signal());

        /* Notify `access_t`s that the namespace is available now */
        cache_entry->namespace_if.pulse(&namespace_interface);

        /* Wait until it's time to shut down */
        while (true) {
            while (cache_entry->ref_count != 0) {
                cond_t ref_count_is_zero;
                assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_zero(
                    &cache_entry->pulse_when_ref_count_becomes_zero,
                    &ref_count_is_zero);
                wait_interruptible(&ref_count_is_zero, keepalive.get_drain_signal());
            }
            signal_timer_t expiration_timer(NAMESPACE_INTERFACE_EXPIRATION_MS);
            cond_t ref_count_is_nonzero;
            assignment_sentry_t<cond_t *> notify_if_ref_count_becomes_nonzero(
                &cache_entry->pulse_when_ref_count_becomes_nonzero,
                &ref_count_is_nonzero);
            wait_any_t waiter(&expiration_timer, &ref_count_is_nonzero);
            wait_interruptible(&waiter, keepalive.get_drain_signal());
            if (!ref_count_is_nonzero.is_pulsed()) {
                guarantee_reviewed(cache_entry->ref_count == 0);
                /* We waited a whole `NAMESPACE_INTERFACE_EXPIRATION_MS` and
                nothing used us. So let's destroy ourselves. */
                break;
            }
        }

    } catch (interrupted_exc_t) {
        /* We got here because we were interrupted in the startup process. That
        means the `namespace_repo_t` destructor was called, which means there
        mustn't exist any `access_t` objects. So ref_count must be 0. */
        guarantee_reviewed(cache_entry->ref_count == 0);
    }

    ASSERT_NO_CORO_WAITING;
    cache->entries.erase(namespace_id);
}

#include "mock/dummy_protocol.hpp"
#include "memcached/protocol.hpp"
#include "rdb_protocol/protocol.hpp"

template class namespace_repo_t<mock::dummy_protocol_t>;
template class namespace_repo_t<memcached_protocol_t>;
template class namespace_repo_t<rdb_protocol_t>;
<|endoftext|>


<commit_before>
#ifndef FIXED_FIXED_HPP_INCLUDED
#define FIXED_FIXED_HPP_INCLUDED

// Copyright Joel Riendeau        2008
//           Jean-Philippe Gravel 2008
//           Jean-Olivier Racine  2008
//
// Distributed under the New BSD License.
// (See accompanying file NewBSDLicense.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)

#include "integer_types.hpp"
#include "boost\mpl\if.hpp"

template <sint8_t Magnitude, uint8_t Fractional>
class Q
{
public:
    Q()                   : m_Comp(0) {}
    Q(const Q& val)       : m_Comp(val.m_Comp) {}
    template <typename T>
	Q(T val)              : m_Magn(static_cast<InternalType>(val)), m_Frac(0) {}

	Q(float val)
    {
        m_Comp = static_cast<InternalType>(val * (1 << Fractional));
    }

	Q(double val)
    {
        m_Comp = static_cast<InternalType>(val * (1 << Fractional));
    }

    template <typename T>
    inline operator T() const
    {
        return static_cast<T>(m_Magn);
    }

    inline operator float() const
    {
        if (0 == m_Comp)
            return 0.0f;
        float result = static_cast<float>(m_Comp);
        ((FloatFormat*)&result)->exponent -= Fractional;
        return result;
    }

    inline bool operator==(const Q& val) const {return m_Comp == val.m_Comp;}
    inline bool operator!=(const Q& val) const {return m_Comp != val.m_Comp;}
    inline bool operator< (const Q& val) const {return m_Comp <  val.m_Comp;}
    inline bool operator<=(const Q& val) const {return m_Comp <= val.m_Comp;}
    inline bool operator> (const Q& val) const {return m_Comp >  val.m_Comp;}
    inline bool operator>=(const Q& val) const {return m_Comp >= val.m_Comp;}

    inline Q operator+ (const Q& val) const {Q res; res.m_Comp = m_Comp + val.m_Comp; return res;}
    inline Q operator+=(const Q& val)       {m_Comp += val.m_Comp; return *this;}
    inline Q operator- (const Q& val) const {Q res; res.m_Comp = m_Comp - val.m_Comp; return res;}
    inline Q operator-=(const Q& val)       {m_Comp -= val.m_Comp; return *this;}
    inline Q operator* (const Q& val) const
    {
        Q res;
        res.m_Comp = (static_cast<MultiplyType>(m_Comp) *
                      static_cast<MultiplyType>(val.m_Comp)) >> Fractional;
        return res;
    }
    inline Q operator*=(const Q& val)
    {
        m_Comp =  (static_cast<MultiplyType>(m_Comp) *
                   static_cast<MultiplyType>(val.m_Comp)) >> Fractional;
        return *this;
    }
    inline Q operator/(const Q& val) const
    {
        Q res;
        if (val.m_Comp == 0) res.m_Comp = ~val.m_Comp;
        res.m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional;
        return res;
    }
    inline Q operator/=(const Q& val)
    {
        if (val.m_Comp == 0)
            m_Comp = ~val.m_Comp;
        else
            m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional;
        return *this;
    }

    // A template to select the smallest integer type for a given amount of bits
    template <uint8_t Bits, bool Signed> struct FixedInteger
    {
        typedef typename boost::mpl::if_c<(Bits <= 8 && Signed),   sint8_t
              , typename boost::mpl::if_c<(Bits <= 8 && !Signed),  uint8_t
              , typename boost::mpl::if_c<(Bits <= 16 && Signed),  sint16_t
              , typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint16_t
              , typename boost::mpl::if_c<(Bits <= 32 && Signed),  sint32_t
              , typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t
              , typename boost::mpl::if_c<(Bits <= 64 && Signed),  sint64_t
              , typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t
              , void>::type >::type >::type >::type >::type >::type >::type >::type type;
    };

    enum
    {
        NBits = (Magnitude < 0 ? -Magnitude : Magnitude) + Fractional,
        NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude),
        NBits_Frac = Fractional
    };

    typedef typename FixedInteger<NBits,   (Magnitude < 0)>::type InternalType;
    typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType;
    typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType;

    inline InternalType Frac() {return m_Frac;}

    union
    {
        struct
        {
            InternalType m_Frac : NBits_Frac;
            InternalType m_Magn : NBits_Magn;
        };
        InternalType m_Comp;
    };

private:
    typedef union FloatFormat
    {
        struct
        {
            uint32_t mantissa : 23;
            uint32_t exponent : 8;
            uint32_t sign : 1;
        };
        uint32_t full;
    } FloatFormat;
};

template <sint8_t Magnitude, uint8_t Fractional>
inline Q<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val)
{
    //if (Magnitude < 0)
    //    return MAX_VAL
    Q<Magnitude, Fractional>::MultiplyType temp = val.m_Comp << Fractional;
    Q<Magnitude, Fractional>::InternalType root = 0, test;
    for (Sint8 i = Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--)
    {
        test = root + (1 << i);
        if (temp >= test << i)
        {   temp -= test << i;
            root |= 2 << i;
        }
    }
    return root >> 1;
}

template <sint8_t Magnitude, uint8_t Fractional>
inline Q<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val)
{
    Q<Magnitude, Fractional> ret = val;
    ret.m_Frac = 0;
    return ret;
}

template <sint8_t Magnitude, uint8_t Fractional>
inline Q<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val)
{
    Q<Magnitude, Fractional> ret = val;
    if (0 != ret.m_Frac)
        ++ret.m_Magn;
    ret.m_Frac = 0;
    return ret;
}

    /*
	fixed pow(fixed fixedPower);
	fixed log10(void);
	fixed log(void);
	fixed exp(void);
	fixed cos(void);
	fixed sin(void);
	fixed tan(void);*/

#endif<commit_msg>-Removed inlines -Set arithmetic operator arguments to receive const references -Added a templated constructor for other Q types -Started working on comparison operators -Forced m_Frac to an unsigned type, and renamed the types used for m_Magn and m_Frac<commit_after>
#ifndef FIXED_FIXED_HPP_INCLUDED
#define FIXED_FIXED_HPP_INCLUDED

// Copyright Joel Riendeau        2008
//           Jean-Philippe Gravel 2008
//           Jean-Olivier Racine  2008
//
// Distributed under the New BSD License.
// (See accompanying file NewBSDLicense.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)

#include "integer_types.hpp"
#include "boost\mpl\if.hpp"

template <sint8_t Magnitude, uint8_t Fractional>
class Q
{
public:
    Q() : m_Comp(0) {}
    template <sint8_t M, uint8_t F>
    explicit Q(const Q<M,F>& val)
    {
        m_Comp = (Fractional > F) ?
                    static_cast<MagnType>(val.m_Comp << (Fractional - F)) :
                    static_cast<MagnType>(val.m_Comp >> (F - Fractional)) ;
    }
    template <typename T>
	Q(T val) : m_Magn(static_cast<MagnType>(val)), m_Frac(0) {}

	Q(float val)
    {
        m_Comp = static_cast<MagnType>(val * (1 << Fractional));
    }

	Q(double val)
    {
        m_Comp = static_cast<MagnType>(val * (1 << Fractional));
    }

    template <typename T>
    operator T() const
    {
        return static_cast<T>(m_Magn);
    }

    operator float() const
    {
        float result = static_cast<float>(m_Comp);
        ((FloatFormat*)&result)->exponent -= Fractional;
        return (0 == m_Comp) ? 0.0f : result;
    }

    template <sint8_t M, uint8_t F>
    bool operator==(const Q<M,F>& val) const
    {
        return (m_Magn == val.m_Magn) && (m_Frac == val.m_Frac);
    }
    bool operator!=(const Q& val) const {return m_Comp != val.m_Comp;}
    bool operator< (const Q& val) const {return m_Comp <  val.m_Comp;}
    bool operator<=(const Q& val) const {return m_Comp <= val.m_Comp;}
    bool operator> (const Q& val) const {return m_Comp >  val.m_Comp;}
    bool operator>=(const Q& val) const {return m_Comp >= val.m_Comp;}

    Q operator+ (const Q& val) const {Q res; res.m_Comp = m_Comp + val.m_Comp; return res;}
    Q operator+=(const Q& val)       {m_Comp += val.m_Comp; return *this;}
    Q operator- (const Q& val) const {Q res; res.m_Comp = m_Comp - val.m_Comp; return res;}
    Q operator-=(const Q& val)       {m_Comp -= val.m_Comp; return *this;}
    Q operator* (const Q& val) const
    {
        Q res;
        res.m_Comp = (static_cast<MultiplyType>(m_Comp) *
                      static_cast<MultiplyType>(val.m_Comp)) >> Fractional;
        return res;
    }
    Q operator*=(const Q& val)
    {
        m_Comp =  (static_cast<MultiplyType>(m_Comp) *
                   static_cast<MultiplyType>(val.m_Comp)) >> Fractional;
        return *this;
    }
    Q operator/(const Q& val) const
    {
        Q res;
        if (val.m_Comp == 0) res.m_Comp = ~val.m_Comp;
        res.m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional;
        return res;
    }
    Q operator/=(const Q& val)
    {
        if (val.m_Comp == 0)
            m_Comp = ~val.m_Comp;
        else
            m_Comp = ((static_cast<MultiplyType>(m_Comp) << Fractional) / val.m_Comp) >> Fractional;
        return *this;
    }

    // A template to select the smallest integer type for a given amount of bits
    template <uint8_t Bits, bool Signed> struct FixedInteger
    {
        typedef typename boost::mpl::if_c<(Bits <= 8 && Signed),   sint8_t
              , typename boost::mpl::if_c<(Bits <= 8 && !Signed),  uint8_t
              , typename boost::mpl::if_c<(Bits <= 16 && Signed),  sint16_t
              , typename boost::mpl::if_c<(Bits <= 16 && !Signed), uint16_t
              , typename boost::mpl::if_c<(Bits <= 32 && Signed),  sint32_t
              , typename boost::mpl::if_c<(Bits <= 32 && !Signed), uint32_t
              , typename boost::mpl::if_c<(Bits <= 64 && Signed),  sint64_t
              , typename boost::mpl::if_c<(Bits <= 64 && !Signed), uint64_t
              , void>::type >::type >::type >::type >::type >::type >::type >::type type;
    };

    enum
    {
        NBits = (Magnitude < 0 ? -Magnitude : Magnitude) + Fractional,
        NBits_Magn = (Magnitude < 0 ? -Magnitude : Magnitude),
        NBits_Frac = Fractional
    };

    typedef typename FixedInteger<NBits,   (Magnitude < 0)>::type MagnType;
    typedef typename FixedInteger<NBits,   false>::type           FracType;
    typedef typename FixedInteger<NBits*2, (Magnitude < 0)>::type MultiplyType;
    typedef typename FixedInteger<(NBits > sizeof(float) ? NBits : sizeof(float)), false>::type FloatCastType;

    FracType Frac() {return m_Frac;}

    union
    {
        struct
        {
            FracType m_Frac : NBits_Frac;
            MagnType m_Magn : NBits_Magn;
        };
        MagnType m_Comp;
    };

private:
    typedef union FloatFormat
    {
        struct
        {
            uint32_t mantissa : 23;
            uint32_t exponent : 8;
            uint32_t sign : 1;
        };
        uint32_t full;
    } FloatFormat;
};

template <sint8_t Magnitude, uint8_t Fractional>
Q<Magnitude, Fractional> sqrt(const Q<Magnitude, Fractional>& val)
{
    //if (Magnitude < 0)
    //    return MAX_VAL
    Q<Magnitude, Fractional>::MultiplyType temp = val.m_Comp << Fractional;
    Q<Magnitude, Fractional>::InternalType root = 0, test;
    for (Sint8 i = Q<Magnitude, Fractional>::NBits - 1; i >= 0; i--)
    {
        test = root + (1 << i);
        if (temp >= test << i)
        {   temp -= test << i;
            root |= 2 << i;
        }
    }
    return root >> 1;
}

template <sint8_t Magnitude, uint8_t Fractional>
Q<Magnitude, Fractional> floor(const Q<Magnitude, Fractional>& val)
{
    Q<Magnitude, Fractional> ret = val;
    ret.m_Frac = 0;
    return ret;
}

template <sint8_t Magnitude, uint8_t Fractional>
Q<Magnitude, Fractional> ceil(const Q<Magnitude, Fractional>& val)
{
    Q<Magnitude, Fractional> ret = val;
    if (0 != ret.m_Frac)
        ++ret.m_Magn;
    ret.m_Frac = 0;
    return ret;
}

    /*
	fixed pow(fixed fixedPower);
	fixed log10(void);
	fixed log(void);
	fixed exp(void);
	fixed cos(void);
	fixed sin(void);
	fixed tan(void);*/

#endif<|endoftext|>


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

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _FLBYTES_HXX
#include <flbytes.hxx>
#endif

#ifndef _SVSTDARR_ULONGS_DECL
#define _SVSTDARR_ULONGS
#include <svstdarr.hxx>
#undef _SVSTDARR_ULONGS
#endif

namespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes;
    // unnamed namespaces don't work well yet

//============================================================================
namespace unnamed_svtools_flbytes {

inline ULONG MyMin( long a, long b )
{
    return Max( long( Min(  a ,  b ) ), 0L );
}

}

//============================================================================
//
//  SvFillLockBytes
//
//============================================================================

TYPEINIT1(SvFillLockBytes, SvLockBytes);

//============================================================================
SvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes )
    : xLockBytes( pLockBytes ),
      nFilledSize( 0 ),
      bTerminated( FALSE )
{
}

//============================================================================
ErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount,
                             ULONG *pRead ) const
{
    if( bTerminated )
        return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
    else
    {
        ULONG nWanted = nPos + nCount;
        if( IsSynchronMode() )
        {
            while( nWanted > nFilledSize && !bTerminated )
                Application::Yield();
            return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
        }
        else
        {
            ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
            ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead );
            return ( !nCount || nRead == nCount || nErr ) ?
                nErr : ERRCODE_IO_PENDING;
        }
    }
}

//============================================================================
ErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer,
                                  ULONG nCount, ULONG *pWritten )
{
    if( bTerminated )
        return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
    else
    {
        ULONG nWanted = nPos + nCount;
        if( IsSynchronMode() )
        {
            while( nWanted > nFilledSize && !bTerminated )
                Application::Yield();
            return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
        }
        else
        {
            ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
            ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten );
            return ( !nCount || nRead == nCount || nErr ) ?
                nErr : ERRCODE_IO_PENDING;
        }
    }
}

//============================================================================
ErrCode SvFillLockBytes::Flush() const
{
    return xLockBytes->Flush( );
}

//============================================================================
ErrCode SvFillLockBytes::SetSize( ULONG nSize )
{
    return xLockBytes->SetSize( nSize );
}

//============================================================================
ErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType)
{
    return xLockBytes->LockRegion( nPos, nCount, eType );
}

//============================================================================
ErrCode SvFillLockBytes::UnlockRegion(
    ULONG nPos, ULONG nCount, LockType eType)
{
    return xLockBytes->UnlockRegion( nPos, nCount, eType );
}

//============================================================================
ErrCode SvFillLockBytes::Stat(
    SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
    return xLockBytes->Stat( pStat, eFlag );
}

//============================================================================
ErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten )
{
    ErrCode nRet = xLockBytes->WriteAt(
        nFilledSize, pBuffer, nCount, pWritten );
    nFilledSize += *pWritten;
    return nRet;
}

//============================================================================
void SvFillLockBytes::Terminate()
{
    bTerminated = TRUE;
}

//============================================================================
SV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* )

//============================================================================
//
//  SvSyncLockBytes
//
//============================================================================

TYPEINIT1(SvSyncLockBytes, SvOpenLockBytes);

//============================================================================
// virtual
ErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,
                                ULONG * pRead) const
{
    for (ULONG nReadTotal = 0;;)
    {
        ULONG nReadCount = 0;
        ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount,
                                                   &nReadCount);
        nReadTotal += nReadCount;
        if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
        {
            if (pRead)
                *pRead = nReadTotal;
            return nError;
        }
        nPos += nReadCount;
        pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount;
        nCount -= nReadCount;
        Application::Yield();
    }
}

//============================================================================
// virtual
ErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer,
                                 ULONG nCount, ULONG * pWritten)
{
    for (ULONG nWrittenTotal = 0;;)
    {
        ULONG nWrittenCount = 0;
        ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount,
                                                    &nWrittenCount);
        nWrittenTotal += nWrittenCount;
        if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
        {
            if (pWritten)
                *pWritten = nWrittenTotal;
            return nError;
        }
        nPos += nWrittenCount;
        pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount;
        nCount -= nWrittenCount;
        Application::Yield();
    }
}

//============================================================================
//
//  SvCompositeLockBytes
//
//============================================================================

struct SvCompositeLockBytes_Impl
{
    SvLockBytesMemberList aLockBytes;
    SvULongs              aPositions;
    SvULongs              aOffsets;
    BOOL                  bPending;
    ULONG RelativeOffset( ULONG nPos ) const;
    ErrCode ReadWrite_Impl(
        ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
        BOOL bRead );
    SvCompositeLockBytes_Impl() : bPending( FALSE ){}
};

//============================================================================
ULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const
{
    const SvULongs& rPositions = aPositions;
    const SvULongs& rOffsets = aOffsets;

    USHORT nMinPos = 0;
    USHORT nListCount = rPositions.Count();

    // Erster Lockbytes, der bearbeitet werden muss
    while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
        nMinPos ++;
    ULONG nSectionStart = rPositions[ nMinPos ];
    if( nSectionStart > nPos )
        return ULONG_MAX;
    return rOffsets[ nMinPos ] + nPos - nSectionStart;
}

//============================================================================
ErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl(
    ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
    BOOL bRead )
{
    ErrCode nErr = ERRCODE_NONE;
    SvULongs& rPositions = aPositions;
    SvULongs& rOffsets = aOffsets;
    SvLockBytesMemberList& rLockBytes = aLockBytes;

    ULONG nBytes = nCount;
    USHORT nListCount = rPositions.Count();
    USHORT nMinPos = 0;

    // Erster Lockbytes, der bearbeitet werden muss
    while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
        nMinPos ++;
    ULONG nSectionStart = rPositions[ nMinPos ];

    if( nSectionStart > nPos )
    {
        // Es wird aus fuehrendem Leerbereich gearbeitet
        *pProcessed = 0;
        return ERRCODE_IO_CANTREAD;
    }

    ULONG nDone;
    while( nMinPos < nListCount )
    {
        ULONG nToProcess;
        ULONG nSectionStop;
        if( nMinPos + 1 < nListCount )
        {
            nSectionStop = rPositions[ nMinPos + 1 ];
            nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes );
        }
        else
        {
            nToProcess = nBytes;
            nSectionStop = 0;
        }
        ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ];
        SvLockBytes* pLB = rLockBytes.GetObject( nMinPos );
        if( bRead )
            nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone );
        else
            nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone );
        nBytes -= nDone;
        if( nErr || nDone < nToProcess || !nBytes )
        {
            *pProcessed = nCount - nBytes;
            // Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und
            // bPending gesetzt ist, Pending zurueck
            if( !nDone && nMinPos == nListCount - 1 )
                return bPending ? ERRCODE_IO_PENDING : nErr;
            else return nErr;
        }
        pBuffer = static_cast< sal_Char * >(pBuffer) + nDone;
        nPos += nDone;
        nSectionStart = nSectionStop;
        nMinPos++;
    }
    return nErr;
}

//============================================================================
TYPEINIT1(SvCompositeLockBytes, SvLockBytes);

//============================================================================
SvCompositeLockBytes::SvCompositeLockBytes()
    : pImpl( new SvCompositeLockBytes_Impl )
{
}

//============================================================================
SvCompositeLockBytes::~SvCompositeLockBytes()
{
    delete pImpl;
}

//============================================================================
void  SvCompositeLockBytes::SetIsPending( BOOL bSet )
{
    pImpl->bPending = bSet;
}

//============================================================================
ULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const
{
    return  pImpl->RelativeOffset( nPos );
}

//============================================================================
ErrCode SvCompositeLockBytes::ReadAt(
    ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const
{
    return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE );
}

//============================================================================
ErrCode SvCompositeLockBytes::WriteAt(
    ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten )
{
    return pImpl->ReadWrite_Impl(
        nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE );
}

//============================================================================
ErrCode SvCompositeLockBytes::Flush() const
{
    SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes;
    ErrCode nErr = ERRCODE_NONE;
    for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; )
        nErr = rLockBytes.GetObject( nCount )->Flush();
    return nErr;
}

//============================================================================
ErrCode SvCompositeLockBytes::SetSize( ULONG )
{
    DBG_ERROR( "not implemented" );
    return ERRCODE_IO_NOTSUPPORTED;
}

//============================================================================
ErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType )
{
    DBG_ERROR( "not implemented" );
    return ERRCODE_IO_NOTSUPPORTED;
}

//============================================================================
ErrCode SvCompositeLockBytes::UnlockRegion(
    ULONG, ULONG, LockType )
{
    DBG_ERROR( "not implemented" );
    return ERRCODE_IO_NOTSUPPORTED;
}

//============================================================================
ErrCode SvCompositeLockBytes::Stat(
    SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
    USHORT nMax = pImpl->aPositions.Count() - 1;

    SvLockBytesStat aStat;
    ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag );
    pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize;

    return nErr;
}

//============================================================================
void SvCompositeLockBytes::Append(
    SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset )
{
    USHORT nCount = pImpl->aOffsets.Count();
    pImpl->aLockBytes.Insert( pLockBytes, nCount );
    pImpl->aPositions.Insert( nPos, nCount );
    pImpl->aOffsets.Insert( nOffset, nCount );
}

//============================================================================
SvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const
{
    return pImpl->aLockBytes.Count() ?
        pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.92); FILE MERGED 2006/09/01 17:43:19 kaib 1.3.92.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: flbytes.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:10:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

#ifndef _FLBYTES_HXX
#include <flbytes.hxx>
#endif

#ifndef _SVSTDARR_ULONGS_DECL
#define _SVSTDARR_ULONGS
#include <svstdarr.hxx>
#undef _SVSTDARR_ULONGS
#endif

namespace unnamed_svtools_flbytes {} using namespace unnamed_svtools_flbytes;
    // unnamed namespaces don't work well yet

//============================================================================
namespace unnamed_svtools_flbytes {

inline ULONG MyMin( long a, long b )
{
    return Max( long( Min(  a ,  b ) ), 0L );
}

}

//============================================================================
//
//  SvFillLockBytes
//
//============================================================================

TYPEINIT1(SvFillLockBytes, SvLockBytes);

//============================================================================
SvFillLockBytes::SvFillLockBytes( SvLockBytes* pLockBytes )
    : xLockBytes( pLockBytes ),
      nFilledSize( 0 ),
      bTerminated( FALSE )
{
}

//============================================================================
ErrCode SvFillLockBytes::ReadAt( ULONG nPos, void* pBuffer, ULONG nCount,
                             ULONG *pRead ) const
{
    if( bTerminated )
        return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
    else
    {
        ULONG nWanted = nPos + nCount;
        if( IsSynchronMode() )
        {
            while( nWanted > nFilledSize && !bTerminated )
                Application::Yield();
            return xLockBytes->ReadAt( nPos, pBuffer, nCount, pRead );
        }
        else
        {
            ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
            ULONG nErr = xLockBytes->ReadAt( nPos, pBuffer, nRead, pRead );
            return ( !nCount || nRead == nCount || nErr ) ?
                nErr : ERRCODE_IO_PENDING;
        }
    }
}

//============================================================================
ErrCode SvFillLockBytes::WriteAt( ULONG nPos, const void* pBuffer,
                                  ULONG nCount, ULONG *pWritten )
{
    if( bTerminated )
        return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
    else
    {
        ULONG nWanted = nPos + nCount;
        if( IsSynchronMode() )
        {
            while( nWanted > nFilledSize && !bTerminated )
                Application::Yield();
            return xLockBytes->WriteAt( nPos, pBuffer, nCount, pWritten );
        }
        else
        {
            ULONG nRead = MyMin( nCount, long( nFilledSize ) - nPos );
            ULONG nErr = xLockBytes->WriteAt( nPos, pBuffer, nRead, pWritten );
            return ( !nCount || nRead == nCount || nErr ) ?
                nErr : ERRCODE_IO_PENDING;
        }
    }
}

//============================================================================
ErrCode SvFillLockBytes::Flush() const
{
    return xLockBytes->Flush( );
}

//============================================================================
ErrCode SvFillLockBytes::SetSize( ULONG nSize )
{
    return xLockBytes->SetSize( nSize );
}

//============================================================================
ErrCode SvFillLockBytes::LockRegion( ULONG nPos, ULONG nCount, LockType eType)
{
    return xLockBytes->LockRegion( nPos, nCount, eType );
}

//============================================================================
ErrCode SvFillLockBytes::UnlockRegion(
    ULONG nPos, ULONG nCount, LockType eType)
{
    return xLockBytes->UnlockRegion( nPos, nCount, eType );
}

//============================================================================
ErrCode SvFillLockBytes::Stat(
    SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
    return xLockBytes->Stat( pStat, eFlag );
}

//============================================================================
ErrCode SvFillLockBytes::FillAppend( const void* pBuffer, ULONG nCount, ULONG *pWritten )
{
    ErrCode nRet = xLockBytes->WriteAt(
        nFilledSize, pBuffer, nCount, pWritten );
    nFilledSize += *pWritten;
    return nRet;
}

//============================================================================
void SvFillLockBytes::Terminate()
{
    bTerminated = TRUE;
}

//============================================================================
SV_DECL_IMPL_REF_LIST( SvLockBytes, SvLockBytes* )

//============================================================================
//
//  SvSyncLockBytes
//
//============================================================================

TYPEINIT1(SvSyncLockBytes, SvOpenLockBytes);

//============================================================================
// virtual
ErrCode SvSyncLockBytes::ReadAt(ULONG nPos, void * pBuffer, ULONG nCount,
                                ULONG * pRead) const
{
    for (ULONG nReadTotal = 0;;)
    {
        ULONG nReadCount = 0;
        ErrCode nError = m_xAsyncLockBytes->ReadAt(nPos, pBuffer, nCount,
                                                   &nReadCount);
        nReadTotal += nReadCount;
        if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
        {
            if (pRead)
                *pRead = nReadTotal;
            return nError;
        }
        nPos += nReadCount;
        pBuffer = static_cast< sal_Char * >(pBuffer) + nReadCount;
        nCount -= nReadCount;
        Application::Yield();
    }
}

//============================================================================
// virtual
ErrCode SvSyncLockBytes::WriteAt(ULONG nPos, const void * pBuffer,
                                 ULONG nCount, ULONG * pWritten)
{
    for (ULONG nWrittenTotal = 0;;)
    {
        ULONG nWrittenCount = 0;
        ErrCode nError = m_xAsyncLockBytes->WriteAt(nPos, pBuffer, nCount,
                                                    &nWrittenCount);
        nWrittenTotal += nWrittenCount;
        if (nError != ERRCODE_IO_PENDING || !IsSynchronMode())
        {
            if (pWritten)
                *pWritten = nWrittenTotal;
            return nError;
        }
        nPos += nWrittenCount;
        pBuffer = static_cast< sal_Char const * >(pBuffer) + nWrittenCount;
        nCount -= nWrittenCount;
        Application::Yield();
    }
}

//============================================================================
//
//  SvCompositeLockBytes
//
//============================================================================

struct SvCompositeLockBytes_Impl
{
    SvLockBytesMemberList aLockBytes;
    SvULongs              aPositions;
    SvULongs              aOffsets;
    BOOL                  bPending;
    ULONG RelativeOffset( ULONG nPos ) const;
    ErrCode ReadWrite_Impl(
        ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
        BOOL bRead );
    SvCompositeLockBytes_Impl() : bPending( FALSE ){}
};

//============================================================================
ULONG SvCompositeLockBytes_Impl::RelativeOffset( ULONG nPos ) const
{
    const SvULongs& rPositions = aPositions;
    const SvULongs& rOffsets = aOffsets;

    USHORT nMinPos = 0;
    USHORT nListCount = rPositions.Count();

    // Erster Lockbytes, der bearbeitet werden muss
    while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
        nMinPos ++;
    ULONG nSectionStart = rPositions[ nMinPos ];
    if( nSectionStart > nPos )
        return ULONG_MAX;
    return rOffsets[ nMinPos ] + nPos - nSectionStart;
}

//============================================================================
ErrCode SvCompositeLockBytes_Impl::ReadWrite_Impl(
    ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pProcessed,
    BOOL bRead )
{
    ErrCode nErr = ERRCODE_NONE;
    SvULongs& rPositions = aPositions;
    SvULongs& rOffsets = aOffsets;
    SvLockBytesMemberList& rLockBytes = aLockBytes;

    ULONG nBytes = nCount;
    USHORT nListCount = rPositions.Count();
    USHORT nMinPos = 0;

    // Erster Lockbytes, der bearbeitet werden muss
    while( nMinPos + 1 < nListCount && rPositions[ nMinPos + 1 ] <= nPos )
        nMinPos ++;
    ULONG nSectionStart = rPositions[ nMinPos ];

    if( nSectionStart > nPos )
    {
        // Es wird aus fuehrendem Leerbereich gearbeitet
        *pProcessed = 0;
        return ERRCODE_IO_CANTREAD;
    }

    ULONG nDone;
    while( nMinPos < nListCount )
    {
        ULONG nToProcess;
        ULONG nSectionStop;
        if( nMinPos + 1 < nListCount )
        {
            nSectionStop = rPositions[ nMinPos + 1 ];
            nToProcess = MyMin( long( nSectionStop ) - nPos, nBytes );
        }
        else
        {
            nToProcess = nBytes;
            nSectionStop = 0;
        }
        ULONG nAbsPos = nPos - nSectionStart + rOffsets[ nMinPos ];
        SvLockBytes* pLB = rLockBytes.GetObject( nMinPos );
        if( bRead )
            nErr = pLB->ReadAt( nAbsPos, pBuffer, nToProcess, &nDone );
        else
            nErr = pLB->WriteAt( nAbsPos, pBuffer, nToProcess, &nDone );
        nBytes -= nDone;
        if( nErr || nDone < nToProcess || !nBytes )
        {
            *pProcessed = nCount - nBytes;
            // Wenn aus dem letzten LockBytes nichts mehr gelesen wurde und
            // bPending gesetzt ist, Pending zurueck
            if( !nDone && nMinPos == nListCount - 1 )
                return bPending ? ERRCODE_IO_PENDING : nErr;
            else return nErr;
        }
        pBuffer = static_cast< sal_Char * >(pBuffer) + nDone;
        nPos += nDone;
        nSectionStart = nSectionStop;
        nMinPos++;
    }
    return nErr;
}

//============================================================================
TYPEINIT1(SvCompositeLockBytes, SvLockBytes);

//============================================================================
SvCompositeLockBytes::SvCompositeLockBytes()
    : pImpl( new SvCompositeLockBytes_Impl )
{
}

//============================================================================
SvCompositeLockBytes::~SvCompositeLockBytes()
{
    delete pImpl;
}

//============================================================================
void  SvCompositeLockBytes::SetIsPending( BOOL bSet )
{
    pImpl->bPending = bSet;
}

//============================================================================
ULONG SvCompositeLockBytes::RelativeOffset( ULONG nPos ) const
{
    return  pImpl->RelativeOffset( nPos );
}

//============================================================================
ErrCode SvCompositeLockBytes::ReadAt(
    ULONG nPos, void* pBuffer, ULONG nCount, ULONG* pRead ) const
{
    return pImpl->ReadWrite_Impl( nPos, pBuffer, nCount, pRead, TRUE );
}

//============================================================================
ErrCode SvCompositeLockBytes::WriteAt(
    ULONG nPos, const void* pBuffer, ULONG nCount, ULONG* pWritten )
{
    return pImpl->ReadWrite_Impl(
        nPos, const_cast< void * >(pBuffer), nCount, pWritten, FALSE );
}

//============================================================================
ErrCode SvCompositeLockBytes::Flush() const
{
    SvLockBytesMemberList& rLockBytes = pImpl->aLockBytes;
    ErrCode nErr = ERRCODE_NONE;
    for( USHORT nCount = (USHORT)rLockBytes.Count(); !nErr && nCount--; )
        nErr = rLockBytes.GetObject( nCount )->Flush();
    return nErr;
}

//============================================================================
ErrCode SvCompositeLockBytes::SetSize( ULONG )
{
    DBG_ERROR( "not implemented" );
    return ERRCODE_IO_NOTSUPPORTED;
}

//============================================================================
ErrCode SvCompositeLockBytes::LockRegion( ULONG, ULONG, LockType )
{
    DBG_ERROR( "not implemented" );
    return ERRCODE_IO_NOTSUPPORTED;
}

//============================================================================
ErrCode SvCompositeLockBytes::UnlockRegion(
    ULONG, ULONG, LockType )
{
    DBG_ERROR( "not implemented" );
    return ERRCODE_IO_NOTSUPPORTED;
}

//============================================================================
ErrCode SvCompositeLockBytes::Stat(
    SvLockBytesStat* pStat, SvLockBytesStatFlag eFlag) const
{
    USHORT nMax = pImpl->aPositions.Count() - 1;

    SvLockBytesStat aStat;
    ErrCode nErr = pImpl->aLockBytes.GetObject( nMax )->Stat( &aStat, eFlag );
    pStat->nSize = pImpl->aPositions[ nMax ] + aStat.nSize;

    return nErr;
}

//============================================================================
void SvCompositeLockBytes::Append(
    SvLockBytes* pLockBytes, ULONG nPos, ULONG nOffset )
{
    USHORT nCount = pImpl->aOffsets.Count();
    pImpl->aLockBytes.Insert( pLockBytes, nCount );
    pImpl->aPositions.Insert( nPos, nCount );
    pImpl->aOffsets.Insert( nOffset, nCount );
}

//============================================================================
SvLockBytes* SvCompositeLockBytes::GetLastLockBytes() const
{
    return pImpl->aLockBytes.Count() ?
        pImpl->aLockBytes.GetObject( pImpl->aLockBytes.Count() - 1 ) : 0;
}

<|endoftext|>


<commit_before>//
//  ex7_13.cpp
//  Exercise 7.13
//
//  Created by pezy on 11/9/14.
//

#include "ex7_12.h"

int main()
{
    Sales_data total(std::cin);
    if (!total.isbn().empty())
    {
        std::istream &is = std::cin;
        while (is) {
            Sales_data trans(is);
            if (total.isbn() == trans.isbn())
                total.combine(trans);
            else {
                print(std::cout, total) << std::endl;
                total = trans;
            }
        }
        print(std::cout, total) << std::endl;
    }
    else
    {
        std::cerr << "No data?!" << std::endl;
        return -1;
    }

    return 0;
}
<commit_msg>Fixed #658<commit_after>//
//  ex7_13.cpp
//  Exercise 7.13
//
//  Created by pezy on 11/9/14.
//

#include "ex7_12.h"

int main()
{
    Sales_data total(std::cin);
    if (!total.isbn().empty())
    {
        std::istream &is = std::cin;
        while (is) {
            Sales_data trans(is);
            if (!is) break;
            if (total.isbn() == trans.isbn())
                total.combine(trans);
            else {
                print(std::cout, total) << std::endl;
                total = trans;
            }
        }
        print(std::cout, total) << std::endl;
    }
    else
    {
        std::cerr << "No data?!" << std::endl;
        return -1;
    }

    return 0;
}
<|endoftext|>


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

#ifndef _EDITOBJ2_HXX
#define _EDITOBJ2_HXX

#include <editobj.hxx>
#include <editdoc.hxx>

#include <vcl/fontcvt.hxx>

class SfxStyleSheetPool;

class XEditAttribute
{
    friend class ContentInfo;   // fuer DTOR
    friend class BinTextObject; // fuer DTOR

private:
    const SfxPoolItem*  pItem;
    USHORT              nStart;
    USHORT              nEnd;

                        XEditAttribute();
                        XEditAttribute( const XEditAttribute& rCopyFrom );

                        ~XEditAttribute();

public:
                        XEditAttribute( const SfxPoolItem& rAttr );
                        XEditAttribute( const SfxPoolItem& rAttr, USHORT nStart, USHORT nEnd );

    const SfxPoolItem*  GetItem() const             { return pItem; }

    USHORT&             GetStart()                  { return nStart; }
    USHORT&             GetEnd()                    { return nEnd; }

    USHORT              GetStart() const            { return nStart; }
    USHORT              GetEnd() const              { return nEnd; }

    USHORT              GetLen() const              { return nEnd-nStart; }

    inline BOOL         IsFeature();
};

inline BOOL XEditAttribute::IsFeature()
{
    USHORT nWhich = pItem->Which();
    return  ( ( nWhich >= EE_FEATURE_START ) &&
              ( nWhich <=  EE_FEATURE_END ) );
}

typedef XEditAttribute* XEditAttributePtr;
SV_DECL_PTRARR( XEditAttributeListImpl, XEditAttributePtr, 0, 4 );

class XEditAttributeList : public XEditAttributeListImpl
{
public:
    XEditAttribute* FindAttrib( USHORT nWhich, USHORT nChar ) const;
};

struct XParaPortion
{
    long                nHeight;
    USHORT              nFirstLineOffset;

    EditLineList        aLines;
    TextPortionList     aTextPortions;
};

typedef XParaPortion* XParaPortionPtr;
SV_DECL_PTRARR( XBaseParaPortionList, XParaPortionPtr, 0, 4 );

class XParaPortionList : public  XBaseParaPortionList
{
    ULONG       nRefDevPtr;
    OutDevType  eRefDevType;
    MapMode     aRefMapMode;
    ULONG       nPaperWidth;

public:
            XParaPortionList( OutputDevice* pRefDev, ULONG nPW ) :
                aRefMapMode( pRefDev->GetMapMode() )
                {
                    nRefDevPtr = (ULONG)pRefDev; nPaperWidth = nPW;
                    eRefDevType = pRefDev->GetOutDevType();
                }

    ULONG           GetRefDevPtr() const        { return nRefDevPtr; }
    ULONG           GetPaperWidth() const       { return nPaperWidth; }
    OutDevType      GetRefDevType() const       { return eRefDevType; }
    const MapMode&  GetRefMapMode() const       { return aRefMapMode; }
};

struct LoadStoreTempInfos
{
    ByteString              aOrgString_Load;

    FontToSubsFontConverter hOldSymbolConv_Store;
    BOOL                    bSymbolParagraph_Store;

    LoadStoreTempInfos() { bSymbolParagraph_Store = FALSE; hOldSymbolConv_Store = NULL; }
};

class ContentInfo
{
    friend class BinTextObject;

private:
    String              aText;
    String              aStyle;
    XEditAttributeList  aAttribs;
    SfxStyleFamily      eFamily;
    SfxItemSet          aParaAttribs;
    WrongList*          pWrongs;

    LoadStoreTempInfos* pTempLoadStoreInfos;

                        ContentInfo( SfxItemPool& rPool );
                        ContentInfo( const ContentInfo& rCopyFrom, SfxItemPool& rPoolToUse  );

public:
                        ~ContentInfo();

    const String&       GetText()           const   { return aText; }
    const String&       GetStyle()          const   { return aStyle; }
    const XEditAttributeList& GetAttribs()  const   { return aAttribs; }
    const SfxItemSet&   GetParaAttribs()    const   { return aParaAttribs; }
    SfxStyleFamily      GetFamily()         const   { return eFamily; }

    String&             GetText()           { return aText; }
    String&             GetStyle()          { return aStyle; }
    XEditAttributeList& GetAttribs()        { return aAttribs; }
    SfxItemSet&         GetParaAttribs()    { return aParaAttribs; }
    SfxStyleFamily&     GetFamily()         { return eFamily; }

    WrongList*          GetWrongList() const            { return pWrongs; }
    void                SetWrongList( WrongList* p )    { pWrongs = p; }

    LoadStoreTempInfos* GetLoadStoreTempInfos() const   { return pTempLoadStoreInfos; }
    void                CreateLoadStoreTempInfos();
    void                DestroyLoadStoreTempInfos();

};

typedef ContentInfo* ContentInfoPtr;
SV_DECL_PTRARR( ContentInfoList, ContentInfoPtr, 1, 4 );

// MT 05/00: Sollte mal direkt EditTextObjekt werden => keine virtuellen Methoden mehr.

class BinTextObject : public EditTextObject
{
private:
    ContentInfoList         aContents;
    SfxItemPool*            pPool;
    BOOL                    bOwnerOfPool;
    XParaPortionList*       pPortionInfo;

    ULONG                   nObjSettings;
    USHORT                  nMetric;
    USHORT                  nVersion;
    USHORT                  nUserType;
    USHORT                  nScriptType;

    BOOL                    bVertical;
    BOOL                    bStoreUnicodeStrings;

protected:
    void                    DeleteContents();
    virtual void            StoreData( SvStream& rOStream ) const;
    virtual void            CreateData( SvStream& rIStream );
    BOOL                    ImpChangeStyleSheets( const String& rOldName, SfxStyleFamily eOldFamily,
                                        const String& rNewName, SfxStyleFamily eNewFamily );

public:
                            BinTextObject( SfxItemPool* pPool );
                            BinTextObject( const BinTextObject& );
    virtual                 ~BinTextObject();

    virtual EditTextObject* Clone() const;

    USHORT                  GetUserType() const;
    void                    SetUserType( USHORT n );

    ULONG                   GetObjectSettings() const;
    void                    SetObjectSettings( ULONG n );

    BOOL                    IsVertical() const;
    void                    SetVertical( BOOL b );

    USHORT                  GetScriptType() const;
    void                    SetScriptType( USHORT nType );

    USHORT                  GetVersion() const; // Solange der Outliner keine Recordlaenge speichert
    void                    SetLRSpaceItemFlags( BOOL bOutlineMode );
    void                    AdjustImportedLRSpaceItems( BOOL bTurnOfBullets );

    ContentInfo*            CreateAndInsertContent();
    XEditAttribute*         CreateAttrib( const SfxPoolItem& rItem, USHORT nStart, USHORT nEnd );
    void                    DestroyAttrib( XEditAttribute* pAttr );

    ContentInfoList&        GetContents()           { return aContents; }
    const ContentInfoList&  GetContents() const     { return aContents; }
    SfxItemPool*            GetPool() const         { return pPool; }
    XParaPortionList*       GetPortionInfo() const  { return pPortionInfo; }
    void                    SetPortionInfo( XParaPortionList* pP )
                                { pPortionInfo = pP; }

    virtual USHORT          GetParagraphCount() const;
    virtual String          GetText( USHORT nParagraph ) const;
    virtual void            Insert( const EditTextObject& rObj, USHORT nPara );
    virtual EditTextObject* CreateTextObject( USHORT nPara, USHORT nParas = 1 ) const;
    virtual void            RemoveParagraph( USHORT nPara );

    virtual BOOL            HasPortionInfo() const;
    virtual void            ClearPortionInfo();

    virtual BOOL            HasOnlineSpellErrors() const;

    virtual BOOL            HasCharAttribs( USHORT nWhich = 0 ) const;
    virtual void            GetCharAttribs( USHORT nPara, EECharAttribArray& rLst ) const;

    virtual BOOL            RemoveCharAttribs( USHORT nWhich = 0 );
    virtual BOOL            RemoveParaAttribs( USHORT nWhich = 0 );

    virtual void            MergeParaAttribs( const SfxItemSet& rAttribs, USHORT nStart, USHORT nEnd );

    virtual BOOL            IsFieldObject() const;
    virtual const SvxFieldItem* GetField() const;
    virtual BOOL            HasField( TypeId Type = NULL ) const;

    SfxItemSet              GetParaAttribs( USHORT nPara ) const;
    void                    SetParaAttribs( USHORT nPara, const SfxItemSet& rAttribs );

    virtual BOOL            HasStyleSheet( const XubString& rName, SfxStyleFamily eFamily ) const;
    virtual void            GetStyleSheet( USHORT nPara, XubString& rName, SfxStyleFamily& eFamily ) const;
    virtual void            SetStyleSheet( USHORT nPara, const XubString& rName, const SfxStyleFamily& eFamily );
    virtual BOOL            ChangeStyleSheets(  const XubString& rOldName, SfxStyleFamily eOldFamily,
                                                const String& rNewName, SfxStyleFamily eNewFamily );
    virtual void            ChangeStyleSheetName( SfxStyleFamily eFamily, const XubString& rOldName, const XubString& rNewName );

    void                    CreateData300( SvStream& rIStream );

    BOOL                    HasMetric() const           { return nMetric != 0xFFFF; }
    USHORT                  GetMetric() const           { return nMetric; }
    void                    SetMetric( USHORT n )       { nMetric = n; }

    BOOL                    IsOwnerOfPool() const       { return bOwnerOfPool; }
    void                    StoreUnicodeStrings( BOOL b ) { bStoreUnicodeStrings = b; }

    void                    PrepareStore( SfxStyleSheetPool* pStyleSheetPool );
    void                    FinishStore();
    void                    FinishLoad( SfxStyleSheetPool* pStyleSheetPool );
};

#endif  // _EDITOBJ2_HXX

<commit_msg>INTEGRATION: CWS impresspresobjs (1.6.140); FILE MERGED 2005/12/09 15:05:20 cl 1.6.140.1: #i58649# added operator== for undo in impress outline view<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: editobj2.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2006-01-10 14:47:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _EDITOBJ2_HXX
#define _EDITOBJ2_HXX

#include <editobj.hxx>
#include <editdoc.hxx>

#include <vcl/fontcvt.hxx>

class SfxStyleSheetPool;

class XEditAttribute
{
    friend class ContentInfo;   // fuer DTOR
    friend class BinTextObject; // fuer DTOR

private:
    const SfxPoolItem*  pItem;
    USHORT              nStart;
    USHORT              nEnd;

                        XEditAttribute();
                        XEditAttribute( const XEditAttribute& rCopyFrom );

                        ~XEditAttribute();

public:
                        XEditAttribute( const SfxPoolItem& rAttr );
                        XEditAttribute( const SfxPoolItem& rAttr, USHORT nStart, USHORT nEnd );

    const SfxPoolItem*  GetItem() const             { return pItem; }

    USHORT&             GetStart()                  { return nStart; }
    USHORT&             GetEnd()                    { return nEnd; }

    USHORT              GetStart() const            { return nStart; }
    USHORT              GetEnd() const              { return nEnd; }

    USHORT              GetLen() const              { return nEnd-nStart; }

    inline BOOL         IsFeature();

    inline bool         operator==( const XEditAttribute& rCompare );
};

inline bool XEditAttribute::operator==( const XEditAttribute& rCompare )
{
    return  (nStart == rCompare.nStart) &&
            (nEnd == rCompare.nEnd) &&
            ( (pItem == rCompare.pItem) || (*pItem == *rCompare.pItem));
}

inline BOOL XEditAttribute::IsFeature()
{
    USHORT nWhich = pItem->Which();
    return  ( ( nWhich >= EE_FEATURE_START ) &&
              ( nWhich <=  EE_FEATURE_END ) );
}

typedef XEditAttribute* XEditAttributePtr;
SV_DECL_PTRARR( XEditAttributeListImpl, XEditAttributePtr, 0, 4 );

class XEditAttributeList : public XEditAttributeListImpl
{
public:
    XEditAttribute* FindAttrib( USHORT nWhich, USHORT nChar ) const;
};

struct XParaPortion
{
    long                nHeight;
    USHORT              nFirstLineOffset;

    EditLineList        aLines;
    TextPortionList     aTextPortions;
};

typedef XParaPortion* XParaPortionPtr;
SV_DECL_PTRARR( XBaseParaPortionList, XParaPortionPtr, 0, 4 );

class XParaPortionList : public  XBaseParaPortionList
{
    ULONG       nRefDevPtr;
    OutDevType  eRefDevType;
    MapMode     aRefMapMode;
    ULONG       nPaperWidth;

public:
            XParaPortionList( OutputDevice* pRefDev, ULONG nPW ) :
                aRefMapMode( pRefDev->GetMapMode() )
                {
                    nRefDevPtr = (ULONG)pRefDev; nPaperWidth = nPW;
                    eRefDevType = pRefDev->GetOutDevType();
                }

    ULONG           GetRefDevPtr() const        { return nRefDevPtr; }
    ULONG           GetPaperWidth() const       { return nPaperWidth; }
    OutDevType      GetRefDevType() const       { return eRefDevType; }
    const MapMode&  GetRefMapMode() const       { return aRefMapMode; }
};

struct LoadStoreTempInfos
{
    ByteString              aOrgString_Load;

    FontToSubsFontConverter hOldSymbolConv_Store;
    BOOL                    bSymbolParagraph_Store;

    LoadStoreTempInfos() { bSymbolParagraph_Store = FALSE; hOldSymbolConv_Store = NULL; }
};

class ContentInfo
{
    friend class BinTextObject;

private:
    String              aText;
    String              aStyle;
    XEditAttributeList  aAttribs;
    SfxStyleFamily      eFamily;
    SfxItemSet          aParaAttribs;
    WrongList*          pWrongs;

    LoadStoreTempInfos* pTempLoadStoreInfos;

                        ContentInfo( SfxItemPool& rPool );
                        ContentInfo( const ContentInfo& rCopyFrom, SfxItemPool& rPoolToUse  );

public:
                        ~ContentInfo();

    const String&       GetText()           const   { return aText; }
    const String&       GetStyle()          const   { return aStyle; }
    const XEditAttributeList& GetAttribs()  const   { return aAttribs; }
    const SfxItemSet&   GetParaAttribs()    const   { return aParaAttribs; }
    SfxStyleFamily      GetFamily()         const   { return eFamily; }

    String&             GetText()           { return aText; }
    String&             GetStyle()          { return aStyle; }
    XEditAttributeList& GetAttribs()        { return aAttribs; }
    SfxItemSet&         GetParaAttribs()    { return aParaAttribs; }
    SfxStyleFamily&     GetFamily()         { return eFamily; }

    WrongList*          GetWrongList() const            { return pWrongs; }
    void                SetWrongList( WrongList* p )    { pWrongs = p; }

    LoadStoreTempInfos* GetLoadStoreTempInfos() const   { return pTempLoadStoreInfos; }
    void                CreateLoadStoreTempInfos();
    void                DestroyLoadStoreTempInfos();

    bool                operator==( const ContentInfo& rCompare ) const;
};

typedef ContentInfo* ContentInfoPtr;
SV_DECL_PTRARR( ContentInfoList, ContentInfoPtr, 1, 4 );

// MT 05/00: Sollte mal direkt EditTextObjekt werden => keine virtuellen Methoden mehr.

class BinTextObject : public EditTextObject
{
private:
    ContentInfoList         aContents;
    SfxItemPool*            pPool;
    BOOL                    bOwnerOfPool;
    XParaPortionList*       pPortionInfo;

    ULONG                   nObjSettings;
    USHORT                  nMetric;
    USHORT                  nVersion;
    USHORT                  nUserType;
    USHORT                  nScriptType;

    BOOL                    bVertical;
    BOOL                    bStoreUnicodeStrings;

protected:
    void                    DeleteContents();
    virtual void            StoreData( SvStream& rOStream ) const;
    virtual void            CreateData( SvStream& rIStream );
    BOOL                    ImpChangeStyleSheets( const String& rOldName, SfxStyleFamily eOldFamily,
                                        const String& rNewName, SfxStyleFamily eNewFamily );

public:
                            BinTextObject( SfxItemPool* pPool );
                            BinTextObject( const BinTextObject& );
    virtual                 ~BinTextObject();

    virtual EditTextObject* Clone() const;

    USHORT                  GetUserType() const;
    void                    SetUserType( USHORT n );

    ULONG                   GetObjectSettings() const;
    void                    SetObjectSettings( ULONG n );

    BOOL                    IsVertical() const;
    void                    SetVertical( BOOL b );

    USHORT                  GetScriptType() const;
    void                    SetScriptType( USHORT nType );

    USHORT                  GetVersion() const; // Solange der Outliner keine Recordlaenge speichert
    void                    SetLRSpaceItemFlags( BOOL bOutlineMode );
    void                    AdjustImportedLRSpaceItems( BOOL bTurnOfBullets );

    ContentInfo*            CreateAndInsertContent();
    XEditAttribute*         CreateAttrib( const SfxPoolItem& rItem, USHORT nStart, USHORT nEnd );
    void                    DestroyAttrib( XEditAttribute* pAttr );

    ContentInfoList&        GetContents()           { return aContents; }
    const ContentInfoList&  GetContents() const     { return aContents; }
    SfxItemPool*            GetPool() const         { return pPool; }
    XParaPortionList*       GetPortionInfo() const  { return pPortionInfo; }
    void                    SetPortionInfo( XParaPortionList* pP )
                                { pPortionInfo = pP; }

    virtual USHORT          GetParagraphCount() const;
    virtual String          GetText( USHORT nParagraph ) const;
    virtual void            Insert( const EditTextObject& rObj, USHORT nPara );
    virtual EditTextObject* CreateTextObject( USHORT nPara, USHORT nParas = 1 ) const;
    virtual void            RemoveParagraph( USHORT nPara );

    virtual BOOL            HasPortionInfo() const;
    virtual void            ClearPortionInfo();

    virtual BOOL            HasOnlineSpellErrors() const;

    virtual BOOL            HasCharAttribs( USHORT nWhich = 0 ) const;
    virtual void            GetCharAttribs( USHORT nPara, EECharAttribArray& rLst ) const;

    virtual BOOL            RemoveCharAttribs( USHORT nWhich = 0 );
    virtual BOOL            RemoveParaAttribs( USHORT nWhich = 0 );

    virtual void            MergeParaAttribs( const SfxItemSet& rAttribs, USHORT nStart, USHORT nEnd );

    virtual BOOL            IsFieldObject() const;
    virtual const SvxFieldItem* GetField() const;
    virtual BOOL            HasField( TypeId Type = NULL ) const;

    SfxItemSet              GetParaAttribs( USHORT nPara ) const;
    void                    SetParaAttribs( USHORT nPara, const SfxItemSet& rAttribs );

    virtual BOOL            HasStyleSheet( const XubString& rName, SfxStyleFamily eFamily ) const;
    virtual void            GetStyleSheet( USHORT nPara, XubString& rName, SfxStyleFamily& eFamily ) const;
    virtual void            SetStyleSheet( USHORT nPara, const XubString& rName, const SfxStyleFamily& eFamily );
    virtual BOOL            ChangeStyleSheets(  const XubString& rOldName, SfxStyleFamily eOldFamily,
                                                const String& rNewName, SfxStyleFamily eNewFamily );
    virtual void            ChangeStyleSheetName( SfxStyleFamily eFamily, const XubString& rOldName, const XubString& rNewName );

    void                    CreateData300( SvStream& rIStream );

    BOOL                    HasMetric() const           { return nMetric != 0xFFFF; }
    USHORT                  GetMetric() const           { return nMetric; }
    void                    SetMetric( USHORT n )       { nMetric = n; }

    BOOL                    IsOwnerOfPool() const       { return bOwnerOfPool; }
    void                    StoreUnicodeStrings( BOOL b ) { bStoreUnicodeStrings = b; }

    void                    PrepareStore( SfxStyleSheetPool* pStyleSheetPool );
    void                    FinishStore();
    void                    FinishLoad( SfxStyleSheetPool* pStyleSheetPool );

    bool                    operator==( const BinTextObject& rCompare ) const;

};

#endif  // _EDITOBJ2_HXX

<|endoftext|>


<commit_before>/*############################################################################################
 Garden System
 Wireless controller for watering electropumps

 Author: Daniele Colanardi
 License: BSD, see LICENSE file
############################################################################################*/

#include <Wire.h>
#include "input.h"

LightMPR121 touch;

void init_buttons() {
	Wire.begin();
    touch.begin();
}

bool update_buttons() {
    touch.update();
}

bool is_pressed(uint8_t i) { return touch.touched(i); }
bool   released(uint8_t i) { return true; }
<commit_msg>Add basic retriggering to input<commit_after>/*############################################################################################
 Garden System
 Wireless controller for watering electropumps

 Author: Daniele Colanardi
 License: BSD, see LICENSE file
############################################################################################*/

#include <Wire.h>
#include "input.h"

LightMPR121 touch;
int last_status;
long repeat_timer;
bool changed;

void init_buttons() {
	Wire.begin();
    touch.begin();
}

bool update_buttons() {
    int new_status = touch.update();

    changed = new_status != last_status;

    last_status = new_status;

    if (changed || millis() - repeat_timer > 150) {
    	repeat_timer = millis();
		if(!changed) changed = true;
    }
}

bool is_pressed(uint8_t i) { return touch.touched(i) && changed; }
bool   released(uint8_t i) { return true; }
<|endoftext|>


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

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

#include "numrule.hxx"
#include "caption.hxx"

#define VERSION_01      1
#define CAPTION_VERSION VERSION_01

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) :
    bUseCaption(FALSE),
    eObjType(eType),
    nNumType(SVX_NUM_ARABIC),
    nPos(1),
    nLevel(0),
    cSeparator('.'),
    bIgnoreSeqOpts(FALSE),
    bCopyAttributes(FALSE)
{
    if (pOleId)
        aOleId = *pOleId;
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt)
{
    *this = rOpt;
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt::~InsCaptionOpt()
{
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt )
{
    bUseCaption = rOpt.bUseCaption;
    eObjType = rOpt.eObjType;
    aOleId = rOpt.aOleId;
    sCategory = rOpt.sCategory;
    nNumType = rOpt.nNumType;
    sCaption = rOpt.sCaption;
    nPos = rOpt.nPos;
    nLevel = rOpt.nLevel;
    cSeparator = rOpt.cSeparator;
    bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts;
    bCopyAttributes = rOpt.bCopyAttributes;

    return *this;
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

BOOL InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const
{
    return (eObjType == rOpt.eObjType &&
            aOleId == rOpt.aOleId); // Damit gleiche Ole-IDs nicht mehrfach eingefuegt
                                    // werden koennen, auf nichts weiteres vergleichen

/*           &&
            sCategory == rOpt.sCategory &&
            nNumType == rOpt.nNumType &&
            sCaption == rOpt.sCaption &&
            nPos == rOpt.nPos &&
            nLevel == rOpt.nLevel &&
            cSeparator == rOpt.cSeparator);*/
}

/*************************************************************************
|*
|*    InsCaptionOpt::operator>>()
|*
|*    Beschreibung      Stream-Leseoperator
|*
*************************************************************************/

SvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt )
{
    rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();
    UINT16 nVal;
    BYTE   cVal;
    BYTE   nVersion;

    rIStream >> nVersion;
    rIStream >> cVal;               rCapOpt.UseCaption() = cVal != 0;
    rIStream >> nVal;               rCapOpt.eObjType = (SwCapObjType)nVal;
    rIStream >> rCapOpt.aOleId;

    rIStream.ReadByteString( rCapOpt.sCategory, eEncoding );
    rIStream >> nVal;               rCapOpt.nNumType = nVal;
    rIStream.ReadByteString( rCapOpt.sCaption, eEncoding );
    rIStream >> nVal;               rCapOpt.nPos = nVal;
    rIStream >> nVal;               rCapOpt.nLevel = nVal;

    rIStream >> cVal;
    rCapOpt.cSeparator = UniString( ByteString(cVal) , eEncoding).GetChar(0);

    return rIStream;
}

/*************************************************************************
|*
|*    InsCaptionOpt::operator<<()
|*
|*    Beschreibung      Stream-Schreiboperator
|*
*************************************************************************/

SvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt )
{
    rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();
    rOStream    << (BYTE)CAPTION_VERSION
                << (BYTE)rCapOpt.UseCaption()
                << (UINT16)rCapOpt.eObjType
                << rCapOpt.aOleId;

    rOStream.WriteByteString( rCapOpt.sCategory, eEncoding );

    rOStream    << (UINT16)rCapOpt.nNumType;

    rOStream.WriteByteString( rCapOpt.sCaption, eEncoding );

    BYTE cSep = ByteString(UniString(rCapOpt.cSeparator), eEncoding).GetChar(0);
    rOStream    << (UINT16)rCapOpt.nPos
                << (UINT16)rCapOpt.nLevel
                << cSep;

    return rOStream;
}

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

#pragma hdrstop

#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

#include "numrule.hxx"
#include "caption.hxx"

#define VERSION_01      1
#define CAPTION_VERSION VERSION_01

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt::InsCaptionOpt(const SwCapObjType eType, const SvGlobalName* pOleId) :
    bUseCaption(FALSE),
    eObjType(eType),
    nNumType(SVX_NUM_ARABIC),
    nPos(1),
    nLevel(0),
    cSeparator('.'),
    bIgnoreSeqOpts(FALSE),
    bCopyAttributes(FALSE)
{
    if (pOleId)
        aOleId = *pOleId;
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt::InsCaptionOpt(const InsCaptionOpt& rOpt)
{
    *this = rOpt;
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt::~InsCaptionOpt()
{
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

InsCaptionOpt& InsCaptionOpt::operator=( const InsCaptionOpt& rOpt )
{
    bUseCaption = rOpt.bUseCaption;
    eObjType = rOpt.eObjType;
    aOleId = rOpt.aOleId;
    sCategory = rOpt.sCategory;
    nNumType = rOpt.nNumType;
    sCaption = rOpt.sCaption;
    nPos = rOpt.nPos;
    nLevel = rOpt.nLevel;
    cSeparator = rOpt.cSeparator;
    bIgnoreSeqOpts = rOpt.bIgnoreSeqOpts;
    bCopyAttributes = rOpt.bCopyAttributes;

    return *this;
}

/*--------------------------------------------------------------------
    Beschreibung:
 --------------------------------------------------------------------*/

BOOL InsCaptionOpt::operator==( const InsCaptionOpt& rOpt ) const
{
    return (eObjType == rOpt.eObjType &&
            aOleId == rOpt.aOleId); // Damit gleiche Ole-IDs nicht mehrfach eingefuegt
                                    // werden koennen, auf nichts weiteres vergleichen

/*           &&
            sCategory == rOpt.sCategory &&
            nNumType == rOpt.nNumType &&
            sCaption == rOpt.sCaption &&
            nPos == rOpt.nPos &&
            nLevel == rOpt.nLevel &&
            cSeparator == rOpt.cSeparator);*/
}

/*************************************************************************
|*
|*    InsCaptionOpt::operator>>()
|*
|*    Beschreibung      Stream-Leseoperator
|*
*************************************************************************/

SvStream& operator>>( SvStream& rIStream, InsCaptionOpt& rCapOpt )
{
    rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();
    UINT16 nVal;
    BYTE   cVal;
    BYTE   nVersion;

    rIStream >> nVersion;
    rIStream >> cVal;               rCapOpt.UseCaption() = cVal != 0;
    rIStream >> nVal;               rCapOpt.eObjType = (SwCapObjType)nVal;
    rIStream >> rCapOpt.aOleId;

    rIStream.ReadByteString( rCapOpt.sCategory, eEncoding );
    rIStream >> nVal;               rCapOpt.nNumType = nVal;
    rIStream.ReadByteString( rCapOpt.sCaption, eEncoding );
    rIStream >> nVal;               rCapOpt.nPos = nVal;
    rIStream >> nVal;               rCapOpt.nLevel = nVal;

    rIStream >> cVal;
    rCapOpt.cSeparator = UniString( ByteString(cVal) , eEncoding).GetChar(0);

    return rIStream;
}

/*************************************************************************
|*
|*    InsCaptionOpt::operator<<()
|*
|*    Beschreibung      Stream-Schreiboperator
|*
*************************************************************************/

SvStream& operator<<( SvStream& rOStream, const InsCaptionOpt& rCapOpt )
{
    rtl_TextEncoding eEncoding = gsl_getSystemTextEncoding();
    rOStream    << (BYTE)CAPTION_VERSION
                << (BYTE)rCapOpt.UseCaption()
                << (UINT16)rCapOpt.eObjType
                << rCapOpt.aOleId;

    rOStream.WriteByteString( rCapOpt.sCategory, eEncoding );

    rOStream    << (UINT16)rCapOpt.nNumType;

    rOStream.WriteByteString( rCapOpt.sCaption, eEncoding );

    BYTE cSep = ByteString(UniString(rCapOpt.cSeparator), eEncoding).GetChar(0);
    rOStream    << (UINT16)rCapOpt.nPos
                << (UINT16)rCapOpt.nLevel
                << cSep;

    return rOStream;
}

<|endoftext|>