<commit_before>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "INetRequest.h"

#include "common/RhoFile.h"
#include "common/RhodesAppBase.h"
#include "common/RhoFilePath.h"
#include "net/URI.h"

namespace rho {
namespace net {

void CNetRequestHolder::setRequest(INetRequestImpl* pReq)
{
    synchronized(m_mxReq)
    {
        m_pReq = pReq;

        if ( pReq )
        {
            m_bCancel = false;
            m_pReq->setSslVerifyPeer(m_sslVerifyPeer);
        }
    }
}

void CNetRequestHolder::cancel()
{
    synchronized(m_mxReq)
    {
        m_bCancel = true;
        if ( m_pReq != 0 )
            m_pReq->cancel();

        m_pReq = 0;
    }
}

boolean CNetRequestHolder::isCancelled()
{
    synchronized(m_mxReq)
    {
        return m_bCancel;
    }
}

/*static*/ String CNetRequestHolder::resolveUrl(const String& strUrl)
{
    return RHODESAPPBASE().canonicalizeRhoUrl(strUrl);
}

bool CNetRequestHolder::isInsideRequest() const
{
	return (m_pReq != 0);
}

CNetRequestWrapper::CNetRequestWrapper(INetRequestImpl* pImpl, CNetRequestHolder* pHolder) : m_pReqImpl(pImpl), m_pHolder(pHolder)
{
    if ( m_pHolder )
        m_pHolder->setRequest(pImpl);
}

CNetRequestWrapper::~CNetRequestWrapper()
{
    if ( m_pHolder )
        m_pHolder->setRequest(0);
}

INetResponse* CNetRequestWrapper::pullData(const String& strUrl, IRhoSession* oSession )
{
    return doRequest("GET",strUrl,String(),oSession,null);
}

INetResponse* CNetRequestWrapper::pushData(const String& strUrl, const String& strBody, IRhoSession* oSession)
{
    return doRequest("POST",strUrl,strBody,oSession,null);
}

INetResponse* CNetRequestWrapper::pullCookies(const String& strUrl, const String& strBody, IRhoSession* oSession)
{
    INetResponse* pResp = doRequest("POST", strUrl, strBody, oSession, null );
    if ( pResp->getRespCode() == 200 )
        pResp->setCharData(pResp->getCookies().c_str());

    return pResp;
}

INetResponse* CNetRequestWrapper::doRequest( const char* method, const String& strUrl, const String& strBody, IRhoSession* oSession, Hashtable<String,String>* pHeaders )
{
    return m_pReqImpl->doRequest(method, strUrl, strBody, oSession, pHeaders );
}

INetResponse* CNetRequestWrapper::pushMultipartData(const String& strUrl, VectorPtr<CMultipartItem*>& arItems, IRhoSession* oSession, Hashtable<String,String>* pHeaders)
{
    return m_pReqImpl->pushMultipartData(strUrl, arItems, oSession, pHeaders);
}

INetResponse* CNetRequestWrapper::pushMultipartData(const String& strUrl, CMultipartItem& oItem, IRhoSession* oSession, Hashtable<String,String>* pHeaders)
{
    VectorPtr<CMultipartItem*> arItems;
    arItems.addElement(&oItem);

    INetResponse* pResp = pushMultipartData(strUrl, arItems, oSession, pHeaders);

    arItems[0] = 0; //do not delete item
    return pResp;
}

INetResponse* CNetRequestWrapper::pullFile(const String& strUrl, const String& strFilePath, IRhoSession* oSession, Hashtable<String,String>* pHeaders,bool overwriteFile,bool createFolders)
{
    if (!overwriteFile && common::CRhoFile::isFileExist(strFilePath.c_str())) {
        LOGC(WARNING,"Net") + "pullFile: " + strFilePath + " already exists, won't download since overwrite flag is not set";
        return m_pReqImpl->createEmptyNetResponse();
    }

    if ( createFolders ) {
        String targetDir = common::CFilePath(strFilePath).getFolderName();

        if ( !common::CRhoFile::isDirectory(targetDir.c_str()) ) {
            common::CRhoFile::recursiveCreateDir(targetDir.c_str(), "");
        }
    }

    String tmpfilename = strFilePath + ".rhodownload";
    String modfilename = strFilePath + ".modtime";

    common::CRhoFile tmpFile;
    common::CRhoFile::EOpenModes openMode = common::CRhoFile::OpenForWrite;

    Hashtable<String, String> h;
    ::getNetRequest().doRequest("HEAD", strUrl, "", oSession, &h );

    if ( h.containsKey("last-modified") )
    {
        if ( common::CRhoFile::isFileExist(modfilename.c_str()) ) {
            String modDate;
            common::CRhoFile fModDate;
            if ( fModDate.open(modfilename.c_str(), common::CRhoFile::OpenReadOnly)) {
                fModDate.readString(modDate);
                if (modDate == h.get("last-modified")) {
                    openMode = common::CRhoFile::OpenForAppend;
                }
            }
        } else {
            common::CRhoFile fModDate;
            if ( fModDate.open(modfilename.c_str(), common::CRhoFile::OpenForWrite) ) {
                const String& modDate = h.get("last-modified");
                fModDate.write((void*)modDate.c_str(), modDate.length());
            }
        }
    }

    if ( !tmpFile.open(tmpfilename.c_str(),openMode) )
    {
        LOGC(ERROR, "Net") + "pullFile: cannot create file :" + tmpfilename;
        return m_pReqImpl->createEmptyNetResponse();
    }

    INetResponse* pResp = m_pReqImpl->pullFile( strUrl, tmpFile, oSession, pHeaders );

    tmpFile.close();

    if ( (pResp->getRespCode() == 200) || (pResp->getRespCode() == 206) ) {
        if ( common::CRhoFile::renameFile( tmpfilename.c_str(), strFilePath.c_str() ) != 0 ) {
            LOGC(ERROR, "Net") + "pullFile: cannot rename file :" + tmpfilename + " to " + strFilePath;
        }

        common::CRhoFile::deleteFile(modfilename.c_str());
    }

    return pResp;
}

String CNetRequestWrapper::resolveUrl(const String& strUrl)
{
    return RHODESAPPBASE().canonicalizeRhoUrl(strUrl);
}

}
}

rho::net::CNetRequestWrapper getNetRequest(rho::net::CNetRequestHolder* pHolder/* = 0*/)
{
    return rho::net::CNetRequestWrapper( rho_get_RhoClassFactory()->createNetRequestImpl(), pHolder );
}
<commit_msg>don't request HEAD if overwriting file.<commit_after>/*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/

#include "INetRequest.h"

#include "common/RhoFile.h"
#include "common/RhodesAppBase.h"
#include "common/RhoFilePath.h"
#include "net/URI.h"

namespace rho {
namespace net {

void CNetRequestHolder::setRequest(INetRequestImpl* pReq)
{
    synchronized(m_mxReq)
    {
        m_pReq = pReq;

        if ( pReq )
        {
            m_bCancel = false;
            m_pReq->setSslVerifyPeer(m_sslVerifyPeer);
        }
    }
}

void CNetRequestHolder::cancel()
{
    synchronized(m_mxReq)
    {
        m_bCancel = true;
        if ( m_pReq != 0 )
            m_pReq->cancel();

        m_pReq = 0;
    }
}

boolean CNetRequestHolder::isCancelled()
{
    synchronized(m_mxReq)
    {
        return m_bCancel;
    }
}

/*static*/ String CNetRequestHolder::resolveUrl(const String& strUrl)
{
    return RHODESAPPBASE().canonicalizeRhoUrl(strUrl);
}

bool CNetRequestHolder::isInsideRequest() const
{
	return (m_pReq != 0);
}

CNetRequestWrapper::CNetRequestWrapper(INetRequestImpl* pImpl, CNetRequestHolder* pHolder) : m_pReqImpl(pImpl), m_pHolder(pHolder)
{
    if ( m_pHolder )
        m_pHolder->setRequest(pImpl);
}

CNetRequestWrapper::~CNetRequestWrapper()
{
    if ( m_pHolder )
        m_pHolder->setRequest(0);
}

INetResponse* CNetRequestWrapper::pullData(const String& strUrl, IRhoSession* oSession )
{
    return doRequest("GET",strUrl,String(),oSession,null);
}

INetResponse* CNetRequestWrapper::pushData(const String& strUrl, const String& strBody, IRhoSession* oSession)
{
    return doRequest("POST",strUrl,strBody,oSession,null);
}

INetResponse* CNetRequestWrapper::pullCookies(const String& strUrl, const String& strBody, IRhoSession* oSession)
{
    INetResponse* pResp = doRequest("POST", strUrl, strBody, oSession, null );
    if ( pResp->getRespCode() == 200 )
        pResp->setCharData(pResp->getCookies().c_str());

    return pResp;
}

INetResponse* CNetRequestWrapper::doRequest( const char* method, const String& strUrl, const String& strBody, IRhoSession* oSession, Hashtable<String,String>* pHeaders )
{
    return m_pReqImpl->doRequest(method, strUrl, strBody, oSession, pHeaders );
}

INetResponse* CNetRequestWrapper::pushMultipartData(const String& strUrl, VectorPtr<CMultipartItem*>& arItems, IRhoSession* oSession, Hashtable<String,String>* pHeaders)
{
    return m_pReqImpl->pushMultipartData(strUrl, arItems, oSession, pHeaders);
}

INetResponse* CNetRequestWrapper::pushMultipartData(const String& strUrl, CMultipartItem& oItem, IRhoSession* oSession, Hashtable<String,String>* pHeaders)
{
    VectorPtr<CMultipartItem*> arItems;
    arItems.addElement(&oItem);

    INetResponse* pResp = pushMultipartData(strUrl, arItems, oSession, pHeaders);

    arItems[0] = 0; //do not delete item
    return pResp;
}

INetResponse* CNetRequestWrapper::pullFile(const String& strUrl, const String& strFilePath, IRhoSession* oSession, Hashtable<String,String>* pHeaders,bool overwriteFile,bool createFolders)
{
    if (!overwriteFile && common::CRhoFile::isFileExist(strFilePath.c_str())) {
        LOGC(WARNING,"Net") + "pullFile: " + strFilePath + " already exists, won't download since overwrite flag is not set";
        return m_pReqImpl->createEmptyNetResponse();
    }

    if ( createFolders ) {
        String targetDir = common::CFilePath(strFilePath).getFolderName();

        if ( !common::CRhoFile::isDirectory(targetDir.c_str()) ) {
            common::CRhoFile::recursiveCreateDir(targetDir.c_str(), "");
        }
    }

    String tmpfilename = strFilePath + ".rhodownload";
    String modfilename = strFilePath + ".modtime";

    common::CRhoFile tmpFile;
    common::CRhoFile::EOpenModes openMode = common::CRhoFile::OpenForWrite;

    //don't request headers of will overwrite anyway
    if (!overwriteFile) {
        Hashtable<String, String> h;
        ::getNetRequest().doRequest("HEAD", strUrl, "", oSession, &h );

        if ( h.containsKey("last-modified") )
        {
            if ( common::CRhoFile::isFileExist(modfilename.c_str()) ) {
                String modDate;
                common::CRhoFile fModDate;
                if ( fModDate.open(modfilename.c_str(), common::CRhoFile::OpenReadOnly)) {
                    fModDate.readString(modDate);
                    if (modDate == h.get("last-modified")) {
                        openMode = common::CRhoFile::OpenForAppend;
                    }
                }
            } else {
                common::CRhoFile fModDate;
                if ( fModDate.open(modfilename.c_str(), common::CRhoFile::OpenForWrite) ) {
                    const String& modDate = h.get("last-modified");
                    fModDate.write((void*)modDate.c_str(), modDate.length());
                }
            }
        }
    }

    if ( !tmpFile.open(tmpfilename.c_str(),openMode) )
    {
        LOGC(ERROR, "Net") + "pullFile: cannot create file :" + tmpfilename;
        return m_pReqImpl->createEmptyNetResponse();
    }

    INetResponse* pResp = m_pReqImpl->pullFile( strUrl, tmpFile, oSession, pHeaders );

    tmpFile.close();

    if ( (pResp->getRespCode() == 200) || (pResp->getRespCode() == 206) ) {
        if ( common::CRhoFile::renameFile( tmpfilename.c_str(), strFilePath.c_str() ) != 0 ) {
            LOGC(ERROR, "Net") + "pullFile: cannot rename file :" + tmpfilename + " to " + strFilePath;
        }

        common::CRhoFile::deleteFile(modfilename.c_str());
    }

    return pResp;
}

String CNetRequestWrapper::resolveUrl(const String& strUrl)
{
    return RHODESAPPBASE().canonicalizeRhoUrl(strUrl);
}

}
}

rho::net::CNetRequestWrapper getNetRequest(rho::net::CNetRequestHolder* pHolder/* = 0*/)
{
    return rho::net::CNetRequestWrapper( rho_get_RhoClassFactory()->createNetRequestImpl(), pHolder );
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: postgisfs.cc 34 2005-04-04 13:27:23Z pavlenko $

#include <boost/lexical_cast.hpp>
#include <boost/scoped_array.hpp>
#include <boost/algorithm/string.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include "postgis.hpp"
#include <sstream>

using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::trim;
using std::string;
using mapnik::Feature;
using mapnik::geometry2d;
using mapnik::byte;
using mapnik::geometry_utils;

std::string numeric2string(const char* buf)
{
   int16_t ndigits = int2net(buf);
   int16_t weight  = int2net(buf+2);
   int16_t sign    = int2net(buf+4);
   int16_t dscale  = int2net(buf+6);

   boost::scoped_array<int16_t> digits(new int16_t[ndigits]);
   for (int n=0; n < ndigits ;++n)
   {
      digits[n] = int2net(buf+8+n*2);
   }

   std::ostringstream ss;

   if (sign == 0x4000) ss << "-";

   int i = std::max(weight,int16_t(0));
   int d = 0;
   while ( i >= 0)
   {
      if (i <= weight && d < ndigits)
         ss <<  digits[d++];
      else
         ss <<  '0';
      i--;
   }
   if (dscale > 0)
   {
      ss << '.';
      while ( i >= -dscale)
      {
         if (i <= weight && d < ndigits)
            ss <<  digits[d++];
         i--;
      }
   }
   return ss.str();
}

postgis_featureset::postgis_featureset(boost::shared_ptr<IResultSet> const& rs,
                                       std::string const& encoding,
                                       bool multiple_geometries,
                                       unsigned num_attrs=0)
    : rs_(rs),
      multiple_geometries_(multiple_geometries),
      num_attrs_(num_attrs),
      tr_(new transcoder(encoding)),
      totalGeomSize_(0),
      count_(0)  {}

feature_ptr postgis_featureset::next()
{
    if (rs_->next())
    {
        feature_ptr feature(new Feature(count_));
        int size=rs_->getFieldLength(0);
        const char *data = rs_->getValue(0);
        geometry_utils::from_wkb(*feature,data,size,multiple_geometries_);
        totalGeomSize_+=size;

        for (unsigned pos=1;pos<num_attrs_+1;++pos)
        {
           std::string name = rs_->getFieldName(pos);

           if (!rs_->isNull(pos))
           {
              const char* buf=rs_->getValue(pos);
              int oid = rs_->getTypeOID(pos);

              if (oid==16) //bool
              {
                 boost::put(*feature,name,buf[0] != 0);
              }
              else if (oid==23) //int4
              {
                 int val = int4net(buf);
                 boost::put(*feature,name,val);
              }
              else if (oid==21) //int2
              {
                 int val = int2net(buf);
                 boost::put(*feature,name,val);
              }
              else if (oid == 700) // float4
              {
                 float val;
                 float4net(val,buf);
                 boost::put(*feature,name,val);
              }
              else if (oid == 701) // float8
              {
                 double val;
                 float8net(val,buf);
                 boost::put(*feature,name,val);
              }
              else if (oid==25 || oid==1042 || oid==1043) // text or bpchar or varchar
              {
                 //std::string str(buf);
                 //trim(str);
                 //std::wstring wstr = tr_->transcode(str);
                 UnicodeString ustr = tr_->transcode(buf);
                 boost::put(*feature,name,ustr);
              }
              else if (oid == 1700) // numeric
              {
                 std::string str = numeric2string(buf);
                 try
                 {
                    double val = boost::lexical_cast<double>(str);
                    boost::put(*feature,name,val);
                 }
                 catch (boost::bad_lexical_cast & ex)
                 {
                    std::clog << ex.what() << "\n";
                 }
              }
              else
              {
#ifdef MAPNIK_DEBUG
                 std::clog << "uknown OID = " << oid << " FIXME \n";
#endif
              }
           }
        }
        ++count_;
        return feature;
    }
    else
    {
        rs_->close();
        return feature_ptr();
    }
}

postgis_featureset::~postgis_featureset()
{
    rs_->close();
}
<commit_msg>+ trim bpchar type <commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: postgisfs.cc 34 2005-04-04 13:27:23Z pavlenko $

#include <boost/lexical_cast.hpp>
#include <boost/scoped_array.hpp>
#include <boost/algorithm/string.hpp>
#include <mapnik/global.hpp>
#include <mapnik/wkb.hpp>
#include <mapnik/unicode.hpp>
#include "postgis.hpp"
#include <sstream>

using boost::lexical_cast;
using boost::bad_lexical_cast;
using boost::trim_copy;
using std::string;
using mapnik::Feature;
using mapnik::geometry2d;
using mapnik::byte;
using mapnik::geometry_utils;

std::string numeric2string(const char* buf)
{
   int16_t ndigits = int2net(buf);
   int16_t weight  = int2net(buf+2);
   int16_t sign    = int2net(buf+4);
   int16_t dscale  = int2net(buf+6);

   boost::scoped_array<int16_t> digits(new int16_t[ndigits]);
   for (int n=0; n < ndigits ;++n)
   {
      digits[n] = int2net(buf+8+n*2);
   }

   std::ostringstream ss;

   if (sign == 0x4000) ss << "-";

   int i = std::max(weight,int16_t(0));
   int d = 0;
   while ( i >= 0)
   {
      if (i <= weight && d < ndigits)
         ss <<  digits[d++];
      else
         ss <<  '0';
      i--;
   }
   if (dscale > 0)
   {
      ss << '.';
      while ( i >= -dscale)
      {
         if (i <= weight && d < ndigits)
            ss <<  digits[d++];
         i--;
      }
   }
   return ss.str();
}

postgis_featureset::postgis_featureset(boost::shared_ptr<IResultSet> const& rs,
                                       std::string const& encoding,
                                       bool multiple_geometries,
                                       unsigned num_attrs=0)
    : rs_(rs),
      multiple_geometries_(multiple_geometries),
      num_attrs_(num_attrs),
      tr_(new transcoder(encoding)),
      totalGeomSize_(0),
      count_(0)  {}

feature_ptr postgis_featureset::next()
{
    if (rs_->next())
    {
        feature_ptr feature(new Feature(count_));
        int size=rs_->getFieldLength(0);
        const char *data = rs_->getValue(0);
        geometry_utils::from_wkb(*feature,data,size,multiple_geometries_);
        totalGeomSize_+=size;

        for (unsigned pos=1;pos<num_attrs_+1;++pos)
        {
           std::string name = rs_->getFieldName(pos);

           if (!rs_->isNull(pos))
           {
              const char* buf=rs_->getValue(pos);
              int oid = rs_->getTypeOID(pos);

              if (oid==16) //bool
              {
                 boost::put(*feature,name,buf[0] != 0);
              }
              else if (oid==23) //int4
              {
                 int val = int4net(buf);
                 boost::put(*feature,name,val);
              }
              else if (oid==21) //int2
              {
                 int val = int2net(buf);
                 boost::put(*feature,name,val);
              }
              else if (oid == 700) // float4
              {
                 float val;
                 float4net(val,buf);
                 boost::put(*feature,name,val);
              }
              else if (oid == 701) // float8
              {
                 double val;
                 float8net(val,buf);
                 boost::put(*feature,name,val);
              }
              else if (oid==25 || oid==1043) // text or varchar
              {
                 UnicodeString ustr = tr_->transcode(buf);
                 boost::put(*feature,name,ustr);
              }
              else if (oid==1042)
              {
                 UnicodeString ustr = tr_->transcode(trim_copy(string(buf)).c_str()); // bpchar
                 boost::put(*feature,name,ustr);
              }
              else if (oid == 1700) // numeric
              {
                 std::string str = numeric2string(buf);
                 try
                 {
                    double val = boost::lexical_cast<double>(str);
                    boost::put(*feature,name,val);
                 }
                 catch (boost::bad_lexical_cast & ex)
                 {
                    std::clog << ex.what() << "\n";
                 }
              }
              else
              {
#ifdef MAPNIK_DEBUG
                 std::clog << "uknown OID = " << oid << " FIXME \n";
#endif
              }
           }
        }
        ++count_;
        return feature;
    }
    else
    {
        rs_->close();
        return feature_ptr();
    }
}

postgis_featureset::~postgis_featureset()
{
    rs_->close();
}
<|endoftext|>


<commit_before>#include "../include/scene.hpp"

////////////////////////////////////////////////////////////////////////////////

scene::scene(const double screen_w, const double screen_h, const uint map_size, const double tiles_separation, const double map_separation):
    tile_map_(map_size, tiles_separation),
    map_separation_(map_separation),
    screen_w_(screen_w),
    screen_h_(screen_h),
    map_size_(map_size),
    inc_x_(0),
    inc_y_(0),
    zoom_(1),
    show_menu_(true),
    isplaying_(false),
    istracking_(false),
    esc_was_pressed_(false),

    restart_("images/restart.png"),
    play_("images/play_disabled.png"),
    random_("images/random.png"),
    step_("images/step.png"),
    tracking_("images/tracking_disabled.png"),

    quit_("QUIT", default_animation_time_),

    algorithm_("Algorithm  ", {"AAA", "BBBB", "CCCC"}, "images/larrow.png"),

    width_("Grid width ", "images/larrow.png", 1, 100),
    height_("Grid height", "images/larrow.png", 1, 100),

    speed_(scroll::VERTICAL),
    obstacles_(scroll::HORIZONTAL)
{
    resize(screen_w_, screen_h_);
}

////////////////////////////////////////////////////////////////////////////////

scene::~scene()
{}

////////////////////////////////////////////////////////////////////////////////

void scene::generate(const uint rivers, const uint min_size_river, const bool accumulative_rivers)
{
    tile_map_.generate(rivers,min_size_river,accumulative_rivers);
}

////////////////////////////////////////////////////////////////////////////////

void scene::draw()
{
    std::vector<ALLEGRO_VERTEX> vertices;

    double cx = screen_w_/2.0 + inc_x_;
    double cy = screen_h_/2.0 + inc_y_;

    static double zoom = 1; // TODO mouse inside
    zoom = mouse.getZ()*0.1 + 1;

    // GET VERTICES
    if (!show_menu_)
        tile_map_.appendVertices(vertices, cx, cy, screen_h_*zoom, screen_w_-50, screen_h_);

    // CLEAR
    al_clear_to_color(BACKGROUND_COLOR);

    // LOCK
    al_lock_bitmap(al_get_target_bitmap(), ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READWRITE );

    // DRAW
    if (!show_menu_)
    {
        al_draw_prim(vertices.data(), nullptr, nullptr, 0, vertices.size(), ALLEGRO_PRIM_TRIANGLE_LIST);
        al_draw_filled_rectangle(screen_w_-60, 0, screen_w_, screen_h_, PURE_WHITE);
    }

    // UNLOCK
    al_unlock_bitmap(al_get_target_bitmap());

    // MENU
    if (show_menu_)
        drawMenu();
    else
        drawSimMenu(vertices.size()/3);

    // ESC KEY
    if (keysPress[ALLEGRO_KEY_ESCAPE])
        esc_was_pressed_ = true;
    else if (esc_was_pressed_)
    {
        show_menu_ = !show_menu_;
        esc_was_pressed_ = false;
    }

}

////////////////////////////////////////////////////////////////////////////////

void scene::drawSimMenu(const uint triangles)
{
    double speed = speed_.getValue();

    if (play_.wasPressed())
        isplaying_ = !isplaying_;

    if (tracking_.wasPressed())
        istracking_ = !istracking_;

    if (speed < 0.001)
        isplaying_ = false;

    tracking_.setImage(istracking_ ? "images/tracking.png" : "images/tracking_disabled.png");
    step_.setImage(speed < 0.001 ? "images/step.png" : "images/step_disabled.png");
    if (speed > 0.001)
        play_.setImage(isplaying_ ? "images/pause.png" : "images/play.png");
    else
        play_.setImage("images/play_disabled.png");

    tracking_.draw();
    restart_.draw();
    step_.draw();
    play_.draw();
    random_.draw();
    speed_.draw();

    if (restart_.mouseOver()    ||
        play_.mouseOver() ||
        random_.mouseOver()  ||
        step_.mouseOver()       ||
        tracking_.mouseOver() )

        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_LINK);
    else
        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);

    // TEXT & DEBG
    al_draw_text(caviar_font_16, BLACK, 100, 10,ALLEGRO_ALIGN_LEFT, ("Triangles: "+std::to_string(triangles)).c_str());
    displayFPS(caviar_font_16);
}

////////////////////////////////////////////////////////////////////////////////

void scene::drawMenu()
{
    obstacles_.draw();
    quit_.draw();
    algorithm_.draw();
    width_.draw();
    height_.draw();

    al_draw_text(caviar_font_16, BLACK, 150, 420,ALLEGRO_ALIGN_LEFT, (std::to_string(int(obstacles_.getValue()*100))+"% Obstacles").c_str());

    if (quit_.mouseOver() || algorithm_.mouseOverArrow() || width_.mouseOverArrow() || height_.mouseOverArrow())
        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_LINK);
    else
        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);

    if (quit_.wasPressed())
        quit = true;
}

////////////////////////////////////////////////////////////////////////////////

void scene::update()
{
    if (show_menu_)
    {
        obstacles_.update();
        quit_.update();
        algorithm_.update();
        width_.update();
        height_.update();
    }
    else
    {
        restart_.update();
        play_.update();
        random_.update();
        speed_.update();
        step_.update();
    }
}

////////////////////////////////////////////////////////////////////////////////

void scene::moveX(const double x)
{
    inc_x_ += x;
}

////////////////////////////////////////////////////////////////////////////////

void scene::moveY(const double y)
{
    inc_y_ += y;
}

////////////////////////////////////////////////////////////////////////////////

void scene::resize(const double w, const double h)
{
    screen_w_ = w;
    screen_h_ = h;

    width_.moveTo(150, 130);
    height_.moveTo(150, 220);
    algorithm_.moveTo(150, 310);
    obstacles_.moveTo(150, 400, screen_w_-300, 5);
    quit_.moveTo(screen_w_-120, screen_h_-70, 100, 50);

    speed_.moveTo(  screen_w_-30, 50, 5, screen_h_-220);
    tracking_.moveTo(  screen_w_-46, 10           , 40, 40);
    step_.moveTo(      screen_w_-45, screen_h_-160, 40, 40);
    play_.moveTo(screen_w_-45, screen_h_-120, 40, 40);
    restart_.moveTo(   screen_w_-45, screen_h_-80 , 40, 40);
    random_.moveTo( screen_w_-45, screen_h_-40 , 40, 40);
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Reformatted scene<commit_after>#include "../include/scene.hpp"

////////////////////////////////////////////////////////////////////////////////

scene::scene(const double screen_w, const double screen_h, const uint map_size, const double tiles_separation, const double map_separation):
    tile_map_(map_size, tiles_separation),
    map_separation_(map_separation),
    screen_w_(screen_w),
    screen_h_(screen_h),
    map_size_(map_size),
    inc_x_(0),
    inc_y_(0),
    zoom_(1),
    show_menu_(false),
    isplaying_(false),
    istracking_(false),
    esc_was_pressed_(false),

    restart_("images/restart.png"),
    play_("images/play_disabled.png"),
    random_("images/random.png"),
    step_("images/step.png"),
    tracking_("images/tracking_disabled.png"),

    quit_("QUIT", default_animation_time_),

    algorithm_("Algorithm  ", {"AAA", "BBBB", "CCCC"}, "images/larrow.png"),

    width_("Grid width ", "images/larrow.png", 1, 100),
    height_("Grid height", "images/larrow.png", 1, 100),

    speed_(scroll::VERTICAL),
    obstacles_(scroll::HORIZONTAL)
{
    resize(screen_w_, screen_h_);
}

////////////////////////////////////////////////////////////////////////////////

scene::~scene()
{}

////////////////////////////////////////////////////////////////////////////////

void scene::generate(const uint rivers, const uint min_size_river, const bool accumulative_rivers)
{
    tile_map_.generate(rivers,min_size_river,accumulative_rivers);
}

////////////////////////////////////////////////////////////////////////////////

void scene::draw()
{
    std::vector<ALLEGRO_VERTEX> vertices;

    double cx = screen_w_/2.0 + inc_x_;
    double cy = screen_h_/2.0 + inc_y_;

    static double zoom = 1; // TODO mouse inside
    zoom = mouse.getZ()*0.1 + 1;

    // CLEAR
    al_clear_to_color(BACKGROUND_COLOR);

    // LOCK
    al_lock_bitmap(al_get_target_bitmap(), ALLEGRO_PIXEL_FORMAT_ANY, ALLEGRO_LOCK_READWRITE );

    // DRAW
    if (!show_menu_)
    {
        tile_map_.appendVertices(vertices, cx, cy, screen_h_*zoom, screen_w_-50, screen_h_);
        al_draw_prim(vertices.data(), nullptr, nullptr, 0, vertices.size(), ALLEGRO_PRIM_TRIANGLE_LIST);
        al_draw_filled_rectangle(screen_w_-60, 0, screen_w_, screen_h_, PURE_WHITE);
    }

    // UNLOCK
    al_unlock_bitmap(al_get_target_bitmap());

    // MENU
    if (show_menu_)
        drawMenu();
    else
        drawSimMenu(vertices.size()/3);

    // ESC KEY
    if (keysPress[ALLEGRO_KEY_ESCAPE])
        esc_was_pressed_ = true;
    else if (esc_was_pressed_)
    {
        show_menu_ = !show_menu_;
        esc_was_pressed_ = false;
    }

}

////////////////////////////////////////////////////////////////////////////////

void scene::drawSimMenu(const uint triangles)
{
    tracking_.draw();
    restart_.draw();
    step_.draw();
    play_.draw();
    random_.draw();
    speed_.draw();

    if (restart_.mouseOver()    ||
        play_.mouseOver() ||
        random_.mouseOver()  ||
        step_.mouseOver()       ||
        tracking_.mouseOver() )

        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_LINK);
    else
        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);

    // TEXT & DEBUG
    al_draw_text(caviar_font_16, BLACK, 100, 10,ALLEGRO_ALIGN_LEFT, ("Triangles: "+std::to_string(triangles)).c_str());
    displayFPS(caviar_font_16);
}

////////////////////////////////////////////////////////////////////////////////

void scene::drawMenu()
{
    obstacles_.draw();
    quit_.draw();
    algorithm_.draw();
    width_.draw();
    height_.draw();

    if (quit_.mouseOver() || algorithm_.mouseOverArrow() || width_.mouseOverArrow() || height_.mouseOverArrow())
        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_LINK);
    else
        mouse.setCursor(ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);

    // TEXT & DEBG
    al_draw_text(caviar_font_16, BLACK, 150, 420,ALLEGRO_ALIGN_LEFT, (std::to_string(int(obstacles_.getValue()*100))+"% Obstacles").c_str());
}

////////////////////////////////////////////////////////////////////////////////

void scene::update()
{
    if (show_menu_)
    {
        obstacles_.update();
        quit_.update();
        algorithm_.update();
        width_.update();
        height_.update();

        if (quit_.wasPressed()) quit = true;
    }
    else
    {
        restart_.update();
        play_.update();
        random_.update();
        speed_.update();
        step_.update();

        double speed = speed_.getValue();

        if (play_.wasPressed()    ) isplaying_  = !isplaying_;
        if (tracking_.wasPressed()) istracking_ = !istracking_;
        if (speed < 0.001         ) isplaying_  = false;

        tracking_.setImage(istracking_   ? "images/tracking.png" : "images/tracking_disabled.png");
        step_.setImage(speed < 0.001 ? "images/step.png" : "images/step_disabled.png");

        if (speed > 0.001)
            play_.setImage(isplaying_ ? "images/pause.png" : "images/play.png");
        else
            play_.setImage("images/play_disabled.png");
    }
}

////////////////////////////////////////////////////////////////////////////////

void scene::moveX(const double x)
{
    inc_x_ += x;
}

////////////////////////////////////////////////////////////////////////////////

void scene::moveY(const double y)
{
    inc_y_ += y;
}

////////////////////////////////////////////////////////////////////////////////

void scene::resize(const double w, const double h)
{
    screen_w_ = w;
    screen_h_ = h;

    width_.moveTo(150, 130);
    height_.moveTo(150, 220);
    algorithm_.moveTo(150, 310);

    obstacles_.moveTo(150, 400, screen_w_-300, 5);
    quit_.moveTo(screen_w_-120, screen_h_-70, 100, 50);
    speed_.moveTo(screen_w_-30, 50, 5, screen_h_-220);
    tracking_.moveTo(screen_w_-46, 10, 40, 40);
    step_.moveTo(screen_w_-45, screen_h_-160, 40, 40);
    play_.moveTo(screen_w_-45, screen_h_-120, 40, 40);
    restart_.moveTo(screen_w_-45, screen_h_-80 , 40, 40);
    random_.moveTo( screen_w_-45, screen_h_-40 , 40, 40);
}

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


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#ifndef GUARD_FORD_HPP
#define GUARD_FORD_HPP

#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <functional>
#include <miopen/par_for.hpp>
#include <miopen/each_args.hpp>
#include <miopen/returns.hpp>
#include <numeric>
#include <vector>

#ifdef __MINGW32__
#include <mingw.thread.h>
#else
#include <thread>
#endif

#include <future>

// An improved async, that doesn't block
template <class Function>
std::future<typename std::result_of<Function()>::type> detach_async(Function&& f)
{
    using result_type = typename std::result_of<Function()>::type;
    std::packaged_task<result_type()> task(std::forward<Function>(f));
    auto fut = task.get_future();
    std::thread(std::move(task)).detach();
    return std::move(fut);
}

template <class T, class Work>
auto then(std::future<T> f, Work w) -> std::future<decltype(w(f.get()))>
{
    return std::async(std::launch::deferred,
                      [=, f = std::move(f)]() mutable { return w(f.get()); });
}

struct joinable_thread : std::thread
{
    template <class... Xs>
    joinable_thread(Xs&&... xs) : std::thread(std::forward<Xs>(xs)...) // NOLINT
    {
    }

    joinable_thread& operator=(joinable_thread&& other) = default;
    joinable_thread(joinable_thread&& other)            = default;

    ~joinable_thread()
    {
        if(this->joinable())
            this->join();
    }
};

struct thread_factory
{
    template <class F>
    joinable_thread operator()(std::size_t& work, std::size_t n, std::size_t grainsize, F f) const
    {
        auto result = joinable_thread([=] {
            std::size_t start = work;
            std::size_t last  = std::min(n, work + grainsize);
            for(std::size_t i = start; i < last; i++)
            {
                f(i);
            }
        });
        work += grainsize;
        return result;
    }
};

using miopen::par_for; // NOLINT

template <class T>
struct ford_wrapper
{
    template <class... Ts>
    auto operator()(Ts... xs) const MIOPEN_RETURNS(std::bind(T{}, std::placeholders::_1, xs...));
};

// Multidimensional for loop
struct ford_impl
{
    template <class F>
    void operator()(F f) const
    {
        f();
    }

    template <class F, class T, class... Ts>
    void operator()(F f, T x, Ts... xs) const
    {
        // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914
        for(T i = 0; i < x; i++)
        {
            (*this)([&](Ts... is) { f(i, is...); }, xs...);
        }
    }
};

static constexpr ford_wrapper<ford_impl> ford{};

struct par_ford_impl
{
    template <class F, class... Ts>
    void operator()(F f, Ts... xs) const
    {
        using array_type = std::array<std::size_t, sizeof...(Ts)>;
        array_type lens  = {{static_cast<std::size_t>(xs)...}};
        array_type strides;
        strides.fill(1);
        std::partial_sum(
            lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<std::size_t>());
        auto size = std::accumulate(lens.begin(), lens.end(), 1, std::multiplies<std::size_t>());
        par_for(size, [&](std::size_t i) {
            array_type indices;
            std::transform(strides.begin(),
                           strides.end(),
                           lens.begin(),
                           indices.begin(),
                           [&](size_t stride, size_t len) { return (i / stride) % len; });
            miopen::unpack(f, indices);
        });
    }
};

static constexpr ford_wrapper<par_ford_impl> par_ford{};

#endif
<commit_msg>[HOST] fix a host static for loop bug (#1380)<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2017 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/
#ifndef GUARD_FORD_HPP
#define GUARD_FORD_HPP

#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <functional>
#include <miopen/par_for.hpp>
#include <miopen/each_args.hpp>
#include <miopen/returns.hpp>
#include <numeric>
#include <vector>

#ifdef __MINGW32__
#include <mingw.thread.h>
#else
#include <thread>
#endif

#include <future>

// An improved async, that doesn't block
template <class Function>
std::future<typename std::result_of<Function()>::type> detach_async(Function&& f)
{
    using result_type = typename std::result_of<Function()>::type;
    std::packaged_task<result_type()> task(std::forward<Function>(f));
    auto fut = task.get_future();
    std::thread(std::move(task)).detach();
    return std::move(fut);
}

template <class T, class Work>
auto then(std::future<T> f, Work w) -> std::future<decltype(w(f.get()))>
{
    return std::async(std::launch::deferred,
                      [=, f = std::move(f)]() mutable { return w(f.get()); });
}

struct joinable_thread : std::thread
{
    template <class... Xs>
    joinable_thread(Xs&&... xs) : std::thread(std::forward<Xs>(xs)...) // NOLINT
    {
    }

    joinable_thread& operator=(joinable_thread&& other) = default;
    joinable_thread(joinable_thread&& other)            = default;

    ~joinable_thread()
    {
        if(this->joinable())
            this->join();
    }
};

struct thread_factory
{
    template <class F>
    joinable_thread operator()(std::size_t& work, std::size_t n, std::size_t grainsize, F f) const
    {
        auto result = joinable_thread([=] {
            std::size_t start = work;
            std::size_t last  = std::min(n, work + grainsize);
            for(std::size_t i = start; i < last; i++)
            {
                f(i);
            }
        });
        work += grainsize;
        return result;
    }
};

using miopen::par_for; // NOLINT

template <class T>
struct ford_wrapper
{
    template <class... Ts>
    auto operator()(Ts... xs) const MIOPEN_RETURNS(std::bind(T{}, std::placeholders::_1, xs...));
};

// Multidimensional for loop
struct ford_impl
{
    template <class F>
    void operator()(F f) const
    {
        f();
    }

    template <class F, class T, class... Ts>
    void operator()(F f, T x, Ts... xs) const
    {
        // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55914
        for(T i = 0; i < x; i++)
        {
            (*this)([&](Ts... is) { f(i, is...); }, xs...);
        }
    }
};

static constexpr ford_wrapper<ford_impl> ford{};

struct par_ford_impl
{
    template <class F, class... Ts>
    void operator()(F f, Ts... xs) const
    {
        using array_type = std::array<std::size_t, sizeof...(Ts)>;
        array_type lens  = {{static_cast<std::size_t>(xs)...}};
        array_type strides;
        strides.fill(1);
        std::partial_sum(
            lens.rbegin(), lens.rend() - 1, strides.rbegin() + 1, std::multiplies<std::size_t>());
        auto size = std::accumulate(lens.begin(), lens.end(), static_cast<std::size_t>(1), std::multiplies<std::size_t>());
        par_for(size, [&](std::size_t i) {
            array_type indices;
            std::transform(strides.begin(),
                           strides.end(),
                           lens.begin(),
                           indices.begin(),
                           [&](size_t stride, size_t len) { return (i / stride) % len; });
            miopen::unpack(f, indices);
        });
    }
};

static constexpr ford_wrapper<par_ford_impl> par_ford{};

#endif
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TEST_GRIDS_HH
#define DUNE_GDT_TEST_GRIDS_HH

#include <dune/grid/sgrid.hh>
#include <dune/grid/yaspgrid.hh>
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/gdt/spaces/tools.hh>

using namespace Dune;
using namespace GDT;

#define SGRID_TYPES(dim) \
  typedef typename SpaceTools::LeafGridPartView<  SGrid< dim, dim >, false >::Type S ## dim ## dLeafGridPartType; \
  typedef typename SpaceTools::LevelGridPartView< SGrid< dim, dim >, false >::Type S ## dim ## dLevelGridPartType; \
  typedef typename SpaceTools::LeafGridPartView<  SGrid< dim, dim >, true  >::Type S ## dim ## dLeafGridViewType; \
  typedef typename SpaceTools::LevelGridPartView< SGrid< dim, dim >, true  >::Type S ## dim ## dLevelGridViewType;
SGRID_TYPES(1)
SGRID_TYPES(2)
SGRID_TYPES(3)
#undef SGRID_TYPES

#define YASPGRID_TYPES(dim) \
  typedef typename SpaceTools::LeafGridPartView<  YaspGrid< dim >, false >::Type Yasp ## dim ## dLeafGridPartType; \
  typedef typename SpaceTools::LevelGridPartView< YaspGrid< dim >, false >::Type Yasp ## dim ## dLevelGridPartType; \
  typedef typename SpaceTools::LeafGridPartView<  YaspGrid< dim >, true  >::Type Yasp ## dim ## dLeafGridViewType; \
  typedef typename SpaceTools::LevelGridPartView< YaspGrid< dim >, true  >::Type Yasp ## dim ## dLevelGridViewType;
YASPGRID_TYPES(1)
YASPGRID_TYPES(2)
YASPGRID_TYPES(3)
#undef YASPGRID_TYPES

#if HAVE_ALUGRID

typedef ALUGrid< 2, 2, simplex, conforming > AluConform2dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluConform2dGridType, false >::Type AluConform2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluConform2dGridType, false >::Type AluConform2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluConform2dGridType, true  >::Type AluConform2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluConform2dGridType, true  >::Type AluConform2dLevelGridViewType;

typedef ALUGrid< 2, 2, simplex, nonconforming > AluSimplex2dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex2dGridType, false >::Type AluSimplex2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex2dGridType, false >::Type AluSimplex2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex2dGridType, true  >::Type AluSimplex2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex2dGridType, true  >::Type AluSimplex2dLevelGridViewType;

typedef ALUGrid< 3, 3, simplex, nonconforming > AluSimplex3dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex3dGridType, false >::Type AluSimplex3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex3dGridType, false >::Type AluSimplex3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex3dGridType, true  >::Type AluSimplex3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex3dGridType, true  >::Type AluSimplex3dLevelGridViewType;

typedef ALUGrid< 2, 2, cube, nonconforming > AluCube2dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluCube2dGridType, false >::Type AluCube2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluCube2dGridType, false >::Type AluCube2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluCube2dGridType, true  >::Type AluCube2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluCube2dGridType, true  >::Type AluCube2dLevelGridViewType;

typedef ALUGrid< 3, 3, cube, nonconforming > AluCube3dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluCube3dGridType, false >::Type AluCube3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluCube3dGridType, false >::Type AluCube3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluCube3dGridType, true  >::Type AluCube3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluCube3dGridType, true  >::Type AluCube3dLevelGridViewType;

#endif // HAVE_ALUGRID

#endif // DUNE_GDT_TEST_GRIDS_HH
<commit_msg>[test.grids] add definition of AluConform3dGridType<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_TEST_GRIDS_HH
#define DUNE_GDT_TEST_GRIDS_HH

#include <dune/grid/sgrid.hh>
#include <dune/grid/yaspgrid.hh>
#if HAVE_ALUGRID
# include <dune/grid/alugrid.hh>
#endif

#include <dune/gdt/spaces/tools.hh>

using namespace Dune;
using namespace GDT;

#define SGRID_TYPES(dim) \
  typedef typename SpaceTools::LeafGridPartView<  SGrid< dim, dim >, false >::Type S ## dim ## dLeafGridPartType; \
  typedef typename SpaceTools::LevelGridPartView< SGrid< dim, dim >, false >::Type S ## dim ## dLevelGridPartType; \
  typedef typename SpaceTools::LeafGridPartView<  SGrid< dim, dim >, true  >::Type S ## dim ## dLeafGridViewType; \
  typedef typename SpaceTools::LevelGridPartView< SGrid< dim, dim >, true  >::Type S ## dim ## dLevelGridViewType;
SGRID_TYPES(1)
SGRID_TYPES(2)
SGRID_TYPES(3)
#undef SGRID_TYPES

#define YASPGRID_TYPES(dim) \
  typedef typename SpaceTools::LeafGridPartView<  YaspGrid< dim >, false >::Type Yasp ## dim ## dLeafGridPartType; \
  typedef typename SpaceTools::LevelGridPartView< YaspGrid< dim >, false >::Type Yasp ## dim ## dLevelGridPartType; \
  typedef typename SpaceTools::LeafGridPartView<  YaspGrid< dim >, true  >::Type Yasp ## dim ## dLeafGridViewType; \
  typedef typename SpaceTools::LevelGridPartView< YaspGrid< dim >, true  >::Type Yasp ## dim ## dLevelGridViewType;
YASPGRID_TYPES(1)
YASPGRID_TYPES(2)
YASPGRID_TYPES(3)
#undef YASPGRID_TYPES

#if HAVE_ALUGRID

typedef ALUGrid< 2, 2, simplex, conforming > AluConform2dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluConform2dGridType, false >::Type AluConform2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluConform2dGridType, false >::Type AluConform2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluConform2dGridType, true  >::Type AluConform2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluConform2dGridType, true  >::Type AluConform2dLevelGridViewType;

typedef ALUGrid< 3, 3, simplex, conforming > AluConform3dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluConform3dGridType, false >::Type AluConform3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluConform3dGridType, false >::Type AluConform3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluConform3dGridType, true  >::Type AluConform3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluConform3dGridType, true  >::Type AluConform3dLevelGridViewType;

typedef ALUGrid< 2, 2, simplex, nonconforming > AluSimplex2dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex2dGridType, false >::Type AluSimplex2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex2dGridType, false >::Type AluSimplex2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex2dGridType, true  >::Type AluSimplex2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex2dGridType, true  >::Type AluSimplex2dLevelGridViewType;

typedef ALUGrid< 3, 3, simplex, nonconforming > AluSimplex3dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex3dGridType, false >::Type AluSimplex3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex3dGridType, false >::Type AluSimplex3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluSimplex3dGridType, true  >::Type AluSimplex3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluSimplex3dGridType, true  >::Type AluSimplex3dLevelGridViewType;

typedef ALUGrid< 2, 2, cube, nonconforming > AluCube2dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluCube2dGridType, false >::Type AluCube2dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluCube2dGridType, false >::Type AluCube2dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluCube2dGridType, true  >::Type AluCube2dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluCube2dGridType, true  >::Type AluCube2dLevelGridViewType;

typedef ALUGrid< 3, 3, cube, nonconforming > AluCube3dGridType;
typedef typename SpaceTools::LeafGridPartView<  AluCube3dGridType, false >::Type AluCube3dLeafGridPartType;
typedef typename SpaceTools::LevelGridPartView< AluCube3dGridType, false >::Type AluCube3dLevelGridPartType;
typedef typename SpaceTools::LeafGridPartView<  AluCube3dGridType, true  >::Type AluCube3dLeafGridViewType;
typedef typename SpaceTools::LevelGridPartView< AluCube3dGridType, true  >::Type AluCube3dLevelGridViewType;

#endif // HAVE_ALUGRID

#endif // DUNE_GDT_TEST_GRIDS_HH
<|endoftext|>


<commit_before>/*
	Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin
	Copyright (C) 1998, 1999 by Jorrit Tyberghein
	Written by Nathaniel 'NooTe' Saint Martin
      Linux sound driver by Gert Steenssens <gsteenss@eps.agfa.be>

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Library General Public
	License as published by the Free Software Foundation; either
	version 2 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
	Library General Public License for more details.

	You should have received a copy of the GNU Library General Public
	License along with this library; if not, write to the Free
	Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#if defined(OS_BSD)
#  include <machine/soundcard.h>
#else
#  include <sys/soundcard.h>
#endif
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <signal.h>

#include "cssysdef.h"
#include "csutil/scf.h"
#include "ossdrv.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "isys/system.h"
#include "isound/listener.h"
#include "isound/source.h"
#include "isound/renderer.h"
#include "ivaria/reporter.h"
#include "iutil/objreg.h"

CS_IMPLEMENT_PLUGIN

SCF_IMPLEMENT_FACTORY(csSoundDriverOSS)

SCF_EXPORT_CLASS_TABLE(ossdrv)
  SCF_EXPORT_CLASS(csSoundDriverOSS,
    "crystalspace.sound.driver.oss",
    "OSS Sounddriver for Crystal Space")
SCF_EXPORT_CLASS_TABLE_END;

SCF_IMPLEMENT_IBASE(csSoundDriverOSS)
  SCF_IMPLEMENTS_INTERFACE(iSoundDriver)
  SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent)
SCF_IMPLEMENT_IBASE_END;

SCF_IMPLEMENT_EMBEDDED_IBASE (csSoundDriverOSS::eiComponent)
  SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END

int lasterr=0;
int gaudio;
bool inUse=false;
char *err[]=
{
  "no error", "get semaphore", "dec semaphore", "inc semaphore",
  "malloc shmptr", "shmget soundmem", "mark shared mem as removable",
  "mapping shared mem", "detaching shared mem", "msgsnd",
  "semget", "semctl", "get audio queue", "opening audio device",
  "setting samplesize", "setting mono/stereo",
  "setting frequence", "reading blocksize",
  "setting signalhandler", "setting timer", "set fragment size",
  "alloc soundbuffer"
};

#define err_alloc_soundbuffer	21
#define err_set_fragment_size 20
#define err_set_timer 19
#define err_set_handler 18
#define err_get_blocksize 17
#define err_set_frequence 16
#define err_set_stereo 15
#define err_set_samplesize 14
#define err_open_dsp 13
#define err_create_queue 12
#define err_semctl 11
#define err_semget 10
#define err_msgsnd 9
#define err_shm_unmap 8
#define err_shm_map 7
#define err_shmctl_remove 6
#define err_shmget_soundmem 5
#define err_malloc_shmptr 4
#define err_inc_sem 3
#define err_dec_sem 2
#define err_get_sem 1
#define err_no_err 0

bool AudioDeviceBlocked()
{
  // are there free fragments to fill in the soundbuffer ?
  audio_buf_info info;
  ioctl(gaudio, SNDCTL_DSP_GETOSPACE, &info);
  /* Thats what the OSS-specification has to say:
     Number of full fragments that can be read or written without
     blocking.Note that this field is reliable only when the
     application reads/writes full fragments at time.
  */
  return info.fragments == 0;
}

AudioDevice::AudioDevice()
{
  audio = -1;
}

bool AudioDevice::Open(int& frequency, bool& bit16, bool& stereo,
  int& fragments, int& block_size)
{
  int dsp_sample,dsp_stereo,dsp_speed;
  bool succ;

  dsp_speed  = frequency;
  dsp_stereo = stereo;
  dsp_sample = (bit16 ? 16 : 8);

  lasterr=err_open_dsp;
  audio = open(SOUND_DEVICE, O_WRONLY, 0);
  succ = audio != -1;

  if (succ) lasterr=err_set_samplesize;
  succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;

  if (succ) lasterr=err_set_stereo;
  succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;

  if (succ) lasterr=err_set_frequence;
  succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;

  if (succ)
  {
    unsigned int bytes_per_second;
    int frag_size; // fragment size
    int num_frag=0;  // number of fragments
    int hlp;

    // ok, now we know what our soundcard is capable of :) we close it, reopen
    // it and setting the blocksize appropriate for our needs
    close(audio);
    lasterr=err_open_dsp;
    audio = open(SOUND_DEVICE, O_WRONLY, 0);
    succ = audio != -1;
    gaudio = audio;
    // this amount of bytes we pump per second through the audio-device
    bytes_per_second = dsp_speed * (dsp_sample/8) * (dsp_stereo ? 2 : 1);

    // the OSS-specification adivises to use relativly small fragment-sizes
    // (the smallest possible is 256 byte)
    // lets use a fragmentsize of 8192 bytes
    frag_size = 13; // (2^13=8192);
    hlp = bytes_per_second >> frag_size;
    while (hlp)
    {
       num_frag++;
       hlp = hlp >> 1;
    }
//  num_frag++;
    fragments = 1 << num_frag;

    hlp = (num_frag << 16) | frag_size;
    if (succ) lasterr=err_set_fragment_size;
    succ = succ && ioctl (audio, SNDCTL_DSP_SETFRAGMENT, &hlp) != -1;

    if (succ) lasterr=err_set_samplesize;
    succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;

    if (succ) lasterr=err_set_stereo;
    succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;

    if (succ) lasterr=err_set_frequence;
    succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;

    if (succ)
    {
      block_size=8192;
      fprintf(stderr, "block_size: %d\n", block_size);
      frequency = dsp_speed;
      stereo = dsp_stereo;
      bit16 = (dsp_sample == 16 ? true : false);
    }
  }
  return succ;
}

void AudioDevice::Close()
{
  if (audio != -1)
  {
    // close audio device
    close(audio);
    audio = -1;
  }
}

void AudioDevice::Play(unsigned char *snddata, int len)
{
  write(audio, snddata, len);
}

static void* soundptr;

void isTime(int)
{
  iSoundRender *mysound=(iSoundRender*)soundptr;
  if (!AudioDeviceBlocked())
    mysound->MixingFunction();
}

bool csSoundDriverOSS::SetupTimer(int nTimesPerSecond)
{
  struct itimerval itime;
  struct timeval val;
  struct sigaction act;

  val.tv_usec= 1000 / nTimesPerSecond;
  val.tv_sec=0;

  itime.it_value=val;
  itime.it_interval=val;

  act.sa_handler = isTime;
  sigemptyset(&act.sa_mask);
  sigaddset(&act.sa_mask, SIGVTALRM);
  act.sa_flags = SA_NOCLDSTOP | SA_RESTART;

  // set static ptr because the timer handler needs it...
  soundptr=(void*)m_piSoundRender;

  /*
   * Set signal handling function.
   * LINUX-behavior: Dont use signal coz it resets after execution of
   * handlerfunction.  sigaction is a way to make it BSD-like.  NOTE: its not
   * POSIX setting sa_flags to SA_RESTART (from the man page)
   */
  lasterr=err_set_handler;
  bSignalInstalled = (sigaction (SIGVTALRM, &act, &oldact) == 0);

  if (bSignalInstalled) lasterr=err_set_timer;
  // set timer
  bTimerInstalled =
    bSignalInstalled && setitimer (ITIMER_VIRTUAL,&itime,&otime) != -1;
  return bTimerInstalled;
}

csSoundDriverOSS::csSoundDriverOSS(iBase *piBase)
{
  SCF_CONSTRUCT_IBASE(piBase);
  SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);
  object_reg = NULL;
  m_piSoundRender = NULL;
  memorysize = 0;
  memory = NULL;
  block_size=0;
  block = 0;
  fragments = 0;
  soundbuffer = NULL;
  bSignalInstalled = false;
  bTimerInstalled = false;
}

csSoundDriverOSS::~csSoundDriverOSS()
{
  // if (memory) delete [] memory;
}

bool csSoundDriverOSS::Open(iSoundRender *render, int frequency, bool bit16,
  bool stereo)
{
  csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,
  	"crystalspace.sound.oss",
    	"SoundDriver OSS selected");
  m_piSoundRender = render;
  m_bStereo = stereo;
  m_b16Bits = bit16;
  m_nFrequency = frequency;

  bool Active = device.Open(frequency,bit16,stereo, fragments, block_size);
  if (Active)
  {
    lasterr = err_alloc_soundbuffer;
    soundbuffer = new unsigned char[fragments * block_size];
    Active = (soundbuffer != NULL) && SetupTimer(fragments);
  }

  if (!Active)
  {
    perror(err[lasterr]);
    return false;
  }

  return true;
}

void csSoundDriverOSS::Close()
{
  if (bTimerInstalled) setitimer (ITIMER_VIRTUAL, &otime, NULL);
  if (bSignalInstalled) sigaction (SIGVTALRM, &oldact, NULL);
  if (soundbuffer) { delete soundbuffer; soundbuffer=NULL; }
  device.Close();
  memory=NULL;
  memorysize=0;
}

void csSoundDriverOSS::LockMemory(void **mem, int *memsize)
{
  *mem = &soundbuffer[block * block_size];
  *memsize = block_size;
}

void csSoundDriverOSS::UnlockMemory()
{
  // tell device to play this soundblock
  device.Play(&soundbuffer[block * block_size], block_size);
  block = (block+1) % fragments;
}

bool csSoundDriverOSS::IsHandleVoidSound() { return true; }
bool csSoundDriverOSS::IsBackground() { return true; }
bool csSoundDriverOSS::Is16Bits() { return  m_b16Bits; }
bool csSoundDriverOSS::IsStereo() { return m_bStereo; }
int csSoundDriverOSS::GetFrequency() { return m_nFrequency; }
<commit_msg>Patch for NetBSD from Jorge Acereda (al004046@anubis.uji.es).<commit_after>/*
	Copyright (C) 1998, 1999 by Nathaniel 'NooTe' Saint Martin
	Copyright (C) 1998, 1999 by Jorrit Tyberghein
	Written by Nathaniel 'NooTe' Saint Martin
      Linux sound driver by Gert Steenssens <gsteenss@eps.agfa.be>

	This library is free software; you can redistribute it and/or
	modify it under the terms of the GNU Library General Public
	License as published by the Free Software Foundation; either
	version 2 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
	Library General Public License for more details.

	You should have received a copy of the GNU Library General Public
	License along with this library; if not, write to the Free
	Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <signal.h>

#include "cssysdef.h"
#if defined(__NetBSD__)
#  include <soundcard.h>
#elif defined(OS_BSD)
#  include <machine/soundcard.h>
#else
#  include <sys/soundcard.h>
#endif
#include "csutil/scf.h"
#include "ossdrv.h"
#include "iutil/eventh.h"
#include "iutil/comp.h"
#include "isys/system.h"
#include "isound/listener.h"
#include "isound/source.h"
#include "isound/renderer.h"
#include "ivaria/reporter.h"
#include "iutil/objreg.h"

CS_IMPLEMENT_PLUGIN

SCF_IMPLEMENT_FACTORY(csSoundDriverOSS)

SCF_EXPORT_CLASS_TABLE(ossdrv)
  SCF_EXPORT_CLASS(csSoundDriverOSS,
    "crystalspace.sound.driver.oss",
    "OSS Sounddriver for Crystal Space")
SCF_EXPORT_CLASS_TABLE_END;

SCF_IMPLEMENT_IBASE(csSoundDriverOSS)
  SCF_IMPLEMENTS_INTERFACE(iSoundDriver)
  SCF_IMPLEMENTS_EMBEDDED_INTERFACE(iComponent)
SCF_IMPLEMENT_IBASE_END;

SCF_IMPLEMENT_EMBEDDED_IBASE (csSoundDriverOSS::eiComponent)
  SCF_IMPLEMENTS_INTERFACE (iComponent)
SCF_IMPLEMENT_EMBEDDED_IBASE_END

int lasterr=0;
int gaudio;
bool inUse=false;
char *err[]=
{
  "no error", "get semaphore", "dec semaphore", "inc semaphore",
  "malloc shmptr", "shmget soundmem", "mark shared mem as removable",
  "mapping shared mem", "detaching shared mem", "msgsnd",
  "semget", "semctl", "get audio queue", "opening audio device",
  "setting samplesize", "setting mono/stereo",
  "setting frequence", "reading blocksize",
  "setting signalhandler", "setting timer", "set fragment size",
  "alloc soundbuffer"
};

#define err_alloc_soundbuffer	21
#define err_set_fragment_size 20
#define err_set_timer 19
#define err_set_handler 18
#define err_get_blocksize 17
#define err_set_frequence 16
#define err_set_stereo 15
#define err_set_samplesize 14
#define err_open_dsp 13
#define err_create_queue 12
#define err_semctl 11
#define err_semget 10
#define err_msgsnd 9
#define err_shm_unmap 8
#define err_shm_map 7
#define err_shmctl_remove 6
#define err_shmget_soundmem 5
#define err_malloc_shmptr 4
#define err_inc_sem 3
#define err_dec_sem 2
#define err_get_sem 1
#define err_no_err 0

bool AudioDeviceBlocked()
{
  // are there free fragments to fill in the soundbuffer ?
  audio_buf_info info;
  ioctl(gaudio, SNDCTL_DSP_GETOSPACE, &info);
  /* Thats what the OSS-specification has to say:
     Number of full fragments that can be read or written without
     blocking.Note that this field is reliable only when the
     application reads/writes full fragments at time.
  */
  return info.fragments == 0;
}

AudioDevice::AudioDevice()
{
  audio = -1;
}

bool AudioDevice::Open(int& frequency, bool& bit16, bool& stereo,
  int& fragments, int& block_size)
{
  int dsp_sample,dsp_stereo,dsp_speed;
  bool succ;

  dsp_speed  = frequency;
  dsp_stereo = stereo;
  dsp_sample = (bit16 ? 16 : 8);

  lasterr=err_open_dsp;
  audio = open(SOUND_DEVICE, O_WRONLY, 0);
  succ = audio != -1;

  if (succ) lasterr=err_set_samplesize;
  succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;

  if (succ) lasterr=err_set_stereo;
  succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;

  if (succ) lasterr=err_set_frequence;
  succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;

  if (succ)
  {
    unsigned int bytes_per_second;
    int frag_size; // fragment size
    int num_frag=0;  // number of fragments
    int hlp;

    // ok, now we know what our soundcard is capable of :) we close it, reopen
    // it and setting the blocksize appropriate for our needs
    close(audio);
    lasterr=err_open_dsp;
    audio = open(SOUND_DEVICE, O_WRONLY, 0);
    succ = audio != -1;
    gaudio = audio;
    // this amount of bytes we pump per second through the audio-device
    bytes_per_second = dsp_speed * (dsp_sample/8) * (dsp_stereo ? 2 : 1);

    // the OSS-specification adivises to use relativly small fragment-sizes
    // (the smallest possible is 256 byte)
    // lets use a fragmentsize of 8192 bytes
    frag_size = 13; // (2^13=8192);
    hlp = bytes_per_second >> frag_size;
    while (hlp)
    {
       num_frag++;
       hlp = hlp >> 1;
    }
//  num_frag++;
    fragments = 1 << num_frag;

    hlp = (num_frag << 16) | frag_size;
    if (succ) lasterr=err_set_fragment_size;
    succ = succ && ioctl (audio, SNDCTL_DSP_SETFRAGMENT, &hlp) != -1;

    if (succ) lasterr=err_set_samplesize;
    succ = succ && ioctl(audio, SNDCTL_DSP_SAMPLESIZE, &dsp_sample) != -1;

    if (succ) lasterr=err_set_stereo;
    succ = succ && ioctl (audio, SNDCTL_DSP_STEREO, &dsp_stereo) != -1;

    if (succ) lasterr=err_set_frequence;
    succ = succ && ioctl (audio, SNDCTL_DSP_SPEED, &dsp_speed) != -1;

    if (succ)
    {
      block_size=8192;
      fprintf(stderr, "block_size: %d\n", block_size);
      frequency = dsp_speed;
      stereo = dsp_stereo;
      bit16 = (dsp_sample == 16 ? true : false);
    }
  }
  return succ;
}

void AudioDevice::Close()
{
  if (audio != -1)
  {
    // close audio device
    close(audio);
    audio = -1;
  }
}

void AudioDevice::Play(unsigned char *snddata, int len)
{
  write(audio, snddata, len);
}

static void* soundptr;

void isTime(int)
{
  iSoundRender *mysound=(iSoundRender*)soundptr;
  if (!AudioDeviceBlocked())
    mysound->MixingFunction();
}

bool csSoundDriverOSS::SetupTimer(int nTimesPerSecond)
{
  struct itimerval itime;
  struct timeval val;
  struct sigaction act;

  val.tv_usec= 1000 / nTimesPerSecond;
  val.tv_sec=0;

  itime.it_value=val;
  itime.it_interval=val;

  act.sa_handler = isTime;
  sigemptyset(&act.sa_mask);
  sigaddset(&act.sa_mask, SIGVTALRM);
  act.sa_flags = SA_NOCLDSTOP | SA_RESTART;

  // set static ptr because the timer handler needs it...
  soundptr=(void*)m_piSoundRender;

  /*
   * Set signal handling function.
   * LINUX-behavior: Dont use signal coz it resets after execution of
   * handlerfunction.  sigaction is a way to make it BSD-like.  NOTE: its not
   * POSIX setting sa_flags to SA_RESTART (from the man page)
   */
  lasterr=err_set_handler;
  bSignalInstalled = (sigaction (SIGVTALRM, &act, &oldact) == 0);

  if (bSignalInstalled) lasterr=err_set_timer;
  // set timer
  bTimerInstalled =
    bSignalInstalled && setitimer (ITIMER_VIRTUAL,&itime,&otime) != -1;
  return bTimerInstalled;
}

csSoundDriverOSS::csSoundDriverOSS(iBase *piBase)
{
  SCF_CONSTRUCT_IBASE(piBase);
  SCF_CONSTRUCT_EMBEDDED_IBASE(scfiComponent);
  object_reg = NULL;
  m_piSoundRender = NULL;
  memorysize = 0;
  memory = NULL;
  block_size=0;
  block = 0;
  fragments = 0;
  soundbuffer = NULL;
  bSignalInstalled = false;
  bTimerInstalled = false;
}

csSoundDriverOSS::~csSoundDriverOSS()
{
  // if (memory) delete [] memory;
}

bool csSoundDriverOSS::Open(iSoundRender *render, int frequency, bool bit16,
  bool stereo)
{
  csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,
  	"crystalspace.sound.oss",
    	"SoundDriver OSS selected");
  m_piSoundRender = render;
  m_bStereo = stereo;
  m_b16Bits = bit16;
  m_nFrequency = frequency;

  bool Active = device.Open(frequency,bit16,stereo, fragments, block_size);
  if (Active)
  {
    lasterr = err_alloc_soundbuffer;
    soundbuffer = new unsigned char[fragments * block_size];
    Active = (soundbuffer != NULL) && SetupTimer(fragments);
  }

  if (!Active)
  {
    perror(err[lasterr]);
    return false;
  }

  return true;
}

void csSoundDriverOSS::Close()
{
  if (bTimerInstalled) setitimer (ITIMER_VIRTUAL, &otime, NULL);
  if (bSignalInstalled) sigaction (SIGVTALRM, &oldact, NULL);
  if (soundbuffer) { delete soundbuffer; soundbuffer=NULL; }
  device.Close();
  memory=NULL;
  memorysize=0;
}

void csSoundDriverOSS::LockMemory(void **mem, int *memsize)
{
  *mem = &soundbuffer[block * block_size];
  *memsize = block_size;
}

void csSoundDriverOSS::UnlockMemory()
{
  // tell device to play this soundblock
  device.Play(&soundbuffer[block * block_size], block_size);
  block = (block+1) % fragments;
}

bool csSoundDriverOSS::IsHandleVoidSound() { return true; }
bool csSoundDriverOSS::IsBackground() { return true; }
bool csSoundDriverOSS::Is16Bits() { return  m_b16Bits; }
bool csSoundDriverOSS::IsStereo() { return m_bStereo; }
int csSoundDriverOSS::GetFrequency() { return m_nFrequency; }
<|endoftext|>


<commit_before>class Solution {
public:
    int mySqrt(int x) {
        if(x<0){
            return -1;
        }
        long long l = 0;
        long long r = x/2 + 1;

        while(l < r){
            long long mid = (l+r)/2;
            long long tmp = mid * mid;
            if(tmp == x) return mid;
            else if(tmp > x) r = mid -1;
            else l = mid + 1;
        }

        // not found a little
        long long temp=r*r;

        if(temp>x){
            return r-1;
        }else{
            return r;
        }
    }
};<commit_msg>fix code and look more generic<commit_after>class Solution {
public:
    int mySqrt(int x) {
        if(x<0){
            return -1;
        }
        long long l = 0;
        long long r = x/2 + 2;

        while(l < r){
            long long mid = (l+r)/2;
            long long tmp = mid * mid;
            if(tmp == x) return mid;
            else if(tmp > x) r = mid;
            else l = mid + 1;
        }

        // not found sqrt(x) directly. change a little bit
        // l is the upper_bount of sqrt(n)

        return l-1;
    }
};<|endoftext|>


<commit_before>#include "Falcon.h"

//Moose Includes
#include "Parser.h"
#include "Moose.h"
#include "Executioner.h"

// C++ include files
#include <iostream>

// libMesh includes
#include "perf_log.h"

PerfLog Moose::perf_log("Falcon");

 // Begin the main program.
int main (int argc, char** argv)
{
  Moose::perf_log.push("main()","Falcon");

  MooseInit init (argc, argv);

  srand(libMesh::processor_id());

  Falcon::registerObjects();

  Parser p;

  std::string input_filename = "";
  if ( Moose::command_line->search("-i") )
    input_filename = Moose::command_line->next(input_filename);
  else
    mooseError("Must specify an input file using -i");

  p.parse(input_filename);
  p.execute();

  if(!Moose::executioner)
    mooseError("Executioner not supplied!");

  Moose::executioner->setup();
  Moose::executioner->execute();

  Moose::perf_log.pop("main()","Falcon");
}
<commit_msg>add MooseSystem<commit_after>#include "Falcon.h"

//Moose Includes
#include "Parser.h"
#include "Moose.h"
#include "Executioner.h"
#include "MooseSystem.h"

// C++ include files
#include <iostream>

// libMesh includes
#include "perf_log.h"

PerfLog Moose::perf_log("Falcon");

 // Begin the main program.
int main (int argc, char** argv)
{
  Moose::perf_log.push("main()","Falcon");

  MooseInit init (argc, argv);

  MooseSystem moose_system;

  srand(libMesh::processor_id());

  Falcon::registerObjects();

  Parser p(moose_system);

  std::string input_filename = "";
  if ( Moose::command_line->search("-i") )
    input_filename = Moose::command_line->next(input_filename);
  else
    mooseError("Must specify an input file using -i");

  p.parse(input_filename);
  p.execute();

  if(!Moose::executioner)
    mooseError("Executioner not supplied!");

  Moose::executioner->setup();
  Moose::executioner->execute();

  Moose::perf_log.pop("main()","Falcon");
}
<|endoftext|>


<commit_before>#include "fs.h"
#include "../exception.h"
#include <iterator>
#include <fstream>
#include <boost/filesystem.hpp>

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>

using namespace dariadb::utils::fs;

namespace bi=boost::interprocess;

namespace dariadb{
    namespace  utils {
        namespace fs {
            std::list<std::string> ls(const std::string &path){
                std::list<boost::filesystem::path> result;
                std::list<std::string> s_result;
                std::copy(boost::filesystem::directory_iterator(path),
                          boost::filesystem::directory_iterator(),
                          std::back_inserter(result));

                for(boost::filesystem::path& it:result){
                    s_result.push_back(it.string());
                }
                return s_result;

            }

            std::list<std::string> ls(const std::string &path, const std::string &ext){
                std::list<boost::filesystem::path> result;
                std::list<std::string> s_result;

                std::copy(boost::filesystem::directory_iterator(path),
                          boost::filesystem::directory_iterator(),
                          std::back_inserter(result));

                // ext filter
                result.remove_if([&ext](boost::filesystem::path p) {
                    return p.extension().string() != ext;
                });

                for(boost::filesystem::path& it:result){
                    s_result.push_back(it.string());
                }
                return s_result;
            }

            bool rm(const std::string &rm_path){
                if (!boost::filesystem::exists(rm_path))
                    return true;
                try {
                    if (boost::filesystem::is_directory(rm_path)) {
                        boost::filesystem::path path_to_remove(rm_path);
                        for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove);
                             it != end_dir_it; ++it) {
                            if (!boost::filesystem::remove_all(it->path())) {
                                return false;
                            }
                        }
                    }
                    boost::filesystem::remove_all(rm_path);
                    return true;
                } catch (boost::filesystem::filesystem_error &ex) {
                    std::string msg = ex.what();
                    MAKE_EXCEPTION("utils::rm exception: " + msg);
                    throw;
                }
            }

            std::string filename(const std::string & fname){ // without ex
                boost::filesystem::path p(fname);
                return p.stem().string();
            }

            std::string parent_path(const std::string & fname){
                boost::filesystem::path p(fname);
                return p.parent_path().string();
            }

			std::string append_path(const std::string & p1, const std::string & p2) {
				boost::filesystem::path p(p1);
				p.append(p2);
				return p.string();
			}

			bool path_exists(const std::string & path)
			{
				return boost::filesystem::exists(path);
			}
			void mkdir(const std::string & path)
			{
				if (!boost::filesystem::exists(path)) {
					boost::filesystem::create_directory(path);
				}
			}
        }
    }
}
class MappedFile::Impl
{
public:
    Impl(){
        _closed=false;
        m_file=nullptr;
        m_region=nullptr;
    }

    ~Impl(){
        if(!_closed){
            close();
        }
    }

    static Impl*open(const std::string&path){
        auto result=new Impl();
        result->m_file = new bi::file_mapping(path.c_str(), bi::read_write);
        result->m_region = new bi::mapped_region(*(result->m_file), bi::read_write);
        return result;
    }

    static Impl*touch(const std::string&path, uint64_t size){
        try {
            bi::file_mapping::remove(path.c_str());
            std::filebuf fbuf;
            fbuf.open(path,
                      std::ios_base::in |
                      std::ios_base::out|
                      std::ios_base::trunc|
                      std::ios_base::binary);
            //Set the size
            fbuf.pubseekoff(size-1, std::ios_base::beg);
            fbuf.sputc(0);
            fbuf.close();
            return Impl::open(path);
        } catch (std::runtime_error &ex) {
            std::string what = ex.what();
            throw MAKE_EXCEPTION(ex.what());
        }

    }

    void close(){
        _closed=true;
        m_region->flush();
        delete m_region;
        delete m_file;
        m_region=nullptr;
        m_file=nullptr;
    }

    uint8_t* data(){
        return static_cast<uint8_t*>(m_region->get_address());
    }

protected:
    bool _closed;

    bi::file_mapping*m_file;
    bi::mapped_region*m_region;
};

MappedFile::MappedFile(Impl* im):_impl(im){

}

MappedFile::~MappedFile(){

}

MappedFile::MapperFile_ptr MappedFile::open(const std::string&path){
    auto impl_res=MappedFile::Impl::open(path);
    MappedFile::MapperFile_ptr  result{new MappedFile{impl_res}};
    return result;
}

MappedFile::MapperFile_ptr MappedFile::touch(const std::string&path, uint64_t size){
    auto impl_res=MappedFile::Impl::touch(path,size);
    MappedFile::MapperFile_ptr  result{new MappedFile{impl_res}};
    return result;
}

void MappedFile::close(){
    _impl->close();
}

uint8_t* MappedFile::data(){
    return _impl->data();
}
<commit_msg>fs append path build.<commit_after>#include "fs.h"
#include "../exception.h"
#include <iterator>
#include <fstream>
#include <boost/filesystem.hpp>

#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/mapped_region.hpp>

using namespace dariadb::utils::fs;

namespace bi=boost::interprocess;

namespace dariadb{
    namespace  utils {
        namespace fs {
            std::list<std::string> ls(const std::string &path){
                std::list<boost::filesystem::path> result;
                std::list<std::string> s_result;
                std::copy(boost::filesystem::directory_iterator(path),
                          boost::filesystem::directory_iterator(),
                          std::back_inserter(result));

                for(boost::filesystem::path& it:result){
                    s_result.push_back(it.string());
                }
                return s_result;

            }

            std::list<std::string> ls(const std::string &path, const std::string &ext){
                std::list<boost::filesystem::path> result;
                std::list<std::string> s_result;

                std::copy(boost::filesystem::directory_iterator(path),
                          boost::filesystem::directory_iterator(),
                          std::back_inserter(result));

                // ext filter
                result.remove_if([&ext](boost::filesystem::path p) {
                    return p.extension().string() != ext;
                });

                for(boost::filesystem::path& it:result){
                    s_result.push_back(it.string());
                }
                return s_result;
            }

            bool rm(const std::string &rm_path){
                if (!boost::filesystem::exists(rm_path))
                    return true;
                try {
                    if (boost::filesystem::is_directory(rm_path)) {
                        boost::filesystem::path path_to_remove(rm_path);
                        for (boost::filesystem::directory_iterator end_dir_it, it(path_to_remove);
                             it != end_dir_it; ++it) {
                            if (!boost::filesystem::remove_all(it->path())) {
                                return false;
                            }
                        }
                    }
                    boost::filesystem::remove_all(rm_path);
                    return true;
                } catch (boost::filesystem::filesystem_error &ex) {
                    std::string msg = ex.what();
                    MAKE_EXCEPTION("utils::rm exception: " + msg);
                    throw;
                }
            }

            std::string filename(const std::string & fname){ // without ex
                boost::filesystem::path p(fname);
                return p.stem().string();
            }

            std::string parent_path(const std::string & fname){
                boost::filesystem::path p(fname);
                return p.parent_path().string();
            }

			std::string append_path(const std::string & p1, const std::string & p2) {
				boost::filesystem::path p(p1);
				boost::filesystem::path p_sub(p2);
				p /= p_sub;
				return p.string();
			}

			bool path_exists(const std::string & path)
			{
				return boost::filesystem::exists(path);
			}
			void mkdir(const std::string & path)
			{
				if (!boost::filesystem::exists(path)) {
					boost::filesystem::create_directory(path);
				}
			}
        }
    }
}
class MappedFile::Impl
{
public:
    Impl(){
        _closed=false;
        m_file=nullptr;
        m_region=nullptr;
    }

    ~Impl(){
        if(!_closed){
            close();
        }
    }

    static Impl*open(const std::string&path){
        auto result=new Impl();
        result->m_file = new bi::file_mapping(path.c_str(), bi::read_write);
        result->m_region = new bi::mapped_region(*(result->m_file), bi::read_write);
        return result;
    }

    static Impl*touch(const std::string&path, uint64_t size){
        try {
            bi::file_mapping::remove(path.c_str());
            std::filebuf fbuf;
            fbuf.open(path,
                      std::ios_base::in |
                      std::ios_base::out|
                      std::ios_base::trunc|
                      std::ios_base::binary);
            //Set the size
            fbuf.pubseekoff(size-1, std::ios_base::beg);
            fbuf.sputc(0);
            fbuf.close();
            return Impl::open(path);
        } catch (std::runtime_error &ex) {
            std::string what = ex.what();
            throw MAKE_EXCEPTION(ex.what());
        }

    }

    void close(){
        _closed=true;
        m_region->flush();
        delete m_region;
        delete m_file;
        m_region=nullptr;
        m_file=nullptr;
    }

    uint8_t* data(){
        return static_cast<uint8_t*>(m_region->get_address());
    }

protected:
    bool _closed;

    bi::file_mapping*m_file;
    bi::mapped_region*m_region;
};

MappedFile::MappedFile(Impl* im):_impl(im){

}

MappedFile::~MappedFile(){

}

MappedFile::MapperFile_ptr MappedFile::open(const std::string&path){
    auto impl_res=MappedFile::Impl::open(path);
    MappedFile::MapperFile_ptr  result{new MappedFile{impl_res}};
    return result;
}

MappedFile::MapperFile_ptr MappedFile::touch(const std::string&path, uint64_t size){
    auto impl_res=MappedFile::Impl::touch(path,size);
    MappedFile::MapperFile_ptr  result{new MappedFile{impl_res}};
    return result;
}

void MappedFile::close(){
    _impl->close();
}

uint8_t* MappedFile::data(){
    return _impl->data();
}
<|endoftext|>


<commit_before>// Copyright (c) 2005 Daniel Wallin, Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#include <iostream>
#include <cstring>

extern "C"
{
    #include "lauxlib.h"
    #include "lualib.h"
}

#include <luabind/open.hpp>
#include "test.hpp"

extern "C" struct lua_State;

void test_main(lua_State*);

struct lua_state
{
    lua_state();
    ~lua_state();

    operator lua_State*() const;
	void check() const;

private:
    lua_State* m_state;
    int m_top;
};

lua_state::lua_state()
    : m_state(lua_open())
{
    luaopen_base(m_state);
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501
	 // lua 5.1 or newer
	 luaL_openlibs(m_state);
#else
	 // lua 5.0.2 or older
    lua_baselibopen(m_state);
#endif
    m_top = lua_gettop(m_state);
    luabind::open(m_state);
}

lua_state::~lua_state()
{
    TEST_CHECK(lua_gettop(m_state) == m_top);
    lua_close(m_state);
}

void lua_state::check() const
{
    TEST_CHECK(lua_gettop(m_state) == m_top);
}

lua_state::operator lua_State*() const
{
    return m_state;
}

int pcall_handler(lua_State* L)
{
	return 1;
}

void dostring(lua_State* state, char const* str)
{
    lua_pushcclosure(state, &pcall_handler, 0);

    if (luaL_loadbuffer(state, str, std::strlen(str), str))
    {
        std::string err(lua_tostring(state, -1));
        lua_pop(state, 2);
		throw err;
    }

    if (lua_pcall(state, 0, 0, -2))
    {
        std::string err(lua_tostring(state, -1));
        lua_pop(state, 2);
		throw err;
    }

    lua_pop(state, 1);
}

bool tests_failure = false;

void report_failure(char const* err, char const* file, int line)
{
	std::cerr << file << ":" << line << "\"" << err << "\"\n";
	tests_failure = true;
}

int main()
{
	lua_state L;
	try
	{
		test_main(L);
		return tests_failure ? 1 : 0;
	}
	catch (luabind::error const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"
			<< lua_tostring(e.state(), -1) << "\n";
		return 1;
	}
	catch (std::exception const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
		return 1;
	}
	catch (...)
	{
		std::cerr << "Terminated with unknown exception\n";
		return 1;
	}
}

<commit_msg>Always check the stack state after each test.<commit_after>// Copyright (c) 2005 Daniel Wallin, Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#include <iostream>
#include <cstring>

extern "C"
{
    #include "lauxlib.h"
    #include "lualib.h"
}

#include <luabind/open.hpp>
#include "test.hpp"

extern "C" struct lua_State;

void test_main(lua_State*);

struct lua_state
{
    lua_state();
    ~lua_state();

    operator lua_State*() const;
	void check() const;

private:
    lua_State* m_state;
    int m_top;
};

lua_state::lua_state()
    : m_state(lua_open())
{
    luaopen_base(m_state);
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501
	 // lua 5.1 or newer
	 luaL_openlibs(m_state);
#else
	 // lua 5.0.2 or older
    lua_baselibopen(m_state);
#endif
    m_top = lua_gettop(m_state);
    luabind::open(m_state);
}

lua_state::~lua_state()
{
    lua_close(m_state);
}

void lua_state::check() const
{
    TEST_CHECK(lua_gettop(m_state) == m_top);
}

lua_state::operator lua_State*() const
{
    return m_state;
}

int pcall_handler(lua_State* L)
{
	return 1;
}

void dostring(lua_State* state, char const* str)
{
    lua_pushcclosure(state, &pcall_handler, 0);

    if (luaL_loadbuffer(state, str, std::strlen(str), str))
    {
        std::string err(lua_tostring(state, -1));
        lua_pop(state, 2);
		throw err;
    }

    if (lua_pcall(state, 0, 0, -2))
    {
        std::string err(lua_tostring(state, -1));
        lua_pop(state, 2);
		throw err;
    }

    lua_pop(state, 1);
}

bool tests_failure = false;

void report_failure(char const* err, char const* file, int line)
{
	std::cerr << file << ":" << line << "\"" << err << "\"\n";
	tests_failure = true;
}

int main()
{
	lua_state L;
	try
	{
		test_main(L);
		L.check();
		return tests_failure ? 1 : 0;
	}
	catch (luabind::error const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n"
			<< lua_tostring(e.state(), -1) << "\n";
		return 1;
	}
	catch (std::exception const& e)
	{
		std::cerr << "Terminated with exception: \"" << e.what() << "\"\n";
		return 1;
	}
	catch (...)
	{
		std::cerr << "Terminated with unknown exception\n";
		return 1;
	}
}

<|endoftext|>