<commit_before>//===-- ClangIncludeFixer.cpp - Standalone change namespace ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This tool can be used to change the surrounding namespaces of class/function
// definitions.
//
// Example: test.cc
//    namespace na {
//    class X {};
//    namespace nb {
//    class Y { X x; };
//    } // namespace nb
//    } // namespace na
// To move the definition of class Y from namespace "na::nb" to "x::y", run:
//    clang-change-namespace --old_namespace "na::nb" \
//      --new_namespace "x::y" --file_pattern "test.cc" test.cc --
// Output:
//    namespace na {
//    class X {};
//    } // namespace na
//    namespace x {
//    namespace y {
//    class Y { na::X x; };
//    } // namespace y
//    } // namespace x

#include "ChangeNamespace.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"

using namespace clang;
using namespace llvm;

namespace {

cl::OptionCategory ChangeNamespaceCategory("Change namespace.");

cl::opt<std::string> OldNamespace("old_namespace", cl::Required,
                                  cl::desc("Old namespace."),
                                  cl::cat(ChangeNamespaceCategory));

cl::opt<std::string> NewNamespace("new_namespace", cl::Required,
                                  cl::desc("New namespace."),
                                  cl::cat(ChangeNamespaceCategory));

cl::opt<std::string> FilePattern(
    "file_pattern", cl::Required,
    cl::desc("Only rename namespaces in files that match the given pattern."),
    cl::cat(ChangeNamespaceCategory));

cl::opt<bool> Inplace("i", cl::desc("Inplace edit <file>s, if specified."),
                      cl::cat(ChangeNamespaceCategory));

cl::opt<std::string> Style("style",
                           cl::desc("The style name used for reformatting."),
                           cl::init("LLVM"), cl::cat(ChangeNamespaceCategory));

} // anonymous namespace

int main(int argc, const char **argv) {
  tooling::CommonOptionsParser OptionsParser(argc, argv,
                                             ChangeNamespaceCategory);
  const auto &Files = OptionsParser.getSourcePathList();
  tooling::RefactoringTool Tool(OptionsParser.getCompilations(), Files);
  change_namespace::ChangeNamespaceTool NamespaceTool(
      OldNamespace, NewNamespace, FilePattern, &Tool.getReplacements(), Style);
  ast_matchers::MatchFinder Finder;
  NamespaceTool.registerMatchers(&Finder);
  std::unique_ptr<tooling::FrontendActionFactory> Factory =
      tooling::newFrontendActionFactory(&Finder);

  if (int Result = Tool.run(Factory.get()))
    return Result;
  LangOptions DefaultLangOptions;
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
      &DiagnosticPrinter, false);
  auto &FileMgr = Tool.getFiles();
  SourceManager Sources(Diagnostics, FileMgr);
  Rewriter Rewrite(Sources, DefaultLangOptions);

  if (!formatAndApplyAllReplacements(Tool.getReplacements(), Rewrite, Style)) {
    llvm::errs() << "Failed applying all replacements.\n";
    return 1;
  }
  if (Inplace)
    return Rewrite.overwriteChangedFiles();

  for (const auto &File : Files) {
    const auto *Entry = FileMgr.getFile(File);

    auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
    // FIXME: print results in parsable format, e.g. JSON.
    outs() << "============== " << File << " ==============\n";
    Rewrite.getEditBuffer(ID).write(llvm::outs());
    outs() << "\n============================================\n";
  }
  return 0;
}
<commit_msg>Print stack trace for clang-change-namespace tool.<commit_after>//===-- ClangIncludeFixer.cpp - Standalone change namespace ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This tool can be used to change the surrounding namespaces of class/function
// definitions.
//
// Example: test.cc
//    namespace na {
//    class X {};
//    namespace nb {
//    class Y { X x; };
//    } // namespace nb
//    } // namespace na
// To move the definition of class Y from namespace "na::nb" to "x::y", run:
//    clang-change-namespace --old_namespace "na::nb" \
//      --new_namespace "x::y" --file_pattern "test.cc" test.cc --
// Output:
//    namespace na {
//    class X {};
//    } // namespace na
//    namespace x {
//    namespace y {
//    class Y { na::X x; };
//    } // namespace y
//    } // namespace x

#include "ChangeNamespace.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Refactoring.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Signals.h"

using namespace clang;
using namespace llvm;

namespace {

cl::OptionCategory ChangeNamespaceCategory("Change namespace.");

cl::opt<std::string> OldNamespace("old_namespace", cl::Required,
                                  cl::desc("Old namespace."),
                                  cl::cat(ChangeNamespaceCategory));

cl::opt<std::string> NewNamespace("new_namespace", cl::Required,
                                  cl::desc("New namespace."),
                                  cl::cat(ChangeNamespaceCategory));

cl::opt<std::string> FilePattern(
    "file_pattern", cl::Required,
    cl::desc("Only rename namespaces in files that match the given pattern."),
    cl::cat(ChangeNamespaceCategory));

cl::opt<bool> Inplace("i", cl::desc("Inplace edit <file>s, if specified."),
                      cl::cat(ChangeNamespaceCategory));

cl::opt<std::string> Style("style",
                           cl::desc("The style name used for reformatting."),
                           cl::init("LLVM"), cl::cat(ChangeNamespaceCategory));

} // anonymous namespace

int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);
  tooling::CommonOptionsParser OptionsParser(argc, argv,
                                             ChangeNamespaceCategory);
  const auto &Files = OptionsParser.getSourcePathList();
  tooling::RefactoringTool Tool(OptionsParser.getCompilations(), Files);
  change_namespace::ChangeNamespaceTool NamespaceTool(
      OldNamespace, NewNamespace, FilePattern, &Tool.getReplacements(), Style);
  ast_matchers::MatchFinder Finder;
  NamespaceTool.registerMatchers(&Finder);
  std::unique_ptr<tooling::FrontendActionFactory> Factory =
      tooling::newFrontendActionFactory(&Finder);

  if (int Result = Tool.run(Factory.get()))
    return Result;
  LangOptions DefaultLangOptions;
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  clang::TextDiagnosticPrinter DiagnosticPrinter(errs(), &*DiagOpts);
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts,
      &DiagnosticPrinter, false);
  auto &FileMgr = Tool.getFiles();
  SourceManager Sources(Diagnostics, FileMgr);
  Rewriter Rewrite(Sources, DefaultLangOptions);

  if (!formatAndApplyAllReplacements(Tool.getReplacements(), Rewrite, Style)) {
    llvm::errs() << "Failed applying all replacements.\n";
    return 1;
  }
  if (Inplace)
    return Rewrite.overwriteChangedFiles();

  for (const auto &File : Files) {
    const auto *Entry = FileMgr.getFile(File);

    auto ID = Sources.getOrCreateFileID(Entry, SrcMgr::C_User);
    // FIXME: print results in parsable format, e.g. JSON.
    outs() << "============== " << File << " ==============\n";
    Rewrite.getEditBuffer(ID).write(llvm::outs());
    outs() << "\n============================================\n";
  }
  return 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 * @(#)root/roofitcore:$Id$
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2005, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

//////////////////////////////////////////////////////////////////////////////
//
// BEGIN_HTML
// Class RooParamBinning is an implementation of RooAbsBinning that constructs
// a binning with a range definition that depends on external RooAbsReal objects.
// The external RooAbsReal definitions are explicitly allowed to depend on other
// observables and parameters, and make it possible to define non-rectangular
// range definitions in RooFit. Objects of class RooParamBinning are made
// by the RooRealVar::setRange() that takes RooAbsReal references as arguments
// END_HTML
//

#include "RooFit.h"

#include "RooParamBinning.h"
#include "RooParamBinning.h"
#include "RooMsgService.h"

#include "Riostream.h"

ClassImp(RooParamBinning)
;

//_____________________________________________________________________________
RooParamBinning::RooParamBinning(const char* name) :
  RooAbsBinning(name), _lp(0), _xlo(0), _xhi(0), _owner(0)
{
  // Default constructor

  _array = 0 ;
}

//_____________________________________________________________________________
RooParamBinning::RooParamBinning(RooAbsReal& xloIn, RooAbsReal& xhiIn, Int_t nBins, const char* name) :
  RooAbsBinning(name),
  _array(0),
  _xlo(&xloIn),
  _xhi(&xhiIn),
  _nbins(nBins),
  _lp(0),
  _owner(0)
{
  // Construct binning with 'nBins' bins and with a range
  // parameterized by external RooAbsReals xloIn and xhiIn.
}

//_____________________________________________________________________________
RooParamBinning::~RooParamBinning()
{
  // Destructor

  if (_array) delete[] _array ;
  if (_lp) delete _lp ;
}

//_____________________________________________________________________________
RooParamBinning::RooParamBinning(const RooParamBinning& other, const char* name) :
  RooAbsBinning(name), _owner(0)
{
  // Copy constructor

  _array = 0 ;

  if (other._lp) {
    //cout << "RooParamBinning::cctor(this = " << this << " taking addresses from ListProxy" << endl ;
    _xlo = (RooAbsReal*) other._lp->at(0) ;
    _xhi = (RooAbsReal*) other._lp->at(1) ;

  } else {

    //cout << "RooParamBinning::cctor(this = " << this << " taking addresses from pointers " << endl ;

    _xlo   = other._xlo ;
    _xhi   = other._xhi ;
  }

  _nbins = other._nbins ;
  _lp = 0 ;

  //cout << "RooParamBinning::cctor(this = " << this << " xlo = " << &_xlo << " xhi = " << &_xhi << " _lp = " << _lp << " owner = " << _owner << ")" << endl ;
}

//_____________________________________________________________________________
void RooParamBinning::insertHook(RooAbsRealLValue& owner) const
{
  // Hook function called by RooAbsRealLValue when this binning
  // is inserted as binning for into given owner. Create
  // list proxy registered with owner that will track and implement
  // server directs to external RooAbsReals of this binning

  _owner = &owner ;

  // If list proxy already exists update pointers from proxy
  if (_lp) {
    _xlo = xlo() ;
    _xhi = xhi() ;
    delete _lp ;
  }

  // If list proxy does not exist, creat it now
  _lp = new RooListProxy(Form("range::%s",GetName()),"lp",&owner,kFALSE,kTRUE) ;
  _lp->add(*_xlo) ;
  _lp->add(*_xhi) ;
  _xlo = 0 ;
  _xhi = 0 ;

}

//_____________________________________________________________________________
void RooParamBinning::removeHook(RooAbsRealLValue& /*owner*/) const
{
  // Hook function called by RooAbsRealLValue when this binning
  // is removed as binning for into given owner. Delete list
  // proxy that was inserted in owner

  _owner = 0 ;

  // Remove list proxy from owner
  if (_lp) {
    _xlo = xlo() ;
    _xhi = xhi() ;
    delete _lp ;
    _lp = 0 ;
  }
}

//_____________________________________________________________________________
void RooParamBinning::setRange(Double_t newxlo, Double_t newxhi)
{
  // Adjust range by adjusting values of external RooAbsReal values
  // Only functional when external representations are lvalues

  if (newxlo>newxhi) {
    coutE(InputArguments) << "RooParamBinning::setRange: ERROR low bound > high bound" << endl ;
    return ;
  }

  RooAbsRealLValue* xlolv = dynamic_cast<RooAbsRealLValue*>(xlo()) ;
  if (xlolv) {
    xlolv->setVal(newxlo) ;
  } else {
    coutW(InputArguments) << "RooParamBinning::setRange: WARNING lower bound not represented by lvalue, cannot set lower bound value through setRange()" << endl ;
  }

  RooAbsRealLValue* xhilv = dynamic_cast<RooAbsRealLValue*>(xhi()) ;
  if (xhilv) {
    xhilv->setVal(newxhi) ;
  } else {
    coutW(InputArguments) << "RooParamBinning::setRange: WARNING upper bound not represented by lvalue, cannot set upper bound value through setRange()" << endl ;
  }

}

//_____________________________________________________________________________
Int_t RooParamBinning::binNumber(Double_t x) const
{
  // Return the fit bin index for the current value

  if (x >= xhi()->getVal()) return _nbins-1 ;
  if (x < xlo()->getVal()) return 0 ;

  return Int_t((x - xlo()->getVal())/averageBinWidth()) ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binCenter(Int_t i) const
{
  // Return the central value of the 'i'-th fit bin

  if (i<0 || i>=_nbins) {
    coutE(InputArguments) << "RooParamBinning::binCenter ERROR: bin index " << i
			  << " is out of range (0," << _nbins-1 << ")" << endl ;
    return 0 ;
  }

  return xlo()->getVal() + (i + 0.5)*averageBinWidth() ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binWidth(Int_t /*bin*/) const
{
  // Return average bin width

  return (xhi()->getVal()-xlo()->getVal())/_nbins ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binLow(Int_t i) const
{
  // Return the low edge of the 'i'-th fit bin

  if (i<0 || i>=_nbins) {
    coutE(InputArguments) << "RooParamBinning::binLow ERROR: bin index " << i
			  << " is out of range (0," << _nbins-1 << ")" << endl ;
    return 0 ;
  }

  return xlo()->getVal() + i*binWidth(i) ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binHigh(Int_t i) const
{
  // Return the high edge of the 'i'-th fit bin

  if (i<0 || i>=_nbins) {
    coutE(InputArguments) << "RooParamBinning::fitBinHigh ERROR: bin index " << i
			  << " is out of range (0," << _nbins-1 << ")" << endl ;
    return 0 ;
  }

  return xlo()->getVal() + (i + 1)*binWidth(i) ;
}

//_____________________________________________________________________________
Double_t* RooParamBinning::array() const
{
  // Return array of bin boundaries

  if (_array) delete[] _array ;
  _array = new Double_t[_nbins+1] ;

  Int_t i ;
  for (i=0 ; i<=_nbins ; i++) {
    _array[i] = xlo()->getVal() + i*binWidth(i) ;
  }
  return _array ;
}

//_____________________________________________________________________________
void RooParamBinning::printMultiline(ostream &os, Int_t /*content*/, Bool_t /*verbose*/, TString indent) const
{
  // Print details of binning
  os << indent << "_xlo = " << _xlo << endl ;
  os << indent << "_xhi = " << _xhi << endl ;
  if (_lp) {
    os << indent << "xlo() = " << xlo() << endl ;
    os << indent << "xhi() = " << xhi() << endl ;
  }
  if (xlo()) {
    xlo()->Print("t") ;
  }
  if (xhi()) {
    xhi()->Print("t") ;
  }
}

<commit_msg><commit_after>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 * @(#)root/roofitcore:$Id$
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2005, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

//////////////////////////////////////////////////////////////////////////////
//
// BEGIN_HTML
// Class RooParamBinning is an implementation of RooAbsBinning that constructs
// a binning with a range definition that depends on external RooAbsReal objects.
// The external RooAbsReal definitions are explicitly allowed to depend on other
// observables and parameters, and make it possible to define non-rectangular
// range definitions in RooFit. Objects of class RooParamBinning are made
// by the RooRealVar::setRange() that takes RooAbsReal references as arguments
// END_HTML
//

#include "RooFit.h"

#include "RooParamBinning.h"
#include "RooParamBinning.h"
#include "RooMsgService.h"

#include "Riostream.h"

ClassImp(RooParamBinning)
;

//_____________________________________________________________________________
RooParamBinning::RooParamBinning(const char* name) :
  RooAbsBinning(name), _xlo(0), _xhi(0), _lp(0), _owner(0)
{
  // Default constructor

  _array = 0 ;
}

//_____________________________________________________________________________
RooParamBinning::RooParamBinning(RooAbsReal& xloIn, RooAbsReal& xhiIn, Int_t nBins, const char* name) :
  RooAbsBinning(name),
  _array(0),
  _xlo(&xloIn),
  _xhi(&xhiIn),
  _nbins(nBins),
  _lp(0),
  _owner(0)
{
  // Construct binning with 'nBins' bins and with a range
  // parameterized by external RooAbsReals xloIn and xhiIn.
}

//_____________________________________________________________________________
RooParamBinning::~RooParamBinning()
{
  // Destructor

  if (_array) delete[] _array ;
  if (_lp) delete _lp ;
}

//_____________________________________________________________________________
RooParamBinning::RooParamBinning(const RooParamBinning& other, const char* name) :
  RooAbsBinning(name), _owner(0)
{
  // Copy constructor

  _array = 0 ;

  if (other._lp) {
    //cout << "RooParamBinning::cctor(this = " << this << " taking addresses from ListProxy" << endl ;
    _xlo = (RooAbsReal*) other._lp->at(0) ;
    _xhi = (RooAbsReal*) other._lp->at(1) ;

  } else {

    //cout << "RooParamBinning::cctor(this = " << this << " taking addresses from pointers " << endl ;

    _xlo   = other._xlo ;
    _xhi   = other._xhi ;
  }

  _nbins = other._nbins ;
  _lp = 0 ;

  //cout << "RooParamBinning::cctor(this = " << this << " xlo = " << &_xlo << " xhi = " << &_xhi << " _lp = " << _lp << " owner = " << _owner << ")" << endl ;
}

//_____________________________________________________________________________
void RooParamBinning::insertHook(RooAbsRealLValue& owner) const
{
  // Hook function called by RooAbsRealLValue when this binning
  // is inserted as binning for into given owner. Create
  // list proxy registered with owner that will track and implement
  // server directs to external RooAbsReals of this binning

  _owner = &owner ;

  // If list proxy already exists update pointers from proxy
  if (_lp) {
    _xlo = xlo() ;
    _xhi = xhi() ;
    delete _lp ;
  }

  // If list proxy does not exist, creat it now
  _lp = new RooListProxy(Form("range::%s",GetName()),"lp",&owner,kFALSE,kTRUE) ;
  _lp->add(*_xlo) ;
  _lp->add(*_xhi) ;
  _xlo = 0 ;
  _xhi = 0 ;

}

//_____________________________________________________________________________
void RooParamBinning::removeHook(RooAbsRealLValue& /*owner*/) const
{
  // Hook function called by RooAbsRealLValue when this binning
  // is removed as binning for into given owner. Delete list
  // proxy that was inserted in owner

  _owner = 0 ;

  // Remove list proxy from owner
  if (_lp) {
    _xlo = xlo() ;
    _xhi = xhi() ;
    delete _lp ;
    _lp = 0 ;
  }
}

//_____________________________________________________________________________
void RooParamBinning::setRange(Double_t newxlo, Double_t newxhi)
{
  // Adjust range by adjusting values of external RooAbsReal values
  // Only functional when external representations are lvalues

  if (newxlo>newxhi) {
    coutE(InputArguments) << "RooParamBinning::setRange: ERROR low bound > high bound" << endl ;
    return ;
  }

  RooAbsRealLValue* xlolv = dynamic_cast<RooAbsRealLValue*>(xlo()) ;
  if (xlolv) {
    xlolv->setVal(newxlo) ;
  } else {
    coutW(InputArguments) << "RooParamBinning::setRange: WARNING lower bound not represented by lvalue, cannot set lower bound value through setRange()" << endl ;
  }

  RooAbsRealLValue* xhilv = dynamic_cast<RooAbsRealLValue*>(xhi()) ;
  if (xhilv) {
    xhilv->setVal(newxhi) ;
  } else {
    coutW(InputArguments) << "RooParamBinning::setRange: WARNING upper bound not represented by lvalue, cannot set upper bound value through setRange()" << endl ;
  }

}

//_____________________________________________________________________________
Int_t RooParamBinning::binNumber(Double_t x) const
{
  // Return the fit bin index for the current value

  if (x >= xhi()->getVal()) return _nbins-1 ;
  if (x < xlo()->getVal()) return 0 ;

  return Int_t((x - xlo()->getVal())/averageBinWidth()) ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binCenter(Int_t i) const
{
  // Return the central value of the 'i'-th fit bin

  if (i<0 || i>=_nbins) {
    coutE(InputArguments) << "RooParamBinning::binCenter ERROR: bin index " << i
			  << " is out of range (0," << _nbins-1 << ")" << endl ;
    return 0 ;
  }

  return xlo()->getVal() + (i + 0.5)*averageBinWidth() ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binWidth(Int_t /*bin*/) const
{
  // Return average bin width

  return (xhi()->getVal()-xlo()->getVal())/_nbins ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binLow(Int_t i) const
{
  // Return the low edge of the 'i'-th fit bin

  if (i<0 || i>=_nbins) {
    coutE(InputArguments) << "RooParamBinning::binLow ERROR: bin index " << i
			  << " is out of range (0," << _nbins-1 << ")" << endl ;
    return 0 ;
  }

  return xlo()->getVal() + i*binWidth(i) ;
}

//_____________________________________________________________________________
Double_t RooParamBinning::binHigh(Int_t i) const
{
  // Return the high edge of the 'i'-th fit bin

  if (i<0 || i>=_nbins) {
    coutE(InputArguments) << "RooParamBinning::fitBinHigh ERROR: bin index " << i
			  << " is out of range (0," << _nbins-1 << ")" << endl ;
    return 0 ;
  }

  return xlo()->getVal() + (i + 1)*binWidth(i) ;
}

//_____________________________________________________________________________
Double_t* RooParamBinning::array() const
{
  // Return array of bin boundaries

  if (_array) delete[] _array ;
  _array = new Double_t[_nbins+1] ;

  Int_t i ;
  for (i=0 ; i<=_nbins ; i++) {
    _array[i] = xlo()->getVal() + i*binWidth(i) ;
  }
  return _array ;
}

//_____________________________________________________________________________
void RooParamBinning::printMultiline(ostream &os, Int_t /*content*/, Bool_t /*verbose*/, TString indent) const
{
  // Print details of binning
  os << indent << "_xlo = " << _xlo << endl ;
  os << indent << "_xhi = " << _xhi << endl ;
  if (_lp) {
    os << indent << "xlo() = " << xlo() << endl ;
    os << indent << "xhi() = " << xhi() << endl ;
  }
  if (xlo()) {
    xlo()->Print("t") ;
  }
  if (xhi()) {
    xhi()->Print("t") ;
  }
}

<|endoftext|>


<commit_before>/* This file is part of Zanshin

   Copyright 2014 Kevin Ottens <ervin@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "applicationmodel.h"

#include "domain/artifactqueries.h"
#include "domain/noterepository.h"
#include "domain/taskqueries.h"
#include "domain/taskrepository.h"

#include "presentation/datasourcelistmodel.h"
#include "presentation/querytreemodel.h"
#include "presentation/inboxpagemodel.h"

#include "utils/dependencymanager.h"

using namespace Presentation;

ApplicationModel::ApplicationModel(QObject *parent)
    : QObject(parent),
      m_currentPage(0),
      m_artifactQueries(Utils::DependencyManager::globalInstance().create<Domain::ArtifactQueries>()),
      m_sourceQueries(Utils::DependencyManager::globalInstance().create<Domain::DataSourceQueries>()),
      m_taskQueries(Utils::DependencyManager::globalInstance().create<Domain::TaskQueries>()),
      m_taskRepository(Utils::DependencyManager::globalInstance().create<Domain::TaskRepository>()),
      m_taskSourcesModel(0),
      m_noteRepository(Utils::DependencyManager::globalInstance().create<Domain::NoteRepository>()),
      m_noteSourcesModel(0),
      m_ownInterface(true)
{
    qRegisterMetaType<QAbstractItemModel*>();
    qRegisterMetaType<Domain::DataSource::Ptr>();
}

ApplicationModel::ApplicationModel(Domain::ArtifactQueries *artifactQueries,
                       Domain::DataSourceQueries *sourceQueries,
                       Domain::TaskQueries *taskQueries,
                       Domain::TaskRepository *taskRepository,
                       Domain::NoteRepository *noteRepository,
                       QObject *parent)
    : QObject(parent),
      m_currentPage(0),
      m_artifactQueries(artifactQueries),
      m_sourceQueries(sourceQueries),
      m_taskQueries(taskQueries),
      m_taskRepository(taskRepository),
      m_taskSourcesModel(0),
      m_noteRepository(noteRepository),
      m_noteSourcesModel(0),
      m_ownInterface(false)
{
    qRegisterMetaType<QAbstractItemModel*>();
    qRegisterMetaType<Domain::DataSource::Ptr>();
}

ApplicationModel::~ApplicationModel()
{
}

QAbstractItemModel *ApplicationModel::noteSourcesModel()
{
    if (!m_noteSourcesModel) {
        m_noteSourcesModel = new DataSourceListModel([this] { return noteSources(); }, this);
    }

    return m_noteSourcesModel;
}

Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::noteSources()
{
    if (!m_noteSources) {
        m_noteSources = m_sourceQueries->findNotes();
    }

    return m_noteSources;
}

Domain::DataSource::Ptr ApplicationModel::defaultNoteDataSource()
{
    QList<Domain::DataSource::Ptr> sources = noteSources()->data();

    if (sources.isEmpty())
        return Domain::DataSource::Ptr();

    auto source = std::find_if(sources.begin(), sources.end(),
                               [this] (const Domain::DataSource::Ptr &source) {
                                   return m_noteRepository->isDefaultSource(source);
                               });

    if (source != sources.end())
        return *source;
    else
        return sources.first();
}

QAbstractItemModel *ApplicationModel::taskSourcesModel()
{
    if (!m_taskSourcesModel) {
        m_taskSourcesModel = new DataSourceListModel([this] { return taskSources(); }, this);
    }

    return m_taskSourcesModel;
}

Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::taskSources()
{
    if (!m_taskSources) {
        m_taskSources = m_sourceQueries->findTasks();
    }

    return m_taskSources;
}

Domain::DataSource::Ptr ApplicationModel::defaultTaskDataSource()
{
    QList<Domain::DataSource::Ptr> sources = taskSources()->data();

    if (sources.isEmpty())
        return Domain::DataSource::Ptr();

    auto source = std::find_if(sources.begin(), sources.end(),
                               [this] (const Domain::DataSource::Ptr &source) {
                                   return m_taskRepository->isDefaultSource(source);
                               });

    if (source != sources.end())
        return *source;
    else
        return sources.first();
}

QObject *ApplicationModel::currentPage()
{
    if (!m_currentPage) {
        m_currentPage = new InboxPageModel(m_artifactQueries, m_taskQueries,
                                           m_taskRepository, m_noteRepository);
    }

    return m_currentPage;
}

void ApplicationModel::setDefaultNoteDataSource(Domain::DataSource::Ptr source)
{
    m_noteRepository->setDefaultSource(source);
}

void ApplicationModel::setDefaultTaskDataSource(Domain::DataSource::Ptr source)
{
    m_taskRepository->setDefaultSource(source);
}
<commit_msg>What about not leaking memory?<commit_after>/* This file is part of Zanshin

   Copyright 2014 Kevin Ottens <ervin@kde.org>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License as
   published by the Free Software Foundation; either version 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "applicationmodel.h"

#include "domain/artifactqueries.h"
#include "domain/noterepository.h"
#include "domain/taskqueries.h"
#include "domain/taskrepository.h"

#include "presentation/datasourcelistmodel.h"
#include "presentation/querytreemodel.h"
#include "presentation/inboxpagemodel.h"

#include "utils/dependencymanager.h"

using namespace Presentation;

ApplicationModel::ApplicationModel(QObject *parent)
    : QObject(parent),
      m_currentPage(0),
      m_artifactQueries(Utils::DependencyManager::globalInstance().create<Domain::ArtifactQueries>()),
      m_sourceQueries(Utils::DependencyManager::globalInstance().create<Domain::DataSourceQueries>()),
      m_taskQueries(Utils::DependencyManager::globalInstance().create<Domain::TaskQueries>()),
      m_taskRepository(Utils::DependencyManager::globalInstance().create<Domain::TaskRepository>()),
      m_taskSourcesModel(0),
      m_noteRepository(Utils::DependencyManager::globalInstance().create<Domain::NoteRepository>()),
      m_noteSourcesModel(0),
      m_ownInterface(true)
{
    qRegisterMetaType<QAbstractItemModel*>();
    qRegisterMetaType<Domain::DataSource::Ptr>();
}

ApplicationModel::ApplicationModel(Domain::ArtifactQueries *artifactQueries,
                       Domain::DataSourceQueries *sourceQueries,
                       Domain::TaskQueries *taskQueries,
                       Domain::TaskRepository *taskRepository,
                       Domain::NoteRepository *noteRepository,
                       QObject *parent)
    : QObject(parent),
      m_currentPage(0),
      m_artifactQueries(artifactQueries),
      m_sourceQueries(sourceQueries),
      m_taskQueries(taskQueries),
      m_taskRepository(taskRepository),
      m_taskSourcesModel(0),
      m_noteRepository(noteRepository),
      m_noteSourcesModel(0),
      m_ownInterface(false)
{
    qRegisterMetaType<QAbstractItemModel*>();
    qRegisterMetaType<Domain::DataSource::Ptr>();
}

ApplicationModel::~ApplicationModel()
{
    if (m_ownInterface) {
        delete m_artifactQueries;
        delete m_sourceQueries;
        delete m_taskQueries;
        delete m_taskRepository;
        delete m_noteRepository;
    }
}

QAbstractItemModel *ApplicationModel::noteSourcesModel()
{
    if (!m_noteSourcesModel) {
        m_noteSourcesModel = new DataSourceListModel([this] { return noteSources(); }, this);
    }

    return m_noteSourcesModel;
}

Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::noteSources()
{
    if (!m_noteSources) {
        m_noteSources = m_sourceQueries->findNotes();
    }

    return m_noteSources;
}

Domain::DataSource::Ptr ApplicationModel::defaultNoteDataSource()
{
    QList<Domain::DataSource::Ptr> sources = noteSources()->data();

    if (sources.isEmpty())
        return Domain::DataSource::Ptr();

    auto source = std::find_if(sources.begin(), sources.end(),
                               [this] (const Domain::DataSource::Ptr &source) {
                                   return m_noteRepository->isDefaultSource(source);
                               });

    if (source != sources.end())
        return *source;
    else
        return sources.first();
}

QAbstractItemModel *ApplicationModel::taskSourcesModel()
{
    if (!m_taskSourcesModel) {
        m_taskSourcesModel = new DataSourceListModel([this] { return taskSources(); }, this);
    }

    return m_taskSourcesModel;
}

Domain::QueryResult<Domain::DataSource::Ptr>::Ptr ApplicationModel::taskSources()
{
    if (!m_taskSources) {
        m_taskSources = m_sourceQueries->findTasks();
    }

    return m_taskSources;
}

Domain::DataSource::Ptr ApplicationModel::defaultTaskDataSource()
{
    QList<Domain::DataSource::Ptr> sources = taskSources()->data();

    if (sources.isEmpty())
        return Domain::DataSource::Ptr();

    auto source = std::find_if(sources.begin(), sources.end(),
                               [this] (const Domain::DataSource::Ptr &source) {
                                   return m_taskRepository->isDefaultSource(source);
                               });

    if (source != sources.end())
        return *source;
    else
        return sources.first();
}

QObject *ApplicationModel::currentPage()
{
    if (!m_currentPage) {
        m_currentPage = new InboxPageModel(m_artifactQueries, m_taskQueries,
                                           m_taskRepository, m_noteRepository, this);
    }

    return m_currentPage;
}

void ApplicationModel::setDefaultNoteDataSource(Domain::DataSource::Ptr source)
{
    m_noteRepository->setDefaultSource(source);
}

void ApplicationModel::setDefaultTaskDataSource(Domain::DataSource::Ptr source)
{
    m_taskRepository->setDefaultSource(source);
}
<|endoftext|>


<commit_before>// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/timestamp.h"
#include <chrono>
#include <iomanip>
#include <sstream>
#include "llvm/Support/Format.h"

using namespace ofp;

const UInt32 kNanoPerSec = 1000000000;

/// \brief Compute difference in seconds.
///
/// \returns elapsed seconds between `this` and `ts.
///
/// Value is negative if ts > this.
double Timestamp::secondsSince(const Timestamp &ts) const {
  if (ts > *this) {
    return -ts.secondsSince(*this);
  }

  assert(*this >= ts);

  UInt64 diff = Unsigned_cast(seconds() - ts.seconds());
  if (nanoseconds() >= ts.nanoseconds()) {
    return diff +
           static_cast<double>(nanoseconds() - ts.nanoseconds()) / kNanoPerSec;
  }

  assert(diff > 0);
  return (diff - 1) +
         static_cast<double>(kNanoPerSec - ts.nanoseconds() +
                             nanoseconds()) / kNanoPerSec;
}

static const UInt32 kPower10[10] = {
    1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};

bool Timestamp::parse(const std::string &s) {
  UInt64 wholeNum = 0;
  UInt32 fracNum = 0;
  const char *p = s.c_str();

  const char *wholeStart = p;
  while (isdigit(*p)) {
    wholeNum = (wholeNum * 10) + Unsigned_cast(*p - '0');
    ++p;
  }

  if (p == wholeStart)
    return false;

  if (*p != '.')
    return false;
  ++p;

  const char *fracStart = p;
  while (isdigit(*p)) {
    fracNum = (fracNum * 10) + Unsigned_cast(*p - '0');
    ++p;
  }

  if (*p != 0)
    return false;

  auto fracDigits = p - fracStart;
  if (fracDigits == 0 || fracDigits > 9)
    return false;

  fracNum *= kPower10[9 - fracDigits];
  assert(fracNum < 1000000000);

  time_.first = static_cast<time_t>(wholeNum);
  time_.second = fracNum;

  return true;
}

std::string Timestamp::toString() const {
  std::stringstream strm;
  strm << time_.first << '.' << std::setfill('0') << std::setw(9)
       << time_.second;
  return strm.str();
}

std::string Timestamp::toStringUTC() const {
  char buf[TS_BUFSIZE];
  auto len = toStringUTC(buf);
  return std::string{buf, len};
}

size_t Timestamp::toStringUTC(char (&buf)[TS_BUFSIZE]) const {
  const int TIMESTAMP_LEN = 30;
  static_assert(TIMESTAMP_LEN + 1 < sizeof(buf), "Buffer too small");

  auto secs = seconds();
  auto nsec = nanoseconds();

  struct tm date;
  gmtime_r(&secs, &date);
  date.tm_year += 1900;
  date.tm_mon += 1;

  int rc = snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02d.%09dZ",
                    date.tm_year, date.tm_mon, date.tm_mday, date.tm_hour,
                    date.tm_min, date.tm_sec, nsec);
  assert(rc == TIMESTAMP_LEN);
  return (rc == TIMESTAMP_LEN) ? TIMESTAMP_LEN : 0;
}

Timestamp Timestamp::now() {
  using namespace std::chrono;

  auto now = system_clock::now();
  auto duration = now.time_since_epoch();
  auto nano = duration_cast<std::chrono::nanoseconds>(duration).count();

  return Timestamp{static_cast<time_t>(nano / 1000000000),
                   UInt32_narrow_cast(nano % 1000000000)};
}

namespace ofp {

llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Timestamp &value) {
  return os << llvm::format("%llu.%09lu", value.time_.first, value.time_.second);
}

}  // namespace ofp
<commit_msg>Fix format string.<commit_after>// Copyright (c) 2015-2016 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.

#include "ofp/timestamp.h"
#include <chrono>
#include <iomanip>
#include <sstream>
#include "llvm/Support/Format.h"

using namespace ofp;

const UInt32 kNanoPerSec = 1000000000;

/// \brief Compute difference in seconds.
///
/// \returns elapsed seconds between `this` and `ts.
///
/// Value is negative if ts > this.
double Timestamp::secondsSince(const Timestamp &ts) const {
  if (ts > *this) {
    return -ts.secondsSince(*this);
  }

  assert(*this >= ts);

  UInt64 diff = Unsigned_cast(seconds() - ts.seconds());
  if (nanoseconds() >= ts.nanoseconds()) {
    return diff +
           static_cast<double>(nanoseconds() - ts.nanoseconds()) / kNanoPerSec;
  }

  assert(diff > 0);
  return (diff - 1) +
         static_cast<double>(kNanoPerSec - ts.nanoseconds() +
                             nanoseconds()) / kNanoPerSec;
}

static const UInt32 kPower10[10] = {
    1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};

bool Timestamp::parse(const std::string &s) {
  UInt64 wholeNum = 0;
  UInt32 fracNum = 0;
  const char *p = s.c_str();

  const char *wholeStart = p;
  while (isdigit(*p)) {
    wholeNum = (wholeNum * 10) + Unsigned_cast(*p - '0');
    ++p;
  }

  if (p == wholeStart)
    return false;

  if (*p != '.')
    return false;
  ++p;

  const char *fracStart = p;
  while (isdigit(*p)) {
    fracNum = (fracNum * 10) + Unsigned_cast(*p - '0');
    ++p;
  }

  if (*p != 0)
    return false;

  auto fracDigits = p - fracStart;
  if (fracDigits == 0 || fracDigits > 9)
    return false;

  fracNum *= kPower10[9 - fracDigits];
  assert(fracNum < 1000000000);

  time_.first = static_cast<time_t>(wholeNum);
  time_.second = fracNum;

  return true;
}

std::string Timestamp::toString() const {
  std::stringstream strm;
  strm << time_.first << '.' << std::setfill('0') << std::setw(9)
       << time_.second;
  return strm.str();
}

std::string Timestamp::toStringUTC() const {
  char buf[TS_BUFSIZE];
  auto len = toStringUTC(buf);
  return std::string{buf, len};
}

size_t Timestamp::toStringUTC(char (&buf)[TS_BUFSIZE]) const {
  const int TIMESTAMP_LEN = 30;
  static_assert(TIMESTAMP_LEN + 1 < sizeof(buf), "Buffer too small");

  auto secs = seconds();
  auto nsec = nanoseconds();

  struct tm date;
  gmtime_r(&secs, &date);
  date.tm_year += 1900;
  date.tm_mon += 1;

  int rc = snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02d.%09dZ",
                    date.tm_year, date.tm_mon, date.tm_mday, date.tm_hour,
                    date.tm_min, date.tm_sec, nsec);
  assert(rc == TIMESTAMP_LEN);
  return (rc == TIMESTAMP_LEN) ? TIMESTAMP_LEN : 0;
}

Timestamp Timestamp::now() {
  using namespace std::chrono;

  auto now = system_clock::now();
  auto duration = now.time_since_epoch();
  auto nano = duration_cast<std::chrono::nanoseconds>(duration).count();

  return Timestamp{static_cast<time_t>(nano / 1000000000),
                   UInt32_narrow_cast(nano % 1000000000)};
}

namespace ofp {

llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Timestamp &value) {
  return os << llvm::format("%llu.%09u", value.time_.first, value.time_.second);
}

}  // namespace ofp
<|endoftext|>


<commit_before>#include "test-drafter.h"

#include "cdrafter.h"

#include <string.h>

TEST_CASE("c-interface parse blueprint ","[c-interface]")
{
    ITFixtureFiles fixture = ITFixtureFiles("test/fixtures/annotations-with-warning");

    std::string source = fixture.get(".apib");

    char *result = NULL;

    int ret = drafter_c_parse(source.c_str(), 0, &result);

    REQUIRE(ret == 0);

    REQUIRE(result != NULL);
    REQUIRE(strcmp(result, fixture.get(".result.json").c_str()) == 0);

    free(result);
}

TEST_CASE("c-interface parse blueprint with sourceMap","[c-interface]")
{
    ITFixtureFiles fixture = ITFixtureFiles("test/fixtures/annotations-with-warning");

    std::string source = fixture.get(".apib");

    char *result = NULL;

    int ret = drafter_c_parse(source.c_str(), SC_EXPORT_SORUCEMAP_OPTION, &result);

    REQUIRE(ret == 0);

    REQUIRE(result != NULL);
    REQUIRE(strcmp(result, fixture.get(".result-with-sourcemap.json").c_str()) == 0);

    free(result);
}

TEST_CASE("c-interface check result, without memory alloc","[c-interface]")
{
    ITFixtureFiles fixture = ITFixtureFiles("test/fixtures/annotations-with-warning");

    std::string source = fixture.get(".apib");

    char *ast = NULL, *report = NULL;

    int ret = drafter_c_parse(source.c_str(), 0, NULL);

    REQUIRE(ret == 0);
}

<commit_msg>Remove warning on gcc 4.6<commit_after>#include "test-drafter.h"

#include "cdrafter.h"

#include <string.h>

TEST_CASE("c-interface parse blueprint ","[c-interface]")
{
    ITFixtureFiles fixture = ITFixtureFiles("test/fixtures/annotations-with-warning");

    std::string source = fixture.get(".apib");

    char *result = NULL;

    int ret = drafter_c_parse(source.c_str(), 0, &result);

    REQUIRE(ret == 0);

    REQUIRE(result);
    REQUIRE(strcmp(result, fixture.get(".result.json").c_str()) == 0);

    free(result);
}

TEST_CASE("c-interface parse blueprint with sourceMap","[c-interface]")
{
    ITFixtureFiles fixture = ITFixtureFiles("test/fixtures/annotations-with-warning");

    std::string source = fixture.get(".apib");

    char *result = NULL;

    int ret = drafter_c_parse(source.c_str(), SC_EXPORT_SORUCEMAP_OPTION, &result);

    REQUIRE(ret == 0);

    REQUIRE(result);
    REQUIRE(strcmp(result, fixture.get(".result-with-sourcemap.json").c_str()) == 0);

    free(result);
}

TEST_CASE("c-interface check result, without memory alloc","[c-interface]")
{
    ITFixtureFiles fixture = ITFixtureFiles("test/fixtures/annotations-with-warning");

    std::string source = fixture.get(".apib");

    char *ast = NULL, *report = NULL;

    int ret = drafter_c_parse(source.c_str(), 0, NULL);

    REQUIRE(ret == 0);
}

<|endoftext|>


<commit_before>#pragma once

class Solution {
public:
    int strStr(char* haystack, char* needle) {
        int m, n, j;
        for (m = n = 0; haystack[m] != '\0'; m += n) {
            if (haystack[m] == needle[0]) {
                for ((j = n), n = 0; haystack[m + j] != '\0' && needle[j] != '\0' && haystack[m + j] == needle[j]; ++j) {
                    if (j > n) {
                        if (haystack[m + j] == needle[n]) {
                            ++n;
                        } else {
                            n = 0;
                        }
                    }
                }

                if (needle[j] == '\0') {
                    return m;
                }

                if (n == 0) {
                    n = j;
                }

            }
        }

        return -1;
    }
};
<commit_msg>redoing kmp solution, this time with overlap table overlap function implemented<commit_after>#pragma once

#include <cstring>
#include <vector>

using std::vector;

class Solution {
public:
    int strStr(char* haystack, char* needle) {
        auto haySZ = strlen(haystack);
        auto neeSZ = strlen(needle);

        vector<int> overlap;
        buildOverlapTable(needle, neeSZ, overlap);
    }

private:
    void buildOverlapTable(char* neeedle, size_t sz, vector<int>& table) {
        table.push_back(0);
        --sz;

        for (int i = 0; i < sz; ++i) {
            char ch = neeedle[i + 1];
            int overlap = table[i];

            for (; overlap != 0 && neeedle[i + 1] != ch; overlap = table[overlap]);

            if (neeedle[i + 1] == ch) {
                table.push_back(overlap + 1);
            } else {
                table.push_back(0);
            }
        }
    }
};
<|endoftext|>


<commit_before>#pragma once

#include <array>
#include <string_view>
#include <charconv>

#include <r4/vector.hpp>

#include "config.hpp"
#include "elements/coordinate_units.hpp"

#include "fast_float/fast_float.hxx"

namespace svgdom{

class string_parser{
    std::string_view view;

    void throw_if_empty();

public:
    static bool is_space(char c);

    string_parser(std::string_view view) :
            view(view)
    {}

    void skip_whitespaces();
    void skip_whitespaces_and_comma();
    void skip_inclusive_until(char c);

    std::string_view read_word();
    std::string_view read_word_until(char c);

    // skips leading whitespaces
    template <class real_type>
    real_type read_real(){
        std::conditional_t<
                std::is_same<real_type, float>::value || std::is_same<real_type, double>::value,
                real_type,
                double // TODO: use long double when std::from_chars for floats is widely supported by C++17 compilers
            > ret;

        // TODO: use std::from_chars for floats when it is widely supported by C++17 compilers
        auto res = fast_float::from_chars(this->view.data(), this->view.data() + this->view.size(), ret);

        if(res.ec == std::errc::invalid_argument){
            throw std::invalid_argument("string_parser::read_real(): could not parse real number");
        }

        ASSERT(this->view.data() != res.ptr)

        this->view = this->view.substr(res.ptr - this->view.data());

        return real_type(ret);
    }

    // skips leading whitespaces
    template <class integer_type>
    integer_type read_integer(){
        integer_type ret = 0;

        auto res = std::from_chars(this->view.data(), this->view.data() + this->view.size(), ret);

        if(res.ec == std::errc::invalid_argument){
            throw std::invalid_argument("string_parser::read_integer(): could not parse integer number");
        }

        ASSERT(this->view.data() != res.ptr)

        this->view = this->view.substr(res.ptr - this->view.data());

        return ret;
    }

    char read_char();

    char peek_char();

    std::string_view read_chars(size_t n);
    std::string_view read_chars_until(char c);

    bool empty()const noexcept{
        return this->view.empty();
    }
};

std::string_view trim_tail(std::string_view s);

std::string iri_to_local_id(std::string_view iri);

coordinate_units parse_coordinate_units(std::string_view s);

std::string coordinate_units_to_string(coordinate_units u);

r4::vector2<real> parse_number_and_optional_number(std::string_view s, r4::vector2<real> defaults);

std::string number_and_optional_number_to_string(std::array<real, 2> non, real optional_number_default);

}
<commit_msg>add explicit skipping of leading whitespaces<commit_after>#pragma once

#include <array>
#include <string_view>
#include <charconv>

#include <r4/vector.hpp>

#include "config.hpp"
#include "elements/coordinate_units.hpp"

#include "fast_float/fast_float.hxx"

namespace svgdom{

class string_parser{
    std::string_view view;

    void throw_if_empty();

public:
    static bool is_space(char c);

    string_parser(std::string_view view) :
            view(view)
    {}

    void skip_whitespaces();
    void skip_whitespaces_and_comma();
    void skip_inclusive_until(char c);

    std::string_view read_word();
    std::string_view read_word_until(char c);

    // skips leading whitespaces
    template <class real_type>
    real_type read_real(){
        this->skip_whitespaces();

        std::conditional_t<
                std::is_same<real_type, float>::value || std::is_same<real_type, double>::value,
                real_type,
                double // TODO: use long double when std::from_chars for floats is widely supported by C++17 compilers
            > ret;

        // TODO: use std::from_chars for floats when it is widely supported by C++17 compilers
        auto res = fast_float::from_chars(this->view.data(), this->view.data() + this->view.size(), ret);

        if(res.ec == std::errc::invalid_argument){
            throw std::invalid_argument("string_parser::read_real(): could not parse real number");
        }

        ASSERT(this->view.data() != res.ptr)

        this->view = this->view.substr(res.ptr - this->view.data());

        return real_type(ret);
    }

    // skips leading whitespaces
    template <class integer_type>
    integer_type read_integer(){
        this->skip_whitespaces();

        integer_type ret = 0;

        auto res = std::from_chars(this->view.data(), this->view.data() + this->view.size(), ret);

        if(res.ec == std::errc::invalid_argument){
            throw std::invalid_argument("string_parser::read_integer(): could not parse integer number");
        }

        ASSERT(this->view.data() != res.ptr)

        this->view = this->view.substr(res.ptr - this->view.data());

        return ret;
    }

    char read_char();

    char peek_char();

    std::string_view read_chars(size_t n);
    std::string_view read_chars_until(char c);

    bool empty()const noexcept{
        return this->view.empty();
    }
};

std::string_view trim_tail(std::string_view s);

std::string iri_to_local_id(std::string_view iri);

coordinate_units parse_coordinate_units(std::string_view s);

std::string coordinate_units_to_string(coordinate_units u);

r4::vector2<real> parse_number_and_optional_number(std::string_view s, r4::vector2<real> defaults);

std::string number_and_optional_number_to_string(std::array<real, 2> non, real optional_number_default);

}
<|endoftext|>


<commit_before>/*  cbr
 *  ObjectHost.hpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  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 cbr 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 _CBR_OBJECT_HOST_HPP_
#define _CBR_OBJECT_HOST_HPP_

#include "ObjectHostContext.hpp"
#include "QueueRouterElement.hpp"
#include "PollingService.hpp"
#include "TimeProfiler.hpp"
#include "Message.hpp"
#include "SSTImpl.hpp"

#include <sirikata/util/SerializationCheck.hpp>

namespace CBR {

class Object;
class ServerIDMap;

class ObjectHost : public Service {
public:

    bool randomPing(const Time& t);
    typedef std::tr1::function<void(ServerID)> SessionCallback;
    // Callback indicating that a connection to the server was made and it is available for sessions
    typedef SessionCallback ConnectedCallback;
    // Callback indicating that a connection is being migrated to a new server.  This occurs as soon
    // as the object host starts the transition and no additional notification is given since, for all
    // intents and purposes this is the point at which the transition happens
    typedef SessionCallback MigratedCallback;
    typedef std::tr1::function<void()> StreamCreatedCallback;

    // FIXME the ServerID is used to track unique sources, we need to do this separately for object hosts
    ObjectHost(ObjectHostContext* ctx, Trace* trace, ServerIDMap* sidmap);

    ~ObjectHost();

    const ObjectHostContext* context() const;

    // NOTE: The public interface is only safe to access from the main strand.

    /** Connect the object to the space with the given starting parameters. */
    void connect(Object* obj, const SolidAngle& init_sa, ConnectedCallback connected_cb,
		 MigratedCallback migrated_cb, StreamCreatedCallback stream_created_cb);
    void connect(Object* obj, ConnectedCallback connected_cb, MigratedCallback migrated_cb,
		 StreamCreatedCallback stream_created_cb);
    /** Disconnect the object from the space. */
    void disconnect(Object* obj);

    bool send(const Object* src, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload);

    bool send(const uint16 src_port, const UUID& src, const uint16 dest_port, const UUID& dest,const std::string& payload);

    /* Ping Utility Methods. */
    bool ping(const Time& t, const Object *src, const UUID&dest, double distance=-0);

    boost::shared_ptr<Stream<UUID> > getSpaceStream(const UUID& objectID);

private:
    // Implementation Note: mIOStrand is a bit misleading. All the "real" IO is isolated to that strand --
    // reads and writes to the actual sockets are handled in mIOStrand. But that is all that is handled
    // there. Since creating/connecting/disconnecting/destroying SpaceNodeConnections is cheap and relatively
    // rare, we keep these in the main strand, allowing us to leave the SpaceNodeConnection map without a lock.
    // Note that the SpaceNodeConnections may themselves be accessed from multiple threads.
    //
    // The data exchange between the strands happens in two places. When sending, it occurs in the connections
    // queue, which is thread safe.  When receiving, it occurs by posting a handler for the parsed message
    // to the main thread.
    //
    // Note that this means the majority of this class is executed in the main strand. Only reading and writing
    // are separated out, which allows us to ensure the network will be serviced as fast as possible, but
    // doesn't help if our limiting factor is the speed at which this input/output can be handled.
    //
    // Note also that this class does *not* handle multithreaded input -- currently all access of public
    // methods should be performed from the main strand.

    struct SpaceNodeConnection;
    struct ConnectingInfo;

    // Service Implementation
    virtual void start();
    virtual void stop();

    // Private version of send that doesn't verify src UUID, allows us to masquerade for session purposes
    // The allow_connecting parameter allows you to use a connection over which the object is still opening
    // a connection.  This is safe since it can only be used by this class (since this is private), so it will
    // only be used to deal with session management.
    // If dest_server is NullServerID, then getConnectedServer is used to determine where to send the packet.
    // This is used to possibly exchange data between the main and IO strands, so it acquires locks.
    bool send(const UUID& src, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload, ServerID dest_server = NullServerID);

    // Periodically called to generate random ping messages
    void generatePings();

    // Starting point for handling of all messages from the server -- either handled as a special case, such as
    // for session management, or dispatched to the object
    void handleServerMessage(SpaceNodeConnection* conn);

    // Handles session messages received from the server -- connection replies, migration requests, etc.
    void handleSessionMessage(CBR::Protocol::Object::ObjectMessage* msg);
    void retryOpenConnection(const UUID&uuid,ServerID sid);

    // Utility method which keeps trying to resend a message
    void sendRetryingMessage(const UUID& src, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload, ServerID dest_server, IOStrand* strand, const Duration& rate);

    /** SpaceNodeConnection initiation. */

    // Get an existing space connection or initiate a new one at random
    // which can be used for bootstrapping connections
    typedef std::tr1::function<void(SpaceNodeConnection*)> GotSpaceConnectionCallback;
    void getAnySpaceConnection(GotSpaceConnectionCallback cb);
    // Get the connection to the specified space node
    void getSpaceConnection(ServerID sid, GotSpaceConnectionCallback cb);

    // Set up a space connection to the given server
    void setupSpaceConnection(ServerID server, GotSpaceConnectionCallback cb);

    // Handle a connection event, i.e. the socket either successfully connected or failed
    void handleSpaceConnection(const Sirikata::Network::Stream::ConnectionStatus status,
                               const std::string&reason,
                               ServerID sid);

    /** Object session initiation. */

    // Private utility method that the public versions all use to initialize connection struct
  void openConnection(Object* obj, const TimedMotionVector3f& init_loc, const BoundingSphere3f& init_bounds, bool regquery, const SolidAngle& init_sa, ConnectedCallback connect_cb, MigratedCallback migrate_cb, StreamCreatedCallback);

    // Final callback in session initiation -- we have all the info and now just have to return it to the object
    void openConnectionStartSession(const UUID& uuid, SpaceNodeConnection* conn);

    /** Object session migration. */

    // Start the migration process for the object to the given server.
    void migrate(const UUID& obj_id, ServerID sid);

    // Callback that indicates we have a connection to the new server and can now start the migration to it.
    void openConnectionStartMigration(const UUID& uuid, ServerID sid, SpaceNodeConnection* conn);

    OptionSet* mStreamOptions;

    // THREAD SAFE
    // These may be accessed safely by any thread

    ObjectHostContext* mContext;

    IOService* mIOService;
    IOStrand* mIOStrand;
    IOWork* mIOWork;
    Thread* mIOThread;

    ServerIDMap* mServerIDMap;
    Duration mSimDuration;
    Poller* mPingPoller;

    TimeProfiler::Stage* mHandleMessageProfiler;

    Sirikata::SerializationCheck mSerialization;

    // Main strand only

    // Connections to servers
    struct SpaceNodeConnection {
        typedef std::tr1::function<void(SpaceNodeConnection*)> ReceiveCallback;

        SpaceNodeConnection(ObjectHostContext* ctx, IOStrand* ioStrand, OptionSet *streamOptions, ServerID sid, ReceiveCallback rcb);
        ~SpaceNodeConnection();

        // Thread Safe
        ObjectHostContext* mContext;
        ObjectHost* parent;
        ServerID server;
        Sirikata::Network::Stream* socket;

        // Push a packet to be sent out
        bool push(ObjectMessage* msg);

        // Pull a packet from the receive queue
        ObjectMessage* pull();

        void shutdown();

        // Callback for when the connection receives data
        Sirikata::Network::Stream::ReceivedResponse handleRead(Sirikata::Network::Chunk& chunk);

        // Main Strand
        std::vector<GotSpaceConnectionCallback> connectCallbacks;
        bool connecting;

        // IO Strand
        QueueRouterElement<ObjectMessage> receive_queue;

        ReceiveCallback mReceiveCB;
    };
    // Only main strand accesses and manipulates the map, although other strand
    // may access the SpaceNodeConnection*'s.
    typedef std::map<ServerID, SpaceNodeConnection*> ServerConnectionMap;
    ServerConnectionMap mConnections;

    // Info associated with opening connections
    struct ConnectingInfo {
        TimedMotionVector3f loc;
        BoundingSphere3f bounds;
        bool regQuery;
        SolidAngle queryAngle;
    };

    // Objects connections, maintains object connections and mapping
    class ObjectConnections {
    public:
        ObjectConnections();

        // Add the object, completely disconnected, to the index
        void add(Object* obj, ConnectingInfo ci, ConnectedCallback connect_cb, MigratedCallback migrate_cb,
	       StreamCreatedCallback stream_created_cb);

        // Mark the object as connecting to the given server
        ConnectingInfo& connectingTo(const UUID& obj, ServerID connecting_to);

        // Start a migration to a new server, return the MigratedCallback for the object
        void startMigration(const UUID& objid, ServerID migrating_to);

        WARN_UNUSED
        ConnectedCallback& getConnectCallback(const UUID& objid);

        // Marks as connected and returns the server connected to
        ServerID handleConnectSuccess(const UUID& obj);

        void handleConnectError(const UUID& objid);

        void handleConnectStream(const UUID& objid);

        void remove(const UUID& obj);

        // Get object for the object ID
        Object* object(const UUID& obj_id);
        // Lookup the server the object is connected to.  With allow_connecting, allows using
        // the server currently being connected to, not just one where a session has been
        // established
        ServerID getConnectedServer(const UUID& obj_id, bool allow_connecting = false);

        // Select random objects uniformly, uniformly from server, using round robin
        Object* randomObject(bool null_if_disconnected = false);
        Object* randomObject(ServerID whichServer, bool null_if_disconnected = false);
        Object* roundRobinObject(ServerID whichServer, bool null_if_disconnected = false);
        ServerID numServerIDs()const;
    private:
        struct ObjectInfo {
            ObjectInfo(Object* obj);
            ObjectInfo(); // Don't use, necessary for std::map

            Object* object;

            ConnectingInfo connectingInfo;

            // Server currently being connected to
            ServerID connectingTo;
            // Server currently connected to
            ServerID connectedTo;
            // Server we're trying to migrate to
            ServerID migratingTo;

            ConnectedCallback connectedCB;
            MigratedCallback migratedCB;
  	    StreamCreatedCallback streamCreatedCB;
        };
        typedef std::tr1::unordered_map<ServerID, std::vector<UUID> > ObjectServerMap;
        ObjectServerMap mObjectServerMap;
        typedef std::tr1::unordered_map<UUID, ObjectInfo, UUID::Hasher> ObjectInfoMap;
        ObjectInfoMap mObjectInfo;

        UUID mLastRRObject;
        size_t mLastRRIndex;
    };
    ObjectConnections mObjectConnections;

    bool mShuttingDown;
    uint64 mPingId;
    typedef std::tr1::function<void(const CBR::Protocol::Object::ObjectMessage&)> ObjectMessageCallback;
    std::tr1::unordered_map<uint64, ObjectMessageCallback > mRegisteredServices;

    void spaceConnectCallback(int err, boost::shared_ptr< Stream<UUID> > s, UUID obj);
    std::map<UUID, boost::shared_ptr<Stream<UUID> > > mObjectToSpaceStreams;

public:
    ObjectConnections*getObjectConnections(){return &mObjectConnections;}
    ///Register to intercept all incoming messages on a given port
    bool registerService(uint64 port, const ObjectMessageCallback&cb);
    ///Unregister to intercept all incoming messages on a given port
    bool unregisterService(uint64 port);
}; // class ObjectHost

} // namespace CBR

#endif //_CBR_OBJECT_HOST_HPP_
<commit_msg>Remove unused mPingPoller from ObjectHost.<commit_after>/*  cbr
 *  ObjectHost.hpp
 *
 *  Copyright (c) 2009, Ewen Cheslack-Postava
 *  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 cbr 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 _CBR_OBJECT_HOST_HPP_
#define _CBR_OBJECT_HOST_HPP_

#include "ObjectHostContext.hpp"
#include "QueueRouterElement.hpp"
#include "PollingService.hpp"
#include "TimeProfiler.hpp"
#include "Message.hpp"
#include "SSTImpl.hpp"

#include <sirikata/util/SerializationCheck.hpp>

namespace CBR {

class Object;
class ServerIDMap;

class ObjectHost : public Service {
public:

    bool randomPing(const Time& t);
    typedef std::tr1::function<void(ServerID)> SessionCallback;
    // Callback indicating that a connection to the server was made and it is available for sessions
    typedef SessionCallback ConnectedCallback;
    // Callback indicating that a connection is being migrated to a new server.  This occurs as soon
    // as the object host starts the transition and no additional notification is given since, for all
    // intents and purposes this is the point at which the transition happens
    typedef SessionCallback MigratedCallback;
    typedef std::tr1::function<void()> StreamCreatedCallback;

    // FIXME the ServerID is used to track unique sources, we need to do this separately for object hosts
    ObjectHost(ObjectHostContext* ctx, Trace* trace, ServerIDMap* sidmap);

    ~ObjectHost();

    const ObjectHostContext* context() const;

    // NOTE: The public interface is only safe to access from the main strand.

    /** Connect the object to the space with the given starting parameters. */
    void connect(Object* obj, const SolidAngle& init_sa, ConnectedCallback connected_cb,
		 MigratedCallback migrated_cb, StreamCreatedCallback stream_created_cb);
    void connect(Object* obj, ConnectedCallback connected_cb, MigratedCallback migrated_cb,
		 StreamCreatedCallback stream_created_cb);
    /** Disconnect the object from the space. */
    void disconnect(Object* obj);

    bool send(const Object* src, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload);

    bool send(const uint16 src_port, const UUID& src, const uint16 dest_port, const UUID& dest,const std::string& payload);

    /* Ping Utility Methods. */
    bool ping(const Time& t, const Object *src, const UUID&dest, double distance=-0);

    boost::shared_ptr<Stream<UUID> > getSpaceStream(const UUID& objectID);

private:
    // Implementation Note: mIOStrand is a bit misleading. All the "real" IO is isolated to that strand --
    // reads and writes to the actual sockets are handled in mIOStrand. But that is all that is handled
    // there. Since creating/connecting/disconnecting/destroying SpaceNodeConnections is cheap and relatively
    // rare, we keep these in the main strand, allowing us to leave the SpaceNodeConnection map without a lock.
    // Note that the SpaceNodeConnections may themselves be accessed from multiple threads.
    //
    // The data exchange between the strands happens in two places. When sending, it occurs in the connections
    // queue, which is thread safe.  When receiving, it occurs by posting a handler for the parsed message
    // to the main thread.
    //
    // Note that this means the majority of this class is executed in the main strand. Only reading and writing
    // are separated out, which allows us to ensure the network will be serviced as fast as possible, but
    // doesn't help if our limiting factor is the speed at which this input/output can be handled.
    //
    // Note also that this class does *not* handle multithreaded input -- currently all access of public
    // methods should be performed from the main strand.

    struct SpaceNodeConnection;
    struct ConnectingInfo;

    // Service Implementation
    virtual void start();
    virtual void stop();

    // Private version of send that doesn't verify src UUID, allows us to masquerade for session purposes
    // The allow_connecting parameter allows you to use a connection over which the object is still opening
    // a connection.  This is safe since it can only be used by this class (since this is private), so it will
    // only be used to deal with session management.
    // If dest_server is NullServerID, then getConnectedServer is used to determine where to send the packet.
    // This is used to possibly exchange data between the main and IO strands, so it acquires locks.
    bool send(const UUID& src, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload, ServerID dest_server = NullServerID);

    // Periodically called to generate random ping messages
    void generatePings();

    // Starting point for handling of all messages from the server -- either handled as a special case, such as
    // for session management, or dispatched to the object
    void handleServerMessage(SpaceNodeConnection* conn);

    // Handles session messages received from the server -- connection replies, migration requests, etc.
    void handleSessionMessage(CBR::Protocol::Object::ObjectMessage* msg);
    void retryOpenConnection(const UUID&uuid,ServerID sid);

    // Utility method which keeps trying to resend a message
    void sendRetryingMessage(const UUID& src, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload, ServerID dest_server, IOStrand* strand, const Duration& rate);

    /** SpaceNodeConnection initiation. */

    // Get an existing space connection or initiate a new one at random
    // which can be used for bootstrapping connections
    typedef std::tr1::function<void(SpaceNodeConnection*)> GotSpaceConnectionCallback;
    void getAnySpaceConnection(GotSpaceConnectionCallback cb);
    // Get the connection to the specified space node
    void getSpaceConnection(ServerID sid, GotSpaceConnectionCallback cb);

    // Set up a space connection to the given server
    void setupSpaceConnection(ServerID server, GotSpaceConnectionCallback cb);

    // Handle a connection event, i.e. the socket either successfully connected or failed
    void handleSpaceConnection(const Sirikata::Network::Stream::ConnectionStatus status,
                               const std::string&reason,
                               ServerID sid);

    /** Object session initiation. */

    // Private utility method that the public versions all use to initialize connection struct
  void openConnection(Object* obj, const TimedMotionVector3f& init_loc, const BoundingSphere3f& init_bounds, bool regquery, const SolidAngle& init_sa, ConnectedCallback connect_cb, MigratedCallback migrate_cb, StreamCreatedCallback);

    // Final callback in session initiation -- we have all the info and now just have to return it to the object
    void openConnectionStartSession(const UUID& uuid, SpaceNodeConnection* conn);

    /** Object session migration. */

    // Start the migration process for the object to the given server.
    void migrate(const UUID& obj_id, ServerID sid);

    // Callback that indicates we have a connection to the new server and can now start the migration to it.
    void openConnectionStartMigration(const UUID& uuid, ServerID sid, SpaceNodeConnection* conn);

    OptionSet* mStreamOptions;

    // THREAD SAFE
    // These may be accessed safely by any thread

    ObjectHostContext* mContext;

    IOService* mIOService;
    IOStrand* mIOStrand;
    IOWork* mIOWork;
    Thread* mIOThread;

    ServerIDMap* mServerIDMap;
    Duration mSimDuration;

    TimeProfiler::Stage* mHandleMessageProfiler;

    Sirikata::SerializationCheck mSerialization;

    // Main strand only

    // Connections to servers
    struct SpaceNodeConnection {
        typedef std::tr1::function<void(SpaceNodeConnection*)> ReceiveCallback;

        SpaceNodeConnection(ObjectHostContext* ctx, IOStrand* ioStrand, OptionSet *streamOptions, ServerID sid, ReceiveCallback rcb);
        ~SpaceNodeConnection();

        // Thread Safe
        ObjectHostContext* mContext;
        ObjectHost* parent;
        ServerID server;
        Sirikata::Network::Stream* socket;

        // Push a packet to be sent out
        bool push(ObjectMessage* msg);

        // Pull a packet from the receive queue
        ObjectMessage* pull();

        void shutdown();

        // Callback for when the connection receives data
        Sirikata::Network::Stream::ReceivedResponse handleRead(Sirikata::Network::Chunk& chunk);

        // Main Strand
        std::vector<GotSpaceConnectionCallback> connectCallbacks;
        bool connecting;

        // IO Strand
        QueueRouterElement<ObjectMessage> receive_queue;

        ReceiveCallback mReceiveCB;
    };
    // Only main strand accesses and manipulates the map, although other strand
    // may access the SpaceNodeConnection*'s.
    typedef std::map<ServerID, SpaceNodeConnection*> ServerConnectionMap;
    ServerConnectionMap mConnections;

    // Info associated with opening connections
    struct ConnectingInfo {
        TimedMotionVector3f loc;
        BoundingSphere3f bounds;
        bool regQuery;
        SolidAngle queryAngle;
    };

    // Objects connections, maintains object connections and mapping
    class ObjectConnections {
    public:
        ObjectConnections();

        // Add the object, completely disconnected, to the index
        void add(Object* obj, ConnectingInfo ci, ConnectedCallback connect_cb, MigratedCallback migrate_cb,
	       StreamCreatedCallback stream_created_cb);

        // Mark the object as connecting to the given server
        ConnectingInfo& connectingTo(const UUID& obj, ServerID connecting_to);

        // Start a migration to a new server, return the MigratedCallback for the object
        void startMigration(const UUID& objid, ServerID migrating_to);

        WARN_UNUSED
        ConnectedCallback& getConnectCallback(const UUID& objid);

        // Marks as connected and returns the server connected to
        ServerID handleConnectSuccess(const UUID& obj);

        void handleConnectError(const UUID& objid);

        void handleConnectStream(const UUID& objid);

        void remove(const UUID& obj);

        // Get object for the object ID
        Object* object(const UUID& obj_id);
        // Lookup the server the object is connected to.  With allow_connecting, allows using
        // the server currently being connected to, not just one where a session has been
        // established
        ServerID getConnectedServer(const UUID& obj_id, bool allow_connecting = false);

        // Select random objects uniformly, uniformly from server, using round robin
        Object* randomObject(bool null_if_disconnected = false);
        Object* randomObject(ServerID whichServer, bool null_if_disconnected = false);
        Object* roundRobinObject(ServerID whichServer, bool null_if_disconnected = false);
        ServerID numServerIDs()const;
    private:
        struct ObjectInfo {
            ObjectInfo(Object* obj);
            ObjectInfo(); // Don't use, necessary for std::map

            Object* object;

            ConnectingInfo connectingInfo;

            // Server currently being connected to
            ServerID connectingTo;
            // Server currently connected to
            ServerID connectedTo;
            // Server we're trying to migrate to
            ServerID migratingTo;

            ConnectedCallback connectedCB;
            MigratedCallback migratedCB;
  	    StreamCreatedCallback streamCreatedCB;
        };
        typedef std::tr1::unordered_map<ServerID, std::vector<UUID> > ObjectServerMap;
        ObjectServerMap mObjectServerMap;
        typedef std::tr1::unordered_map<UUID, ObjectInfo, UUID::Hasher> ObjectInfoMap;
        ObjectInfoMap mObjectInfo;

        UUID mLastRRObject;
        size_t mLastRRIndex;
    };
    ObjectConnections mObjectConnections;

    bool mShuttingDown;
    uint64 mPingId;
    typedef std::tr1::function<void(const CBR::Protocol::Object::ObjectMessage&)> ObjectMessageCallback;
    std::tr1::unordered_map<uint64, ObjectMessageCallback > mRegisteredServices;

    void spaceConnectCallback(int err, boost::shared_ptr< Stream<UUID> > s, UUID obj);
    std::map<UUID, boost::shared_ptr<Stream<UUID> > > mObjectToSpaceStreams;

public:
    ObjectConnections*getObjectConnections(){return &mObjectConnections;}
    ///Register to intercept all incoming messages on a given port
    bool registerService(uint64 port, const ObjectMessageCallback&cb);
    ///Unregister to intercept all incoming messages on a given port
    bool unregisterService(uint64 port);
}; // class ObjectHost

} // namespace CBR

#endif //_CBR_OBJECT_HOST_HPP_
<|endoftext|>


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

#include "chrome/browser/extensions/extension_creator.h"

#include <vector>
#include <string>

#include "base/crypto/rsa_private_key.h"
#include "base/crypto/signature_creator.h"
#include "base/file_util.h"
#include "base/scoped_handle.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/sandboxed_extension_unpacker.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/zip.h"
#include "net/base/base64.h"

namespace {
  const int kRSAKeySize = 1024;
};

bool ExtensionCreator::InitializeInput(
    const FilePath& extension_dir,
    const FilePath& private_key_path,
    const FilePath& private_key_output_path) {
  // Validate input |extension_dir|.
  if (extension_dir.value().empty() ||
      !file_util::DirectoryExists(extension_dir)) {
    error_message_ = "Input directory must exist.";
    return false;
  }

  // Validate input |private_key| (if provided).
  if (!private_key_path.value().empty() &&
      !file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must be a valid path.";
    return false;
  }

  // If an |output_private_key| path is given, make sure it doesn't over-write
  // an existing private key.
  if (private_key_path.value().empty() &&
      !private_key_output_path.value().empty() &&
      file_util::PathExists(private_key_output_path)) {
      error_message_ = "A private key for specified extension already exists. "
                       "Reuse that key or delete it first.";
      return false;
  }

  return true;
}

base::RSAPrivateKey* ExtensionCreator::ReadInputKey(const FilePath&
    private_key_path) {
  if (!file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must exist.";
    return false;
  }

  std::string private_key_contents;
  if (!file_util::ReadFileToString(private_key_path,
      &private_key_contents)) {
    error_message_ = "Failed to read private key.";
    return false;
  }

  std::string private_key_bytes;
  if (!Extension::ParsePEMKeyBytes(private_key_contents,
       &private_key_bytes)) {
    error_message_ = "Invalid private key.";
    return false;
  }

  return base::RSAPrivateKey::CreateFromPrivateKeyInfo(
      std::vector<uint8>(private_key_bytes.begin(), private_key_bytes.end()));
}

base::RSAPrivateKey* ExtensionCreator::GenerateKey(const FilePath&
    output_private_key_path) {
  scoped_ptr<base::RSAPrivateKey> key_pair(
      base::RSAPrivateKey::Create(kRSAKeySize));
  if (!key_pair.get()) {
    error_message_ = "Yikes! Failed to generate random RSA private key.";
    return NULL;
  }

  std::vector<uint8> private_key_vector;
  if (!key_pair->ExportPrivateKey(&private_key_vector)) {
    error_message_ = "Failed to export private key.";
    return NULL;
  }
  std::string private_key_bytes(
      reinterpret_cast<char*>(&private_key_vector.front()),
      private_key_vector.size());

  std::string private_key;
  if (!Extension::ProducePEM(private_key_bytes, &private_key)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }
  std::string pem_output;
  if (!Extension::FormatPEMForFileOutput(private_key, &pem_output,
       false)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }

  if (!output_private_key_path.empty()) {
    if (-1 == file_util::WriteFile(output_private_key_path,
        pem_output.c_str(), pem_output.size())) {
      error_message_ = "Failed to write private key.";
      return NULL;
    }
  }

  return key_pair.release();
}

bool ExtensionCreator::CreateZip(const FilePath& extension_dir,
                                 FilePath* zip_path) {
  file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("chrome_"), zip_path);
  *zip_path = zip_path->Append(FILE_PATH_LITERAL("extension.zip"));

  if (!Zip(extension_dir, *zip_path)) {
    error_message_ = "Failed to create temporary zip file during packaging.";
    return false;
  }

  return true;
}

bool ExtensionCreator::SignZip(const FilePath& zip_path,
                               base::RSAPrivateKey* private_key,
                               std::vector<uint8>* signature) {
  scoped_ptr<base::SignatureCreator> signature_creator(
      base::SignatureCreator::Create(private_key));
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  uint8 buffer[1 << 16];
  int bytes_read = -1;
  while ((bytes_read = fread(buffer, 1, sizeof(buffer),
       zip_handle.get())) > 0) {
    if (!signature_creator->Update(buffer, bytes_read)) {
      error_message_ = "Error while signing extension.";
      return false;
    }
  }
  zip_handle.Close();

  signature_creator->Final(signature);
  return true;
}

bool ExtensionCreator::WriteCRX(const FilePath& zip_path,
                                base::RSAPrivateKey* private_key,
                                const std::vector<uint8>& signature,
                                const FilePath& crx_path) {
  if (file_util::PathExists(crx_path))
    file_util::Delete(crx_path, false);
  ScopedStdioHandle crx_handle(file_util::OpenFile(crx_path, "wb"));

  std::vector<uint8> public_key;
  if (!private_key->ExportPublicKey(&public_key)) {
    error_message_ = "Failed to export public key.";
    return false;
  }

  SandboxedExtensionUnpacker::ExtensionHeader header;
  memcpy(&header.magic, SandboxedExtensionUnpacker::kExtensionHeaderMagic,
         SandboxedExtensionUnpacker::kExtensionHeaderMagicSize);
  header.version = SandboxedExtensionUnpacker::kCurrentVersion;
  header.key_size = public_key.size();
  header.signature_size = signature.size();

  fwrite(&header, sizeof(SandboxedExtensionUnpacker::ExtensionHeader), 1,
      crx_handle.get());
  fwrite(&public_key.front(), sizeof(uint8), public_key.size(),
      crx_handle.get());
  fwrite(&signature.front(), sizeof(uint8), signature.size(),
      crx_handle.get());

  uint8 buffer[1 << 16];
  int bytes_read = -1;
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  while ((bytes_read = fread(buffer, 1, sizeof(buffer),
      zip_handle.get())) > 0) {
    fwrite(buffer, sizeof(char), bytes_read, crx_handle.get());
  }

  return true;
}

bool ExtensionCreator::Run(const FilePath& extension_dir,
                           const FilePath& crx_path,
                           const FilePath& private_key_path,
                           const FilePath& output_private_key_path) {
  // Check input diretory and read manifest.
  if (!InitializeInput(extension_dir, private_key_path,
                       output_private_key_path)) {
    return false;
  }

  // Initialize Key Pair
  scoped_ptr<base::RSAPrivateKey> key_pair;
  if (!private_key_path.value().empty())
    key_pair.reset(ReadInputKey(private_key_path));
  else
    key_pair.reset(GenerateKey(output_private_key_path));
  if (!key_pair.get())
    return false;

  // Zip up the extension.
  FilePath zip_path;
  std::vector<uint8> signature;
  bool result = false;
  if (CreateZip(extension_dir, &zip_path) &&
      SignZip(zip_path, key_pair.get(), &signature) &&
      WriteCRX(zip_path, key_pair.get(), signature, crx_path)) {
    result = true;
  }

  file_util::Delete(zip_path, false);
  return result;
}
<commit_msg>Use heap memory intead of stack memory to avoid having to grow the stack.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_creator.h"

#include <vector>
#include <string>

#include "base/crypto/rsa_private_key.h"
#include "base/crypto/signature_creator.h"
#include "base/file_util.h"
#include "base/scoped_handle.h"
#include "base/string_util.h"
#include "chrome/browser/extensions/sandboxed_extension_unpacker.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/zip.h"
#include "net/base/base64.h"

namespace {
  const int kRSAKeySize = 1024;
};

bool ExtensionCreator::InitializeInput(
    const FilePath& extension_dir,
    const FilePath& private_key_path,
    const FilePath& private_key_output_path) {
  // Validate input |extension_dir|.
  if (extension_dir.value().empty() ||
      !file_util::DirectoryExists(extension_dir)) {
    error_message_ = "Input directory must exist.";
    return false;
  }

  // Validate input |private_key| (if provided).
  if (!private_key_path.value().empty() &&
      !file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must be a valid path.";
    return false;
  }

  // If an |output_private_key| path is given, make sure it doesn't over-write
  // an existing private key.
  if (private_key_path.value().empty() &&
      !private_key_output_path.value().empty() &&
      file_util::PathExists(private_key_output_path)) {
      error_message_ = "A private key for specified extension already exists. "
                       "Reuse that key or delete it first.";
      return false;
  }

  return true;
}

base::RSAPrivateKey* ExtensionCreator::ReadInputKey(const FilePath&
    private_key_path) {
  if (!file_util::PathExists(private_key_path)) {
    error_message_ = "Input value for private key must exist.";
    return false;
  }

  std::string private_key_contents;
  if (!file_util::ReadFileToString(private_key_path,
      &private_key_contents)) {
    error_message_ = "Failed to read private key.";
    return false;
  }

  std::string private_key_bytes;
  if (!Extension::ParsePEMKeyBytes(private_key_contents,
       &private_key_bytes)) {
    error_message_ = "Invalid private key.";
    return false;
  }

  return base::RSAPrivateKey::CreateFromPrivateKeyInfo(
      std::vector<uint8>(private_key_bytes.begin(), private_key_bytes.end()));
}

base::RSAPrivateKey* ExtensionCreator::GenerateKey(const FilePath&
    output_private_key_path) {
  scoped_ptr<base::RSAPrivateKey> key_pair(
      base::RSAPrivateKey::Create(kRSAKeySize));
  if (!key_pair.get()) {
    error_message_ = "Yikes! Failed to generate random RSA private key.";
    return NULL;
  }

  std::vector<uint8> private_key_vector;
  if (!key_pair->ExportPrivateKey(&private_key_vector)) {
    error_message_ = "Failed to export private key.";
    return NULL;
  }
  std::string private_key_bytes(
      reinterpret_cast<char*>(&private_key_vector.front()),
      private_key_vector.size());

  std::string private_key;
  if (!Extension::ProducePEM(private_key_bytes, &private_key)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }
  std::string pem_output;
  if (!Extension::FormatPEMForFileOutput(private_key, &pem_output,
       false)) {
    error_message_ = "Failed to output private key.";
    return NULL;
  }

  if (!output_private_key_path.empty()) {
    if (-1 == file_util::WriteFile(output_private_key_path,
        pem_output.c_str(), pem_output.size())) {
      error_message_ = "Failed to write private key.";
      return NULL;
    }
  }

  return key_pair.release();
}

bool ExtensionCreator::CreateZip(const FilePath& extension_dir,
                                 FilePath* zip_path) {
  file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("chrome_"), zip_path);
  *zip_path = zip_path->Append(FILE_PATH_LITERAL("extension.zip"));

  if (!Zip(extension_dir, *zip_path)) {
    error_message_ = "Failed to create temporary zip file during packaging.";
    return false;
  }

  return true;
}

bool ExtensionCreator::SignZip(const FilePath& zip_path,
                               base::RSAPrivateKey* private_key,
                               std::vector<uint8>* signature) {
  scoped_ptr<base::SignatureCreator> signature_creator(
      base::SignatureCreator::Create(private_key));
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  size_t buffer_size = 1 << 16;
  scoped_array<uint8> buffer(new uint8[buffer_size]);
  int bytes_read = -1;
  while ((bytes_read = fread(buffer.get(), 1, buffer_size,
       zip_handle.get())) > 0) {
    if (!signature_creator->Update(buffer.get(), bytes_read)) {
      error_message_ = "Error while signing extension.";
      return false;
    }
  }
  zip_handle.Close();

  signature_creator->Final(signature);
  return true;
}

bool ExtensionCreator::WriteCRX(const FilePath& zip_path,
                                base::RSAPrivateKey* private_key,
                                const std::vector<uint8>& signature,
                                const FilePath& crx_path) {
  if (file_util::PathExists(crx_path))
    file_util::Delete(crx_path, false);
  ScopedStdioHandle crx_handle(file_util::OpenFile(crx_path, "wb"));

  std::vector<uint8> public_key;
  if (!private_key->ExportPublicKey(&public_key)) {
    error_message_ = "Failed to export public key.";
    return false;
  }

  SandboxedExtensionUnpacker::ExtensionHeader header;
  memcpy(&header.magic, SandboxedExtensionUnpacker::kExtensionHeaderMagic,
         SandboxedExtensionUnpacker::kExtensionHeaderMagicSize);
  header.version = SandboxedExtensionUnpacker::kCurrentVersion;
  header.key_size = public_key.size();
  header.signature_size = signature.size();

  fwrite(&header, sizeof(SandboxedExtensionUnpacker::ExtensionHeader), 1,
      crx_handle.get());
  fwrite(&public_key.front(), sizeof(uint8), public_key.size(),
      crx_handle.get());
  fwrite(&signature.front(), sizeof(uint8), signature.size(),
      crx_handle.get());

  size_t buffer_size = 1 << 16;
  scoped_array<uint8> buffer(new uint8[buffer_size]);
  int bytes_read = -1;
  ScopedStdioHandle zip_handle(file_util::OpenFile(zip_path, "rb"));
  while ((bytes_read = fread(buffer.get(), 1, buffer_size,
      zip_handle.get())) > 0) {
    fwrite(buffer.get(), sizeof(char), bytes_read, crx_handle.get());
  }

  return true;
}

bool ExtensionCreator::Run(const FilePath& extension_dir,
                           const FilePath& crx_path,
                           const FilePath& private_key_path,
                           const FilePath& output_private_key_path) {
  // Check input diretory and read manifest.
  if (!InitializeInput(extension_dir, private_key_path,
                       output_private_key_path)) {
    return false;
  }

  // Initialize Key Pair
  scoped_ptr<base::RSAPrivateKey> key_pair;
  if (!private_key_path.value().empty())
    key_pair.reset(ReadInputKey(private_key_path));
  else
    key_pair.reset(GenerateKey(output_private_key_path));
  if (!key_pair.get())
    return false;

  // Zip up the extension.
  FilePath zip_path;
  std::vector<uint8> signature;
  bool result = false;
  if (CreateZip(extension_dir, &zip_path) &&
      SignZip(zip_path, key_pair.get(), &signature) &&
      WriteCRX(zip_path, key_pair.get(), signature, crx_path)) {
    result = true;
  }

  file_util::Delete(zip_path, false);
  return result;
}
<|endoftext|>


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

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/test/in_process_browser_test.h"

class ViewIDTest : public InProcessBrowserTest {
 public:
  ViewIDTest() : root_window_(NULL) {}

  void CheckViewID(ViewID id, bool should_have) {
    if (!root_window_)
      root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());

    ASSERT_TRUE(root_window_);
    EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id));
  }

 private:
  GtkWidget* root_window_;
};

IN_PROC_BROWSER_TEST_F(ViewIDTest, Basic) {
  for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
    CheckViewID(static_cast<ViewID>(i), true);
  }

  CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}

IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, false);

  browser()->OpenURL(GURL("about:blank"), GURL(""),
                     NEW_BACKGROUND_TAB, PageTransition::TYPED);

  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, true);
}
<commit_msg>Disable ViewIDTest.Basic.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/test/in_process_browser_test.h"

class ViewIDTest : public InProcessBrowserTest {
 public:
  ViewIDTest() : root_window_(NULL) {}

  void CheckViewID(ViewID id, bool should_have) {
    if (!root_window_)
      root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());

    ASSERT_TRUE(root_window_);
    EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id));
  }

 private:
  GtkWidget* root_window_;
};

// Disabled since it is failing on buildbots.
// http://code.google.com/p/chromium/issues/detail?id=21443
IN_PROC_BROWSER_TEST_F(ViewIDTest, DISABLED_Basic) {
  for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
    CheckViewID(static_cast<ViewID>(i), true);
  }

  CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}

IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, false);

  browser()->OpenURL(GURL("about:blank"), GURL(""),
                     NEW_BACKGROUND_TAB, PageTransition::TYPED);

  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, true);
}
<|endoftext|>