<commit_before>/*-------------------------------------------------------------------------
 *
 * plan_transformer.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /n-store/src/bridge/plan_transformer.cpp
 *
 *-------------------------------------------------------------------------
 */

#include "nodes/pprint.h"
#include "utils/rel.h"
#include "bridge/bridge.h"
#include "executor/executor.h"

#include "backend/bridge/plan_transformer.h"
#include "backend/bridge/tuple_transformer.h"
#include "backend/storage/data_table.h"
#include "backend/planner/insert_node.h"

void printPlanStateTree(const PlanState * planstate);

namespace peloton {
namespace bridge {

/**
 * @brief Get an instance of the plan transformer.
 * @return The instance.
 */
PlanTransformer& PlanTransformer::GetInstance() {
  static PlanTransformer planTransformer;
  return planTransformer;
}

/**
 * @brief Pretty print the plan state tree.
 * @return none.
 */
void PlanTransformer::PrintPlanState(const PlanState *plan_state) const {
  printPlanStateTree(plan_state);
}

/**
 * @brief Convert Postgres PlanState into AbstractPlanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 */
planner::AbstractPlanNode *PlanTransformer::TransformPlan(const PlanState *plan_state) {

  Plan *plan = plan_state->plan;
  planner::AbstractPlanNode *plan_node;

  switch (nodeTag(plan)) {
    case T_ModifyTable:
      plan_node = PlanTransformer::TransformModifyTable(reinterpret_cast<const ModifyTableState *>(plan_state));
      break;
    case T_SeqScan:
      plan_node = PlanTransformer::TransformSeqScan(reinterpret_cast<const SeqScanState*>(plan_state));
      break;
    default:
      plan_node = nullptr;
      break;
  }

  return plan_node;
}

/**
 * @brief Convert ModifyTableState into AbstractPlanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 */
planner::AbstractPlanNode *PlanTransformer::TransformModifyTable(
    const ModifyTableState *mt_plan_state) {

  /* TODO: handle UPDATE, DELETE */
  /* TODO: Add logging */
  ModifyTable *plan = (ModifyTable *) mt_plan_state->ps.plan;

  switch (plan->operation) {
    case CMD_INSERT:
      return PlanTransformer::TransformInsert(mt_plan_state);
      break;

    default:
      break;
  }

  return nullptr;
}

/**
 * @brief Convert ModifyTableState Insert case into AbstractPlanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 */
planner::AbstractPlanNode *PlanTransformer::TransformInsert(
    const ModifyTableState *mt_plan_state) {

  /* Resolve result table */
  ResultRelInfo *result_rel_info = mt_plan_state->resultRelInfo;
  Relation result_relation_desc = result_rel_info->ri_RelationDesc;

  /* Currently, we only support plain insert statement.
   * So, the number of subplan must be exactly 1.
   * TODO: can it be 0? */
  assert(mt_plan_state->mt_nplans == 1);

  Oid database_oid = GetCurrentDatabaseOid();
  Oid table_oid = result_relation_desc->rd_id;

  /* Get the target table */
  storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
      GetLocation(database_oid, table_oid));

  /* Get the tuple schema */
  auto schema = target_table->GetSchema();

  /* Should be only one which is a Result Plan */
  PlanState *subplan_state = mt_plan_state->mt_plans[0];
  TupleTableSlot *plan_slot;
  std::vector<storage::Tuple *> tuples;

  /*
  plan_slot = ExecProcNode(subplan_state);
  assert(!TupIsNull(plan_slot)); // The tuple should not be null

  auto tuple = TupleTransformer(plan_slot, schema);
  tuples.push_back(tuple);
  */

  auto plan_node = new planner::InsertNode(target_table, tuples);

  return plan_node;
}

/**
 * @brief Convert a Postgres SeqScanState into a Peloton SeqScanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 *
 * TODO: Can we also scan result from a child operator? (Non-base-table scan?)
 * We can't for now, but postgres can.
 */
planner::AbstractPlanNode* PlanTransformer::TransformSeqScan(
    const SeqScanState* ss_plan_state) {

  // Grab Database ID and Table ID
  assert(ss_plan_state->ss_currentRelation); // Null if not a base table scan
  Oid database_oid = GetCurrentDatabaseOid();
  Oid table_oid = ss_plan_state->ss_currentRelation->rd_id;

  /* Grab the target table */
  storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
      GetLocation(database_oid, table_oid));

  /*
   * Grab and transform the predicate.
   *
   * TODO:
   * The qualifying predicate should extracted from:
   * ss_plan_state->ps.qual
   *
   * Let's just use a null predicate for now.
   */
  expression::AbstractExpression* predicate = nullptr;

  /*
   * Grab and transform the output column Id's.
   *
   * TODO:
   * The output columns should be extracted from:
   * ss_plan_state->ps.ps_ProjInfo  (null if no projection)
   *
   * Let's just select all columns for now
   */
  auto schema = target_table->GetSchema();
  std::vector<oid_t> column_ids(schema->GetColumnCount());
  std::iota(column_ids.begin(), column_ids.end(), 0);
  assert(column_ids.size() > 0);

  /* Construct and return the Peloton plan node */
  auto plan_node = new planner::SeqScanNode(target_table, predicate, column_ids);
  return plan_node;
}

} // namespace bridge
} // namespace peloton
<commit_msg>Fix compilation<commit_after>/*-------------------------------------------------------------------------
 *
 * plan_transformer.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /n-store/src/bridge/plan_transformer.cpp
 *
 *-------------------------------------------------------------------------
 */

#include "nodes/pprint.h"
#include "utils/rel.h"
#include "bridge/bridge.h"
#include "executor/executor.h"

#include "backend/bridge/plan_transformer.h"
#include "backend/bridge/tuple_transformer.h"
#include "backend/expression/abstract_expression.h"
#include "backend/storage/data_table.h"
#include "backend/planner/insert_node.h"
#include "backend/planner/seq_scan_node.h"

void printPlanStateTree(const PlanState * planstate);

namespace peloton {
namespace bridge {

/**
 * @brief Get an instance of the plan transformer.
 * @return The instance.
 */
PlanTransformer& PlanTransformer::GetInstance() {
  static PlanTransformer planTransformer;
  return planTransformer;
}

/**
 * @brief Pretty print the plan state tree.
 * @return none.
 */
void PlanTransformer::PrintPlanState(const PlanState *plan_state) const {
  printPlanStateTree(plan_state);
}

/**
 * @brief Convert Postgres PlanState into AbstractPlanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 */
planner::AbstractPlanNode *PlanTransformer::TransformPlan(const PlanState *plan_state) {

  Plan *plan = plan_state->plan;
  planner::AbstractPlanNode *plan_node;

  switch (nodeTag(plan)) {
    case T_ModifyTable:
      plan_node = PlanTransformer::TransformModifyTable(reinterpret_cast<const ModifyTableState *>(plan_state));
      break;
    case T_SeqScan:
      plan_node = PlanTransformer::TransformSeqScan(reinterpret_cast<const SeqScanState*>(plan_state));
      break;
    default:
      plan_node = nullptr;
      break;
  }

  return plan_node;
}

/**
 * @brief Convert ModifyTableState into AbstractPlanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 */
planner::AbstractPlanNode *PlanTransformer::TransformModifyTable(
    const ModifyTableState *mt_plan_state) {

  /* TODO: handle UPDATE, DELETE */
  /* TODO: Add logging */
  ModifyTable *plan = (ModifyTable *) mt_plan_state->ps.plan;

  switch (plan->operation) {
    case CMD_INSERT:
      return PlanTransformer::TransformInsert(mt_plan_state);
      break;

    default:
      break;
  }

  return nullptr;
}

/**
 * @brief Convert ModifyTableState Insert case into AbstractPlanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 */
planner::AbstractPlanNode *PlanTransformer::TransformInsert(
    const ModifyTableState *mt_plan_state) {

  /* Resolve result table */
  ResultRelInfo *result_rel_info = mt_plan_state->resultRelInfo;
  Relation result_relation_desc = result_rel_info->ri_RelationDesc;

  /* Currently, we only support plain insert statement.
   * So, the number of subplan must be exactly 1.
   * TODO: can it be 0? */
  assert(mt_plan_state->mt_nplans == 1);

  Oid database_oid = GetCurrentDatabaseOid();
  Oid table_oid = result_relation_desc->rd_id;

  /* Get the target table */
  storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
      GetLocation(database_oid, table_oid));

  /* Get the tuple schema */
  auto schema = target_table->GetSchema();

  /* Should be only one which is a Result Plan */
  PlanState *subplan_state = mt_plan_state->mt_plans[0];
  TupleTableSlot *plan_slot;
  std::vector<storage::Tuple *> tuples;

  /*
  plan_slot = ExecProcNode(subplan_state);
  assert(!TupIsNull(plan_slot)); // The tuple should not be null

  auto tuple = TupleTransformer(plan_slot, schema);
  tuples.push_back(tuple);
  */

  auto plan_node = new planner::InsertNode(target_table, tuples);

  return plan_node;
}

/**
 * @brief Convert a Postgres SeqScanState into a Peloton SeqScanNode.
 * @return Pointer to the constructed AbstractPlanNode.
 *
 * TODO: Can we also scan result from a child operator? (Non-base-table scan?)
 * We can't for now, but postgres can.
 */
planner::AbstractPlanNode* PlanTransformer::TransformSeqScan(
    const SeqScanState* ss_plan_state) {

  assert(nodeTag(ss_plan_state) == T_SeqScanState);

  // Grab Database ID and Table ID
  assert(ss_plan_state->ss_currentRelation); // Null if not a base table scan
  Oid database_oid = GetCurrentDatabaseOid();
  Oid table_oid = ss_plan_state->ss_currentRelation->rd_id;

  /* Grab the target table */
  storage::DataTable *target_table = static_cast<storage::DataTable*>(catalog::Manager::GetInstance().
      GetLocation(database_oid, table_oid));

  /*
   * Grab and transform the predicate.
   *
   * TODO:
   * The qualifying predicate should extracted from:
   * ss_plan_state->ps.qual
   *
   * Let's just use a null predicate for now.
   */
  expression::AbstractExpression* predicate = nullptr;

  /*
   * Grab and transform the output column Id's.
   *
   * TODO:
   * The output columns should be extracted from:
   * ss_plan_state->ps.ps_ProjInfo  (null if no projection)
   *
   * Let's just select all columns for now
   */
  auto schema = target_table->GetSchema();
  std::vector<oid_t> column_ids(schema->GetColumnCount());
  std::iota(column_ids.begin(), column_ids.end(), 0);
  assert(column_ids.size() > 0);

  /* Construct and return the Peloton plan node */
  auto plan_node = new planner::SeqScanNode(target_table, predicate, column_ids);
  return plan_node;
}

} // namespace bridge
} // namespace peloton
<|endoftext|>


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

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

#include <outl_pch.hxx>

#define _OUTLINER_CXX
#include <svx/outliner.hxx>
#include <outlundo.hxx>

OutlinerUndoBase::OutlinerUndoBase( USHORT _nId, Outliner* pOutliner )
    : EditUndo( _nId, NULL )
{
    DBG_ASSERT( pOutliner, "Undo: Outliner?!" );
    mpOutliner = pOutliner;
}

OutlinerUndoChangeDepth::OutlinerUndoChangeDepth( Outliner* pOutliner, USHORT nPara, USHORT nOldDepth, USHORT nNewDepth )
    : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner )
{
    mnPara = nPara;
    mnOldDepth = nOldDepth;
    mnNewDepth = nNewDepth;
}

void OutlinerUndoChangeDepth::Undo()
{
    GetOutliner()->ImplInitDepth( mnPara, mnOldDepth, FALSE );
}

void OutlinerUndoChangeDepth::Redo()
{
    GetOutliner()->ImplInitDepth( mnPara, mnNewDepth, FALSE );
}

void OutlinerUndoChangeDepth::Repeat()
{
    DBG_ERROR( "Repeat not implemented!" );
}

OutlinerUndoCheckPara::OutlinerUndoCheckPara( Outliner* pOutliner, USHORT nPara )
    : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner )
{
    mnPara = nPara;
}

void OutlinerUndoCheckPara::Undo()
{
    Paragraph* pPara = GetOutliner()->GetParagraph( mnPara );
    pPara->Invalidate();
    GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE );
}

void OutlinerUndoCheckPara::Redo()
{
    Paragraph* pPara = GetOutliner()->GetParagraph( mnPara );
    pPara->Invalidate();
    GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE );
}

void OutlinerUndoCheckPara::Repeat()
{
    DBG_ERROR( "Repeat not implemented!" );
}

DBG_NAME(OLUndoExpand);

OLUndoExpand::OLUndoExpand(Outliner* pOut, USHORT _nId )
    : EditUndo( _nId, 0 )
{
    DBG_CTOR(OLUndoExpand,0);
    DBG_ASSERT(pOut,"Undo:No Outliner");
    pOutliner = pOut;
    nCount = 0;
    pParas = 0;
}

OLUndoExpand::~OLUndoExpand()
{
    DBG_DTOR(OLUndoExpand,0);
    delete pParas;
}

void OLUndoExpand::Restore( BOOL bUndo )
{
    DBG_CHKTHIS(OLUndoExpand,0);
    DBG_ASSERT(pOutliner,"Undo:No Outliner");
    DBG_ASSERT(pOutliner->pEditEngine,"Outliner already deleted");
    Paragraph* pPara;

    BOOL bExpand = FALSE;
    USHORT _nId = GetId();
    if((_nId == OLUNDO_EXPAND && !bUndo) || (_nId == OLUNDO_COLLAPSE && bUndo))
        bExpand = TRUE;
    if( !pParas )
    {
        pPara = pOutliner->GetParagraph( (ULONG)nCount );
        if( bExpand )
            pOutliner->Expand( pPara );
        else
            pOutliner->Collapse( pPara );
    }
    else
    {
        for( USHORT nIdx = 0; nIdx < nCount; nIdx++ )
        {
            pPara = pOutliner->GetParagraph( (ULONG)(pParas[nIdx]) );
            if( bExpand )
                pOutliner->Expand( pPara );
            else
                pOutliner->Collapse( pPara );
        }
    }
}

void OLUndoExpand::Undo()
{
    DBG_CHKTHIS(OLUndoExpand,0);
    Restore( TRUE );
}

void OLUndoExpand::Redo()
{
    DBG_CHKTHIS(OLUndoExpand,0);
    Restore( FALSE );
}

void OLUndoExpand::Repeat()
{
    DBG_CHKTHIS(OLUndoExpand,0);
    DBG_ERROR("Not implemented");
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.368); FILE MERGED 2008/03/31 14:23:09 rt 1.7.368.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: outlundo.cxx,v $
 * $Revision: 1.8 $
 *
 * 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.
 *
 ************************************************************************/

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

#include <outl_pch.hxx>

#define _OUTLINER_CXX
#include <svx/outliner.hxx>
#include <outlundo.hxx>

OutlinerUndoBase::OutlinerUndoBase( USHORT _nId, Outliner* pOutliner )
    : EditUndo( _nId, NULL )
{
    DBG_ASSERT( pOutliner, "Undo: Outliner?!" );
    mpOutliner = pOutliner;
}

OutlinerUndoChangeDepth::OutlinerUndoChangeDepth( Outliner* pOutliner, USHORT nPara, USHORT nOldDepth, USHORT nNewDepth )
    : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner )
{
    mnPara = nPara;
    mnOldDepth = nOldDepth;
    mnNewDepth = nNewDepth;
}

void OutlinerUndoChangeDepth::Undo()
{
    GetOutliner()->ImplInitDepth( mnPara, mnOldDepth, FALSE );
}

void OutlinerUndoChangeDepth::Redo()
{
    GetOutliner()->ImplInitDepth( mnPara, mnNewDepth, FALSE );
}

void OutlinerUndoChangeDepth::Repeat()
{
    DBG_ERROR( "Repeat not implemented!" );
}

OutlinerUndoCheckPara::OutlinerUndoCheckPara( Outliner* pOutliner, USHORT nPara )
    : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner )
{
    mnPara = nPara;
}

void OutlinerUndoCheckPara::Undo()
{
    Paragraph* pPara = GetOutliner()->GetParagraph( mnPara );
    pPara->Invalidate();
    GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE );
}

void OutlinerUndoCheckPara::Redo()
{
    Paragraph* pPara = GetOutliner()->GetParagraph( mnPara );
    pPara->Invalidate();
    GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE );
}

void OutlinerUndoCheckPara::Repeat()
{
    DBG_ERROR( "Repeat not implemented!" );
}

DBG_NAME(OLUndoExpand);

OLUndoExpand::OLUndoExpand(Outliner* pOut, USHORT _nId )
    : EditUndo( _nId, 0 )
{
    DBG_CTOR(OLUndoExpand,0);
    DBG_ASSERT(pOut,"Undo:No Outliner");
    pOutliner = pOut;
    nCount = 0;
    pParas = 0;
}

OLUndoExpand::~OLUndoExpand()
{
    DBG_DTOR(OLUndoExpand,0);
    delete pParas;
}

void OLUndoExpand::Restore( BOOL bUndo )
{
    DBG_CHKTHIS(OLUndoExpand,0);
    DBG_ASSERT(pOutliner,"Undo:No Outliner");
    DBG_ASSERT(pOutliner->pEditEngine,"Outliner already deleted");
    Paragraph* pPara;

    BOOL bExpand = FALSE;
    USHORT _nId = GetId();
    if((_nId == OLUNDO_EXPAND && !bUndo) || (_nId == OLUNDO_COLLAPSE && bUndo))
        bExpand = TRUE;
    if( !pParas )
    {
        pPara = pOutliner->GetParagraph( (ULONG)nCount );
        if( bExpand )
            pOutliner->Expand( pPara );
        else
            pOutliner->Collapse( pPara );
    }
    else
    {
        for( USHORT nIdx = 0; nIdx < nCount; nIdx++ )
        {
            pPara = pOutliner->GetParagraph( (ULONG)(pParas[nIdx]) );
            if( bExpand )
                pOutliner->Expand( pPara );
            else
                pOutliner->Collapse( pPara );
        }
    }
}

void OLUndoExpand::Undo()
{
    DBG_CHKTHIS(OLUndoExpand,0);
    Restore( TRUE );
}

void OLUndoExpand::Redo()
{
    DBG_CHKTHIS(OLUndoExpand,0);
    Restore( FALSE );
}

void OLUndoExpand::Repeat()
{
    DBG_CHKTHIS(OLUndoExpand,0);
    DBG_ERROR("Not implemented");
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include <fstream>

#include "vast/error.hpp"

#include "vast/detail/fdinbuf.hpp"
#include "vast/detail/fdostream.hpp"
#include "vast/detail/make_io_stream.hpp"
#include "vast/detail/posix.hpp"

namespace vast {
namespace detail {

expected<std::unique_ptr<std::istream>>
make_input_stream(const std::string& input, bool is_uds) {
  struct owning_istream : public std::istream {
    owning_istream(std::unique_ptr<std::streambuf>&& ptr) : std::istream{ptr.release()} {
      // nop
    }
    ~owning_istream() {
      delete rdbuf();
    }
  };
  if (is_uds) {
    if (input == "-")
      return make_error(ec::filesystem_error,
                        "cannot use stdin as UNIX domain socket");
    auto uds = unix_domain_socket::connect(input);
    if (!uds)
      return make_error(ec::filesystem_error,
                        "failed to connect to UNIX domain socket at", input);
    auto remote_fd = uds.recv_fd(); // Blocks!
    auto sb = std::make_unique<fdinbuf>(remote_fd);
    return std::make_unique<owning_istream>(std::move(sb));
  }
  if (input == "-") {
    auto sb = std::make_unique<fdinbuf>(0);
    return std::make_unique<owning_istream>(std::move(sb));
  }
  auto fb = std::make_unique<std::filebuf>();
  fb->open(input, std::ios_base::binary | std::ios_base::in);
  return std::make_unique<owning_istream>(std::move(fb));
}

expected<std::unique_ptr<std::ostream>>
make_output_stream(const std::string& output, bool is_uds) {
  if (is_uds) {
      return make_error(ec::filesystem_error,
                        "cannot use stdout as UNIX domain socket");
    auto uds = unix_domain_socket::connect(output);
    if (!uds)
      return make_error(ec::filesystem_error,
                        "failed to connect to UNIX domain socket at", output);
    auto remote_fd = uds.recv_fd(); // Blocks!
    return std::make_unique<fdostream>(remote_fd);
  }
  if (output == "-")
    return std::make_unique<fdostream>(1); // stdout
  return std::make_unique<std::ofstream>(output);
}

} // namespace detail
} // namespace vast
<commit_msg>Adhere to style guide<commit_after>/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#include <fstream>

#include "vast/error.hpp"

#include "vast/detail/fdinbuf.hpp"
#include "vast/detail/fdostream.hpp"
#include "vast/detail/make_io_stream.hpp"
#include "vast/detail/posix.hpp"

namespace vast {
namespace detail {

expected<std::unique_ptr<std::istream>>
make_input_stream(const std::string& input, bool is_uds) {
  struct owning_istream : public std::istream {
    owning_istream(std::unique_ptr<std::streambuf>&& ptr)
      : std::istream{ptr.release()} {
      // nop
    }
    ~owning_istream() {
      delete rdbuf();
    }
  };
  if (is_uds) {
    if (input == "-")
      return make_error(ec::filesystem_error,
                        "cannot use stdin as UNIX domain socket");
    auto uds = unix_domain_socket::connect(input);
    if (!uds)
      return make_error(ec::filesystem_error,
                        "failed to connect to UNIX domain socket at", input);
    auto remote_fd = uds.recv_fd(); // Blocks!
    auto sb = std::make_unique<fdinbuf>(remote_fd);
    return std::make_unique<owning_istream>(std::move(sb));
  }
  if (input == "-") {
    auto sb = std::make_unique<fdinbuf>(0); // stdin
    return std::make_unique<owning_istream>(std::move(sb));
  }
  auto fb = std::make_unique<std::filebuf>();
  fb->open(input, std::ios_base::binary | std::ios_base::in);
  return std::make_unique<owning_istream>(std::move(fb));
}

expected<std::unique_ptr<std::ostream>>
make_output_stream(const std::string& output, bool is_uds) {
  if (is_uds) {
      return make_error(ec::filesystem_error,
                        "cannot use stdout as UNIX domain socket");
    auto uds = unix_domain_socket::connect(output);
    if (!uds)
      return make_error(ec::filesystem_error,
                        "failed to connect to UNIX domain socket at", output);
    auto remote_fd = uds.recv_fd(); // Blocks!
    return std::make_unique<fdostream>(remote_fd);
  }
  if (output == "-")
    return std::make_unique<fdostream>(1); // stdout
  return std::make_unique<std::ofstream>(output);
}

} // namespace detail
} // namespace vast
<|endoftext|>


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

/*! @file benchmarks/benchmark-example.C
 * @ingroup benchmarks
 * @brief Benchmarking example
 * @example benchmark
 */

#include "benchmarks/benchmark.h"
#include "linbox/util/error.h"
#include "fflas-ffpack/fflas-ffpack.h"
#include "linbox/field/modular.h"
#include "linbox/field/modular-balanced.h"
#include "linbox/matrix/random-matrix.h"
#include "linbox/matrix/dense-matrix.h"
#include "linbox/matrix/matrix-domain.h"
#include "linbox/matrix/sparse-matrix.h"
#include "linbox/solutions/rank.h"

using namespace LinBox ;
using Givaro::Timer;

/* compute MegaFLOPS for mat mul (2 m n k) */
double mm_mflops(index_t m, index_t n, index_t k)
{
	return 2*(double)m/100*(double)n/100*(double)k/100 ;
}

/* Benchmark on a field */

/*! @internal
 * @brief launches the benchmarks for the square case.
 * @param F field
 * @param min min size to bench
 * @param max max size to bench
 * @param step step between two sizes
 * @param Data where data is stored
 * @param series_nb index of the current series of measures.
 */
template<class Field>
void launch_bench_square(Field & F // const problem
			 , index_t min, index_t max, index_t step // no negative step
			 , PlotData & Data
			)
{
	linbox_check(step);
	linbox_check(min <= max);

	std::ostringstream nam ;
	F.write(nam);
	// Data.setCurrentSerieName(nam.str());

	Data.newSerie(nam.str());
	Chrono<Timer> TW ;

	typedef typename Field::RandIter Randiter ;
	Randiter R(F) ;
	BlasMatrixDomain<Field> BMD(F) ;
	RandomDenseMatrix<Randiter,Field> RandMat(F,R);

	for ( index_t i = min ; i < max ; i += step ) {

		showAdvanceLinear(i,min,max);
		size_t ii = i ;
		BlasMatrix<Field> A (F,ii,ii);
		BlasMatrix<Field> B (F,ii,ii);
		BlasMatrix<Field> C (F,ii,ii);

		index_t j = 0 ; // number of repets.

		RandMat.random(A);
		RandMat.random(B);
		RandMat.random(C);
		TW.clear() ;
		while( Data.keepon(j,TW.time()) ) {
			TW.start() ;
			BMD.mul(C,A,B) ; // C = AB
			TW.stop();
			++j ;
		}
		double mflops = computeMFLOPS(TW.times(),mm_mflops(i,i,i));

		Data.setCurrentSeriesEntry(i,mflops,i,TW.time()); // could be i*i*i

	}

	Data.finishSerie();
}

/* Collects Benchmarks */

/*! @brief Benchmark square fgemm Y=AX for several fields.
 * @param min min size
 * @param max max size
 * @param step step of the size between 2 benchmarks
 * @param charac characteristic of the field.
 */
void bench_square( index_t min, index_t max, index_t step, int charac )
{

	index_t nb = 1 ;// une col de plus (la première)
	typedef LinBox::Modular<double>          Field0 ; ++nb ;
	typedef LinBox::Modular<float>           Field1 ; ++nb ;
	// typedef LinBox::Modular<int32_t>         Field2 ; ++nb ;
	// typedef LinBox::ModularBalanced<double>  Field3 ; ++nb ;
	// typedef LinBox::ModularBalanced<float>   Field4 ; ++nb ;
	// typedef LinBox::ModularBalanced<int32_t> Field5 ; ++nb ;
	// GivaroZpZ

	///// DATA HARVEST ////

	PlotData  Data;
	showProgression Show(nb) ;

	Field0 F0(charac) ;
	// launch_bench_square<Field0>(F0,100,1500,300,Data);
	launch_bench_square<Field0>(F0,min,max,step,Data);
	Show.FinishIter();

	if (charac < 2048) {
		Field1 F1(charac) ;
		// launch_bench_square(F1,200,1500,200,Data);
		launch_bench_square(F1,min,max,step,Data);
		Show.FinishIter();
	}
	else {
		Show.SkipIter();
	}

#if 0
	Field2 F2(charac) ;
	launch_bench_square(F2,min,max,step,Data);
	Show.FinishIter();

	Field3 F3(charac) ;
	launch_bench_square(F3,min,max,step,Data);
	Show.FinishIter();

	if (charac < 2048) {
		Field4 F4(charac) ;
		launch_bench_square(F4,min,max,step,Data);
		Show.FinishIter();
	}
	else {
		Show.SkipIter();
	}

	Field5 F5(charac) ;
	launch_bench_square(F5,min,max,step,Data);
	Show.FinishIter();
#endif

	///// PLOT STYLE ////
	LinBox::PlotStyle Style;

	Style.setTerm(LinBox::PlotStyle::Term::eps);
	Style.setTitle("BlasMatrixDomain mul","Mflops","dimensions");

	Style.setPlotType(LinBox::PlotStyle::Plot::graph);
	Style.setLineType(LinBox::PlotStyle::Line::linespoints);

	LinBox::PlotGraph Graph(Data,Style);
	Graph.setOutFilename("bmdmul_square");

	// Graph.plot();

	Graph.print(Tag::Printer::gnuplot);

	Graph.print(Tag::Printer::tex);
	Graph.print(Tag::Printer::csv);

	return ;

}

template<class Field>
void launch_bench_rank(const Field &F, const std::string & name
			 , PlotData & Data
		       )
{

	SparseMatrix<Field> Mat(F);
	std::ifstream mat1 (name);
	Mat.read(mat1);

	MatrixMetaData mmd (Mat,name);

	// Data.newSerie(name);
	Chrono<Timer> TW ;

	showAdvanceLinear(1,1,2);

	TW.clear() ;
	index_t j = 0 ;
	while( Data.keepon(j,TW.time()) ) {
		TW.start() ;
		unsigned long d ;
		LinBox::rank(d,Mat,Method::Blackbox());
		TW.stop();
		++j ;
	}

	// double mflops = computeMFLOPS(TW.times(),mm_mflops(i,i,i));

	Data.setSeriesEntry("Rank (Blackbox)",name,TW.time(),(double)Mat.size(),TW.time());
	Data.addCurrentEntryMetaData(mmd);
	// Data.addCurrentSerieMetaData(mmd);
	// Data.addMetaData(mmd);

	showAdvanceLinear(2,1,2);

	TW.clear() ;
	j = 0 ;
	while( Data.keepon(j,TW.time()) ) {
		TW.start() ;
		unsigned long d ;
		LinBox::rank(d,Mat,Method::SparseElimination());
		TW.stop();
		++j ;
	}

	Data.selectSeries("Rank (SparseElimination)");
	Data.setCurrentSeriesEntry(name,TW.time(),(double)Mat.size(),TW.time());
	Data.addCurrentEntryMetaData(mmd);

}

void bench_rank(int carac)
{
	typedef LinBox::Modular<double>  Field0 ;
	Field0 F(carac);
	int nb = 1;

	//! @bug no gz reader ?

	std::string m1 = "matrix/bibd_12_5_66x792.sms" ; ++nb;
	std::string m2 = "matrix/bibd_13_6_78x1716.sms" ; ++nb;
	std::string m3 = "matrix/bibd_14_7_91x3432.sms" ; ++nb;

	PlotData  Data;
	showProgression Show((index_t)nb) ;

	launch_bench_rank(F,m1,Data);
	Show.FinishIter();

	launch_bench_rank(F,m2,Data);
	Show.FinishIter();

	launch_bench_rank(F,m3,Data);
	Show.FinishIter();

	///// PLOT STYLE ////
	LinBox::PlotStyle Style;
	Style.setTerm(LinBox::PlotStyle::Term::eps);
	Style.setTitle("Rank algorithms","seconds","matrices");
	Style.setXtics(LinBox::PlotStyle::Options::oblique);

	Style.setPlotType(LinBox::PlotStyle::Plot::histo);
	Style.setLineType(LinBox::PlotStyle::Line::histogram);

	LinBox::PlotGraph Graph(Data,Style);
	Graph.setOutFilename("rank_comparison");

	// Graph.plot();

	Graph.print(Tag::Printer::gnuplot);

	// change style
	Graph.refStyle().setTerm(LinBox::PlotStyle::Term::png);
	Graph.print(Tag::Printer::gnuplot);

	Graph.print(Tag::Printer::xml);
	Graph.print(Tag::Printer::html);

	return;
}

/*  main */

int main( int ac, char ** av)
{
	/*  Argument parsing/setting */

	static index_t       min  = 100;     /*  min size */
	static index_t       max  = 1500;    /*  max size (not included) */
	static index_t       step = 300;    /*  step between 2 sizes */
	// static std::list<int> lst  ;       /*  what bench to start ? */
	// lst.push_front(1);// ={1,2} vivement le nouveau std...
	// lst.push_front(2);

	static Argument as[] = {
		{ 'm', "-m min" , "Set minimal size of matrix to test."    , TYPE_INT , &min },
		{ 'M', "-M Max" , "Set maximal size."                      , TYPE_INT , &max },
		{ 's', "-s step", "Sets the gap between two matrix sizes.", TYPE_INT , &step },
		// { 'l', "-l list", "Only launches a subset of available benchmarks\n - 1: compare to raw blas\n - 2:various square sizes\n - 3:various shapes\n - 4: various parameters (a,b)\n - 5 : various transp. combinations", TYPE_INTLIST, &lst },
		END_OF_ARGUMENTS
	};

	parseArguments (ac, av, as);

	if (min >= max) {
		throw LinBoxError("min value should be smaller than max...");
	}
	if (min + step >= max) {
		std::cout << "Warning : your x axis has only one point. You should have a smaller step." << std::endl;
	}

	/* square for various fields */
	{
		std::cout << " *** Lines plot *** " << std::endl;
		std::cout << "Benchmark square matrix multiplication via BMD.mul()" << std::endl;
		bench_square(min,max,step,13);
	}

	/* different sparse matrix   */

	{
		std::cout << " *** Bar plot *** " << std::endl;
		std::cout << "Benchmark different matrices on different rank algorithms" << std::endl;
		bench_rank(13);
	}

	return EXIT_SUCCESS ;
}

// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<commit_msg>double vs int<commit_after>/* Copyright (C) 2011 LinBox
 * Written by BB <brice.boyer@imag.fr>
 *
 *
 *
 * ========LICENCE========
 * This file is part of the library LinBox.
 *
  * LinBox is free software: you can redistribute it and/or modify
 * it under the terms of the  GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * ========LICENCE========
 */

/*! @file benchmarks/benchmark-example.C
 * @ingroup benchmarks
 * @brief Benchmarking example
 * @example benchmark
 */

#include "benchmarks/benchmark.h"
#include "linbox/util/error.h"
#include "fflas-ffpack/fflas-ffpack.h"
#include "linbox/field/modular.h"
#include "linbox/field/modular-balanced.h"
#include "linbox/matrix/random-matrix.h"
#include "linbox/matrix/dense-matrix.h"
#include "linbox/matrix/matrix-domain.h"
#include "linbox/matrix/sparse-matrix.h"
#include "linbox/solutions/rank.h"

using namespace LinBox ;
using Givaro::Timer;

/* compute MegaFLOPS for mat mul (2 m n k) */
double mm_mflops(index_t m, index_t n, index_t k)
{
	return 2*(double)m/100*(double)n/100*(double)k/100 ;
}

/* Benchmark on a field */

/*! @internal
 * @brief launches the benchmarks for the square case.
 * @param F field
 * @param min min size to bench
 * @param max max size to bench
 * @param step step between two sizes
 * @param Data where data is stored
 * @param series_nb index of the current series of measures.
 */
template<class Field>
void launch_bench_square(Field & F // const problem
			 , index_t min, index_t max, index_t step // no negative step
			 , PlotData & Data
			)
{
	linbox_check(step);
	linbox_check(min <= max);

	std::ostringstream nam ;
	F.write(nam);
	// Data.setCurrentSerieName(nam.str());

	Data.newSerie(nam.str());
	Chrono<Timer> TW ;

	typedef typename Field::RandIter Randiter ;
	Randiter R(F) ;
	BlasMatrixDomain<Field> BMD(F) ;
	RandomDenseMatrix<Randiter,Field> RandMat(F,R);

	for ( index_t i = min ; i < max ; i += step ) {

		showAdvanceLinear(i,min,max);
		size_t ii = i ;
		BlasMatrix<Field> A (F,ii,ii);
		BlasMatrix<Field> B (F,ii,ii);
		BlasMatrix<Field> C (F,ii,ii);

		index_t j = 0 ; // number of repets.

		RandMat.random(A);
		RandMat.random(B);
		RandMat.random(C);
		TW.clear() ;
		while( Data.keepon(j,TW.time()) ) {
			TW.start() ;
			BMD.mul(C,A,B) ; // C = AB
			TW.stop();
			++j ;
		}
		double mflops = computeMFLOPS(TW.times(),mm_mflops(i,i,i));

		Data.setCurrentSeriesEntry(i,mflops,(double)i,TW.time()); // could be i*i*i

	}

	Data.finishSerie();
}

/* Collects Benchmarks */

/*! @brief Benchmark square fgemm Y=AX for several fields.
 * @param min min size
 * @param max max size
 * @param step step of the size between 2 benchmarks
 * @param charac characteristic of the field.
 */
void bench_square( index_t min, index_t max, index_t step, int charac )
{

	index_t nb = 1 ;// une col de plus (la première)
	typedef LinBox::Modular<double>          Field0 ; ++nb ;
	typedef LinBox::Modular<float>           Field1 ; ++nb ;
	// typedef LinBox::Modular<int32_t>         Field2 ; ++nb ;
	// typedef LinBox::ModularBalanced<double>  Field3 ; ++nb ;
	// typedef LinBox::ModularBalanced<float>   Field4 ; ++nb ;
	// typedef LinBox::ModularBalanced<int32_t> Field5 ; ++nb ;
	// GivaroZpZ

	///// DATA HARVEST ////

	PlotData  Data;
	showProgression Show(nb) ;

	Field0 F0(charac) ;
	// launch_bench_square<Field0>(F0,100,1500,300,Data);
	launch_bench_square<Field0>(F0,min,max,step,Data);
	Show.FinishIter();

	if (charac < 2048) {
		Field1 F1(charac) ;
		// launch_bench_square(F1,200,1500,200,Data);
		launch_bench_square(F1,min,max,step,Data);
		Show.FinishIter();
	}
	else {
		Show.SkipIter();
	}

#if 0
	Field2 F2(charac) ;
	launch_bench_square(F2,min,max,step,Data);
	Show.FinishIter();

	Field3 F3(charac) ;
	launch_bench_square(F3,min,max,step,Data);
	Show.FinishIter();

	if (charac < 2048) {
		Field4 F4(charac) ;
		launch_bench_square(F4,min,max,step,Data);
		Show.FinishIter();
	}
	else {
		Show.SkipIter();
	}

	Field5 F5(charac) ;
	launch_bench_square(F5,min,max,step,Data);
	Show.FinishIter();
#endif

	///// PLOT STYLE ////
	LinBox::PlotStyle Style;

	Style.setTerm(LinBox::PlotStyle::Term::eps);
	Style.setTitle("BlasMatrixDomain mul","Mflops","dimensions");

	Style.setPlotType(LinBox::PlotStyle::Plot::graph);
	Style.setLineType(LinBox::PlotStyle::Line::linespoints);

	LinBox::PlotGraph Graph(Data,Style);
	Graph.setOutFilename("bmdmul_square");

	// Graph.plot();

	Graph.print(Tag::Printer::gnuplot);

	Graph.print(Tag::Printer::tex);
	Graph.print(Tag::Printer::csv);

	return ;

}

template<class Field>
void launch_bench_rank(const Field &F, const std::string & name
			 , PlotData & Data
		       )
{

	SparseMatrix<Field> Mat(F);
	std::ifstream mat1 (name);
	Mat.read(mat1);

	MatrixMetaData mmd (Mat,name);

	// Data.newSerie(name);
	Chrono<Timer> TW ;

	showAdvanceLinear(1,1,2);

	TW.clear() ;
	index_t j = 0 ;
	while( Data.keepon(j,TW.time()) ) {
		TW.start() ;
		unsigned long d ;
		LinBox::rank(d,Mat,Method::Blackbox());
		TW.stop();
		++j ;
	}

	// double mflops = computeMFLOPS(TW.times(),mm_mflops(i,i,i));

	Data.setSeriesEntry("Rank (Blackbox)",name,TW.time(),(double)Mat.size(),TW.time());
	Data.addCurrentEntryMetaData(mmd);
	// Data.addCurrentSerieMetaData(mmd);
	// Data.addMetaData(mmd);

	showAdvanceLinear(2,1,2);

	TW.clear() ;
	j = 0 ;
	while( Data.keepon(j,TW.time()) ) {
		TW.start() ;
		unsigned long d ;
		LinBox::rank(d,Mat,Method::SparseElimination());
		TW.stop();
		++j ;
	}

	Data.selectSeries("Rank (SparseElimination)");
	Data.setCurrentSeriesEntry(name,TW.time(),(double)Mat.size(),TW.time());
	Data.addCurrentEntryMetaData(mmd);

}

void bench_rank(int carac)
{
	typedef LinBox::Modular<double>  Field0 ;
	Field0 F(carac);
	int nb = 1;

	//! @bug no gz reader ?

	std::string m1 = "matrix/bibd_12_5_66x792.sms" ; ++nb;
	std::string m2 = "matrix/bibd_13_6_78x1716.sms" ; ++nb;
	std::string m3 = "matrix/bibd_14_7_91x3432.sms" ; ++nb;

	PlotData  Data;
	showProgression Show((index_t)nb) ;

	launch_bench_rank(F,m1,Data);
	Show.FinishIter();

	launch_bench_rank(F,m2,Data);
	Show.FinishIter();

	launch_bench_rank(F,m3,Data);
	Show.FinishIter();

	///// PLOT STYLE ////
	LinBox::PlotStyle Style;
	Style.setTerm(LinBox::PlotStyle::Term::eps);
	Style.setTitle("Rank algorithms","seconds","matrices");
	Style.setXtics(LinBox::PlotStyle::Options::oblique);

	Style.setPlotType(LinBox::PlotStyle::Plot::histo);
	Style.setLineType(LinBox::PlotStyle::Line::histogram);

	LinBox::PlotGraph Graph(Data,Style);
	Graph.setOutFilename("rank_comparison");

	// Graph.plot();

	Graph.print(Tag::Printer::gnuplot);

	// change style
	Graph.refStyle().setTerm(LinBox::PlotStyle::Term::png);
	Graph.print(Tag::Printer::gnuplot);

	Graph.print(Tag::Printer::xml);
	Graph.print(Tag::Printer::html);

	return;
}

/*  main */

int main( int ac, char ** av)
{
	/*  Argument parsing/setting */

	static index_t       min  = 100;     /*  min size */
	static index_t       max  = 1500;    /*  max size (not included) */
	static index_t       step = 300;    /*  step between 2 sizes */
	// static std::list<int> lst  ;       /*  what bench to start ? */
	// lst.push_front(1);// ={1,2} vivement le nouveau std...
	// lst.push_front(2);

	static Argument as[] = {
		{ 'm', "-m min" , "Set minimal size of matrix to test."    , TYPE_INT , &min },
		{ 'M', "-M Max" , "Set maximal size."                      , TYPE_INT , &max },
		{ 's', "-s step", "Sets the gap between two matrix sizes.", TYPE_INT , &step },
		// { 'l', "-l list", "Only launches a subset of available benchmarks\n - 1: compare to raw blas\n - 2:various square sizes\n - 3:various shapes\n - 4: various parameters (a,b)\n - 5 : various transp. combinations", TYPE_INTLIST, &lst },
		END_OF_ARGUMENTS
	};

	parseArguments (ac, av, as);

	if (min >= max) {
		throw LinBoxError("min value should be smaller than max...");
	}
	if (min + step >= max) {
		std::cout << "Warning : your x axis has only one point. You should have a smaller step." << std::endl;
	}

	/* square for various fields */
	{
		std::cout << " *** Lines plot *** " << std::endl;
		std::cout << "Benchmark square matrix multiplication via BMD.mul()" << std::endl;
		bench_square(min,max,step,13);
	}

	/* different sparse matrix   */

	{
		std::cout << " *** Bar plot *** " << std::endl;
		std::cout << "Benchmark different matrices on different rank algorithms" << std::endl;
		bench_rank(13);
	}

	return EXIT_SUCCESS ;
}

// Local Variables:
// mode: C++
// tab-width: 8
// indent-tabs-mode: nil
// c-basic-offset: 8
// End:
// vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s
<|endoftext|>


<commit_before>#pragma once

#include <DO/Core/Pixel/ChannelConversion.hpp>

namespace DO {

  //! \defgroup ColorTypes Color typedefs
  //! @{

  // ======================================================================== //
  //! Macro for generic color typedefs like in OpenGL.
#define DEFINE_GENERIC_COLOR_TYPEDEFS(N)            \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<unsigned char, N, 1> Color##N##ub; \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<char, N, 1> Color##N##b;           \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<unsigned short, N, 1> Color##N##us;\
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<short, N, 1> Color##N##s;          \
  /*! \brief Color{NumChannels}{ChannelType}. */    \
  typedef Matrix<unsigned int, N, 1> Color##N##ui;  \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<int, N, 1> Color##N##i;            \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<float, N, 1> Color##N##f;          \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<double, N, 1> Color##N##d;

  DEFINE_GENERIC_COLOR_TYPEDEFS(3)
  DEFINE_GENERIC_COLOR_TYPEDEFS(4)
#undef DEFINE_GENERIC_COLOR_TYPEDEFS

  // ======================================================================== //
  //! Macro for color typedefs.
#define DEFINE_COLOR_TYPES(colorspace)                      \
  /*! \brief {ColorSpace}{BitDepthPerChannel} */            \
  typedef Pixel<unsigned char, colorspace> colorspace##8;   \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<unsigned short, colorspace> colorspace##16; \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<unsigned int, colorspace> colorspace##32;   \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<char, colorspace> colorspace##8s;           \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<short, colorspace> colorspace##16s;         \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<int, colorspace> colorspace##32s;           \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<float, colorspace> colorspace##32f;         \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<double, colorspace> colorspace##64f;

  DEFINE_COLOR_TYPES(Rgb)
  DEFINE_COLOR_TYPES(Rgba)
  DEFINE_COLOR_TYPES(Yuv)
#undef DEFINE_COLOR_TYPES

  //! @} ColorTypes

  // ======================================================================== //
  //! \defgroup PrimaryColors Primary Colors in RGB.
  //! @{

  //! White color function.
  template <typename T> inline Matrix<T, 3, 1> white()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_max_value<T>(),
      channel_max_value<T>() );
  }
  //! Black color function.
  template <typename T> inline Matrix<T, 3, 1> black()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_min_value<T>(),
      channel_min_value<T>() );
  }
  //! Red color function.
  template <typename T> inline Matrix<T, 3, 1> red()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_min_value<T>(),
      channel_min_value<T>() );
  }
  //! Green color function.
  template <typename T> inline Matrix<T, 3, 1> green()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_max_value<T>(),
      channel_min_value<T>() );
  }
  //! Blue color function.
  template <typename T> inline Matrix<T, 3, 1> blue()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_min_value<T>(),
      channel_max_value<T>() );
  }
  //! Cyan color function.
  template <typename T> inline Matrix<T, 3, 1> cyan()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_max_value<T>(),
      channel_max_value<T>() );
  }
  //! Yellow color function.
  template <typename T> inline Matrix<T, 3, 1> yellow()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_max_value<T>(),
      channel_min_value<T>() );
  }
  //! Magenta color function.
  template <typename T> inline Matrix<T, 3, 1> magenta()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_min_value<T>(),
      channel_max_value<T>() );
  }

  //! Primary color definition.
#define DEFINE_COLOR_CONSTANT(Name, function)       \
  /*! \brief Return primary color of type Rgb8. */  \
  const Rgb8 Name##8(function<unsigned char>());    \
  /*! \brief Return primary color of type Rgb8s. */ \
  const Rgb8s Name##8s(function<char>());           \
  /*! \brief Return primary color of type Rgb16. */ \
  const Rgb16 Name##16(function<unsigned short>()); \
  /*! \brief Return primary color of type Rgb16s. */\
  const Rgb16s Name##16s(function<short>());        \
  /*! \brief Return primary color of type Rgb32. */ \
  const Rgb32 Name##32(function<unsigned int>());   \
  /*! \brief Return primary color of type Rgb32s. */\
  const Rgb32s Name##32s(function<int>());          \
  /*! \brief Return primary color of type Rgb32f. */\
  const Rgb32f Name##32f(function<float>());        \
  /*! \brief Return primary color of type Rgb64f. */\
  const Rgb64f Name##64f(function<double>());

  DEFINE_COLOR_CONSTANT(Red, red)
  DEFINE_COLOR_CONSTANT(Green, green)
  DEFINE_COLOR_CONSTANT(Blue, blue)
  DEFINE_COLOR_CONSTANT(Cyan, cyan)
  DEFINE_COLOR_CONSTANT(Magenta, magenta)
  DEFINE_COLOR_CONSTANT(Yellow, yellow)
  DEFINE_COLOR_CONSTANT(Black, black)
  DEFINE_COLOR_CONSTANT(White, white)
#undef DEFINE_COLOR_CONSTANT

  //! @}

} /* namespace DO */<commit_msg>Add missing header inclusion to file 'Typedefs.hpp'.<commit_after>#pragma once

#include <DO/Core/Pixel/ChannelConversion.hpp>
#include <DO/Core/Pixel/ColorSpace.hpp>
#include <DO/Core/Pixel/Pixel.hpp>

namespace DO {

  //! \defgroup ColorTypes Color typedefs
  //! @{

  // ======================================================================== //
  //! Macro for generic color typedefs like in OpenGL.
#define DEFINE_GENERIC_COLOR_TYPEDEFS(N)            \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<unsigned char, N, 1> Color##N##ub; \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<char, N, 1> Color##N##b;           \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<unsigned short, N, 1> Color##N##us;\
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<short, N, 1> Color##N##s;          \
  /*! \brief Color{NumChannels}{ChannelType}. */    \
  typedef Matrix<unsigned int, N, 1> Color##N##ui;  \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<int, N, 1> Color##N##i;            \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<float, N, 1> Color##N##f;          \
  /*! \brief Color{NumChannels}{ChannelType} */     \
  typedef Matrix<double, N, 1> Color##N##d;

  DEFINE_GENERIC_COLOR_TYPEDEFS(3)
  DEFINE_GENERIC_COLOR_TYPEDEFS(4)
#undef DEFINE_GENERIC_COLOR_TYPEDEFS

  // ======================================================================== //
  //! Macro for color typedefs.
#define DEFINE_COLOR_TYPES(colorspace)                      \
  /*! \brief {ColorSpace}{BitDepthPerChannel} */            \
  typedef Pixel<unsigned char, colorspace> colorspace##8;   \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<unsigned short, colorspace> colorspace##16; \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<unsigned int, colorspace> colorspace##32;   \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<char, colorspace> colorspace##8s;           \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<short, colorspace> colorspace##16s;         \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<int, colorspace> colorspace##32s;           \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<float, colorspace> colorspace##32f;         \
  /*! \brief {PixelSpace}{BitDepthPerChannel} */            \
  typedef Pixel<double, colorspace> colorspace##64f;

  DEFINE_COLOR_TYPES(Rgb)
  DEFINE_COLOR_TYPES(Rgba)
  DEFINE_COLOR_TYPES(Yuv)
#undef DEFINE_COLOR_TYPES

  //! @} ColorTypes

  // ======================================================================== //
  //! \defgroup PrimaryColors Primary Colors in RGB.
  //! @{

  //! White color function.
  template <typename T> inline Matrix<T, 3, 1> white()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_max_value<T>(),
      channel_max_value<T>() );
  }
  //! Black color function.
  template <typename T> inline Matrix<T, 3, 1> black()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_min_value<T>(),
      channel_min_value<T>() );
  }
  //! Red color function.
  template <typename T> inline Matrix<T, 3, 1> red()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_min_value<T>(),
      channel_min_value<T>() );
  }
  //! Green color function.
  template <typename T> inline Matrix<T, 3, 1> green()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_max_value<T>(),
      channel_min_value<T>() );
  }
  //! Blue color function.
  template <typename T> inline Matrix<T, 3, 1> blue()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_min_value<T>(),
      channel_max_value<T>() );
  }
  //! Cyan color function.
  template <typename T> inline Matrix<T, 3, 1> cyan()
  {
    return Matrix<T,3,1>(
      channel_min_value<T>(),
      channel_max_value<T>(),
      channel_max_value<T>() );
  }
  //! Yellow color function.
  template <typename T> inline Matrix<T, 3, 1> yellow()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_max_value<T>(),
      channel_min_value<T>() );
  }
  //! Magenta color function.
  template <typename T> inline Matrix<T, 3, 1> magenta()
  {
    return Matrix<T,3,1>(
      channel_max_value<T>(),
      channel_min_value<T>(),
      channel_max_value<T>() );
  }

  //! Primary color definition.
#define DEFINE_COLOR_CONSTANT(Name, function)       \
  /*! \brief Return primary color of type Rgb8. */  \
  const Rgb8 Name##8(function<unsigned char>());    \
  /*! \brief Return primary color of type Rgb8s. */ \
  const Rgb8s Name##8s(function<char>());           \
  /*! \brief Return primary color of type Rgb16. */ \
  const Rgb16 Name##16(function<unsigned short>()); \
  /*! \brief Return primary color of type Rgb16s. */\
  const Rgb16s Name##16s(function<short>());        \
  /*! \brief Return primary color of type Rgb32. */ \
  const Rgb32 Name##32(function<unsigned int>());   \
  /*! \brief Return primary color of type Rgb32s. */\
  const Rgb32s Name##32s(function<int>());          \
  /*! \brief Return primary color of type Rgb32f. */\
  const Rgb32f Name##32f(function<float>());        \
  /*! \brief Return primary color of type Rgb64f. */\
  const Rgb64f Name##64f(function<double>());

  DEFINE_COLOR_CONSTANT(Red, red)
  DEFINE_COLOR_CONSTANT(Green, green)
  DEFINE_COLOR_CONSTANT(Blue, blue)
  DEFINE_COLOR_CONSTANT(Cyan, cyan)
  DEFINE_COLOR_CONSTANT(Magenta, magenta)
  DEFINE_COLOR_CONSTANT(Yellow, yellow)
  DEFINE_COLOR_CONSTANT(Black, black)
  DEFINE_COLOR_CONSTANT(White, white)
#undef DEFINE_COLOR_CONSTANT

  //! @}

} /* namespace DO */<|endoftext|>


<commit_before><commit_msg>coverity#704894 Explicit NULL derefenced<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor a tiny bit of SwLayAction::IsShortCut<commit_after><|endoftext|>


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

#include "itrpaint.hxx"

class SwFlyCntPortion;
class SwInterHyphInfo;
class SwDropPortion;
class SwFmtDrop;
class SwDrawObjs;
class SwTxtAttr;
class SwNumberPortion;
class SwErgoSumPortion;
class SwExpandPortion;
class SwMultiPortion;
class SvLongs;

/*************************************************************************
 *                      class SwTxtFormatter
 *************************************************************************/

class SwTxtFormatter : public SwTxtPainter
{
    const SwFmtDrop *pDropFmt;
    SwMultiPortion* pMulti; // during formatting a multi-portion
    sal_uInt8 nCntEndHyph;  // zaehlt aufeinanderfolgende Hyphens am Zeilenende
    sal_uInt8 nCntMidHyph;  // zaehlt aufeinanderfolgende Hyphens vor Flies
    xub_StrLen nLeftScanIdx; // for increasing performance during
    xub_StrLen nRightScanIdx;     // scanning for portion ends
    sal_Bool bOnceMore : 1; // noch 'ne Runde?
    sal_Bool bFlyInCntBase : 1; // Base-Referenz der zeichengeb. Rahmen setzen
    sal_Bool bChanges : 1; // Flag, fuer die Berechnung des Repaint-Rechtecks
    sal_Bool bTruncLines : 1; // Flag, Repaint-Rechtecks ggf. erweitern
    sal_Bool bUnclipped : 1; // Flag, ob Repaint groesser als feste Zeilenhoehe
    SwLinePortion *NewPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion  *NewTxtPortion( SwTxtFormatInfo &rInf );
    SwLinePortion *NewExtraPortion( SwTxtFormatInfo &rInf );
    SwTabPortion *NewTabPortion( SwTxtFormatInfo &rInf, bool bAuto ) const;
    SwNumberPortion *NewNumberPortion( SwTxtFormatInfo &rInf ) const;
    SwDropPortion *NewDropPortion( SwTxtFormatInfo &rInf );
    SwNumberPortion *NewFtnNumPortion( SwTxtFormatInfo &rInf ) const;
    SwErgoSumPortion *NewErgoSumPortion( SwTxtFormatInfo &rInf ) const;
    SwExpandPortion *NewFldPortion( SwTxtFormatInfo &rInf,
                                    const SwTxtAttr *pHt ) const;
    SwFtnPortion *NewFtnPortion( SwTxtFormatInfo &rInf, SwTxtAttr *pHt );
    SwFlyCntPortion *NewFlyCntPortion( SwTxtFormatInfo &rInf,
                                       SwTxtAttr *pHt ) const;
    SwLinePortion *WhichFirstPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion *WhichTxtPor( SwTxtFormatInfo &rInf ) const;

    // Das Herzstueck der Formatierung
    void BuildPortions( SwTxtFormatInfo &rInf );
    BOOL BuildMultiPortion( SwTxtFormatInfo &rInf, SwMultiPortion& rMulti );

    // Berechnung des emulierten rechten Rands
    void CalcFlyWidth( SwTxtFormatInfo &rInf );

    // wird von SwTxtFormatter wegen UpdatePos ueberladen
    void CalcAdjustLine( SwLineLayout *pCurr );

    // consideres line spacing attributes
    void CalcRealHeight( sal_Bool bNewLine = sal_False );

    // uebertraegt die Daten nach rInf
    void FeedInf( SwTxtFormatInfo &rInf ) const;

    // behandelt die Unterlaufsituationen
    SwLinePortion *UnderFlow( SwTxtFormatInfo &rInf );

    // errechnet den Ascent und die Hoehe aus der Fontmetric
    void CalcAscent( SwTxtFormatInfo &rInf, SwLinePortion *pPor );

    // determines, if a optimized repaint rectange is allowed
    sal_Bool AllowRepaintOpt() const;

    // calculates and sets the optimized repaint offset
    long CalcOptRepaint( xub_StrLen nOldLineEnd, const SvLongs* pFlyStart );

    // wird von FormatLine gerufen.
    void FormatReset( SwTxtFormatInfo &rInf );

    // durch das Adjustment aendert sich die Position der Portions
    void UpdatePos( SwLineLayout *pCurr, Point aStart, xub_StrLen nStartIdx,
            sal_Bool bAllWays = sal_False ) const;

    // Setze alle FlyInCntFrms auf die uebergebene BaseLine
    void AlignFlyInCntBase( long nBaseLine ) const;

    // Unterlaufbedingungen bei Flys
    sal_Bool ChkFlyUnderflow( SwTxtFormatInfo &rInf ) const;

    // Portion einfuegen.
    void InsertPortion( SwTxtFormatInfo &rInf, SwLinePortion *pPor ) const;

    // schaetzt die Hoehe fuer die DropPortion
    void GuessDropHeight( const MSHORT nLines );

public:
    // errechnet die Hoehe fuer die DropPortion
    void CalcDropHeight( const MSHORT nLines );

    // errechnet den Bottom des Absatzes, beruecksichtigt an diesem verankerte
    // Objekte mit Umlauf 1. Absatz.
    SwTwips CalcBottomLine() const;

    // Beruecksichtigt zeichengebundene Objekte bei der Repaintrechteck-
    // berechnung in Zeilen mit fester Zeilenhoehe
    void CalcUnclipped( SwTwips& rTop, SwTwips& rBottom );

    // u.a. fuer DropCaps
    sal_Bool CalcOnceMore();

    void CtorInit( SwTxtFrm *pFrm, SwTxtFormatInfo *pInf );
    inline SwTxtFormatter( SwTxtFrm *pFrm, SwTxtFormatInfo *pInf )
           { CtorInit( pFrm, pInf ); }
    ~SwTxtFormatter();

    xub_StrLen FormatLine( const xub_StrLen nStart );

    void RecalcRealHeight();

    // Wir formatieren eine Zeile fuer die interaktive Trennung
    sal_Bool Hyphenate( SwInterHyphInfo &rInf );

    // Spezialmethode fuer QuoVadis-Texte
    // nErgo ist die Seitennummer der ErgoSum-Ftn
    // Bei 0 ist es noch unklar.
    xub_StrLen FormatQuoVadis( const xub_StrLen nStart );

    // Die Notbremse: Formatierung abbrechen, Zeile verwerfen.
    inline sal_Bool IsStop() const { return GetInfo().IsStop(); }

    // Das Gegenstueck: Formatierung unbedingt fortsetzen.
    inline sal_Bool IsNewLine() const { return GetInfo().IsNewLine(); }

    // FormatQuick(); auffrischen von Formatinformationen
    inline sal_Bool IsQuick() const { return GetInfo().IsQuick(); }

    // erzeugt ggfs. ein SwLineLayout, dass Ftn/Fly--Oszillation unterbindet.
    void MakeDummyLine();

    // SwTxtIter-Funktionalitaet
    void Insert( SwLineLayout *pLine );

    // die noch verbleibende Hoehe bis zum Seitenrand
    KSHORT GetFrmRstHeight() const;

    // Wie breit waerest Du ohne rechte Begrenzungen (Flys etc.)?
    KSHORT _CalcFitToContent( );

    SwLinePortion* MakeRestPortion(const SwLineLayout* pLine, xub_StrLen nPos);

    inline const SwFmtDrop *GetDropFmt() const { return pDropFmt; }
    inline void ClearDropFmt() { pDropFmt = 0; }

    inline SwMultiPortion *GetMulti() const { return pMulti; }

    inline const sal_Bool IsOnceMore() const { return bOnceMore; }
    inline void       SetOnceMore( sal_Bool bNew ) { bOnceMore = bNew; }

    inline const sal_Bool HasChanges() const { return bChanges; }
    inline void       SetChanges()       { bChanges = sal_True; }

    inline const sal_Bool HasTruncLines() const { return bTruncLines; }
    inline void       SetTruncLines( sal_Bool bNew ) { bTruncLines = bNew; }

    inline const sal_Bool IsUnclipped() const { return bUnclipped; }
    inline void       SetUnclipped( sal_Bool bNew ) { bUnclipped = bNew; }

    inline const sal_Bool IsFlyInCntBase() const { return bFlyInCntBase; }
    inline void  SetFlyInCntBase( sal_Bool bNew = sal_True ){ bFlyInCntBase = bNew; }

    inline SwTxtFormatInfo &GetInfo()
        { return (SwTxtFormatInfo&)SwTxtIter::GetInfo(); }
    inline const SwTxtFormatInfo &GetInfo() const
        { return (const SwTxtFormatInfo&)SwTxtIter::GetInfo(); }

    inline void InitCntHyph() { CntHyphens( nCntEndHyph, nCntMidHyph ); }
    inline const sal_uInt8 &CntEndHyph() const { return nCntEndHyph; }
    inline const sal_uInt8 &CntMidHyph() const { return nCntMidHyph; }
    inline sal_uInt8 &CntEndHyph() { return nCntEndHyph; }
    inline sal_uInt8 &CntMidHyph() { return nCntMidHyph; }
};

#endif
<commit_msg>INTEGRATION: CWS swobjpos04 (1.12.60); FILE MERGED 2004/05/07 15:23:47 od 1.12.60.1: #i28701# - usage of new class <SwSortedObjs><commit_after>/*************************************************************************
 *
 *  $RCSfile: itrform2.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-02 14:15:18 $
 *
 *  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 _ITRFORM2_HXX
#define _ITRFORM2_HXX

#include "itrpaint.hxx"

class SwFlyCntPortion;
class SwInterHyphInfo;
class SwDropPortion;
class SwFmtDrop;
class SwTxtAttr;
class SwNumberPortion;
class SwErgoSumPortion;
class SwExpandPortion;
class SwMultiPortion;
class SvLongs;

/*************************************************************************
 *                      class SwTxtFormatter
 *************************************************************************/

class SwTxtFormatter : public SwTxtPainter
{
    const SwFmtDrop *pDropFmt;
    SwMultiPortion* pMulti; // during formatting a multi-portion
    sal_uInt8 nCntEndHyph;  // zaehlt aufeinanderfolgende Hyphens am Zeilenende
    sal_uInt8 nCntMidHyph;  // zaehlt aufeinanderfolgende Hyphens vor Flies
    xub_StrLen nLeftScanIdx; // for increasing performance during
    xub_StrLen nRightScanIdx;     // scanning for portion ends
    sal_Bool bOnceMore : 1; // noch 'ne Runde?
    sal_Bool bFlyInCntBase : 1; // Base-Referenz der zeichengeb. Rahmen setzen
    sal_Bool bChanges : 1; // Flag, fuer die Berechnung des Repaint-Rechtecks
    sal_Bool bTruncLines : 1; // Flag, Repaint-Rechtecks ggf. erweitern
    sal_Bool bUnclipped : 1; // Flag, ob Repaint groesser als feste Zeilenhoehe
    SwLinePortion *NewPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion  *NewTxtPortion( SwTxtFormatInfo &rInf );
    SwLinePortion *NewExtraPortion( SwTxtFormatInfo &rInf );
    SwTabPortion *NewTabPortion( SwTxtFormatInfo &rInf, bool bAuto ) const;
    SwNumberPortion *NewNumberPortion( SwTxtFormatInfo &rInf ) const;
    SwDropPortion *NewDropPortion( SwTxtFormatInfo &rInf );
    SwNumberPortion *NewFtnNumPortion( SwTxtFormatInfo &rInf ) const;
    SwErgoSumPortion *NewErgoSumPortion( SwTxtFormatInfo &rInf ) const;
    SwExpandPortion *NewFldPortion( SwTxtFormatInfo &rInf,
                                    const SwTxtAttr *pHt ) const;
    SwFtnPortion *NewFtnPortion( SwTxtFormatInfo &rInf, SwTxtAttr *pHt );
    SwFlyCntPortion *NewFlyCntPortion( SwTxtFormatInfo &rInf,
                                       SwTxtAttr *pHt ) const;
    SwLinePortion *WhichFirstPortion( SwTxtFormatInfo &rInf );
    SwTxtPortion *WhichTxtPor( SwTxtFormatInfo &rInf ) const;

    // Das Herzstueck der Formatierung
    void BuildPortions( SwTxtFormatInfo &rInf );
    BOOL BuildMultiPortion( SwTxtFormatInfo &rInf, SwMultiPortion& rMulti );

    // Berechnung des emulierten rechten Rands
    void CalcFlyWidth( SwTxtFormatInfo &rInf );

    // wird von SwTxtFormatter wegen UpdatePos ueberladen
    void CalcAdjustLine( SwLineLayout *pCurr );

    // consideres line spacing attributes
    void CalcRealHeight( sal_Bool bNewLine = sal_False );

    // uebertraegt die Daten nach rInf
    void FeedInf( SwTxtFormatInfo &rInf ) const;

    // behandelt die Unterlaufsituationen
    SwLinePortion *UnderFlow( SwTxtFormatInfo &rInf );

    // errechnet den Ascent und die Hoehe aus der Fontmetric
    void CalcAscent( SwTxtFormatInfo &rInf, SwLinePortion *pPor );

    // determines, if a optimized repaint rectange is allowed
    sal_Bool AllowRepaintOpt() const;

    // calculates and sets the optimized repaint offset
    long CalcOptRepaint( xub_StrLen nOldLineEnd, const SvLongs* pFlyStart );

    // wird von FormatLine gerufen.
    void FormatReset( SwTxtFormatInfo &rInf );

    // durch das Adjustment aendert sich die Position der Portions
    void UpdatePos( SwLineLayout *pCurr, Point aStart, xub_StrLen nStartIdx,
            sal_Bool bAllWays = sal_False ) const;

    // Setze alle FlyInCntFrms auf die uebergebene BaseLine
    void AlignFlyInCntBase( long nBaseLine ) const;

    // Unterlaufbedingungen bei Flys
    sal_Bool ChkFlyUnderflow( SwTxtFormatInfo &rInf ) const;

    // Portion einfuegen.
    void InsertPortion( SwTxtFormatInfo &rInf, SwLinePortion *pPor ) const;

    // schaetzt die Hoehe fuer die DropPortion
    void GuessDropHeight( const MSHORT nLines );

public:
    // errechnet die Hoehe fuer die DropPortion
    void CalcDropHeight( const MSHORT nLines );

    // errechnet den Bottom des Absatzes, beruecksichtigt an diesem verankerte
    // Objekte mit Umlauf 1. Absatz.
    SwTwips CalcBottomLine() const;

    // Beruecksichtigt zeichengebundene Objekte bei der Repaintrechteck-
    // berechnung in Zeilen mit fester Zeilenhoehe
    void CalcUnclipped( SwTwips& rTop, SwTwips& rBottom );

    // u.a. fuer DropCaps
    sal_Bool CalcOnceMore();

    void CtorInit( SwTxtFrm *pFrm, SwTxtFormatInfo *pInf );
    inline SwTxtFormatter( SwTxtFrm *pFrm, SwTxtFormatInfo *pInf )
           { CtorInit( pFrm, pInf ); }
    ~SwTxtFormatter();

    xub_StrLen FormatLine( const xub_StrLen nStart );

    void RecalcRealHeight();

    // Wir formatieren eine Zeile fuer die interaktive Trennung
    sal_Bool Hyphenate( SwInterHyphInfo &rInf );

    // Spezialmethode fuer QuoVadis-Texte
    // nErgo ist die Seitennummer der ErgoSum-Ftn
    // Bei 0 ist es noch unklar.
    xub_StrLen FormatQuoVadis( const xub_StrLen nStart );

    // Die Notbremse: Formatierung abbrechen, Zeile verwerfen.
    inline sal_Bool IsStop() const { return GetInfo().IsStop(); }

    // Das Gegenstueck: Formatierung unbedingt fortsetzen.
    inline sal_Bool IsNewLine() const { return GetInfo().IsNewLine(); }

    // FormatQuick(); auffrischen von Formatinformationen
    inline sal_Bool IsQuick() const { return GetInfo().IsQuick(); }

    // erzeugt ggfs. ein SwLineLayout, dass Ftn/Fly--Oszillation unterbindet.
    void MakeDummyLine();

    // SwTxtIter-Funktionalitaet
    void Insert( SwLineLayout *pLine );

    // die noch verbleibende Hoehe bis zum Seitenrand
    KSHORT GetFrmRstHeight() const;

    // Wie breit waerest Du ohne rechte Begrenzungen (Flys etc.)?
    KSHORT _CalcFitToContent( );

    SwLinePortion* MakeRestPortion(const SwLineLayout* pLine, xub_StrLen nPos);

    inline const SwFmtDrop *GetDropFmt() const { return pDropFmt; }
    inline void ClearDropFmt() { pDropFmt = 0; }

    inline SwMultiPortion *GetMulti() const { return pMulti; }

    inline const sal_Bool IsOnceMore() const { return bOnceMore; }
    inline void       SetOnceMore( sal_Bool bNew ) { bOnceMore = bNew; }

    inline const sal_Bool HasChanges() const { return bChanges; }
    inline void       SetChanges()       { bChanges = sal_True; }

    inline const sal_Bool HasTruncLines() const { return bTruncLines; }
    inline void       SetTruncLines( sal_Bool bNew ) { bTruncLines = bNew; }

    inline const sal_Bool IsUnclipped() const { return bUnclipped; }
    inline void       SetUnclipped( sal_Bool bNew ) { bUnclipped = bNew; }

    inline const sal_Bool IsFlyInCntBase() const { return bFlyInCntBase; }
    inline void  SetFlyInCntBase( sal_Bool bNew = sal_True ){ bFlyInCntBase = bNew; }

    inline SwTxtFormatInfo &GetInfo()
        { return (SwTxtFormatInfo&)SwTxtIter::GetInfo(); }
    inline const SwTxtFormatInfo &GetInfo() const
        { return (const SwTxtFormatInfo&)SwTxtIter::GetInfo(); }

    inline void InitCntHyph() { CntHyphens( nCntEndHyph, nCntMidHyph ); }
    inline const sal_uInt8 &CntEndHyph() const { return nCntEndHyph; }
    inline const sal_uInt8 &CntMidHyph() const { return nCntMidHyph; }
    inline sal_uInt8 &CntEndHyph() { return nCntEndHyph; }
    inline sal_uInt8 &CntMidHyph() { return nCntMidHyph; }
};

#endif
<|endoftext|>


<commit_before><commit_msg>Rework some loops<commit_after><|endoftext|>


<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program 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 General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include <e32cmn.h>
#include <e32des8.h>
#include <e32def.h>
#include <e32std.h>

#include "base/fscapi.h"
#include "base/Log.h"
#include "base/util/utils.h"
#include "base/util/symbianUtils.h"
#include "base/globalsdef.h"

BEGIN_NAMESPACE

wchar_t * wcsncpy (wchar_t *dst, const wchar_t *src, size_t count) {
    memcpy(dst, src, count * sizeof(wchar_t));
    return dst;
}

int towlower(int c) {
    wchar_t tmpStr[2];
    tmpStr[0] = (wchar_t)c;
    tmpStr[1] = 0;
    TBuf16<1> buf = (const TUint16*)tmpStr;
    buf.LowerCase();
    const TUint16* resStr = buf.Ptr();
    return (int)*resStr;
}

int towupper(int c)  {
    wchar_t tmpStr[2];
    tmpStr[1] = 0;
    tmpStr[0] = (wchar_t)c;
    TBuf16<1> buf = (const TUint16*)tmpStr;
    buf.UpperCase();
    const TUint16* resStr = buf.Ptr();
    return (int)*resStr;
}

static size_t estimateMaxSize(const char* format, PLATFORM_VA_LIST ap) {

    const char* p = format;
    size_t maxSize = strlen(format);
    while (*p) {
        if (*p == '%') {
            ++p;
            // We may have a precision or width here and we must skip it
            while ((*p) >= '0' && (*p) <= '9') {
                ++p;
            }
            char type = *p;
            switch (type) {
                case 'd':
                case 'i':
                case 'u':
                {
                    maxSize += 10;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 's':
                {
                    char* s = PLATFORM_VA_ARG(ap, char*);
                    maxSize += strlen(s);
                    break;
                }
                case 'b':
                {
                    maxSize += 32 * 8 + 2;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'x':
                {
                    maxSize += 32 + 2;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'o':
                {
                    maxSize += 32 * 2 + 2;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'c':
                {
                    maxSize += 1;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'L':
                case 'l':
                {
                    if (*(p+1) == 's') {
                        // Symbian does not support %ls because the underlying
                        // FormatList does not support it.
                        // To avoid problems we do not print this string, as we
                        // do not have an easy way of doing it
                        return -2;
                    } else {
                        maxSize += 20;
                        PLATFORM_VA_ARG(ap, int64_t);
                    }
                    break;
                }
                default:
                {
                    // Floating point cases...
                    maxSize += 50;
                }
            }
        }
        ++p;
    }
    return maxSize;
}

static char* translateFormat(const char* format) {
    char* ret     = new char[strlen(format) + 1];
    char* p       = ret;
    const char* q = format;

    while (*q) {
        if (*q == '%') {
            q++;
            // We may have a precision or width here and we must just copy it
            while ((*q) >= '0' && (*q) <= '9') {
                *(p++) = *(q++);
            }
            char fmt = *q;
            *(p++) = '%';
            switch (fmt) {
                case 'l':
                {
                    q++;
                    if (*q == 'l') {
                        *p = 'L';
                        q++;
                        p++;
                    }
                    *p = *q;
                    break;
                }
                default:
                {
                    *p = fmt;
                }
            }
        } else {
            *p = *q;
        }
        ++q;
        ++p;
    }
    *p = NULL;
    return ret;
}

size_t vsnprintf(char* s, size_t size, const char* format, PLATFORM_VA_LIST aq) {

    char* newFormat = translateFormat(format);
    TPtrC8 formatBuf((unsigned char*)newFormat);
    TInt error;
    RBuf8 formattedBuf;
    PLATFORM_VA_LIST aqCopy;
    size_t finalSize = (size_t)-1;

#ifdef va_copy
        PLATFORM_VA_COPY(aqCopy, aq);
#else
        aqCopy = aq;
#endif

    size_t estimatedSize = estimateMaxSize(format, aqCopy);

    // Handle errors
    if (estimatedSize == -2) {
        // The string contains formats which are not supported
        // and we cannot print the string
        char* replaceMsg = "Symbian does not support %ls";
        int   replaceMsgLen = strlen(replaceMsg);
        if (replaceMsgLen < size) {
            memcpy(s, replaceMsg, replaceMsgLen);
            s[replaceMsgLen-1] = (char)0;
            return replaceMsgLen;
        } else {
            memcpy(s, replaceMsg, size);
            if (size > 1) {
                s[size-1] = (char)0;
                return size-1;
            } else {
                return 0;
            }
        }
    }

    if (estimatedSize > size) {
        finalSize = estimatedSize;
    } else {
        TRAP(error, formattedBuf.CreateL(size));
        if (error == KErrNone) {
            TRAP(error, formattedBuf.FormatList(formatBuf, aq));
            if (error == KErrNone) {
                char* ptr = (char *) formattedBuf.Ptr();
                finalSize = formattedBuf.Length();
                if (finalSize < size) {
                    memcpy(s, ptr, finalSize);
                    s[finalSize] = (char)0;           // Symbian descriptors don't have the trailing null char
                } else {
                    // In this case we truncate. We signal this by returning -1
                    memcpy(s, ptr, size);
                    if (size) {
                        s[size-1] = (char)0;
                    }
                    finalSize = (size_t)-1;
                }
            }
        }
    }

    delete newFormat;
    return finalSize;
}

// TODO: convert to the specified encoding, assuming wc is UTF-8
char* toMultibyte(const WCHAR *wc, const char *encoding)
{
#ifdef USE_WCHAR
    size_t length = wcstombs(NULL, wc, 0) + 1;
    if(length == (size_t)-1) {
        //LOG.error("toMultibyte: invalid string.");
        return strdup("");
    }
    char* ret = new char[length];
    wcstombs(ret, wc, length);

    return ret;
#else
    return stringdup(wc);
#endif
}

// TODO: convert to UTF-8 from the specified encoding
WCHAR* toWideChar(const char *mb, const char *encoding)
{
#ifdef USE_WCHAR
    size_t length = mbstowcs(NULL, mb, 0) + 1;
    if(length == (size_t)-1) {
        //LOG.error("toWideChar: invalid string.");
        return wstrdup(TEXT(""));
    }
    WCHAR* ret = new WCHAR[length];
    mbstowcs(ret, mb, length);

    return ret;
#else
    return stringdup(mb);
#endif
}

size_t snwprintf(WCHAR *v, size_t size, const WCHAR* format, unsigned long value) {

    TPtrC16 formatBuf((const TUint16*)format);
    TInt error;
    RBuf16 formattedBuf;

    TRAP(error, formattedBuf.CreateL(size));
    if (error == KErrNone) {
        TRAP(error, formattedBuf.Format(formatBuf, value));
        if (error == KErrNone) {
            WCHAR* ptr = (WCHAR *) formattedBuf.Ptr();
            size_t finalSize = formattedBuf.Length() * sizeof(WCHAR);
            if (finalSize < size) {
                memcpy(v, ptr, finalSize);
                v[finalSize] = 0;   // Symbian descriptors don't have the trailing null char
                return finalSize;
            } else {
                // In this case we truncate. We signal this by returning -1
                memcpy(v, ptr, size);
                v[size] = 0;   // Symbian descriptors don't have the trailing null char
                return (size_t)-1;
            }
        }
    }
    // We cannot format the string. Return -1.
    return (size_t)-1;
}

bool saveFile(const char *filename, const char *buffer, size_t len, bool binary)
{
    const char *mode = binary ? "wb" : "w" ;

    FILE *f = fopen(filename, "w");

    if(!f)
        return false;

    if (fwrite(buffer, sizeof(char), len, f) != len) {
        fclose(f);
        return false;
    }
    fclose(f);

    return true;
}

bool readFile(const char* path, char **message, size_t *len, bool binary)
{
    FILE *f = NULL;
    size_t msglen=0;
    char *msg=0;
    const char *mode = binary ? "rb" : "r" ;
    bool res = false;
    size_t read = 0;

    *len = 0;
    f = fopen(path, mode);
    if ( !f ) {
        goto done;
    }

    // Get file length
    fseek(f, 0, SEEK_END);
    msglen = (size_t)ftell(f);
    fseek(f, 0, SEEK_SET);

    msg = new char[msglen+1];
    if (!msg) {
        goto done;
    }

    while (read < msglen) {
        read += fread(msg + read, sizeof(char), 256, f);
        if (ferror(f)) {
            goto done;
        }
    }
    if (read != msglen) {
        goto done;
    }

    *len = msglen;
    msg[msglen] = 0;

    // Set return parameters
    *message=msg;
    msg = 0;
    res = true;

  done:
    if (f) {
        fclose(f);
    }
    if (msg) {
        delete [] msg;
    }

    return res;
}

WCHAR *wcschr(const WCHAR *ws, WCHAR wc) {
    LOG.error("***** wcschr not implemented *****");
    return NULL;
}

WCHAR *wcsstr(WCHAR *ws1, WCHAR *ws2) {
    LOG.error("***** wcsstr not implemented *****");
    return NULL;
}

WCHAR *wcstok(WCHAR *ws1, const WCHAR *ws2) {
    LOG.error("***** wcstok not implemented *****");
    return NULL;
}

WCHAR *wcsncat(WCHAR *ws1, const WCHAR *ws2, size_t n) {
    LOG.error("***** wcsncat not implemented *****");
    return NULL;
}

double wcstod(const WCHAR *nptr, WCHAR **endptr) {
    LOG.error("***** wcstod not implemented *****");
    return 0.0;
}

int _wtoi(const WCHAR *str) {
    LOG.error("***** _wtoi not implemented *****");
    return 0;
}

StringBuffer getCacheDirectory() {
    StringBuffer empty;
    return empty;
}

END_NAMESPACE

<commit_msg>Bug fixed in vsnprintf.<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program 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 General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include <e32cmn.h>
#include <e32des8.h>
#include <e32def.h>
#include <e32std.h>

#include "base/fscapi.h"
#include "base/Log.h"
#include "base/util/utils.h"
#include "base/util/symbianUtils.h"
#include "base/globalsdef.h"

BEGIN_NAMESPACE

wchar_t * wcsncpy (wchar_t *dst, const wchar_t *src, size_t count) {
    memcpy(dst, src, count * sizeof(wchar_t));
    return dst;
}

int towlower(int c) {
    wchar_t tmpStr[2];
    tmpStr[0] = (wchar_t)c;
    tmpStr[1] = 0;
    TBuf16<1> buf = (const TUint16*)tmpStr;
    buf.LowerCase();
    const TUint16* resStr = buf.Ptr();
    return (int)*resStr;
}

int towupper(int c)  {
    wchar_t tmpStr[2];
    tmpStr[1] = 0;
    tmpStr[0] = (wchar_t)c;
    TBuf16<1> buf = (const TUint16*)tmpStr;
    buf.UpperCase();
    const TUint16* resStr = buf.Ptr();
    return (int)*resStr;
}

static size_t estimateMaxSize(const char* format, PLATFORM_VA_LIST ap) {

    const char* p = format;
    size_t maxSize = strlen(format);
    while (*p) {
        if (*p == '%') {
            ++p;
            // We may have a precision or width here and we must skip it
            char number[16];
            int idx = 0;
            while ((*p) >= '0' && (*p) <= '9') {
                number[idx++] = *p;
                ++p;
            }
            number[idx] = (char)0;
            char type = *p;
            switch (type) {
                case 'd':
                case 'i':
                case 'u':
                {
                    maxSize += 10;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 's':
                {
                    char* s = PLATFORM_VA_ARG(ap, char*);
                    int len = 0;
                    if (s) {
                        len = strlen(s);
                    }
                    int align = atoi(number);
                    maxSize += (len>align) ? len : align;
                    break;
                }
                case 'b':
                {
                    maxSize += 32 * 8 + 2;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'x':
                {
                    maxSize += 32 + 2;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'o':
                {
                    maxSize += 32 * 2 + 2;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'c':
                {
                    maxSize += 1;
                    PLATFORM_VA_ARG(ap, int32_t);
                    break;
                }
                case 'L':
                case 'l':
                {
                    if (*(p+1) == 's') {
                        // Symbian does not support %ls because the underlying
                        // FormatList does not support it.
                        // To avoid problems we do not print this string, as we
                        // do not have an easy way of doing it
                        return -2;
                    } else {
                        maxSize += 20;
                        PLATFORM_VA_ARG(ap, int64_t);
                    }
                    break;
                }
                default:
                {
                    // Floating point cases...
                    maxSize += 50;
                }
            }
        }
        ++p;
    }
    return maxSize;
}

static char* translateFormat(const char* format) {
    char* ret     = new char[strlen(format) + 1];
    char* p       = ret;
    const char* q = format;

    while (*q) {
        if (*q == '%') {
            q++;
            *(p++) = '%';
            // We may have a precision or width here and we must just copy it
            while ((*q) >= '0' && (*q) <= '9') {
                *(p++) = *(q++);
            }
            char fmt = *q;
            switch (fmt) {
                case 'l':
                {
                    q++;
                    if (*q == 'l') {
                        *p = 'L';
                        q++;
                        p++;
                    }
                    *p = *q;
                    break;
                }
                default:
                {
                    *p = fmt;
                }
            }
        } else {
            *p = *q;
        }
        ++q;
        ++p;
    }
    *p = NULL;
    return ret;
}

size_t vsnprintf(char* s, size_t size, const char* format, PLATFORM_VA_LIST aq) {

    char* newFormat = translateFormat(format);
    TPtrC8 formatBuf((unsigned char*)newFormat);
    TInt error;
    RBuf8 formattedBuf;
    PLATFORM_VA_LIST aqCopy;
    size_t finalSize = (size_t)-1;

#ifdef va_copy
        PLATFORM_VA_COPY(aqCopy, aq);
#else
        aqCopy = aq;
#endif

    size_t estimatedSize = estimateMaxSize(format, aqCopy);

    // Handle errors
    if (estimatedSize == -2) {
        // The string contains formats which are not supported
        // and we cannot print the string
        char* replaceMsg = "Symbian does not support %ls";
        int   replaceMsgLen = strlen(replaceMsg);
        if (replaceMsgLen < size) {
            memcpy(s, replaceMsg, replaceMsgLen);
            s[replaceMsgLen-1] = (char)0;
            return replaceMsgLen;
        } else {
            memcpy(s, replaceMsg, size);
            if (size > 1) {
                s[size-1] = (char)0;
                return size-1;
            } else {
                return 0;
            }
        }
    }

    if (estimatedSize > size) {
        finalSize = estimatedSize;
    } else {
        TRAP(error, formattedBuf.CreateL(size));
        if (error == KErrNone) {
            TRAP(error, formattedBuf.FormatList(formatBuf, aq));
            if (error == KErrNone) {
                char* ptr = (char *) formattedBuf.Ptr();
                finalSize = formattedBuf.Length();
                if (finalSize < size) {
                    memcpy(s, ptr, finalSize);
                    s[finalSize] = (char)0;           // Symbian descriptors don't have the trailing null char
                } else {
                    // In this case we truncate. We signal this by returning -1
                    memcpy(s, ptr, size);
                    if (size) {
                        s[size-1] = (char)0;
                    }
                    finalSize = (size_t)-1;
                }
            }
        }
    }

    delete newFormat;
    return finalSize;
}

// TODO: convert to the specified encoding, assuming wc is UTF-8
char* toMultibyte(const WCHAR *wc, const char *encoding)
{
#ifdef USE_WCHAR
    size_t length = wcstombs(NULL, wc, 0) + 1;
    if(length == (size_t)-1) {
        //LOG.error("toMultibyte: invalid string.");
        return strdup("");
    }
    char* ret = new char[length];
    wcstombs(ret, wc, length);

    return ret;
#else
    return stringdup(wc);
#endif
}

// TODO: convert to UTF-8 from the specified encoding
WCHAR* toWideChar(const char *mb, const char *encoding)
{
#ifdef USE_WCHAR
    size_t length = mbstowcs(NULL, mb, 0) + 1;
    if(length == (size_t)-1) {
        //LOG.error("toWideChar: invalid string.");
        return wstrdup(TEXT(""));
    }
    WCHAR* ret = new WCHAR[length];
    mbstowcs(ret, mb, length);

    return ret;
#else
    return stringdup(mb);
#endif
}

size_t snwprintf(WCHAR *v, size_t size, const WCHAR* format, unsigned long value) {

    TPtrC16 formatBuf((const TUint16*)format);
    TInt error;
    RBuf16 formattedBuf;

    TRAP(error, formattedBuf.CreateL(size));
    if (error == KErrNone) {
        TRAP(error, formattedBuf.Format(formatBuf, value));
        if (error == KErrNone) {
            WCHAR* ptr = (WCHAR *) formattedBuf.Ptr();
            size_t finalSize = formattedBuf.Length() * sizeof(WCHAR);
            if (finalSize < size) {
                memcpy(v, ptr, finalSize);
                v[finalSize] = 0;   // Symbian descriptors don't have the trailing null char
                return finalSize;
            } else {
                // In this case we truncate. We signal this by returning -1
                memcpy(v, ptr, size);
                v[size] = 0;   // Symbian descriptors don't have the trailing null char
                return (size_t)-1;
            }
        }
    }
    // We cannot format the string. Return -1.
    return (size_t)-1;
}

bool saveFile(const char *filename, const char *buffer, size_t len, bool binary)
{
    const char *mode = binary ? "wb" : "w" ;

    FILE *f = fopen(filename, "w");

    if(!f)
        return false;

    if (fwrite(buffer, sizeof(char), len, f) != len) {
        fclose(f);
        return false;
    }
    fclose(f);

    return true;
}

bool readFile(const char* path, char **message, size_t *len, bool binary)
{
    FILE *f = NULL;
    size_t msglen=0;
    char *msg=0;
    const char *mode = binary ? "rb" : "r" ;
    bool res = false;
    size_t read = 0;

    *len = 0;
    f = fopen(path, mode);
    if ( !f ) {
        goto done;
    }

    // Get file length
    fseek(f, 0, SEEK_END);
    msglen = (size_t)ftell(f);
    fseek(f, 0, SEEK_SET);

    msg = new char[msglen+1];
    if (!msg) {
        goto done;
    }

    while (read < msglen) {
        read += fread(msg + read, sizeof(char), 256, f);
        if (ferror(f)) {
            goto done;
        }
    }
    if (read != msglen) {
        goto done;
    }

    *len = msglen;
    msg[msglen] = 0;

    // Set return parameters
    *message=msg;
    msg = 0;
    res = true;

  done:
    if (f) {
        fclose(f);
    }
    if (msg) {
        delete [] msg;
    }

    return res;
}

WCHAR *wcschr(const WCHAR *ws, WCHAR wc) {
    LOG.error("***** wcschr not implemented *****");
    return NULL;
}

WCHAR *wcsstr(WCHAR *ws1, WCHAR *ws2) {
    LOG.error("***** wcsstr not implemented *****");
    return NULL;
}

WCHAR *wcstok(WCHAR *ws1, const WCHAR *ws2) {
    LOG.error("***** wcstok not implemented *****");
    return NULL;
}

WCHAR *wcsncat(WCHAR *ws1, const WCHAR *ws2, size_t n) {
    LOG.error("***** wcsncat not implemented *****");
    return NULL;
}

double wcstod(const WCHAR *nptr, WCHAR **endptr) {
    LOG.error("***** wcstod not implemented *****");
    return 0.0;
}

int _wtoi(const WCHAR *str) {
    LOG.error("***** _wtoi not implemented *****");
    return 0;
}

StringBuffer getCacheDirectory() {
    StringBuffer empty;
    return empty;
}

END_NAMESPACE

<|endoftext|>