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

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _CMDMAILMSG_HXX_
#include "cmdmailmsg.hxx"
#endif

//#############################################################
// <HACK> #110368#
// Mozilla and Co. expect file urls but not UTF8 encoded as we
// do but in the current system encoding, so we have to recode
// our file urls to this encoding
#ifndef _RTL_URI_H_
#include <rtl/uri.hxx>
#endif

#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif

/* a slightly modified version of Pchar in rtl/source/uri.c */
const sal_Bool uriCharClass[128] =
{
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Pchar but without encoding slashes */
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* !"#$%&'()*+,-./  */
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, /* 0123456789:;<=>? */
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* @ABCDEFGHIJKLMNO */
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* PQRSTUVWXYZ[\]^_ */
  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* `abcdefghijklmno */
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0  /* pqrstuvwxyz{|}~  */
};

//-------------------------------------
rtl::OUString reencode_file_url(
    const rtl::OUString& file_url,
    rtl_TextEncoding from_textenc,
    rtl_TextEncoding to_textenc)
{
    rtl::OUString tmp = rtl::Uri::decode(
        file_url, rtl_UriDecodeWithCharset, from_textenc);

    return rtl::Uri::encode(
        tmp, uriCharClass, rtl_UriEncodeIgnoreEscapes, to_textenc);
}

//-------------------------------------
void reencode_file_url_list(/*inout*/ com::sun::star::uno::Sequence<rtl::OUString>& file_url_list)
{
    sal_uInt32 nmax = file_url_list.getLength();
    for (sal_uInt32 i = 0; i < nmax; i++)
        file_url_list[i] = reencode_file_url(
            file_url_list[i], RTL_TEXTENCODING_UTF8, osl_getThreadTextEncoding());
}
//
// </HACK> #110368#
//#############################################################

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::lang::WrappedTargetException;
using com::sun::star::container::NoSuchElementException;
using com::sun::star::container::XNameAccess;
using rtl::OUString;
using osl::MutexGuard;

using namespace cppu;
using namespace com::sun::star::uno;

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

void SAL_CALL CmdMailMsg::setRecipient( const ::rtl::OUString& aRecipient )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_aRecipient = aRecipient;
}

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

::rtl::OUString SAL_CALL CmdMailMsg::getRecipient(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_aRecipient;
}

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

void SAL_CALL CmdMailMsg::setCcRecipient( const Sequence< OUString >& aCcRecipient )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_CcRecipients = aCcRecipient;
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getCcRecipient(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_CcRecipients;
}

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

void SAL_CALL CmdMailMsg::setBccRecipient( const Sequence< OUString >& aBccRecipient )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_BccRecipients = aBccRecipient;
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getBccRecipient(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_BccRecipients;
}

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

void SAL_CALL CmdMailMsg::setOriginator( const OUString& aOriginator )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_aOriginator = aOriginator;
}

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

OUString SAL_CALL CmdMailMsg::getOriginator(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_aOriginator;
}

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

void SAL_CALL CmdMailMsg::setSubject( const OUString& aSubject )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_aSubject = aSubject;
}

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

OUString SAL_CALL CmdMailMsg::getSubject(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_aSubject;
}

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

void SAL_CALL CmdMailMsg::setAttachement( const Sequence< ::rtl::OUString >& aAttachment )
    throw (IllegalArgumentException, RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_Attachments = aAttachment;

    //#######################################
    //#110368#
    reencode_file_url_list(m_Attachments);
    //#110368#
    //#######################################
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getAttachement(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_Attachments;
}

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

Any SAL_CALL CmdMailMsg::getByName( const OUString& aName )
    throw (NoSuchElementException, WrappedTargetException, RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    if( 0 == aName.compareToAscii( "from" ) &&  m_aOriginator.getLength() )
        return makeAny( m_aOriginator );

    else if( 0 == aName.compareToAscii( "to" ) &&  m_aRecipient.getLength() )
        return makeAny( m_aRecipient );

    else if( 0 == aName.compareToAscii( "cc" ) &&  m_CcRecipients.getLength() )
        return makeAny( m_CcRecipients );

    else if( 0 == aName.compareToAscii( "bcc" ) &&  m_BccRecipients.getLength() )
        return makeAny( m_BccRecipients );

    else if( 0 == aName.compareToAscii( "subject" ) &&  m_aSubject.getLength() )
        return makeAny( m_aSubject );

    else if( 0 == aName.compareToAscii( "attachment" ) &&  m_Attachments.getLength() )
        return makeAny( m_Attachments );

   throw NoSuchElementException( OUString::createFromAscii( "key not found: ") + aName,
        static_cast < XNameAccess * > (this) );
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getElementNames(  )
    throw (::com::sun::star::uno::RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    sal_Int32 nItems = 0;
    Sequence< OUString > aRet( 6 );

    if( m_aOriginator.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "from" );

    if( m_aRecipient.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "to" );

    if( m_CcRecipients.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "cc" );

    if( m_BccRecipients.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "bcc" );

    if( m_aSubject.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "subject" );

    if( m_Attachments.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "attachment" );

    aRet.realloc( nItems );
    return aRet;
}

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

 sal_Bool SAL_CALL CmdMailMsg::hasByName( const ::rtl::OUString& aName )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    if( 0 == aName.compareToAscii( "from" ) &&  m_aOriginator.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "to" ) &&  m_aRecipient.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "cc" ) &&  m_CcRecipients.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "bcc" ) &&  m_BccRecipients.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "subject" ) &&  m_aSubject.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "attachment" ) &&  m_Attachments.getLength() )
        return sal_True;

    return sal_False;
}

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

Type SAL_CALL CmdMailMsg::getElementType(  )
    throw (RuntimeException)
{
    // returning void for multi type container
    return Type();
}

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

sal_Bool SAL_CALL CmdMailMsg::hasElements(  )
    throw (RuntimeException)
{
    return 0 != getElementNames().getLength();
}
<commit_msg>INTEGRATION: CWS sb17 (1.2.100); FILE MERGED 2004/06/03 12:04:27 sb 1.2.100.2: #109735# Fixed typo. 2004/06/02 10:55:59 sb 1.2.100.1: #109735# Adapted to ExternalUriReferenceTranslator service.<commit_after>/*************************************************************************
 *
 *  $RCSfile: cmdmailmsg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-06-17 11:34:14 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

#ifndef _CMDMAILMSG_HXX_
#include "cmdmailmsg.hxx"
#endif

#ifndef _COM_SUN_STAR_URI_XEXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/XExternalUriReferenceTranslator.hpp>
#endif

#ifndef _COM_SUN_STAR_URI_EXTERNALURIREFERENCETRANSLATOR_HPP_
#include <com/sun/star/uri/ExternalUriReferenceTranslator.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

//------------------------------------------------------------------------
// namespace directives
//------------------------------------------------------------------------

using com::sun::star::lang::IllegalArgumentException;
using com::sun::star::lang::WrappedTargetException;
using com::sun::star::container::NoSuchElementException;
using com::sun::star::container::XNameAccess;
using rtl::OUString;
using osl::MutexGuard;

using namespace cppu;
using namespace com::sun::star::uno;

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

void SAL_CALL CmdMailMsg::setRecipient( const ::rtl::OUString& aRecipient )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_aRecipient = aRecipient;
}

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

::rtl::OUString SAL_CALL CmdMailMsg::getRecipient(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_aRecipient;
}

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

void SAL_CALL CmdMailMsg::setCcRecipient( const Sequence< OUString >& aCcRecipient )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_CcRecipients = aCcRecipient;
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getCcRecipient(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_CcRecipients;
}

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

void SAL_CALL CmdMailMsg::setBccRecipient( const Sequence< OUString >& aBccRecipient )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_BccRecipients = aBccRecipient;
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getBccRecipient(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_BccRecipients;
}

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

void SAL_CALL CmdMailMsg::setOriginator( const OUString& aOriginator )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_aOriginator = aOriginator;
}

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

OUString SAL_CALL CmdMailMsg::getOriginator(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_aOriginator;
}

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

void SAL_CALL CmdMailMsg::setSubject( const OUString& aSubject )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_aSubject = aSubject;
}

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

OUString SAL_CALL CmdMailMsg::getSubject(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_aSubject;
}

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

void SAL_CALL CmdMailMsg::setAttachement( const Sequence< ::rtl::OUString >& aAttachment )
    throw (IllegalArgumentException, RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    m_Attachments = aAttachment;
    sal_Int32 n = m_Attachments.getLength();
    if (n > 0) {
        Reference< com::sun::star::uri::XExternalUriReferenceTranslator >
            translator(
                com::sun::star::uri::ExternalUriReferenceTranslator::create(
                    m_xContext));
        for (sal_Int32 i = 0; i < n; ++i) {
            OUString external(
                translator->translateToExternal(m_Attachments[i]));
            if (external.getLength() == 0
                && m_Attachments[i].getLength() != 0)
            {
                throw RuntimeException(
                    (OUString(
                        RTL_CONSTASCII_USTRINGPARAM(
                            "Cannot translate URI reference to external"
                            " format: "))
                     + m_Attachments[i]),
                    static_cast< cppu::OWeakObject * >(this));
            }
            m_Attachments[i] = external;
        }
    }
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getAttachement(  )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );
    return m_Attachments;
}

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

Any SAL_CALL CmdMailMsg::getByName( const OUString& aName )
    throw (NoSuchElementException, WrappedTargetException, RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    if( 0 == aName.compareToAscii( "from" ) &&  m_aOriginator.getLength() )
        return makeAny( m_aOriginator );

    else if( 0 == aName.compareToAscii( "to" ) &&  m_aRecipient.getLength() )
        return makeAny( m_aRecipient );

    else if( 0 == aName.compareToAscii( "cc" ) &&  m_CcRecipients.getLength() )
        return makeAny( m_CcRecipients );

    else if( 0 == aName.compareToAscii( "bcc" ) &&  m_BccRecipients.getLength() )
        return makeAny( m_BccRecipients );

    else if( 0 == aName.compareToAscii( "subject" ) &&  m_aSubject.getLength() )
        return makeAny( m_aSubject );

    else if( 0 == aName.compareToAscii( "attachment" ) &&  m_Attachments.getLength() )
        return makeAny( m_Attachments );

   throw NoSuchElementException( OUString::createFromAscii( "key not found: ") + aName,
        static_cast < XNameAccess * > (this) );
}

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

Sequence< OUString > SAL_CALL CmdMailMsg::getElementNames(  )
    throw (::com::sun::star::uno::RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    sal_Int32 nItems = 0;
    Sequence< OUString > aRet( 6 );

    if( m_aOriginator.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "from" );

    if( m_aRecipient.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "to" );

    if( m_CcRecipients.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "cc" );

    if( m_BccRecipients.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "bcc" );

    if( m_aSubject.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "subject" );

    if( m_Attachments.getLength() )
        aRet[nItems++] = OUString::createFromAscii( "attachment" );

    aRet.realloc( nItems );
    return aRet;
}

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

 sal_Bool SAL_CALL CmdMailMsg::hasByName( const ::rtl::OUString& aName )
    throw (RuntimeException)
{
    MutexGuard aGuard( m_aMutex );

    if( 0 == aName.compareToAscii( "from" ) &&  m_aOriginator.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "to" ) &&  m_aRecipient.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "cc" ) &&  m_CcRecipients.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "bcc" ) &&  m_BccRecipients.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "subject" ) &&  m_aSubject.getLength() )
        return sal_True;

    else if( 0 == aName.compareToAscii( "attachment" ) &&  m_Attachments.getLength() )
        return sal_True;

    return sal_False;
}

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

Type SAL_CALL CmdMailMsg::getElementType(  )
    throw (RuntimeException)
{
    // returning void for multi type container
    return Type();
}

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

sal_Bool SAL_CALL CmdMailMsg::hasElements(  )
    throw (RuntimeException)
{
    return 0 != getElementNames().getLength();
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * thrill/common/string.hpp
 *
 * Some string helper functions
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef THRILL_COMMON_STRING_HEADER
#define THRILL_COMMON_STRING_HEADER

#include <cstdarg>
#include <random>
#include <string>
#include <vector>

namespace thrill {
namespace common {

/**
 * Dump a (binary) string as a sequence of hexadecimal pairs.
 *
 * \param data  binary data to output in hex
 * \param size  length of binary data
 * \return      string of hexadecimal pairs
 */
std::string hexdump(const void* const data, size_t size);

/**
 * Dump a (binary) string as a sequence of hexadecimal pairs.
 *
 * \param str  binary data to output in hex
 * \return     string of hexadecimal pairs
 */
std::string hexdump(const std::string& str);

/**
 * Checks if the given match string is located at the start of this string.
 */
static inline
bool starts_with(const std::string& str, const std::string& match) {
    if (match.size() > str.size()) return false;
    return std::equal(match.begin(), match.end(), str.begin());
}

/**
 * Checks if the given match string is located at the end of this string.
 */
static inline
bool ends_with(const std::string& str, const std::string& match) {
    if (match.size() > str.size()) return false;
    return std::equal(match.begin(), match.end(),
                      str.end() - match.size());
}

/*!
 * Helper for using sprintf to format into std::string and also to_string
 * converters.
 *
 * \param max_size maximum length of output string, longer ones are truncated.
 * \param fmt printf format and additional parameters
 */
template <typename String = std::string,
          typename CharT = typename String::value_type>
String str_snprintf(size_t max_size, const CharT* fmt, ...)
__attribute__ ((format(printf, 2, 3)));

template <typename String = std::string,
          typename CharT = typename String::value_type>
String str_snprintf(size_t max_size, const CharT* fmt, ...) {
    CharT* s = static_cast<CharT*>(alloca(sizeof(CharT) * max_size));

    va_list args;
    va_start(args, fmt);

    const int len = std::vsnprintf(s, max_size, fmt, args);

    va_end(args);

    return String(s, s + len);
}

/**
 * Split the given string at each separator character into distinct
 * substrings. Multiple consecutive separators are considered individually and
 * will result in empty split substrings.
 *
 * \param str    string to split
 * \param sep    separator character
 * \param limit  maximum number of parts returned
 * \return       vector containing each split substring
 */
static inline
std::vector<std::string> split(
    const std::string& str, char sep,
    std::string::size_type limit = std::string::npos) {

    std::vector<std::string> out;
    if (limit == 0) return out;

    std::string::const_iterator it = str.begin(), last = it;

    for ( ; it != str.end(); ++it)
    {
        if (*it == sep)
        {
            if (out.size() + 1 >= limit)
            {
                out.push_back(std::string(last, str.end()));
                return out;
            }

            out.push_back(std::string(last, it));
            last = it + 1;
        }
    }

    out.push_back(std::string(last, it));
    return out;
}

/**
 * Split the given string at each separator string into distinct
 * substrings. Multiple consecutive separators are considered individually and
 * will result in empty split substrings.
 *
 * \param str     string to split
 * \param sepstr  separator string, NOT a set of characters!
 * \param limit   maximum number of parts returned
 * \return        vector containing each split substring
 */
static inline
std::vector<std::string> split(
    const std::string& str, const std::string& sepstr,
    std::string::size_type limit = std::string::npos) {

    std::vector<std::string> out;
    if (limit == 0) return out;
    if (sepstr.empty()) return out;

    std::string::const_iterator it = str.begin(), last = it;

    for ( ; it + sepstr.size() < str.end(); ++it)
    {
        if (std::equal(sepstr.begin(), sepstr.end(), it))
        {
            if (out.size() + 1 >= limit)
            {
                out.push_back(std::string(last, str.end()));
                return out;
            }

            out.push_back(std::string(last, it));
            last = it + sepstr.size();
        }
    }

    out.push_back(std::string(last, str.end()));
    return out;
}

/**
 * Join a sequence of strings by some glue string between each pair from the
 * sequence. The sequence in given as a range between two iterators.
 *
 * \param glue  string to glue
 * \param first the beginning iterator of the range to join
 * \param last  the ending iterator of the range to join
 * \return      string constructed from the range with the glue between them.
 */
template <typename Iterator>
static inline
std::string join(const std::string& glue, Iterator first, Iterator last) {
    std::string out;
    if (first == last) return out;

    out.append(*first);
    ++first;

    while (first != last)
    {
        out.append(glue);
        out.append(*first);
        ++first;
    }

    return out;
}

/**
 * Join a Container (like a vector) of strings using some glue string between
 * each pair from the sequence.
 *
 * \param glue  string to glue
 * \param parts the vector of strings to join
 * \return      string constructed from the vector with the glue between them.
 */
template <typename Container>
static inline
std::string join(const std::string& glue, const Container& parts) {
    return join(glue, parts.begin(), parts.end());
}

/**
 * Replace all occurrences of needle in str. Each needle will be replaced with
 * instead, if found. The replacement is done in the given string and a
 * reference to the same is returned.
 *
 * @param str           the string to process
 * @param needle        string to search for in str
 * @param instead       replace needle with instead
 * @return              reference to str
 */
static inline
std::string & replace_all(std::string& str, const std::string& needle,
                          const std::string& instead) {
    std::string::size_type lastpos = 0, thispos;

    while ((thispos = str.find(needle, lastpos)) != std::string::npos)
    {
        str.replace(thispos, needle.size(), instead);
        lastpos = thispos + instead.size();
    }
    return str;
}

/**
 * Generate a random string of given length. The set of available
 * bytes/characters is given as the second argument. Each byte is equally
 * probable. Uses the pseudo-random number generator from stdlib; take care to
 * seed it using srand() before calling this function.
 *
 * \param size     length of result
 * \param rng      Random number generator to use, e.g. std::default_random_engine.
 * \param letters  character set to choose from
 * \return         random string of given length
 */
template <typename RandomEngine = std::default_random_engine>
static inline std::string
RandomString(std::string::size_type size, RandomEngine rng,
             const std::string& letters
                 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
    std::string out;
    out.resize(size);

    std::uniform_int_distribution<size_t> distribution(0, letters.size() - 1);

    for (size_t i = 0; i < size; ++i)
        out[i] = letters[distribution(rng)];

    return out;
}

} // namespace common
} // namespace thrill

#endif // !THRILL_COMMON_STRING_HEADER

/******************************************************************************/
<commit_msg>Fixing clang and maybe macosx.<commit_after>/*******************************************************************************
 * thrill/common/string.hpp
 *
 * Some string helper functions
 *
 * Part of Project Thrill.
 *
 * Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#pragma once
#ifndef THRILL_COMMON_STRING_HEADER
#define THRILL_COMMON_STRING_HEADER

#include <cstdarg>
#include <random>
#include <string>
#include <vector>

namespace thrill {
namespace common {

/**
 * Dump a (binary) string as a sequence of hexadecimal pairs.
 *
 * \param data  binary data to output in hex
 * \param size  length of binary data
 * \return      string of hexadecimal pairs
 */
std::string hexdump(const void* const data, size_t size);

/**
 * Dump a (binary) string as a sequence of hexadecimal pairs.
 *
 * \param str  binary data to output in hex
 * \return     string of hexadecimal pairs
 */
std::string hexdump(const std::string& str);

/**
 * Checks if the given match string is located at the start of this string.
 */
static inline
bool starts_with(const std::string& str, const std::string& match) {
    if (match.size() > str.size()) return false;
    return std::equal(match.begin(), match.end(), str.begin());
}

/**
 * Checks if the given match string is located at the end of this string.
 */
static inline
bool ends_with(const std::string& str, const std::string& match) {
    if (match.size() > str.size()) return false;
    return std::equal(match.begin(), match.end(),
                      str.end() - match.size());
}

/*!
 * Helper for using sprintf to format into std::string and also to_string
 * converters.
 *
 * \param max_size maximum length of output string, longer ones are truncated.
 * \param fmt printf format and additional parameters
 */
template <typename String = std::string>
String str_snprintf(size_t max_size, const char* fmt, ...)
__attribute__ ((format(printf, 2, 3)));

template <typename String>
String str_snprintf(size_t max_size, const char* fmt, ...) {
    // allocate buffer on stack
    char* s = static_cast<char*>(alloca(max_size));

    va_list args;
    va_start(args, fmt);

    const int len = std::vsnprintf(s, max_size, fmt, args);

    va_end(args);

    return String(s, s + len);
}

/**
 * Split the given string at each separator character into distinct
 * substrings. Multiple consecutive separators are considered individually and
 * will result in empty split substrings.
 *
 * \param str    string to split
 * \param sep    separator character
 * \param limit  maximum number of parts returned
 * \return       vector containing each split substring
 */
static inline
std::vector<std::string> split(
    const std::string& str, char sep,
    std::string::size_type limit = std::string::npos) {

    std::vector<std::string> out;
    if (limit == 0) return out;

    std::string::const_iterator it = str.begin(), last = it;

    for ( ; it != str.end(); ++it)
    {
        if (*it == sep)
        {
            if (out.size() + 1 >= limit)
            {
                out.push_back(std::string(last, str.end()));
                return out;
            }

            out.push_back(std::string(last, it));
            last = it + 1;
        }
    }

    out.push_back(std::string(last, it));
    return out;
}

/**
 * Split the given string at each separator string into distinct
 * substrings. Multiple consecutive separators are considered individually and
 * will result in empty split substrings.
 *
 * \param str     string to split
 * \param sepstr  separator string, NOT a set of characters!
 * \param limit   maximum number of parts returned
 * \return        vector containing each split substring
 */
static inline
std::vector<std::string> split(
    const std::string& str, const std::string& sepstr,
    std::string::size_type limit = std::string::npos) {

    std::vector<std::string> out;
    if (limit == 0) return out;
    if (sepstr.empty()) return out;

    std::string::const_iterator it = str.begin(), last = it;

    for ( ; it + sepstr.size() < str.end(); ++it)
    {
        if (std::equal(sepstr.begin(), sepstr.end(), it))
        {
            if (out.size() + 1 >= limit)
            {
                out.push_back(std::string(last, str.end()));
                return out;
            }

            out.push_back(std::string(last, it));
            last = it + sepstr.size();
        }
    }

    out.push_back(std::string(last, str.end()));
    return out;
}

/**
 * Join a sequence of strings by some glue string between each pair from the
 * sequence. The sequence in given as a range between two iterators.
 *
 * \param glue  string to glue
 * \param first the beginning iterator of the range to join
 * \param last  the ending iterator of the range to join
 * \return      string constructed from the range with the glue between them.
 */
template <typename Iterator>
static inline
std::string join(const std::string& glue, Iterator first, Iterator last) {
    std::string out;
    if (first == last) return out;

    out.append(*first);
    ++first;

    while (first != last)
    {
        out.append(glue);
        out.append(*first);
        ++first;
    }

    return out;
}

/**
 * Join a Container (like a vector) of strings using some glue string between
 * each pair from the sequence.
 *
 * \param glue  string to glue
 * \param parts the vector of strings to join
 * \return      string constructed from the vector with the glue between them.
 */
template <typename Container>
static inline
std::string join(const std::string& glue, const Container& parts) {
    return join(glue, parts.begin(), parts.end());
}

/**
 * Replace all occurrences of needle in str. Each needle will be replaced with
 * instead, if found. The replacement is done in the given string and a
 * reference to the same is returned.
 *
 * @param str           the string to process
 * @param needle        string to search for in str
 * @param instead       replace needle with instead
 * @return              reference to str
 */
static inline
std::string & replace_all(std::string& str, const std::string& needle,
                          const std::string& instead) {
    std::string::size_type lastpos = 0, thispos;

    while ((thispos = str.find(needle, lastpos)) != std::string::npos)
    {
        str.replace(thispos, needle.size(), instead);
        lastpos = thispos + instead.size();
    }
    return str;
}

/**
 * Generate a random string of given length. The set of available
 * bytes/characters is given as the second argument. Each byte is equally
 * probable. Uses the pseudo-random number generator from stdlib; take care to
 * seed it using srand() before calling this function.
 *
 * \param size     length of result
 * \param rng      Random number generator to use, e.g. std::default_random_engine.
 * \param letters  character set to choose from
 * \return         random string of given length
 */
template <typename RandomEngine = std::default_random_engine>
static inline std::string
RandomString(std::string::size_type size, RandomEngine rng,
             const std::string& letters
                 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") {
    std::string out;
    out.resize(size);

    std::uniform_int_distribution<size_t> distribution(0, letters.size() - 1);

    for (size_t i = 0; i < size; ++i)
        out[i] = letters[distribution(rng)];

    return out;
}

} // namespace common
} // namespace thrill

#endif // !THRILL_COMMON_STRING_HEADER

/******************************************************************************/
<|endoftext|>


<commit_before>// DnaMatchingAndVariationDetection.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include "Sequence.h"

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	// Define the sample sequences.
	char sequence1[33] = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTG";
	char sequence2[17] = "CTGCTGCTCTCCGGGG";
	char sequence3[33] = "ACAAGATGCCATTAGCCCCCGGCCTCCTGCTC";
	char sequence4[369] = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAATTACAGACCTGAA";
	char sequence5[369] = "ACAAGCAGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGCCCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGAAATCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAAAAACAGACCTGAA";

	// Create the necessary Sequence objects.
	Sequence s1, s2, s3, s4, s5;

	// Initialize the Sequence objects.
	s1.Initialize(sequence1);
	s2.Initialize(sequence2, 16);
	s3.Initialize(sequence3);
	s4.Initialize(sequence4, 368);
	s5.Initialize(sequence5, 368);

	// Define search keys.
	const int SEARCH_KEY_SIZE_1 = 3;
	char searchKey1[SEARCH_KEY_SIZE_1 + 1] = "CCC";
	char searchKey2[SEARCH_KEY_SIZE_1 + 1] = "AAA";
	const int SEARCH_KEY_SIZE_2 = 8;
	char searchKey3[SEARCH_KEY_SIZE_2 + 1] = "CTCCGGGG";
	char searchKey4[SEARCH_KEY_SIZE_2 + 1] = "CTGCTGCG";
	const int SEARCH_KEY_SIZE_3 = 16;
	char searchKey5[SEARCH_KEY_SIZE_3 + 1] = "ACAAGATGCCATTGTC";
	char searchKey6[SEARCH_KEY_SIZE_3 + 1] = "AAAAAAAAAAAAAAAA";

	// Test sequence 1 (default sequence size) and search functionality.
	cout << "Sequence 1: \""; s1.PrintSequence(); cout << "\"" << endl;
	cout << "    - Size: " << s1.GetSize() << endl;
	cout << "Search Key: " << searchKey1 << endl;
	cout << "    - Keys Found: " << s1.Search(searchKey1, SEARCH_KEY_SIZE_1) << endl;
	cout << "Search Key: " << searchKey2 << endl;
	cout << "    - Keys Found: " << s1.Search(searchKey2, SEARCH_KEY_SIZE_1) << endl << endl;

	// Test sequence 2 (specified sequence size) and search functionality.
	cout << "Sequence 2: \""; s2.PrintSequence(); cout << "\"" << endl;
	cout << "    - Size: " << s2.GetSize() << endl;
	cout << "Search Key: " << searchKey3 << endl;
	cout << "    - Keys Found: " << s2.Search(searchKey3, SEARCH_KEY_SIZE_2) << endl;
	cout << "Search Key: " << searchKey4 << endl;
	cout << "    - Keys Found: " << s2.Search(searchKey4, SEARCH_KEY_SIZE_2) << endl << endl;

	// Test sequence 1 (default sequence size) and compare functionality.
	cout << "Sequence 1: \""; s1.PrintSequence(); cout << "\"" << endl;
	cout << "    - Size: " << s1.GetSize() << endl;
	cout << "Compared with Sequence 1: \""; s1.PrintSequence(); cout << "\"" << endl;
	cout << "    - Variations: " << (s1.Compare(s1) ? "TRUE" : "FALSE") << endl;
	if (s1.Compare(s1)) {
		cout << "                  "; s1.PrintVariations(s1); cout << endl;
	}
	cout << "Compared with Sequence 3: \""; s3.PrintSequence(); cout << "\"" << endl;
	cout << "    - Variations: " << (s1.Compare(s3) ? "TRUE" : "FALSE") << endl;
	if (s1.Compare(s3)) {
		cout << "                  "; s1.PrintVariations(s3); cout << endl << endl;
	}

	// Test sequence 4 (large sequence size) and search functionality.
	cout << "Sequence 4: \""; s4.PrintSequence(); cout << "\"" << endl;
	cout << "    - Size: " << s4.GetSize() << endl;
	cout << "Search Key: " << searchKey5 << endl;
	cout << "    - Keys Found: " << s4.Search(searchKey5, SEARCH_KEY_SIZE_3) << endl;
	cout << "Search Key: " << searchKey6 << endl;
	cout << "    - Keys Found: " << s4.Search(searchKey6, SEARCH_KEY_SIZE_3) << endl << endl;

	// Test sequence 4 (large sequence size) and compare functionality.
	cout << "Sequence 4: \""; s4.PrintSequence(); cout << "\"" << endl;
	cout << "    - Size: " << s4.GetSize() << endl;
	cout << "Compared with Sequence 4: \""; s4.PrintSequence(); cout << "\"" << endl;
	cout << "    - Variations: " << (s1.Compare(s4) ? "TRUE" : "FALSE") << endl;
	if (s4.Compare(s4)) {
		cout << "                  "; s4.PrintVariations(s4); cout << endl;
	}
	cout << "Compared with Sequence 5: \""; s5.PrintSequence(); cout << "\"" << endl;
	cout << "    - Variations: " << (s4.Compare(s5) ? "TRUE" : "FALSE") << endl;
	if (s4.Compare(s5)) {
		cout << "                  "; s4.PrintVariations(s5); cout << endl << endl;
	}

	return 0;
}<commit_msg>Structured application code into a test suite format filled with test cases<commit_after>#include "stdafx.h"
#include <iostream>
#include "Sequence.h"

using namespace std;

//=============================================================================
//  TEST CASE SWITCHES
//=============================================================================

#define ENABLED 1
#define DISABLED 0

#define TESTCASE_SEQUENCE_CPP_SEARCH_WITHVALIDTHREECHARACTERKEY_WITHDEFAULTSEQUENCESIZE_EXPECTTWOKEYSFOUND ENABLED
#define TESTCASE_SEQUENCE_CPP_SEARCH_WITHINVALIDTHREECHARACTERKEY_WITHDEFAULTSEQUENCESIZE_EXPECTZEROKEYSFOUND ENABLED
#define TESTCASE_SEQUENCE_CPP_SEARCH_WITHVALIDTHREECHARACTERKEY_WITHSPECIFIEDSEQUENCESIZE_EXPECTTHIRTEENKEYSFOUND ENABLED
#define TESTCASE_SEQUENCE_CPP_SEARCH_WITHINVALIDFOURCHARACTERKEY_WITHSPECIFIEDSEQUENCESIZE_EXPECTZEROKEYSFOUND ENABLED
#define TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTSAMECOMPARESEQUENCE_WITHDEFAULTSEQUENCESIZE_EXPECTNOVARIATIONS ENABLED
#define TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTDIFFERENTCOMPARESEQUENCE_WITHDEFAULTSEQUENCESIZE_EXPECTVARIATIONS ENABLED
#define TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTSAMECOMPARESEQUENCE_WITHSPECIFIEDSEQUENCESIZE_EXPECTNOVARIATIONS ENABLED
#define TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTDIFFERENTCOMPARESEQUENCE_WITHSPECIFIEDSEQUENCESIZE_EXPECTVARIATIONS ENABLED

//=============================================================================
//  TEST HELPERS
//=============================================================================

// Sequences
char SEQUENCE_DEFAULT[33] = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTG";
char SEQUENCE_DEFAULT_VARIATIONS[33] = "ACAAGATGCCATTAGCCCCCGGCCTCCTGCTC";
char SEQUENCE_SPECIFIED[369] = "ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAATTACAGACCTGAA";
char SEQUENCE_SPECIFIED_VARIATIONS[369] = "ACAAGCAGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGCCCCACGGCCACCGCTGCCCTGCCCCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGCCTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGAAATCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGGAAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCCCTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAGTTTAAAAACAGACCTGAA";

// Sequence Sizes
int SEQUENCE_SIZE_SPECIFIED = 368;

// Search Keys
char SEARCH_KEY_THREE_CHARACTERS_VALID[4] = "TGC";
char SEARCH_KEY_THREE_CHARACTERS_INVALID_DEFAULT[4] = "AAA";
char SEARCH_KEY_FOUR_CHARACTERS_INVALID_LONG[5] = "TTTT";

// Search Key Sizes
int SEARCH_KEY_SIZE_THREE_CHARACTERS = 3;
int SEARCH_KEY_SIZE_FOUR_CHARACTERS = 4;

//=============================================================================
//  TEST CASE PROTOTYPES
//=============================================================================

void TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithDefaultSequenceSize_ExpectTwoKeysFound();
void TestCase_Sequence_cpp_Search_WithInvalidThreeCharacterKey_WithDefaultSequenceSize_ExpectZeroKeysFound();
void TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithSpecifiedSequenceSize_ExpectThirteenKeysFound();
void TestCase_Sequence_cpp_Search_WithInvalidFourCharacterKey_WithSpecifiedSequenceSize_ExpectZeroKeysFound();
void TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithDefaultSequenceSize_ExpectNoVariations();
void TestCase_Sequence_cpp_Compare_AgainstDifferentCompareSequence_WithDefaultSequenceSize_ExpectVariations();
void TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithSpecifiedSequenceSize_ExpectNoVariations();
void TestCase_Sequence_cpp_CompareAgainstDifferentCompareSequence_WithSpecifiedSequenceSize_ExpectVariations();

//=============================================================================
//  MAIN EXECUTION
//=============================================================================

int _tmain(int argc, _TCHAR* argv[])
{
#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHVALIDTHREECHARACTERKEY_WITHDEFAULTSEQUENCESIZE_EXPECTTWOKEYSFOUND)
	TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithDefaultSequenceSize_ExpectTwoKeysFound();
#endif

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHINVALIDTHREECHARACTERKEY_WITHDEFAULTSEQUENCESIZE_EXPECTZEROKEYSFOUND)
	TestCase_Sequence_cpp_Search_WithInvalidThreeCharacterKey_WithDefaultSequenceSize_ExpectZeroKeysFound();
#endif

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHVALIDTHREECHARACTERKEY_WITHSPECIFIEDSEQUENCESIZE_EXPECTTHIRTEENKEYSFOUND)
	TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithSpecifiedSequenceSize_ExpectThirteenKeysFound();
#endif

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHINVALIDFOURCHARACTERKEY_WITHSPECIFIEDSEQUENCESIZE_EXPECTZEROKEYSFOUND)
	TestCase_Sequence_cpp_Search_WithInvalidFourCharacterKey_WithSpecifiedSequenceSize_ExpectZeroKeysFound();
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTSAMECOMPARESEQUENCE_WITHDEFAULTSEQUENCESIZE_EXPECTNOVARIATIONS)
	TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithDefaultSequenceSize_ExpectNoVariations();
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTDIFFERENTCOMPARESEQUENCE_WITHDEFAULTSEQUENCESIZE_EXPECTVARIATIONS)
	TestCase_Sequence_cpp_Compare_AgainstDifferentCompareSequence_WithDefaultSequenceSize_ExpectVariations();
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTSAMECOMPARESEQUENCE_WITHSPECIFIEDSEQUENCESIZE_EXPECTNOVARIATIONS)
	TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithSpecifiedSequenceSize_ExpectNoVariations();
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTDIFFERENTCOMPARESEQUENCE_WITHSPECIFIEDSEQUENCESIZE_EXPECTVARIATIONS)
	TestCase_Sequence_cpp_CompareAgainstDifferentCompareSequence_WithSpecifiedSequenceSize_ExpectVariations();
#endif

	return 0;
}

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHVALIDTHREECHARACTERKEY_WITHDEFAULTSEQUENCESIZE_EXPECTTWOKEYSFOUND)
void TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithDefaultSequenceSize_ExpectTwoKeysFound()
{
	cout << "BEGIN TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithDefaultSequenceSize_ExpectTwoKeysFound" << endl << endl;

	// Initialization
	Sequence sequence;
	sequence.Initialize(SEQUENCE_DEFAULT);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "search key = " << SEARCH_KEY_THREE_CHARACTERS_VALID << endl;
	cout << endl;

	// Expected Output
	int expectedKeysFound = 2;
	cout << "// Expected Output" << endl;
	cout << "keys found: " << expectedKeysFound << endl;
	cout << endl;

	// Actual Output
	int actualKeysFound = sequence.Search(SEARCH_KEY_THREE_CHARACTERS_VALID, SEARCH_KEY_SIZE_THREE_CHARACTERS);
	cout << "// Actual Output" << endl;
	cout << "keys found: " << actualKeysFound << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualKeysFound == expectedKeysFound)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithDefaultSequenceSize_ExpectTwoKeysFound" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHINVALIDTHREECHARACTERKEY_WITHDEFAULTSEQUENCESIZE_EXPECTZEROKEYSFOUND)
void TestCase_Sequence_cpp_Search_WithInvalidThreeCharacterKey_WithDefaultSequenceSize_ExpectZeroKeysFound()
{
	cout << "BEGIN TestCase_Sequence_cpp_Search_WithInvalidThreeCharacterKey_WithDefaultSequenceSize_ExpectZeroKeysFound" << endl << endl;

	// Initialization
	Sequence sequence;
	sequence.Initialize(SEQUENCE_DEFAULT);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "search key = " << SEARCH_KEY_THREE_CHARACTERS_INVALID_DEFAULT << endl;
	cout << endl;

	// Expected Output
	int expectedKeysFound = 0;
	cout << "// Expected Output" << endl;
	cout << "keys found: " << expectedKeysFound << endl;
	cout << endl;

	// Actual Output
	int actualKeysFound = sequence.Search(SEARCH_KEY_THREE_CHARACTERS_INVALID_DEFAULT, SEARCH_KEY_SIZE_THREE_CHARACTERS);
	cout << "// Actual Output" << endl;
	cout << "keys found: " << actualKeysFound << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualKeysFound == expectedKeysFound)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Search_WithInvalidThreeCharacterKey_WithDefaultSequenceSize_ExpectZeroKeysFound" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHVALIDTHREECHARACTERKEY_WITHSPECIFIEDSEQUENCESIZE_EXPECTTHIRTEENKEYSFOUND)
void TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithSpecifiedSequenceSize_ExpectThirteenKeysFound()
{
	cout << "BEGIN TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithSpecifiedSequenceSize_ExpectThirteenKeysFound" << endl << endl;

	// Initialization
	Sequence sequence;
	sequence.Initialize(SEQUENCE_SPECIFIED, SEQUENCE_SIZE_SPECIFIED);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "search key = " << SEARCH_KEY_THREE_CHARACTERS_VALID << endl;
	cout << endl;

	// Expected Output
	int expectedKeysFound = 13;
	cout << "// Expected Output" << endl;
	cout << "keys found: " << expectedKeysFound << endl;
	cout << endl;

	// Actual Output
	int actualKeysFound = sequence.Search(SEARCH_KEY_THREE_CHARACTERS_VALID, SEARCH_KEY_SIZE_THREE_CHARACTERS);
	cout << "// Actual Output" << endl;
	cout << "keys found: " << actualKeysFound << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualKeysFound == expectedKeysFound)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Search_WithValidThreeCharacterKey_WithSpecifiedSequenceSize_ExpectThirteenKeysFound" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_SEARCH_WITHINVALIDFOURCHARACTERKEY_WITHSPECIFIEDSEQUENCESIZE_EXPECTZEROKEYSFOUND)
void TestCase_Sequence_cpp_Search_WithInvalidFourCharacterKey_WithSpecifiedSequenceSize_ExpectZeroKeysFound()
{
	cout << "BEGIN TestCase_Sequence_cpp_Search_WithInvalidFourCharacterKey_WithSpecifiedSequenceSize_ExpectZeroKeysFound" << endl << endl;

	// Initialization
	Sequence sequence;
	sequence.Initialize(SEQUENCE_SPECIFIED, SEQUENCE_SIZE_SPECIFIED);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "search key = " << SEARCH_KEY_FOUR_CHARACTERS_INVALID_LONG << endl;
	cout << endl;

	// Expected Output
	int expectedKeysFound = 0;
	cout << "// Expected Output" << endl;
	cout << "keys found: " << expectedKeysFound << endl;
	cout << endl;

	// Actual Output
	int actualKeysFound = sequence.Search(SEARCH_KEY_FOUR_CHARACTERS_INVALID_LONG, SEARCH_KEY_SIZE_FOUR_CHARACTERS);
	cout << "// Actual Output" << endl;
	cout << "keys found: " << actualKeysFound << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualKeysFound == expectedKeysFound)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Search_WithInvalidFourCharacterKey_WithSpecifiedSequenceSize_ExpectZeroKeysFound" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTSAMECOMPARESEQUENCE_WITHDEFAULTSEQUENCESIZE_EXPECTNOVARIATIONS)
void TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithDefaultSequenceSize_ExpectNoVariations()
{
	cout << "BEGIN TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithDefaultSequenceSize_ExpectNoVariations" << endl << endl;

	// Initialization
	Sequence sequence;
	sequence.Initialize(SEQUENCE_DEFAULT);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << "compareSequence = "; sequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "print variations (variations marked by brackets) = "; sequence.PrintVariations(sequence); cout << endl;
	cout << endl;

	// Expected Output
	bool expectedVariations = false;
	cout << "// Expected Output" << endl;
	cout << "variations = " << (expectedVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Actual Output
	bool actualVariations = sequence.Compare(sequence);
	cout << "// Actual Output" << endl;
	cout << "variations = " << (actualVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualVariations == expectedVariations)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithDefaultSequenceSize_ExpectNoVariations" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTDIFFERENTCOMPARESEQUENCE_WITHDEFAULTSEQUENCESIZE_EXPECTVARIATIONS)
void TestCase_Sequence_cpp_Compare_AgainstDifferentCompareSequence_WithDefaultSequenceSize_ExpectVariations()
{
	cout << "BEGIN TestCase_Sequence_cpp_Compare_AgainstDifferentCompareSequence_WithDefaultSequenceSize_ExpectVariations" << endl << endl;

	// Initialization
	Sequence sequence, compareSequence;
	sequence.Initialize(SEQUENCE_DEFAULT);
	compareSequence.Initialize(SEQUENCE_DEFAULT_VARIATIONS);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << "compareSequence = "; compareSequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "print variations (variations marked by brackets) = "; sequence.PrintVariations(compareSequence); cout << endl;
	cout << endl;

	// Expected Output
	bool expectedVariations = true;
	cout << "// Expected Output" << endl;
	cout << "variations = " << (expectedVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Actual Output
	bool actualVariations = sequence.Compare(compareSequence);
	cout << "// Actual Output" << endl;
	cout << "variations = " << (actualVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualVariations == expectedVariations)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Compare_AgainstDifferentCompareSequence_WithDefaultSequenceSize_ExpectVariations" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTSAMECOMPARESEQUENCE_WITHSPECIFIEDSEQUENCESIZE_EXPECTNOVARIATIONS)
void TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithSpecifiedSequenceSize_ExpectNoVariations()
{
	cout << "BEGIN TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithSpecifiedSequenceSize_ExpectNoVariations" << endl << endl;

	// Initialization
	Sequence sequence;
	sequence.Initialize(SEQUENCE_SPECIFIED, SEQUENCE_SIZE_SPECIFIED);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << "compareSequence = "; sequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "print variations (variations marked by brackets) = "; sequence.PrintVariations(sequence); cout << endl;
	cout << endl;

	// Expected Output
	bool expectedVariations = false;
	cout << "// Expected Output" << endl;
	cout << "variations = " << (expectedVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Actual Output
	bool actualVariations = sequence.Compare(sequence);
	cout << "// Actual Output" << endl;
	cout << "variations = " << (actualVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualVariations == expectedVariations)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_Compare_AgainstSameCompareSequence_WithSpecifiedSequenceSize_ExpectNoVariations" << endl << endl;
}
#endif

#if (TESTCASE_SEQUENCE_CPP_COMPARE_AGAINSTDIFFERENTCOMPARESEQUENCE_WITHSPECIFIEDSEQUENCESIZE_EXPECTVARIATIONS)
void TestCase_Sequence_cpp_CompareAgainstDifferentCompareSequence_WithSpecifiedSequenceSize_ExpectVariations()
{
	cout << "BEGIN TestCase_Sequence_cpp_CompareAgainstDifferentCompareSequence_WithSpecifiedSequenceSize_ExpectVariations" << endl << endl;

	// Initialization
	Sequence sequence, compareSequence;
	sequence.Initialize(SEQUENCE_SPECIFIED, SEQUENCE_SIZE_SPECIFIED);
	compareSequence.Initialize(SEQUENCE_SPECIFIED_VARIATIONS, SEQUENCE_SIZE_SPECIFIED);
	cout << "// Initialization" << endl;
	cout << "sequence = "; sequence.PrintSequence(); cout << endl;
	cout << "compareSequence = "; compareSequence.PrintSequence(); cout << endl;
	cout << endl;

	// Test Implementation
	cout << "// Test Implementation" << endl;
	cout << "print variations (variations marked by brackets) = "; sequence.PrintVariations(compareSequence); cout << endl;
	cout << endl;

	// Expected Output
	bool expectedVariations = true;
	cout << "// Expected Output" << endl;
	cout << "variations = " << (expectedVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Actual Output
	bool actualVariations = sequence.Compare(compareSequence);
	cout << "// Actual Output" << endl;
	cout << "variations = " << (actualVariations ? "TRUE" : "FALSE") << endl;
	cout << endl;

	// Test Case Status
	cout << "// Test Case Status" << endl;
	cout << "status = ";
	if (actualVariations == expectedVariations)
	{
		cout << "PASS";
	}

	else
	{
		cout << "FAIL";
	}
	cout << endl;

	cout << endl << "END TestCase_Sequence_cpp_CompareAgainstDifferentCompareSequence_WithSpecifiedSequenceSize_ExpectVariations" << endl << endl;
}
#endif<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//_________________________________________________________________________
// This is a TTask that makes TOF-Digits out of TOF-SDigits.
// The simulation of the detector is performed at sdigits level:
// during digitization the unique task is the sum of all sdigits in the
// same pad.
// Digits are written to TreeD in branch "TOF".
//
// -- Author :  F. Pierella (Bologna University) pierella@bo.infn.it
//////////////////////////////////////////////////////////////////////////////

#include <TTree.h>
#include <TVector.h>
#include <TObjArray.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>

#include "AliTOFDigitizer.h"
#include "AliTOF.h"
#include "AliTOFSDigitizer.h"
#include "AliTOFhit.h"
#include "AliTOFdigit.h"
#include "AliTOFSDigit.h"
#include "AliTOFHitMap.h"
#include "AliDigitizer.h"
#include "AliRunDigitizer.h"

#include "AliRun.h"
#include "AliPDG.h"

#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>

ClassImp(AliTOFDigitizer)

//___________________________________________
  AliTOFDigitizer::AliTOFDigitizer()  :AliDigitizer()
{
  // Default ctor - don't use it
  fDigits=0;
  fSDigitsArray=0;
  fhitMap=0;
}

//___________________________________________
AliTOFDigitizer::AliTOFDigitizer(AliRunDigitizer* manager)
    :AliDigitizer(manager)
{
  fDigits=0;
  fSDigitsArray=0;
  fhitMap=0;
}

//------------------------------------------------------------------------
AliTOFDigitizer::~AliTOFDigitizer()
{
  // Destructor
}

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

void AliTOFDigitizer::Exec(Option_t* option)
{
  //
  // Perform digitization and merging.
  // The algorithm is the following:
  // - a hitmap is created to check if a pad is already activated;
  // - an sdigits container is created to collect all sdigits from
  //   different files;
  // - sdigits are summed using the hitmap;
  // - the sdigits container is used to create the array of AliTOFdigit.
  //

  if(strstr(option,"deb")) cout<<"AliTOFDigitizer::Exec\n";

  // get the ptr to TOF detector
  AliTOF * tof = (AliTOF *) gAlice->GetDetector("TOF") ;

  //Make branches
  char branchname[20];
  sprintf (branchname, "%s", tof->GetName ());

  fDigits=new TClonesArray("AliTOFdigit",4000);

  TTree* treeD = fManager->GetTreeD();
  //Make branch for digits (to be created in Init())
  tof->MakeBranchInTree(treeD,branchname,&fDigits,4000);

  // container for all summed sdigits (to be created in Init())
  fSDigitsArray=new TClonesArray("AliTOFSDigit",1000);

  // create hit map (to be created in Init())
  fhitMap = new AliTOFHitMap(fSDigitsArray);

  // Loop over files to digitize

  for (Int_t inputFile=0; inputFile<fManager->GetNinputs();
       inputFile++) {
    ReadSDigit(inputFile);
  }

  // create digits
  CreateDigits();

  // free used memory for Hit Map in current event
  delete fhitMap;
  fSDigitsArray->Delete();
  treeD->Fill();

  fManager->GetTreeD()->AutoSave(); // to fit with the framework
  fDigits->Delete();
  delete fDigits;

}

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

void AliTOFDigitizer::CreateDigits()
{
  // loop on sdigits container to fill the AliTOFdigit TClonesArray
  // start digitizing all the collected sdigits

  Int_t ndump=15; // dump the first ndump created digits for each event

  // get the total number of collected sdigits
  Int_t ndig = fSDigitsArray->GetEntriesFast();

  for (Int_t k = 0; k < ndig; k++) {

    Int_t    vol[5];       // location for a digit

    // Get the information for this digit
    AliTOFSDigit *tofsdigit = (AliTOFSDigit *) fSDigitsArray->UncheckedAt(k);

    Int_t nslot=tofsdigit->GetNDigits(); // get the number of slots
    // for current sdigit

    // TOF sdigit volumes (always the same for all slots)
    Int_t sector    = tofsdigit->GetSector(); // range [1-18]
    Int_t plate     = tofsdigit->GetPlate();  // range [1- 5]
    Int_t strip     = tofsdigit->GetStrip();  // range [1-20]
    Int_t padz      = tofsdigit->GetPadz();   // range [1- 2]
    Int_t padx      = tofsdigit->GetPadx();   // range [1-48]

    vol[0] = sector;
    vol[1] = plate;
    vol[2] = strip;
    vol[3] = padx;
    vol[4] = padz;

    //--------------------- QA section ----------------------
    // in the while, I perform QA
    Bool_t isSDigitBad = (sector<1 || sector>18 || plate<1 || plate >5 || padz<1 || padz>2 || padx<1 || padx>48);

    if (isSDigitBad) {
      cout << "<AliTOFSDigits2Digits>  strange sdigit found" << endl;
      abort();
    }
    //-------------------------------------------------------

    //------------------- Dump section ----------------------
    if(k<ndump){
      cout << k << "-th | " << "Sector " << sector << " | Plate " << plate << " | Strip " << strip << " | PadZ " << padz << " | PadX " << padx << endl;
      cout << k << "-th sdigit" << endl;
      cout << "----------------------------------------------------"<< endl;
    }
    // ------------------------------------------------------

    // start loop on number of slots for current sdigit
    for (Int_t islot = 0; islot < nslot; islot++) {
      Float_t  digit[2];     // TOF digit variables
      Int_t tracknum[kMAXDIGITS];     // contributing tracks for the current slot

      Float_t tdc=tofsdigit->GetTdc(islot); digit[0]=tdc;
      Float_t adc=tofsdigit->GetAdc(islot); digit[1]=adc;

      tracknum[0]=tofsdigit->GetTrack(islot,0);
      tracknum[1]=tofsdigit->GetTrack(islot,1);
      tracknum[2]=tofsdigit->GetTrack(islot,2);

      // adding a TOF digit for each slot
      AliTOFdigit* newDigit=new AliTOFdigit(tracknum, vol, digit);
      fDigits->Add(newDigit);
    }

  } // end loop on sdigits - end digitizing all collected sdigits

}

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

void AliTOFDigitizer::ReadSDigit(Int_t inputFile )
{
  // Read sdigits for current event and inputFile;
  // store them into the sdigits container
  // and update the hit map
  // SDigits from different files are assumed to
  // be created with the same simulation parameters.

  // get the treeS from manager
  TTree* currentTreeS=fManager->GetInputTreeS(inputFile);

  // get the branch TOF inside the treeS
  TClonesArray * sdigitsDummyContainer= new TClonesArray("AliTOFSDigit",  1000);

  // check if the branch exist
  TBranch* tofBranch=currentTreeS->GetBranch("TOF");

  if(!tofBranch){
    Fatal("ReadSDigit","TOF branch not found for input %d",inputFile);
  }

  tofBranch->SetAddress(&sdigitsDummyContainer);

  Int_t nEntries = (Int_t)tofBranch->GetEntries();

  // Loop through all entries in the tree
  Int_t nbytes;

  for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {

    // Import the tree
    nbytes += tofBranch->GetEvent(iEntry);

    // Get the number of sdigits
    Int_t ndig = sdigitsDummyContainer->GetEntriesFast();

    for (Int_t k=0; k<ndig; k++) {
      AliTOFSDigit *tofSdigit= (AliTOFSDigit*) sdigitsDummyContainer->UncheckedAt(k);

      Int_t    vol[5];       // location for a sdigit

      // check the sdigit volume
      vol[0] = tofSdigit->GetSector();
      vol[1] = tofSdigit->GetPlate();
      vol[2] = tofSdigit->GetStrip();
      vol[3] = tofSdigit->GetPadx();
      vol[4] = tofSdigit->GetPadz();

      if (fhitMap->TestHit(vol) != kEmpty) {
	AliTOFSDigit *sdig = static_cast<AliTOFSDigit*>(fhitMap->GetHit(vol));
	sdig->Update(tofSdigit);

      } else {

	CollectSDigit(tofSdigit); // collect the current sdigit
	fhitMap->SetHit(vol);     // update the hitmap for location vol

      } // if (hitMap->TestHit(vol) != kEmpty)

    } // for (Int_t k=0; k<ndig; k++)

  } // end loop on entries

  sdigitsDummyContainer->Delete();
  sdigitsDummyContainer=0;

}

//_____________________________________________________________________________
void AliTOFDigitizer::CollectSDigit(AliTOFSDigit * sdigit)
{
  //
  // Add a TOF digit
  // new with placement used
  AliTOFSDigit sdigitCopy=AliTOFSDigit(*sdigit); // make a copy of the current sdigit
  fSDigitsArray->Add(&sdigitCopy); // put it into tmp array
}
<commit_msg>AliTOFDigitizer modified<commit_after>/**************************************************************************
 * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//_________________________________________________________________________
// This is a TTask that makes TOF-Digits out of TOF-SDigits.
// The simulation of the detector is performed at sdigits level:
// during digitization the unique task is the sum of all sdigits in the
// same pad.
// Digits are written to TreeD in branch "TOF".
//
// -- Author :  F. Pierella (Bologna University) pierella@bo.infn.it
//////////////////////////////////////////////////////////////////////////////

#include <TTree.h>
#include <TVector.h>
#include <TObjArray.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>

#include "AliTOFDigitizer.h"
#include "AliTOF.h"
#include "AliTOFSDigitizer.h"
#include "AliTOFhit.h"
#include "AliTOFdigit.h"
#include "AliTOFSDigit.h"
#include "AliTOFHitMap.h"
#include "AliDigitizer.h"
#include "AliRunDigitizer.h"

#include "AliRun.h"
#include "AliPDG.h"

#include <stdlib.h>
#include <iostream.h>
#include <fstream.h>

ClassImp(AliTOFDigitizer)

//___________________________________________
  AliTOFDigitizer::AliTOFDigitizer()  :AliDigitizer()
{
  // Default ctor - don't use it
  fDigits=0;
  fSDigitsArray=0;
  fhitMap=0;
}

//___________________________________________
AliTOFDigitizer::AliTOFDigitizer(AliRunDigitizer* manager)
    :AliDigitizer(manager)
{
  fDigits=0;
  fSDigitsArray=0;
  fhitMap=0;
}

//------------------------------------------------------------------------
AliTOFDigitizer::~AliTOFDigitizer()
{
  // Destructor
}

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

void AliTOFDigitizer::Exec(Option_t* option)
{
  //
  // Perform digitization and merging.
  // The algorithm is the following:
  // - a hitmap is created to check if a pad is already activated;
  // - an sdigits container is created to collect all sdigits from
  //   different files;
  // - sdigits are summed using the hitmap;
  // - the sdigits container is used to create the array of AliTOFdigit.
  //

  if(strstr(option,"deb")) cout<<"AliTOFDigitizer::Exec\n";

  // get the ptr to TOF detector
  AliTOF * tof = (AliTOF *) gAlice->GetDetector("TOF") ;

  //Make branches
  char branchname[20];
  sprintf (branchname, "%s", tof->GetName ());

  fDigits=new TClonesArray("AliTOFdigit",4000);

  TTree* treeD = fManager->GetTreeD();
  //Make branch for digits (to be created in Init())
  tof->MakeBranchInTree(treeD,branchname,&fDigits,4000);

  // container for all summed sdigits (to be created in Init())
  fSDigitsArray=new TClonesArray("AliTOFSDigit",1000);

  // create hit map (to be created in Init())
  fhitMap = new AliTOFHitMap(fSDigitsArray);

  // Loop over files to digitize

  for (Int_t inputFile=0; inputFile<fManager->GetNinputs();
       inputFile++) {
    ReadSDigit(inputFile);
  }

  // create digits
  CreateDigits();

  // free used memory for Hit Map in current event
  delete fhitMap;
  fSDigitsArray->Delete();
  treeD->Fill();

  fManager->GetTreeD()->AutoSave(); // to fit with the framework
  fDigits->Delete();
  delete fDigits;

}

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

void AliTOFDigitizer::CreateDigits()
{
  // loop on sdigits container to fill the AliTOFdigit TClonesArray
  // start digitizing all the collected sdigits

  Int_t ndump=15; // dump the first ndump created digits for each event

  // get the total number of collected sdigits
  Int_t ndig = fSDigitsArray->GetEntriesFast();

  for (Int_t k = 0; k < ndig; k++) {

    Int_t    vol[5];       // location for a digit

    // Get the information for this digit
    AliTOFSDigit *tofsdigit = (AliTOFSDigit *) fSDigitsArray->UncheckedAt(k);

    Int_t nslot=tofsdigit->GetNDigits(); // get the number of slots
    // for current sdigit

    // TOF sdigit volumes (always the same for all slots)
    Int_t sector    = tofsdigit->GetSector(); // range [1-18]
    Int_t plate     = tofsdigit->GetPlate();  // range [1- 5]
    Int_t strip     = tofsdigit->GetStrip();  // range [1-20]
    Int_t padz      = tofsdigit->GetPadz();   // range [1- 2]
    Int_t padx      = tofsdigit->GetPadx();   // range [1-48]

    vol[0] = sector;
    vol[1] = plate;
    vol[2] = strip;
    vol[3] = padx;
    vol[4] = padz;

    //--------------------- QA section ----------------------
    // in the while, I perform QA
    Bool_t isSDigitBad = (sector<1 || sector>18 || plate<1 || plate >5 || padz<1 || padz>2 || padx<1 || padx>48);

    if (isSDigitBad) {
      cout << "<AliTOFSDigits2Digits>  strange sdigit found" << endl;
      abort();
    }
    //-------------------------------------------------------

    //------------------- Dump section ----------------------
    if(k<ndump){
      cout << k << "-th | " << "Sector " << sector << " | Plate " << plate << " | Strip " << strip << " | PadZ " << padz << " | PadX " << padx << endl;
      cout << k << "-th sdigit" << endl;
      cout << "----------------------------------------------------"<< endl;
    }
    // ------------------------------------------------------

    // start loop on number of slots for current sdigit
    for (Int_t islot = 0; islot < nslot; islot++) {
      Float_t  digit[2];     // TOF digit variables
      Int_t tracknum[kMAXDIGITS];     // contributing tracks for the current slot

      Float_t tdc=tofsdigit->GetTdc(islot); digit[0]=tdc;
      Float_t adc=tofsdigit->GetAdc(islot); digit[1]=adc;

      tracknum[0]=tofsdigit->GetTrack(islot,0);
      tracknum[1]=tofsdigit->GetTrack(islot,1);
      tracknum[2]=tofsdigit->GetTrack(islot,2);

      // new with placement must be used
      // adding a TOF digit for each slot
      TClonesArray &aDigits = *fDigits;
      Int_t last=fDigits->GetEntriesFast();
      new (aDigits[last]) AliTOFdigit(tracknum, vol, digit);

    }

  } // end loop on sdigits - end digitizing all collected sdigits

}

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

void AliTOFDigitizer::ReadSDigit(Int_t inputFile )
{
  // Read sdigits for current event and inputFile;
  // store them into the sdigits container
  // and update the hit map
  // SDigits from different files are assumed to
  // be created with the same simulation parameters.

  // get the treeS from manager
  TTree* currentTreeS=fManager->GetInputTreeS(inputFile);

  // get the branch TOF inside the treeS
  TClonesArray * sdigitsDummyContainer= new TClonesArray("AliTOFSDigit",  1000);

  // check if the branch exist
  TBranch* tofBranch=currentTreeS->GetBranch("TOF");

  if(!tofBranch){
    Fatal("ReadSDigit","TOF branch not found for input %d",inputFile);
  }

  tofBranch->SetAddress(&sdigitsDummyContainer);

  Int_t nEntries = (Int_t)tofBranch->GetEntries();

  // Loop through all entries in the tree
  Int_t nbytes;

  for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {

    // Import the tree
    nbytes += tofBranch->GetEvent(iEntry);

    // Get the number of sdigits
    Int_t ndig = sdigitsDummyContainer->GetEntriesFast();

    for (Int_t k=0; k<ndig; k++) {
      AliTOFSDigit *tofSdigit= (AliTOFSDigit*) sdigitsDummyContainer->UncheckedAt(k);

      Int_t    vol[5];       // location for a sdigit

      // check the sdigit volume
      vol[0] = tofSdigit->GetSector();
      vol[1] = tofSdigit->GetPlate();
      vol[2] = tofSdigit->GetStrip();
      vol[3] = tofSdigit->GetPadx();
      vol[4] = tofSdigit->GetPadz();

      if (fhitMap->TestHit(vol) != kEmpty) {
	AliTOFSDigit *sdig = static_cast<AliTOFSDigit*>(fhitMap->GetHit(vol));
	sdig->Update(tofSdigit);

      } else {

	CollectSDigit(tofSdigit); // collect the current sdigit
	fhitMap->SetHit(vol);     // update the hitmap for location vol

      } // if (hitMap->TestHit(vol) != kEmpty)

    } // for (Int_t k=0; k<ndig; k++)

  } // end loop on entries

  sdigitsDummyContainer->Delete();
  sdigitsDummyContainer=0;

}

//_____________________________________________________________________________
void AliTOFDigitizer::CollectSDigit(AliTOFSDigit * sdigit)
{
  //
  // Add a TOF sdigit in container
  // new with placement must be used
  TClonesArray &aSDigitsArray = *fSDigitsArray;
  Int_t last=fSDigitsArray->GetEntriesFast();
  // make a copy of the current sdigit and
  // put it into tmp array
  new (aSDigitsArray[last]) AliTOFSDigit(*sdigit);
}
<|endoftext|>


<commit_before>#include "ofMath.h"
#include "ofAppRunner.h"

#ifndef TARGET_WIN32
	#include <sys/time.h>
#endif

//--------------------------------------------------
int ofNextPow2(int a){
	// from nehe.gamedev.net lesson 43
	int rval=1;
	while(rval<a) rval<<=1;
	return rval;
}

//--------------------------------------------------
void ofSeedRandom() {

	// good info here:
	// http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand

	#ifdef TARGET_WIN32
		srand(GetTickCount());
	#else
		// use XOR'd second, microsecond precision AND pid as seed
		struct timeval tv;
		gettimeofday(&tv, 0);
		long int n = (tv.tv_sec ^ tv.tv_usec) ^ getpid();
		srand(n);
	#endif
}

//--------------------------------------------------
void ofSeedRandom(int val) {
	srand((long) val);
}

//--------------------------------------------------
float ofRandom(float x, float y) {

	float high = 0;
	float low = 0;
	float randNum = 0;
	// if there is no range, return the value
	if (x == y) return x; 			// float == ?, wise? epsilon?
	high = MAX(x,y);
	low = MIN(x,y);
	randNum = low + ((high-low) * rand()/(RAND_MAX + 1.0));
	return randNum;
}

//--------------------------------------------------
float ofRandomf() {
	float randNum = 0;
	randNum = (rand()/(RAND_MAX + 1.0)) * 2.0 - 1.0;
	return randNum;
}

//--------------------------------------------------
float ofRandomuf() {
	float randNum = 0;
	randNum = rand()/(RAND_MAX + 1.0);
	return randNum;
}

//---- new to 006
//from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413

//--------------------------------------------------
float ofNormalize(float value, float min, float max){
   return ofClamp( (value - min) / (max - min), 0, 1);
}

//check for division by zero???
//--------------------------------------------------
float ofMap(float value, float inputMin, float inputMax, float outputMin, float outputMax) {
   return ((value - inputMin) / (inputMax - inputMin) * (outputMax - outputMin) + outputMin);
}

//--------------------------------------------------
float ofDist(float x1, float y1, float x2, float y2) {
   return sqrt(double((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));
}

//--------------------------------------------------
float ofDistSquared(float x1, float y1, float x2, float y2) {
   return ( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) );
}

//--------------------------------------------------
float ofClamp(float value, float min, float max) {
   return value < min ? min : value > max ? max : value;
}

// return sign of the number
//--------------------------------------------------
int ofSign(float n) {
  if( n > 0 ) return 1;
  else if(n < 0) return -1;
  else return 0;
}

//--------------------------------------------------
bool ofInRange(float t, float min, float max) {
   return t>=min && t<=max;
}

//--------------------------------------------------
float ofRadToDeg(float radians) {
   return radians * RAD_TO_DEG;
}

//--------------------------------------------------
float ofDegToRad(float degrees) {
    return degrees * DEG_TO_RAD;
}

//--------------------------------------------------
float ofLerp(float start, float stop, float amt) {
    return start + (stop-start) * amt;
}

//--------------------------------------------------
float ofRandomWidth() {
   return ofRandom(0, ofGetWidth());
}

//--------------------------------------------------
float ofRandomHeight() {
   return ofRandom(0, ofGetHeight());
}
<commit_msg>added ofMap() fixes...  (uses FLT_EPSILON) and retabbed a bit...<commit_after>#include "ofMath.h"
#include "ofAppRunner.h"

#ifndef TARGET_WIN32
	#include <sys/time.h>
#endif

//--------------------------------------------------
int ofNextPow2(int a){
	// from nehe.gamedev.net lesson 43
	int rval=1;
	while(rval<a) rval<<=1;
	return rval;
}

//--------------------------------------------------
void ofSeedRandom() {

	// good info here:
	// http://stackoverflow.com/questions/322938/recommended-way-to-initialize-srand

	#ifdef TARGET_WIN32
		srand(GetTickCount());
	#else
		// use XOR'd second, microsecond precision AND pid as seed
		struct timeval tv;
		gettimeofday(&tv, 0);
		long int n = (tv.tv_sec ^ tv.tv_usec) ^ getpid();
		srand(n);
	#endif
}

//--------------------------------------------------
void ofSeedRandom(int val) {
	srand((long) val);
}

//--------------------------------------------------
float ofRandom(float x, float y) {

	float high = 0;
	float low = 0;
	float randNum = 0;
	// if there is no range, return the value
	if (x == y) return x; 			// float == ?, wise? epsilon?
	high = MAX(x,y);
	low = MIN(x,y);
	randNum = low + ((high-low) * rand()/(RAND_MAX + 1.0));
	return randNum;
}

//--------------------------------------------------
float ofRandomf() {
	float randNum = 0;
	randNum = (rand()/(RAND_MAX + 1.0)) * 2.0 - 1.0;
	return randNum;
}

//--------------------------------------------------
float ofRandomuf() {
	float randNum = 0;
	randNum = rand()/(RAND_MAX + 1.0);
	return randNum;
}

//---- new to 006
//from the forums http://www.openframeworks.cc/forum/viewtopic.php?t=1413

//--------------------------------------------------
float ofNormalize(float value, float min, float max){
	return ofClamp( (value - min) / (max - min), 0, 1);
}

//check for division by zero???
//--------------------------------------------------
float ofMap(float value, float inputMin, float inputMax, float outputMin, float outputMax) {

	if (fabs(inputMin - inputMax) < FLT_EPSILON){
		ofLog(OF_LOG_WARNING, "ofMap: avoiding possible divide by zero, check inputMin and inputMax\n");
		return outputMin;
	} else {
		return ((value - inputMin) / (inputMax - inputMin) * (outputMax - outputMin) + outputMin);
	}

}

//--------------------------------------------------
float ofDist(float x1, float y1, float x2, float y2) {
	return sqrt(double((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));
}

//--------------------------------------------------
float ofDistSquared(float x1, float y1, float x2, float y2) {
	return ( (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) );
}

//--------------------------------------------------
float ofClamp(float value, float min, float max) {
	return value < min ? min : value > max ? max : value;
}

// return sign of the number
//--------------------------------------------------
int ofSign(float n) {
	if( n > 0 ) return 1;
	else if(n < 0) return -1;
	else return 0;
}

//--------------------------------------------------
bool ofInRange(float t, float min, float max) {
	return t>=min && t<=max;
}

//--------------------------------------------------
float ofRadToDeg(float radians) {
	return radians * RAD_TO_DEG;
}

//--------------------------------------------------
float ofDegToRad(float degrees) {
    return degrees * DEG_TO_RAD;
}

//--------------------------------------------------
float ofLerp(float start, float stop, float amt) {
	return start + (stop-start) * amt;
}

//--------------------------------------------------
float ofRandomWidth() {
	return ofRandom(0, ofGetWidth());
}

//--------------------------------------------------
float ofRandomHeight() {
	return ofRandom(0, ofGetHeight());
}
<|endoftext|>