<commit_before># ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
# include <cppad/local/optimize/hash_code.hpp>
/*!
\file match_op.hpp
Check if current operator matches a previous operator.
*/
// BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE
namespace CppAD { namespace local { namespace optimize  {
/*!
Search for a previous operator that matches the current one.

If an argument for the current operator is a variable,
and the argument has previous match,
the previous match for the argument is used when checking for a match
for the current operator.

\param var2op
mapping from variable index to operator index.

\param op_info
Mapping from operator index to operator information.
The input value of op_info[current].previous is assumed to be zero.
If a match if found,
the output value of op_info[current].previous is set to the
matching operator index, otherwise it is left as is.
Note that op_info[current].previous < current.

\param current
is the index of the current operator which must be an unary
or binary operator. Note that NumArg(ErfOp) == 3 but it is effectivey
a unary operator and is allowed otherwise NumArg( op_info[current].op) < 3.
It is assumed that hash_table_op is initialized as a vector of emtpy
sets. After this initialization, the value of current inceases with
each call to match_op.

\li
This must be a unary or binary
operator; hence, NumArg( op_info[current].op ) is one or two.
There is one exception, NumRes( ErfOp ) == 3, but arg[0]
is the only true arguments (the others are always the same).

\li
This must not be a VecAD load or store operation; i.e.,
LtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.
It also must not be an independent variable operator InvOp.

\param hash_table_op
is a vector of sets,
hash_table_op.n_set() == CPPAD_HASH_TABLE_SIZE and
hash_table_op.end() == op_info.size().
If i_op is an element of set[j],
then the operation op_info[i_op] has hash code j,
and op_info[i_op] does not match any other element of set[j].
An entry will be added each time match_op is called
and a match for the current operator is not found.
*/

inline void match_op(
	const vector<addr_t>&          var2op         ,
	vector<struct_op_info>&        op_info        ,
	size_t                         current        ,
	sparse_list&                   hash_table_op  )
{	size_t num_op = op_info.size();
	//
	CPPAD_ASSERT_UNKNOWN( op_info[current].previous == 0 );
	CPPAD_ASSERT_UNKNOWN(
		hash_table_op.n_set() == CPPAD_HASH_TABLE_SIZE
	);
	CPPAD_ASSERT_UNKNOWN( hash_table_op.end() == num_op );
	CPPAD_ASSERT_UNKNOWN( current < num_op );
	//
	// current operator
	OpCode        op         = op_info[current].op;
	const addr_t* arg        = op_info[current].arg;
	//
	// which arguments are variable
	size_t num_arg = NumArg(op);
	//
	bool   variable[2];
	variable[0] = false;
	variable[1] = false;
	switch(op)
	{	//
		case ErfOp:
		num_arg = 1; // other arugments are always the same
		//
		case AbsOp:
		case AcosOp:
		case AcoshOp:
		case AsinOp:
		case AsinhOp:
		case AtanOp:
		case AtanhOp:
		case CosOp:
		case CoshOp:
		case ExpOp:
		case Expm1Op:
		case LogOp:
		case Log1pOp:
		case SignOp:
		case SinOp:
		case SinhOp:
		case SqrtOp:
		case TanOp:
		case TanhOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 1 );
		variable[0] = true;
		break;

		case AddpvOp:
		case DisOp:
		case DivpvOp:
		case EqpvOp:
		case LepvOp:
		case LtpvOp:
		case MulpvOp:
		case NepvOp:
		case PowpvOp:
		case SubpvOp:
		case ZmulpvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[1] = true;
		break;

		case DivvpOp:
		case LevpOp:
		case LtvpOp:
		case PowvpOp:
		case SubvpOp:
		case ZmulvpOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		break;

		case AddvvOp:
		case DivvvOp:
		case EqvvOp:
		case LevvOp:
		case LtvvOp:
		case MulvvOp:
		case NevvOp:
		case PowvvOp:
		case SubvvOp:
		case ZmulvvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		variable[1] = true;
		break;

		default:
		CPPAD_ASSERT_UNKNOWN(false);
	}
	//
	// If i-th argument to current operator has a previous operator,
	// this is the i-th argument for previous operator.
	// Otherwise, it is the i-th argument for the current operator
	// (if a previous variable exists)
	addr_t arg_match[2];
	for(size_t j = 0; j < num_arg; ++j)
	{	arg_match[j] = arg[j];
		if( variable[j] )
		{	size_t previous = op_info[ var2op[arg[j]] ].previous;
			if( previous != 0 )
			{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
				//
				arg_match[j] = op_info[previous].i_var;
			}
		}
	}
	size_t code = optimize_hash_code(op, num_arg, arg_match);
	//
	// iterator for the set with this hash code
	sparse_list_const_iterator itr(hash_table_op, code);
	//
	// check for a match
	size_t count = 0;
	while( *itr != num_op )
	{	++count;
		//
		// candidate previous for current operator
		size_t  candidate  = *itr;
		CPPAD_ASSERT_UNKNOWN( candidate < current );
		CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
		//
		// check for a match
		bool match = op == op_info[candidate].op;
		if( match )
		{	for(size_t j = 0; j < num_arg; j++)
			{	if( variable[j] )
				{	size_t previous =
						op_info[ var2op[op_info[candidate].arg[j]] ].previous;
					if( previous != 0 )
					{	CPPAD_ASSERT_UNKNOWN(op_info[previous].previous == 0);
						//
						match &=
							arg_match[j] == addr_t( op_info[previous].i_var );
					}
					else
						match &= arg_match[j] == op_info[candidate].arg[j];
				}
			}
		}
		if( match )
		{	op_info[current].previous = candidate;
			return;
		}
		++itr;
	}

	// special case where operator is commutative
	if( (op == AddvvOp) | (op == MulvvOp ) )
	{	CPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );
		std::swap( arg_match[0], arg_match[1] );
		//
		code      = optimize_hash_code(op, num_arg, arg_match);
		sparse_list_const_iterator itr_swap(hash_table_op, code);
		while( *itr_swap != num_op )
		{
			size_t candidate  = *itr_swap;
			CPPAD_ASSERT_UNKNOWN( candidate < current );
			CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
			//
			bool match = op == op_info[candidate].op;
			if( match )
			{	for(size_t j = 0; j < num_arg; j++)
				{	CPPAD_ASSERT_UNKNOWN( variable[j] )
					size_t previous =
						op_info[ var2op[op_info[candidate].arg[j]] ].previous;
					if( previous != 0 )
					{	CPPAD_ASSERT_UNKNOWN(op_info[previous].previous == 0);
						//
						match &=
							arg_match[j] == addr_t( op_info[previous].i_var );
					}
					else
						match &= arg_match[j] == op_info[candidate].arg[j];
				}
			}
			if( match )
			{	op_info[current].previous = candidate;
				return;
			}
			++itr_swap;
		}
	}
	CPPAD_ASSERT_UNKNOWN( count < 11 );
	if( count == 10 )
	{	// restart the list
		hash_table_op.clear(code);
	}
	// no match was found, add this operator the the set for this hash code
	hash_table_op.add_element(code, current);
}

} } } // END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE

# endif
<commit_msg>match_op.hpp: fix a conversion warning.<commit_after># ifndef CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
# define CPPAD_LOCAL_OPTIMIZE_MATCH_OP_HPP
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-17 Bradley M. Bell

CppAD is distributed under multiple licenses. This distribution is under
the terms of the
                    Eclipse Public License Version 1.0.

A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
# include <cppad/local/optimize/hash_code.hpp>
/*!
\file match_op.hpp
Check if current operator matches a previous operator.
*/
// BEGIN_CPPAD_LOCAL_OPTIMIZE_NAMESPACE
namespace CppAD { namespace local { namespace optimize  {
/*!
Search for a previous operator that matches the current one.

If an argument for the current operator is a variable,
and the argument has previous match,
the previous match for the argument is used when checking for a match
for the current operator.

\param var2op
mapping from variable index to operator index.

\param op_info
Mapping from operator index to operator information.
The input value of op_info[current].previous is assumed to be zero.
If a match if found,
the output value of op_info[current].previous is set to the
matching operator index, otherwise it is left as is.
Note that op_info[current].previous < current.

\param current
is the index of the current operator which must be an unary
or binary operator. Note that NumArg(ErfOp) == 3 but it is effectivey
a unary operator and is allowed otherwise NumArg( op_info[current].op) < 3.
It is assumed that hash_table_op is initialized as a vector of emtpy
sets. After this initialization, the value of current inceases with
each call to match_op.

\li
This must be a unary or binary
operator; hence, NumArg( op_info[current].op ) is one or two.
There is one exception, NumRes( ErfOp ) == 3, but arg[0]
is the only true arguments (the others are always the same).

\li
This must not be a VecAD load or store operation; i.e.,
LtpvOp, LtvpOp, LtvvOp, StppOp, StpvOp, StvpOp, StvvOp.
It also must not be an independent variable operator InvOp.

\param hash_table_op
is a vector of sets,
hash_table_op.n_set() == CPPAD_HASH_TABLE_SIZE and
hash_table_op.end() == op_info.size().
If i_op is an element of set[j],
then the operation op_info[i_op] has hash code j,
and op_info[i_op] does not match any other element of set[j].
An entry will be added each time match_op is called
and a match for the current operator is not found.
*/

inline void match_op(
	const vector<addr_t>&          var2op         ,
	vector<struct_op_info>&        op_info        ,
	size_t                         current        ,
	sparse_list&                   hash_table_op  )
{	size_t num_op = op_info.size();
	//
	CPPAD_ASSERT_UNKNOWN( op_info[current].previous == 0 );
	CPPAD_ASSERT_UNKNOWN(
		hash_table_op.n_set() == CPPAD_HASH_TABLE_SIZE
	);
	CPPAD_ASSERT_UNKNOWN( hash_table_op.end() == num_op );
	CPPAD_ASSERT_UNKNOWN( current < num_op );
	//
	// current operator
	OpCode        op         = op_info[current].op;
	const addr_t* arg        = op_info[current].arg;
	//
	// which arguments are variable
	size_t num_arg = NumArg(op);
	//
	bool   variable[2];
	variable[0] = false;
	variable[1] = false;
	switch(op)
	{	//
		case ErfOp:
		num_arg = 1; // other arugments are always the same
		//
		case AbsOp:
		case AcosOp:
		case AcoshOp:
		case AsinOp:
		case AsinhOp:
		case AtanOp:
		case AtanhOp:
		case CosOp:
		case CoshOp:
		case ExpOp:
		case Expm1Op:
		case LogOp:
		case Log1pOp:
		case SignOp:
		case SinOp:
		case SinhOp:
		case SqrtOp:
		case TanOp:
		case TanhOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 1 );
		variable[0] = true;
		break;

		case AddpvOp:
		case DisOp:
		case DivpvOp:
		case EqpvOp:
		case LepvOp:
		case LtpvOp:
		case MulpvOp:
		case NepvOp:
		case PowpvOp:
		case SubpvOp:
		case ZmulpvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[1] = true;
		break;

		case DivvpOp:
		case LevpOp:
		case LtvpOp:
		case PowvpOp:
		case SubvpOp:
		case ZmulvpOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		break;

		case AddvvOp:
		case DivvvOp:
		case EqvvOp:
		case LevvOp:
		case LtvvOp:
		case MulvvOp:
		case NevvOp:
		case PowvvOp:
		case SubvvOp:
		case ZmulvvOp:
		CPPAD_ASSERT_UNKNOWN( num_arg == 2 );
		variable[0] = true;
		variable[1] = true;
		break;

		default:
		CPPAD_ASSERT_UNKNOWN(false);
	}
	//
	// If i-th argument to current operator has a previous operator,
	// this is the i-th argument for previous operator.
	// Otherwise, it is the i-th argument for the current operator
	// (if a previous variable exists)
	addr_t arg_match[2];
	for(size_t j = 0; j < num_arg; ++j)
	{	arg_match[j] = arg[j];
		if( variable[j] )
		{	size_t previous = op_info[ var2op[arg[j]] ].previous;
			if( previous != 0 )
			{	CPPAD_ASSERT_UNKNOWN( op_info[previous].previous == 0 );
				//
				arg_match[j] = op_info[previous].i_var;
			}
		}
	}
	size_t code = optimize_hash_code(op, num_arg, arg_match);
	//
	// iterator for the set with this hash code
	sparse_list_const_iterator itr(hash_table_op, code);
	//
	// check for a match
	size_t count = 0;
	while( *itr != num_op )
	{	++count;
		//
		// candidate previous for current operator
		size_t  candidate  = *itr;
		CPPAD_ASSERT_UNKNOWN( candidate < current );
		CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
		//
		// check for a match
		bool match = op == op_info[candidate].op;
		if( match )
		{	for(size_t j = 0; j < num_arg; j++)
			{	if( variable[j] )
				{	size_t previous =
						op_info[ var2op[op_info[candidate].arg[j]] ].previous;
					if( previous != 0 )
					{	CPPAD_ASSERT_UNKNOWN(op_info[previous].previous == 0);
						//
						match &=
							arg_match[j] == addr_t( op_info[previous].i_var );
					}
					else
						match &= arg_match[j] == op_info[candidate].arg[j];
				}
			}
		}
		if( match )
		{	op_info[current].previous = static_cast<addr_t>( candidate );
			return;
		}
		++itr;
	}

	// special case where operator is commutative
	if( (op == AddvvOp) | (op == MulvvOp ) )
	{	CPPAD_ASSERT_UNKNOWN( NumArg(op) == 2 );
		std::swap( arg_match[0], arg_match[1] );
		//
		code      = optimize_hash_code(op, num_arg, arg_match);
		sparse_list_const_iterator itr_swap(hash_table_op, code);
		while( *itr_swap != num_op )
		{
			size_t candidate  = *itr_swap;
			CPPAD_ASSERT_UNKNOWN( candidate < current );
			CPPAD_ASSERT_UNKNOWN( op_info[candidate].previous == 0 );
			//
			bool match = op == op_info[candidate].op;
			if( match )
			{	for(size_t j = 0; j < num_arg; j++)
				{	CPPAD_ASSERT_UNKNOWN( variable[j] )
					size_t previous =
						op_info[ var2op[op_info[candidate].arg[j]] ].previous;
					if( previous != 0 )
					{	CPPAD_ASSERT_UNKNOWN(op_info[previous].previous == 0);
						//
						match &=
							arg_match[j] == addr_t( op_info[previous].i_var );
					}
					else
						match &= arg_match[j] == op_info[candidate].arg[j];
				}
			}
			if( match )
			{	op_info[current].previous = static_cast<addr_t>( candidate );
				return;
			}
			++itr_swap;
		}
	}
	CPPAD_ASSERT_UNKNOWN( count < 11 );
	if( count == 10 )
	{	// restart the list
		hash_table_op.clear(code);
	}
	// no match was found, add this operator the the set for this hash code
	hash_table_op.add_element(code, current);
}

} } } // END_CPPAD_LOCAL_OPTIMIZE_NAMESPACE

# endif
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include "hashtable.h"
#include <vespa/vespalib/util/array.hpp>
#include <algorithm>

namespace vespalib {

namespace {

/// TODO Currently we require that you have atleast one element in _nodes to avoid one extra branch
/// However that means that empty unused hashtables are larger than necessary.
/// This we should probably reconsider.
template<typename Modulator>
uint32_t
computeModulo(size_t size) {
    return (size > 0) ? Modulator::selectHashTableSize(roundUp2inN(size) / 3) : 1;
}

template <typename NodeStore>
NodeStore
createStore(size_t size, uint32_t modulo) {
    size = (size > 0) ? roundUp2inN(std::max(size_t(modulo), roundUp2inN(size))) : 1;
    NodeStore store;
    store.reserve(size);
    store.resize(modulo);
    return store;
}

}
template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::swap(hashtable & rhs)
{
    std::swap(_modulator, rhs._modulator);
    std::swap(_count, rhs._count);
    _nodes.swap(rhs._nodes);
    std::swap(_hasher, rhs._hasher);
    std::swap(_equal, rhs._equal);
    std::swap(_keyExtractor, rhs._keyExtractor);
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::hashtable(size_t reservedSpace) :
    _modulator(computeModulo<Modulator>(reservedSpace)),
    _count(0),
    _nodes(createStore<NodeStore>(reservedSpace, _modulator.getTableSize()))
{ }

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::hashtable(size_t reservedSpace, const Hash & hasher, const Equal & equal) :
    _modulator(computeModulo<Modulator>(reservedSpace)),
    _count(0),
    _nodes(createStore<NodeStore>(reservedSpace, _modulator.getTableSize())),
    _hasher(hasher),
    _equal(equal)
{
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::hashtable(const hashtable &) = default;

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator> &
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::operator = (const hashtable &) = default;

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::~hashtable() = default;

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const Key & key)
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::const_iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const Key & key) const
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return const_iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template< typename AltKey>
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const AltKey & key)
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template< typename AltKey>
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::const_iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const AltKey & key) const
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return const_iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::erase(const Key & key) {
    const_iterator found(find(key));
    if (found != end()) {
        DefaultMoveHandler moveHandler;
        erase(moveHandler, hash(key), found);
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::clear() {
    _nodes.clear();
    resize(getTableSize());
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template< typename V >
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::insert_result
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::insertInternal(V && node)
{
    const next_t h = hash(_keyExtractor(node));
    if ( ! _nodes[h].valid() ) {
        _nodes[h] = std::forward<V>(node);
        _count++;
        return insert_result(iterator(this, h), true);
    } else if (_nodes.size() <= _nodes.capacity()) {
        for (next_t c(h); c != Node::npos; c = _nodes[c].getNext()) {
            if (_equal(_keyExtractor(_nodes[c].getValue()), _keyExtractor(node))) {
                return insert_result(iterator(this, c), false);
            }
        }
        if (_nodes.size() < _nodes.capacity()) {
            const next_t p(_nodes[h].getNext());
            const next_t newIdx(_nodes.size());
            _nodes[h].setNext(newIdx);
            new (_nodes.push_back_fast()) Node(std::forward<V>(node), p);
            _count++;
            return insert_result(iterator(this, newIdx), true);
        } else {
            resize(_nodes.capacity()*2);
            return insertInternal(std::forward<V>(node));
        }
    } else {
        resize(_nodes.capacity()*2);
        return insertInternal(std::forward<V>(node));
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template<typename MoveHandler>
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::reclaim(MoveHandler & moveHandler, next_t node)
{
    size_t last(_nodes.size()-1);
    if (last >= getTableSize()) {
        if (last != node) {
            next_t h = hash(_keyExtractor(_nodes[last].getValue()));
            for (next_t n(_nodes[h].getNext()); n != last; n=_nodes[h].getNext()) {
                h = n;
            }
            move(moveHandler, last, node);
            _nodes[h].setNext(node);
        }
        _nodes.resize(last);
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template <typename Func>
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::for_each(Func func) const
{
    uint32_t i(0);
    for (; i < _modulator.getTableSize(); i++) {
        if (_nodes[i].valid()) {
            func(_nodes[i].getValue());
        }
    }
    for (; i < _nodes.size(); i++) {
        func(_nodes[i].getValue());
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template <typename MoveHandler>
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::erase(MoveHandler & moveHandler, next_t h, const const_iterator & it)
{
    next_t prev = Node::npos;
    do {
        if (h == it.getInternalIndex()) {
            if (prev != Node::npos) {
                _nodes[prev].setNext(_nodes[h].getNext());
                reclaim(moveHandler, h);
            } else {
                if (_nodes[h].hasNext()) {
                    next_t next = _nodes[h].getNext();
                    move(moveHandler, next, h);
                    reclaim(moveHandler, next);
                } else {
                    _nodes[h].invalidate();
                }
            }
            _count--;
            return;
        }
        prev = h;
        h = _nodes[h].getNext();
    } while (h != Node::npos);
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::resize(size_t newSize)
{
    next_t newModulo = computeModulo<Modulator>(newSize);
    NodeStore newStore = createStore<NodeStore>(newSize, newModulo);
    _modulator = Modulator(newModulo);
    _count = 0;
    _nodes.swap(newStore);
    move(std::move(newStore));
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::move(NodeStore && oldStore)
{
    for (auto & entry : oldStore) {
        if (entry.valid()) {
            insert(std::move(entry.getValue()));
        }
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
size_t
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::getMemoryConsumption() const
{
    return sizeof(hashtable<Key, Value, Hash, Equal, KeyExtract>)
            + _nodes.capacity() * sizeof(Node);
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
size_t
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::getMemoryUsed() const
{
    return sizeof(hashtable<Key, Value, Hash, Equal, KeyExtract>)
            + _nodes.size() * sizeof(Node);
}

}

<commit_msg>avoid unneeded check<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once

#include "hashtable.h"
#include <vespa/vespalib/util/array.hpp>
#include <algorithm>

namespace vespalib {

namespace {

/// TODO Currently we require that you have atleast one element in _nodes to avoid one extra branch
/// However that means that empty unused hashtables are larger than necessary.
/// This we should probably reconsider.
template<typename Modulator>
uint32_t
computeModulo(size_t size) {
    return (size > 0) ? Modulator::selectHashTableSize(roundUp2inN(size) / 3) : 1;
}

template <typename NodeStore>
NodeStore
createStore(size_t size, uint32_t modulo) {
    size = (size > 0) ? roundUp2inN(std::max(size_t(modulo), roundUp2inN(size))) : 1;
    NodeStore store;
    store.reserve(size);
    store.resize(modulo);
    return store;
}

}
template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::swap(hashtable & rhs)
{
    std::swap(_modulator, rhs._modulator);
    std::swap(_count, rhs._count);
    _nodes.swap(rhs._nodes);
    std::swap(_hasher, rhs._hasher);
    std::swap(_equal, rhs._equal);
    std::swap(_keyExtractor, rhs._keyExtractor);
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::hashtable(size_t reservedSpace) :
    _modulator(computeModulo<Modulator>(reservedSpace)),
    _count(0),
    _nodes(createStore<NodeStore>(reservedSpace, _modulator.getTableSize()))
{ }

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::hashtable(size_t reservedSpace, const Hash & hasher, const Equal & equal) :
    _modulator(computeModulo<Modulator>(reservedSpace)),
    _count(0),
    _nodes(createStore<NodeStore>(reservedSpace, _modulator.getTableSize())),
    _hasher(hasher),
    _equal(equal)
{
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::hashtable(const hashtable &) = default;

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator> &
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::operator = (const hashtable &) = default;

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::~hashtable() = default;

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const Key & key)
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::const_iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const Key & key) const
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return const_iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template< typename AltKey>
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const AltKey & key)
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template< typename AltKey>
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::const_iterator
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::find(const AltKey & key) const
{
    next_t h = hash(key);
    if (__builtin_expect(_nodes[h].valid(), true)) {
        do {
            if (__builtin_expect(_equal(_keyExtractor(_nodes[h].getValue()), key), true)) {
                return const_iterator(this, h);
            }
            h = _nodes[h].getNext();
        } while (h != Node::npos);
    }
    return end();
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::erase(const Key & key) {
    const_iterator found(find(key));
    if (found != end()) {
        DefaultMoveHandler moveHandler;
        erase(moveHandler, hash(key), found);
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::clear() {
    _nodes.clear();
    resize(getTableSize());
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template< typename V >
typename hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::insert_result
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::insertInternal(V && node)
{
    const next_t h = hash(_keyExtractor(node));
    if ( ! _nodes[h].valid() ) {
        _nodes[h] = std::forward<V>(node);
        _count++;
        return insert_result(iterator(this, h), true);
    } else {
        for (next_t c(h); c != Node::npos; c = _nodes[c].getNext()) {
            if (_equal(_keyExtractor(_nodes[c].getValue()), _keyExtractor(node))) {
                return insert_result(iterator(this, c), false);
            }
        }
        if (_nodes.size() < _nodes.capacity()) {
            const next_t p(_nodes[h].getNext());
            const next_t newIdx(_nodes.size());
            _nodes[h].setNext(newIdx);
            new (_nodes.push_back_fast()) Node(std::forward<V>(node), p);
            _count++;
            return insert_result(iterator(this, newIdx), true);
        } else {
            resize(_nodes.capacity()*2);
            return insertInternal(std::forward<V>(node));
        }
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template<typename MoveHandler>
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::reclaim(MoveHandler & moveHandler, next_t node)
{
    size_t last(_nodes.size()-1);
    if (last >= getTableSize()) {
        if (last != node) {
            next_t h = hash(_keyExtractor(_nodes[last].getValue()));
            for (next_t n(_nodes[h].getNext()); n != last; n=_nodes[h].getNext()) {
                h = n;
            }
            move(moveHandler, last, node);
            _nodes[h].setNext(node);
        }
        _nodes.resize(last);
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template <typename Func>
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::for_each(Func func) const
{
    uint32_t i(0);
    for (; i < _modulator.getTableSize(); i++) {
        if (_nodes[i].valid()) {
            func(_nodes[i].getValue());
        }
    }
    for (; i < _nodes.size(); i++) {
        func(_nodes[i].getValue());
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
template <typename MoveHandler>
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::erase(MoveHandler & moveHandler, next_t h, const const_iterator & it)
{
    next_t prev = Node::npos;
    do {
        if (h == it.getInternalIndex()) {
            if (prev != Node::npos) {
                _nodes[prev].setNext(_nodes[h].getNext());
                reclaim(moveHandler, h);
            } else {
                if (_nodes[h].hasNext()) {
                    next_t next = _nodes[h].getNext();
                    move(moveHandler, next, h);
                    reclaim(moveHandler, next);
                } else {
                    _nodes[h].invalidate();
                }
            }
            _count--;
            return;
        }
        prev = h;
        h = _nodes[h].getNext();
    } while (h != Node::npos);
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::resize(size_t newSize)
{
    next_t newModulo = computeModulo<Modulator>(newSize);
    NodeStore newStore = createStore<NodeStore>(newSize, newModulo);
    _modulator = Modulator(newModulo);
    _count = 0;
    _nodes.swap(newStore);
    move(std::move(newStore));
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
void
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::move(NodeStore && oldStore)
{
    for (auto & entry : oldStore) {
        if (entry.valid()) {
            insert(std::move(entry.getValue()));
        }
    }
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
size_t
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::getMemoryConsumption() const
{
    return sizeof(hashtable<Key, Value, Hash, Equal, KeyExtract>)
            + _nodes.capacity() * sizeof(Node);
}

template< typename Key, typename Value, typename Hash, typename Equal, typename KeyExtract, typename Modulator >
size_t
hashtable<Key, Value, Hash, Equal, KeyExtract, Modulator>::getMemoryUsed() const
{
    return sizeof(hashtable<Key, Value, Hash, Equal, KeyExtract>)
            + _nodes.size() * sizeof(Node);
}

}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: datwin.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 20:40: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 _SFXDATWIN_HXX
#define _SFXDATWIN_HXX

#ifndef _BRWBOX_HXX
#include <brwbox.hxx>
#endif

#ifndef _BRWHEAD_HXX
#include <brwhead.hxx>
#endif

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _IMAGE_HXX //autogen
#include <vcl/image.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _TRANSFER_HXX
#include "transfer.hxx"
#endif

//===================================================================

#define MIN_COLUMNWIDTH  2
#define DRAG_CRITICAL    4

DECLARE_LIST( RectangleList, Rectangle* )

//===================================================================

class ButtonFrame
{
    Rectangle   aRect;
    Rectangle   aInnerRect;
    String      aText;
    BOOL        bPressed;
    BOOL        bCurs;
    BOOL        bAbbr;
    BOOL        m_bDrawDisabled;

public:
               ButtonFrame( const Point& rPt, const Size& rSz,
                            const String &rText,
                            BOOL bPress = FALSE,
                            BOOL bCursor = FALSE,
                            BOOL bAbbreviate = TRUE,
                            BOOL _bDrawDisabled = FALSE)
                :aRect( rPt, rSz )
                ,aInnerRect( Point( aRect.Left()+1, aRect.Top()+1 ),
                            Size( aRect.GetWidth()-2, aRect.GetHeight()-2 ) )
                ,aText(rText)
                ,bPressed(bPress)
                ,bCurs(bCursor)
                ,bAbbr(bAbbreviate)
                ,m_bDrawDisabled(_bDrawDisabled)
            {
            }

    void    Draw( OutputDevice& rDev );
};

//===================================================================

class BrowserColumn
{
    USHORT              _nId;
    ULONG               _nOriginalWidth;
    ULONG               _nWidth;
    Image               _aImage;
    String              _aTitle;
    BOOL                _bFrozen;
    HeaderBarItemBits   _nFlags;

public:
                        BrowserColumn( USHORT nItemId, const Image &rImage,
                                        const String& rTitle, ULONG nWidthPixel, const Fraction& rCurrentZoom,
                                        HeaderBarItemBits nFlags );
    virtual            ~BrowserColumn();

    USHORT              GetId() const { return _nId; }

    ULONG               Width() { return _nWidth; }
    Image&              GetImage() { return _aImage; }
    String&             Title() { return _aTitle; }
    HeaderBarItemBits&  Flags() { return _nFlags; }

    BOOL                IsFrozen() const { return _bFrozen; }
    void                Freeze( BOOL bFreeze = TRUE ) { _bFrozen = bFreeze; }

    virtual void        Draw( BrowseBox& rBox, OutputDevice& rDev,
                              const Point& rPos, BOOL bCurs  );

    void                SetWidth(ULONG nNewWidthPixel, const Fraction& rCurrentZoom);
    void                ZoomChanged(const Fraction& rNewZoom);
};

//===================================================================

class BrowserDataWin
            :public Control
            ,public DragSourceHelper
            ,public DropTargetHelper
{
public:
    BrowserHeader*  pHeaderBar;     // only for BROWSER_HEADERBAR_NEW
    Window*         pEventWin;      // Window of forwarded events
    ScrollBarBox*   pCornerWin;     // Window in the corner btw the ScrollBars
    BOOL*           pDtorNotify;
    AutoTimer       aMouseTimer;    // recalls MouseMove on dragging out
    MouseEvent      aRepeatEvt;     // a MouseEvent to repeat
    Point           aLastMousePos;  // verhindert pseudo-MouseMoves

    String          aRealRowCount;  // zur Anzeige im VScrollBar

    RectangleList   aInvalidRegion; // invalidated Rectangles during !UpdateMode
    FASTBOOL        bInPaint;       // TRUE while in Paint
    FASTBOOL        bInCommand;     // TRUE while in Command
    FASTBOOL        bNoScrollBack;  // nur vorwaerts scrollen
    FASTBOOL        bNoHScroll;     // kein horizontaler Scrollbar
    FASTBOOL        bNoVScroll;     // no vertical scrollbar
    FASTBOOL        bAutoHScroll;   // autohide horizontaler Scrollbar
    FASTBOOL        bAutoVScroll;   // autohide horizontaler Scrollbar
    FASTBOOL        bUpdateMode;    // nicht SV-UpdateMode wegen Invalidate()
    FASTBOOL        bAutoSizeLastCol;// last column always fills up window
    FASTBOOL        bHighlightAuto; // new auto-highlight by SetFont() etc.
    FASTBOOL        bResizeOnPaint; // outstanding resize-event
    FASTBOOL        bUpdateOnUnlock;    // Update() while locked
    FASTBOOL        bInUpdateScrollbars;    // Rekursionsschutz
    FASTBOOL        bHadRecursion;          // Rekursion war aufgetreten
    FASTBOOL        bOwnDataChangedHdl;     // dont change colors in DataChanged
    FASTBOOL        bCallingDropCallback;   // we're in a callback to AcceptDrop or ExecuteDrop curently
    USHORT          nUpdateLock;    // lock count, dont call Control::Update()!
    short           nCursorHidden;  // new conuter for DoHide/ShowCursor

    long            m_nDragRowDividerLimit;
    long            m_nDragRowDividerOffset;

public:
                    BrowserDataWin( BrowseBox* pParent );
                    ~BrowserDataWin();

    virtual void    DataChanged( const DataChangedEvent& rDCEvt );
    virtual void    Paint( const Rectangle& rRect );
    virtual void    RequestHelp( const HelpEvent& rHEvt );
    virtual void    Command( const CommandEvent& rEvt );
    virtual void    MouseButtonDown( const MouseEvent& rEvt );
    virtual void    MouseMove( const MouseEvent& rEvt );
                    DECL_LINK( RepeatedMouseMove, void * );

    virtual void    MouseButtonUp( const MouseEvent& rEvt );
    virtual void    KeyInput( const KeyEvent& rEvt );
    virtual void    Tracking( const TrackingEvent& rTEvt );

    // DropTargetHelper overridables
    virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );

    // DragSourceHelper overridables
    virtual void    StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );

    BrowseEvent     CreateBrowseEvent( const Point& rPosPixel );
    void            Repaint();
    BrowseBox*      GetParent() const
                         { return (BrowseBox*) Window::GetParent(); }
    const String&   GetRealRowCount() const { return aRealRowCount; }

    void            SetUpdateMode( BOOL bMode );
    FASTBOOL        GetUpdateMode() const { return bUpdateMode; }
    void            EnterUpdateLock() { ++nUpdateLock; }
    void            LeaveUpdateLock();
    void            Update();
    void            DoOutstandingInvalidations();
    void            Invalidate( USHORT nFlags = 0 );
    void            Invalidate( const Rectangle& rRect, USHORT nFlags = 0 );
    void            Invalidate( const Region& rRegion, USHORT nFlags = 0 )
                    { Control::Invalidate( rRegion, nFlags ); }

protected:
    void            StartRowDividerDrag( const Point& _rStartPos );
    BOOL            ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent );
};

//-------------------------------------------------------------------

inline void BrowserDataWin::Repaint()
{
    if ( GetUpdateMode() )
        Update();
    Paint( Rectangle( Point(), GetOutputSizePixel() ) );
}

//===================================================================

class BrowserScrollBar: public ScrollBar
{
    ULONG           _nTip;
    ULONG           _nLastPos;
    BrowserDataWin* _pDataWin;

public:
                    BrowserScrollBar( Window* pParent, WinBits nStyle,
                                      BrowserDataWin *pDataWin )
                    :   ScrollBar( pParent, nStyle ),
                        _nTip( 0 ),
                        _nLastPos( ULONG_MAX ),
                        _pDataWin( pDataWin )
                    {}
                    //ScrollBar( Window* pParent, const ResId& rResId );

    virtual void    Tracking( const TrackingEvent& rTEvt );
    virtual void    EndScroll();
};

//===================================================================

void InitSettings_Impl( Window *pWin,
         BOOL bFont = TRUE, BOOL bForeground = TRUE, BOOL bBackground = TRUE );

//===================================================================

#ifdef DBG_MI

void DoLog_Impl( const BrowseBox *pThis, const char *pWhat, const char *pWho );
#define LOG(pThis,what,who) DoLog_Impl(pThis,what,who)

#else

#define LOG(pThis,what,who)

#endif

#endif

<commit_msg>INTEGRATION: CWS vgbugs07 (1.11.298); FILE MERGED 2007/06/04 13:31:25 vg 1.11.298.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: datwin.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 21:08:23 $
 *
 *  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 _SFXDATWIN_HXX
#define _SFXDATWIN_HXX

#ifndef _BRWBOX_HXX
#include <svtools/brwbox.hxx>
#endif

#ifndef _BRWHEAD_HXX
#include <svtools/brwhead.hxx>
#endif

#ifndef _TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _IMAGE_HXX //autogen
#include <vcl/image.hxx>
#endif
#ifndef _LIST_HXX //autogen
#include <tools/list.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

//===================================================================

#define MIN_COLUMNWIDTH  2
#define DRAG_CRITICAL    4

DECLARE_LIST( RectangleList, Rectangle* )

//===================================================================

class ButtonFrame
{
    Rectangle   aRect;
    Rectangle   aInnerRect;
    String      aText;
    BOOL        bPressed;
    BOOL        bCurs;
    BOOL        bAbbr;
    BOOL        m_bDrawDisabled;

public:
               ButtonFrame( const Point& rPt, const Size& rSz,
                            const String &rText,
                            BOOL bPress = FALSE,
                            BOOL bCursor = FALSE,
                            BOOL bAbbreviate = TRUE,
                            BOOL _bDrawDisabled = FALSE)
                :aRect( rPt, rSz )
                ,aInnerRect( Point( aRect.Left()+1, aRect.Top()+1 ),
                            Size( aRect.GetWidth()-2, aRect.GetHeight()-2 ) )
                ,aText(rText)
                ,bPressed(bPress)
                ,bCurs(bCursor)
                ,bAbbr(bAbbreviate)
                ,m_bDrawDisabled(_bDrawDisabled)
            {
            }

    void    Draw( OutputDevice& rDev );
};

//===================================================================

class BrowserColumn
{
    USHORT              _nId;
    ULONG               _nOriginalWidth;
    ULONG               _nWidth;
    Image               _aImage;
    String              _aTitle;
    BOOL                _bFrozen;
    HeaderBarItemBits   _nFlags;

public:
                        BrowserColumn( USHORT nItemId, const Image &rImage,
                                        const String& rTitle, ULONG nWidthPixel, const Fraction& rCurrentZoom,
                                        HeaderBarItemBits nFlags );
    virtual            ~BrowserColumn();

    USHORT              GetId() const { return _nId; }

    ULONG               Width() { return _nWidth; }
    Image&              GetImage() { return _aImage; }
    String&             Title() { return _aTitle; }
    HeaderBarItemBits&  Flags() { return _nFlags; }

    BOOL                IsFrozen() const { return _bFrozen; }
    void                Freeze( BOOL bFreeze = TRUE ) { _bFrozen = bFreeze; }

    virtual void        Draw( BrowseBox& rBox, OutputDevice& rDev,
                              const Point& rPos, BOOL bCurs  );

    void                SetWidth(ULONG nNewWidthPixel, const Fraction& rCurrentZoom);
    void                ZoomChanged(const Fraction& rNewZoom);
};

//===================================================================

class BrowserDataWin
            :public Control
            ,public DragSourceHelper
            ,public DropTargetHelper
{
public:
    BrowserHeader*  pHeaderBar;     // only for BROWSER_HEADERBAR_NEW
    Window*         pEventWin;      // Window of forwarded events
    ScrollBarBox*   pCornerWin;     // Window in the corner btw the ScrollBars
    BOOL*           pDtorNotify;
    AutoTimer       aMouseTimer;    // recalls MouseMove on dragging out
    MouseEvent      aRepeatEvt;     // a MouseEvent to repeat
    Point           aLastMousePos;  // verhindert pseudo-MouseMoves

    String          aRealRowCount;  // zur Anzeige im VScrollBar

    RectangleList   aInvalidRegion; // invalidated Rectangles during !UpdateMode
    FASTBOOL        bInPaint;       // TRUE while in Paint
    FASTBOOL        bInCommand;     // TRUE while in Command
    FASTBOOL        bNoScrollBack;  // nur vorwaerts scrollen
    FASTBOOL        bNoHScroll;     // kein horizontaler Scrollbar
    FASTBOOL        bNoVScroll;     // no vertical scrollbar
    FASTBOOL        bAutoHScroll;   // autohide horizontaler Scrollbar
    FASTBOOL        bAutoVScroll;   // autohide horizontaler Scrollbar
    FASTBOOL        bUpdateMode;    // nicht SV-UpdateMode wegen Invalidate()
    FASTBOOL        bAutoSizeLastCol;// last column always fills up window
    FASTBOOL        bHighlightAuto; // new auto-highlight by SetFont() etc.
    FASTBOOL        bResizeOnPaint; // outstanding resize-event
    FASTBOOL        bUpdateOnUnlock;    // Update() while locked
    FASTBOOL        bInUpdateScrollbars;    // Rekursionsschutz
    FASTBOOL        bHadRecursion;          // Rekursion war aufgetreten
    FASTBOOL        bOwnDataChangedHdl;     // dont change colors in DataChanged
    FASTBOOL        bCallingDropCallback;   // we're in a callback to AcceptDrop or ExecuteDrop curently
    USHORT          nUpdateLock;    // lock count, dont call Control::Update()!
    short           nCursorHidden;  // new conuter for DoHide/ShowCursor

    long            m_nDragRowDividerLimit;
    long            m_nDragRowDividerOffset;

public:
                    BrowserDataWin( BrowseBox* pParent );
                    ~BrowserDataWin();

    virtual void    DataChanged( const DataChangedEvent& rDCEvt );
    virtual void    Paint( const Rectangle& rRect );
    virtual void    RequestHelp( const HelpEvent& rHEvt );
    virtual void    Command( const CommandEvent& rEvt );
    virtual void    MouseButtonDown( const MouseEvent& rEvt );
    virtual void    MouseMove( const MouseEvent& rEvt );
                    DECL_LINK( RepeatedMouseMove, void * );

    virtual void    MouseButtonUp( const MouseEvent& rEvt );
    virtual void    KeyInput( const KeyEvent& rEvt );
    virtual void    Tracking( const TrackingEvent& rTEvt );

    // DropTargetHelper overridables
    virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt );

    // DragSourceHelper overridables
    virtual void    StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );

    BrowseEvent     CreateBrowseEvent( const Point& rPosPixel );
    void            Repaint();
    BrowseBox*      GetParent() const
                         { return (BrowseBox*) Window::GetParent(); }
    const String&   GetRealRowCount() const { return aRealRowCount; }

    void            SetUpdateMode( BOOL bMode );
    FASTBOOL        GetUpdateMode() const { return bUpdateMode; }
    void            EnterUpdateLock() { ++nUpdateLock; }
    void            LeaveUpdateLock();
    void            Update();
    void            DoOutstandingInvalidations();
    void            Invalidate( USHORT nFlags = 0 );
    void            Invalidate( const Rectangle& rRect, USHORT nFlags = 0 );
    void            Invalidate( const Region& rRegion, USHORT nFlags = 0 )
                    { Control::Invalidate( rRegion, nFlags ); }

protected:
    void            StartRowDividerDrag( const Point& _rStartPos );
    BOOL            ImplRowDividerHitTest( const BrowserMouseEvent& _rEvent );
};

//-------------------------------------------------------------------

inline void BrowserDataWin::Repaint()
{
    if ( GetUpdateMode() )
        Update();
    Paint( Rectangle( Point(), GetOutputSizePixel() ) );
}

//===================================================================

class BrowserScrollBar: public ScrollBar
{
    ULONG           _nTip;
    ULONG           _nLastPos;
    BrowserDataWin* _pDataWin;

public:
                    BrowserScrollBar( Window* pParent, WinBits nStyle,
                                      BrowserDataWin *pDataWin )
                    :   ScrollBar( pParent, nStyle ),
                        _nTip( 0 ),
                        _nLastPos( ULONG_MAX ),
                        _pDataWin( pDataWin )
                    {}
                    //ScrollBar( Window* pParent, const ResId& rResId );

    virtual void    Tracking( const TrackingEvent& rTEvt );
    virtual void    EndScroll();
};

//===================================================================

void InitSettings_Impl( Window *pWin,
         BOOL bFont = TRUE, BOOL bForeground = TRUE, BOOL bBackground = TRUE );

//===================================================================

#ifdef DBG_MI

void DoLog_Impl( const BrowseBox *pThis, const char *pWhat, const char *pWho );
#define LOG(pThis,what,who) DoLog_Impl(pThis,what,who)

#else

#define LOG(pThis,what,who)

#endif

#endif

<|endoftext|>


<commit_before>#ifndef _CUI_IMAPWND_HXX
#define _CUI_IMAPWND_HXX

#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_MENU_HXX //autogen
#include <vcl/menu.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _GOODIES_IMAPOBJ_HXX //autogen
#include <svtools/imapobj.hxx>
#endif
#ifndef _TRANSFER_HXX //autogen
#include <svtools/transfer.hxx>
#endif
#ifndef _IMAP_HXX //autogen
#include <svtools/imap.hxx>
#endif
#ifndef _SFXFRAME_HXX
#include <sfx2/frame.hxx>
#endif
#include <svtools/svmedit.hxx>

/*************************************************************************
|*
|*
|*
\************************************************************************/

class URLDlg : public ModalDialog
{
    FixedText           maFtURL;
    Edit                maEdtURL;
    FixedText           maFtTarget;
    ComboBox            maCbbTargets;
    FixedText           maFtName;
    Edit                maEdtName;
    FixedText           maFtAlternativeText;
    Edit                maEdtAlternativeText;
    FixedText           maFtDescription;
    MultiLineEdit       maEdtDescription;
    FixedLine           maFlURL;
    HelpButton          maBtnHelp;
    OKButton            maBtnOk;
    CancelButton        maBtnCancel;

public:

                        URLDlg( Window* pWindow,
                                const String& rURL, const String& rAlternativeText, const String& rDescription,
                                const String& rTarget, const String& rName,
                                TargetList& rTargetList );

    String              GetURL() const { return maEdtURL.GetText(); }
    String              GetAltText() const { return maEdtAlternativeText.GetText(); }
    String              GetDesc() const { return maEdtDescription.GetText(); }
    String              GetTarget() const { return maCbbTargets.GetText(); }
    String              GetName() const { return maEdtName.GetText(); }
};

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.4.368); FILE MERGED 2008/04/01 15:50:17 thb 1.4.368.1: #i85898# Stripping all external header guards<commit_after>#ifndef _CUI_IMAPWND_HXX
#define _CUI_IMAPWND_HXX

#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include <vcl/menu.hxx>
#include <svtools/itempool.hxx>
#include <svtools/imapobj.hxx>
#include <svtools/transfer.hxx>
#include <svtools/imap.hxx>
#include <sfx2/frame.hxx>
#include <svtools/svmedit.hxx>

/*************************************************************************
|*
|*
|*
\************************************************************************/

class URLDlg : public ModalDialog
{
    FixedText           maFtURL;
    Edit                maEdtURL;
    FixedText           maFtTarget;
    ComboBox            maCbbTargets;
    FixedText           maFtName;
    Edit                maEdtName;
    FixedText           maFtAlternativeText;
    Edit                maEdtAlternativeText;
    FixedText           maFtDescription;
    MultiLineEdit       maEdtDescription;
    FixedLine           maFlURL;
    HelpButton          maBtnHelp;
    OKButton            maBtnOk;
    CancelButton        maBtnCancel;

public:

                        URLDlg( Window* pWindow,
                                const String& rURL, const String& rAlternativeText, const String& rDescription,
                                const String& rTarget, const String& rName,
                                TargetList& rTargetList );

    String              GetURL() const { return maEdtURL.GetText(); }
    String              GetAltText() const { return maEdtAlternativeText.GetText(); }
    String              GetDesc() const { return maEdtDescription.GetText(); }
    String              GetTarget() const { return maCbbTargets.GetText(); }
    String              GetName() const { return maEdtName.GetText(); }
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unopolyhelper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:28:59 $
 *
 *  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 _SVX_UNOPOLYHELPER_HXX
#define _SVX_UNOPOLYHELPER_HXX

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

namespace com { namespace sun { namespace star { namespace drawing {
    struct PolyPolygonBezierCoords;
} } } }

class XPolygon;
class XPolyPolygon;

/** convert a drawing::PolyPolygonBezierCoords to a XPolygon
*/
void SvxConvertPolyPolygonBezierToXPolygon( const com::sun::star::drawing::PolyPolygonBezierCoords* pSourcePolyPolygon, XPolygon& rNewPolygon )
    throw( com::sun::star::lang::IllegalArgumentException );

/** convert a drawing::PolyPolygonBezierCoords to a XPolyPolygon
*/
void SvxConvertPolyPolygonBezierToXPolyPolygon( const com::sun::star::drawing::PolyPolygonBezierCoords* pSourcePolyPolygon, XPolyPolygon& rNewPolygon )
    throw( com::sun::star::lang::IllegalArgumentException );

/** convert a XPolygon to a drawing::PolyPolygonBezierCoords
*/
void SvxConvertXPolygonToPolyPolygonBezier( const XPolygon& rPolygon, com::sun::star::drawing::PolyPolygonBezierCoords& rRetval )
    throw();

void SvxPolyPolygonToPolyPolygonBezierCoords( const XPolyPolygon& rPolyPoly, com::sun::star::drawing::PolyPolygonBezierCoords& rRetval );

#endif

<commit_msg>INTEGRATION: CWS aw024 (1.3.506); FILE MERGED 2006/10/27 12:14:01 aw 1.3.506.5: #i39528# ::basegfx -> basegfx adaption 2005/09/18 04:20:30 aw 1.3.506.4: RESYNC: (1.3-1.4); FILE MERGED 2005/05/25 09:50:49 aw 1.3.506.3: #i39529# 2005/05/12 16:39:27 aw 1.3.506.2: #i39529# 2005/04/26 15:04:17 aw 1.3.506.1: #i39528#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unopolyhelper.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2006-11-14 13:28:12 $
 *
 *  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 _SVX_UNOPOLYHELPER_HXX
#define _SVX_UNOPOLYHELPER_HXX

#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif

namespace com { namespace sun { namespace star { namespace drawing {
    struct PolyPolygonBezierCoords;
} } } }

namespace basegfx {
    class B2DPolyPolygon;
}

/** convert a drawing::PolyPolygonBezierCoords to a B2DPolyPolygon
*/
basegfx::B2DPolyPolygon SvxConvertPolyPolygonBezierToB2DPolyPolygon( const com::sun::star::drawing::PolyPolygonBezierCoords* pSourcePolyPolygon)
    throw( com::sun::star::lang::IllegalArgumentException );

/** convert a B2DPolyPolygon to a drawing::PolyPolygonBezierCoords
*/
void SvxConvertB2DPolyPolygonToPolyPolygonBezier( const basegfx::B2DPolyPolygon& rPolyPoly, com::sun::star::drawing::PolyPolygonBezierCoords& rRetval );

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: crstrvl1.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 13:45:04 $
 *
 *  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 _CRSRSH_HXX
#include <crsrsh.hxx>
#endif
#ifndef _VISCRS_HXX
#include <viscrs.hxx>
#endif
#ifndef _CALLNK_HXX
#include <callnk.hxx>
#endif

FASTBOOL SwCrsrShell::IsStartWord() const
{
    return pCurCrsr->IsStartWord();
}
FASTBOOL SwCrsrShell::IsEndWord() const
{
    return pCurCrsr->IsEndWord();
}
FASTBOOL SwCrsrShell::IsInWord() const
{
    return pCurCrsr->IsInWord();
}

FASTBOOL SwCrsrShell::GoStartWord()
{
    return CallCrsrFN( &SwCursor::GoStartWord );
}
FASTBOOL SwCrsrShell::GoEndWord()
{
    return CallCrsrFN( &SwCursor::GoEndWord );
}
FASTBOOL SwCrsrShell::GoNextWord()
{
    return CallCrsrFN( &SwCursor::GoNextWord );
}
FASTBOOL SwCrsrShell::GoPrevWord()
{
    return CallCrsrFN( &SwCursor::GoPrevWord );
}
FASTBOOL SwCrsrShell::GoNextSentence()
{
    return CallCrsrFN( &SwCursor::GoNextSentence );
}
FASTBOOL SwCrsrShell::GoPrevSentence()
{
    return CallCrsrFN( &SwCursor::GoPrevSentence );
}

FASTBOOL SwCrsrShell::SelectWord( const Point* pPt )
{
    return pCurCrsr->SelectWord( pPt );
}

<commit_msg>INTEGRATION: CWS enhselect (1.2.622); FILE MERGED 2004/08/10 15:00:45 fme 1.2.622.1: #i32329# Enhanced table selection<commit_after>/*************************************************************************
 *
 *  $RCSfile: crstrvl1.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-09-09 09:13:10 $
 *
 *  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 _CRSRSH_HXX
#include <crsrsh.hxx>
#endif
#ifndef _VISCRS_HXX
#include <viscrs.hxx>
#endif
#ifndef _CALLNK_HXX
#include <callnk.hxx>
#endif

FASTBOOL SwCrsrShell::IsStartWord() const
{
    return pCurCrsr->IsStartWord();
}
FASTBOOL SwCrsrShell::IsEndWord() const
{
    return pCurCrsr->IsEndWord();
}
FASTBOOL SwCrsrShell::IsStartSentence() const
{
    return pCurCrsr->IsStartEndSentence( false );
}
FASTBOOL SwCrsrShell::IsEndSentence() const
{
    return pCurCrsr->IsStartEndSentence( true );
}
FASTBOOL SwCrsrShell::IsInWord() const
{
    return pCurCrsr->IsInWord();
}

FASTBOOL SwCrsrShell::GoStartWord()
{
    return CallCrsrFN( &SwCursor::GoStartWord );
}
FASTBOOL SwCrsrShell::GoEndWord()
{
    return CallCrsrFN( &SwCursor::GoEndWord );
}
FASTBOOL SwCrsrShell::GoNextWord()
{
    return CallCrsrFN( &SwCursor::GoNextWord );
}
FASTBOOL SwCrsrShell::GoPrevWord()
{
    return CallCrsrFN( &SwCursor::GoPrevWord );
}
FASTBOOL SwCrsrShell::GoNextSentence()
{
    return CallCrsrFN( &SwCursor::GoNextSentence );
}
FASTBOOL SwCrsrShell::GoPrevSentence()
{
    return CallCrsrFN( &SwCursor::GoPrevSentence );
}
FASTBOOL SwCrsrShell::GoStartSentence()
{
    return CallCrsrFN( &SwCursor::GoStartSentence );
}
FASTBOOL SwCrsrShell::GoEndSentence()
{
    return CallCrsrFN( &SwCursor::GoEndSentence );
}

FASTBOOL SwCrsrShell::SelectWord( const Point* pPt )
{
    return pCurCrsr->SelectWord( pPt );
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swacorr.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 21:27:34 $
 *
 *  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_sw.hxx"

#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SWACORR_HXX
#include <swacorr.hxx>
#endif
#ifndef _SWBLOCKS_HXX
#include <swblocks.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include "SwXMLTextBlocks.hxx"
#endif
#ifndef _SWSERROR_H
#include <swerror.h>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#include <sot/storage.hxx>

TYPEINIT1( SwAutoCorrect, SvxAutoCorrect );

    //  - return den Ersetzungstext (nur fuer SWG-Format, alle anderen
    //      koennen aus der Wortliste herausgeholt werden!)
    //      rShort ist der Stream-Name - gecryptet!

BOOL SwAutoCorrect::GetLongText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >& rStg, const String& rFileName, const String& rShort, String& rLong )
{
    ULONG nRet;
    if (rStg.is())
    {
        // mba: relative URLs don't make sense here
        SwXMLTextBlocks aBlk( rStg, rFileName );
        nRet = aBlk.GetText( rShort, rLong );
    }
    else
        ASSERT ( rStg.is(), "Someone passed SwAutoCorrect::GetLongText a dud storage!");
    return !IsError( nRet ) && rLong.Len();
}

    //  - Text mit Attributierung (kann nur der SWG - SWG-Format!)
    //      rShort ist der Stream-Name - gecryptet!
BOOL SwAutoCorrect::PutText( const com::sun::star::uno::Reference < com::sun::star::embed::XStorage >&  rStg, const String& rFileName, const String& rShort,
                            SfxObjectShell& rObjSh, String& rLong )
{
    if( !rObjSh.IsA( TYPE(SwDocShell) ) )
        return FALSE;

    SwDocShell& rDShell = (SwDocShell&)rObjSh;
    ULONG nRet = 0;

    // mba: relative URLs don't make sense here
    SwXMLTextBlocks aBlk( rStg, rFileName );
    SwDoc* pDoc = aBlk.GetDoc();

    nRet = aBlk.BeginPutDoc( rShort, rShort );
    if( !IsError( nRet ) )
    {
        ((SwEditShell*)rDShell.GetWrtShell())->_CopySelToDoc( pDoc );
        nRet = aBlk.PutDoc();
        aBlk.AddName ( rShort, rShort, FALSE );
        if( !IsError( nRet ) )
            nRet = aBlk.GetText( rShort, rLong );
    }
    return !IsError( nRet );
}

SwAutoCorrect::SwAutoCorrect( const SvxAutoCorrect& rACorr )
    : SvxAutoCorrect( rACorr )
{
    SwEditShell::SetAutoFmtFlags(&GetSwFlags());
}

SwAutoCorrect::~SwAutoCorrect()
{
}
<commit_msg>INTEGRATION: CWS swwarnings (1.10.222); FILE MERGED 2007/04/11 07:02:52 tl 1.10.222.2: #i69287# warning-free code 2007/03/09 16:07:24 fme 1.10.222.1: #i69287# Warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swacorr.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 09:09:09 $
 *
 *  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_sw.hxx"

#ifndef _URLOBJ_HXX //autogen
#include <tools/urlobj.hxx>
#endif
#ifndef _SWACORR_HXX
#include <swacorr.hxx>
#endif
#ifndef _SWBLOCKS_HXX
#include <swblocks.hxx>
#endif
#ifndef _SW_XMLTEXTBLOCKS_HXX
#include "SwXMLTextBlocks.hxx"
#endif
#ifndef _SWSERROR_H
#include <swerror.h>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _EDITSH_HXX
#include <editsh.hxx>
#endif
#include <sot/storage.hxx>

using namespace ::com::sun::star;

TYPEINIT1( SwAutoCorrect, SvxAutoCorrect );

    //  - return den Ersetzungstext (nur fuer SWG-Format, alle anderen
    //      koennen aus der Wortliste herausgeholt werden!)
    //      rShort ist der Stream-Name - gecryptet!

BOOL SwAutoCorrect::GetLongText( const uno::Reference < embed::XStorage >& rStg, const String& rFileName, const String& rShort, String& rLong )
{
    ULONG nRet = 0;
    if (rStg.is())
    {
        // mba: relative URLs don't make sense here
        SwXMLTextBlocks aBlk( rStg, rFileName );
        nRet = aBlk.GetText( rShort, rLong );
    }
    else
        ASSERT ( rStg.is(), "Someone passed SwAutoCorrect::GetLongText a dud storage!");
    return !IsError( nRet ) && rLong.Len();
}

    //  - Text mit Attributierung (kann nur der SWG - SWG-Format!)
    //      rShort ist der Stream-Name - gecryptet!
BOOL SwAutoCorrect::PutText( const uno::Reference < embed::XStorage >&  rStg, const String& rFileName, const String& rShort,
                            SfxObjectShell& rObjSh, String& rLong )
{
    if( !rObjSh.IsA( TYPE(SwDocShell) ) )
        return FALSE;

    SwDocShell& rDShell = (SwDocShell&)rObjSh;
    ULONG nRet = 0;

    // mba: relative URLs don't make sense here
    SwXMLTextBlocks aBlk( rStg, rFileName );
    SwDoc* pDoc = aBlk.GetDoc();

    nRet = aBlk.BeginPutDoc( rShort, rShort );
    if( !IsError( nRet ) )
    {
        ((SwEditShell*)rDShell.GetWrtShell())->_CopySelToDoc( pDoc );
        nRet = aBlk.PutDoc();
        aBlk.AddName ( rShort, rShort, FALSE );
        if( !IsError( nRet ) )
            nRet = aBlk.GetText( rShort, rLong );
    }
    return !IsError( nRet );
}

SwAutoCorrect::SwAutoCorrect( const SvxAutoCorrect& rACorr )
    : SvxAutoCorrect( rACorr )
{
    SwEditShell::SetAutoFmtFlags(&GetSwFlags());
}

SwAutoCorrect::~SwAutoCorrect()
{
}
<|endoftext|>


<commit_before>/*
The MIT License (MIT)
Copyright (c) 2015 University of Central Florida's Computer Software Engineering
Scalable & Secure Systems (CSE - S3) Lab
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <cstring>
#include <cstdio>
#include <iostream>

#include "../../include/util/libomdb.h"

/*****************************************************************
 * Helper functions
 *****************************************************************/
void deserializeResultColumnsAndTerminator(ResultMetaDataPacket* packet,
                                           const char* serializedPacket,
                                           uint index) {
  uint32_t col = 0;
  ResultColumn columns[MAX_NUM_COLUMNS];
  while (serializedPacket[index] != THE_TERMINATOR) {
    ResultColumn column;
    memcpy(column.name, &serializedPacket[index], COL_NAME_LEN);
    index += COL_NAME_LEN;
    uint16_t* type = new uint16_t;
    memcpy(type, &serializedPacket[index], sizeof(uint16_t));
    column.type = *type;
    delete(type);
    columns[col] = column;
    col++;
    index += (COL_NAME_LEN + sizeof(uint16_t));
  }

  //packet->columns = columns;
  memcpy(packet->columns, columns, sizeof(columns));
}

// Need to map to enums from strings.
CommandType mapStringToCommandType(char* type) {
  CommandType commandType = static_cast<CommandType>(type[0]);
  //CommandType commandType = static_cast<CommandType>(std::stoi(typeString));
  if (commandType == CommandType::DB_COMMAND || commandType == CommandType::SQL_STATEMENT) {
    return commandType;
  }

  return CommandType::INVALID_COMMAND;
}

PacketType mapStringToPacketType(char* type) {
  if (strcmp(type, "NONE") == 0) {
    return PacketType::NONE;
  } else if (strcmp(type, "COMMAND")) {
    return PacketType::COMMAND;
  } else if (strcmp(type, "RESULT_METADATA") == 0) {
    return PacketType::RESULT_METADATA;
  } else if (strcmp(type, "RESULT_DATA") == 0) {
    return PacketType::RESULT_DATA;
  }

  return PacketType::INVALID_PACKET;
}

ResultStatus mapStringToResultStatus(char* status) {
  if (strcmp(status, "OK")) {
    return ResultStatus::OK;
  } else if (strcmp(status, "ERROR_SYNTAX")) {
    return ResultStatus::ERROR_SYNTAX;
  }

  return ResultStatus::ERROR ;
}

/*****************************************************************
 * Serialization functions
 *****************************************************************/

char* SerializeCommandPacket(CommandPacket packet) {
  // Take command packet and turn into char*
  //char serializedCommandPacket[sizeof(packet)];
  char* serializedCommandPacket = new char[sizeof(packet)];
  memcpy(serializedCommandPacket, &packet, sizeof(packet));
  return serializedCommandPacket;
}

char* SerializeConnectionPacket(ConnectionPacket packet){
  //char serializedConnectionPacket[sizeof(packet)];
  char* serializedConnectionPacket = new char[sizeof(packet)];
  memcpy(serializedConnectionPacket, &packet, sizeof(packet));
  return serializedConnectionPacket;
}

char* SerializeResultMetaDataPacket(ResultMetaDataPacket packet){
  char* buffer = new (std::nothrow) char[sizeof(ResultMetaDataPacket)];
  if(buffer == nullptr) {
    printf("ERROR: Failed to allocate memory for packet buffer!\n");
    return nullptr;
  }

  memcpy(buffer, &packet, sizeof(ResultMetaDataPacket));
  return buffer;
}

char* SerializeResultPacket(ResultPacket packet){
  char* buffer = new (std::nothrow) char[sizeof(ResultPacket) + packet.resultSize];
  std::cout << "memcpying " << sizeof(ResultPacket) + packet.resultSize << std::endl;
  memcpy(buffer, &packet, (sizeof(ResultPacket) + packet.resultSize));
  return buffer;
}

/*****************************************************************
 * Deserialization functions
 *****************************************************************/

CommandPacket DeserializeCommandPacket(char* serializedPacket){
  CommandPacket commandPacket;
  char* type = new char[sizeof(CommandType)];
  memcpy(type, &serializedPacket[0], sizeof(CommandType));
  memcpy(commandPacket.message, &serializedPacket[1], DB_NAME_LEN);
  commandPacket.commandType = mapStringToCommandType(type);
  delete(type);
  return commandPacket;
}

ConnectionPacket DeserializeConnectionPacket(const char* serializedPacket){
  ConnectionPacket connectionPacket;
  char* type = new char[sizeof(ConnectionPacket)];
  memcpy(type, &serializedPacket[0], sizeof(uint8_t));
  memcpy(connectionPacket.name, &serializedPacket[1], DB_NAME_LEN);
  connectionPacket.type = mapStringToPacketType(type);
  delete(type);
  //connectionPacket.name[DB_NAME_LEN - 1] = 0; // I think neil said not necessary
  return connectionPacket;
}

ResultMetaDataPacket DeserializeResultMetaDataPacket(char* serializedPacket){
  ResultMetaDataPacket metaDataPacket;
  memcpy(&metaDataPacket, serializedPacket, sizeof(ResultMetaDataPacket));
  return metaDataPacket;
}

ResultPacket DeserializeResultPacket(char* serializedPacket){
//  ResultPacket resultPacket;
//  memcpy(resultPacket, serializedPacket, sizeof(ResultPacket));
//  return resultPacket;
}
<commit_msg>Some work on SerializeResultPacket Still not copying properly. Neil said he would work on this<commit_after>/*
The MIT License (MIT)
Copyright (c) 2015 University of Central Florida's Computer Software Engineering
Scalable & Secure Systems (CSE - S3) Lab
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <cstring>
#include <cstdio>
#include <iostream>

#include "../../include/util/libomdb.h"

/*****************************************************************
 * Helper functions
 *****************************************************************/
void deserializeResultColumnsAndTerminator(ResultMetaDataPacket* packet,
                                           const char* serializedPacket,
                                           uint index) {
  uint32_t col = 0;
  ResultColumn columns[MAX_NUM_COLUMNS];
  while (serializedPacket[index] != THE_TERMINATOR) {
    ResultColumn column;
    memcpy(column.name, &serializedPacket[index], COL_NAME_LEN);
    index += COL_NAME_LEN;
    uint16_t* type = new uint16_t;
    memcpy(type, &serializedPacket[index], sizeof(uint16_t));
    column.type = *type;
    delete(type);
    columns[col] = column;
    col++;
    index += (COL_NAME_LEN + sizeof(uint16_t));
  }

  //packet->columns = columns;
  memcpy(packet->columns, columns, sizeof(columns));
}

// Need to map to enums from strings.
CommandType mapStringToCommandType(char* type) {
  CommandType commandType = static_cast<CommandType>(type[0]);
  //CommandType commandType = static_cast<CommandType>(std::stoi(typeString));
  if (commandType == CommandType::DB_COMMAND || commandType == CommandType::SQL_STATEMENT) {
    return commandType;
  }

  return CommandType::INVALID_COMMAND;
}

PacketType mapStringToPacketType(char* type) {
  if (strcmp(type, "NONE") == 0) {
    return PacketType::NONE;
  } else if (strcmp(type, "COMMAND")) {
    return PacketType::COMMAND;
  } else if (strcmp(type, "RESULT_METADATA") == 0) {
    return PacketType::RESULT_METADATA;
  } else if (strcmp(type, "RESULT_DATA") == 0) {
    return PacketType::RESULT_DATA;
  }

  return PacketType::INVALID_PACKET;
}

ResultStatus mapStringToResultStatus(char* status) {
  if (strcmp(status, "OK")) {
    return ResultStatus::OK;
  } else if (strcmp(status, "ERROR_SYNTAX")) {
    return ResultStatus::ERROR_SYNTAX;
  }

  return ResultStatus::ERROR ;
}

/*****************************************************************
 * Serialization functions
 *****************************************************************/

char* SerializeCommandPacket(CommandPacket packet) {
  // Take command packet and turn into char*
  //char serializedCommandPacket[sizeof(packet)];
  char* serializedCommandPacket = new char[sizeof(packet)];
  memcpy(serializedCommandPacket, &packet, sizeof(packet));
  return serializedCommandPacket;
}

char* SerializeConnectionPacket(ConnectionPacket packet){
  //char serializedConnectionPacket[sizeof(packet)];
  char* serializedConnectionPacket = new char[sizeof(packet)];
  memcpy(serializedConnectionPacket, &packet, sizeof(packet));
  return serializedConnectionPacket;
}

char* SerializeResultMetaDataPacket(ResultMetaDataPacket packet){
  char* buffer = new (std::nothrow) char[sizeof(ResultMetaDataPacket)];
  if(buffer == nullptr) {
    printf("ERROR: Failed to allocate memory for packet buffer!\n");
    return nullptr;
  }

  memcpy(buffer, &packet, sizeof(ResultMetaDataPacket));
  return buffer;
}

char* SerializeResultPacket(ResultPacket packet){
  size_t size = 6 + packet.resultSize + 1;
  char* buffer = new (std::nothrow) char[size];
  memset(buffer, 0, size);
  memcpy(buffer, &packet, sizeof(char) * 5);
  memcpy(buffer + 5, &packet.data, packet.resultSize);
  buffer[size - 1] = THE_TERMINATOR;
  return buffer;
}

/*****************************************************************
 * Deserialization functions
 *****************************************************************/

CommandPacket DeserializeCommandPacket(char* serializedPacket){
  CommandPacket commandPacket;
  char* type = new char[sizeof(CommandType)];
  memcpy(type, &serializedPacket[0], sizeof(CommandType));
  memcpy(commandPacket.message, &serializedPacket[1], DB_NAME_LEN);
  commandPacket.commandType = mapStringToCommandType(type);
  delete(type);
  return commandPacket;
}

ConnectionPacket DeserializeConnectionPacket(const char* serializedPacket){
  ConnectionPacket connectionPacket;
  char* type = new char[sizeof(ConnectionPacket)];
  memcpy(type, &serializedPacket[0], sizeof(uint8_t));
  memcpy(connectionPacket.name, &serializedPacket[1], DB_NAME_LEN);
  connectionPacket.type = mapStringToPacketType(type);
  delete(type);
  //connectionPacket.name[DB_NAME_LEN - 1] = 0; // I think neil said not necessary
  return connectionPacket;
}

ResultMetaDataPacket DeserializeResultMetaDataPacket(char* serializedPacket){
  ResultMetaDataPacket metaDataPacket;
  memcpy(&metaDataPacket, serializedPacket, sizeof(ResultMetaDataPacket));
  return metaDataPacket;
}

ResultPacket DeserializeResultPacket(char* serializedPacket){
//  ResultPacket resultPacket;
//  memcpy(resultPacket, serializedPacket, sizeof(ResultPacket));
//  return resultPacket;
}
<|endoftext|>


<commit_before>#include "BmpFont.h"

#include "common/FileSystem.h"
#include "common/ByteBuffer.h"
#include "graphics/device/Device.h"

namespace gfx
{

BmpFont::BmpFont(device::Device & device, std::string const & bmpfFilename,
		std::string const & bmpFilename) :
	device(device),
	bmpFilename(bmpFilename),
	texture(device.loadTextureFromFile(bmpFilename, false, true)),
	frameCount(0),
	frameWidth(0),
	frameHeight(0),
	indexes(),
	charSizes()
{
	loadFontFile(bmpfFilename);
}

BmpFont::BmpFont(BmpFont const & other) :
	device(other.device),
	bmpFilename(other.bmpFilename),
	texture(device.grabTexture(bmpFilename)),
	frameCount(other.frameCount),
	frameWidth(other.frameWidth),
	frameHeight(other.frameHeight),
	indexes(other.indexes),
	charSizes(other.charSizes)
{}

BmpFont::~BmpFont()
{
	device.releaseTexture(bmpFilename);
}

void BmpFont::loadFontFile(std::string const & filename)
{
	if (!fs::checkFileExists(filename)) {
		throw std::runtime_error(
			std::string("Unable to load ") + filename + ": file does not exist");
	}

	ByteBuffer buffer(fs::getFileSize(filename));
	if (!fs::loadFile(filename, buffer)) {
		throw std::runtime_error(
			std::string("Unable to load ") + filename + ": io error");
	}

	try {
		buffer.readLine(); // skip header

		frameCount = buffer.readUint16();
		frameWidth = buffer.readUint16();
		frameHeight = buffer.readUint16();

		for (uint16_t i = 0; i < frameCount; ++i) {
			uint8_t character = buffer.readUint8();

			indexes[character] = i;
			charSizes[character] = buffer.readUint16();
		}
	} catch (std::runtime_error & e) {
		throw std::runtime_error(
			std::string("Unable to load ") + filename + ": data error");
	}
}

} // namespace gfx
<commit_msg>Fix compilation error for #1<commit_after>#include "BmpFont.h"

#include <stdexcept>

#include "common/FileSystem.h"
#include "common/ByteBuffer.h"
#include "graphics/device/Device.h"

namespace gfx
{

BmpFont::BmpFont(device::Device & device, std::string const & bmpfFilename,
		std::string const & bmpFilename) :
	device(device),
	bmpFilename(bmpFilename),
	texture(device.loadTextureFromFile(bmpFilename, false, true)),
	frameCount(0),
	frameWidth(0),
	frameHeight(0),
	indexes(),
	charSizes()
{
	loadFontFile(bmpfFilename);
}

BmpFont::BmpFont(BmpFont const & other) :
	device(other.device),
	bmpFilename(other.bmpFilename),
	texture(device.grabTexture(bmpFilename)),
	frameCount(other.frameCount),
	frameWidth(other.frameWidth),
	frameHeight(other.frameHeight),
	indexes(other.indexes),
	charSizes(other.charSizes)
{}

BmpFont::~BmpFont()
{
	device.releaseTexture(bmpFilename);
}

void BmpFont::loadFontFile(std::string const & filename)
{
	if (!fs::checkFileExists(filename)) {
		throw std::runtime_error(
			std::string("Unable to load ") + filename + ": file does not exist");
	}

	ByteBuffer buffer(fs::getFileSize(filename));
	if (!fs::loadFile(filename, buffer)) {
		throw std::runtime_error(
			std::string("Unable to load ") + filename + ": io error");
	}

	try {
		buffer.readLine(); // skip header

		frameCount = buffer.readUint16();
		frameWidth = buffer.readUint16();
		frameHeight = buffer.readUint16();

		for (uint16_t i = 0; i < frameCount; ++i) {
			uint8_t character = buffer.readUint8();

			indexes[character] = i;
			charSizes[character] = buffer.readUint16();
		}
	} catch (std::runtime_error & e) {
		throw std::runtime_error(
			std::string("Unable to load ") + filename + ": data error");
	}
}

} // namespace gfx
<|endoftext|>