<commit_before>// $Id: ThreadPool.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $

/***********************************************************************
 Moses - factored phrase-based language decoder
 Copyright (C) 2009 University of Edinburgh

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

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

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ***********************************************************************/
#include <stdio.h>
#ifdef __linux
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <thread>

#include "ThreadPool.h"

using namespace std;

namespace Moses2
{

#define handle_error_en(en, msg) \
  do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

ThreadPool::ThreadPool(size_t numThreads, int cpuAffinityOffset,
                       int cpuAffinityIncr) :
  m_stopped(false), m_stopping(false), m_queueLimit(0)
{
  //size_t numCPU = sysconf(_SC_NPROCESSORS_ONLN);
  size_t numCPU = std::thread::hardware_concurrency();
  int cpuInd = cpuAffinityOffset % numCPU;

  for (size_t i = 0; i < numThreads; ++i) {
    boost::thread *thread = m_threads.create_thread(
                              boost::bind(&ThreadPool::Execute, this));

#ifdef __linux
    if (cpuAffinityOffset >= 0) {
      int s;

      boost::thread::native_handle_type handle = thread->native_handle();

      //cerr << "numCPU=" << numCPU << endl;
      cpu_set_t cpuset;
      CPU_ZERO(&cpuset);

      CPU_SET(cpuInd, &cpuset);
      cpuInd += cpuAffinityIncr;
      cpuInd = cpuInd % numCPU;

      s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
      if (s != 0) {
        handle_error_en(s, "pthread_setaffinity_np");
        //cerr << "affinity error with thread " << i << endl;
      }

      // get affinity
      CPU_ZERO(&cpuset);
      s = pthread_getaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
      cerr << "Set returned by pthread_getaffinity_np() contained:\n";
      for (int j = 0; j < CPU_SETSIZE; j++) {
        if (CPU_ISSET(j, &cpuset)) {
          cerr << "    CPU " << j << "\n";
        }
      }
    }
#endif
  }
}

void ThreadPool::Execute()
{
  do {
    boost::shared_ptr<Task> task;
    {
      // Find a job to perform
      boost::mutex::scoped_lock lock(m_mutex);
      if (m_tasks.empty() && !m_stopped) {
        m_threadNeeded.wait(lock);
      }
      if (!m_stopped && !m_tasks.empty()) {
        task = m_tasks.front();
        m_tasks.pop();
      }
    }
    //Execute job
    if (task) {
      // must read from task before run. otherwise task may be deleted by main thread
      // race condition
      task->DeleteAfterExecution();
      task->Run();
    }
    m_threadAvailable.notify_all();
  } while (!m_stopped);
}

void ThreadPool::Submit(boost::shared_ptr<Task> task)
{
  boost::mutex::scoped_lock lock(m_mutex);
  if (m_stopping) {
    throw runtime_error("ThreadPool stopping - unable to accept new jobs");
  }
  while (m_queueLimit > 0 && m_tasks.size() >= m_queueLimit) {
    m_threadAvailable.wait(lock);
  }
  m_tasks.push(task);
  m_threadNeeded.notify_all();
}

void ThreadPool::Stop(bool processRemainingJobs)
{
  {
    //prevent more jobs from being added to the queue
    boost::mutex::scoped_lock lock(m_mutex);
    if (m_stopped) return;
    m_stopping = true;
  }
  if (processRemainingJobs) {
    boost::mutex::scoped_lock lock(m_mutex);
    //wait for queue to drain.
    while (!m_tasks.empty() && !m_stopped) {
      m_threadAvailable.wait(lock);
    }
  }
  //tell all threads to stop
  {
    boost::mutex::scoped_lock lock(m_mutex);
    m_stopped = true;
  }
  m_threadNeeded.notify_all();

  m_threads.join_all();
}

}

<commit_msg>go back to using sysconf() for linux/osx. Runs ok on new systems but not thor.  std::thread::hardware_concurrency() returns 0 on thor<commit_after>// $Id: ThreadPool.cpp 3045 2010-04-05 13:07:29Z hieuhoang1972 $

/***********************************************************************
 Moses - factored phrase-based language decoder
 Copyright (C) 2009 University of Edinburgh

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

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

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 ***********************************************************************/
#include <stdio.h>
#ifdef __linux
#include <pthread.h>
#include <unistd.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <thread>

#include "ThreadPool.h"

using namespace std;

namespace Moses2
{

#define handle_error_en(en, msg) \
  do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

ThreadPool::ThreadPool(size_t numThreads, int cpuAffinityOffset,
                       int cpuAffinityIncr) :
  m_stopped(false), m_stopping(false), m_queueLimit(0)
{
#if defined(_WIN32) || defined(_WIN64)
  size_t numCPU = std::thread::hardware_concurrency();
#else
  size_t numCPU = sysconf(_SC_NPROCESSORS_ONLN);
#endif
  //cerr << "numCPU=" << numCPU << endl;

  int cpuInd = cpuAffinityOffset % numCPU;

  for (size_t i = 0; i < numThreads; ++i) {
    boost::thread *thread = m_threads.create_thread(
                              boost::bind(&ThreadPool::Execute, this));

#ifdef __linux
    if (cpuAffinityOffset >= 0) {
      int s;

      boost::thread::native_handle_type handle = thread->native_handle();

      //cerr << "numCPU=" << numCPU << endl;
      cpu_set_t cpuset;
      CPU_ZERO(&cpuset);

      CPU_SET(cpuInd, &cpuset);
      cpuInd += cpuAffinityIncr;
      cpuInd = cpuInd % numCPU;

      s = pthread_setaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
      if (s != 0) {
        handle_error_en(s, "pthread_setaffinity_np");
        //cerr << "affinity error with thread " << i << endl;
      }

      // get affinity
      CPU_ZERO(&cpuset);
      s = pthread_getaffinity_np(handle, sizeof(cpu_set_t), &cpuset);
      cerr << "Set returned by pthread_getaffinity_np() contained:\n";
      for (int j = 0; j < CPU_SETSIZE; j++) {
        if (CPU_ISSET(j, &cpuset)) {
          cerr << "    CPU " << j << "\n";
        }
      }
    }
#endif
  }
}

void ThreadPool::Execute()
{
  do {
    boost::shared_ptr<Task> task;
    {
      // Find a job to perform
      boost::mutex::scoped_lock lock(m_mutex);
      if (m_tasks.empty() && !m_stopped) {
        m_threadNeeded.wait(lock);
      }
      if (!m_stopped && !m_tasks.empty()) {
        task = m_tasks.front();
        m_tasks.pop();
      }
    }
    //Execute job
    if (task) {
      // must read from task before run. otherwise task may be deleted by main thread
      // race condition
      task->DeleteAfterExecution();
      task->Run();
    }
    m_threadAvailable.notify_all();
  } while (!m_stopped);
}

void ThreadPool::Submit(boost::shared_ptr<Task> task)
{
  boost::mutex::scoped_lock lock(m_mutex);
  if (m_stopping) {
    throw runtime_error("ThreadPool stopping - unable to accept new jobs");
  }
  while (m_queueLimit > 0 && m_tasks.size() >= m_queueLimit) {
    m_threadAvailable.wait(lock);
  }
  m_tasks.push(task);
  m_threadNeeded.notify_all();
}

void ThreadPool::Stop(bool processRemainingJobs)
{
  {
    //prevent more jobs from being added to the queue
    boost::mutex::scoped_lock lock(m_mutex);
    if (m_stopped) return;
    m_stopping = true;
  }
  if (processRemainingJobs) {
    boost::mutex::scoped_lock lock(m_mutex);
    //wait for queue to drain.
    while (!m_tasks.empty() && !m_stopped) {
      m_threadAvailable.wait(lock);
    }
  }
  //tell all threads to stop
  {
    boost::mutex::scoped_lock lock(m_mutex);
    m_stopped = true;
  }
  m_threadNeeded.notify_all();

  m_threads.join_all();
}

}

<|endoftext|>


<commit_before><commit_msg>vcl: cosmetic reident and cleanup of RawBitmap class definition<commit_after><|endoftext|>


<commit_before>#include "stdafx.h"
#include "../NWindow.h"

namespace nui
{
    namespace Ui
    {
        NWindow::NWindow()
        {
        }

        NWindow::~NWindow()
        {
        }

        NFrame* NWindow::GetRootFrame()
        {
            if(rootFrame_ == NULL)
            {
                Base::NInstPtr<NFrame> rootFrame(MemToolParam);
                rootFrame_ = (NFrame*)rootFrame;
                rootFrame_->window_ = this;
                Base::NRect rect;
                GetRect(rect);
                rootFrame_->SetSize(rect.Width(), rect.Height());
            }
            return rootFrame_;
        }

        NRender* NWindow::GetRender() const
        {
            return render_;
        }

        void NWindow::SetDrawCallback(WindowDrawCallback callback)
        {
            drawCallback_ = callback;
        }

        // WindowMsgFilter
        bool NWindow::OnMessage(UINT message, WPARAM wParam, LPARAM lParam, LRESULT& lResult)
        {
            if(NWindowBase::OnMessage(message, wParam, lParam, lResult))
                return true;

            switch(message)
            {
            case WM_CREATE:
                render_ = NUiBus::Instance().CreateRender();
                break;
            case WM_DESTROY:
                render_ = NULL;
                rootFrame_ = NULL;
                break;
            case WM_ERASEBKGND:
                lResult = 1;
                return true;
            case WM_NCACTIVATE:
                {
                    if(::IsIconic(window_))
                        return false;
                    lResult = (wParam == 0) ? TRUE : FALSE;
                    return true;
                }
            case WM_NCHITTEST:
                {
                    lResult = HTCLIENT;
                    return true;
                }
            case WM_NCPAINT:
            case WM_NCCALCSIZE:
                {
                    lResult = 0;
                    return true;
                }
            case WM_PAINT:
                {
                    PAINTSTRUCT ps = {0};
                    HDC hDc = ::BeginPaint(window_, &ps);
                    Draw(hDc);
                    ::EndPaint(window_, &ps);
                }
                break;
            case WM_PRINT:
                {
                    HDC hDc = (HDC)wParam;
                    Draw(hDc);
                }
                break;
            case WM_SIZE:
                if(wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED)
                {
                    lResult = DoDefault(message, wParam, lParam);
                    OnSize(LOWORD(lParam), HIWORD(lParam));
                    return true;
                }
                break;
            case WM_ACTIVATE:
                {
                    BOOL bActive = (LOWORD(wParam) != WA_INACTIVE);
                    if(!bActive)
                    {
                        SetHoverItem(NULL);
                        NUiBus::Instance().SetCaptureFrame(NULL);
                    }
                    break;
                }
            case WM_MOUSEMOVE:
                {
                    Base::NPoint point(LOWORD(lParam), HIWORD(lParam));
                    RefreshHoverItem(point);
                }
                break;
            case WM_LBUTTONDOWN:
                ::SendMessage(window_, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
                break;
            case WM_LBUTTONUP:
                break;
                break;
            }
            return false;
        }

        void NWindow::OnSize(int width, int height)
        {
            if(rootFrame_)
                rootFrame_->SetSize(width, height);

            HRGN rgn = ::CreateRectRgn(0, 0, width, height);
            if(rgn != NULL)
                ::SetWindowRgn(GetNative(), rgn, FALSE);
        }

        void NWindow::OnDraw(NRender* render, const Base::NRect& clipRect)
        {
            if(drawCallback_ && drawCallback_(this, render, clipRect))
                return;

            if(rootFrame_ != NULL)
            {
                Base::NPoint pt;
                rootFrame_->Draw(render, pt, clipRect);
            }
        }

        void NWindow::Draw(HDC hDc)
        {
            Base::NRect clientRect;
            ::GetClientRect(window_, clientRect);
            render_->Init(hDc, clientRect);

            Base::NRect clipRect;
            int nResult = GetClipBox(hDc, clipRect);
            if(nResult == NULLREGION)
                ::GetClientRect(window_, clipRect);
            OnDraw(render_, clipRect);

            render_->DrawBack(IsLayered());
        }

        void NWindow::SetHoverItem(NFrame* frame)
        {
            if(hoverFrame_ == frame)
                return;
            if(hoverFrame_)
                hoverFrame_->CancelHover();
            hoverFrame_ = frame;
            if(hoverFrame_)
                hoverFrame_->BeginHover();
        }

        void NWindow::RefreshHoverItem(const Base::NPoint& point)
        {
            NFrame* newHover = NULL;
            if(hoverFrame_)
            {
                newHover = hoverFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
            }
            if(!newHover)
            {
                newHover = rootFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
            }
            SetHoverItem(newHover);
        }
    }
}
<commit_msg>fix crash<commit_after>#include "stdafx.h"
#include "../NWindow.h"

namespace nui
{
    namespace Ui
    {
        NWindow::NWindow()
        {
        }

        NWindow::~NWindow()
        {
        }

        NFrame* NWindow::GetRootFrame()
        {
            if(rootFrame_ == NULL)
            {
                Base::NInstPtr<NFrame> rootFrame(MemToolParam);
                rootFrame_ = (NFrame*)rootFrame;
                rootFrame_->window_ = this;
                Base::NRect rect;
                GetRect(rect);
                rootFrame_->SetSize(rect.Width(), rect.Height());
            }
            return rootFrame_;
        }

        NRender* NWindow::GetRender() const
        {
            return render_;
        }

        void NWindow::SetDrawCallback(WindowDrawCallback callback)
        {
            drawCallback_ = callback;
        }

        // WindowMsgFilter
        bool NWindow::OnMessage(UINT message, WPARAM wParam, LPARAM lParam, LRESULT& lResult)
        {
            if(NWindowBase::OnMessage(message, wParam, lParam, lResult))
                return true;

            switch(message)
            {
            case WM_CREATE:
                render_ = NUiBus::Instance().CreateRender();
                break;
            case WM_DESTROY:
                render_ = NULL;
                rootFrame_ = NULL;
                break;
            case WM_ERASEBKGND:
                lResult = 1;
                return true;
            case WM_NCACTIVATE:
                {
                    if(::IsIconic(window_))
                        return false;
                    lResult = (wParam == 0) ? TRUE : FALSE;
                    return true;
                }
            case WM_NCHITTEST:
                {
                    lResult = HTCLIENT;
                    return true;
                }
            case WM_NCPAINT:
            case WM_NCCALCSIZE:
                {
                    lResult = 0;
                    return true;
                }
            case WM_PAINT:
                {
                    PAINTSTRUCT ps = {0};
                    HDC hDc = ::BeginPaint(window_, &ps);
                    Draw(hDc);
                    ::EndPaint(window_, &ps);
                }
                break;
            case WM_PRINT:
                {
                    HDC hDc = (HDC)wParam;
                    Draw(hDc);
                }
                break;
            case WM_SIZE:
                if(wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED)
                {
                    lResult = DoDefault(message, wParam, lParam);
                    OnSize(LOWORD(lParam), HIWORD(lParam));
                    return true;
                }
                break;
            case WM_ACTIVATE:
                {
                    BOOL bActive = (LOWORD(wParam) != WA_INACTIVE);
                    if(!bActive)
                    {
                        SetHoverItem(NULL);
                        NUiBus::Instance().SetCaptureFrame(NULL);
                    }
                    break;
                }
            case WM_MOUSEMOVE:
                {
                    Base::NPoint point(LOWORD(lParam), HIWORD(lParam));
                    RefreshHoverItem(point);
                }
                break;
            case WM_LBUTTONDOWN:
                ::SendMessage(window_, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
                break;
            case WM_LBUTTONUP:
                break;
                break;
            }
            return false;
        }

        void NWindow::OnSize(int width, int height)
        {
            if(rootFrame_)
                rootFrame_->SetSize(width, height);

            HRGN rgn = ::CreateRectRgn(0, 0, width, height);
            if(rgn != NULL)
                ::SetWindowRgn(GetNative(), rgn, FALSE);
        }

        void NWindow::OnDraw(NRender* render, const Base::NRect& clipRect)
        {
            if(drawCallback_ && drawCallback_(this, render, clipRect))
                return;

            if(rootFrame_ != NULL)
            {
                Base::NPoint pt;
                rootFrame_->Draw(render, pt, clipRect);
            }
        }

        void NWindow::Draw(HDC hDc)
        {
            Base::NRect clientRect;
            ::GetClientRect(window_, clientRect);
            render_->Init(hDc, clientRect);

            Base::NRect clipRect;
            int nResult = GetClipBox(hDc, clipRect);
            if(nResult == NULLREGION)
                ::GetClientRect(window_, clipRect);
            OnDraw(render_, clipRect);

            render_->DrawBack(IsLayered());
        }

        void NWindow::SetHoverItem(NFrame* frame)
        {
            if(hoverFrame_ == frame)
                return;
            if(hoverFrame_)
                hoverFrame_->CancelHover();
            hoverFrame_ = frame;
            if(hoverFrame_)
                hoverFrame_->BeginHover();
        }

        void NWindow::RefreshHoverItem(const Base::NPoint& point)
        {
            if(rootFrame_ == NULL)
                return;
            NFrame* newHover = NULL;
            if(hoverFrame_)
            {
                newHover = hoverFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
            }
            if(!newHover)
            {
                newHover = rootFrame_->GetChildByPointAndFlag(point, NFrame::FlagCanHover);
            }
            SetHoverItem(newHover);
        }
    }
}
<|endoftext|>


<commit_before>//===--- ToolChain.cpp - Collections of tools for one platform ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/ToolChain.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang::driver;
using namespace clang;

ToolChain::ToolChain(const Driver &D, const llvm::Triple &T)
  : D(D), Triple(T) {
}

ToolChain::~ToolChain() {
}

const Driver &ToolChain::getDriver() const {
 return D;
}

std::string ToolChain::getDefaultUniversalArchName() const {
  // In universal driver terms, the arch name accepted by -arch isn't exactly
  // the same as the ones that appear in the triple. Roughly speaking, this is
  // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
  // only interesting special case is powerpc.
  switch (Triple.getArch()) {
  case llvm::Triple::ppc:
    return "ppc";
  case llvm::Triple::ppc64:
    return "ppc64";
  default:
    return Triple.getArchName();
  }
}

bool ToolChain::IsUnwindTablesDefault() const {
  return false;
}

std::string ToolChain::GetFilePath(const char *Name) const {
  return D.GetFilePath(Name, *this);

}

std::string ToolChain::GetProgramPath(const char *Name) const {
  return D.GetProgramPath(Name, *this);
}

types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
  return types::lookupTypeForExtension(Ext);
}

bool ToolChain::HasNativeLLVMSupport() const {
  return false;
}

ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
                     VersionTuple());
}

/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
//
// FIXME: tblgen this.
static const char *getARMTargetCPU(const ArgList &Args,
                                   const llvm::Triple &Triple) {
  // For Darwin targets, the -arch option (which is translated to a
  // corresponding -march option) should determine the architecture
  // (and the Mach-O slice) regardless of any -mcpu options.
  if (!Triple.isOSDarwin()) {
    // FIXME: Warn on inconsistent use of -mcpu and -march.
    // If we have -mcpu=, use that.
    if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
      return A->getValue();
  }

  StringRef MArch;
  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
    // Otherwise, if we have -march= choose the base CPU for that arch.
    MArch = A->getValue();
  } else {
    // Otherwise, use the Arch from the triple.
    MArch = Triple.getArchName();
  }

  return llvm::StringSwitch<const char *>(MArch)
    .Cases("armv2", "armv2a","arm2")
    .Case("armv3", "arm6")
    .Case("armv3m", "arm7m")
    .Cases("armv4", "armv4t", "arm7tdmi")
    .Cases("armv5", "armv5t", "arm10tdmi")
    .Cases("armv5e", "armv5te", "arm1026ejs")
    .Case("armv5tej", "arm926ej-s")
    .Cases("armv6", "armv6k", "arm1136jf-s")
    .Case("armv6j", "arm1136j-s")
    .Cases("armv6z", "armv6zk", "arm1176jzf-s")
    .Case("armv6t2", "arm1156t2-s")
    .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
    .Cases("armv7l", "armv7-l", "cortex-a8")
    .Cases("armv7f", "armv7-f", "cortex-a9-mp")
    .Cases("armv7s", "armv7-s", "swift")
    .Cases("armv7r", "armv7-r", "cortex-r4", "cortex-r5")
    .Cases("armv7m", "armv7-m", "cortex-m3")
    .Case("ep9312", "ep9312")
    .Case("iwmmxt", "iwmmxt")
    .Case("xscale", "xscale")
    .Cases("armv6m", "armv6-m", "cortex-m0")
    // If all else failed, return the most base CPU LLVM supports.
    .Default("arm7tdmi");
}

/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
/// CPU.
//
// FIXME: This is redundant with -mcpu, why does LLVM use this.
// FIXME: tblgen this, or kill it!
static const char *getLLVMArchSuffixForARM(StringRef CPU) {
  return llvm::StringSwitch<const char *>(CPU)
    .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
    .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
    .Cases("arm920", "arm920t", "arm922t", "v4t")
    .Cases("arm940t", "ep9312","v4t")
    .Cases("arm10tdmi",  "arm1020t", "v5")
    .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
    .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
    .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
    .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
    .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
    .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
    .Cases("cortex-a8", "cortex-a9", "cortex-a15", "v7")
    .Case("cortex-m3", "v7m")
    .Case("cortex-m4", "v7m")
    .Case("cortex-m0", "v6m")
    .Case("cortex-a9-mp", "v7f")
    .Case("swift", "v7s")
    .Default("");
}

std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
                                         types::ID InputType) const {
  switch (getTriple().getArch()) {
  default:
    return getTripleString();

  case llvm::Triple::arm:
  case llvm::Triple::thumb: {
    // FIXME: Factor into subclasses.
    llvm::Triple Triple = getTriple();

    // Thumb2 is the default for V7 on Darwin.
    //
    // FIXME: Thumb should just be another -target-feaure, not in the triple.
    StringRef Suffix =
      getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
    bool ThumbDefault = (Suffix.startswith("v7") && getTriple().isOSDarwin());
    std::string ArchName = "arm";

    // Assembly files should start in ARM mode.
    if (InputType != types::TY_PP_Asm &&
        Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
      ArchName = "thumb";
    Triple.setArchName(ArchName + Suffix.str());

    return Triple.getTriple();
  }
  }
}

std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
                                                   types::ID InputType) const {
  // Diagnose use of Darwin OS deployment target arguments on non-Darwin.
  if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
                               options::OPT_miphoneos_version_min_EQ,
                               options::OPT_mios_simulator_version_min_EQ))
    getDriver().Diag(diag::err_drv_clang_unsupported)
      << A->getAsString(Args);

  return ComputeLLVMTriple(Args, InputType);
}

void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
                                          ArgStringList &CC1Args) const {
  // Each toolchain should provide the appropriate include flags.
}

void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
                                      ArgStringList &CC1Args) const {
}

ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
  const ArgList &Args) const
{
  if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
    StringRef Value = A->getValue();
    if (Value == "compiler-rt")
      return ToolChain::RLT_CompilerRT;
    if (Value == "libgcc")
      return ToolChain::RLT_Libgcc;
    getDriver().Diag(diag::err_drv_invalid_rtlib_name)
      << A->getAsString(Args);
  }

  return GetDefaultRuntimeLibType();
}

ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
    StringRef Value = A->getValue();
    if (Value == "libc++")
      return ToolChain::CST_Libcxx;
    if (Value == "libstdc++")
      return ToolChain::CST_Libstdcxx;
    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
      << A->getAsString(Args);
  }

  return ToolChain::CST_Libstdcxx;
}

/// \brief Utility function to add a system include directory to CC1 arguments.
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
                                            ArgStringList &CC1Args,
                                            const Twine &Path) {
  CC1Args.push_back("-internal-isystem");
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
}

/// \brief Utility function to add a system include directory with extern "C"
/// semantics to CC1 arguments.
///
/// Note that this should be used rarely, and only for directories that
/// historically and for legacy reasons are treated as having implicit extern
/// "C" semantics. These semantics are *ignored* by and large today, but its
/// important to preserve the preprocessor changes resulting from the
/// classification.
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
                                                   ArgStringList &CC1Args,
                                                   const Twine &Path) {
  CC1Args.push_back("-internal-externc-isystem");
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
}

/// \brief Utility function to add a list of system include directories to CC1.
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
                                             ArgStringList &CC1Args,
                                             ArrayRef<StringRef> Paths) {
  for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
       I != E; ++I) {
    CC1Args.push_back("-internal-isystem");
    CC1Args.push_back(DriverArgs.MakeArgString(*I));
  }
}

void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
                                             ArgStringList &CC1Args) const {
  // Header search paths should be handled by each of the subclasses.
  // Historically, they have not been, and instead have been handled inside of
  // the CC1-layer frontend. As the logic is hoisted out, this generic function
  // will slowly stop being called.
  //
  // While it is being called, replicate a bit of a hack to propagate the
  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  // header search paths with it. Once all systems are overriding this
  // function, the CC1 flag and this line can be removed.
  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
}

void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
                                    ArgStringList &CmdArgs) const {
  CXXStdlibType Type = GetCXXStdlibType(Args);

  switch (Type) {
  case ToolChain::CST_Libcxx:
    CmdArgs.push_back("-lc++");
    break;

  case ToolChain::CST_Libstdcxx:
    CmdArgs.push_back("-lstdc++");
    break;
  }
}

void ToolChain::AddCCKextLibArgs(const ArgList &Args,
                                 ArgStringList &CmdArgs) const {
  CmdArgs.push_back("-lcc_kext");
}

bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
                                              ArgStringList &CmdArgs) const {
  // Check if -ffast-math or -funsafe-math is enabled.
  Arg *A = Args.getLastArg(options::OPT_ffast_math,
                           options::OPT_fno_fast_math,
                           options::OPT_funsafe_math_optimizations,
                           options::OPT_fno_unsafe_math_optimizations);

  if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
      A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
    return false;

  // If crtfastmath.o exists add it to the arguments.
  std::string Path = GetFilePath("crtfastmath.o");
  if (Path == "crtfastmath.o") // Not found.
    return false;

  CmdArgs.push_back(Args.MakeArgString(Path));
  return true;
}
<commit_msg>Fix confused use of llvm::StringSwitch for armv7r architecture.<commit_after>//===--- ToolChain.cpp - Collections of tools for one platform ------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/ToolChain.h"
#include "clang/Basic/ObjCRuntime.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Arg.h"
#include "clang/Driver/ArgList.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Option.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
using namespace clang::driver;
using namespace clang;

ToolChain::ToolChain(const Driver &D, const llvm::Triple &T)
  : D(D), Triple(T) {
}

ToolChain::~ToolChain() {
}

const Driver &ToolChain::getDriver() const {
 return D;
}

std::string ToolChain::getDefaultUniversalArchName() const {
  // In universal driver terms, the arch name accepted by -arch isn't exactly
  // the same as the ones that appear in the triple. Roughly speaking, this is
  // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the
  // only interesting special case is powerpc.
  switch (Triple.getArch()) {
  case llvm::Triple::ppc:
    return "ppc";
  case llvm::Triple::ppc64:
    return "ppc64";
  default:
    return Triple.getArchName();
  }
}

bool ToolChain::IsUnwindTablesDefault() const {
  return false;
}

std::string ToolChain::GetFilePath(const char *Name) const {
  return D.GetFilePath(Name, *this);

}

std::string ToolChain::GetProgramPath(const char *Name) const {
  return D.GetProgramPath(Name, *this);
}

types::ID ToolChain::LookupTypeForExtension(const char *Ext) const {
  return types::lookupTypeForExtension(Ext);
}

bool ToolChain::HasNativeLLVMSupport() const {
  return false;
}

ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const {
  return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC,
                     VersionTuple());
}

/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
//
// FIXME: tblgen this.
static const char *getARMTargetCPU(const ArgList &Args,
                                   const llvm::Triple &Triple) {
  // For Darwin targets, the -arch option (which is translated to a
  // corresponding -march option) should determine the architecture
  // (and the Mach-O slice) regardless of any -mcpu options.
  if (!Triple.isOSDarwin()) {
    // FIXME: Warn on inconsistent use of -mcpu and -march.
    // If we have -mcpu=, use that.
    if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
      return A->getValue();
  }

  StringRef MArch;
  if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) {
    // Otherwise, if we have -march= choose the base CPU for that arch.
    MArch = A->getValue();
  } else {
    // Otherwise, use the Arch from the triple.
    MArch = Triple.getArchName();
  }

  return llvm::StringSwitch<const char *>(MArch)
    .Cases("armv2", "armv2a","arm2")
    .Case("armv3", "arm6")
    .Case("armv3m", "arm7m")
    .Cases("armv4", "armv4t", "arm7tdmi")
    .Cases("armv5", "armv5t", "arm10tdmi")
    .Cases("armv5e", "armv5te", "arm1026ejs")
    .Case("armv5tej", "arm926ej-s")
    .Cases("armv6", "armv6k", "arm1136jf-s")
    .Case("armv6j", "arm1136j-s")
    .Cases("armv6z", "armv6zk", "arm1176jzf-s")
    .Case("armv6t2", "arm1156t2-s")
    .Cases("armv7", "armv7a", "armv7-a", "cortex-a8")
    .Cases("armv7l", "armv7-l", "cortex-a8")
    .Cases("armv7f", "armv7-f", "cortex-a9-mp")
    .Cases("armv7s", "armv7-s", "swift")
    .Cases("armv7r", "armv7-r", "cortex-r4")
    .Cases("armv7m", "armv7-m", "cortex-m3")
    .Case("ep9312", "ep9312")
    .Case("iwmmxt", "iwmmxt")
    .Case("xscale", "xscale")
    .Cases("armv6m", "armv6-m", "cortex-m0")
    // If all else failed, return the most base CPU LLVM supports.
    .Default("arm7tdmi");
}

/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
/// CPU.
//
// FIXME: This is redundant with -mcpu, why does LLVM use this.
// FIXME: tblgen this, or kill it!
static const char *getLLVMArchSuffixForARM(StringRef CPU) {
  return llvm::StringSwitch<const char *>(CPU)
    .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t")
    .Cases("arm720t", "arm9", "arm9tdmi", "v4t")
    .Cases("arm920", "arm920t", "arm922t", "v4t")
    .Cases("arm940t", "ep9312","v4t")
    .Cases("arm10tdmi",  "arm1020t", "v5")
    .Cases("arm9e",  "arm926ej-s",  "arm946e-s", "v5e")
    .Cases("arm966e-s",  "arm968e-s",  "arm10e", "v5e")
    .Cases("arm1020e",  "arm1022e",  "xscale", "iwmmxt", "v5e")
    .Cases("arm1136j-s",  "arm1136jf-s",  "arm1176jz-s", "v6")
    .Cases("arm1176jzf-s",  "mpcorenovfp",  "mpcore", "v6")
    .Cases("arm1156t2-s",  "arm1156t2f-s", "v6t2")
    .Cases("cortex-a8", "cortex-a9", "cortex-a15", "v7")
    .Case("cortex-m3", "v7m")
    .Case("cortex-m4", "v7m")
    .Case("cortex-m0", "v6m")
    .Case("cortex-a9-mp", "v7f")
    .Case("swift", "v7s")
    .Default("");
}

std::string ToolChain::ComputeLLVMTriple(const ArgList &Args,
                                         types::ID InputType) const {
  switch (getTriple().getArch()) {
  default:
    return getTripleString();

  case llvm::Triple::arm:
  case llvm::Triple::thumb: {
    // FIXME: Factor into subclasses.
    llvm::Triple Triple = getTriple();

    // Thumb2 is the default for V7 on Darwin.
    //
    // FIXME: Thumb should just be another -target-feaure, not in the triple.
    StringRef Suffix =
      getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
    bool ThumbDefault = (Suffix.startswith("v7") && getTriple().isOSDarwin());
    std::string ArchName = "arm";

    // Assembly files should start in ARM mode.
    if (InputType != types::TY_PP_Asm &&
        Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
      ArchName = "thumb";
    Triple.setArchName(ArchName + Suffix.str());

    return Triple.getTriple();
  }
  }
}

std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args,
                                                   types::ID InputType) const {
  // Diagnose use of Darwin OS deployment target arguments on non-Darwin.
  if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ,
                               options::OPT_miphoneos_version_min_EQ,
                               options::OPT_mios_simulator_version_min_EQ))
    getDriver().Diag(diag::err_drv_clang_unsupported)
      << A->getAsString(Args);

  return ComputeLLVMTriple(Args, InputType);
}

void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
                                          ArgStringList &CC1Args) const {
  // Each toolchain should provide the appropriate include flags.
}

void ToolChain::addClangTargetOptions(const ArgList &DriverArgs,
                                      ArgStringList &CC1Args) const {
}

ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType(
  const ArgList &Args) const
{
  if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) {
    StringRef Value = A->getValue();
    if (Value == "compiler-rt")
      return ToolChain::RLT_CompilerRT;
    if (Value == "libgcc")
      return ToolChain::RLT_Libgcc;
    getDriver().Diag(diag::err_drv_invalid_rtlib_name)
      << A->getAsString(Args);
  }

  return GetDefaultRuntimeLibType();
}

ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
  if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
    StringRef Value = A->getValue();
    if (Value == "libc++")
      return ToolChain::CST_Libcxx;
    if (Value == "libstdc++")
      return ToolChain::CST_Libstdcxx;
    getDriver().Diag(diag::err_drv_invalid_stdlib_name)
      << A->getAsString(Args);
  }

  return ToolChain::CST_Libstdcxx;
}

/// \brief Utility function to add a system include directory to CC1 arguments.
/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs,
                                            ArgStringList &CC1Args,
                                            const Twine &Path) {
  CC1Args.push_back("-internal-isystem");
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
}

/// \brief Utility function to add a system include directory with extern "C"
/// semantics to CC1 arguments.
///
/// Note that this should be used rarely, and only for directories that
/// historically and for legacy reasons are treated as having implicit extern
/// "C" semantics. These semantics are *ignored* by and large today, but its
/// important to preserve the preprocessor changes resulting from the
/// classification.
/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs,
                                                   ArgStringList &CC1Args,
                                                   const Twine &Path) {
  CC1Args.push_back("-internal-externc-isystem");
  CC1Args.push_back(DriverArgs.MakeArgString(Path));
}

/// \brief Utility function to add a list of system include directories to CC1.
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
                                             ArgStringList &CC1Args,
                                             ArrayRef<StringRef> Paths) {
  for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end();
       I != E; ++I) {
    CC1Args.push_back("-internal-isystem");
    CC1Args.push_back(DriverArgs.MakeArgString(*I));
  }
}

void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
                                             ArgStringList &CC1Args) const {
  // Header search paths should be handled by each of the subclasses.
  // Historically, they have not been, and instead have been handled inside of
  // the CC1-layer frontend. As the logic is hoisted out, this generic function
  // will slowly stop being called.
  //
  // While it is being called, replicate a bit of a hack to propagate the
  // '-stdlib=' flag down to CC1 so that it can in turn customize the C++
  // header search paths with it. Once all systems are overriding this
  // function, the CC1 flag and this line can be removed.
  DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ);
}

void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args,
                                    ArgStringList &CmdArgs) const {
  CXXStdlibType Type = GetCXXStdlibType(Args);

  switch (Type) {
  case ToolChain::CST_Libcxx:
    CmdArgs.push_back("-lc++");
    break;

  case ToolChain::CST_Libstdcxx:
    CmdArgs.push_back("-lstdc++");
    break;
  }
}

void ToolChain::AddCCKextLibArgs(const ArgList &Args,
                                 ArgStringList &CmdArgs) const {
  CmdArgs.push_back("-lcc_kext");
}

bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args,
                                              ArgStringList &CmdArgs) const {
  // Check if -ffast-math or -funsafe-math is enabled.
  Arg *A = Args.getLastArg(options::OPT_ffast_math,
                           options::OPT_fno_fast_math,
                           options::OPT_funsafe_math_optimizations,
                           options::OPT_fno_unsafe_math_optimizations);

  if (!A || A->getOption().getID() == options::OPT_fno_fast_math ||
      A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations)
    return false;

  // If crtfastmath.o exists add it to the arguments.
  std::string Path = GetFilePath("crtfastmath.o");
  if (Path == "crtfastmath.o") // Not found.
    return false;

  CmdArgs.push_back(Args.MakeArgString(Path));
  return true;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <random>
#define SIZEF 500

struct Position{
  int x;
  int y;
};

using namespace std;

void walk(Position *p,int &board,int size){
  //https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
  random_device rd;
  mt19937_64 gen(rd());
  //http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
  uniform_int_distribution<int> uni(0,100);
  int random = uni(gen);
  cout << random<<"\n";
}

int main(int argc, char const *argv[]) {
  int board [SIZEF][SIZEF];
  int size,count;
  Position *p;
  p = (Position *) malloc(sizeof(Position));
  cin >> size;
  p->x = 0;
  p->y = 0;
  board[0][0] = 1;
  count = 2;
  for (int i = 0; i < size; i++) {
    for (int j = 0;j < size; j++){
      walk(p,**board,size);
    }
  }
  return 0;
}
<commit_msg>walk() func walking???<commit_after>#include <iostream>
#include <random>
#define SIZEF 500

struct Position{
  int x;
  int y;
};

using namespace std;

int walk(Position *p,int &board,int size){
  //https://stackoverflow.com/questions/5008804/generating-random-integer-from-a-range
  random_device rd;
  mt19937_64 gen(rd());
  //http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
  uniform_real_distribution<> uni(0,99);
  cout << uni(gen)<<"\n";
  float random = uni(gen);

  while(1){
    if (0 <= random%100 < 12.5) { // move 1
      if((p->x-2>=0)&&(p->y+1<size)){
        if (board[p->x-2][p->y+1] == 0) {
          p->x-=2;
          p->y+=1;
        }
      }
    }else if (12.5 <= random%100 < 25){ // move 2
      if((p->x-1>=0)&&(p->y+2<size)){
        if (board[p->x-1][p->y+2] == 0) {
          p->x-=1;
          p->y+=2;
        }
      }
    }else if (25 <= random%100 < 37.5){ // move 3
      if((p->x+1<size)&&(p->y+2<size)){
        if (board[p->x+1][p->y+2] == 0) {
          p->x+=1;
          p->y+=2;
        }
      }
    }else if (37.5 <= random%100 < 50){ // move 4
      if((p->x+2<size)&&(p->y+1<size)){
        if (board[p->x+2][p->y+1] == 0) {
          p->x+=2;
          p->y+=1;
        }
      }
    }else if (50 <= random%100 < 62.5){ // move 5
      if((p->x+2<size)&&(p->y-1>=0)){
        if (board[p->x+2][p->y+1] == 0) {
          p->x+=2;
          p->y-=1;
        }
      }
    }else if (62.5 <= random%100 < 75){ // move 6
      if((p->x+1<size)&&(p->y-2>=0)){
        if (board[p->x+1][p->y+2] == 0) {
          p->x+=1;
          p->y-=2;
        }
      }
    }else if (75 <= random%100 < 87.5){ // move 7
      if((p->x-1>=0)&&(p->y-2>=0)){
        if (board[p->x-1][p->y-2] == 0) {
          p->x-=1;
          p->y-=2;
        }
      }
    }else if (87.5 <= random%100 < 100){ // move 8
      if((p->x-2>=0)&&(p->y-1>=0)){
        if (board[p->x-2][p->y-1] == 0) {
          p->x-=2;
          p->y-=1;
        }
      }
    }

  }

}

int main(int argc, char const *argv[]) {
  int board [SIZEF][SIZEF] = {0};
  int size,count,end;
  int i, j;
  Position *p;
  p = (Position *) malloc(sizeof(Position));
  cin >> size;
  while (1) {
    p->x = 0;
    p->y = 0;
    board[0][0] = 1;
    count = 2;
    for (i = 0; i < size; i++) {
      for (j = 0;j < size; j++){
        end = walk(p,**board,size);
        if (end == 1) {

        }
      }
    }
  }
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>fix windows build<commit_after><|endoftext|>


<commit_before>/*

  Sequence hot to se the PWG1 analysis tasks:

  //1. Load libraries if needed:
  //
  gSystem->Load("/usr/local/grid/XRootd/GSI/lib/libXrdClient.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libPWG0base.so");
  gSystem->Load("libPWG0dep.so");
  gSystem->Load("libPWG1.so");

  AliLog::SetGlobalLogLevel(AliLog::kError);

  //2. Make a chain e.g.:
  //
  gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
  gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+");
  AliXRDPROOFtoolkit tool;
  TChain * chainEsd = tool.MakeChain("esd.txt","esdTree",0,5000);
  chainEsd->Lookup();
  //

  //3. Make a analysis manager with attached task:
  .L $ALICE_ROOT/PWG1/Macros/taskComp.C
  Init();
  AliAnalysisManager *mgr = MakeManager();

  //4. Process task localy
  //
  mgr->SetNSysInfo(100);
  mgr->SetDebugLevel(1);
  mgr->StartAnalysis("local",chainEsd);

  //
  //4. Process task on proof
  //
  TProof::Open("");
  .L /u/miranov/macros/ProofEnableAliRoot.C
  ProofEnableAliRoot("/usr/local/grid/AliRoot/HEAD0108");
  gProof->Exec("gSystem->Load(\"libANALYSIS.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libAOD.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libANALYSISalice.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libPWG0base.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libPWG0dep.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libPWG1.so\")",kTRUE);
  mgr->StartAnalysis("proof",chainEsd);
  //5. Get debug stream - if speciefied
  TFile f("mcTaskDebug.root");
  TTree *treeCMP = (TTree*)f.Get("RC");

  //6. Read the analysis object
  TFile f("Output.root");
  TObjArray * array = (TObjArray*)f.Get("AliComparisonRes");
  AliComparisonRes * compObj = (AliComparisonRes*)array->FindObject("AliComparisonRes");
  //
  //7. Get debug streamer on PROOF
  gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
  gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+")
  AliXRDPROOFtoolkit tool;
  TChain * chainTr = tool.MakeChain("cmp.txt","RC",0,1000000);
  chainTr->Lookup();
  chainTr->SetProof(kTRUE);
  TChain * chainTPC = tool.MakeChain("tpc.txt","Crefit",0,50);
  chainTPC->Lookup();
  chainTr->SetProof(kTRUE);

  TFile f("mcTaskDebug.root");
  TTree *treeCMP = (TTree*)f.Get("RC");

*/

void AddComparison( AliGenInfoTask * task);

void Init(){
  //
  // Init mag field and the geo manager
  //
  TGeoManager::Import("/u/miranov/proof/geometry.root");
  AliGeomManager::LoadGeometry("/u/miranov/proof/geometry.root");

  TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));

}

AliAnalysisManager *  MakeManager(){
  //
  //
  //
  AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisComponentManager");
  mgr->SetDebugLevel(1);
  cout << "Creating ESD event handler" << endl;
  AliESDInputHandler* esdH = new AliESDInputHandler();
  // set the ESDfriend branch active (my modification of AliESDInputHandler)
  esdH->SetActiveBranches("ESDfriend");
  mgr->SetInputEventHandler(esdH);

  AliMCEventHandler* mcHandler = new AliMCEventHandler();
  mgr->SetMCtruthEventHandler(mcHandler);
  //

  AliGenInfoTask *genTask = new AliGenInfoTask("genTask");
  genTask->SetStreamLevel(10);
  genTask->SetDebugLevel(10);
  genTask->SetDebugOuputhPath(gSystem->pwd());

 //  //AddComparison(genTask);
//   mgr->AddTask(genTask);
//   //
//   //
//   AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
//   mgr->ConnectInput(genTask,0,cinput1);
//   //
//   AliAnalysisDataContainer *coutput1
//     =mgr->CreateContainer("AliComparisonRes",TObjArray::Class(),
// 			   AliAnalysisManager::kOutputContainer,
//  			  "Output.root");
//   mgr->ConnectOutput(genTask,0,coutput1);

  //
  // TPC PID task
  //
  AliTPCtaskPID *pidTask = new AliTPCtaskPID("pidTask");
  mgr->AddTask(pidTask);
  AliAnalysisDataContainer *cinput2 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(pidTask,0,cinput2);
  //
  AliAnalysisDataContainer *coutput2
    =mgr->CreateContainer("tpcTaskPID", TObjArray::Class(),
			  AliAnalysisManager::kOutputContainer,
			  "OutputPID.root");
  mgr->ConnectOutput(pidTask,0,coutput2);

  //
  // TPC QA task
  //
  AliTPCtaskQA *qaTask = new AliTPCtaskQA("qaTask");
  mgr->AddTask(qaTask);
  AliAnalysisDataContainer *cinput3 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(qaTask,0,cinput3);
  //
  AliAnalysisDataContainer *coutput3
    =mgr->CreateContainer("tpcTaskQA", TObjArray::Class(),
			  AliAnalysisManager::kOutputContainer,
			  "OutputQA.root");
  mgr->ConnectOutput(qaTask,0,coutput3);
  //
  if (!mgr->InitAnalysis()) return 0;
  return mgr;
}

void AddComparison( AliGenInfoTask * task){

  // Create ESD track reconstruction cuts
  AliRecInfoCuts *pRecInfoCuts = new AliRecInfoCuts();
  if(pRecInfoCuts) {
    pRecInfoCuts->SetPtRange(0.15,200.0);
    pRecInfoCuts->SetMaxAbsTanTheta(1.0);
    pRecInfoCuts->SetMinNClustersTPC(10);
    pRecInfoCuts->SetMinNClustersITS(2);
    pRecInfoCuts->SetMinTPCsignalN(50);

	pRecInfoCuts->SetHistogramsOn(kFALSE);
  } else {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliRecInfoCuts object");
  }

  // Create MC track reconstruction cuts
  AliMCInfoCuts  *pMCInfoCuts = new AliMCInfoCuts();
  if(pMCInfoCuts) {
    pMCInfoCuts->SetMinRowsWithDigits(50);
    pMCInfoCuts->SetMaxR(0.001);
    pMCInfoCuts->SetMaxVz(0.001);
    pMCInfoCuts->SetRangeTPCSignal(0.5,1.4);
  } else {
    AliDebug(AliLog::kError, "ERROR: Cannot AliMCInfoCuts object");
  }

  //
  // Create comparison objects and set cuts
  //

  // Resolution
  AliComparisonRes *pCompRes = new AliComparisonRes("AliComparisonRes","AliComparisonRes");
  if(!pCompRes) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonRes object");
  }
  pCompRes->SetAliRecInfoCuts(pRecInfoCuts);
  pCompRes->SetAliMCInfoCuts(pMCInfoCuts);

  // Efficiency
  AliComparisonEff *pCompEff =  new AliComparisonEff("AliComparisonEff","AliComparisonEff");
  if(!pCompEff) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonEff object");
  }
  pCompEff->SetAliRecInfoCuts(pRecInfoCuts);
  pCompEff->SetAliMCInfoCuts(pMCInfoCuts);

  // dE/dx
  AliComparisonDEdx *pCompDEdx = new AliComparisonDEdx("AliComparisonDEdx","AliComparisonDEdx");
  if(!pCompDEdx) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDEdx object");
  }
  pCompDEdx->SetAliRecInfoCuts(pRecInfoCuts);
  pCompDEdx->SetAliMCInfoCuts(pMCInfoCuts);
  pCompDEdx->SetMCPtMin(0.5);
  pCompDEdx->SetMCAbsTanThetaMax(0.5);
  pCompDEdx->SetMCPdgCode(pMCInfoCuts->GetPiP()); // only pi+ particles

  // DCA
  AliComparisonDCA *pCompDCA = new AliComparisonDCA("AliComparisonDCA","AliComparisonDCA");
  if(!pCompDCA) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDCA object");
  }
  pCompDCA->SetAliRecInfoCuts(pRecInfoCuts);
  pCompDCA->SetAliMCInfoCuts(pMCInfoCuts);
  //
  //
  //
  task->AddComparisonObject( pCompRes );
  task->AddComparisonObject( pCompEff );
  task->AddComparisonObject( pCompDEdx );
  task->AddComparisonObject( pCompDCA );
}

<commit_msg>Example macro to run ( not only) AliMCTrackinTestTask<commit_after>/*

  Sequence hot to se the PWG1 analysis tasks:

  //1. Load libraries if needed:
  //
  gSystem->Load("/usr/local/grid/XRootd/GSI/lib/libXrdClient.so");
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libPWG0base.so");
  gSystem->Load("libPWG0dep.so");
  gSystem->Load("libPWG1.so");

  AliLog::SetGlobalLogLevel(AliLog::kError);

  //2. Make a chain e.g.:
  //
  gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
  gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+");
  AliXRDPROOFtoolkit tool;
  TChain * chainEsd = tool.MakeChain("esd.txt","esdTree",0,5);
  chainEsd->Lookup();
  //

  //3. Make a analysis manager with attached task:
  .L $ALICE_ROOT/PWG1/macros/taskComp.C
  Init();
  AliAnalysisManager *mgr = MakeManager();

  //4. Process task localy
  //
  mgr->SetNSysInfo(100);
  mgr->SetDebugLevel(1);
  mgr->StartAnalysis("local",chainEsd);

  //
  //4. Process task on proof
  //
  TProof::Open("");
  .L /u/miranov/macros/ProofEnableAliRoot.C
  ProofEnableAliRoot("/usr/local/grid/AliRoot/HEAD0108");
  gProof->Exec("gSystem->Load(\"libANALYSIS.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libAOD.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libANALYSISalice.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libPWG0base.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libPWG0dep.so\")",kTRUE);
  gProof->Exec("gSystem->Load(\"libPWG1.so\")",kTRUE);

  TString path=gSystem->pwd();
  TString execCDB="gROOT->Macro(\"";
  execCDB+=path+"/ConfigOCDB.C\"\)";
  gProof->Exec(execCDB->Data(),kFALSE);

  mgr->StartAnalysis("proof",chainEsd);
  //5. Get debug stream - if speciefied
  TFile f("mcTaskDebug.root");
  TTree *treeCMP = (TTree*)f.Get("RC");

  //6. Read the analysis object
  TFile f("Output.root");
  TObjArray * array = (TObjArray*)f.Get("AliComparisonRes");
  AliComparisonRes * compObj = (AliComparisonRes*)array->FindObject("AliComparisonRes");
  //
  //7. Get debug streamer on PROOF
  gSystem->AddIncludePath("-I$ALICE_ROOT/TPC/macros");
  gROOT->LoadMacro("$ALICE_ROOT/TPC/macros/AliXRDPROOFtoolkit.cxx+")
  AliXRDPROOFtoolkit tool;
  TChain * chainTr = tool.MakeChain("cmp.txt","RC",0,1000000);
  chainTr->Lookup();
  chainTr->SetProof(kTRUE);
  TChain * chainTPC = tool.MakeChain("tpc.txt","Crefit",0,50);
  chainTPC->Lookup();
  chainTr->SetProof(kTRUE);

  TChain * chainTracking = tool.MakeChain("mctracking.txt","MCupdate",0,50);
  chainTracking->Lookup();
  chainTracking->SetProof(kTRUE);

  TFile f("mcTaskDebug.root");
  TTree *treeCMP = (TTree*)f.Get("RC");

*/

void AddComparison( AliGenInfoTask * task);

void Init(){
  //
  // Init mag field and the geo manager
  //
  TGeoManager::Import("/u/miranov/proof/geometry.root");
  AliGeomManager::LoadGeometry("/u/miranov/proof/geometry.root");

  TGeoGlobalMagField::Instance()->SetField(new AliMagF("Maps","Maps", 2, 1., 1., 10., AliMagF::k5kG));

}

AliAnalysisManager *  MakeManager(){
  //
  //
  //
  AliAnalysisManager *mgr = new AliAnalysisManager("AnalysisComponentManager");
  mgr->SetDebugLevel(1);
  cout << "Creating ESD event handler" << endl;
  AliESDInputHandler* esdH = new AliESDInputHandler();
  // set the ESDfriend branch active (my modification of AliESDInputHandler)
  esdH->SetActiveBranches("ESDfriend");
  mgr->SetInputEventHandler(esdH);

  AliMCEventHandler* mcHandler = new AliMCEventHandler();
  mgr->SetMCtruthEventHandler(mcHandler);
  //

  AliGenInfoTask *genTask = new AliGenInfoTask("genTask");
  genTask->SetStreamLevel(10);
  genTask->SetDebugLevel(10);
  genTask->SetDebugOuputhPath(Form("%s/",gSystem->pwd()));

 //  //AddComparison(genTask);
//   mgr->AddTask(genTask);
//   //
//   //
//   AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer();
//   mgr->ConnectInput(genTask,0,cinput1);
//   //
//   AliAnalysisDataContainer *coutput1
//     =mgr->CreateContainer("AliComparisonRes",TObjArray::Class(),
// 			   AliAnalysisManager::kOutputContainer,
//  			  "Output.root");
//   mgr->ConnectOutput(genTask,0,coutput1);

  //
  // TPC PID task
  //
  AliTPCtaskPID *pidTask = new AliTPCtaskPID("pidTask");
  mgr->AddTask(pidTask);
  AliAnalysisDataContainer *cinput2 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(pidTask,0,cinput2);
  //
  AliAnalysisDataContainer *coutput2
    =mgr->CreateContainer("tpcTaskPID", TObjArray::Class(),
			  AliAnalysisManager::kOutputContainer,
			  "OutputPID.root");
  mgr->ConnectOutput(pidTask,0,coutput2);

  //
  // TPC QA task
  //
  AliTPCtaskQA *qaTask = new AliTPCtaskQA("qaTask");
  mgr->AddTask(qaTask);
  AliAnalysisDataContainer *cinput3 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(qaTask,0,cinput3);
  //
  AliAnalysisDataContainer *coutput3
    =mgr->CreateContainer("tpcTaskQA", TObjArray::Class(),
			  AliAnalysisManager::kOutputContainer,
			  "OutputQA.root");
  mgr->ConnectOutput(qaTask,0,coutput3);
  //
  //
  //
  AliMCTrackingTestTask *mcTracking = new  AliMCTrackingTestTask("mcTracking");
  mcTracking->SetStreamLevel(10);
  mcTracking->SetDebugLevel(10);
  mgr->AddTask(mcTracking);
  mcTracking->SetDebugOuputhPath(gSystem->pwd());
  AliAnalysisDataContainer *cinput4 = mgr->GetCommonInputContainer();
  mgr->ConnectInput(mcTracking,0,cinput4);
  //
  AliAnalysisDataContainer *coutput4
    =mgr->CreateContainer("mcTask", TObjArray::Class(),
			  AliAnalysisManager::kOutputContainer,
			  "OutputMC.root");
  mgr->ConnectOutput(mcTracking,0,coutput4);

  //
  if (!mgr->InitAnalysis()) return 0;
  return mgr;
}

void AddComparison( AliGenInfoTask * task){

  // Create ESD track reconstruction cuts
  AliRecInfoCuts *pRecInfoCuts = new AliRecInfoCuts();
  if(pRecInfoCuts) {
    pRecInfoCuts->SetPtRange(0.15,200.0);
    pRecInfoCuts->SetMaxAbsTanTheta(1.0);
    pRecInfoCuts->SetMinNClustersTPC(10);
    pRecInfoCuts->SetMinNClustersITS(2);
    pRecInfoCuts->SetMinTPCsignalN(50);

	pRecInfoCuts->SetHistogramsOn(kFALSE);
  } else {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliRecInfoCuts object");
  }

  // Create MC track reconstruction cuts
  AliMCInfoCuts  *pMCInfoCuts = new AliMCInfoCuts();
  if(pMCInfoCuts) {
    pMCInfoCuts->SetMinRowsWithDigits(50);
    pMCInfoCuts->SetMaxR(0.001);
    pMCInfoCuts->SetMaxVz(0.001);
    pMCInfoCuts->SetRangeTPCSignal(0.5,1.4);
  } else {
    AliDebug(AliLog::kError, "ERROR: Cannot AliMCInfoCuts object");
  }

  //
  // Create comparison objects and set cuts
  //

  // Resolution
  AliComparisonRes *pCompRes = new AliComparisonRes("AliComparisonRes","AliComparisonRes");
  if(!pCompRes) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonRes object");
  }
  pCompRes->SetAliRecInfoCuts(pRecInfoCuts);
  pCompRes->SetAliMCInfoCuts(pMCInfoCuts);

  // Efficiency
  AliComparisonEff *pCompEff =  new AliComparisonEff("AliComparisonEff","AliComparisonEff");
  if(!pCompEff) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonEff object");
  }
  pCompEff->SetAliRecInfoCuts(pRecInfoCuts);
  pCompEff->SetAliMCInfoCuts(pMCInfoCuts);

  // dE/dx
  AliComparisonDEdx *pCompDEdx = new AliComparisonDEdx("AliComparisonDEdx","AliComparisonDEdx");
  if(!pCompDEdx) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDEdx object");
  }
  pCompDEdx->SetAliRecInfoCuts(pRecInfoCuts);
  pCompDEdx->SetAliMCInfoCuts(pMCInfoCuts);
  pCompDEdx->SetMCPtMin(0.5);
  pCompDEdx->SetMCAbsTanThetaMax(0.5);
  pCompDEdx->SetMCPdgCode(pMCInfoCuts->GetPiP()); // only pi+ particles

  // DCA
  AliComparisonDCA *pCompDCA = new AliComparisonDCA("AliComparisonDCA","AliComparisonDCA");
  if(!pCompDCA) {
    AliDebug(AliLog::kError, "ERROR: Cannot create AliComparisonDCA object");
  }
  pCompDCA->SetAliRecInfoCuts(pRecInfoCuts);
  pCompDCA->SetAliMCInfoCuts(pMCInfoCuts);
  //
  //
  //
  task->AddComparisonObject( pCompRes );
  task->AddComparisonObject( pCompEff );
  task->AddComparisonObject( pCompDEdx );
  task->AddComparisonObject( pCompDCA );
}

<|endoftext|>


<commit_before><commit_msg>use LanguageTag<commit_after><|endoftext|>


<commit_before><commit_msg>WaE: comparison between signed and unsigned integer expressions<commit_after><|endoftext|>


<commit_before>#pragma once

#include <agency/new_executor_traits.hpp>
#include <agency/future.hpp>
#include <agency/detail/executor_traits/check_for_member_functions.hpp>
#include <type_traits>
#include <iostream>

namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
namespace multi_agent_when_all_execute_and_select_implementation_strategies
{

struct use_multi_agent_when_all_execute_and_select_member_function {};

struct use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function {};

struct use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute {};

template<class IndexSequence, class Executor, class Function, class TupleOfFutures>
using has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits =
  has_multi_agent_when_all_execute_and_select_with_shared_inits<
    IndexSequence,
    Executor,
    Function,
    TupleOfFutures,
    detail::type_list_repeat<new_executor_traits<Executor>::execution_depth, detail::ignore_t>
  >;

template<class Executor>
struct dummy_functor_taking_index_type
{
  __AGENCY_ANNOTATION
  void operator()(const typename new_executor_traits<Executor>::index_type&) const {}
};

template<class Executor>
using has_multi_agent_execute_returning_void =
  new_executor_traits_detail::has_multi_agent_execute_returning_void<
    Executor,
    dummy_functor_taking_index_type<Executor>
  >;

template<class Executor, class Function, class TupleOfFutures, size_t... Indices>
using select_multi_agent_when_all_execute_and_select_implementation =
  typename std::conditional<
    has_multi_agent_when_all_execute_and_select<Executor, Function, TupleOfFutures, Indices...>::value,
    use_multi_agent_when_all_execute_and_select_member_function,
    typename std::conditional<
      has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits<detail::index_sequence<Indices...>, Executor, Function, TupleOfFutures>::value,
      use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
      use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute
    >::type
  >::type;

template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<Indices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_member_function,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
  return ex.template when_all_execute_and_select<Indices...>(f, shape, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()

template<size_t num_ignored_arguments, class Function>
struct multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor
{
  mutable Function f;

  template<size_t... ArgIndices, class Index, class Tuple>
  __AGENCY_ANNOTATION
  void impl(detail::index_sequence<ArgIndices...>, Index&& idx, Tuple&& arg_tuple) const
  {
    f(idx, std::get<ArgIndices>(std::forward<Tuple>(arg_tuple))...);
  }

  template<class Index, class... Args>
  __AGENCY_ANNOTATION
  void operator()(Index&& idx, Args&&... args) const
  {
    // ignore the arguments that come after the futures
    constexpr size_t num_non_ignored_arguments = sizeof...(Args) - num_ignored_arguments;
    impl(detail::make_index_sequence<num_non_ignored_arguments>(), std::forward<Index>(idx), detail::forward_as_tuple(std::forward<Args>(args)...));
  }
};

template<size_t... SelectedIndices, size_t... SharedInitIndices, class Executor, class Function, class TupleOfFutures, class... Types>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<SelectedIndices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
                                          detail::index_sequence<SharedInitIndices...>,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures, const detail::tuple<Types...>& ignored_shared_inits)
{
  constexpr size_t num_ignored_arguments = sizeof...(Types);
  auto g = multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor<num_ignored_arguments, Function>{f};

  return ex.template when_all_execute_and_select<SelectedIndices...>(g, shape, std::forward<TupleOfFutures>(futures), std::get<SharedInitIndices>(ignored_shared_inits)...);
} // end multi_agent_when_all_execute_and_select()

template<size_t... SelectedIndices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<SelectedIndices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function implementation_strategy,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
  constexpr size_t depth = new_executor_traits<Executor>::execution_depth;

  // create ignored shared initializers
  auto ignored_shared_inits = detail::tuple_repeat<depth>(detail::ignore);

  return multi_agent_when_all_execute_and_select<SelectedIndices...>(implementation_strategy,
                                                                     detail::make_index_sequence<depth>(),
                                                                     ex, f, shape, std::forward<TupleOfFutures>(futures), ignored_shared_inits);
} // end multi_agent_when_all_execute_and_select()

template<class Executor, class Function>
struct multi_agent_when_all_execute_and_select_functor_using_nested_execute
{
  Executor& ex;
  mutable Function f;
  typename new_executor_traits<Executor>::shape_type shape;

  template<class... Args>
  struct inner_functor
  {
    mutable Function f;
    mutable detail::tuple<Args&...> args;

    template<size_t... TupleIndices, class Index>
    __AGENCY_ANNOTATION
    void impl(detail::index_sequence<TupleIndices...>, const Index& idx) const
    {
      f(idx, std::get<TupleIndices>(args)...);
    }

    template<class Index>
    __AGENCY_ANNOTATION
    void operator()(const Index& idx) const
    {
      impl(detail::make_index_sequence<sizeof...(Args)>(), idx);
    }
  };

  template<class... Args>
  __AGENCY_ANNOTATION
  void operator()(Args&... args) const
  {
    new_executor_traits<Executor>::execute(ex, inner_functor<Args...>{f, detail::tie(args...)}, shape);
  }
};

template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<Indices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
  return new_executor_traits<Executor>::template when_all_execute_and_select<Indices...>(ex, multi_agent_when_all_execute_and_select_functor_using_nested_execute<Executor,Function>{ex,f,shape}, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()

} // end multi_agent_when_all_execute_and_select_implementation_strategies
} // end new_executor_traits_detail
} // end detail

template<class Executor>
template<size_t... Indices, class Function, class TupleOfFutures>
  typename new_executor_traits<Executor>::template future<
    detail::when_all_execute_and_select_result_t<
      detail::index_sequence<Indices...>,
      typename std::decay<TupleOfFutures>::type
    >
  >
  new_executor_traits<Executor>
    ::when_all_execute_and_select(typename new_executor_traits<Executor>::executor_type& ex,
                                  Function f,
                                  typename new_executor_traits<Executor>::shape_type shape,
                                  TupleOfFutures&& futures)
{
  namespace ns = detail::new_executor_traits_detail::multi_agent_when_all_execute_and_select_implementation_strategies;

  using implementation_strategy = ns::select_multi_agent_when_all_execute_and_select_implementation<
    Executor,
    Function,
    typename std::decay<TupleOfFutures>::type,
    Indices...
  >;

  return ns::multi_agent_when_all_execute_and_select<Indices...>(implementation_strategy(), ex, f, shape, std::forward<TupleOfFutures>(futures));
} // end new_executor_traits::when_all_execute_and_select()

} // end agency

<commit_msg>Use agency::invoke() to avoid __host__ __device__ warnings with nvcc<commit_after>#pragma once

#include <agency/new_executor_traits.hpp>
#include <agency/future.hpp>
#include <agency/detail/executor_traits/check_for_member_functions.hpp>
#include <agency/functional.hpp>
#include <type_traits>
#include <iostream>

namespace agency
{
namespace detail
{
namespace new_executor_traits_detail
{
namespace multi_agent_when_all_execute_and_select_implementation_strategies
{

struct use_multi_agent_when_all_execute_and_select_member_function {};

struct use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function {};

struct use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute {};

template<class IndexSequence, class Executor, class Function, class TupleOfFutures>
using has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits =
  has_multi_agent_when_all_execute_and_select_with_shared_inits<
    IndexSequence,
    Executor,
    Function,
    TupleOfFutures,
    detail::type_list_repeat<new_executor_traits<Executor>::execution_depth, detail::ignore_t>
  >;

template<class Executor>
struct dummy_functor_taking_index_type
{
  __AGENCY_ANNOTATION
  void operator()(const typename new_executor_traits<Executor>::index_type&) const {}
};

template<class Executor>
using has_multi_agent_execute_returning_void =
  new_executor_traits_detail::has_multi_agent_execute_returning_void<
    Executor,
    dummy_functor_taking_index_type<Executor>
  >;

template<class Executor, class Function, class TupleOfFutures, size_t... Indices>
using select_multi_agent_when_all_execute_and_select_implementation =
  typename std::conditional<
    has_multi_agent_when_all_execute_and_select<Executor, Function, TupleOfFutures, Indices...>::value,
    use_multi_agent_when_all_execute_and_select_member_function,
    typename std::conditional<
      has_multi_agent_when_all_execute_and_select_with_ignored_shared_inits<detail::index_sequence<Indices...>, Executor, Function, TupleOfFutures>::value,
      use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
      use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute
    >::type
  >::type;

template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<Indices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_member_function,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
  return ex.template when_all_execute_and_select<Indices...>(f, shape, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()

template<size_t num_ignored_arguments, class Function>
struct multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor
{
  mutable Function f;

  template<size_t... ArgIndices, class Index, class Tuple>
  __AGENCY_ANNOTATION
  void impl(detail::index_sequence<ArgIndices...>, Index&& idx, Tuple&& arg_tuple) const
  {
    f(idx, std::get<ArgIndices>(std::forward<Tuple>(arg_tuple))...);
  }

  template<class Index, class... Args>
  __AGENCY_ANNOTATION
  void operator()(Index&& idx, Args&&... args) const
  {
    // ignore the arguments that come after the futures
    constexpr size_t num_non_ignored_arguments = sizeof...(Args) - num_ignored_arguments;
    impl(detail::make_index_sequence<num_non_ignored_arguments>(), std::forward<Index>(idx), detail::forward_as_tuple(std::forward<Args>(args)...));
  }
};

template<size_t... SelectedIndices, size_t... SharedInitIndices, class Executor, class Function, class TupleOfFutures, class... Types>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<SelectedIndices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function,
                                          detail::index_sequence<SharedInitIndices...>,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures, const detail::tuple<Types...>& ignored_shared_inits)
{
  constexpr size_t num_ignored_arguments = sizeof...(Types);
  auto g = multi_agent_when_all_execute_and_select_using_ignored_shared_inits_functor<num_ignored_arguments, Function>{f};

  return ex.template when_all_execute_and_select<SelectedIndices...>(g, shape, std::forward<TupleOfFutures>(futures), std::get<SharedInitIndices>(ignored_shared_inits)...);
} // end multi_agent_when_all_execute_and_select()

template<size_t... SelectedIndices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<SelectedIndices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_multi_agent_when_all_execute_and_select_with_shared_inits_member_function implementation_strategy,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
  constexpr size_t depth = new_executor_traits<Executor>::execution_depth;

  // create ignored shared initializers
  auto ignored_shared_inits = detail::tuple_repeat<depth>(detail::ignore);

  return multi_agent_when_all_execute_and_select<SelectedIndices...>(implementation_strategy,
                                                                     detail::make_index_sequence<depth>(),
                                                                     ex, f, shape, std::forward<TupleOfFutures>(futures), ignored_shared_inits);
} // end multi_agent_when_all_execute_and_select()

template<class Executor, class Function>
struct multi_agent_when_all_execute_and_select_functor_using_nested_execute
{
  Executor& ex;
  mutable Function f;
  typename new_executor_traits<Executor>::shape_type shape;

  template<class... Args>
  struct inner_functor
  {
    mutable Function f;
    mutable detail::tuple<Args&...> args;

    template<size_t... TupleIndices, class Index>
    __AGENCY_ANNOTATION
    void impl(detail::index_sequence<TupleIndices...>, const Index& idx) const
    {
      agency::invoke(f, idx, std::get<TupleIndices>(args)...);
    }

    template<class Index>
    __AGENCY_ANNOTATION
    void operator()(const Index& idx) const
    {
      impl(detail::make_index_sequence<sizeof...(Args)>(), idx);
    }
  };

  template<class... Args>
  __AGENCY_ANNOTATION
  void operator()(Args&... args) const
  {
    new_executor_traits<Executor>::execute(ex, inner_functor<Args...>{f, detail::tie(args...)}, shape);
  }
};

template<size_t... Indices, class Executor, class Function, class TupleOfFutures>
typename new_executor_traits<Executor>::template future<
  detail::when_all_execute_and_select_result_t<
    detail::index_sequence<Indices...>,
    typename std::decay<TupleOfFutures>::type
  >
>
  multi_agent_when_all_execute_and_select(use_single_agent_when_all_execute_and_select_with_nested_multi_agent_execute,
                                          Executor& ex, Function f, typename new_executor_traits<Executor>::shape_type shape, TupleOfFutures&& futures)
{
  return new_executor_traits<Executor>::template when_all_execute_and_select<Indices...>(ex, multi_agent_when_all_execute_and_select_functor_using_nested_execute<Executor,Function>{ex,f,shape}, std::forward<TupleOfFutures>(futures));
} // end multi_agent_when_all_execute_and_select()

} // end multi_agent_when_all_execute_and_select_implementation_strategies
} // end new_executor_traits_detail
} // end detail

template<class Executor>
template<size_t... Indices, class Function, class TupleOfFutures>
  typename new_executor_traits<Executor>::template future<
    detail::when_all_execute_and_select_result_t<
      detail::index_sequence<Indices...>,
      typename std::decay<TupleOfFutures>::type
    >
  >
  new_executor_traits<Executor>
    ::when_all_execute_and_select(typename new_executor_traits<Executor>::executor_type& ex,
                                  Function f,
                                  typename new_executor_traits<Executor>::shape_type shape,
                                  TupleOfFutures&& futures)
{
  namespace ns = detail::new_executor_traits_detail::multi_agent_when_all_execute_and_select_implementation_strategies;

  using implementation_strategy = ns::select_multi_agent_when_all_execute_and_select_implementation<
    Executor,
    Function,
    typename std::decay<TupleOfFutures>::type,
    Indices...
  >;

  return ns::multi_agent_when_all_execute_and_select<Indices...>(implementation_strategy(), ex, f, shape, std::forward<TupleOfFutures>(futures));
} // end new_executor_traits::when_all_execute_and_select()

} // end agency

<|endoftext|>


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

#ifndef _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_
#include <comphelper/oslfile2streamwrap.hxx>
#endif

#include <algorithm>

namespace comphelper
{
    using namespace osl;

//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File& _rFile )
                 :m_pFile(&_rFile)
                 ,m_bFileOwner(sal_False)
{
}

//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File* pStream, sal_Bool bOwner )
                 :m_pFile( pStream )
                 ,m_bFileOwner( bOwner )
{
}

//------------------------------------------------------------------
OSLInputStreamWrapper::~OSLInputStreamWrapper()
{
    if( m_bFileOwner )
        delete m_pFile;
}

//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead)
                throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    if (nBytesToRead < 0)
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    ::osl::MutexGuard aGuard( m_aMutex );

    aData.realloc(nBytesToRead);

    sal_uInt64 nRead = 0;
    FileBase::RC eError = m_pFile->read((void*)aData.getArray(), nBytesToRead, nRead);
    if (eError != FileBase::E_None)
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    // Wenn gelesene Zeichen < MaxLength, staruno::Sequence anpassen
    if (nRead < (sal_uInt32)nBytesToRead)
        aData.realloc( sal::static_int_cast< sal_Int32 >(nRead) );

    return sal::static_int_cast< sal_Int32 >(nRead);
}

//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readSomeBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    if (nMaxBytesToRead < 0)
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    /*
      if (m_pFile->IsEof())
      {
      aData.realloc(0);
      return 0;
      }
      else
    */
    return readBytes(aData, nMaxBytesToRead);
}

//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::skipBytes(sal_Int32 nBytesToSkip) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    sal_uInt64 nCurrentPos;
    m_pFile->getPos(nCurrentPos);

    sal_uInt64 nNewPos = nCurrentPos + nBytesToSkip;
    FileBase::RC eError = m_pFile->setPos(osl_Pos_Absolut, nNewPos);
    if (eError != FileBase::E_None)
    {
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
    }

#ifdef DBG_UTIL
    m_pFile->getPos(nCurrentPos);
//  volatile int dummy = 0;                      // to take a look at last changes ;-)
#endif
}

//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::available() throw( stario::NotConnectedException, staruno::RuntimeException )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    sal_uInt64 nPos;
    FileBase::RC eError = m_pFile->getPos(nPos);
    if (eError != FileBase::E_None)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    sal_uInt64 nDummy = 0;
    eError = m_pFile->setPos(Pos_End, nDummy);
    if (eError != FileBase::E_None)
       throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    sal_uInt64 nAvailable;
    eError = m_pFile->getPos(nAvailable);
    if (eError != FileBase::E_None)
       throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    nAvailable = nAvailable - nPos;
    eError = m_pFile->setPos(Pos_Absolut, nPos);
    if (eError != FileBase::E_None)
       throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
    return sal::static_int_cast< sal_Int32 >(
        std::max(nAvailable, sal::static_int_cast< sal_uInt64 >(SAL_MAX_INT32)));
}

//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::closeInput() throw( stario::NotConnectedException, staruno::RuntimeException )
{
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    m_pFile->close();
    if (m_bFileOwner)
        delete m_pFile;

    m_pFile = NULL;
}

/*************************************************************************/
// stario::XOutputStream
//------------------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::writeBytes(const staruno::Sequence< sal_Int8 >& aData) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    sal_uInt64 nWritten;
    FileBase::RC eError = rFile.write(aData.getConstArray(),aData.getLength(), nWritten);
    if (eError != FileBase::E_None
        || nWritten != sal::static_int_cast< sal_uInt32 >(aData.getLength()))
    {
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
    }
}

//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::flush() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
}

//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::closeOutput() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    rFile.close();
}

} // namespace comphelper

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.36); FILE MERGED 2006/09/01 17:19:49 kaib 1.3.36.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: oslfile2streamwrap.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 17:20:34 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _COMPHELPER_STREAM_OSLFILEWRAPPER_HXX_
#include <comphelper/oslfile2streamwrap.hxx>
#endif

#include <algorithm>

namespace comphelper
{
    using namespace osl;

//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File& _rFile )
                 :m_pFile(&_rFile)
                 ,m_bFileOwner(sal_False)
{
}

//------------------------------------------------------------------
OSLInputStreamWrapper::OSLInputStreamWrapper( File* pStream, sal_Bool bOwner )
                 :m_pFile( pStream )
                 ,m_bFileOwner( bOwner )
{
}

//------------------------------------------------------------------
OSLInputStreamWrapper::~OSLInputStreamWrapper()
{
    if( m_bFileOwner )
        delete m_pFile;
}

//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nBytesToRead)
                throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    if (nBytesToRead < 0)
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    ::osl::MutexGuard aGuard( m_aMutex );

    aData.realloc(nBytesToRead);

    sal_uInt64 nRead = 0;
    FileBase::RC eError = m_pFile->read((void*)aData.getArray(), nBytesToRead, nRead);
    if (eError != FileBase::E_None)
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    // Wenn gelesene Zeichen < MaxLength, staruno::Sequence anpassen
    if (nRead < (sal_uInt32)nBytesToRead)
        aData.realloc( sal::static_int_cast< sal_Int32 >(nRead) );

    return sal::static_int_cast< sal_Int32 >(nRead);
}

//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::readSomeBytes(staruno::Sequence< sal_Int8 >& aData, sal_Int32 nMaxBytesToRead) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    if (nMaxBytesToRead < 0)
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    /*
      if (m_pFile->IsEof())
      {
      aData.realloc(0);
      return 0;
      }
      else
    */
    return readBytes(aData, nMaxBytesToRead);
}

//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::skipBytes(sal_Int32 nBytesToSkip) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    sal_uInt64 nCurrentPos;
    m_pFile->getPos(nCurrentPos);

    sal_uInt64 nNewPos = nCurrentPos + nBytesToSkip;
    FileBase::RC eError = m_pFile->setPos(osl_Pos_Absolut, nNewPos);
    if (eError != FileBase::E_None)
    {
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));
    }

#ifdef DBG_UTIL
    m_pFile->getPos(nCurrentPos);
//  volatile int dummy = 0;                      // to take a look at last changes ;-)
#endif
}

//------------------------------------------------------------------------------
sal_Int32 SAL_CALL OSLInputStreamWrapper::available() throw( stario::NotConnectedException, staruno::RuntimeException )
{
    ::osl::MutexGuard aGuard( m_aMutex );
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    sal_uInt64 nPos;
    FileBase::RC eError = m_pFile->getPos(nPos);
    if (eError != FileBase::E_None)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    sal_uInt64 nDummy = 0;
    eError = m_pFile->setPos(Pos_End, nDummy);
    if (eError != FileBase::E_None)
       throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    sal_uInt64 nAvailable;
    eError = m_pFile->getPos(nAvailable);
    if (eError != FileBase::E_None)
       throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));

    nAvailable = nAvailable - nPos;
    eError = m_pFile->setPos(Pos_Absolut, nPos);
    if (eError != FileBase::E_None)
       throw stario::NotConnectedException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
    return sal::static_int_cast< sal_Int32 >(
        std::max(nAvailable, sal::static_int_cast< sal_uInt64 >(SAL_MAX_INT32)));
}

//------------------------------------------------------------------------------
void SAL_CALL OSLInputStreamWrapper::closeInput() throw( stario::NotConnectedException, staruno::RuntimeException )
{
    if (!m_pFile)
        throw stario::NotConnectedException(::rtl::OUString(), static_cast<staruno::XWeak*>(this));

    m_pFile->close();
    if (m_bFileOwner)
        delete m_pFile;

    m_pFile = NULL;
}

/*************************************************************************/
// stario::XOutputStream
//------------------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::writeBytes(const staruno::Sequence< sal_Int8 >& aData) throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    sal_uInt64 nWritten;
    FileBase::RC eError = rFile.write(aData.getConstArray(),aData.getLength(), nWritten);
    if (eError != FileBase::E_None
        || nWritten != sal::static_int_cast< sal_uInt32 >(aData.getLength()))
    {
        throw stario::BufferSizeExceededException(::rtl::OUString(),static_cast<staruno::XWeak*>(this));
    }
}

//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::flush() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
}

//------------------------------------------------------------------
void SAL_CALL OSLOutputStreamWrapper::closeOutput() throw( stario::NotConnectedException, stario::BufferSizeExceededException, staruno::RuntimeException )
{
    rFile.close();
}

} // namespace comphelper

<|endoftext|>