<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, 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.                  *
 **************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Macros analyzing the ESD file
// Use Case :
//          root> .L AnaESD.C++
//          root> ana() --> prints the objects stored in ESD
//
// author  : Yves Schutz (CERN/SUBATECH)
// February 2004
//_________________________________________________________________________
#include "TFile.h"
#include "TMath.h"
#include "AliPHOSGetter.h"
#include "Riostream.h"
#include "AliESD.h"
#include "AliESDtrack.h"
#include "AliESDCaloTrack.h"
#include "AliEMCALRecParticle.h"
#include "AliPHOSRecParticle.h"
#include "AliKalmanTrack.h"

void Ana()
{
  AliPHOSGetter * gime = AliPHOSGetter::Instance("galice.root") ;
  Int_t nEvent = gime->MaxEvent() ;
  Int_t event ;
  AliESD * esd = 0 ;
  for (event = 0 ; event < nEvent; event++) {
    esd = gime->ESD(event) ;
    esd->Print();
    Int_t index ;
    // Calorimeter tracks
    AliESDCaloTrack * ct ;
    AliPHOSRecParticle * pp ;
    AliEMCALRecParticle * ep ;
    for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
      ct = esd->GetCaloTrack(index) ;
      pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
      ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
      if (pp) {
	TVector3 pos = pp->GetPos() ;
	cout << "PHOS particle # " << index << " pos " <<
	  TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() + pos.Z()*pos.Z() ) << endl ;
      }
      if(ep) {
 	TVector3 pos = ep->GetPos() ;
	cout << "EMCAL particle # " << index << " pos " <<
	  TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() + pos.Z()*pos.Z() ) << endl ;
      }
    }
    //Charged tracks from central tracking
    AliESDtrack * cp ;
    for (index = 0 ; index < esd->GetNumberOfTracks() ; index++) {
      cp = esd->GetTrack(index) ;
      ULong_t status = cp->GetStatus() ;

      // check if the tracks comes out of TRD
      if ((status & AliESDtrack::kTRDout)==0)
	continue;
      if ((status & AliESDtrack::kTRDStop)!=0)
	continue;

      // Gets the Global coordinate of the track at the entrance of PHOS
      Double_t xyzAtPHOS[3] ;
      cp->GetOuterXYZ(xyzAtPHOS) ;
      // cout << xyzAtPHOS[0] << " " << xyzAtPHOS[1] << " "<< xyzAtPHOS[2]  << endl ;
      //cout << TMath::Sqrt(xyzAtPHOS[0]*xyzAtPHOS[0] + xyzAtPHOS[1]*xyzAtPHOS[1] + xyzAtPHOS[2]*xyzAtPHOS[2]) << endl ;

      // Does the matching with PHOS/EMCAL
//       for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
// 	ct = esd->GetCaloTrack(index) ;
// 	pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
// 	ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
// 	if (pp) {
// 	  TVector3 pos = pp->GetPos() ;
// 	}
//       }
    }
  }
}
<commit_msg>Updating<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, 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.                  *
 **************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Macros analyzing the ESD file
// Use Case :
//          root> .L AnaESD.C++
//          root> ana() --> prints the objects stored in ESD
//
// author  : Yves Schutz (CERN/SUBATECH)
// February 2004
//_________________________________________________________________________
#include "TFile.h"
#include "TMath.h"
#include "AliPHOSGetter.h"
#include "AliPHOSGeometry.h"
#include "Riostream.h"
#include "AliESD.h"
#include "AliESDtrack.h"
#include "AliESDCaloTrack.h"
#include "AliEMCALRecParticle.h"
#include "AliPHOSRecParticle.h"
#include "AliKalmanTrack.h"

void Ana()
{
  AliPHOSGetter * gime = AliPHOSGetter::Instance("galice.root") ;
  Int_t nEvent = gime->MaxEvent() ;
  Int_t event ;
  AliESD * esd = 0 ;
  for (event = 0 ; event < nEvent; event++) {
    esd = gime->ESD(event) ;
    esd->Print();
    Int_t index ;
    // Calorimeter tracks
    AliESDCaloTrack * ct ;
    AliPHOSRecParticle * pp ;
    AliEMCALRecParticle * ep ;
    for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
      ct = esd->GetCaloTrack(index) ;
      pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
      ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
      if (pp) {
	TVector3 pos = pp->GetPos() ;
	cout << "PHOS particle # " << index << " pos ("
	     << pos.X() << ", " << pos.Y() << ", " <<pos.Z() << ") : (" << pos.Eta()
	     << ", " << pos.Phi()*TMath::RadToDeg() << ") : "
	     << TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() ) << endl ;
	Int_t n ;
	Double_t z,x ;
	gime->PHOSGeometry()->ImpactOnEmc(pos.Theta(), pos.Phi(), n, z, x) ;
	if (n)
	  cout << "Matching: " << n << " " << z << " " << x << endl ;
      }
      if(ep) {
 	TVector3 pos = ep->GetPos() ;
	//cout << "EMCAL particle # " << index << " pos " <<
	//  TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() ) << endl ;
      }
    }
    //Charged tracks from central tracking
    AliESDtrack * cp ;
    for (index = 0 ; index < esd->GetNumberOfTracks() ; index++) {
      cp = esd->GetTrack(index) ;
      ULong_t status = cp->GetStatus() ;

      // check if the tracks comes out of TRD
      if ((status & AliESDtrack::kTRDout)==0)
	continue;
      if ((status & AliESDtrack::kTRDStop)!=0)
	continue;

      // Gets the Global coordinate of the track at the entrance of PHOS
      Double_t xyzAtPHOS[3] ;
      cp->GetOuterXYZ(xyzAtPHOS) ;
      TVector3 poscp(xyzAtPHOS[0], xyzAtPHOS[1], xyzAtPHOS[2]) ;
      cout << "Charged particle # " << index << " pos ("
	   << poscp.X() << ", " << poscp.Y() << ", " <<poscp.Z() << ") : (" << poscp.Eta()
	   << ", " << poscp.Phi()*TMath::RadToDeg() << ") : "
	   << TMath::Sqrt(poscp.X()*poscp.X() + poscp.Y()*poscp.Y() ) << endl ;
      Int_t n ;
      Double_t z,x ;
      gime->PHOSGeometry()->ImpactOnEmc(poscp.Theta(), poscp.Phi(), n, z, x) ;
      if (n)
	cout << "Matching: " << n << " " << z << " " << x << endl ;
      // Does the matching with PHOS/EMCAL
//       for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
// 	ct = esd->GetCaloTrack(index) ;
// 	pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
// 	ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
// 	if (pp) {
// 	  TVector3 pos = pp->GetPos() ;
// 	}
//       }
    }
  }
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, 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.                  *
 **************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Macros analyzing the ESD file
// Use Case :
//          root> .L AnaESD.C++
//          root> ana() --> prints the objects stored in ESD
//
// author  : Yves Schutz (CERN/SUBATECH)
// February 2004
//_________________________________________________________________________
#include "TFile.h"
#include "TMath.h"
#include "AliPHOSGetter.h"
#include "AliPHOSGeometry.h"
#include "Riostream.h"
#include "AliESD.h"
#include "AliESDtrack.h"
#include "AliESDCaloTrack.h"
#include "AliEMCALRecParticle.h"
#include "AliPHOSRecParticle.h"
#include "AliKalmanTrack.h"

void Ana()
{
  AliPHOSGetter * gime = AliPHOSGetter::Instance("galice.root") ;
  Int_t nEvent = gime->MaxEvent() ;
  Int_t event ;
  AliESD * esd = 0 ;
  for (event = 0 ; event < nEvent; event++) {
    esd = gime->ESD(event) ;
    esd->Print();
    Int_t index ;
    // Calorimeter tracks
    AliESDCaloTrack * ct ;
    AliPHOSRecParticle * pp ;
    AliEMCALRecParticle * ep ;
    for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
      ct = esd->GetCaloTrack(index) ;
      pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
      ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
      if (pp) {
	TVector3 pos = pp->GetPos() ;
	cout << "PHOS particle # " << index << " pos ("
	     << pos.X() << ", " << pos.Y() << ", " <<pos.Z() << ") : (" << pos.Eta()
	     << ", " << pos.Phi()*TMath::RadToDeg() << ") : "
	     << TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() ) << endl ;
	Int_t n ;
	Double_t z,x ;
	gime->PHOSGeometry()->ImpactOnEmc(pos.Theta(), pos.Phi(), n, z, x) ;
	if (n)
	  cout << "Matching: " << n << " " << z << " " << x << endl ;
      }
      if(ep) {
 	TVector3 pos = ep->GetPos() ;
	//cout << "EMCAL particle # " << index << " pos " <<
	//  TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() ) << endl ;
      }
    }
    //Charged tracks from central tracking
    AliESDtrack * cp ;
    for (index = 0 ; index < esd->GetNumberOfTracks() ; index++) {
      cp = esd->GetTrack(index) ;
      ULong_t status = cp->GetStatus() ;

      // check if the tracks comes out of TRD
      if ((status & AliESDtrack::kTRDout)==0)
	continue;
      if ((status & AliESDtrack::kTRDStop)!=0)
	continue;

      // Gets the Global coordinate of the track at the entrance of PHOS
      Double_t xyzAtPHOS[3] ;
      cp->GetOuterXYZ(xyzAtPHOS) ;
      TVector3 poscp(xyzAtPHOS[0], xyzAtPHOS[1], xyzAtPHOS[2]) ;
      cout << "Charged particle # " << index << " pos ("
	   << poscp.X() << ", " << poscp.Y() << ", " <<poscp.Z() << ") : (" << poscp.Eta()
	   << ", " << poscp.Phi()*TMath::RadToDeg() << ") : "
	   << TMath::Sqrt(poscp.X()*poscp.X() + poscp.Y()*poscp.Y() ) << endl ;
      Int_t n ;
      Double_t z,x ;
      gime->PHOSGeometry()->ImpactOnEmc(poscp.Theta(), poscp.Phi(), n, z, x) ;
      if (n)
	cout << "Matching: " << n << " " << z << " " << x << endl ;
      // Does the matching with PHOS/EMCAL
//       for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
// 	ct = esd->GetCaloTrack(index) ;
// 	pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
// 	ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
// 	if (pp) {
// 	  TVector3 pos = pp->GetPos() ;
// 	}
//       }
    }
  }
}
<commit_msg>updating<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, 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.                  *
 **************************************************************************/
/* $Id$ */
//_________________________________________________________________________
// Macros analyzing the ESD file
// Use Case :
//          root> .L AnaESD.C++
//          root> ana() --> prints the objects stored in ESD
//
// author  : Yves Schutz (CERN/SUBATECH)
// February 2004
//_________________________________________________________________________
#include "TFile.h"
#include "TMath.h"
#include "AliPHOSGetter.h"
#include "AliPHOSGeometry.h"
#include "Riostream.h"
#include "AliESD.h"
#include "AliESDtrack.h"
#include "AliESDCaloTrack.h"
#include "AliEMCALRecParticle.h"
#include "AliPHOSRecParticle.h"
#include "AliKalmanTrack.h"

void Ana()
{
  AliPHOSGetter * gime = AliPHOSGetter::Instance("galice.root") ;
  Int_t nEvent = gime->MaxEvent() ;
  Int_t event ;
  AliESD * esd = 0 ;
  for (event = 0 ; event < nEvent; event++) {
    esd = gime->ESD(event) ;
    esd->Print();
    Int_t index ;
    // Calorimeter tracks
    AliESDCaloTrack * ct ;
    AliPHOSRecParticle * pp ;
    AliEMCALRecParticle * ep ;
    for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
      ct = esd->GetCaloTrack(index) ;
      pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
      ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
      if (pp) {
	TVector3 pos = pp->GetPos() ;
	cout << "PHOS particle # " << index << " pos ("
	     << pos.X() << ", " << pos.Y() << ", " <<pos.Z() << ") : (" << pos.Eta()
	     << ", " << pos.Phi()*TMath::RadToDeg() << ") : "
	     << TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() ) << endl ;
	Int_t n ;
	Double_t z,x ;
	gime->PHOSGeometry()->ImpactOnEmc(pos.Theta(), pos.Phi(), n, z, x) ;
	if (n)
	  cout << "Matching: " << n << " " << z << " " << x << endl ;
      }
      if(ep) {
 	TVector3 pos = ep->GetPos() ;
	//cout << "EMCAL particle # " << index << " pos " <<
	//  TMath::Sqrt(pos.X()*pos.X() + pos.Y()*pos.Y() ) << endl ;
      }
    }
    //Charged tracks from central tracking
    AliESDtrack * cp ;
    for (index = 0 ; index < esd->GetNumberOfTracks() ; index++) {
      cp = esd->GetTrack(index) ;
      Double_t xyzAtPHOS[3] ;
      cp->GetOuterXYZ(xyzAtPHOS) ;
      // check if the track reaches PHOS
      if ( (xyzAtPHOS[0] +  xyzAtPHOS[1] + xyzAtPHOS[2]) == 0.)
	continue;
      // the next check are only if we want high quality tracks
      //       ULong_t status = cp->GetStatus() ;
      //       if ((status & AliESDtrack::kTRDput)==0)
      // 	continue;
      //       if ((status & AliESDtrack::kTRDStop)!=0)
      // 	continue;

      // Gets the Global coordinate of the track at the entrance of PHOS

      TVector3 poscp(xyzAtPHOS[0], xyzAtPHOS[1], xyzAtPHOS[2]) ;
      cout << "Charged particle # " << index << " pos ("
	   << poscp.X() << ", " << poscp.Y() << ", " <<poscp.Z() << ") : (" << poscp.Eta()
	   << ", " << poscp.Phi()*TMath::RadToDeg() << ") : "
	   << TMath::Sqrt(poscp.X()*poscp.X() + poscp.Y()*poscp.Y() ) << endl ;
      Int_t n ;
      Double_t z,x ;
      gime->PHOSGeometry()->ImpactOnEmc(poscp.Theta(), poscp.Phi(), n, z, x) ;
      if (n)
	cout << "Matching: " << n << " " << z << " " << x << endl ;
      // Does the matching with PHOS/EMCAL
//       for (index = 0 ; index < esd->GetNumberOfCaloTracks() ; index++) {
// 	ct = esd->GetCaloTrack(index) ;
// 	pp = dynamic_cast<AliPHOSRecParticle*>(ct->GetRecParticle()) ;
// 	ep = dynamic_cast<AliEMCALRecParticle*>(ct->GetRecParticle()) ;
// 	if (pp) {
// 	  TVector3 pos = pp->GetPos() ;
// 	}
//       }
    }
  }
}
<|endoftext|>


<commit_before>#ifndef OBJECT_ENCODER_HPP
#define OBJECT_ENCODER_HPP

#include <boost/assert.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>

#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

#include <cstdint>
#include <climits>

namespace osrm
{
namespace engine
{

namespace detail
{
static_assert(CHAR_BIT == 8u, "we assume a byte holds 8 bits");
static_assert(sizeof(char) == 1u, "we assume a char is one byte large");

using Base64FromBinary = boost::archive::iterators::base64_from_binary<
    boost::archive::iterators::transform_width<const char *, // sequence of chars
                                               6,            // get view of 6 bit
                                               8             // from sequence of 8 bit
                                               >>;

using BinaryFromBase64 = boost::archive::iterators::transform_width<
    boost::archive::iterators::binary_from_base64<std::string::const_iterator>,
    8, // get a view of 8 bit
    6  // from a sequence of 6 bit
    >;
} // ns detail

template <typename T> std::string encodeBase64(const T &x)
{
    // static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");

    std::vector<unsigned char> bytes{reinterpret_cast<const char *>(&x),
                                     reinterpret_cast<const char *>(&x) + sizeof(T)};
    BOOST_ASSERT(!bytes.empty());

    const auto next_divisible_by_three = ((bytes.size() / 3u) + 1u) * 3u;
    BOOST_ASSERT(next_divisible_by_three >= bytes.size());

    const auto bytes_to_pad = next_divisible_by_three - bytes.size();
    BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2);

    bytes.insert(end(bytes), bytes_to_pad, 0x00);
    BOOST_ASSERT_MSG(0 == bytes.size() % 3, "base64 input data size is not a multiple of 3");

    std::string encoded{detail::Base64FromBinary{bytes.data()},
                        detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}};

    std::replace(begin(encoded), end(encoded), '+', '-');
    std::replace(begin(encoded), end(encoded), '/', '_');

    return encoded;
}

template <typename T> T decodeBase64(std::string encoded)
{
    // static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");

    std::replace(begin(encoded), end(encoded), '-', '+');
    std::replace(begin(encoded), end(encoded), '_', '/');

    T rv;

    std::copy(detail::BinaryFromBase64{begin(encoded)},
              detail::BinaryFromBase64{begin(encoded) + encoded.length()},
              reinterpret_cast<char *>(&rv));

    return rv;
}

} // ns engine
} // ns osrm

#endif /* OBJECT_ENCODER_HPP */
<commit_msg>Ifdef is_trivially_copyable<T> behind gcc >= 5 guard<commit_after>#ifndef OBJECT_ENCODER_HPP
#define OBJECT_ENCODER_HPP

#include <boost/assert.hpp>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>

#include <algorithm>
#include <iterator>
#include <string>
#include <vector>

#include <cstdint>
#include <climits>

namespace osrm
{
namespace engine
{

namespace detail
{
static_assert(CHAR_BIT == 8u, "we assume a byte holds 8 bits");
static_assert(sizeof(char) == 1u, "we assume a char is one byte large");

using Base64FromBinary = boost::archive::iterators::base64_from_binary<
    boost::archive::iterators::transform_width<const char *, // sequence of chars
                                               6,            // get view of 6 bit
                                               8             // from sequence of 8 bit
                                               >>;

using BinaryFromBase64 = boost::archive::iterators::transform_width<
    boost::archive::iterators::binary_from_base64<std::string::const_iterator>,
    8, // get a view of 8 bit
    6  // from a sequence of 6 bit
    >;
} // ns detail

template <typename T> std::string encodeBase64(const T &x)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    std::vector<unsigned char> bytes{reinterpret_cast<const char *>(&x),
                                     reinterpret_cast<const char *>(&x) + sizeof(T)};
    BOOST_ASSERT(!bytes.empty());

    const auto next_divisible_by_three = ((bytes.size() / 3u) + 1u) * 3u;
    BOOST_ASSERT(next_divisible_by_three >= bytes.size());

    const auto bytes_to_pad = next_divisible_by_three - bytes.size();
    BOOST_ASSERT(bytes_to_pad == 0 || bytes_to_pad == 1 || bytes_to_pad == 2);

    bytes.insert(end(bytes), bytes_to_pad, 0x00);
    BOOST_ASSERT_MSG(0 == bytes.size() % 3, "base64 input data size is not a multiple of 3");

    std::string encoded{detail::Base64FromBinary{bytes.data()},
                        detail::Base64FromBinary{bytes.data() + (bytes.size() - bytes_to_pad)}};

    std::replace(begin(encoded), end(encoded), '+', '-');
    std::replace(begin(encoded), end(encoded), '/', '_');

    return encoded;
}

template <typename T> T decodeBase64(std::string encoded)
{
#if not defined __GNUC__ or __GNUC__ > 4
    static_assert(std::is_trivially_copyable<T>::value, "requires a trivially copyable type");
#endif

    std::replace(begin(encoded), end(encoded), '-', '+');
    std::replace(begin(encoded), end(encoded), '_', '/');

    T rv;

    std::copy(detail::BinaryFromBase64{begin(encoded)},
              detail::BinaryFromBase64{begin(encoded) + encoded.length()},
              reinterpret_cast<char *>(&rv));

    return rv;
}

} // ns engine
} // ns osrm

#endif /* OBJECT_ENCODER_HPP */
<|endoftext|>


<commit_before>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include "include/mapviz_plugins/point_click_publisher_plugin.h"
#include <geometry_msgs/PointStamped.h>
#include <yaml_util/yaml_util.h>

#include <boost/shared_ptr.hpp>

// Declare plugin
#include <pluginlib/class_list_macros.h>
PLUGINLIB_DECLARE_CLASS(
    mapviz_plugins,
    point_click_publisher,
    mapviz_plugins::PointClickPublisherPlugin,
    mapviz::MapvizPlugin)

namespace mapviz_plugins {

  PointClickPublisherPlugin::PointClickPublisherPlugin() :
  config_widget_(new QWidget()),
  canvas_(NULL)
  {
    ui_.setupUi(config_widget_);

    connect(&click_filter_, SIGNAL(pointClicked(const QPointF&)),
            this, SLOT(pointClicked(const QPointF&)));
    connect(ui_.topic, SIGNAL(textEdited(const QString&)),
            this, SLOT(topicChanged(const QString&)));

    frame_timer_.start(1000);
    connect(&frame_timer_, SIGNAL(timeout()), this, SLOT(updateFrames()));
  }

  PointClickPublisherPlugin::~PointClickPublisherPlugin()
  {
    if (canvas_) {
      canvas_->removeEventFilter(&click_filter_);
    }
  }

  bool PointClickPublisherPlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = static_cast<mapviz::MapCanvas*>(canvas);
    canvas_->installEventFilter(&click_filter_);

    PrintInfo("Ready.");

    return true;
  }

  void PointClickPublisherPlugin::Draw(double x, double y, double scale)
  {
  }

  void PointClickPublisherPlugin::LoadConfig(const YAML::Node& node, const std::string& path)
  {
    std::string tmp;
    if (node.FindValue("topic"))
    {
      node["topic"] >> tmp;
      ui_.topic->setText(QString(tmp.c_str()));
    }

    topicChanged(ui_.topic->text());

    if (node.FindValue("output_frame"))
    {
      node["output_frame"] >> tmp;
      ui_.outputframe->addItem(QString(tmp.c_str()));
    }
  }

  void PointClickPublisherPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path)
  {
    emitter << YAML::Key << "topic" << YAML::Value << ui_.topic->text().toStdString();
    emitter << YAML::Key << "output_frame" << YAML::Value << ui_.outputframe->currentText().toStdString();
  }

  QWidget* PointClickPublisherPlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  void PointClickPublisherPlugin::pointClicked(const QPointF& point)
  {
    QPointF transformed = canvas_->MapGlCoordToFixedFrame(point);

    std::string output_frame = ui_.outputframe->currentText().toStdString();

    if (target_frame_ != output_frame) {
      transform_util::Transform tf;
      tf::Point tfPoint(transformed.x(), transformed.y(), 0.0);
      if (tf_manager_.GetTransform(output_frame, target_frame_, tf)) {
        tfPoint = tf * tfPoint;
      }
      else {
        std::stringstream error;
        error << "Unable to find transform from " << target_frame_ << " to " << output_frame << ".";
        PrintError(error.str());
        return;
      }
      transformed.setX(tfPoint.x());
      transformed.setY(tfPoint.y());
    }

    std::stringstream ss;
    ss << "Point in " << output_frame.c_str() << ": " << transformed.x() << "," << transformed.y();
    PrintInfo(ss.str());

    boost::shared_ptr<geometry_msgs::PointStamped> stamped = boost::make_shared<geometry_msgs::PointStamped>();
    stamped->header.frame_id = output_frame;
    stamped->header.stamp = ros::Time::now();
    stamped->point.x = transformed.x();
    stamped->point.y = transformed.y();
    stamped->point.z = 0.0;

    point_publisher_.publish(stamped);
  }

  void PointClickPublisherPlugin::SetNode(const ros::NodeHandle& node)
  {
    mapviz::MapvizPlugin::SetNode(node);

    // We override this method so that we can initialize our publisher after
    // our node has been set, ensuring that it's in mapviz's namespace.
    topicChanged(ui_.topic->text());
  }

  void PointClickPublisherPlugin::PrintError(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_ERROR("Error: %s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void PointClickPublisherPlugin::PrintInfo(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_INFO("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::green);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void PointClickPublisherPlugin::PrintWarning(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_WARN("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::darkYellow);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void PointClickPublisherPlugin::topicChanged(const QString& topic)
  {
    std::stringstream ss;
    ss << "Publishing points to topic: " << topic.toStdString().c_str();
    PrintInfo(ss.str());

    if (!topic.isEmpty())
    {
      point_publisher_ = node_.advertise<geometry_msgs::PointStamped>(topic.toStdString(), 1000);
    }
  }

  void PointClickPublisherPlugin::updateFrames()
  {
    std::vector<std::string> frames;
    tf_->getFrameStrings(frames);

    if (ui_.outputframe->count() >= 0 &&
        static_cast<size_t>(ui_.outputframe->count()) == frames.size())
    {
      bool changed = false;
      for (size_t i = 0; i < frames.size(); i++)
      {
        if (frames[i] != ui_.outputframe->itemText(i).toStdString())
        {
          changed = true;
        }
      }

      if (!changed)
        return;
    }

    std::string current_output = ui_.outputframe->currentText().toStdString();

    ui_.outputframe->clear();
    for (size_t i = 0; i < frames.size(); i++)
    {
      ui_.outputframe->addItem(frames[i].c_str());
    }

    if (current_output != "")
    {
      int index = ui_.outputframe->findText(current_output.c_str());
      if (index < 0)
      {
        ui_.outputframe->addItem(current_output.c_str());
      }

      index = ui_.outputframe->findText(current_output.c_str());
      ui_.outputframe->setCurrentIndex(index);
    }
  }
}<commit_msg>Indigo compatibility.<commit_after>// *****************************************************************************
//
// Copyright (c) 2014, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include "include/mapviz_plugins/point_click_publisher_plugin.h"
#include <geometry_msgs/PointStamped.h>
#include <swri_yaml_util/yaml_util.h>

#include <boost/shared_ptr.hpp>

// Declare plugin
#include <pluginlib/class_list_macros.h>
PLUGINLIB_DECLARE_CLASS(
    mapviz_plugins,
    point_click_publisher,
    mapviz_plugins::PointClickPublisherPlugin,
    mapviz::MapvizPlugin)

namespace mapviz_plugins {

  PointClickPublisherPlugin::PointClickPublisherPlugin() :
  config_widget_(new QWidget()),
  canvas_(NULL)
  {
    ui_.setupUi(config_widget_);

    connect(&click_filter_, SIGNAL(pointClicked(const QPointF&)),
            this, SLOT(pointClicked(const QPointF&)));
    connect(ui_.topic, SIGNAL(textEdited(const QString&)),
            this, SLOT(topicChanged(const QString&)));

    frame_timer_.start(1000);
    connect(&frame_timer_, SIGNAL(timeout()), this, SLOT(updateFrames()));
  }

  PointClickPublisherPlugin::~PointClickPublisherPlugin()
  {
    if (canvas_) {
      canvas_->removeEventFilter(&click_filter_);
    }
  }

  bool PointClickPublisherPlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = static_cast<mapviz::MapCanvas*>(canvas);
    canvas_->installEventFilter(&click_filter_);

    PrintInfo("Ready.");

    return true;
  }

  void PointClickPublisherPlugin::Draw(double x, double y, double scale)
  {
  }

  void PointClickPublisherPlugin::LoadConfig(const YAML::Node& node, const std::string& path)
  {
    std::string tmp;
    if (swri_yaml_util::FindValue(node, "topic"))
    {
      node["topic"] >> tmp;
      ui_.topic->setText(QString(tmp.c_str()));
    }

    topicChanged(ui_.topic->text());

    if (swri_yaml_util::FindValue(node, "output_frame"))
    {
      node["output_frame"] >> tmp;
      ui_.outputframe->addItem(QString(tmp.c_str()));
    }
  }

  void PointClickPublisherPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path)
  {
    emitter << YAML::Key << "topic" << YAML::Value << ui_.topic->text().toStdString();
    emitter << YAML::Key << "output_frame" << YAML::Value << ui_.outputframe->currentText().toStdString();
  }

  QWidget* PointClickPublisherPlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  void PointClickPublisherPlugin::pointClicked(const QPointF& point)
  {
    QPointF transformed = canvas_->MapGlCoordToFixedFrame(point);

    std::string output_frame = ui_.outputframe->currentText().toStdString();

    if (target_frame_ != output_frame) {
      swri_transform_util::Transform tf;
      tf::Point tfPoint(transformed.x(), transformed.y(), 0.0);
      if (tf_manager_.GetTransform(output_frame, target_frame_, tf)) {
        tfPoint = tf * tfPoint;
      }
      else {
        std::stringstream error;
        error << "Unable to find transform from " << target_frame_ << " to " << output_frame << ".";
        PrintError(error.str());
        return;
      }
      transformed.setX(tfPoint.x());
      transformed.setY(tfPoint.y());
    }

    std::stringstream ss;
    ss << "Point in " << output_frame.c_str() << ": " << transformed.x() << "," << transformed.y();
    PrintInfo(ss.str());

    boost::shared_ptr<geometry_msgs::PointStamped> stamped = boost::make_shared<geometry_msgs::PointStamped>();
    stamped->header.frame_id = output_frame;
    stamped->header.stamp = ros::Time::now();
    stamped->point.x = transformed.x();
    stamped->point.y = transformed.y();
    stamped->point.z = 0.0;

    point_publisher_.publish(stamped);
  }

  void PointClickPublisherPlugin::SetNode(const ros::NodeHandle& node)
  {
    mapviz::MapvizPlugin::SetNode(node);

    // We override this method so that we can initialize our publisher after
    // our node has been set, ensuring that it's in mapviz's namespace.
    topicChanged(ui_.topic->text());
  }

  void PointClickPublisherPlugin::PrintError(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_ERROR("Error: %s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void PointClickPublisherPlugin::PrintInfo(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_INFO("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::green);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void PointClickPublisherPlugin::PrintWarning(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_WARN("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::darkYellow);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void PointClickPublisherPlugin::topicChanged(const QString& topic)
  {
    std::stringstream ss;
    ss << "Publishing points to topic: " << topic.toStdString().c_str();
    PrintInfo(ss.str());

    if (!topic.isEmpty())
    {
      point_publisher_ = node_.advertise<geometry_msgs::PointStamped>(topic.toStdString(), 1000);
    }
  }

  void PointClickPublisherPlugin::updateFrames()
  {
    std::vector<std::string> frames;
    tf_->getFrameStrings(frames);

    if (ui_.outputframe->count() >= 0 &&
        static_cast<size_t>(ui_.outputframe->count()) == frames.size())
    {
      bool changed = false;
      for (size_t i = 0; i < frames.size(); i++)
      {
        if (frames[i] != ui_.outputframe->itemText(i).toStdString())
        {
          changed = true;
        }
      }

      if (!changed)
        return;
    }

    std::string current_output = ui_.outputframe->currentText().toStdString();

    ui_.outputframe->clear();
    for (size_t i = 0; i < frames.size(); i++)
    {
      ui_.outputframe->addItem(frames[i].c_str());
    }

    if (current_output != "")
    {
      int index = ui_.outputframe->findText(current_output.c_str());
      if (index < 0)
      {
        ui_.outputframe->addItem(current_output.c_str());
      }

      index = ui_.outputframe->findText(current_output.c_str());
      ui_.outputframe->setCurrentIndex(index);
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) ICG. All rights reserved.
 *
 * Institute for Computer Graphics and Vision
 * Graz University of Technology / Austria
 *
 *
 * This software is distributed WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the above copyright notices for more information.
 *
 *
 * Project     : ImageUtilities
 * Module      : Unit Tests
 * Class       : none
 * Language    : C++
 * Description : Unit tests for VideoCapture class
 *
 * Author     : Manuel Werlberger
 * EMail      : werlberger@icg.tugraz.at
 *
 */

// system includes
#include <iostream>
#include <cuda_runtime.h>

#include <iudefs.h>
#include <iucore.h>
#include <iuio.h>
#include <iuvideocapture.h>
#include <highgui.h>

int main(int argc, char** argv)
{
  iu::VideoCapture* cap = 0;

  int device = 0;
  if(argc < 2)
  {
    std::cout << "using camera" << std::endl;
    cap = new iu::VideoCapture(device);
  }
  else
  {
    std::string filename = argv[1];
    std::cout << "reading video " << filename << std::endl;
    cap = new iu::VideoCapture(filename);
  }

  for(;;)
  {
    printf("cap image size = %d/%d\n", cap->size().width, cap->size().height);
    iu::ImageCpu_32f_C1 image(cap->size());
    printf("trying to get image\n");
    if(cap->getImage(&image))
    {
      printf("display image\n");
      iu::imshow(&image, "cpu image");
      printf("next round\n");
    }
    printf("wait\n");
//    cv::waitKey();
    printf("main next round...\n");
    //if(cv::waitKey(30) >= 0) break;
  }

  std::cout << std::endl;
  std::cout << "**************************************************************************" << std::endl;
//  std::cout << "*  Everything seem to be ok. -- All assertions passed.                   *" << std::endl;
  std::cout << "*  Look at the images and press a key to close the windows and derminate the unittests.  *" << std::endl;
  std::cout << "**************************************************************************" << std::endl;
  std::cout << std::endl;

  cv::waitKey();

  // CLEANUP
  delete(cap);

  return EXIT_SUCCESS;

}
<commit_msg><commit_after>/*
 * Copyright (c) ICG. All rights reserved.
 *
 * Institute for Computer Graphics and Vision
 * Graz University of Technology / Austria
 *
 *
 * This software is distributed WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the above copyright notices for more information.
 *
 *
 * Project     : ImageUtilities
 * Module      : Unit Tests
 * Class       : none
 * Language    : C++
 * Description : Unit tests for VideoCapture class
 *
 * Author     : Manuel Werlberger
 * EMail      : werlberger@icg.tugraz.at
 *
 */

// system includes
#include <iostream>
#include <cuda_runtime.h>

#include <iudefs.h>
#include <iucore.h>
#include <iuio.h>
#include <iuvideocapture.h>
#include <highgui.h>

int main(int argc, char** argv)
{
  iu::VideoCapture* cap = 0;

  int device = 0;
  if(argc < 2)
  {
    std::cout << "using camera" << std::endl;
    cap = new iu::VideoCapture(device);
  }
  else
  {
    std::string filename = argv[1];
    std::cout << "reading video " << filename << std::endl;
    cap = new iu::VideoCapture(filename);
  }

  for(;;)
  {
    printf("cap image size = %d/%d\n", cap->size().width, cap->size().height);
    iu::ImageCpu_32f_C1 image(cap->size());
    printf("trying to get image\n");
    if(cap->getImage(&image))
    {
      printf("display image\n");
      iu::imshow(&image, "cpu image");
      printf("next round\n");
    }
    printf("wait\n");
//    cv::waitKey();
    printf("main next round...\n");
    if(cv::waitKey(30) >= 0) break;
  }

  std::cout << std::endl;
  std::cout << "**************************************************************************" << std::endl;
//  std::cout << "*  Everything seem to be ok. -- All assertions passed.                   *" << std::endl;
  std::cout << "*  Look at the images and press a key to close the windows and derminate the unittests.  *" << std::endl;
  std::cout << "**************************************************************************" << std::endl;
  std::cout << std::endl;

  cv::waitKey();

  // CLEANUP
  delete(cap);

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer --------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format Alpha assembly language.
//
//===----------------------------------------------------------------------===//

#include "Alpha.h"
#include "AlphaInstrInfo.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/AsmPrinter.h"

#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"

#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include <cctype>
using namespace llvm;

namespace {
  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");

  struct AlphaAsmPrinter : public AsmPrinter {

    /// Unique incrementer for label values for referencing Global values.
    ///
    unsigned LabelNumber;

     AlphaAsmPrinter(std::ostream &o, TargetMachine &tm)
      : AsmPrinter(o, tm), LabelNumber(0)
    { }

    /// We name each basic block in a Function with a unique number, so
    /// that we can consistently refer to them later. This is cleared
    /// at the beginning of each call to runOnMachineFunction().
    ///
    typedef std::map<const Value *, unsigned> ValueMapTy;
    ValueMapTy NumberForBB;

    virtual const char *getPassName() const {
      return "Alpha Assembly Printer";
    }
    bool printInstruction(const MachineInstr *MI);
    void printOp(const MachineOperand &MO, bool IsCallOp = false);
    void printConstantPool(MachineConstantPool *MCP);
    void printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT);
    void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
    void printMachineInstruction(const MachineInstr *MI);
    bool runOnMachineFunction(MachineFunction &F);
    bool doInitialization(Module &M);
    bool doFinalization(Module &M);
  };
} // end of anonymous namespace

/// createAlphaCodePrinterPass - Returns a pass that prints the Alpha
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description.  This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createAlphaCodePrinterPass (std::ostream &o,
                                                  TargetMachine &tm) {
  return new AlphaAsmPrinter(o, tm);
}

#include "AlphaGenAsmWriter.inc"

void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT)
{
  const MachineOperand &MO = MI->getOperand(opNum);
  if (MO.getType() == MachineOperand::MO_MachineRegister) {
    assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
    O << LowercaseString(TM.getRegisterInfo()->get(MO.getReg()).Name);
  } else if (MO.isImmediate()) {
    O << MO.getImmedValue();
  } else {
    printOp(MO);
  }
}

void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
  const MRegisterInfo &RI = *TM.getRegisterInfo();
  int new_symbol;

  switch (MO.getType()) {
  case MachineOperand::MO_VirtualRegister:
    if (Value *V = MO.getVRegValueOrNull()) {
      O << "<" << V->getName() << ">";
      return;
    }
    // FALLTHROUGH
  case MachineOperand::MO_MachineRegister:
  case MachineOperand::MO_CCRegister:
    O << LowercaseString(RI.get(MO.getReg()).Name);
    return;

  case MachineOperand::MO_SignExtendedImmed:
  case MachineOperand::MO_UnextendedImmed:
    std::cerr << "printOp() does not handle immediate values\n";
    abort();
    return;

  case MachineOperand::MO_PCRelativeDisp:
    std::cerr << "Shouldn't use addPCDisp() when building PPC MachineInstrs";
    abort();
    return;

  case MachineOperand::MO_MachineBasicBlock: {
    MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
    O << "$LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
      << "_" << MBBOp->getNumber() << "\t" << CommentString << " "
      << MBBOp->getBasicBlock()->getName();
    return;
  }

  case MachineOperand::MO_ConstantPoolIndex:
    O << "$CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
    return;

  case MachineOperand::MO_ExternalSymbol:
    O << MO.getSymbolName();
    return;

  case MachineOperand::MO_GlobalAddress:
    //std::cerr << "Global Addresses?  Are you kidding?\n"
    //abort();
    O << Mang->getValueName(MO.getGlobal());
    return;

  default:
    O << "<unknown operand type: " << MO.getType() << ">";
    return;
  }
}

/// printMachineInstruction -- Print out a single Alpha MI to
/// the current output stream.
///
void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
  ++EmittedInsts;
  if (printInstruction(MI))
    return; // Printer was automatically generated

  assert(0 && "Unhandled instruction in asm writer!");
  abort();
  return;
}

/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  setupMachineFunction(MF);
  O << "\n\n";

  if (CurrentFnName.compare("main") == 0)
    {
      O << "\n\n#HACK\n\t.text\n\t.ent __main\n__main:\n\tret $31,($26),1\n\t.end __main\n#ENDHACK\n\n";
    }

  // Print out constants referenced by the function
  printConstantPool(MF.getConstantPool());

  // Print out labels for the function.
  O << "\t.text\n";
  emitAlignment(2);
  O << "\t.globl\t" << CurrentFnName << "\n";
  O << "\t.ent\t" << CurrentFnName << "\n";

  O << CurrentFnName << ":\n";

  // Print out code for the function.
  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
       I != E; ++I) {
    // Print a label for the basic block.
    O << "$LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
      << CommentString << " " << I->getBasicBlock()->getName() << "\n";
    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
         II != E; ++II) {
      // Print the assembly for the instruction.
      O << "\t";
      printMachineInstruction(II);
    }
  }
  ++LabelNumber;

  O << "\t.end\t" << CurrentFnName << "\n";

  // We didn't modify anything.
  return false;
}

/// printConstantPool - Print to the current output stream assembly
/// representations of the constants in the constant pool MCP. This is
/// used to print out constants which have been "spilled to memory" by
/// the code generator.
///
void AlphaAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
  const std::vector<Constant*> &CP = MCP->getConstants();
  const TargetData &TD = TM.getTargetData();

  if (CP.empty()) return;

  abort();
//   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
//     O << "\t.section\t.rodata\n";
//     emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
//     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
//       << *CP[i] << "\n";
//     //emitGlobalConstant(CP[i]);
//   }
}

bool AlphaAsmPrinter::doInitialization(Module &M)
{
  AsmPrinter::doInitialization(M);
  O << "\t.arch ev56\n";
  return false;
}

// SwitchSection - Switch to the specified section of the executable if we are
// not already in it!
//
static void SwitchSection(std::ostream &OS, std::string &CurSection,
                          const char *NewSection) {
  if (CurSection != NewSection) {
    CurSection = NewSection;
    if (!CurSection.empty())
      OS << "\t" << NewSection << "\n";
  }
}

bool AlphaAsmPrinter::doFinalization(Module &M) {
  const TargetData &TD = TM.getTargetData();
  std::string CurSection;

  for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
    if (I->hasInitializer()) {   // External global require no code
      O << "\n\n";
      std::string name = Mang->getValueName(I);
      Constant *C = I->getInitializer();
      unsigned Size = TD.getTypeSize(C->getType());
      unsigned Align = TD.getTypeAlignmentShift(C->getType());

      if (C->isNullValue() &&
          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
        SwitchSection(O, CurSection, ".data");
        if (I->hasInternalLinkage())
          O << "\t.local " << name << "\n";

        O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
          << "," << (1 << Align);
        O << "\t\t# ";
        WriteAsOperand(O, I, true, true, &M);
        O << "\n";
      } else {
        switch (I->getLinkage()) {
        case GlobalValue::LinkOnceLinkage:
        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
          // Nonnull linkonce -> weak
          O << "\t.weak " << name << "\n";
          SwitchSection(O, CurSection, "");
          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
          break;
        case GlobalValue::AppendingLinkage:
          // FIXME: appending linkage variables should go into a section of
          // their name or something.  For now, just emit them as external.
        case GlobalValue::ExternalLinkage:
          // If external or appending, declare as a global symbol
          O << "\t.globl " << name << "\n";
          // FALL THROUGH
        case GlobalValue::InternalLinkage:
          if (C->isNullValue())
            SwitchSection(O, CurSection, ".bss");
          else
            SwitchSection(O, CurSection, ".data");
          break;
        case GlobalValue::GhostLinkage:
          std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n";
          abort();
        }

        emitAlignment(Align);
        O << "\t.type " << name << ",@object\n";
        O << "\t.size " << name << "," << Size << "\n";
        O << name << ":\t\t\t\t# ";
        WriteAsOperand(O, I, true, true, &M);
        O << " = ";
        WriteAsOperand(O, C, false, false, &M);
        O << "\n";
        emitGlobalConstant(C);
      }
    }

  AsmPrinter::doFinalization(M);
  return false;
}
<commit_msg>Pruned includes<commit_after>//===-- AlphaAsmPrinter.cpp - Alpha LLVM assembly writer ------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains a printer that converts from our internal representation
// of machine-dependent LLVM code to GAS-format Alpha assembly language.
//
//===----------------------------------------------------------------------===//

#include "Alpha.h"
#include "AlphaInstrInfo.h"
#include "llvm/Module.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/CodeGen/AsmPrinter.h"

#include "llvm/Target/TargetMachine.h"

#include "llvm/Support/Mangler.h"
#include "llvm/ADT/Statistic.h"

using namespace llvm;

namespace {
  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");

  struct AlphaAsmPrinter : public AsmPrinter {

    /// Unique incrementer for label values for referencing Global values.
    ///
    unsigned LabelNumber;

     AlphaAsmPrinter(std::ostream &o, TargetMachine &tm)
      : AsmPrinter(o, tm), LabelNumber(0)
    { }

    /// We name each basic block in a Function with a unique number, so
    /// that we can consistently refer to them later. This is cleared
    /// at the beginning of each call to runOnMachineFunction().
    ///
    typedef std::map<const Value *, unsigned> ValueMapTy;
    ValueMapTy NumberForBB;

    virtual const char *getPassName() const {
      return "Alpha Assembly Printer";
    }
    bool printInstruction(const MachineInstr *MI);
    void printOp(const MachineOperand &MO, bool IsCallOp = false);
    void printConstantPool(MachineConstantPool *MCP);
    void printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT);
    void printBaseOffsetPair (const MachineInstr *MI, int i, bool brackets=true);
    void printMachineInstruction(const MachineInstr *MI);
    bool runOnMachineFunction(MachineFunction &F);
    bool doInitialization(Module &M);
    bool doFinalization(Module &M);
  };
} // end of anonymous namespace

/// createAlphaCodePrinterPass - Returns a pass that prints the Alpha
/// assembly code for a MachineFunction to the given output stream,
/// using the given target machine description.  This should work
/// regardless of whether the function is in SSA form.
///
FunctionPass *llvm::createAlphaCodePrinterPass (std::ostream &o,
                                                  TargetMachine &tm) {
  return new AlphaAsmPrinter(o, tm);
}

#include "AlphaGenAsmWriter.inc"

void AlphaAsmPrinter::printOperand(const MachineInstr *MI, int opNum, MVT::ValueType VT)
{
  const MachineOperand &MO = MI->getOperand(opNum);
  if (MO.getType() == MachineOperand::MO_MachineRegister) {
    assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
    O << TM.getRegisterInfo()->get(MO.getReg()).Name;
  } else if (MO.isImmediate()) {
    O << MO.getImmedValue();
  } else {
    printOp(MO);
  }
}

void AlphaAsmPrinter::printOp(const MachineOperand &MO, bool IsCallOp) {
  const MRegisterInfo &RI = *TM.getRegisterInfo();
  int new_symbol;

  switch (MO.getType()) {
  case MachineOperand::MO_VirtualRegister:
    if (Value *V = MO.getVRegValueOrNull()) {
      O << "<" << V->getName() << ">";
      return;
    }
    // FALLTHROUGH
  case MachineOperand::MO_MachineRegister:
  case MachineOperand::MO_CCRegister:
    O << RI.get(MO.getReg()).Name;
    return;

  case MachineOperand::MO_SignExtendedImmed:
  case MachineOperand::MO_UnextendedImmed:
    std::cerr << "printOp() does not handle immediate values\n";
    abort();
    return;

  case MachineOperand::MO_PCRelativeDisp:
    std::cerr << "Shouldn't use addPCDisp() when building Alpha MachineInstrs";
    abort();
    return;

  case MachineOperand::MO_MachineBasicBlock: {
    MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
    O << "$LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
      << "_" << MBBOp->getNumber() << "\t" << CommentString << " "
      << MBBOp->getBasicBlock()->getName();
    return;
  }

  case MachineOperand::MO_ConstantPoolIndex:
    O << "$CPI" << CurrentFnName << "_" << MO.getConstantPoolIndex();
    return;

  case MachineOperand::MO_ExternalSymbol:
    O << MO.getSymbolName();
    return;

  case MachineOperand::MO_GlobalAddress:
    O << Mang->getValueName(MO.getGlobal());
    return;

  default:
    O << "<unknown operand type: " << MO.getType() << ">";
    return;
  }
}

/// printMachineInstruction -- Print out a single Alpha MI to
/// the current output stream.
///
void AlphaAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
  ++EmittedInsts;
  if (printInstruction(MI))
    return; // Printer was automatically generated

  assert(0 && "Unhandled instruction in asm writer!");
  abort();
  return;
}

/// runOnMachineFunction - This uses the printMachineInstruction()
/// method to print assembly for each instruction.
///
bool AlphaAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
  setupMachineFunction(MF);
  O << "\n\n";

  if (CurrentFnName.compare("main") == 0)
    {
      O << "\n\n#HACK\n\t.text\n\t.ent __main\n__main:\n\tret $31,($26),1\n\t.end __main\n#ENDHACK\n\n";
    }

  // Print out constants referenced by the function
  printConstantPool(MF.getConstantPool());

  // Print out labels for the function.
  O << "\t.text\n";
  emitAlignment(2);
  O << "\t.globl\t" << CurrentFnName << "\n";
  O << "\t.ent\t" << CurrentFnName << "\n";

  O << CurrentFnName << ":\n";

  // Print out code for the function.
  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
       I != E; ++I) {
    // Print a label for the basic block.
    O << "$LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
      << CommentString << " " << I->getBasicBlock()->getName() << "\n";
    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
         II != E; ++II) {
      // Print the assembly for the instruction.
      O << "\t";
      printMachineInstruction(II);
    }
  }
  ++LabelNumber;

  O << "\t.end\t" << CurrentFnName << "\n";

  // We didn't modify anything.
  return false;
}

/// printConstantPool - Print to the current output stream assembly
/// representations of the constants in the constant pool MCP. This is
/// used to print out constants which have been "spilled to memory" by
/// the code generator.
///
void AlphaAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
  const std::vector<Constant*> &CP = MCP->getConstants();
  const TargetData &TD = TM.getTargetData();

  if (CP.empty()) return;

  abort();
//   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
//     O << "\t.section\t.rodata\n";
//     emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
//     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
//       << *CP[i] << "\n";
//     //emitGlobalConstant(CP[i]);
//   }
}

bool AlphaAsmPrinter::doInitialization(Module &M)
{
  AsmPrinter::doInitialization(M);
  O << "\t.arch ev56\n";
  return false;
}

// SwitchSection - Switch to the specified section of the executable if we are
// not already in it!
//
static void SwitchSection(std::ostream &OS, std::string &CurSection,
                          const char *NewSection) {
  if (CurSection != NewSection) {
    CurSection = NewSection;
    if (!CurSection.empty())
      OS << "\t" << NewSection << "\n";
  }
}

bool AlphaAsmPrinter::doFinalization(Module &M) {
  const TargetData &TD = TM.getTargetData();
  std::string CurSection;

  for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
    if (I->hasInitializer()) {   // External global require no code
      O << "\n\n";
      std::string name = Mang->getValueName(I);
      Constant *C = I->getInitializer();
      unsigned Size = TD.getTypeSize(C->getType());
      unsigned Align = TD.getTypeAlignmentShift(C->getType());

      if (C->isNullValue() &&
          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
        SwitchSection(O, CurSection, ".data");
        if (I->hasInternalLinkage())
          O << "\t.local " << name << "\n";

        O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
          << "," << (1 << Align);
        O << "\t\t# ";
        WriteAsOperand(O, I, true, true, &M);
        O << "\n";
      } else {
        switch (I->getLinkage()) {
        case GlobalValue::LinkOnceLinkage:
        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
          // Nonnull linkonce -> weak
          O << "\t.weak " << name << "\n";
          SwitchSection(O, CurSection, "");
          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
          break;
        case GlobalValue::AppendingLinkage:
          // FIXME: appending linkage variables should go into a section of
          // their name or something.  For now, just emit them as external.
        case GlobalValue::ExternalLinkage:
          // If external or appending, declare as a global symbol
          O << "\t.globl " << name << "\n";
          // FALL THROUGH
        case GlobalValue::InternalLinkage:
          if (C->isNullValue())
            SwitchSection(O, CurSection, ".bss");
          else
            SwitchSection(O, CurSection, ".data");
          break;
        case GlobalValue::GhostLinkage:
          std::cerr << "GhostLinkage cannot appear in X86AsmPrinter!\n";
          abort();
        }

        emitAlignment(Align);
        O << "\t.type " << name << ",@object\n";
        O << "\t.size " << name << "," << Size << "\n";
        O << name << ":\t\t\t\t# ";
        WriteAsOperand(O, I, true, true, &M);
        O << " = ";
        WriteAsOperand(O, C, false, false, &M);
        O << "\n";
        emitGlobalConstant(C);
      }
    }

  AsmPrinter::doFinalization(M);
  return false;
}
<|endoftext|>


<commit_before>// Filename: sgiglxGraphicsPipe.cxx
// Created by:  cary (01Oct99)
//
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
// Includes
////////////////////////////////////////////////////////////////////
#include "sgiglxGraphicsPipe.h"
#include "config_sgiglxdisplay.h"

TypeHandle SgiGlxGraphicsPipe::_type_handle;

SgiGlxGraphicsPipe::SgiGlxGraphicsPipe(const PipeSpecifier& spec)
  : sgiGraphicsPipe(spec)
    glxDisplay(this, spec.get_X_specifier())
{
}

////////////////////////////////////////////////////////////////////
//     Function: SgiGlxGraphicsPipe::get_window_type
//       Access: Public, Virtual
//  Description: Returns the TypeHandle of the kind of window
//               preferred by this kind of pipe.
////////////////////////////////////////////////////////////////////
TypeHandle SgiGlxGraphicsPipe::
get_window_type() const {
  return glxGraphicsWindow::get_class_type();
}

////////////////////////////////////////////////////////////////////
//     Function: SgiGlxGraphicsPipe::get_glx_display
//       Access: Public, Virtual
//  Description: Returns the glxDisplay information associated with
//               this pipe.
////////////////////////////////////////////////////////////////////
SgiGlxDisplay *glxGraphicsPipe::
get_glx_display() {
  return this;
}

GraphicsPipe *SgiGlxGraphicsPipe::
make_sgiglxgraphicspipe(const FactoryParams &params) {
  GraphicsPipe::PipeSpec *pipe_param;
  if (!get_param_into(pipe_param, params)) {
    return new SgiGlxGraphicsPipe(PipeSpecifier());
  } else {
    return new SgiGlxGraphicsPipe(pipe_param->get_specifier());
  }
}

TypeHandle SgiGlxGraphicsPipe::get_class_type(void) {
  return _type_handle;
}

void SgiGlxGraphicsPipe::init_type(void) {
  sgiGraphicsPipe::init_type();
  glxDisplay::init_type();
  register_type(_type_handle, "SgiGlxGraphicsPipe",
		sgiGraphicsPipe::get_class_type(),
		glxDisplay::get_class_type());
}

TypeHandle SgiGlxGraphicsPipe::get_type(void) const {
  return get_class_type();
}

TypeHandle SgiGlxGraphicsPipe::force_init_type(void) {
  init_type();
  return get_class_type();
}
<commit_msg>*** empty log message ***<commit_after>// Filename: sgiglxGraphicsPipe.cxx
// Created by:  cary (01Oct99)
//
////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////
// Includes
////////////////////////////////////////////////////////////////////
#include "sgiglxGraphicsPipe.h"
#include "config_sgiglxdisplay.h"

#include <glxGraphicsWindow.h>

TypeHandle SgiGlxGraphicsPipe::_type_handle;

SgiGlxGraphicsPipe::SgiGlxGraphicsPipe(const PipeSpecifier& spec)
  : sgiGraphicsPipe(spec),
    glxDisplay(this, spec.get_X_specifier())
{
}

////////////////////////////////////////////////////////////////////
//     Function: SgiGlxGraphicsPipe::get_window_type
//       Access: Public, Virtual
//  Description: Returns the TypeHandle of the kind of window
//               preferred by this kind of pipe.
////////////////////////////////////////////////////////////////////
TypeHandle SgiGlxGraphicsPipe::
get_window_type() const {
  return glxGraphicsWindow::get_class_type();
}

////////////////////////////////////////////////////////////////////
//     Function: SgiGlxGraphicsPipe::get_glx_display
//       Access: Public, Virtual
//  Description: Returns the glxDisplay information associated with
//               this pipe.
////////////////////////////////////////////////////////////////////
glxDisplay *SgiGlxGraphicsPipe::
get_glx_display() {
  return this;
}

GraphicsPipe *SgiGlxGraphicsPipe::
make_sgiglxgraphicspipe(const FactoryParams &params) {
  GraphicsPipe::PipeSpec *pipe_param;
  if (!get_param_into(pipe_param, params)) {
    return new SgiGlxGraphicsPipe(PipeSpecifier());
  } else {
    return new SgiGlxGraphicsPipe(pipe_param->get_specifier());
  }
}

TypeHandle SgiGlxGraphicsPipe::get_class_type(void) {
  return _type_handle;
}

void SgiGlxGraphicsPipe::init_type(void) {
  sgiGraphicsPipe::init_type();
  glxDisplay::init_type();
  register_type(_type_handle, "SgiGlxGraphicsPipe",
		sgiGraphicsPipe::get_class_type(),
		glxDisplay::get_class_type());
}

TypeHandle SgiGlxGraphicsPipe::get_type(void) const {
  return get_class_type();
}

TypeHandle SgiGlxGraphicsPipe::force_init_type(void) {
  init_type();
  return get_class_type();
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <Mode.hpp>

//////////////////////////////////////////////////////////////////
TEST(Mode, test_01)
{
     using namespace linux::posix;
     Mode m(0777);
     ASSERT_EQ(0777, m.get());
}

TEST(Mode, test_02)
{
     using namespace linux::posix;
     Mode m;
     ASSERT_EQ(0644, m.get());
}
/*
TEST(Mode, test_03)
{
     using namespace linux::posix;
     Mode m;
     m.user.set_read();
     m.group.set_read();
     m.other.set_read();
     m.user.set_write();
     m.group.set_write();
     m.other.set_write();
     m.user.set_execute();
     m.group.set_execute();
     m.other.set_execute();
     ASSERT_EQ(0777, m.get());
}

TEST(Mode, test_04)
{
     using namespace linux::posix;
     Mode m1(0777);
     Mode m2;
     ASSERT_NE(m1, m2);
}

TEST(Mode, test_05)
{
     using namespace linux::posix;
     Mode m1(0777);
     Mode m2;
     m2.user.set_read();
     m2.group.set_read();
     m2.other.set_read();
     m2.user.set_write();
     m2.group.set_write();
     m2.other.set_write();
     m2.user.set_execute();
     m2.group.set_execute();
     m2.other.set_execute();
     ASSERT_EQ(m1, m2);
}
*/
//////////////////////////////////////////////////////////////////
<commit_msg>add unit test for Mode<commit_after>#include <gtest/gtest.h>
#include <Mode.hpp>

//////////////////////////////////////////////////////////////////
TEST(Mode, test_01)
{
     using namespace linux::posix;
     Mode m(0777);
     ASSERT_EQ(0777, m.get());
}

TEST(Mode, test_02)
{
     using namespace linux::posix;
     Mode m;
     ASSERT_EQ(0644, m.get());
}
/*
TEST(Mode, test_03)
{
     using namespace linux::posix;
     Mode m;
     m.user.set_read();
     m.group.set_read();
     m.other.set_read();
     m.user.set_write();
     m.group.set_write();
     m.other.set_write();
     m.user.set_execute();
     m.group.set_execute();
     m.other.set_execute();
     ASSERT_EQ(0777, m.get());
}
*/
TEST(Mode, test_04)
{
     using namespace linux::posix;
     Mode m1(0777);
     Mode m2;
     ASSERT_NE(m1, m2);
}

TEST(Mode, test_05)
{
     using namespace linux::posix;
     Mode m1;
     Mode m2;
     ASSERT_EQ(m1, m2);
}
/*
TEST(Mode, test_05)
{
     using namespace linux::posix;
     Mode m1(0777);
     Mode m2;
     m2.user.set_read();
     m2.group.set_read();
     m2.other.set_read();
     m2.user.set_write();
     m2.group.set_write();
     m2.other.set_write();
     m2.user.set_execute();
     m2.group.set_execute();
     m2.other.set_execute();
     ASSERT_EQ(m1, m2);
}
*/
//////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
 */

#include <cstdarg>
#include <cstdio>
#include <stdio.h>
#include <stdarg.h>

#include <rtl/logfile.h>
#include <osl/process.h>
#include <osl/time.h>
#include <osl/mutex.hxx>
#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/alloc.h>
#include <rtl/instance.hxx>
#include <sal/log.hxx>
#include "osl/thread.h"
#include "osl/thread.hxx"

#include <algorithm>

#ifdef _MSC_VER
#define vsnprintf _vsnprintf
#endif

using namespace osl;
using namespace std;

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace {

static oslFileHandle g_aFile = 0;
static sal_Bool g_bHasBeenCalled = sal_False;
static const sal_Int32 g_BUFFERSIZE = 4096;
static sal_Char *g_buffer = 0;

class   LoggerGuard
{
public:
    ~LoggerGuard();
};

LoggerGuard::~LoggerGuard()
{
    if( g_buffer )
    {
        sal_Int64 nWritten, nConverted =
            sprintf( g_buffer, "closing log file at %06" SAL_PRIuUINT32, osl_getGlobalTimer() );
        if( nConverted > 0 )
            osl_writeFile( g_aFile, g_buffer, nConverted, (sal_uInt64 *)&nWritten );
        osl_closeFile( g_aFile );
        g_aFile = 0;

        rtl_freeMemory( g_buffer );
        g_buffer = 0;
        g_bHasBeenCalled = sal_False;
    }
}

// The destructor of this static LoggerGuard is "activated" by the assignment to
// g_buffer in init():
LoggerGuard loggerGuard;

namespace
{
    class theLogMutex : public rtl::Static<osl::Mutex, theLogMutex>{};
}

static Mutex & getLogMutex()
{
    return theLogMutex::get();
}

OUString getFileUrl( const OUString &name )
{
    OUString aRet;
    if ( osl_getFileURLFromSystemPath( name.pData, &aRet.pData )
         != osl_File_E_None )
    {
        SAL_WARN(
            "sal.rtl", "osl_getFileURLFromSystemPath failed for \"" << name << '"');
    }

    OUString aWorkingDirectory;
    osl_getProcessWorkingDir( &(aWorkingDirectory.pData) );
    osl_getAbsoluteFileURL( aWorkingDirectory.pData, aRet.pData, &(aRet.pData) );

    return aRet;
}

void init() {
    if( !g_bHasBeenCalled )
    {
        MutexGuard guard( getLogMutex() );
        if( ! g_bHasBeenCalled )
        {
            OUString name( "RTL_LOGFILE" );
            OUString value;
            if( rtl_bootstrap_get( name.pData, &value.pData, 0 ) )
            {
                //  Obtain process id.
                oslProcessIdentifier aProcessId = 0;
                oslProcessInfo info;
                info.Size = sizeof (oslProcessInfo);
                if (osl_getProcessInfo (0, osl_Process_IDENTIFIER, &info) == osl_Process_E_None)
                    aProcessId = info.Ident;

                //  Construct name of log file and open the file.
                OUStringBuffer buf( 128 );
                buf.append( value );

                // if the filename ends with .nopid, the incoming filename is not modified
                if( value.getLength() < 6 /* ".nopid" */ ||
                    rtl_ustr_ascii_compare_WithLength(
                        value.getStr() + (value.getLength()-6) , 6 , ".nopid" ) )
                {
                    buf.appendAscii( "_" );
                    buf.append( (sal_Int32) aProcessId );
                    buf.appendAscii( ".log" );
                }

                OUString o = getFileUrl( buf.makeStringAndClear() );
                oslFileError e = osl_openFile(
                    o.pData, &g_aFile, osl_File_OpenFlag_Write|osl_File_OpenFlag_Create);

                if( osl_File_E_None == e )
                {
                    TimeValue aCurrentTime;
                    g_buffer = ( sal_Char * ) rtl_allocateMemory( g_BUFFERSIZE );
                    sal_Int64 nConverted = 0;
                    if (osl_getSystemTime (&aCurrentTime))
                    {
                        nConverted = (sal_Int64 ) sprintf (
                                g_buffer,
                                "opening log file %f seconds past January 1st 1970\n"
                                "corresponding to %" SAL_PRIuUINT32 " ms after timer start\n",
                                aCurrentTime.Seconds + 1e-9 * aCurrentTime.Nanosec,
                                osl_getGlobalTimer());

                        if( nConverted > 0 )
                        {
                            sal_Int64 nWritten;
                            osl_writeFile( g_aFile, g_buffer, nConverted , (sal_uInt64 *)&nWritten );
                        }
                    }

                    nConverted = sprintf (g_buffer, "Process id is %" SAL_PRIuUINT32 "\n", aProcessId);
                    if( nConverted )
                    {
                        sal_Int64 nWritten;
                        osl_writeFile( g_aFile, g_buffer, nConverted, (sal_uInt64 *)&nWritten );
                    }
                }
                else
                {
                    SAL_WARN(
                        "sal.rtl",
                        "Couldn't open logfile " << o << '(' << +e << ')');
                }
            }
            g_bHasBeenCalled = sal_True;
        }
    }
}

}

extern "C" void SAL_CALL rtl_logfile_trace  ( const char *pszFormat, ... )
{
    init();
    if( g_buffer )
    {
        va_list args;
        va_start(args, pszFormat);
        {
            sal_Int64 nConverted, nWritten;
            MutexGuard guard( getLogMutex() );
            nConverted = vsnprintf( g_buffer , g_BUFFERSIZE, pszFormat, args );
            nConverted = (nConverted > g_BUFFERSIZE ? g_BUFFERSIZE : nConverted );
            if( nConverted > 0 )
                osl_writeFile( g_aFile, g_buffer, nConverted, (sal_uInt64*)&nWritten );
        }
        va_end(args);
    }
}

extern "C" void SAL_CALL rtl_logfile_longTrace(char const * format, ...) {
    init();
    if (g_buffer != 0) {
        sal_uInt32 time = osl_getGlobalTimer();
        oslThreadIdentifier threadId = osl::Thread::getCurrentIdentifier();
        va_list args;
        va_start(args, format);
        {
            MutexGuard g(getLogMutex());
            int n1 = snprintf(
                g_buffer, g_BUFFERSIZE, "%06" SAL_PRIuUINT32 " %" SAL_PRIuUINT32 " ", time, threadId);
            if (n1 >= 0) {
                sal_uInt64 n2;
                osl_writeFile(
                    g_aFile, g_buffer,
                    static_cast< sal_uInt64 >(
                        std::min(n1, static_cast< int >(g_BUFFERSIZE))),
                    &n2);
                n1 = vsnprintf(g_buffer, g_BUFFERSIZE, format, args);
                if (n1 > 0) {
                    osl_writeFile(
                        g_aFile, g_buffer,
                        static_cast< sal_uInt64 >(
                            std::min(n1, static_cast< int >(g_BUFFERSIZE))),
                        &n2);
                }
            }
        }
        va_end(args);
    }
}

extern "C" sal_Bool SAL_CALL rtl_logfile_hasLogFile( void ) {
    init();
    return g_buffer != 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Use rtl::Static<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
 */

#include <cstdarg>
#include <cstdio>
#include <stdio.h>
#include <stdarg.h>

#include <rtl/logfile.h>
#include <osl/process.h>
#include <osl/time.h>
#include <osl/mutex.hxx>
#include <rtl/bootstrap.h>
#include <rtl/ustring.hxx>
#include <rtl/ustrbuf.hxx>
#include <rtl/alloc.h>
#include <rtl/instance.hxx>
#include <sal/log.hxx>
#include "osl/thread.h"
#include "osl/thread.hxx"

#include <algorithm>

#ifdef _MSC_VER
#define vsnprintf _vsnprintf
#endif

using namespace osl;
using namespace std;

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace {

OUString getFileUrl( const OUString &name )
{
    OUString aRet;
    if ( osl_getFileURLFromSystemPath( name.pData, &aRet.pData )
         != osl_File_E_None )
    {
        SAL_WARN(
            "sal.rtl", "osl_getFileURLFromSystemPath failed for \"" << name << '"');
    }

    OUString aWorkingDirectory;
    osl_getProcessWorkingDir( &(aWorkingDirectory.pData) );
    osl_getAbsoluteFileURL( aWorkingDirectory.pData, aRet.pData, &(aRet.pData) );

    return aRet;
}

static const sal_Int32 g_BUFFERSIZE = 4096;

struct Logger {
    oslFileHandle aFile;
    sal_Char *buffer;
    osl::Mutex mutex;

    Logger();

    ~Logger();
};

Logger::Logger(): aFile(0), buffer(0)
{
    OUString name( "RTL_LOGFILE" );
    OUString value;
    if( rtl_bootstrap_get( name.pData, &value.pData, 0 ) )
    {
        //  Obtain process id.
        oslProcessIdentifier aProcessId = 0;
        oslProcessInfo info;
        info.Size = sizeof (oslProcessInfo);
        if (osl_getProcessInfo (0, osl_Process_IDENTIFIER, &info) == osl_Process_E_None)
            aProcessId = info.Ident;

        //  Construct name of log file and open the file.
        OUStringBuffer buf( 128 );
        buf.append( value );

        // if the filename ends with .nopid, the incoming filename is not modified
        if( value.getLength() < 6 /* ".nopid" */ ||
            rtl_ustr_ascii_compare_WithLength(
                value.getStr() + (value.getLength()-6) , 6 , ".nopid" ) )
        {
            buf.appendAscii( "_" );
            buf.append( (sal_Int32) aProcessId );
            buf.appendAscii( ".log" );
        }

        OUString o = getFileUrl( buf.makeStringAndClear() );
        oslFileError e = osl_openFile(
            o.pData, &aFile, osl_File_OpenFlag_Write|osl_File_OpenFlag_Create);

        if( osl_File_E_None == e )
        {
            TimeValue aCurrentTime;
            buffer = ( sal_Char * ) rtl_allocateMemory( g_BUFFERSIZE );
            sal_Int64 nConverted = 0;
            if (osl_getSystemTime (&aCurrentTime))
            {
                nConverted = (sal_Int64 ) sprintf (
                    buffer,
                    "opening log file %f seconds past January 1st 1970\n"
                    "corresponding to %" SAL_PRIuUINT32 " ms after timer start\n",
                    aCurrentTime.Seconds + 1e-9 * aCurrentTime.Nanosec,
                    osl_getGlobalTimer());

                if( nConverted > 0 )
                {
                    sal_Int64 nWritten;
                    osl_writeFile( aFile, buffer, nConverted , (sal_uInt64 *)&nWritten );
                }
            }

            nConverted = sprintf (buffer, "Process id is %" SAL_PRIuUINT32 "\n", aProcessId);
            if( nConverted )
            {
                sal_Int64 nWritten;
                osl_writeFile( aFile, buffer, nConverted, (sal_uInt64 *)&nWritten );
            }
        }
        else
        {
            SAL_WARN(
                "sal.rtl",
                "Couldn't open logfile " << o << '(' << +e << ')');
        }
    }
}

Logger::~Logger()
{
    if( buffer )
    {
        sal_Int64 nWritten, nConverted =
            sprintf( buffer, "closing log file at %06" SAL_PRIuUINT32, osl_getGlobalTimer() );
        if( nConverted > 0 )
            osl_writeFile( aFile, buffer, nConverted, (sal_uInt64 *)&nWritten );
        osl_closeFile( aFile );
        rtl_freeMemory( buffer );
    }
}

struct theLogger: public rtl::Static<Logger, theLogger> {};

}

extern "C" void SAL_CALL rtl_logfile_trace  ( const char *pszFormat, ... )
{
    Logger & logger = theLogger::get();
    if( logger.buffer )
    {
        va_list args;
        va_start(args, pszFormat);
        {
            sal_Int64 nConverted, nWritten;
            MutexGuard guard( logger.mutex );
            nConverted = vsnprintf( logger.buffer , g_BUFFERSIZE, pszFormat, args );
            nConverted = (nConverted > g_BUFFERSIZE ? g_BUFFERSIZE : nConverted );
            if( nConverted > 0 )
                osl_writeFile( logger.aFile, logger.buffer, nConverted, (sal_uInt64*)&nWritten );
        }
        va_end(args);
    }
}

extern "C" void SAL_CALL rtl_logfile_longTrace(char const * format, ...) {
    Logger & logger = theLogger::get();
    if (logger.buffer != 0) {
        sal_uInt32 time = osl_getGlobalTimer();
        oslThreadIdentifier threadId = osl::Thread::getCurrentIdentifier();
        va_list args;
        va_start(args, format);
        {
            MutexGuard g(logger.mutex);
            int n1 = snprintf(
                logger.buffer, g_BUFFERSIZE, "%06" SAL_PRIuUINT32 " %" SAL_PRIuUINT32 " ", time, threadId);
            if (n1 >= 0) {
                sal_uInt64 n2;
                osl_writeFile(
                    logger.aFile, logger.buffer,
                    static_cast< sal_uInt64 >(
                        std::min(n1, static_cast< int >(g_BUFFERSIZE))),
                    &n2);
                n1 = vsnprintf(logger.buffer, g_BUFFERSIZE, format, args);
                if (n1 > 0) {
                    osl_writeFile(
                        logger.aFile, logger.buffer,
                        static_cast< sal_uInt64 >(
                            std::min(n1, static_cast< int >(g_BUFFERSIZE))),
                        &n2);
                }
            }
        }
        va_end(args);
    }
}

extern "C" sal_Bool SAL_CALL rtl_logfile_hasLogFile( void ) {
    return theLogger::get().buffer != 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>