<commit_before>#include "UserCode/diall/interface/genParticleProducer.h"
#include "UserCode/diall/interface/hiEventProducer.h"
#include "UserCode/diall/interface/lwMuonProducer.h"
#include "UserCode/diall/interface/pfParticleProducer.h"
#include "UserCode/diall/interface/LWJetProducer.h"
#include "UserCode/diall/interface/lwJetContainer.h"
#include "UserCode/diall/interface/lwJetFromForestProducer.h"
#include "UserCode/diall/interface/triggerProducer.h"
#include "UserCode/diall/interface/anaBaseTask.h"
#include "UserCode/diall/interface/anaJetEnergyScale.h"
#include "UserCode/diall/interface/anaJetMatching.h"
#include "UserCode/diall/interface/anaJetQA.h"
#include "UserCode/diall/interface/anaRhoProducer.h"
#include "UserCode/diall/interface/anaMET.h"
#include "UserCode/diall/interface/anaMuonIsolation.h"
#include "UserCode/diall/interface/anaMuonMatcher.h"
#include "UserCode/diall/interface/anaPuppiProducer.h"
#include "UserCode/diall/interface/anaPuppiParticles.h"
#include "UserCode/diall/interface/anaSubJet.h"
#include "UserCode/diall/interface/anaZToMuMu.h"

#include <TList.h>
#include <TChain.h>
#include <TFile.h>

#include <iostream>

using namespace std;

void analyzeSubJets(std::vector<std::string> urls, const char *outname = "eventObjects.root", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {

  /*
    ptminType: minimum raw pt for particles used by puppi
    0 : 0 GeV
    1 : 1 GeV
    2 : 2 GeV

    jetSignalType: jets used to select jetty region in events
    0 : detector-level jets (akPu4PF)
    1 : particle-level jets (gen jets)
   */

  double ptminjet = 30.;
  TString jetName = "aktCs4PFSoftDrop";
  TString jetTreeName = "akCs4PFSoftDropJetAnalyzer";
  //jetName = "akCs4PFFilter";
  //jetTreeName = "akCs4PFFilterJetAnalyzer";

  std::cout << "analyzing subjets for: " << jetName << " tree: " << jetTreeName << std::endl;

  std::cout << "nfiles: " << urls.size() << std::endl;
  for (auto i = urls.begin(); i != urls.end(); ++i)
    std::cout << *i << std::endl;

  size_t firstFile = 0;
  size_t lastFile = urls.size();

  if(firstF>-1) {
    firstFile = (size_t)firstF;
    lastFile = (size_t)lastF;
  }
  std::cout << "firstFile: " << firstFile << "  lastFile: " << lastFile << std::endl;

  Int_t lastEvent = nentries;
  if(firstEvent>0) {
    lastEvent = firstEvent + nentries;
  }
  std::cout << "firstEvent: " << firstEvent << std::endl;

  //add files to chain
  TChain *chain = NULL;
  chain = new TChain("hiEvtAnalyzer/HiTree");
  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());
  Printf("hiTree done");

  TChain *hltTree = new TChain("hltanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());
  Printf("hltTree done");

  TChain *jetTree = new TChain(Form("%s/t",jetTreeName.Data()));
  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());
  chain->AddFriend(jetTree);
  Printf("jetTree done");

  // TChain *csJetTree = new TChain(Form("%s/t","akCs4PFJetAnalyzer"));
  // for(size_t i=firstFile; i<lastFile; i++) csJetTree->Add(urls[i].c_str());
  // chain->AddFriend(csJetTree);
  // Printf("csJetTree done");

  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  triggerProducer *p_trg = new triggerProducer("trigProd");
  p_trg->SetInput(hltTree);
  p_trg->SetTriggerMapName("triggerMap");
  p_trg->AddTrigger("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  p_trg->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer("lwJetForestProd");
  p_PUJet->SetInput(chain);
  p_PUJet->SetJetContName(jetName);
  p_PUJet->SetGenJetContName("");
  p_PUJet->SetEventObjects(fEventObjects);
  p_PUJet->SetRadius(0.4);
  p_PUJet->SetMinJetPt(ptminjet);
  // lwJetFromForestProducer *p_CSJet = new lwJetFromForestProducer("lwJetForestProd");
  // p_CSJet->SetInput(csJetTree);
  // p_CSJet->SetJetContName("aktCs4PF");
  // p_CSJet->SetGenJetContName("");
  // p_CSJet->SetEventObjects(fEventObjects);
  // p_CSJet->SetRadius(0.4);

  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaSubJet *anasubjets = new anaSubJet("anaSubJets","anaSubJets");
  anasubjets->ConnectEventObject(fEventObjects);
  anasubjets->SetHiEvtName("hiEventContainer");
  anasubjets->SetTriggerMapName("triggerMap");
  anasubjets->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anasubjets->SetJetsName(jetName);
  anasubjets->SetNCentBins(4);
  anasubjets->SetJetEtaRange(-2.,2.);
  anasubjets->SetDoDijets(true);
  anasubjets->AddLeadingJetPtBin(120.,150.);
  anasubjets->AddLeadingJetPtBin(150.,180.);
  anasubjets->AddLeadingJetPtBin(180.,220.);
  anasubjets->AddLeadingJetPtBin(220.,260.);
  anasubjets->AddLeadingJetPtBin(260.,300.);
  anasubjets->AddLeadingJetPtBin(300.,500.);
  anasubjets->SetPtMinSubleading(30.);
  handler->Add(anasubjets);

  anaSubJet *anasubjetsMassCut = new anaSubJet("anasubjetsMassCut","anasubjetsMassCut");
  anasubjetsMassCut->ConnectEventObject(fEventObjects);
  anasubjetsMassCut->SetHiEvtName("hiEventContainer");
  anasubjetsMassCut->SetTriggerMapName("triggerMap");
  anasubjetsMassCut->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anasubjetsMassCut->SetJetsName(jetName);
  anasubjetsMassCut->SetNCentBins(4);
  anasubjetsMassCut->SetJetEtaRange(-2.,2.);
  anasubjetsMassCut->SetDoDijets(true);
  anasubjetsMassCut->AddLeadingJetPtBin(120.,150.);
  anasubjetsMassCut->AddLeadingJetPtBin(150.,180.);
  anasubjetsMassCut->AddLeadingJetPtBin(180.,220.);
  anasubjetsMassCut->AddLeadingJetPtBin(220.,260.);
  anasubjetsMassCut->AddLeadingJetPtBin(260.,300.);
  anasubjetsMassCut->AddLeadingJetPtBin(300.,500.);
  anasubjetsMassCut->SetPtMinSubleading(30.);
  anasubjetsMassCut->SetMinMassLeading(10.);
  handler->Add(anasubjetsMassCut);

  // anaSubJet *anasubjetsCSJets = new anaSubJet("anasubjetsCSJets","anasubjetsCSJets");
  // anasubjetsCSJets->ConnectEventObject(fEventObjects);
  // anasubjetsCSJets->SetHiEvtName("hiEventContainer");
  // anasubjetsCSJets->SetJetsName("aktCs4PF");
  // anasubjetsCSJets->SetNCentBins(4);
  // anasubjetsCSJets->SetJetEtaRange(-2.,2.);
  // anasubjetsCSJets->SetDoDijets(false);
  // handler->Add(anasubjetsCSJets);

  //---------------------------------------------------------------
  //Event loop
  //---------------------------------------------------------------
  Long64_t entries_tot =  chain->GetEntries(); //93064
  if(nentries<0) lastEvent = chain->GetEntries();
  Printf("nentries: %lld  tot: %lld",nentries,entries_tot);
  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {
    if(jentry%10000==0) cout << "entry: "<< jentry << endl;
    //Run producers
    //Printf("produce hiEvent");
    p_evt->Run(jentry);   //hi event properties
    //Printf("produce PU jets");
    p_PUJet->Run(jentry); //forest jets
    p_trg->Run(jentry);

    //Execute all analysis tasks
    handler->ExecuteTask();
  }

  fEventObjects->Print();

  TFile *out = new TFile(outname,"RECREATE");
  TList *tasks = handler->GetListOfTasks();
  TIter next(tasks);
  anaBaseTask *obj;
  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))
    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);

  out->Write();
  out->Close();

}
<commit_msg>lastFile fix<commit_after>#include "UserCode/diall/interface/genParticleProducer.h"
#include "UserCode/diall/interface/hiEventProducer.h"
#include "UserCode/diall/interface/lwMuonProducer.h"
#include "UserCode/diall/interface/pfParticleProducer.h"
#include "UserCode/diall/interface/LWJetProducer.h"
#include "UserCode/diall/interface/lwJetContainer.h"
#include "UserCode/diall/interface/lwJetFromForestProducer.h"
#include "UserCode/diall/interface/triggerProducer.h"
#include "UserCode/diall/interface/anaBaseTask.h"
#include "UserCode/diall/interface/anaJetEnergyScale.h"
#include "UserCode/diall/interface/anaJetMatching.h"
#include "UserCode/diall/interface/anaJetQA.h"
#include "UserCode/diall/interface/anaRhoProducer.h"
#include "UserCode/diall/interface/anaMET.h"
#include "UserCode/diall/interface/anaMuonIsolation.h"
#include "UserCode/diall/interface/anaMuonMatcher.h"
#include "UserCode/diall/interface/anaPuppiProducer.h"
#include "UserCode/diall/interface/anaPuppiParticles.h"
#include "UserCode/diall/interface/anaSubJet.h"
#include "UserCode/diall/interface/anaZToMuMu.h"

#include <TList.h>
#include <TChain.h>
#include <TFile.h>

#include <iostream>

using namespace std;

void analyzeSubJets(std::vector<std::string> urls, const char *outname = "eventObjects.root", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {

  /*
    ptminType: minimum raw pt for particles used by puppi
    0 : 0 GeV
    1 : 1 GeV
    2 : 2 GeV

    jetSignalType: jets used to select jetty region in events
    0 : detector-level jets (akPu4PF)
    1 : particle-level jets (gen jets)
   */

  double ptminjet = 30.;
  TString jetName = "aktCs4PFSoftDrop";
  TString jetTreeName = "akCs4PFSoftDropJetAnalyzer";
  //jetName = "akCs4PFFilter";
  //jetTreeName = "akCs4PFFilterJetAnalyzer";

  std::cout << "analyzing subjets for: " << jetName << " tree: " << jetTreeName << std::endl;

  std::cout << "nfiles: " << urls.size() << std::endl;
  for (auto i = urls.begin(); i != urls.end(); ++i)
    std::cout << *i << std::endl;

  size_t firstFile = 0;
  size_t lastFile = urls.size();

  if(firstF>-1) {
    firstFile = (size_t)firstF;
    lastFile = std::min((size_t)lastF,lastFile);
  }
  std::cout << "firstFile: " << firstFile << "  lastFile: " << lastFile << std::endl;

  Int_t lastEvent = nentries;
  if(firstEvent>0) {
    lastEvent = firstEvent + nentries;
  }
  std::cout << "firstEvent: " << firstEvent << std::endl;

  //add files to chain
  TChain *chain = NULL;
  chain = new TChain("hiEvtAnalyzer/HiTree");
  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());
  Printf("hiTree done");

  TChain *hltTree = new TChain("hltanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());
  Printf("hltTree done");

  TChain *jetTree = new TChain(Form("%s/t",jetTreeName.Data()));
  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());
  chain->AddFriend(jetTree);
  Printf("jetTree done");

  // TChain *csJetTree = new TChain(Form("%s/t","akCs4PFJetAnalyzer"));
  // for(size_t i=firstFile; i<lastFile; i++) csJetTree->Add(urls[i].c_str());
  // chain->AddFriend(csJetTree);
  // Printf("csJetTree done");

  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  triggerProducer *p_trg = new triggerProducer("trigProd");
  p_trg->SetInput(hltTree);
  p_trg->SetTriggerMapName("triggerMap");
  p_trg->AddTrigger("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  p_trg->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer("lwJetForestProd");
  p_PUJet->SetInput(chain);
  p_PUJet->SetJetContName(jetName);
  p_PUJet->SetGenJetContName("");
  p_PUJet->SetEventObjects(fEventObjects);
  p_PUJet->SetRadius(0.4);
  p_PUJet->SetMinJetPt(ptminjet);
  // lwJetFromForestProducer *p_CSJet = new lwJetFromForestProducer("lwJetForestProd");
  // p_CSJet->SetInput(csJetTree);
  // p_CSJet->SetJetContName("aktCs4PF");
  // p_CSJet->SetGenJetContName("");
  // p_CSJet->SetEventObjects(fEventObjects);
  // p_CSJet->SetRadius(0.4);

  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaSubJet *anasubjets = new anaSubJet("anaSubJets","anaSubJets");
  anasubjets->ConnectEventObject(fEventObjects);
  anasubjets->SetHiEvtName("hiEventContainer");
  anasubjets->SetTriggerMapName("triggerMap");
  anasubjets->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anasubjets->SetJetsName(jetName);
  anasubjets->SetNCentBins(4);
  anasubjets->SetJetEtaRange(-2.,2.);
  anasubjets->SetDoDijets(true);
  anasubjets->AddLeadingJetPtBin(120.,150.);
  anasubjets->AddLeadingJetPtBin(150.,180.);
  anasubjets->AddLeadingJetPtBin(180.,220.);
  anasubjets->AddLeadingJetPtBin(220.,260.);
  anasubjets->AddLeadingJetPtBin(260.,300.);
  anasubjets->AddLeadingJetPtBin(300.,500.);
  anasubjets->SetPtMinSubleading(30.);
  handler->Add(anasubjets);

  anaSubJet *anasubjetsMassCut = new anaSubJet("anasubjetsMassCut","anasubjetsMassCut");
  anasubjetsMassCut->ConnectEventObject(fEventObjects);
  anasubjetsMassCut->SetHiEvtName("hiEventContainer");
  anasubjetsMassCut->SetTriggerMapName("triggerMap");
  anasubjetsMassCut->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anasubjetsMassCut->SetJetsName(jetName);
  anasubjetsMassCut->SetNCentBins(4);
  anasubjetsMassCut->SetJetEtaRange(-2.,2.);
  anasubjetsMassCut->SetDoDijets(true);
  anasubjetsMassCut->AddLeadingJetPtBin(120.,150.);
  anasubjetsMassCut->AddLeadingJetPtBin(150.,180.);
  anasubjetsMassCut->AddLeadingJetPtBin(180.,220.);
  anasubjetsMassCut->AddLeadingJetPtBin(220.,260.);
  anasubjetsMassCut->AddLeadingJetPtBin(260.,300.);
  anasubjetsMassCut->AddLeadingJetPtBin(300.,500.);
  anasubjetsMassCut->SetPtMinSubleading(30.);
  anasubjetsMassCut->SetMinMassLeading(10.);
  handler->Add(anasubjetsMassCut);

  // anaSubJet *anasubjetsCSJets = new anaSubJet("anasubjetsCSJets","anasubjetsCSJets");
  // anasubjetsCSJets->ConnectEventObject(fEventObjects);
  // anasubjetsCSJets->SetHiEvtName("hiEventContainer");
  // anasubjetsCSJets->SetJetsName("aktCs4PF");
  // anasubjetsCSJets->SetNCentBins(4);
  // anasubjetsCSJets->SetJetEtaRange(-2.,2.);
  // anasubjetsCSJets->SetDoDijets(false);
  // handler->Add(anasubjetsCSJets);

  //---------------------------------------------------------------
  //Event loop
  //---------------------------------------------------------------
  Long64_t entries_tot =  chain->GetEntries(); //93064
  if(nentries<0) lastEvent = chain->GetEntries();
  Printf("nentries: %lld  tot: %lld",nentries,entries_tot);
  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {
    if(jentry%10000==0) cout << "entry: "<< jentry << endl;
    //Run producers
    //Printf("produce hiEvent");
    p_evt->Run(jentry);   //hi event properties
    //Printf("produce PU jets");
    p_PUJet->Run(jentry); //forest jets
    p_trg->Run(jentry);

    //Execute all analysis tasks
    handler->ExecuteTask();
  }

  fEventObjects->Print();

  TFile *out = new TFile(outname,"RECREATE");
  TList *tasks = handler->GetListOfTasks();
  TIter next(tasks);
  anaBaseTask *obj;
  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))
    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);

  out->Write();
  out->Close();

}
<|endoftext|>


<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

#ifndef GCN_LISTMODEL_HPP
#define GCN_LISTMODEL_HPP

#include <string>

#include "guichan/platform.hpp"

namespace gcn
{
    /**
     * Represents a list. It is used in certain Widgets, like the ListBox, to
     * handle a list with string elements. If you want to use Widgets like
     * ListBox, you should inherit from this calss and implement it's
     * functions.
     */
    class GCN_CORE_DECLSPEC ListModel
    {

    public:
        /**
         * Destructor.
         */
        virtual ~ListModel() { }

        /**
         * Gets the number of elements in the ListModel.
         *
         * @return the number of elements in the ListModel
         */
        virtual int getNumberOfElements() = 0;

        /**
         * Gets an element at a certain index in the list.
         *
         * @param i an index in the list.
         * @return an element as a string.
         */
        virtual std::string getElementAt(int i) = 0;
    };
}

#endif // end GCN_LISTMODEL_HPP
<commit_msg>A spelling misstake has been fixed.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

#ifndef GCN_LISTMODEL_HPP
#define GCN_LISTMODEL_HPP

#include <string>

#include "guichan/platform.hpp"

namespace gcn
{
    /**
     * Represents a list. It is used in certain Widgets, like the ListBox, to
     * handle a list with string elements. If you want to use Widgets like
     * ListBox, you should inherit from this class and implement it's
     * functions.
     */
    class GCN_CORE_DECLSPEC ListModel
    {

    public:
        /**
         * Destructor.
         */
        virtual ~ListModel() { }

        /**
         * Gets the number of elements in the ListModel.
         *
         * @return the number of elements in the ListModel
         */
        virtual int getNumberOfElements() = 0;

        /**
         * Gets an element at a certain index in the list.
         *
         * @param i an index in the list.
         * @return an element as a string.
         */
        virtual std::string getElementAt(int i) = 0;
    };
}

#endif // end GCN_LISTMODEL_HPP
<|endoftext|>


<commit_before>#pragma once

// Based on http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0640r0.pdf

#include <sstream>
#include <memory>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <cstddef>

#if defined(__GNUG__) && !defined(KL_NO_DEMANGLE)
#  include <cxxabi.h>
#  include <cstdlib>
#endif

namespace kl {

namespace detail {

class exception_info_node_base
{
public:
    virtual ~exception_info_node_base() noexcept = default;

    virtual const void* find(const std::type_info& tag) const noexcept = 0;
    virtual void* find(const std::type_info& tag) noexcept = 0;
    virtual void diagnostic_info(std::ostream& os) = 0;

    std::shared_ptr<exception_info_node_base> next_{};
};

#if defined(__GNUG__) && !defined(KL_NO_DEMANGLE)

inline auto demangled(const char* name) noexcept
{
    int status = -4;
    std::unique_ptr<char, void (*)(void*)> demangled{
        abi::__cxa_demangle(name, nullptr, nullptr, &status), std::free};
    return demangled;
}

#  define KL_TYPE_ID_PRETTY_NAME(x) ::kl::detail::demangled((x).name()).get()
#else
#  define KL_TYPE_ID_PRETTY_NAME(x) (x).name()
#endif

template <typename T>
auto diagnostic_info_impl(std::ostream& os, const std::type_info& tag,
                          const T& value, int)
    -> decltype((os << value), void())
{
    os << KL_TYPE_ID_PRETTY_NAME(tag) << " = " << value << '\n';
}

template <typename T>
void diagnostic_info_impl(std::ostream& os, const std::type_info& tag,
                          const T& value, ...)
{
    os << KL_TYPE_ID_PRETTY_NAME(tag) << " = [";

    constexpr const char* hex = "0123456789ABCDEF";
    const auto bytes =
        reinterpret_cast<const unsigned char*>(std::addressof(value));
    const auto num_bytes = sizeof(value);

    for (std::size_t i = 0; i < num_bytes; ++i)
    {
        if (i > 0)
            os << ' ';
        os << hex[(bytes[i] & 0xF0) >> 4] << hex[bytes[i] & 0xF];
    }

    os << "]\n";
}

template <typename Tag>
class exception_info_node : public exception_info_node_base
{
public:
    explicit exception_info_node(const typename Tag::type& value)
        : value_{value}
    {
    }
    explicit exception_info_node(typename Tag::type&& value)
        : value_{std::move(value)}
    {
    }

    const void* find(const std::type_info& tag) const noexcept override
    {
        return tag == typeid(Tag) ? &value_ : nullptr;
    }

    void* find(const std::type_info& tag) noexcept override
    {
        return tag == typeid(Tag) ? &value_ : nullptr;
    }

    void diagnostic_info(std::ostream& os) override
    {
        diagnostic_info_impl(os, typeid(Tag), value_, 0);
    }

private:
    typename Tag::type value_;
};
} // namespace detail

class exception_info
{
public:
    exception_info() noexcept = default;
    exception_info(const char* file, int line, const char* function) noexcept
        : file_{file}, line_{line}, function_{function}
    {
    }

    virtual ~exception_info() noexcept = default;

    exception_info(const exception_info& other) = default;
    exception_info(exception_info&& other) noexcept = default;

    exception_info& operator=(const exception_info& other) = default;
    exception_info& operator=(exception_info&& other) noexcept = default;

    [[nodiscard]] const char* file() const noexcept { return file_; }
    [[nodiscard]] int line() const noexcept { return line_; }
    [[nodiscard]] const char* function() const noexcept { return function_; }

    template <typename Tag>
    exception_info& set(const typename Tag::type& x)
    {
        auto node = std::make_shared<detail::exception_info_node<Tag>>(x);
        node->next_ = head_;
        head_ = node;
        return *this;
    }

    template <typename Tag>
    exception_info& set(typename Tag::type&& x)
    {
        auto node =
            std::make_shared<detail::exception_info_node<Tag>>(std::move(x));
        node->next_ = head_;
        head_ = node;
        return *this;
    }

    template <typename Tag>
    exception_info& unset() noexcept
    {
        if (!head_)
            return *this;

        std::shared_ptr<detail::exception_info_node_base>* node = &head_;
        std::shared_ptr<detail::exception_info_node_base>* prev = nullptr;
        const auto& tag = typeid(Tag);

        while (*node)
        {
            if ((*node)->find(tag))
            {
                if (prev)
                    (*prev)->next_ = (*node)->next_;
                else
                    head_ = (*node)->next_;
                break;
            }

            prev = node;
            node = &(*node)->next_;
        }

        return *this;
    }

    template <typename Tag>
    [[nodiscard]] const typename Tag::type* get() const noexcept
    {
        return const_cast<exception_info*>(this)->template get<Tag>();
    }

    template <typename Tag>
    [[nodiscard]] typename Tag::type* get() noexcept
    {
        const auto& tag = typeid(Tag);
        for (auto* node = &head_; *node;)
        {
            if (void* ptr = (*node)->find(tag); ptr)
                return static_cast<typename Tag::type*>(ptr);
            node = &(*node)->next_;
        }

        return nullptr;
    }

    [[nodiscard]] std::string diagnostic_info() const
    {
        std::ostringstream ss;
        if (file_)
            ss << file_ << '(' << line_ << ')';
        else
            ss << "<unknown-file>";

        ss << ": throw_with_info in function "
           << (function_ ? function_ : "<unknown-function>") << '\n';
        for (auto* node = &head_; *node;)
        {
            (*node)->diagnostic_info(ss);
            node = &(*node)->next_;
        }
        return ss.str();
    }

private:
    const char* file_{};
    int line_{};
    const char* function_{};

    // Not unique because of copyability requirement
    std::shared_ptr<detail::exception_info_node_base> head_{};
};

namespace detail {

struct exception_with_info_base : public exception_info
{
    exception_with_info_base(const std::type_info& exception_type,
                             exception_info xi)
        : exception_info{std::move(xi)}, exception_type{exception_type}
    {
    }

    const std::type_info& exception_type;
};

template <typename E>
class exception_with_info : public E, public exception_with_info_base
{
public:
    exception_with_info(const E& e, exception_info xi)
        : E{e}, exception_with_info_base{typeid(E), std::move(xi)}
    {
    }

    exception_with_info(E&& e, exception_info xi)
        : E{std::move(e)}, exception_with_info_base{typeid(E), std::move(xi)}
    {
    }
};
} // namespace detail

template <typename E>
[[noreturn]] void throw_with_info(E&& e, exception_info&& xi = exception_info())
{
    using e_type = std::remove_cv_t<std::remove_reference_t<E>>;

    static_assert(std::is_class_v<e_type> && !std::is_final_v<e_type>);
    static_assert(!std::is_base_of_v<exception_info, e_type>);

    throw detail::exception_with_info<e_type>(std::forward<E>(e),
                                              std::move(xi));
}

template <typename E>
[[noreturn]] void throw_with_info(E&& e, const exception_info& xi)
{
    throw_with_info(std::forward<E>(e), exception_info{xi});
}

template <typename E>
[[nodiscard]] const exception_info* get_exception_info(const E& e)
{
    static_assert(std::is_polymorphic_v<E>);
    return dynamic_cast<const exception_info*>(std::addressof(e));
}

template <typename E>
[[nodiscard]] exception_info* get_exception_info(E& e)
{
    static_assert(std::is_polymorphic_v<E>);
    return dynamic_cast<exception_info*>(std::addressof(e));
}

template <typename E>
[[nodiscard]] std::string exception_diagnostic_info(const E& e)
{
    std::ostringstream ss;

    if constexpr (!std::is_polymorphic_v<E>)
    {
        ss << "dynamic exception type: " << KL_TYPE_ID_PRETTY_NAME(typeid(E))
           << '\n';
    }
    else
    {
        const E* ep = std::addressof(e);
        if (const auto* p =
                dynamic_cast<const detail::exception_with_info_base*>(ep))
        {
            ss << "dynamic exception type: "
               << KL_TYPE_ID_PRETTY_NAME(p->exception_type) << '\n';
        }
        else
        {
            ss << "dynamic exception type: "
               << KL_TYPE_ID_PRETTY_NAME(typeid(e)) << '\n';
        }

        if (const auto* p = dynamic_cast<const std::exception*>(ep))
            ss << "what: " << p->what() << '\n';

        if (const auto* p = dynamic_cast<const exception_info*>(ep))
            ss << p->diagnostic_info();
    }

    return ss.str();
}

[[nodiscard]] inline std::string
    exception_diagnostic_info(const std::exception_ptr& p)
try
{
    if (p)
        std::rethrow_exception(p);
    return "no exception";
}
catch (const exception_info& xi)
{
    return exception_diagnostic_info(xi);
}
catch (const std::exception& ex)
{
    return exception_diagnostic_info(ex);
}
catch (...)
{
    return "dynamic exception type: <unknown-exception>\n";
}

#if defined(_MSC_VER)
#  define KL_FUNCTION_NAME __FUNCSIG__
#elif defined(__GNUG__)
#  define KL_FUNCTION_NAME __PRETTY_FUNCTION__
#else
#  define KL_FUNCTION_NAME __func__
#endif

#define KL_MAKE_EXCEPTION_INFO()                                               \
    ::kl::exception_info{__FILE__, __LINE__, KL_FUNCTION_NAME}
} // namespace kl
<commit_msg>Use Boost's demangle<commit_after>#pragma once

// Based on http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0640r0.pdf

#include <boost/core/demangle.hpp>

#include <sstream>
#include <memory>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <cstddef>

namespace kl {

namespace detail {

class exception_info_node_base
{
public:
    virtual ~exception_info_node_base() noexcept = default;

    virtual const void* find(const std::type_info& tag) const noexcept = 0;
    virtual void* find(const std::type_info& tag) noexcept = 0;
    virtual void diagnostic_info(std::ostream& os) = 0;

    std::shared_ptr<exception_info_node_base> next_{};
};

struct demangled_type_name
{
    friend std::ostream& operator<<(std::ostream& os, demangled_type_name dtn)
    {
        boost::core::scoped_demangled_name name{dtn.ti.name()};
        const char* p = name.get();
        if (!p)
            p = dtn.ti.name();
        return os << p;
    }

    const std::type_info& ti;
};

template <typename T>
auto diagnostic_info_impl(std::ostream& os, const std::type_info& tag,
                          const T& value, int)
    -> decltype((os << value), void())
{
    os << demangled_type_name{tag} << " = " << value << '\n';
}

template <typename T>
void diagnostic_info_impl(std::ostream& os, const std::type_info& tag,
                          const T& value, ...)
{
    os << demangled_type_name{tag} << " = [";

    constexpr const char* hex = "0123456789ABCDEF";
    const auto bytes =
        reinterpret_cast<const unsigned char*>(std::addressof(value));
    const auto num_bytes = sizeof(value);

    for (std::size_t i = 0; i < num_bytes; ++i)
    {
        if (i > 0)
            os << ' ';
        os << hex[(bytes[i] & 0xF0) >> 4] << hex[bytes[i] & 0xF];
    }

    os << "]\n";
}

template <typename Tag>
class exception_info_node : public exception_info_node_base
{
public:
    explicit exception_info_node(const typename Tag::type& value)
        : value_{value}
    {
    }
    explicit exception_info_node(typename Tag::type&& value)
        : value_{std::move(value)}
    {
    }

    const void* find(const std::type_info& tag) const noexcept override
    {
        return tag == typeid(Tag) ? &value_ : nullptr;
    }

    void* find(const std::type_info& tag) noexcept override
    {
        return tag == typeid(Tag) ? &value_ : nullptr;
    }

    void diagnostic_info(std::ostream& os) override
    {
        diagnostic_info_impl(os, typeid(Tag), value_, 0);
    }

private:
    typename Tag::type value_;
};
} // namespace detail

class exception_info
{
public:
    exception_info() noexcept = default;
    exception_info(const char* file, int line, const char* function) noexcept
        : file_{file}, line_{line}, function_{function}
    {
    }

    virtual ~exception_info() noexcept = default;

    exception_info(const exception_info& other) = default;
    exception_info(exception_info&& other) noexcept = default;

    exception_info& operator=(const exception_info& other) = default;
    exception_info& operator=(exception_info&& other) noexcept = default;

    [[nodiscard]] const char* file() const noexcept { return file_; }
    [[nodiscard]] int line() const noexcept { return line_; }
    [[nodiscard]] const char* function() const noexcept { return function_; }

    template <typename Tag>
    exception_info& set(const typename Tag::type& x)
    {
        auto node = std::make_shared<detail::exception_info_node<Tag>>(x);
        node->next_ = head_;
        head_ = node;
        return *this;
    }

    template <typename Tag>
    exception_info& set(typename Tag::type&& x)
    {
        auto node =
            std::make_shared<detail::exception_info_node<Tag>>(std::move(x));
        node->next_ = head_;
        head_ = node;
        return *this;
    }

    template <typename Tag>
    exception_info& unset() noexcept
    {
        if (!head_)
            return *this;

        std::shared_ptr<detail::exception_info_node_base>* node = &head_;
        std::shared_ptr<detail::exception_info_node_base>* prev = nullptr;
        const auto& tag = typeid(Tag);

        while (*node)
        {
            if ((*node)->find(tag))
            {
                if (prev)
                    (*prev)->next_ = (*node)->next_;
                else
                    head_ = (*node)->next_;
                break;
            }

            prev = node;
            node = &(*node)->next_;
        }

        return *this;
    }

    template <typename Tag>
    [[nodiscard]] const typename Tag::type* get() const noexcept
    {
        return const_cast<exception_info*>(this)->template get<Tag>();
    }

    template <typename Tag>
    [[nodiscard]] typename Tag::type* get() noexcept
    {
        const auto& tag = typeid(Tag);
        for (auto* node = &head_; *node;)
        {
            if (void* ptr = (*node)->find(tag); ptr)
                return static_cast<typename Tag::type*>(ptr);
            node = &(*node)->next_;
        }

        return nullptr;
    }

    [[nodiscard]] std::string diagnostic_info() const
    {
        std::ostringstream ss;
        if (file_)
            ss << file_ << '(' << line_ << ')';
        else
            ss << "<unknown-file>";

        ss << ": throw_with_info in function "
           << (function_ ? function_ : "<unknown-function>") << '\n';
        for (auto* node = &head_; *node;)
        {
            (*node)->diagnostic_info(ss);
            node = &(*node)->next_;
        }
        return ss.str();
    }

private:
    const char* file_{};
    int line_{};
    const char* function_{};

    // Not unique because of copyability requirement
    std::shared_ptr<detail::exception_info_node_base> head_{};
};

namespace detail {

struct exception_with_info_base : public exception_info
{
    exception_with_info_base(const std::type_info& exception_type,
                             exception_info xi)
        : exception_info{std::move(xi)}, exception_type{exception_type}
    {
    }

    const std::type_info& exception_type;
};

template <typename E>
class exception_with_info : public E, public exception_with_info_base
{
public:
    exception_with_info(const E& e, exception_info xi)
        : E{e}, exception_with_info_base{typeid(E), std::move(xi)}
    {
    }

    exception_with_info(E&& e, exception_info xi)
        : E{std::move(e)}, exception_with_info_base{typeid(E), std::move(xi)}
    {
    }
};
} // namespace detail

template <typename E>
[[noreturn]] void throw_with_info(E&& e, exception_info&& xi = exception_info())
{
    using e_type = std::remove_cv_t<std::remove_reference_t<E>>;

    static_assert(std::is_class_v<e_type> && !std::is_final_v<e_type>);
    static_assert(!std::is_base_of_v<exception_info, e_type>);

    throw detail::exception_with_info<e_type>(std::forward<E>(e),
                                              std::move(xi));
}

template <typename E>
[[noreturn]] void throw_with_info(E&& e, const exception_info& xi)
{
    throw_with_info(std::forward<E>(e), exception_info{xi});
}

template <typename E>
[[nodiscard]] const exception_info* get_exception_info(const E& e)
{
    static_assert(std::is_polymorphic_v<E>);
    return dynamic_cast<const exception_info*>(std::addressof(e));
}

template <typename E>
[[nodiscard]] exception_info* get_exception_info(E& e)
{
    static_assert(std::is_polymorphic_v<E>);
    return dynamic_cast<exception_info*>(std::addressof(e));
}

template <typename E>
[[nodiscard]] std::string exception_diagnostic_info(const E& e)
{
    std::ostringstream ss;
    using detail::demangled_type_name;

    if constexpr (!std::is_polymorphic_v<E>)
    {
        ss << "dynamic exception type: " << demangled_type_name{typeid(E)}
           << '\n';
    }
    else
    {
        const E* ep = std::addressof(e);
        if (const auto* p =
                dynamic_cast<const detail::exception_with_info_base*>(ep))
        {
            ss << "dynamic exception type: "
               << demangled_type_name{p->exception_type} << '\n';
        }
        else
        {
            ss << "dynamic exception type: " << demangled_type_name{typeid(e)}
               << '\n';
        }

        if (const auto* p = dynamic_cast<const std::exception*>(ep))
            ss << "what: " << p->what() << '\n';

        if (const auto* p = dynamic_cast<const exception_info*>(ep))
            ss << p->diagnostic_info();
    }

    return ss.str();
}

[[nodiscard]] inline std::string
    exception_diagnostic_info(const std::exception_ptr& p)
try
{
    if (p)
        std::rethrow_exception(p);
    return "no exception";
}
catch (const exception_info& xi)
{
    return exception_diagnostic_info(xi);
}
catch (const std::exception& ex)
{
    return exception_diagnostic_info(ex);
}
catch (...)
{
    return "dynamic exception type: <unknown-exception>\n";
}

#if defined(_MSC_VER)
#  define KL_FUNCTION_NAME __FUNCSIG__
#elif defined(__GNUG__)
#  define KL_FUNCTION_NAME __PRETTY_FUNCTION__
#else
#  define KL_FUNCTION_NAME __func__
#endif

#define KL_MAKE_EXCEPTION_INFO()                                               \
    ::kl::exception_info{__FILE__, __LINE__, KL_FUNCTION_NAME}
} // namespace kl
<|endoftext|>


<commit_before>/*

Copyright (c) 2008, Arvid Norberg
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 the author 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

*/

#ifndef TORRENT_ALLOCA

#include "libtorrent/config.hpp"

#ifdef TORRENT_WINDOWS

#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)));

#else

#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)));

#endif

#endif

<commit_msg>remove unnecessary semicolon<commit_after>/*

Copyright (c) 2008, Arvid Norberg
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 the author 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

*/

#ifndef TORRENT_ALLOCA

#include "libtorrent/config.hpp"

#ifdef TORRENT_WINDOWS

#include <malloc.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n)))

#else

#include <alloca.h>
#define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n)))

#endif

#endif

<|endoftext|>


<commit_before>/*

Copyright (c) 2005, Arvid Norberg
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 the author 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

// ======= GCC =========

#if defined __GNUC__

# if __GNUC__ >= 3
#  define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif

// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __attribute__ ((visibility("default")))
#  endif
# endif

// ======= SUNPRO =========

#elif defined __SUNPRO_CC

# if __SUNPRO_CC >= 0x550
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __global
#  endif
# endif

// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1

// ======= MSVC =========

#elif defined BOOST_MSVC

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif

#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)

#endif

// ======= PLATFORMS =========

// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#define TORRENT_USE_ICONV 0

// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#define TORRENT_USE_ICONV 0
#endif
#define TORRENT_HAS_FALLOCATE 0

// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX

// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0

// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0

// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1

// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_ICONV 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif

// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows

// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX

// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH

// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH

// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX

// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255

#endif

#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW

// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)

#include <stdarg.h>

inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	int ret = _vsnprintf(buf, len, fmt, lp);
	va_end(lp);
	if (ret < 0) { buf[len-1] = 0; ret = len-1; }
	return ret;
}

#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
	&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif

// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif

#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif

#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE

#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif

#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif

#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif

#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif

#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif

#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif

#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif

#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif

#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif

// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
	&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
	&& !defined TORRENT_USE_CLOCK_GETTIME \
	&& !defined TORRENT_USE_BOOST_DATE_TIME \
	&& !defined TORRENT_USE_ECLOCK \
	&& !defined TORRENT_USE_SYSTEM_TIME

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<commit_msg>DEBUG_BUFFERS doesn't work unless pool allocators are turned off<commit_after>/*

Copyright (c) 2005, Arvid Norberg
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 the author 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

*/

#ifndef TORRENT_CONFIG_HPP_INCLUDED
#define TORRENT_CONFIG_HPP_INCLUDED

#include <boost/config.hpp>
#include <boost/version.hpp>
#include <stdio.h> // for snprintf

#if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATORS
#error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators
#endif

#ifndef WIN32
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#endif

#ifndef PRId64
#ifdef _WIN32
#define PRId64 "I64d"
#else
#define PRId64 "lld"
#endif
#endif

// ======= GCC =========

#if defined __GNUC__

# if __GNUC__ >= 3
#  define TORRENT_DEPRECATED __attribute__ ((deprecated))
# endif

// GCC pre 4.0 did not have support for the visibility attribute
# if __GNUC__ >= 4
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __attribute__ ((visibility("default")))
#  endif
# endif

// ======= SUNPRO =========

#elif defined __SUNPRO_CC

# if __SUNPRO_CC >= 0x550
#  if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED)
#   define TORRENT_EXPORT __global
#  endif
# endif

// SunPRO seems to have an overly-strict
// definition of POD types and doesn't
// seem to allow boost::array in unions
#define TORRENT_BROKEN_UNIONS 1

// ======= MSVC =========

#elif defined BOOST_MSVC

#pragma warning(disable: 4258)
#pragma warning(disable: 4251)

# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif

#define TORRENT_DEPRECATED_PREFIX __declspec(deprecated)

#endif

// ======= PLATFORMS =========

// set up defines for target environments
// ==== AMIGA ===
#if defined __AMIGA__ || defined __amigaos__ || defined __AROS__
#define TORRENT_AMIGA
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_WRITEV 0
#define TORRENT_USE_READV 0
#define TORRENT_USE_IPV6 0
#define TORRENT_USE_BOOST_THREAD 0
#define TORRENT_USE_IOSTREAM 0
// set this to 1 to disable all floating point operations
// (disables some float-dependent APIs)
#define TORRENT_NO_FPU 1
#define TORRENT_USE_I2P 0
#define TORRENT_USE_ICONV 0

// ==== Darwin/BSD ===
#elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \
	|| defined __FreeBSD_kernel__
#define TORRENT_BSD
// we don't need iconv on mac, because
// the locale is always utf-8
#if defined __APPLE__
#define TORRENT_USE_ICONV 0
#endif
#define TORRENT_HAS_FALLOCATE 0

// ==== LINUX ===
#elif defined __linux__
#define TORRENT_LINUX

// ==== MINGW ===
#elif defined __MINGW32__
#define TORRENT_MINGW
#define TORRENT_WINDOWS
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0

// ==== WINDOWS ===
#elif defined WIN32
#define TORRENT_WINDOWS
// windows has its own functions to convert
// apple uses utf-8 as its locale, so no conversion
// is necessary
#define TORRENT_USE_ICONV 0
#define TORRENT_USE_RLIMIT 0
#define TORRENT_HAS_FALLOCATE 0

// ==== SOLARIS ===
#elif defined sun || defined __sun
#define TORRENT_SOLARIS
#define TORRENT_COMPLETE_TYPES_REQUIRED 1

// ==== BEOS ===
#elif defined __BEOS__ || defined __HAIKU__
#define TORRENT_BEOS
#include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH
#define TORRENT_HAS_FALLOCATE 0
#define TORRENT_USE_MLOCK 0
#define TORRENT_USE_ICONV 0
#if __GNUCC__ == 2
# if defined(TORRENT_BUILDING_SHARED)
#  define TORRENT_EXPORT __declspec(dllexport)
# elif defined(TORRENT_LINKING_SHARED)
#  define TORRENT_EXPORT __declspec(dllimport)
# endif
#endif
#else
#warning unknown OS, assuming BSD
#define TORRENT_BSD
#endif

// on windows, NAME_MAX refers to Unicode characters
// on linux it refers to bytes (utf-8 encoded)
// TODO: Make this count Unicode characters instead of bytes on windows

// windows
#if defined FILENAME_MAX
#define TORRENT_MAX_PATH FILENAME_MAX

// beos
#elif defined B_PATH_NAME_LENGTH
#define TORRENT_MAX_PATH B_PATH_NAME_LENGTH

// solaris
#elif defined MAXPATH
#define TORRENT_MAX_PATH MAXPATH

// posix
#elif defined NAME_MAX
#define TORRENT_MAX_PATH NAME_MAX

// none of the above
#else
// this is the maximum number of characters in a
// path element / filename on windows
#define TORRENT_MAX_PATH 255
#warning unknown platform, assuming the longest path is 255

#endif

#if defined TORRENT_WINDOWS && !defined TORRENT_MINGW

// class X needs to have dll-interface to be used by clients of class Y
#pragma warning(disable:4251)
// '_vsnprintf': This function or variable may be unsafe
#pragma warning(disable:4996)

#include <stdarg.h>

inline int snprintf(char* buf, int len, char const* fmt, ...)
{
	va_list lp;
	va_start(lp, fmt);
	int ret = _vsnprintf(buf, len, fmt, lp);
	va_end(lp);
	if (ret < 0) { buf[len-1] = 0; ret = len-1; }
	return ret;
}

#define strtoll _strtoi64
#else
#include <limits.h>
#endif

#if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \
	&& !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM
#define TORRENT_UPNP_LOGGING
#endif

// libiconv presence, not implemented yet
#ifndef TORRENT_USE_ICONV
#define TORRENT_USE_ICONV 1
#endif

#ifndef TORRENT_BROKEN_UNIONS
#define TORRENT_BROKEN_UNIONS 0
#endif

#if defined UNICODE && !defined BOOST_NO_STD_WSTRING
#define TORRENT_USE_WSTRING 1
#else
#define TORRENT_USE_WSTRING 0
#endif // UNICODE

#ifndef TORRENT_HAS_FALLOCATE
#define TORRENT_HAS_FALLOCATE 1
#endif

#ifndef TORRENT_EXPORT
# define TORRENT_EXPORT
#endif

#ifndef TORRENT_DEPRECATED_PREFIX
#define TORRENT_DEPRECATED_PREFIX
#endif

#ifndef TORRENT_DEPRECATED
#define TORRENT_DEPRECATED
#endif

#ifndef TORRENT_COMPLETE_TYPES_REQUIRED
#define TORRENT_COMPLETE_TYPES_REQUIRED 0
#endif

#ifndef TORRENT_USE_RLIMIT
#define TORRENT_USE_RLIMIT 1
#endif

#ifndef TORRENT_USE_IPV6
#define TORRENT_USE_IPV6 1
#endif

#ifndef TORRENT_USE_MLOCK
#define TORRENT_USE_MLOCK 1
#endif

#ifndef TORRENT_USE_WRITEV
#define TORRENT_USE_WRITEV 1
#endif

#ifndef TORRENT_USE_READV
#define TORRENT_USE_READV 1
#endif

#ifndef TORRENT_NO_FPU
#define TORRENT_NO_FPU 0
#endif

#if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM
#define TORRENT_USE_IOSTREAM 1
#else
#define TORRENT_USE_IOSTREAM 0
#endif

#ifndef TORRENT_USE_I2P
#define TORRENT_USE_I2P 1
#endif

#if !defined(TORRENT_READ_HANDLER_MAX_SIZE)
# define TORRENT_READ_HANDLER_MAX_SIZE 256
#endif

#if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE)
# define TORRENT_WRITE_HANDLER_MAX_SIZE 256
#endif

#if defined _MSC_VER && _MSC_VER <= 1200
#define for if (false) {} else for
#endif

#if TORRENT_BROKEN_UNIONS
#define TORRENT_UNION struct
#else
#define TORRENT_UNION union
#endif

// determine what timer implementation we can use
// if one is already defined, don't pick one
// autmatically. This lets the user control this
// from the Jamfile
#if !defined TORRENT_USE_ABSOLUTE_TIME \
	&& !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \
	&& !defined TORRENT_USE_CLOCK_GETTIME \
	&& !defined TORRENT_USE_BOOST_DATE_TIME \
	&& !defined TORRENT_USE_ECLOCK \
	&& !defined TORRENT_USE_SYSTEM_TIME

#if defined(__MACH__)
#define TORRENT_USE_ABSOLUTE_TIME 1
#elif defined(_WIN32) || defined TORRENT_MINGW
#define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0
#define TORRENT_USE_CLOCK_GETTIME 1
#elif defined(TORRENT_AMIGA)
#define TORRENT_USE_ECLOCK 1
#elif defined(TORRENT_BEOS)
#define TORRENT_USE_SYSTEM_TIME 1
#else
#define TORRENT_USE_BOOST_DATE_TIME 1
#endif

#endif

#endif // TORRENT_CONFIG_HPP_INCLUDED

<|endoftext|>


<commit_before>/*

Copyright (c) 2009, Arvid Norberg
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 the author 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

*/

#ifndef TORRENT_THREAD_HPP_INCLUDED
#define TORRENT_THREAD_HPP_INCLUDED

#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

#include <memory>

#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
// asio assumes that the windows error codes are defined already
#include <winsock2.h>
#endif

#if defined TORRENT_BEOS
#include <kernel/OS.h>
#endif

#include <memory> // for auto_ptr required by asio

#include <boost/asio/detail/thread.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/event.hpp>

#if TORRENT_USE_POSIX_SEMAPHORE
#include <semaphore.h>      // sem_*
#endif

#if TORRENT_USE_MACH_SEMAPHORE
#include <mach/semaphore.h> // semaphore_signal, semaphore_wait
#include <mach/task.h>      // semaphore_create, semaphore_destroy
#include <mach/mach_init.h> // current_task
#endif

namespace libtorrent
{
	typedef boost::asio::detail::thread thread;
	typedef boost::asio::detail::mutex mutex;
	typedef boost::asio::detail::event event;

	TORRENT_EXPORT void sleep(int milliseconds);

	struct TORRENT_EXPORT condition
	{
		condition();
		~condition();
		void wait(mutex::scoped_lock& l);
		void signal_all(mutex::scoped_lock& l);
	private:
#ifdef BOOST_HAS_PTHREADS
		pthread_cond_t m_cond;
#elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
		HANDLE m_sem;
		mutex m_mutex;
		int m_num_waiters;
#elif defined TORRENT_BEOS
		sem_id m_sem;
		mutex m_mutex;
		int m_num_waiters;
#else
#error not implemented
#endif
	};

	// #error these semaphores needs to release all threads that are waiting for the semaphore when signalled
#if TORRENT_USE_POSIX_SEMAPHORE
	struct TORRENT_EXPORT semaphore
	{
		semaphore() { sem_init(&m_sem, 0, 0); }
		~semaphore() { sem_destroy(&m_sem); }
		void signal()
		{
			int ret = sem_post(&m_sem);
			TORRENT_ASSERT(ret == 0);
		}
		void signal_all()
		{
			int waiters = 0;
			do
			{
				// when anyone is waiting, waiters will be
				// 0 or negative. 0 means one might be waiting
				// -1 means 2 are waiting. Keep posting as long
				// we see negative values or 0
				sem_getvalue(&m_sem, &waiters);
				sem_post(&m_sem);
			} while (waiters < 0);
		}
		void wait()
		{
			int ret = sem_wait(&m_sem);
			TORRENT_ASSERT(ret == 0);
		}
		void timed_wait(int ms)
		{
#if TORRENT_HAS_SEM_RELTIMEDWAIT
			timespec sp = { ms / 1000, (ms % 1000) * 1000000 };
			int ret = sem_reltimedwait_np(&m_sem, &sp);
#else
			timespec sp;
			int ret = clock_gettime(CLOCK_REALTIME, &sp);
			TORRENT_ASSERT(ret == 0);
			sp.tv_sec += ms / 1000;
			ms -= ms / 1000;
			boost::uint64_t carry = sp.tv_nsec;
			carry += ms * 1000000;
			sp.tv_nsec = carry % 1000000000;
			sp.tv_sec += carry / 1000000000;

			ret = sem_timedwait(&m_sem, &sp);
#endif
			TORRENT_ASSERT(ret == 0 || errno == ETIMEDOUT);
		}
		sem_t m_sem;
	};
#elif TORRENT_USE_MACH_SEMAPHORE
	struct TORRENT_EXPORT semaphore
	{
		semaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); }
		~semaphore() { semaphore_destroy(current_task(), m_sem); }
		void signal() { semaphore_signal(m_sem); }
		void signal_all() { semaphore_signal_all(m_sem); }
		void wait() { semaphore_wait(m_sem); }
		void timed_wait(int ms)
		{
			mach_timespec_t sp = { ms / 1000, (ms % 1000) * 100000};
			semaphore_timedwait(m_sem, sp);
		}
		semaphore_t m_sem;
	};
#elif defined TORRENT_WINDOWS
	struct TORRENT_EXPORT semaphore
	{
		semaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); }
		~semaphore() { CloseHandle(m_sem); }
		void signal() { ReleaseSemaphore(m_sem, 1, 0); }
		void signal_all()
		{
			LONG prev = 0;
			do { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1);
		}
		void wait() { WaitForSingleObject(m_sem, INFINITE); }
		void timed_wait(int ms) { WaitForSingleObject(m_sem, ms); }
		HANDLE m_sem;
	};
#endif
}

#endif

<commit_msg>fix compilation warning<commit_after>/*

Copyright (c) 2009, Arvid Norberg
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 the author 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 THE COPYRIGHT OWNER OR CONTRIBUTORS 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.

*/

#ifndef TORRENT_THREAD_HPP_INCLUDED
#define TORRENT_THREAD_HPP_INCLUDED

#include "libtorrent/config.hpp"
#include "libtorrent/assert.hpp"

#include <memory>

#if defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
// asio assumes that the windows error codes are defined already
#include <winsock2.h>
#endif

#if defined TORRENT_BEOS
#include <kernel/OS.h>
#endif

#include <memory> // for auto_ptr required by asio

#include <boost/asio/detail/thread.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/event.hpp>

#if TORRENT_USE_POSIX_SEMAPHORE
#include <semaphore.h>      // sem_*
#endif

#if TORRENT_USE_MACH_SEMAPHORE
#include <mach/semaphore.h> // semaphore_signal, semaphore_wait
#include <mach/task.h>      // semaphore_create, semaphore_destroy
#include <mach/mach_init.h> // current_task
#endif

namespace libtorrent
{
	typedef boost::asio::detail::thread thread;
	typedef boost::asio::detail::mutex mutex;
	typedef boost::asio::detail::event event;

	TORRENT_EXPORT void sleep(int milliseconds);

	struct TORRENT_EXPORT condition
	{
		condition();
		~condition();
		void wait(mutex::scoped_lock& l);
		void signal_all(mutex::scoped_lock& l);
	private:
#ifdef BOOST_HAS_PTHREADS
		pthread_cond_t m_cond;
#elif defined TORRENT_WINDOWS || defined TORRENT_CYGWIN
		HANDLE m_sem;
		mutex m_mutex;
		int m_num_waiters;
#elif defined TORRENT_BEOS
		sem_id m_sem;
		mutex m_mutex;
		int m_num_waiters;
#else
#error not implemented
#endif
	};

	// #error these semaphores needs to release all threads that are waiting for the semaphore when signalled
#if TORRENT_USE_POSIX_SEMAPHORE
	struct TORRENT_EXPORT semaphore
	{
		semaphore() { sem_init(&m_sem, 0, 0); }
		~semaphore() { sem_destroy(&m_sem); }
		void signal()
		{
			sem_post(&m_sem);
		}
		void signal_all()
		{
			int waiters = 0;
			do
			{
				// when anyone is waiting, waiters will be
				// 0 or negative. 0 means one might be waiting
				// -1 means 2 are waiting. Keep posting as long
				// we see negative values or 0
				sem_getvalue(&m_sem, &waiters);
				sem_post(&m_sem);
			} while (waiters < 0);
		}
		void wait()
		{
			sem_wait(&m_sem);
		}
		void timed_wait(int ms)
		{
#if TORRENT_HAS_SEM_RELTIMEDWAIT
			timespec sp = { ms / 1000, (ms % 1000) * 1000000 };
			int ret = sem_reltimedwait_np(&m_sem, &sp);
#else
			timespec sp;
			int ret = clock_gettime(CLOCK_REALTIME, &sp);
			TORRENT_ASSERT(ret == 0);
			sp.tv_sec += ms / 1000;
			ms -= ms / 1000;
			boost::uint64_t carry = sp.tv_nsec;
			carry += ms * 1000000;
			sp.tv_nsec = carry % 1000000000;
			sp.tv_sec += carry / 1000000000;

			ret = sem_timedwait(&m_sem, &sp);
#endif
			TORRENT_ASSERT(ret == 0 || errno == ETIMEDOUT);
		}
		sem_t m_sem;
	};
#elif TORRENT_USE_MACH_SEMAPHORE
	struct TORRENT_EXPORT semaphore
	{
		semaphore() { semaphore_create(current_task(), &m_sem, SYNC_POLICY_FIFO, 0); }
		~semaphore() { semaphore_destroy(current_task(), m_sem); }
		void signal() { semaphore_signal(m_sem); }
		void signal_all() { semaphore_signal_all(m_sem); }
		void wait() { semaphore_wait(m_sem); }
		void timed_wait(int ms)
		{
			mach_timespec_t sp = { ms / 1000, (ms % 1000) * 100000};
			semaphore_timedwait(m_sem, sp);
		}
		semaphore_t m_sem;
	};
#elif defined TORRENT_WINDOWS
	struct TORRENT_EXPORT semaphore
	{
		semaphore() { m_sem = CreateSemaphore(0, 0, 100, 0); }
		~semaphore() { CloseHandle(m_sem); }
		void signal() { ReleaseSemaphore(m_sem, 1, 0); }
		void signal_all()
		{
			LONG prev = 0;
			do { ReleaseSemaphore(m_sem, 1, &prev); } while (prev > 1);
		}
		void wait() { WaitForSingleObject(m_sem, INFINITE); }
		void timed_wait(int ms) { WaitForSingleObject(m_sem, ms); }
		HANDLE m_sem;
	};
#endif
}

#endif

<|endoftext|>