<commit_before>// BuildRegion.cpp
// Implements the BuildRegion class

#include "BuildRegion.h"

#include "InstModel.h"

#include "Timer.h"
#include "Logger.h"
#include "CycException.h"
#include "InputXML.h"

#include <list>
#include <sstream>

using namespace std;

/* --------------------
 * Comparison Functors
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool compare_order_times(PrototypeBuildOrder* o1, PrototypeBuildOrder* o2) {
  return (o1->first < o2->first); // sort by time
}

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

/* --------------------
 * BuildRegion Class Methods
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::init() {
  prototypeOrders_ = new PrototypeOrders();
  builders_ = new map<Model*, std::list<Model*>*>();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::init(xmlNodePtr cur) {
  LOG(LEV_DEBUG2, "breg") << "A Build Region is being initialized";
  // xml inits
  Model::init(cur); // name_ and model_impl_
  RegionModel::initAllowedFacilities(cur); // allowedFacilities_

  // get path to this model
  xmlNodePtr model_cur =
    XMLinput->get_xpath_element(cur,"model/BuildRegion");

  // populate orders for each prototype
  xmlNodeSetPtr prototype_nodes =
    XMLinput->get_xpath_elements(model_cur,"prototyperequirement");
  for (int i=0;i<prototype_nodes->nodeNr;i++){
    populateOrders(prototype_nodes->nodeTab[i]);
  }
  sortOrders();

  // parent_ and tick listener, model 'born'
  RegionModel::initSimInteraction(this);
  // children->setParent, requires init()
  RegionModel::initChildren(cur);

  // populate the list of builders
  populateBuilders();
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::copy(BuildRegion* src) {
  RegionModel::copy(src);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::print() {
  RegionModel::print();
  if ( builders_ == NULL || builders_->empty() ){
    LOG(LEV_DEBUG2, "breg") << name() << " has no builders (currently).";
  }
  else {
    LOG(LEV_DEBUG2, "breg") << name() << " has the following builders: " ;
    for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();
        mit != builders_->end(); mit++) {
      LOG(LEV_DEBUG2, "breg") << "  For prototype: " << mit->first->name();
      for(list<Model*>::iterator inst = mit->second->begin();
          inst != mit->second->end(); inst++) {
        LOG(LEV_DEBUG2, "breg") << "    * " << (*inst)->name();
      }
    }
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::populateOrders(xmlNodePtr cur) {
  // get prototype
  string name =
    (const char*)XMLinput->get_xpath_content(cur, "prototypename");
  Model* prototype = Model::getTemplateByName(name);

  // fill a set of orders with constructed orders
  PrototypeOrders* orders = new PrototypeOrders();

  // for each entry, get time and number and construct an order
  xmlNodeSetPtr entry_nodes =
    XMLinput->get_xpath_elements(cur,"demandschedule");
  string sTime, sNumber;
  int time, number;
  for (int i=0;i<entry_nodes->nodeNr;i++){
    // get data
    xmlNodePtr entry_node =
      XMLinput->get_xpath_element(entry_nodes->nodeTab[i],"entry");
    sTime = XMLinput->get_xpath_content(entry_node,"time");
    sNumber = XMLinput->get_xpath_content(entry_node,"number");
    time = strtol(sTime.c_str(),NULL,10);
    number = strtol(sNumber.c_str(),NULL,10);
    // construct
    PrototypeBuildOrder* order = new PrototypeBuildOrder();
    order = constructOrder(prototype,number,time);
    // fill
    orders->push_back(order);
  }
  populateOrders(orders);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrototypeBuildOrder*
BuildRegion::constructOrder(Model* prototype, int number, int time) {
  PrototypeDemand d(prototype,number);
  PrototypeBuildOrder* b = new PrototypeBuildOrder(time,d);
  return b;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::populateOrders(PrototypeOrders* orders) {
  for ( OrderIterator order = orders->begin();
        order != orders->end(); order++ ) {
    addOrder( (*order) );
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::sortOrders() {
  prototypeOrders_->sort(compare_order_times);
  // error if first order is before the current time
  if ( frontOrder()->first < TI->time() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " has sorted its orders, "
        << "and its first order has a timestamp PRECEDING the current "
        << "time.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::populateBuilders() {
  // if there are no children, yell
  if ( children_.empty() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " cannot populate its list"
        << " of builders because it has no children.";
    throw CycOverrideException(err.str());
  }

  // for each child
  for(vector<Model*>::iterator inst = children_.begin();
      inst != children_.end(); inst++) {
    // for each prototype of that child
    for(PrototypeIterator
          fac = (dynamic_cast<InstModel*>(*inst))->beginPrototype();
        fac != (dynamic_cast<InstModel*>(*inst))->endPrototype();
        fac++) {

      list<Model*>* builder_list;
      // if fac not in builders_
      if ( builders_->find( (*fac) ) == builders_->end() ) {
        builder_list = new list<Model*>();
        builder_list->push_back( (*inst) );
        builders_->
          insert( pair<Model*,list<Model*>*>( (*fac), builder_list) );
      }
      // if fac in builders_
      else {
        (*builders_)[(*fac)]->push_back( (*inst) );
      }

    }  // end prototypes
  } // end children

  // if there are no builders, yell
  if ( builders_->empty() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " has finished populating"
        << " its list of builders, but that list is empty.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::handleTick(int time) {
  // build something if an order has been placed
  if (!prototypeOrders_->empty()) {
    while (!prototypeOrders_->empty() && frontOrder()->first == time) {
      handlePrototypeOrder(frontOrder()->second);
      prototypeOrders_->pop_front();
    }
  }
  // After we finish building, call the normal handleTick for a region
  RegionModel::handleTick(time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::handlePrototypeOrder(PrototypeDemand order) {
  Model* prototype = order.first;
  int nTotal = order.second;
  for (int i = 0; i < nTotal; i++) {
    list<ModelIterator> bidders;
    getAvailableBuilders(prototype,bidders);
    Model* builder = selectBuilder(prototype,bidders);
    placeOrder(prototype,builder);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::getAvailableBuilders(Model* prototype,
                                       std::list<ModelIterator>& bidders) {
  for(ModelIterator child = (*builders_)[prototype]->begin();
      child != (*builders_)[prototype]->end();
      child++) {
    if ( (*child)->canBuild(prototype) ){
      bidders.push_back(child);
    }
  }
  // if there are no bidders, throw an error for now
  if ( bidders.empty() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " is attempting to build "
        << prototype->name() << " but none of its children are "
        << "available to build it.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* BuildRegion::selectBuilder(Model* prototype,
                                  std::list<ModelIterator>& bidders) {
  // highest bidder guaranteed to be front -- see header file
  ModelIterator builder = bidders.front();
  // move builder to end of list
  (*builders_)[prototype]->splice( (*builders_)[prototype]->end(),
                                   (*(*builders_)[prototype]), builder);
  return (*builder);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::placeOrder(Model* prototype, Model* builder) {
  // build functions must know who is placing the build order
  dynamic_cast<InstModel*>(builder)->build(prototype,this);
}

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

/* --------------------
 * Model Class Methods
 * --------------------
 */

extern "C" Model* constructBuildRegion() {
    return new BuildRegion();
}

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

<commit_msg>fixed an issue where BuildRegion only read one entry from the demand schedule.<commit_after>// BuildRegion.cpp
// Implements the BuildRegion class

#include "BuildRegion.h"

#include "InstModel.h"

#include "Timer.h"
#include "Logger.h"
#include "CycException.h"
#include "InputXML.h"

#include <list>
#include <sstream>

using namespace std;

/* --------------------
 * Comparison Functors
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
bool compare_order_times(PrototypeBuildOrder* o1, PrototypeBuildOrder* o2) {
  return (o1->first < o2->first); // sort by time
}

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

/* --------------------
 * BuildRegion Class Methods
 * --------------------
 */
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::init() {
  prototypeOrders_ = new PrototypeOrders();
  builders_ = new map<Model*, std::list<Model*>*>();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::init(xmlNodePtr cur) {
  LOG(LEV_DEBUG2, "breg") << "A Build Region is being initialized";
  // xml inits
  Model::init(cur); // name_ and model_impl_
  RegionModel::initAllowedFacilities(cur); // allowedFacilities_

  // get path to this model
  xmlNodePtr model_cur =
    XMLinput->get_xpath_element(cur,"model/BuildRegion");

  // populate orders for each prototype
  xmlNodeSetPtr prototype_nodes =
    XMLinput->get_xpath_elements(model_cur,"prototyperequirement");
  for (int i=0;i<prototype_nodes->nodeNr;i++){
    populateOrders(prototype_nodes->nodeTab[i]);
  }
  sortOrders();

  // parent_ and tick listener, model 'born'
  RegionModel::initSimInteraction(this);
  // children->setParent, requires init()
  RegionModel::initChildren(cur);

  // populate the list of builders
  populateBuilders();
};

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::copy(BuildRegion* src) {
  RegionModel::copy(src);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::print() {
  RegionModel::print();
  if ( builders_ == NULL || builders_->empty() ){
    LOG(LEV_DEBUG2, "breg") << name() << " has no builders (currently).";
  }
  else {
    LOG(LEV_DEBUG2, "breg") << name() << " has the following builders: " ;
    for(map<Model*, list<Model*>*>::iterator mit=builders_->begin();
        mit != builders_->end(); mit++) {
      LOG(LEV_DEBUG2, "breg") << "  For prototype: " << mit->first->name();
      for(list<Model*>::iterator inst = mit->second->begin();
          inst != mit->second->end(); inst++) {
        LOG(LEV_DEBUG2, "breg") << "    * " << (*inst)->name();
      }
    }
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::populateOrders(xmlNodePtr cur) {
  // get prototype
  string name =
    (const char*)XMLinput->get_xpath_content(cur, "prototypename");
  Model* prototype = Model::getTemplateByName(name);

  // fill a set of orders with constructed orders
  PrototypeOrders* orders = new PrototypeOrders();

  // for each entry, get time and number and construct an order
  xmlNodeSetPtr entry_nodes =
    XMLinput->get_xpath_elements(cur,"demandschedule/entry");
  string sTime, sNumber;
  int time, number;
  for (int i=0;i<entry_nodes->nodeNr;i++){
    // get data
    sTime = XMLinput->get_xpath_content(entry_nodes->nodeTab[i],"time");
    sNumber = XMLinput->get_xpath_content(entry_nodes->nodeTab[i],"number");
    time = strtol(sTime.c_str(),NULL,10);
    number = strtol(sNumber.c_str(),NULL,10);
    // construct
    PrototypeBuildOrder* order = new PrototypeBuildOrder();
    order = constructOrder(prototype,number,time);
    // fill
    orders->push_back(order);
  }
  populateOrders(orders);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrototypeBuildOrder*
BuildRegion::constructOrder(Model* prototype, int number, int time) {
  PrototypeDemand d(prototype,number);
  PrototypeBuildOrder* b = new PrototypeBuildOrder(time,d);
  return b;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::populateOrders(PrototypeOrders* orders) {
  for ( OrderIterator order = orders->begin();
        order != orders->end(); order++ ) {
    addOrder( (*order) );
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::sortOrders() {
  prototypeOrders_->sort(compare_order_times);
  // error if first order is before the current time
  if ( frontOrder()->first < TI->time() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " has sorted its orders, "
        << "and its first order has a timestamp PRECEDING the current "
        << "time.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::populateBuilders() {
  // if there are no children, yell
  if ( children_.empty() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " cannot populate its list"
        << " of builders because it has no children.";
    throw CycOverrideException(err.str());
  }

  // for each child
  for(vector<Model*>::iterator inst = children_.begin();
      inst != children_.end(); inst++) {
    // for each prototype of that child
    for(PrototypeIterator
          fac = (dynamic_cast<InstModel*>(*inst))->beginPrototype();
        fac != (dynamic_cast<InstModel*>(*inst))->endPrototype();
        fac++) {

      list<Model*>* builder_list;
      // if fac not in builders_
      if ( builders_->find( (*fac) ) == builders_->end() ) {
        builder_list = new list<Model*>();
        builder_list->push_back( (*inst) );
        builders_->
          insert( pair<Model*,list<Model*>*>( (*fac), builder_list) );
      }
      // if fac in builders_
      else {
        (*builders_)[(*fac)]->push_back( (*inst) );
      }

    }  // end prototypes
  } // end children

  // if there are no builders, yell
  if ( builders_->empty() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " has finished populating"
        << " its list of builders, but that list is empty.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::handleTick(int time) {
  // build something if an order has been placed
  if (!prototypeOrders_->empty()) {
    while (!prototypeOrders_->empty() && frontOrder()->first == time) {
      handlePrototypeOrder(frontOrder()->second);
      prototypeOrders_->pop_front();
    }
  }
  // After we finish building, call the normal handleTick for a region
  RegionModel::handleTick(time);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::handlePrototypeOrder(PrototypeDemand order) {
  Model* prototype = order.first;
  int nTotal = order.second;
  for (int i = 0; i < nTotal; i++) {
    list<ModelIterator> bidders;
    getAvailableBuilders(prototype,bidders);
    Model* builder = selectBuilder(prototype,bidders);
    placeOrder(prototype,builder);
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::getAvailableBuilders(Model* prototype,
                                       std::list<ModelIterator>& bidders) {
  for(ModelIterator child = (*builders_)[prototype]->begin();
      child != (*builders_)[prototype]->end();
      child++) {
    if ( (*child)->canBuild(prototype) ){
      bidders.push_back(child);
    }
  }
  // if there are no bidders, throw an error for now
  if ( bidders.empty() ) {
    stringstream err("");
    err << "BuildRegion " << this->name() << " is attempting to build "
        << prototype->name() << " but none of its children are "
        << "available to build it.";
    throw CycOverrideException(err.str());
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Model* BuildRegion::selectBuilder(Model* prototype,
                                  std::list<ModelIterator>& bidders) {
  // highest bidder guaranteed to be front -- see header file
  ModelIterator builder = bidders.front();
  // move builder to end of list
  (*builders_)[prototype]->splice( (*builders_)[prototype]->end(),
                                   (*(*builders_)[prototype]), builder);
  return (*builder);
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void BuildRegion::placeOrder(Model* prototype, Model* builder) {
  // build functions must know who is placing the build order
  dynamic_cast<InstModel*>(builder)->build(prototype,this);
}

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

/* --------------------
 * Model Class Methods
 * --------------------
 */

extern "C" Model* constructBuildRegion() {
    return new BuildRegion();
}

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

<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>

#include "Tools/Exception/exception.hpp"
#include "Tools/Algo/Bit_packer.hpp"
#include "Tools/Perf/hard_decision.h"

#include "Decoder_chase_naive.hpp"

using namespace aff3ct;
using namespace aff3ct::module;

template <typename B, typename R>
Decoder_chase_naive<B,R>
::Decoder_chase_naive(const int K, const int N, Encoder<B> &encoder, const uint32_t max_flips, const bool hamming,
                      const int n_frames)
: Decoder                        (K, N,          n_frames, 1),
  Decoder_maximum_likelihood<B,R>(K, N, encoder, n_frames   ),
  max_flips(max_flips),
  hamming(hamming),
  x_max(0),
  min_euclidean_dist(std::numeric_limits<float>::max()),
  min_hamming_dist(std::numeric_limits<uint32_t>::max())
{
	const std::string name = "Decoder_chase_naive";
	this->set_name(name);

	if (N > 64)
	{
		std::stringstream message;
		message << "'N' has to be smaller or equal to 64 ('N' = " << N << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	if (max_flips == 0)
	{
		std::stringstream message;
		message << "'max_flips' has to be bigger than 0 ('max_flips' = " << max_flips << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	// determine the maximum sequence 'x' of codeword bits
	if (N == 64)
		this->x_max = std::numeric_limits<uint64_t>::max();
	else
		this->x_max = ((uint64_t)1 << (uint64_t)(N)) -1;
}

template <typename B, typename R>
Decoder_chase_naive<B,R>
::~Decoder_chase_naive()
{
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_siho(const R *Y_N, B *V_K, const int frame_id)
{
	if (!this->encoder.is_sys())
	{
		std::stringstream message;
		message << "'encoder.is_sys()' has to be true.";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	this->_decode_siho_cw(Y_N, this->best_X_N.data(), frame_id);

	const auto &info_bits_pos = this->encoder.get_info_bits_pos();
	for (auto k = 0; k < this->K; k++)
		V_K[k] = this->best_X_N[info_bits_pos[k]];
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const int frame_id)
{
	tools::hard_decide(Y_N, this->hard_Y_N.data(), this->N);

	// compute Hamming distance instead of Euclidean distance
	if (hamming)
	{
		this->_decode_hiho_cw(this->hard_Y_N.data(), V_N, frame_id);
	}
	else
	{
		this->min_euclidean_dist = std::numeric_limits<float>::max();

		for (auto n_flips = 0; n_flips <= (int)this->max_flips; n_flips++)
		{
			if (n_flips == 0)
			{
				if (this->encoder.is_codeword(this->hard_Y_N.data()))
				{
					// compute the Euclidean distance between the input LLR and the current codeword
					auto cur_euclidean_dist = this->compute_euclidean_dist(this->hard_Y_N.data(), Y_N);

					// update the best codeword
					if (cur_euclidean_dist < this->min_euclidean_dist)
					{
						this->min_euclidean_dist = cur_euclidean_dist;
						std::copy(this->hard_Y_N.begin(), this->hard_Y_N.begin() + this->N, V_N);
					}
				}
			}
			else if (n_flips == 1)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
				{
					std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
					this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;

					if (this->encoder.is_codeword(this->X_N.data()))
					{
						// compute the Euclidean distance between the input LLR and the current codeword
						auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

						// update the best codeword
						if (cur_euclidean_dist < this->min_euclidean_dist)
						{
							this->min_euclidean_dist = cur_euclidean_dist;
							std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
						}
					}
				}
			}
			else if (n_flips == 2)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
					for (auto flip2_pos = flip1_pos +1; flip2_pos < this->N; flip2_pos++)
					{
						std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
						this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;
						this->X_N[flip2_pos] = this->X_N[flip2_pos] ? (B)0 : (B)1;

						if (this->encoder.is_codeword(this->X_N.data()))
						{
							// compute the Euclidean distance between the input LLR and the current codeword
							auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

							// update the best codeword
							if (cur_euclidean_dist < this->min_euclidean_dist)
							{
								this->min_euclidean_dist = cur_euclidean_dist;
								std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
							}
						}
					}
			}
			else if (n_flips == 3)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
					for (auto flip2_pos = flip1_pos +1; flip2_pos < this->N; flip2_pos++)
						for (auto flip3_pos = flip2_pos +1; flip3_pos < this->N; flip3_pos++)
						{
							std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
							this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;
							this->X_N[flip2_pos] = this->X_N[flip2_pos] ? (B)0 : (B)1;
							this->X_N[flip3_pos] = this->X_N[flip3_pos] ? (B)0 : (B)1;

							if (this->encoder.is_codeword(this->X_N.data()))
							{
								// compute the Euclidean distance between the input LLR and the current codeword
								auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

								// update the best codeword
								if (cur_euclidean_dist < this->min_euclidean_dist)
								{
									this->min_euclidean_dist = cur_euclidean_dist;
									std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
								}
							}
						}
			}
			else if (n_flips == 4)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
					for (auto flip2_pos = flip1_pos +1; flip2_pos < this->N; flip2_pos++)
						for (auto flip3_pos = flip2_pos +1; flip3_pos < this->N; flip3_pos++)
							for (auto flip4_pos = flip3_pos +1; flip4_pos < this->N; flip4_pos++)
							{
								std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
								this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;
								this->X_N[flip2_pos] = this->X_N[flip2_pos] ? (B)0 : (B)1;
								this->X_N[flip3_pos] = this->X_N[flip3_pos] ? (B)0 : (B)1;
								this->X_N[flip4_pos] = this->X_N[flip4_pos] ? (B)0 : (B)1;

								if (this->encoder.is_codeword(this->X_N.data()))
								{
									// compute the Euclidean distance between the input LLR and the current codeword
									auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

									// update the best codeword
									if (cur_euclidean_dist < this->min_euclidean_dist)
									{
										this->min_euclidean_dist = cur_euclidean_dist;
										std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
									}
								}
							}
			}
			else
			{
				std::stringstream message;
				message << "'max_flips' unsupported size ('max_flips' = " << max_flips << ").";
				throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
			}
		}
	}
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const int frame_id)
{
	throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const int frame_id)
{
	throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Decoder_chase_naive<B_8,Q_8>;
template class aff3ct::module::Decoder_chase_naive<B_16,Q_16>;
template class aff3ct::module::Decoder_chase_naive<B_32,Q_32>;
template class aff3ct::module::Decoder_chase_naive<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_chase_naive<B,Q>;
#endif
// ==================================================================================== explicit template instantiation<commit_msg>Simplify a little bit the Chase decoder.<commit_after>#include <chrono>
#include <iostream>

#include "Tools/Exception/exception.hpp"
#include "Tools/Algo/Bit_packer.hpp"
#include "Tools/Perf/hard_decision.h"

#include "Decoder_chase_naive.hpp"

using namespace aff3ct;
using namespace aff3ct::module;

template <typename B, typename R>
Decoder_chase_naive<B,R>
::Decoder_chase_naive(const int K, const int N, Encoder<B> &encoder, const uint32_t max_flips, const bool hamming,
                      const int n_frames)
: Decoder                        (K, N,          n_frames, 1),
  Decoder_maximum_likelihood<B,R>(K, N, encoder, n_frames   ),
  max_flips(max_flips),
  hamming(hamming),
  x_max(0),
  min_euclidean_dist(std::numeric_limits<float>::max()),
  min_hamming_dist(std::numeric_limits<uint32_t>::max())
{
	const std::string name = "Decoder_chase_naive";
	this->set_name(name);

	if (N > 64)
	{
		std::stringstream message;
		message << "'N' has to be smaller or equal to 64 ('N' = " << N << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	if (max_flips == 0)
	{
		std::stringstream message;
		message << "'max_flips' has to be bigger than 0 ('max_flips' = " << max_flips << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	// determine the maximum sequence 'x' of codeword bits
	if (N == 64)
		this->x_max = std::numeric_limits<uint64_t>::max();
	else
		this->x_max = ((uint64_t)1 << (uint64_t)(N)) -1;
}

template <typename B, typename R>
Decoder_chase_naive<B,R>
::~Decoder_chase_naive()
{
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_siho(const R *Y_N, B *V_K, const int frame_id)
{
	if (!this->encoder.is_sys())
	{
		std::stringstream message;
		message << "'encoder.is_sys()' has to be true.";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	this->_decode_siho_cw(Y_N, this->best_X_N.data(), frame_id);

	const auto &info_bits_pos = this->encoder.get_info_bits_pos();
	for (auto k = 0; k < this->K; k++)
		V_K[k] = this->best_X_N[info_bits_pos[k]];
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const int frame_id)
{
	tools::hard_decide(Y_N, this->hard_Y_N.data(), this->N);

	// compute Hamming distance instead of Euclidean distance
	if (hamming)
	{
		this->_decode_hiho_cw(this->hard_Y_N.data(), V_N, frame_id);
	}
	else
	{
		this->min_euclidean_dist = std::numeric_limits<float>::max();

		if (this->encoder.is_codeword(this->hard_Y_N.data()))
		{
			// compute the Euclidean distance between the input LLR and the current codeword
			auto cur_euclidean_dist = this->compute_euclidean_dist(this->hard_Y_N.data(), Y_N);

			// update the best codeword
			if (cur_euclidean_dist < this->min_euclidean_dist)
			{
				this->min_euclidean_dist = cur_euclidean_dist;
				std::copy(this->hard_Y_N.begin(), this->hard_Y_N.begin() + this->N, V_N);
			}
		}

		for (auto n_flips = 1; n_flips <= (int)this->max_flips; n_flips++)
		{
			if (n_flips == 1)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
				{
					std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
					this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;

					if (this->encoder.is_codeword(this->X_N.data()))
					{
						// compute the Euclidean distance between the input LLR and the current codeword
						auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

						// update the best codeword
						if (cur_euclidean_dist < this->min_euclidean_dist)
						{
							this->min_euclidean_dist = cur_euclidean_dist;
							std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
						}
					}
				}
			}
			else if (n_flips == 2)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
					for (auto flip2_pos = flip1_pos +1; flip2_pos < this->N; flip2_pos++)
					{
						std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
						this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;
						this->X_N[flip2_pos] = this->X_N[flip2_pos] ? (B)0 : (B)1;

						if (this->encoder.is_codeword(this->X_N.data()))
						{
							// compute the Euclidean distance between the input LLR and the current codeword
							auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

							// update the best codeword
							if (cur_euclidean_dist < this->min_euclidean_dist)
							{
								this->min_euclidean_dist = cur_euclidean_dist;
								std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
							}
						}
					}
			}
			else if (n_flips == 3)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
					for (auto flip2_pos = flip1_pos +1; flip2_pos < this->N; flip2_pos++)
						for (auto flip3_pos = flip2_pos +1; flip3_pos < this->N; flip3_pos++)
						{
							std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
							this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;
							this->X_N[flip2_pos] = this->X_N[flip2_pos] ? (B)0 : (B)1;
							this->X_N[flip3_pos] = this->X_N[flip3_pos] ? (B)0 : (B)1;

							if (this->encoder.is_codeword(this->X_N.data()))
							{
								// compute the Euclidean distance between the input LLR and the current codeword
								auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

								// update the best codeword
								if (cur_euclidean_dist < this->min_euclidean_dist)
								{
									this->min_euclidean_dist = cur_euclidean_dist;
									std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
								}
							}
						}
			}
			else if (n_flips == 4)
			{
				for (auto flip1_pos = 0; flip1_pos < this->N; flip1_pos++)
					for (auto flip2_pos = flip1_pos +1; flip2_pos < this->N; flip2_pos++)
						for (auto flip3_pos = flip2_pos +1; flip3_pos < this->N; flip3_pos++)
							for (auto flip4_pos = flip3_pos +1; flip4_pos < this->N; flip4_pos++)
							{
								std::copy(this->hard_Y_N.begin(), this->hard_Y_N.end(), this->X_N.begin());
								this->X_N[flip1_pos] = this->X_N[flip1_pos] ? (B)0 : (B)1;
								this->X_N[flip2_pos] = this->X_N[flip2_pos] ? (B)0 : (B)1;
								this->X_N[flip3_pos] = this->X_N[flip3_pos] ? (B)0 : (B)1;
								this->X_N[flip4_pos] = this->X_N[flip4_pos] ? (B)0 : (B)1;

								if (this->encoder.is_codeword(this->X_N.data()))
								{
									// compute the Euclidean distance between the input LLR and the current codeword
									auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

									// update the best codeword
									if (cur_euclidean_dist < this->min_euclidean_dist)
									{
										this->min_euclidean_dist = cur_euclidean_dist;
										std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
									}
								}
							}
			}
			else
			{
				std::stringstream message;
				message << "'max_flips' unsupported size ('max_flips' = " << max_flips << ").";
				throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
			}
		}
	}
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const int frame_id)
{
	throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
}

template <typename B, typename R>
void Decoder_chase_naive<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const int frame_id)
{
	throw tools::unimplemented_error(__FILE__, __LINE__, __func__);
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Decoder_chase_naive<B_8,Q_8>;
template class aff3ct::module::Decoder_chase_naive<B_16,Q_16>;
template class aff3ct::module::Decoder_chase_naive<B_32,Q_32>;
template class aff3ct::module::Decoder_chase_naive<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_chase_naive<B,Q>;
#endif
// ==================================================================================== explicit template instantiation<|endoftext|>


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

#include "content/common/gpu/client/context_provider_command_buffer.h"

#include "webkit/gpu/grcontext_for_webgraphicscontext3d.h"

namespace content {

class ContextProviderCommandBuffer::LostContextCallbackProxy
    : public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
 public:
  LostContextCallbackProxy(ContextProviderCommandBuffer* provider)
      : provider_(provider) {
    provider_->context3d_->setContextLostCallback(this);
  }

  virtual void onContextLost() {
    provider_->OnLostContext();
  }

 private:
  ContextProviderCommandBuffer* provider_;
};

class ContextProviderCommandBuffer::MemoryAllocationCallbackProxy
    : public WebKit::WebGraphicsContext3D::
          WebGraphicsMemoryAllocationChangedCallbackCHROMIUM {
 public:
  MemoryAllocationCallbackProxy(ContextProviderCommandBuffer* provider)
      : provider_(provider) {
    provider_->context3d_->setMemoryAllocationChangedCallbackCHROMIUM(this);
  }

  void onMemoryAllocationChanged(WebKit::WebGraphicsMemoryAllocation alloc) {
    provider_->OnMemoryAllocationChanged(!!alloc.gpuResourceSizeInBytes);
  }

 private:
  ContextProviderCommandBuffer* provider_;
};

ContextProviderCommandBuffer::ContextProviderCommandBuffer()
    : destroyed_(false) {
}

ContextProviderCommandBuffer::~ContextProviderCommandBuffer() {}

bool ContextProviderCommandBuffer::InitializeOnMainThread() {
  if (destroyed_)
    return false;
  if (context3d_)
    return true;

  context3d_ = CreateOffscreenContext3d().Pass();
  destroyed_ = !context3d_;
  return !!context3d_;
}

bool ContextProviderCommandBuffer::BindToCurrentThread() {
  if (lost_context_callback_proxy_)
    return true;

  bool result = context3d_->makeContextCurrent();
  lost_context_callback_proxy_.reset(new LostContextCallbackProxy(this));
  return result;
}

WebGraphicsContext3DCommandBufferImpl*
ContextProviderCommandBuffer::Context3d() {
  return context3d_.get();
}

class GrContext* ContextProviderCommandBuffer::GrContext() {
  if (gr_context_)
    return gr_context_->get();

  gr_context_.reset(
      new webkit::gpu::GrContextForWebGraphicsContext3D(context3d_.get()));
  memory_allocation_callback_proxy_.reset(
      new MemoryAllocationCallbackProxy(this));
  return gr_context_->get();
}

void ContextProviderCommandBuffer::VerifyContexts() {
  if (!destroyed_ && context3d_->isContextLost())
    OnLostContext();
}

void ContextProviderCommandBuffer::OnLostContext() {
  base::AutoLock lock(destroyed_lock_);
  destroyed_ = true;
}

bool ContextProviderCommandBuffer::DestroyedOnMainThread() {
  base::AutoLock lock(destroyed_lock_);
  return destroyed_;
}

void ContextProviderCommandBuffer::OnMemoryAllocationChanged(
    bool nonzero_allocation) {
  if (gr_context_)
    gr_context_->SetMemoryLimit(nonzero_allocation);
}

}  // namespace content
<commit_msg>Use explicit for 1-arg constructors.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/common/gpu/client/context_provider_command_buffer.h"

#include "webkit/gpu/grcontext_for_webgraphicscontext3d.h"

namespace content {

class ContextProviderCommandBuffer::LostContextCallbackProxy
    : public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
 public:
  explicit LostContextCallbackProxy(ContextProviderCommandBuffer* provider)
      : provider_(provider) {
    provider_->context3d_->setContextLostCallback(this);
  }

  virtual void onContextLost() {
    provider_->OnLostContext();
  }

 private:
  ContextProviderCommandBuffer* provider_;
};

class ContextProviderCommandBuffer::MemoryAllocationCallbackProxy
    : public WebKit::WebGraphicsContext3D::
          WebGraphicsMemoryAllocationChangedCallbackCHROMIUM {
 public:
  explicit MemoryAllocationCallbackProxy(ContextProviderCommandBuffer* provider)
      : provider_(provider) {
    provider_->context3d_->setMemoryAllocationChangedCallbackCHROMIUM(this);
  }

  void onMemoryAllocationChanged(WebKit::WebGraphicsMemoryAllocation alloc) {
    provider_->OnMemoryAllocationChanged(!!alloc.gpuResourceSizeInBytes);
  }

 private:
  ContextProviderCommandBuffer* provider_;
};

ContextProviderCommandBuffer::ContextProviderCommandBuffer()
    : destroyed_(false) {
}

ContextProviderCommandBuffer::~ContextProviderCommandBuffer() {}

bool ContextProviderCommandBuffer::InitializeOnMainThread() {
  if (destroyed_)
    return false;
  if (context3d_)
    return true;

  context3d_ = CreateOffscreenContext3d().Pass();
  destroyed_ = !context3d_;
  return !!context3d_;
}

bool ContextProviderCommandBuffer::BindToCurrentThread() {
  if (lost_context_callback_proxy_)
    return true;

  bool result = context3d_->makeContextCurrent();
  lost_context_callback_proxy_.reset(new LostContextCallbackProxy(this));
  return result;
}

WebGraphicsContext3DCommandBufferImpl*
ContextProviderCommandBuffer::Context3d() {
  return context3d_.get();
}

class GrContext* ContextProviderCommandBuffer::GrContext() {
  if (gr_context_)
    return gr_context_->get();

  gr_context_.reset(
      new webkit::gpu::GrContextForWebGraphicsContext3D(context3d_.get()));
  memory_allocation_callback_proxy_.reset(
      new MemoryAllocationCallbackProxy(this));
  return gr_context_->get();
}

void ContextProviderCommandBuffer::VerifyContexts() {
  if (!destroyed_ && context3d_->isContextLost())
    OnLostContext();
}

void ContextProviderCommandBuffer::OnLostContext() {
  base::AutoLock lock(destroyed_lock_);
  destroyed_ = true;
}

bool ContextProviderCommandBuffer::DestroyedOnMainThread() {
  base::AutoLock lock(destroyed_lock_);
  return destroyed_;
}

void ContextProviderCommandBuffer::OnMemoryAllocationChanged(
    bool nonzero_allocation) {
  if (gr_context_)
    gr_context_->SetMemoryLimit(nonzero_allocation);
}

}  // namespace content
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
// Copyright (c) 2015 Michael G. Brehm
//
// 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 "stdafx.h"
#include "Bitmap.h"

#pragma warning(push, 4)

//-----------------------------------------------------------------------------
// Bitmap Constructor
//
// Arguments:
//
//	bits		- Number of bits to define for a new, zero-initialized bitmap

Bitmap::Bitmap(uint32_t bits) : m_bitmap({ 0, nullptr })
{
	// Allocate a zero-initialized buffer for the bitmap off the process heap; the buffer size
	// must be a multiple of 32 bits for compatibility with the bitmap API
	m_bitmap.Buffer = reinterpret_cast<PULONG>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, align::up(bits, 32) >> 3));
	if(!m_bitmap.Buffer) throw Exception(E_OUTOFMEMORY);

	m_bitmap.SizeOfBitMap = bits;		// Bitmap was successfully allocated
}

//-----------------------------------------------------------------------------
// Bitmap Copy Constructor

Bitmap::Bitmap(const Bitmap& rhs) : m_bitmap({ 0, nullptr })
{
	// Determine the size of the referenced object's bitmap buffer, in bytes
	size_t size = align::up(rhs.m_bitmap.SizeOfBitMap, 32) >> 3;

	// Allocate a new heap buffer to contain the copy of the referenced object
	m_bitmap.Buffer = reinterpret_cast<PULONG>(HeapAlloc(GetProcessHeap(), 0, size));
	if(m_bitmap.Buffer == nullptr) throw Exception(E_OUTOFMEMORY);

	// Copy the bitmap bits and size from the referenced object
	memcpy(m_bitmap.Buffer, rhs.m_bitmap.Buffer, size);
	m_bitmap.SizeOfBitMap = rhs.m_bitmap.SizeOfBitMap;
}

//-----------------------------------------------------------------------------
// Bitmap Move Constructor

Bitmap::Bitmap(Bitmap&& rhs) : m_bitmap(rhs.m_bitmap)
{
	rhs.m_bitmap.Buffer = nullptr;
	rhs.m_bitmap.SizeOfBitMap = 0;
}

//-----------------------------------------------------------------------------
// Bitmap Destructor

Bitmap::~Bitmap()
{
	if(m_bitmap.Buffer) HeapFree(GetProcessHeap(), 0, m_bitmap.Buffer);
}

//-----------------------------------------------------------------------------
// Bitmap::operator=

Bitmap& Bitmap::operator=(const Bitmap& rhs)
{
	// Determine the size of the referenced object's bitmap buffer, in bytes
	size_t size = align::up(rhs.m_bitmap.SizeOfBitMap, 32) >> 3;

	// Reallocate the heap buffer to match the referenced object's buffer size
	void* newbuffer = HeapReAlloc(GetProcessHeap(), 0, m_bitmap.Buffer, size);
	if(newbuffer == nullptr) throw Exception(E_OUTOFMEMORY);

	// Copy the bits from the referenced object into the reallocated buffer
	memcpy(newbuffer, rhs.m_bitmap.Buffer, size);

	// Assign the updated buffer pointer and bitmap size information
	m_bitmap.Buffer = reinterpret_cast<PULONG>(newbuffer);
	m_bitmap.SizeOfBitMap = rhs.m_bitmap.SizeOfBitMap;

	return *this;
}

//-----------------------------------------------------------------------------
// Bitmap::operator[]

bool Bitmap::operator[](uint32_t bit) const
{
	return (bit < m_bitmap.SizeOfBitMap) ? NtApi::RtlTestBit(&m_bitmap, bit) == TRUE : false;
}

//-----------------------------------------------------------------------------
// Bitmap::AreBitsClear
//
// Determines if all bits in a range are clear
//
// Arguments:
//
//	startbit		- Bit to start the range check against
//	count			- Number of bits in the range to verify

bool Bitmap::AreBitsClear(uint32_t startbit, uint32_t count) const
{
	// Verify that the start bit combined with the count does not exceed the length
	if((startbit + count) > m_bitmap.SizeOfBitMap) return false;

	// Test the requested range of bits in the bitmap
	return (NtApi::RtlAreBitsClear(&m_bitmap, startbit, count) == TRUE);
}

//-----------------------------------------------------------------------------
// Bitmap::AreBitsSet
//
// Determines if all bits in a range are set
//
// Arguments:
//
//	startbit		- Bit to start the range check against
//	count			- Number of bits in the range to verify

bool Bitmap::AreBitsSet(uint32_t startbit, uint32_t count) const
{
	// Verify that the start bit combined with the count does not exceed the length
	if((startbit + count) > m_bitmap.SizeOfBitMap) return false;

	// Test the requested range of bits in the bitmap
	return (NtApi::RtlAreBitsSet(&m_bitmap, startbit, count) == TRUE);
}

//-----------------------------------------------------------------------------
// Bitmap::getAvailable
//
// Gets the number of available bits in the bitmap

uint32_t Bitmap::getAvailable(void) const
{
	return NtApi::RtlNumberOfClearBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::Clear
//
// Clears a single bit in the bitmap
//
// Arguments:
//
//	bit			- Index of the bit to be cleared

void Bitmap::Clear(uint32_t bit)
{
	if(bit < m_bitmap.SizeOfBitMap) NtApi::RtlClearBit(&m_bitmap, bit);
}

//-----------------------------------------------------------------------------
// Bitmap::Clear
//
// Clears a range of bits in the bitmap
//
// Arguments:
//
//	startbit	- Starting bit index
//	count		- Number of bits to clear

void Bitmap::Clear(uint32_t startbit, uint32_t count)
{
	if(startbit < m_bitmap.SizeOfBitMap)
		NtApi::RtlClearBits(&m_bitmap, startbit, std::min(static_cast<ULONG>(count), m_bitmap.SizeOfBitMap - startbit));
}

//-----------------------------------------------------------------------------
// Bitmap::ClearAll
//
// Clears all bits in the bitmap
//
// Arguments:
//
//	NONE

void Bitmap::ClearAll(void)
{
	NtApi::RtlClearAllBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::getConsumed
//
// Gets the number of bits consumed in the bitmap

uint32_t Bitmap::getConsumed(void) const
{
	return NtApi::RtlNumberOfSetBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::getEmpty
//
// Determines if the bitmap is empty

bool Bitmap::getEmpty(void) const
{
	return NtApi::RtlNumberOfSetBits(&m_bitmap) == 0;
}

//-----------------------------------------------------------------------------
// Bitmap::FindClear
//
// Locates a single clear bit in the bitmap
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindClear(void) const
{
	return NtApi::RtlFindClearBits(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClear
//
// Locates a block of clear bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous clear bits to locate

uint32_t Bitmap::FindClear(uint32_t quantity) const
{
	return NtApi::RtlFindClearBits(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClear
//
// Locates a block of clear bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous clear bits to locate
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindClear(uint32_t quantity, uint32_t hint) const
{
	return NtApi::RtlFindClearBits(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClearAndSet
//
// Locates a single clear bit in the bitmap and sets it
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindClearAndSet(void)
{
	return NtApi::RtlFindClearBitsAndSet(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClearAndSet
//
// Locates a block of clear bits in the bitmap and sets them
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and set

uint32_t Bitmap::FindClearAndSet(uint32_t quantity)
{
	return NtApi::RtlFindClearBitsAndSet(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClearAndSet
//
// Locates a block of clear bits in the bitmap and sets them, using a caller
// provided hint on where to start looking for the block
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and set
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindClearAndSet(uint32_t quantity, uint32_t hint)
{
	return NtApi::RtlFindClearBitsAndSet(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSet
//
// Locates a single set bit in the bitmap
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindSet(void) const
{
	return NtApi::RtlFindSetBits(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSet
//
// Locates a block of set bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous set bits to locate

uint32_t Bitmap::FindSet(uint32_t quantity) const
{
	return NtApi::RtlFindSetBits(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSet
//
// Locates a block of set bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous set bits to locate
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindSet(uint32_t quantity, uint32_t hint) const
{
	return NtApi::RtlFindSetBits(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSetAndClear
//
// Locates a single set bit in the bitmap and clears it
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindSetAndClear(void)
{
	return NtApi::RtlFindSetBitsAndClear(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSetAndClear
//
// Locates a block of set bits in the bitmap and clears them
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and clear

uint32_t Bitmap::FindSetAndClear(uint32_t quantity)
{
	return NtApi::RtlFindSetBitsAndClear(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSetAndClear
//
// Locates a block of set bits in the bitmap and clears them, using a caller
// provided hint on where to start looking for the block
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and clear
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindSetAndClear(uint32_t quantity, uint32_t hint)
{
	return NtApi::RtlFindSetBitsAndClear(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::getFull
//
// Determines if the bitmap is full

bool Bitmap::getFull(void) const
{
	return NtApi::RtlNumberOfClearBits(&m_bitmap) == 0;
}

//-----------------------------------------------------------------------------
// Bitmap::Set
//
// Sets a single bit in the bitmap
//
// Arguments:
//
//	bit			- Index of the bit to be set

void Bitmap::Set(uint32_t bit)
{
	if(bit < m_bitmap.SizeOfBitMap) NtApi::RtlSetBit(&m_bitmap, bit);
}

//-----------------------------------------------------------------------------
// Bitmap::Set
//
// Sets a range of bits in the bitmap
//
// Arguments:
//
//	startbit	- Starting bit index
//	count		- Number of bits to set

void Bitmap::Set(uint32_t startbit, uint32_t count)
{
	if(startbit < m_bitmap.SizeOfBitMap)
		NtApi::RtlSetBits(&m_bitmap, startbit, std::min(static_cast<ULONG>(count), m_bitmap.SizeOfBitMap - startbit));
}

//-----------------------------------------------------------------------------
// Bitmap::SetAll
//
// Sets all bits in the bitmap
//
// Arguments:
//
//	NONE

void Bitmap::SetAll(void)
{
	NtApi::RtlSetAllBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::getSize
//
// Gets the size of the bitmap

uint32_t Bitmap::getSize(void) const
{
	return m_bitmap.SizeOfBitMap;
}

//-----------------------------------------------------------------------------
// Bitmap::putSize
//
// Sets the size of the bitmap

void Bitmap::putSize(uint32_t bits)
{
	// When reducing the size of a bitmap, any bits that will dangle between
	// the new size and the 32-bit buffer alignment must be cleared first
	if(bits < m_bitmap.SizeOfBitMap) Clear(bits, bits - m_bitmap.SizeOfBitMap);

	// Reallocate the heap buffer to match the requested new size
	void* newbuffer = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, m_bitmap.Buffer, align::up(bits, 32) >> 3);
	if(newbuffer == nullptr) throw Exception(E_OUTOFMEMORY);

	// Assign the updated buffer pointer and bitmap size information
	m_bitmap.Buffer = reinterpret_cast<PULONG>(newbuffer);
	m_bitmap.SizeOfBitMap = bits;
}

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

#pragma warning(pop)
<commit_msg>Bitmap::putSize should not change anything if the reallocation fails<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2015 Michael G. Brehm
//
// 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 "stdafx.h"
#include "Bitmap.h"

#pragma warning(push, 4)

//-----------------------------------------------------------------------------
// Bitmap Constructor
//
// Arguments:
//
//	bits		- Number of bits to define for a new, zero-initialized bitmap

Bitmap::Bitmap(uint32_t bits) : m_bitmap({ 0, nullptr })
{
	// Allocate a zero-initialized buffer for the bitmap off the process heap; the buffer size
	// must be a multiple of 32 bits for compatibility with the bitmap API
	m_bitmap.Buffer = reinterpret_cast<PULONG>(HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, align::up(bits, 32) >> 3));
	if(!m_bitmap.Buffer) throw Exception(E_OUTOFMEMORY);

	m_bitmap.SizeOfBitMap = bits;		// Bitmap was successfully allocated
}

//-----------------------------------------------------------------------------
// Bitmap Copy Constructor

Bitmap::Bitmap(const Bitmap& rhs) : m_bitmap({ 0, nullptr })
{
	// Determine the size of the referenced object's bitmap buffer, in bytes
	size_t size = align::up(rhs.m_bitmap.SizeOfBitMap, 32) >> 3;

	// Allocate a new heap buffer to contain the copy of the referenced object
	m_bitmap.Buffer = reinterpret_cast<PULONG>(HeapAlloc(GetProcessHeap(), 0, size));
	if(m_bitmap.Buffer == nullptr) throw Exception(E_OUTOFMEMORY);

	// Copy the bitmap bits and size from the referenced object
	memcpy(m_bitmap.Buffer, rhs.m_bitmap.Buffer, size);
	m_bitmap.SizeOfBitMap = rhs.m_bitmap.SizeOfBitMap;
}

//-----------------------------------------------------------------------------
// Bitmap Move Constructor

Bitmap::Bitmap(Bitmap&& rhs) : m_bitmap(rhs.m_bitmap)
{
	rhs.m_bitmap.Buffer = nullptr;
	rhs.m_bitmap.SizeOfBitMap = 0;
}

//-----------------------------------------------------------------------------
// Bitmap Destructor

Bitmap::~Bitmap()
{
	if(m_bitmap.Buffer) HeapFree(GetProcessHeap(), 0, m_bitmap.Buffer);
}

//-----------------------------------------------------------------------------
// Bitmap::operator=

Bitmap& Bitmap::operator=(const Bitmap& rhs)
{
	// Determine the size of the referenced object's bitmap buffer, in bytes
	size_t size = align::up(rhs.m_bitmap.SizeOfBitMap, 32) >> 3;

	// Reallocate the heap buffer to match the referenced object's buffer size
	void* newbuffer = HeapReAlloc(GetProcessHeap(), 0, m_bitmap.Buffer, size);
	if(newbuffer == nullptr) throw Exception(E_OUTOFMEMORY);

	// Copy the bits from the referenced object into the reallocated buffer
	memcpy(newbuffer, rhs.m_bitmap.Buffer, size);

	// Assign the updated buffer pointer and bitmap size information
	m_bitmap.Buffer = reinterpret_cast<PULONG>(newbuffer);
	m_bitmap.SizeOfBitMap = rhs.m_bitmap.SizeOfBitMap;

	return *this;
}

//-----------------------------------------------------------------------------
// Bitmap::operator[]

bool Bitmap::operator[](uint32_t bit) const
{
	return (bit < m_bitmap.SizeOfBitMap) ? NtApi::RtlTestBit(&m_bitmap, bit) == TRUE : false;
}

//-----------------------------------------------------------------------------
// Bitmap::AreBitsClear
//
// Determines if all bits in a range are clear
//
// Arguments:
//
//	startbit		- Bit to start the range check against
//	count			- Number of bits in the range to verify

bool Bitmap::AreBitsClear(uint32_t startbit, uint32_t count) const
{
	// Verify that the start bit combined with the count does not exceed the length
	if((startbit + count) > m_bitmap.SizeOfBitMap) return false;

	// Test the requested range of bits in the bitmap
	return (NtApi::RtlAreBitsClear(&m_bitmap, startbit, count) == TRUE);
}

//-----------------------------------------------------------------------------
// Bitmap::AreBitsSet
//
// Determines if all bits in a range are set
//
// Arguments:
//
//	startbit		- Bit to start the range check against
//	count			- Number of bits in the range to verify

bool Bitmap::AreBitsSet(uint32_t startbit, uint32_t count) const
{
	// Verify that the start bit combined with the count does not exceed the length
	if((startbit + count) > m_bitmap.SizeOfBitMap) return false;

	// Test the requested range of bits in the bitmap
	return (NtApi::RtlAreBitsSet(&m_bitmap, startbit, count) == TRUE);
}

//-----------------------------------------------------------------------------
// Bitmap::getAvailable
//
// Gets the number of available bits in the bitmap

uint32_t Bitmap::getAvailable(void) const
{
	return NtApi::RtlNumberOfClearBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::Clear
//
// Clears a single bit in the bitmap
//
// Arguments:
//
//	bit			- Index of the bit to be cleared

void Bitmap::Clear(uint32_t bit)
{
	if(bit < m_bitmap.SizeOfBitMap) NtApi::RtlClearBit(&m_bitmap, bit);
}

//-----------------------------------------------------------------------------
// Bitmap::Clear
//
// Clears a range of bits in the bitmap
//
// Arguments:
//
//	startbit	- Starting bit index
//	count		- Number of bits to clear

void Bitmap::Clear(uint32_t startbit, uint32_t count)
{
	if(startbit < m_bitmap.SizeOfBitMap)
		NtApi::RtlClearBits(&m_bitmap, startbit, std::min(static_cast<ULONG>(count), m_bitmap.SizeOfBitMap - startbit));
}

//-----------------------------------------------------------------------------
// Bitmap::ClearAll
//
// Clears all bits in the bitmap
//
// Arguments:
//
//	NONE

void Bitmap::ClearAll(void)
{
	NtApi::RtlClearAllBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::getConsumed
//
// Gets the number of bits consumed in the bitmap

uint32_t Bitmap::getConsumed(void) const
{
	return NtApi::RtlNumberOfSetBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::getEmpty
//
// Determines if the bitmap is empty

bool Bitmap::getEmpty(void) const
{
	return NtApi::RtlNumberOfSetBits(&m_bitmap) == 0;
}

//-----------------------------------------------------------------------------
// Bitmap::FindClear
//
// Locates a single clear bit in the bitmap
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindClear(void) const
{
	return NtApi::RtlFindClearBits(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClear
//
// Locates a block of clear bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous clear bits to locate

uint32_t Bitmap::FindClear(uint32_t quantity) const
{
	return NtApi::RtlFindClearBits(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClear
//
// Locates a block of clear bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous clear bits to locate
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindClear(uint32_t quantity, uint32_t hint) const
{
	return NtApi::RtlFindClearBits(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClearAndSet
//
// Locates a single clear bit in the bitmap and sets it
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindClearAndSet(void)
{
	return NtApi::RtlFindClearBitsAndSet(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClearAndSet
//
// Locates a block of clear bits in the bitmap and sets them
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and set

uint32_t Bitmap::FindClearAndSet(uint32_t quantity)
{
	return NtApi::RtlFindClearBitsAndSet(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindClearAndSet
//
// Locates a block of clear bits in the bitmap and sets them, using a caller
// provided hint on where to start looking for the block
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and set
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindClearAndSet(uint32_t quantity, uint32_t hint)
{
	return NtApi::RtlFindClearBitsAndSet(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSet
//
// Locates a single set bit in the bitmap
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindSet(void) const
{
	return NtApi::RtlFindSetBits(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSet
//
// Locates a block of set bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous set bits to locate

uint32_t Bitmap::FindSet(uint32_t quantity) const
{
	return NtApi::RtlFindSetBits(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSet
//
// Locates a block of set bits in the bitmap
//
// Arguments:
//
//	quantity	- Number of contiguous set bits to locate
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindSet(uint32_t quantity, uint32_t hint) const
{
	return NtApi::RtlFindSetBits(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSetAndClear
//
// Locates a single set bit in the bitmap and clears it
//
// Arguments:
//
//	NONE

uint32_t Bitmap::FindSetAndClear(void)
{
	return NtApi::RtlFindSetBitsAndClear(&m_bitmap, 1, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSetAndClear
//
// Locates a block of set bits in the bitmap and clears them
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and clear

uint32_t Bitmap::FindSetAndClear(uint32_t quantity)
{
	return NtApi::RtlFindSetBitsAndClear(&m_bitmap, quantity, 0);
}

//-----------------------------------------------------------------------------
// Bitmap::FindSetAndClear
//
// Locates a block of set bits in the bitmap and clears them, using a caller
// provided hint on where to start looking for the block
//
// Arguments:
//
//	quantity	- Number of contiguous bits to locate and clear
//	hint		- Hint on where to start looking in the bitmap

uint32_t Bitmap::FindSetAndClear(uint32_t quantity, uint32_t hint)
{
	return NtApi::RtlFindSetBitsAndClear(&m_bitmap, quantity, hint);
}

//-----------------------------------------------------------------------------
// Bitmap::getFull
//
// Determines if the bitmap is full

bool Bitmap::getFull(void) const
{
	return NtApi::RtlNumberOfClearBits(&m_bitmap) == 0;
}

//-----------------------------------------------------------------------------
// Bitmap::Set
//
// Sets a single bit in the bitmap
//
// Arguments:
//
//	bit			- Index of the bit to be set

void Bitmap::Set(uint32_t bit)
{
	if(bit < m_bitmap.SizeOfBitMap) NtApi::RtlSetBit(&m_bitmap, bit);
}

//-----------------------------------------------------------------------------
// Bitmap::Set
//
// Sets a range of bits in the bitmap
//
// Arguments:
//
//	startbit	- Starting bit index
//	count		- Number of bits to set

void Bitmap::Set(uint32_t startbit, uint32_t count)
{
	if(startbit < m_bitmap.SizeOfBitMap)
		NtApi::RtlSetBits(&m_bitmap, startbit, std::min(static_cast<ULONG>(count), m_bitmap.SizeOfBitMap - startbit));
}

//-----------------------------------------------------------------------------
// Bitmap::SetAll
//
// Sets all bits in the bitmap
//
// Arguments:
//
//	NONE

void Bitmap::SetAll(void)
{
	NtApi::RtlSetAllBits(&m_bitmap);
}

//-----------------------------------------------------------------------------
// Bitmap::getSize
//
// Gets the size of the bitmap

uint32_t Bitmap::getSize(void) const
{
	return m_bitmap.SizeOfBitMap;
}

//-----------------------------------------------------------------------------
// Bitmap::putSize
//
// Sets the size of the bitmap

void Bitmap::putSize(uint32_t bits)
{
	uint32_t aligned = align::up(bits, 32);		// Align to ULONG boundary

	// Reallocate the heap buffer to match the requested new aligned size
	void* newbuffer = HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, m_bitmap.Buffer, aligned >> 3);
	if(newbuffer == nullptr) throw Exception(E_OUTOFMEMORY);

	// Replace the original pointer and length with the aligned buffer
	m_bitmap.Buffer = reinterpret_cast<PULONG>(newbuffer);
	m_bitmap.SizeOfBitMap = aligned;

	// Clear any bits that lie between the unaligned and aligned length
	// prior to assigning the final requested bitmap size
	if(bits != aligned) {

		NtApi::RtlClearBits(&m_bitmap, bits, aligned - bits);
		m_bitmap.SizeOfBitMap = bits;
	}
}

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

#pragma warning(pop)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fmtclbl.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:23:04 $
 *
 *  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 _FMTCLBL_HXX
#define _FMTCLBL_HXX

#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _HINTIDS_HXX
#include <hintids.hxx>
#endif
#ifndef _FORMAT_HXX //autogen
#include <format.hxx>
#endif
#ifndef INCLUDED_SWDLLAPI_H
#include "swdllapi.h"
#endif

class SW_DLLPUBLIC SwFmtNoBalancedColumns : public SfxBoolItem
{
public:
    SwFmtNoBalancedColumns( BOOL bFlag = FALSE )
        : SfxBoolItem( RES_COLUMNBALANCE, bFlag ) {}

    // "pure virtual Methoden" vom SfxPoolItem
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
};

inline const SwFmtNoBalancedColumns &SwAttrSet::GetBalancedColumns(BOOL bInP) const
    { return (const SwFmtNoBalancedColumns&)Get( RES_COLUMNBALANCE, bInP ); }

inline const SwFmtNoBalancedColumns &SwFmt::GetBalancedColumns(BOOL bInP) const
    { return aSet.GetBalancedColumns( bInP ); }

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.9.738); FILE MERGED 2008/04/01 15:56:11 thb 1.9.738.3: #i85898# Stripping all external header guards 2008/04/01 12:53:29 thb 1.9.738.2: #i85898# Stripping all external header guards 2008/03/31 16:52:37 rt 1.9.738.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: fmtclbl.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _FMTCLBL_HXX
#define _FMTCLBL_HXX

#include <svtools/eitem.hxx>
#include <hintids.hxx>
#include <format.hxx>
#include "swdllapi.h"

class SW_DLLPUBLIC SwFmtNoBalancedColumns : public SfxBoolItem
{
public:
    SwFmtNoBalancedColumns( BOOL bFlag = FALSE )
        : SfxBoolItem( RES_COLUMNBALANCE, bFlag ) {}

    // "pure virtual Methoden" vom SfxPoolItem
    virtual SfxPoolItem*    Clone( SfxItemPool *pPool = 0 ) const;
};

inline const SwFmtNoBalancedColumns &SwAttrSet::GetBalancedColumns(BOOL bInP) const
    { return (const SwFmtNoBalancedColumns&)Get( RES_COLUMNBALANCE, bInP ); }

inline const SwFmtNoBalancedColumns &SwFmt::GetBalancedColumns(BOOL bInP) const
    { return aSet.GetBalancedColumns( bInP ); }

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fmtruby.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-05 15:55:07 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FMTRUBY_HXX
#define _FMTRUBY_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif

class SwFmtRuby : public SfxPoolItem
{
    friend class SwTxtRuby;

    String sRubyTxt;                    // the ruby txt
    String sCharFmtName;                // name of the charformat
    SwTxtRuby* pTxtAttr;                // the TextAttribut
    USHORT nCharFmtId;                  // PoolId of the charformat
    USHORT nPosition;                   // Position of the Ruby-Character
    USHORT nAdjustment;                 // specific adjustment of the Ruby-Ch.

public:
    SwFmtRuby( const String& rRubyTxt );
    SwFmtRuby( const SwFmtRuby& rAttr );
    virtual ~SwFmtRuby();

    SwFmtRuby& operator=( const SwFmtRuby& rAttr );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText,
                                    const IntlWrapper* pIntl = 0 ) const;

    virtual BOOL            QueryValue( com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 ) const;
    virtual BOOL            PutValue( const com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 );

    const SwTxtRuby* GetTxtRuby() const         { return pTxtAttr; }
    SwTxtRuby* GetTxtRuby()                     { return pTxtAttr; }

    const String& GetText() const               { return sRubyTxt; }
    void SetText( const String& rTxt )          { sRubyTxt = rTxt; }

    const String& GetCharFmtName() const        { return sCharFmtName; }
    void SetCharFmtName( const String& rNm )    { sCharFmtName = rNm; }

    USHORT GetCharFmtId() const                 { return nCharFmtId; }
    void SetCharFmtId( USHORT nNew )            { nCharFmtId = nNew; }

    USHORT GetPosition() const                  { return nPosition; }
    void SetPosition( USHORT nNew )             { nPosition = nNew; }

    USHORT GetAdjustment() const                { return nAdjustment; }
    void SetAdjustment( USHORT nNew )           { nAdjustment = nNew; }
};

#endif

<commit_msg>INTEGRATION: CWS gcc4fwdecl (1.4.284); FILE MERGED 2005/06/01 18:38:02 pmladek 1.4.284.1: #i50076# Fixed forward declarations for gcc4 in sw<commit_after>/*************************************************************************
 *
 *  $RCSfile: fmtruby.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2005-06-14 16:27:13 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _FMTRUBY_HXX
#define _FMTRUBY_HXX

#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SFXPOOLITEM_HXX
#include <svtools/poolitem.hxx>
#endif

class SwTxtRuby;

class SwFmtRuby : public SfxPoolItem
{
    friend class SwTxtRuby;

    String sRubyTxt;                    // the ruby txt
    String sCharFmtName;                // name of the charformat
    SwTxtRuby* pTxtAttr;                // the TextAttribut
    USHORT nCharFmtId;                  // PoolId of the charformat
    USHORT nPosition;                   // Position of the Ruby-Character
    USHORT nAdjustment;                 // specific adjustment of the Ruby-Ch.

public:
    SwFmtRuby( const String& rRubyTxt );
    SwFmtRuby( const SwFmtRuby& rAttr );
    virtual ~SwFmtRuby();

    SwFmtRuby& operator=( const SwFmtRuby& rAttr );

    // "pure virtual Methoden" vom SfxPoolItem
    virtual int             operator==( const SfxPoolItem& ) const;
    virtual SfxPoolItem*    Clone( SfxItemPool* pPool = 0 ) const;

    virtual SfxItemPresentation GetPresentation( SfxItemPresentation ePres,
                                    SfxMapUnit eCoreMetric,
                                    SfxMapUnit ePresMetric,
                                    String &rText,
                                    const IntlWrapper* pIntl = 0 ) const;

    virtual BOOL            QueryValue( com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 ) const;
    virtual BOOL            PutValue( const com::sun::star::uno::Any& rVal,
                                        BYTE nMemberId = 0 );

    const SwTxtRuby* GetTxtRuby() const         { return pTxtAttr; }
    SwTxtRuby* GetTxtRuby()                     { return pTxtAttr; }

    const String& GetText() const               { return sRubyTxt; }
    void SetText( const String& rTxt )          { sRubyTxt = rTxt; }

    const String& GetCharFmtName() const        { return sCharFmtName; }
    void SetCharFmtName( const String& rNm )    { sCharFmtName = rNm; }

    USHORT GetCharFmtId() const                 { return nCharFmtId; }
    void SetCharFmtId( USHORT nNew )            { nCharFmtId = nNew; }

    USHORT GetPosition() const                  { return nPosition; }
    void SetPosition( USHORT nNew )             { nPosition = nNew; }

    USHORT GetAdjustment() const                { return nAdjustment; }
    void SetAdjustment( USHORT nNew )           { nAdjustment = nNew; }
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ndhints.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:01:31 $
 *
 *  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 _NDHINTS_HXX
#define _NDHINTS_HXX

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

#ifndef _SVMEMPOOL_HXX //autogen
#include <tools/mempool.hxx>
#endif

#include "numrule.hxx"
#include <vector>

class SwTxtNode;
class SwRegHistory;                 // steht im RolBck.hxx
class SwTxtAttr;

/*
 * Ableitung der Klasse SwpHints ueber den Umweg ueber SwpHts, da
 * lediglich die Klasse SwTxtNode Attribute einfuegen und
 * loeschen koennen soll. Anderen Klassen wie den Frames steht
 * lediglich ein lesender Zugriff ueber den Index-Operator zur
 * Verfuegung.
 * Groesse beim Anlegen gleich 1, weil nur dann ein Array erzeug wird, wenn
 * auch ein Hint eingefuegt wird.
 */

/*************************************************************************
 *                      class SwpHtStart/End
 *************************************************************************/

SV_DECL_PTRARR_SORT(SwpHtStart,SwTxtAttr*,1,1)
SV_DECL_PTRARR_SORT(SwpHtEnd,SwTxtAttr*,1,1)

/*************************************************************************
 *                      class SwpHintsArr
 *************************************************************************/

// Das neue Hintsarray:
class SwpHintsArr : private SwpHtStart
{

protected:
    SwpHtEnd aHtEnd;

public:
    void Insert( const SwTxtAttr *pHt );
    void Delete( const SwTxtAttr *pHt );
    void DeleteAtPos( const USHORT nPosInStart );
    BOOL Resort();
    SwTxtAttr *Cut( const USHORT nPosInStart );

    inline const SwTxtAttr *GetStart( const USHORT nPos ) const { return (*this)[nPos]; }
    inline const SwTxtAttr *GetEnd( const USHORT nPos ) const { return aHtEnd[nPos]; }
    inline SwTxtAttr *GetStart( const USHORT nPos ) { return GetHt(nPos); }
    inline SwTxtAttr *GetEnd( const USHORT nPos ) { return aHtEnd[nPos]; }
    inline USHORT GetEndCount() const { return aHtEnd.Count(); }
    inline USHORT GetStartCount() const { return Count(); }
    inline USHORT GetStartOf( const SwTxtAttr *pHt ) const;
    inline USHORT GetEndOf( const SwTxtAttr *pHt ) const;
    inline USHORT GetPos( const SwTxtAttr *pHt ) const
//  OS: in svmem.hxx wird fuer TCPP GetPos ohne const gerufen
#ifdef TCPP
        { return SwpHtStart::GetPos( (SwTxtAttr *)pHt ); }
#else
        { return SwpHtStart::GetPos( pHt ); }
#endif

    inline SwTxtAttr *GetHt( const USHORT nIdx ) { return SwpHtStart::operator[](nIdx); }
    inline const SwTxtAttr *operator[]( const USHORT nIdx )const
        { return SwpHtStart::operator[](nIdx); }
    inline USHORT Count() const { return SwpHtStart::Count(); }

    // Methoden vom PtrArr weiterreichen, wird fuer Node::_Cut benoetigt
    const SwTxtAttr** GetData() const  { return SwpHtStart::GetData(); }

#ifndef PRODUCT
    BOOL Check() const;
#endif
};

/*************************************************************************
 *                      class SwpHints
 *************************************************************************/

// Die public-Schnittstelle zum Node hin
class SwpHints: public SwpHintsArr
{
private:
    SwRegHistory* pHistory;
    // Numerierung
    BOOL    bHasHiddenParaField    :1;  // HiddenParaFld
    BOOL    bFntChg :1;  // Fontwechsel
    BOOL    bFtn    :1;  // Fussnoten
    BOOL    bInSplitNode: 1;    // TRUE: der Node ist im Split und die Frames
                                // werden verschoben!
    BOOL    bDDEFlds : 1;       // es sind DDE-Felder am TextNode vorhanden
    BOOL    bCalcHiddenParaField : 1; // bHasHiddenParaField ist invalid, CalcHiddenParaField() rufen

    BOOL Resort( const USHORT nPos );
    // loescht Hints, die keinen Zustaendigkeitsbereich mehr haben
    void ClearDummies( SwTxtNode &rNode );
    // Merge verschmilzt aneinanderreichende Hints mit gleichen Attributen
    // und gleichen Werten, falls nichts dagegen spricht, d.h. wenn dadurch
    // keine Ueberlappungen mit gleichartigen Attr. entstehen,
    // Ist der Rueckgabewert TRUE, so wurde verschmolzen und dabei u.a. auch
    // ein Resort ausgeloest.
    BOOL Merge( SwTxtNode &rNode, SwTxtAttr* pAttr = 0 );
    // Haelt ein neues Attribut in pHistory fest.
    void NoteInHistory( SwTxtAttr *pAttr, const BOOL bNew = FALSE );

    void CalcFlags( );

    // die Delete Methoden duerfen nur vom TextNode gerufen werden !!
    // Dieser sorgt dafuer, das bei Attributen ohne Ende auch das
    // entsp. Zeichen entfernt wird !!
    friend class SwTxtNode;
    void DeleteAtPos( const USHORT nPos );
    // Ist der Hint schon bekannt, dann suche die Position und loesche ihn.
    // Ist er nicht im Array, so gibt es ein ASSERT !!
    void Delete( SwTxtAttr* pTxtHt );

    inline void SetCalcHiddenParaField(){ bCalcHiddenParaField = TRUE; }
    inline void SetHiddenParaField( const BOOL bNew )  { bHasHiddenParaField = bNew; }
    inline BOOL HasHiddenParaField() const
        { if( bCalcHiddenParaField ) ((SwpHints*)this)->CalcHiddenParaField(); return bHasHiddenParaField; }

public:
    inline BOOL CanBeDeleted() const { return !Count(); }

    // damit das SwDoc::Undo ueber alle Attributaenderungen informiert
    // wird, gibt es hier einen Pointer auf die History. Nur wenn dieser
    // != 0 ist, muessen alle Attributaenderungen "gemeldet" werden.
    void Register( SwRegHistory* pHist ) { pHistory = pHist; }
    void DeRegister() { Register(0); }

    void Insert( SwTxtAttr *pHt, SwTxtNode &rNode, USHORT nMode = 0 );

    // Forget signalisiert, dass es ueberfluessig ist, das Attribut einzu-
    // fuegen, da es keinen Zustaendigkeitsbereich haette.
    BOOL Forget( const std::vector< const SwTxtAttr* >* pExclude,
                 const USHORT i, const USHORT nWhich,
                 const xub_StrLen nStrt, const xub_StrLen nEnd );

    inline BOOL HasFntChg() const { return bFntChg; }
    inline BOOL HasFtn() const { return bFtn; }
    inline BOOL IsInSplitNode() const { return bInSplitNode; }
    inline BOOL HasDDEFld() const { return bDDEFlds; }

    // Konstruktor  (wird im nur einmal benutzt!)
    SwpHints()
    {
        pHistory = 0;
        bFntChg = TRUE;
        bDDEFlds = bFtn = bInSplitNode = bCalcHiddenParaField = bHasHiddenParaField = FALSE;
    }

    // Berechnung von bHasHiddenParaField, return-Wert TRUE bei Aenderung
    BOOL CalcHiddenParaField();

    DECL_FIXEDMEMPOOL_NEWDEL(SwpHints)
};

// Ausgabeoperator fuer die Texthints
SvStream &operator<<(SvStream &aS, const SwpHints &rHints); //$ ostream

/*************************************************************************
 *                       Inline-Implementationen
 *************************************************************************/

inline USHORT SwpHintsArr::GetStartOf( const SwTxtAttr *pHt ) const
{
    USHORT nPos;
    if( !Seek_Entry( pHt, &nPos ) )
        nPos = USHRT_MAX;
    return nPos;
}

inline USHORT SwpHintsArr::GetEndOf( const SwTxtAttr *pHt ) const
{
    USHORT nPos;
    if( !aHtEnd.Seek_Entry( pHt, &nPos ) )
        nPos = USHRT_MAX;
    return nPos;
}

inline SwTxtAttr *SwpHintsArr::Cut( const USHORT nPosInStart )
{
    SwTxtAttr *pHt = GetHt(nPosInStart);
    DeleteAtPos( nPosInStart );
    return pHt;
}

#endif
<commit_msg>INTEGRATION: CWS writercorehandoff (1.6.466); FILE MERGED 2005/09/13 11:42:30 tra 1.6.466.2: RESYNC: (1.6-1.7); FILE MERGED 2005/06/07 14:10:05 fme 1.6.466.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ndhints.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:27:11 $
 *
 *  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 _NDHINTS_HXX
#define _NDHINTS_HXX

#ifndef _SVARRAY_HXX //autogen
#include <svtools/svarray.hxx>
#endif

#ifndef _SVMEMPOOL_HXX //autogen
#include <tools/mempool.hxx>
#endif

#include "numrule.hxx"
#include <vector>

class SwTxtNode;
class SwRegHistory;                 // steht im RolBck.hxx
class SwTxtAttr;

/*
 * Ableitung der Klasse SwpHints ueber den Umweg ueber SwpHts, da
 * lediglich die Klasse SwTxtNode Attribute einfuegen und
 * loeschen koennen soll. Anderen Klassen wie den Frames steht
 * lediglich ein lesender Zugriff ueber den Index-Operator zur
 * Verfuegung.
 * Groesse beim Anlegen gleich 1, weil nur dann ein Array erzeug wird, wenn
 * auch ein Hint eingefuegt wird.
 */

/*************************************************************************
 *                      class SwpHtStart/End
 *************************************************************************/

SV_DECL_PTRARR_SORT(SwpHtStart,SwTxtAttr*,1,1)
SV_DECL_PTRARR_SORT(SwpHtEnd,SwTxtAttr*,1,1)

/*************************************************************************
 *                      class SwpHintsArr
 *************************************************************************/

// Das neue Hintsarray:
class SwpHintsArr : private SwpHtStart
{

protected:
    SwpHtEnd aHtEnd;

public:
    void Insert( const SwTxtAttr *pHt );
    void Delete( const SwTxtAttr *pHt );
    void DeleteAtPos( const USHORT nPosInStart );
    BOOL Resort();
    SwTxtAttr *Cut( const USHORT nPosInStart );

    inline const SwTxtAttr *GetStart( const USHORT nPos ) const { return (*this)[nPos]; }
    inline const SwTxtAttr *GetEnd( const USHORT nPos ) const { return aHtEnd[nPos]; }
    inline SwTxtAttr *GetStart( const USHORT nPos ) { return GetHt(nPos); }
    inline SwTxtAttr *GetEnd( const USHORT nPos ) { return aHtEnd[nPos]; }
    inline USHORT GetEndCount() const { return aHtEnd.Count(); }
    inline USHORT GetStartCount() const { return Count(); }
    inline USHORT GetStartOf( const SwTxtAttr *pHt ) const;
    inline USHORT GetEndOf( const SwTxtAttr *pHt ) const;
    inline USHORT GetPos( const SwTxtAttr *pHt ) const
//  OS: in svmem.hxx wird fuer TCPP GetPos ohne const gerufen
#ifdef TCPP
        { return SwpHtStart::GetPos( (SwTxtAttr *)pHt ); }
#else
        { return SwpHtStart::GetPos( pHt ); }
#endif

    inline SwTxtAttr *GetHt( const USHORT nIdx ) { return SwpHtStart::operator[](nIdx); }
    inline const SwTxtAttr *operator[]( const USHORT nIdx )const
        { return SwpHtStart::operator[](nIdx); }
    inline USHORT Count() const { return SwpHtStart::Count(); }

#ifndef PRODUCT
    BOOL Check() const;
#endif
};

/*************************************************************************
 *                      class SwpHints
 *************************************************************************/

// Die public-Schnittstelle zum Node hin
class SwpHints: public SwpHintsArr
{
private:
    SwRegHistory* pHistory;
    // Numerierung
    BOOL    bHasHiddenParaField    :1;  // HiddenParaFld
    BOOL    bFntChg :1;  // Fontwechsel
    BOOL    bFtn    :1;  // Fussnoten
    BOOL    bInSplitNode: 1;    // TRUE: der Node ist im Split und die Frames
                                // werden verschoben!
    BOOL    bDDEFlds : 1;       // es sind DDE-Felder am TextNode vorhanden
    BOOL    bCalcHiddenParaField : 1; // bHasHiddenParaField ist invalid, CalcHiddenParaField() rufen

    BOOL Resort( const USHORT nPos );
    // loescht Hints, die keinen Zustaendigkeitsbereich mehr haben
    void ClearDummies( SwTxtNode &rNode );
    // Merge verschmilzt aneinanderreichende Hints mit gleichen Attributen
    // und gleichen Werten, falls nichts dagegen spricht, d.h. wenn dadurch
    // keine Ueberlappungen mit gleichartigen Attr. entstehen,
    // Ist der Rueckgabewert TRUE, so wurde verschmolzen und dabei u.a. auch
    // ein Resort ausgeloest.
    BOOL Merge( SwTxtNode &rNode, SwTxtAttr* pAttr = 0 );
    // Haelt ein neues Attribut in pHistory fest.
    void NoteInHistory( SwTxtAttr *pAttr, const BOOL bNew = FALSE );

    void CalcFlags( );

    // die Delete Methoden duerfen nur vom TextNode gerufen werden !!
    // Dieser sorgt dafuer, das bei Attributen ohne Ende auch das
    // entsp. Zeichen entfernt wird !!
    friend class SwTxtNode;
    void DeleteAtPos( const USHORT nPos );
    // Ist der Hint schon bekannt, dann suche die Position und loesche ihn.
    // Ist er nicht im Array, so gibt es ein ASSERT !!
    void Delete( SwTxtAttr* pTxtHt );

    inline void SetCalcHiddenParaField(){ bCalcHiddenParaField = TRUE; }
    inline void SetHiddenParaField( const BOOL bNew )  { bHasHiddenParaField = bNew; }
    inline BOOL HasHiddenParaField() const
        { if( bCalcHiddenParaField ) ((SwpHints*)this)->CalcHiddenParaField(); return bHasHiddenParaField; }

public:
    inline BOOL CanBeDeleted() const { return !Count(); }

    // damit das SwDoc::Undo ueber alle Attributaenderungen informiert
    // wird, gibt es hier einen Pointer auf die History. Nur wenn dieser
    // != 0 ist, muessen alle Attributaenderungen "gemeldet" werden.
    void Register( SwRegHistory* pHist ) { pHistory = pHist; }
    void DeRegister() { Register(0); }

    void Insert( SwTxtAttr *pHt, SwTxtNode &rNode, USHORT nMode = 0 );

    // Forget signalisiert, dass es ueberfluessig ist, das Attribut einzu-
    // fuegen, da es keinen Zustaendigkeitsbereich haette.
    BOOL Forget( const std::vector< const SwTxtAttr* >* pExclude,
                 const USHORT i, const USHORT nWhich,
                 const xub_StrLen nStrt, const xub_StrLen nEnd );

    inline BOOL HasFtn() const { return bFtn; }
    inline BOOL IsInSplitNode() const { return bInSplitNode; }

    // Konstruktor  (wird im nur einmal benutzt!)
    SwpHints()
    {
        pHistory = 0;
        bFntChg = TRUE;
        bDDEFlds = bFtn = bInSplitNode = bCalcHiddenParaField = bHasHiddenParaField = FALSE;
    }

    // Berechnung von bHasHiddenParaField, return-Wert TRUE bei Aenderung
    BOOL CalcHiddenParaField();

    DECL_FIXEDMEMPOOL_NEWDEL(SwpHints)
};

// Ausgabeoperator fuer die Texthints
SvStream &operator<<(SvStream &aS, const SwpHints &rHints); //$ ostream

/*************************************************************************
 *                       Inline-Implementationen
 *************************************************************************/

inline USHORT SwpHintsArr::GetStartOf( const SwTxtAttr *pHt ) const
{
    USHORT nPos;
    if( !Seek_Entry( pHt, &nPos ) )
        nPos = USHRT_MAX;
    return nPos;
}

inline USHORT SwpHintsArr::GetEndOf( const SwTxtAttr *pHt ) const
{
    USHORT nPos;
    if( !aHtEnd.Seek_Entry( pHt, &nPos ) )
        nPos = USHRT_MAX;
    return nPos;
}

inline SwTxtAttr *SwpHintsArr::Cut( const USHORT nPosInStart )
{
    SwTxtAttr *pHt = GetHt(nPosInStart);
    DeleteAtPos( nPosInStart );
    return pHt;
}

#endif
<|endoftext|>