//
// See the file LICENSE for redistribution information.
//
// Copyright (c) 2002-2003
//	Sleepycat Software.  All rights reserved.
//

static const char revid[] = "$Id: KeyStatistics.cpp,v 1.26 2003/05/23 18:24:34 merrells Exp $";

#include "dbxml_config.h"
#include "dbxml/XmlPortability.hpp"
#include "KeyStatistics.hpp"
#include "ScopedDbt.hpp"
#include "db_utils.h"

#include <sstream>

using namespace DbXml;

KeyStatistics::KeyStatistics()
{
	zero();
}

void KeyStatistics::zero()
{
	numIndexedKeys_ = 0;
	numUniqueKeys_ = 0;
	sumKeyValueSize_ = 0;
}

void KeyStatistics::add(const KeyStatistics& es)
{
	numIndexedKeys_ += es.numIndexedKeys_;
	numUniqueKeys_ += es.numUniqueKeys_;
	sumKeyValueSize_ += es.sumKeyValueSize_;
}

double KeyStatistics::averageKeyValueSize() const
{
	return (numIndexedKeys_ == 0 ? 0 : sumKeyValueSize_ / numIndexedKeys_);
}

void KeyStatistics::setThisFromDbt(const DbtOut &dbt, bool swap)
{
	*this = *(reinterpret_cast<KeyStatistics*>(dbt.get_data())); // copies the data
	if (swap) {
		M_32_SWAP(numIndexedKeys_);
		M_32_SWAP(numUniqueKeys_);
		M_32_SWAP(sumKeyValueSize_);
	}
}

void KeyStatistics::setDbtFromThis(DbtOut &dbt, bool swap) const
{
	dbt.set(this, sizeof(*this)); // copies the data
	if (swap) {
		unsigned long *p = reinterpret_cast<unsigned long*>(dbt.get_data());
		M_32_SWAP(*(p + 0));
		M_32_SWAP(*(p + 1));
		M_32_SWAP(*(p + 2));
	}
}

std::string KeyStatistics::asString() const
{
	std::ostringstream s;
	s << "indexed='" << numIndexedKeys_ << "' ";
	s << "unique='" << numUniqueKeys_ << "' ";
	s << "size='" << sumKeyValueSize_ << "'";
	return s.str();
}

std::ostream& DbXml::operator<<(std::ostream& s, const KeyStatistics &ks)
{
	s << ks.asString();
	return s;
}
