<commit_before>/*
 * This file is part of QTpLogger
 *
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * 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
 */

#include "pending-dates-query.h"
#include "entity.h"
#include "constants.h"
#include <TelepathyQt4/Account>
#include "telepathy-logger/log-manager.h"
#include <QDebug>
#include <glib/gerror.h>
#include <glib/gdate.h>

using namespace QTpLogger;

struct QTPLOGGER_NO_EXPORT PendingDatesQuery::Private
{
    LogManagerPtr manager;
    Tp::AccountPtr account;
    EntityPtr entity;
    EventTypeMask typeMask;
    QDateList dates;

    static void callback(void *logManager, void *result, PendingDatesQuery *self);
};

PendingDatesQuery::PendingDatesQuery(LogManagerPtr manager, Tp::AccountPtr account, EntityPtr entity, EventTypeMask typeMask)
    : PendingOperation(),
      mPriv(new Private())
{
    mPriv->manager = manager;
    mPriv->account = account;
    mPriv->entity = entity;
    mPriv->typeMask = typeMask;
}

PendingDatesQuery::~PendingDatesQuery()
{
    delete mPriv;
}

void PendingDatesQuery::start()
{
    // TODO what to do with AccountPtr
    tpl_log_manager_get_dates_async(mPriv->manager,
        0, // mPriv->account
        mPriv->entity,
        mPriv->typeMask,
        (GAsyncReadyCallback) Private::callback,
        this);
}

QDateList PendingDatesQuery::dates() const
{
    if (!isFinished()) {
        qWarning() << "PendingDatesQuery::dates called before finished, returning empty";
        return QDateList();
    } else if (!isValid()) {
        qWarning() << "PendingDatesQuery::dates called when not valid, returning empty";
        return QDateList();
    }

    return mPriv->dates;
}

void PendingDatesQuery::Private::callback(void *logManager, void *result, PendingDatesQuery *self)
{
    if (!TPL_IS_LOG_MANAGER(logManager)) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, "Invalid log manager in callback");
        return;
    }

    if (!G_IS_ASYNC_RESULT(result)) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, "Invalid async result in callback");
        return;
    }

    GList *dates = NULL;
    GError *error = NULL;
    gboolean success = tpl_log_manager_get_dates_finish(TPL_LOG_MANAGER(logManager), G_ASYNC_RESULT(result), &dates, &error);
    if (error) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, error->message);
        return;
    }

    if (!success) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, "Query failed with specific error");
        return;
    }

    GList *i;
    for (i = dates; i; i = i->next) {
        GDate * item = (GDate *) i->data;
        self->mPriv->dates << QDate(item->year, item->month, item->day);
    }

    g_list_foreach(dates, (GFunc) g_date_free, NULL);
    g_list_free(dates);

    self->setFinished();
}
<commit_msg>Fixed memory leak in case of error<commit_after>/*
 * This file is part of QTpLogger
 *
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *
 * 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
 */

#include "pending-dates-query.h"
#include "entity.h"
#include "constants.h"
#include <TelepathyQt4/Account>
#include "telepathy-logger/log-manager.h"
#include <QDebug>
#include <glib/gerror.h>
#include <glib/gdate.h>

using namespace QTpLogger;

struct QTPLOGGER_NO_EXPORT PendingDatesQuery::Private
{
    LogManagerPtr manager;
    Tp::AccountPtr account;
    EntityPtr entity;
    EventTypeMask typeMask;
    QDateList dates;

    static void callback(void *logManager, void *result, PendingDatesQuery *self);
};

PendingDatesQuery::PendingDatesQuery(LogManagerPtr manager, Tp::AccountPtr account, EntityPtr entity, EventTypeMask typeMask)
    : PendingOperation(),
      mPriv(new Private())
{
    mPriv->manager = manager;
    mPriv->account = account;
    mPriv->entity = entity;
    mPriv->typeMask = typeMask;
}

PendingDatesQuery::~PendingDatesQuery()
{
    delete mPriv;
}

void PendingDatesQuery::start()
{
    // TODO what to do with AccountPtr
    tpl_log_manager_get_dates_async(mPriv->manager,
        0, // mPriv->account
        mPriv->entity,
        mPriv->typeMask,
        (GAsyncReadyCallback) Private::callback,
        this);
}

QDateList PendingDatesQuery::dates() const
{
    if (!isFinished()) {
        qWarning() << "PendingDatesQuery::dates called before finished, returning empty";
        return QDateList();
    } else if (!isValid()) {
        qWarning() << "PendingDatesQuery::dates called when not valid, returning empty";
        return QDateList();
    }

    return mPriv->dates;
}

void PendingDatesQuery::Private::callback(void *logManager, void *result, PendingDatesQuery *self)
{
    if (!TPL_IS_LOG_MANAGER(logManager)) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, "Invalid log manager in callback");
        return;
    }

    if (!G_IS_ASYNC_RESULT(result)) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, "Invalid async result in callback");
        return;
    }

    GList *dates = NULL;
    GError *error = NULL;
    gboolean success = tpl_log_manager_get_dates_finish(TPL_LOG_MANAGER(logManager), G_ASYNC_RESULT(result), &dates, &error);
    if (error) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, error->message);
        g_error_free(error);
        return;
    }

    if (!success) {
        self->setFinishedWithError(QTPLOGGER_ERROR_INVALID_ARGUMENT, "Query failed with specific error");
        return;
    }

    GList *i;
    for (i = dates; i; i = i->next) {
        GDate * item = (GDate *) i->data;
        self->mPriv->dates << QDate(item->year, item->month, item->day);
    }

    g_list_foreach(dates, (GFunc) g_date_free, NULL);
    g_list_free(dates);

    self->setFinished();
}
<|endoftext|>


<commit_before><commit_msg>[PDB] Partial resubmit of r296215, which improved PDB Stream Library.<commit_after><|endoftext|>


<commit_before>/********************************************************************************
 File name: monster.cpp
 Written by: Daniel Nguyen
 Written on 08/27/2016
 Purpose: This is a c++ file containing monster class.

 Class: CPSC 362
 *********************************************************************************/
#include <sstream>
#include <string>
#include "enum.h"
#include "entity.h"

/*********************************************************************
 This is the monster class. It only uses Health, Experience, Attack,
 Defense, ActionCoolDown.
 *********************************************************************/
class Enemy : public Entity{
private:
    std::string name;
public:
    //Constructor
    Enemy();

    //Destructor
    ~Enemy();

    //Set the level of the monster
    void setLevel(int amount)
    {
        _Level = amount;
    }

    //Accessor function for name
    std::string get_name(){return name;}
};

<commit_msg>Update monster.cpp<commit_after>/********************************************************************************
 File name: monster.cpp
 Written by: Daniel Nguyen
 Written on 08/27/2016
 Purpose: This is a c++ file containing monster class.

 Class: CPSC 362
 *********************************************************************************/
#include <sstream>
#include <string>
#include "enums.h"
#include "entity.h"

/*********************************************************************
 This is the monster class. It only uses Health, Experience, Attack,
 Defense, ActionCoolDown.
 *********************************************************************/
class Enemy : public Entity{
private:
    std::string name;
public:
    //Constructor
    Enemy();

    //Destructor
    ~Enemy();

    //Set the level of the monster
    void setLevel(int amount)
    {
        _Level = amount;
    }

    //Accessor function for name
    std::string get_name(){return name;}
};

<|endoftext|>


<commit_before>// @(#)root/tree:$Name:  $:$Id: TLeaf.cxx,v 1.8 2002/05/30 23:42:00 brun Exp $
// Author: Rene Brun   12/01/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// A TLeaf describes individual elements of a TBranch                   //
//       See TBranch structure in TTree.                                //
//////////////////////////////////////////////////////////////////////////

#include "TLeaf.h"
#include "TBranch.h"
#include "TTree.h"
#include "TVirtualPad.h"
#include "TBrowser.h"

#include <ctype.h>

R__EXTERN TTree *gTree;
R__EXTERN TBranch *gBranch;

ClassImp(TLeaf)

//______________________________________________________________________________
TLeaf::TLeaf(): TNamed()
{
//*-*-*-*-*-*Default constructor for Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ============================
   fLen        = 0;
   //fBranch     = 0;
   fBranch     = gBranch;
   fLeafCount  = 0;
   fNdata      = 0;
   fOffset     = 0;
}

//______________________________________________________________________________
TLeaf::TLeaf(const char *name, const char *)
    :TNamed(name,name)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      =============
//
//     See the TTree and TBranch constructors for explanation of parameters.

   fLeafCount  = GetLeafCounter(fLen);
   if (fLen == -1) {MakeZombie(); return;}
   fIsRange    = 0;
   fIsUnsigned = 0;
   fLenType    = 4;
   fNdata      = 0;
   fOffset     = 0;
   if (fLeafCount || strchr(name,'[')) {
      char newname[64];
      strcpy(newname,name);
      char *bracket = strchr(newname,'[');
      *bracket = 0;
      SetName(newname);
   }
   fBranch     = gBranch;
}

//______________________________________________________________________________
TLeaf::~TLeaf()
{
//*-*-*-*-*-*Default destructor for a Leaf*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ===============================

//   if (fBranch) fBranch->GetListOfLeaves().Remove(this);
   if (!fBranch) return;
   TTree *tree = fBranch->GetTree();
   fBranch = 0;
   if (!tree) return;
   tree->GetListOfLeaves()->Remove(this);
}

//______________________________________________________________________________
void TLeaf::Browse(TBrowser *)
{
   char name[64];
   if (strchr(GetName(),'.')) {
      fBranch->GetTree()->Draw(GetName());
   } else {
      sprintf(name,"%s.%s",fBranch->GetName(),GetName());
      fBranch->GetTree()->Draw(name);
   }
   if (gPad) gPad->Update();
}

//______________________________________________________________________________
void TLeaf::FillBasket(TBuffer &)
{
//*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-*
//*-*                  =========================================

}

//______________________________________________________________________________
TLeaf *TLeaf::GetLeafCounter(Int_t &countval) const
{
//*-*-*-*-*-*-*Return Pointer to counter of referenced Leaf*-*-*-*-*-*-*-*
//*-*          ============================================
//
//  If leaf name has the forme var[nelem], where nelem is alphanumeric, then
//     If nelem is a leaf name, return countval = 1 and the pointer to
//     the leaf named nelem.
//  If leaf name has the forme var[nelem], where nelem is a digit, then
//     return countval = nelem and a null pointer.
//  Otherwise return countval=0 and a null pointer.
//

   countval = 1;
   const char *name = GetTitle();
   char *bleft = (char*)strchr(name,'[');
   if (!bleft) return 0;
   bleft++;
   Int_t nch = strlen(bleft);
   char *countname = new char[nch+1];
   strcpy(countname,bleft);
   char *bright = (char*)strchr(countname,']');
   if (!bright) { delete [] countname; return 0;}
   char *bleft2 = (char*)strchr(countname,'[');
   *bright = 0; nch = strlen(countname);

   //*-* Now search a branch name with a leave name = countname
   //    We search for the leaf in the ListOfLeaves from the TTree. We can in principle
   //    access the TTree by calling fBranch()->GetTree(), but fBranch is not set if this
   //    method is called from the TLeaf constructor. In that case, use global pointer
   //    gTree.
   //    Also, if fBranch is set, but fBranch->GetTree() returns NULL, use gTree.
  //TTree* pTree = fBranch ? fBranch->GetTree() : gTree;
  //if(pTree==NULL) pTree = gTree;
  TLeaf *leaf = (TLeaf*) gTree->GetListOfLeaves()->FindObject(countname);
  Int_t i;
  if (leaf) {
     countval = 1;
     leaf->SetRange();
     if (bleft2) {
        sscanf(bleft2,"[%d]",&i);
        countval *= i;
     }
     bleft = bleft2;
     while(bleft) {
        bleft2++;
        bleft = (char*)strchr(bleft2,'[');
        if (!bleft) break;
        sscanf(bleft,"[%d]",&i);
        countval *= i;
        bleft2 = bleft;
     }
     delete [] countname;
     return leaf;
  }
//*-* not found in a branch/leaf. Is it a numerical value?
   for (i=0;i<nch;i++) {
      if (!isdigit(countname[i])) {
        delete [] countname;
        countval = -1;
        return 0;
      }
   }
   sscanf(countname,"%d",&countval);
   if (bleft2) {
      sscanf(bleft2,"[%d]",&i);
      countval *= i;
   }
   bleft = bleft2;
   while(bleft) {
      bleft2++;
      bleft = (char*)strchr(bleft2,'[');
      if (!bleft) break;
      sscanf(bleft,"[%d]",&i);
      countval *= i;
      bleft2 = bleft;
   }
//*/
   delete [] countname;
   return 0;
}

//______________________________________________________________________________
Int_t TLeaf::GetLen() const
{
//*-*-*-*-*-*-*-*-*Return the number of effective elements of this leaf*-*-*-*
//*-*              ====================================================

   Int_t len;
   if (fLeafCount) {
      len = Int_t(fLeafCount->GetValue());
      if (len > fLeafCount->GetMaximum()) {
         printf("ERROR leaf:%s, len=%d and max=%d\n",GetName(),len,fLeafCount->GetMaximum());
         len = fLeafCount->GetMaximum();
      }
      return len*fLen;
   } else {
      return fLen;
   }
}

//______________________________________________________________________________
Int_t TLeaf::ResetAddress(void *add, Bool_t destructor)
{
//*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-*
//*-*                  ============================
//
//  This function is called by all TLeafX::SetAddress

   Int_t todelete = 0;
   if (TestBit(kNewValue)) todelete = 1;
   if (destructor) return todelete;

   if (fLeafCount) fNdata = fLen*(fLeafCount->GetMaximum() + 1);
   else            fNdata = fLen;

   ResetBit(kNewValue);
   if (!add) SetBit(kNewValue);
   return todelete;
}

//_______________________________________________________________________
void TLeaf::Streamer(TBuffer &b)
{
//*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*              =========================================

   if (b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = b.ReadVersion(&R__s, &R__c);
      if (R__v > 1) {
         TLeaf::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
      } else {
         //====process old versions before automatic schema evolution
         TNamed::Streamer(b);
         b >> fLen;
         b >> fLenType;
         b >> fOffset;
         b >> fIsRange;
         b >> fIsUnsigned;
         b >> fLeafCount;
         b.CheckByteCount(R__s, R__c, TLeaf::IsA());
         //====end of old versions
      }
      if (fLen == 0) fLen = 1;
      ResetBit(kNewValue);
      SetAddress();
   } else {
      TLeaf::Class()->WriteBuffer(b,this);
   }
}
<commit_msg>Improvement in TLeaf by Philippe and Paul Balm in case of tree friends<commit_after>// @(#)root/tree:$Name:  $:$Id: TLeaf.cxx,v 1.9 2002/05/31 16:59:54 brun Exp $
// Author: Rene Brun   12/01/96

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// A TLeaf describes individual elements of a TBranch                   //
//       See TBranch structure in TTree.                                //
//////////////////////////////////////////////////////////////////////////

#include "TLeaf.h"
#include "TBranch.h"
#include "TTree.h"
#include "TVirtualPad.h"
#include "TBrowser.h"

#include <ctype.h>

R__EXTERN TTree *gTree;
R__EXTERN TBranch *gBranch;

ClassImp(TLeaf)

//______________________________________________________________________________
TLeaf::TLeaf(): TNamed()
{
//*-*-*-*-*-*Default constructor for Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ============================
   fLen        = 0;
   //fBranch     = 0;
   fBranch     = gBranch;
   fLeafCount  = 0;
   fNdata      = 0;
   fOffset     = 0;
}

//______________________________________________________________________________
TLeaf::TLeaf(const char *name, const char *)
    :TNamed(name,name)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*Create a Leaf*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*                      =============
//
//     See the TTree and TBranch constructors for explanation of parameters.

   fBranch     = 0;
   fLeafCount  = GetLeafCounter(fLen);
   if (fLen == -1) {MakeZombie(); return;}
   fIsRange    = 0;
   fIsUnsigned = 0;
   fLenType    = 4;
   fNdata      = 0;
   fOffset     = 0;
   if (fLeafCount || strchr(name,'[')) {
      char newname[64];
      strcpy(newname,name);
      char *bracket = strchr(newname,'[');
      *bracket = 0;
      SetName(newname);
   }
   fBranch     = gBranch;
}

//______________________________________________________________________________
TLeaf::~TLeaf()
{
//*-*-*-*-*-*Default destructor for a Leaf*-*-*-*-*-*-*-*-*-*-*-*
//*-*        ===============================

//   if (fBranch) fBranch->GetListOfLeaves().Remove(this);
   if (!fBranch) return;
   TTree *tree = fBranch->GetTree();
   fBranch = 0;
   if (!tree) return;
   tree->GetListOfLeaves()->Remove(this);
}

//______________________________________________________________________________
void TLeaf::Browse(TBrowser *)
{
   char name[64];
   if (strchr(GetName(),'.')) {
      fBranch->GetTree()->Draw(GetName());
   } else {
      sprintf(name,"%s.%s",fBranch->GetName(),GetName());
      fBranch->GetTree()->Draw(name);
   }
   if (gPad) gPad->Update();
}

//______________________________________________________________________________
void TLeaf::FillBasket(TBuffer &)
{
//*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-*
//*-*                  =========================================

}

//______________________________________________________________________________
TLeaf *TLeaf::GetLeafCounter(Int_t &countval) const
{
//*-*-*-*-*-*-*Return Pointer to counter of referenced Leaf*-*-*-*-*-*-*-*
//*-*          ============================================
//
//  If leaf name has the forme var[nelem], where nelem is alphanumeric, then
//     If nelem is a leaf name, return countval = 1 and the pointer to
//     the leaf named nelem.
//  If leaf name has the forme var[nelem], where nelem is a digit, then
//     return countval = nelem and a null pointer.
//  Otherwise return countval=0 and a null pointer.
//

   countval = 1;
   const char *name = GetTitle();
   char *bleft = (char*)strchr(name,'[');
   if (!bleft) return 0;
   bleft++;
   Int_t nch = strlen(bleft);
   char *countname = new char[nch+1];
   strcpy(countname,bleft);
   char *bright = (char*)strchr(countname,']');
   if (!bright) { delete [] countname; return 0;}
   char *bleft2 = (char*)strchr(countname,'[');
   *bright = 0; nch = strlen(countname);

   //*-* Now search a branch name with a leave name = countname
   //    We search for the leaf in the ListOfLeaves from the TTree. We can in principle
   //    access the TTree by calling fBranch()->GetTree(), but fBranch is not set if this
   //    method is called from the TLeaf constructor. In that case, use global pointer
   //    gTree.
   //    Also, if fBranch is set, but fBranch->GetTree() returns NULL, use gTree.
  TTree* pTree = fBranch ? fBranch->GetTree() : gTree;
  if (!pTree) pTree = gTree;
  TLeaf *leaf = (TLeaf*) pTree->GetListOfLeaves()->FindObject(countname);
  Int_t i;
  if (leaf) {
     countval = 1;
     leaf->SetRange();
     if (bleft2) {
        sscanf(bleft2,"[%d]",&i);
        countval *= i;
     }
     bleft = bleft2;
     while(bleft) {
        bleft2++;
        bleft = (char*)strchr(bleft2,'[');
        if (!bleft) break;
        sscanf(bleft,"[%d]",&i);
        countval *= i;
        bleft2 = bleft;
     }
     delete [] countname;
     return leaf;
  }
//*-* not found in a branch/leaf. Is it a numerical value?
   for (i=0;i<nch;i++) {
      if (!isdigit(countname[i])) {
        delete [] countname;
        countval = -1;
        return 0;
      }
   }
   sscanf(countname,"%d",&countval);
   if (bleft2) {
      sscanf(bleft2,"[%d]",&i);
      countval *= i;
   }
   bleft = bleft2;
   while(bleft) {
      bleft2++;
      bleft = (char*)strchr(bleft2,'[');
      if (!bleft) break;
      sscanf(bleft,"[%d]",&i);
      countval *= i;
      bleft2 = bleft;
   }
//*/
   delete [] countname;
   return 0;
}

//______________________________________________________________________________
Int_t TLeaf::GetLen() const
{
//*-*-*-*-*-*-*-*-*Return the number of effective elements of this leaf*-*-*-*
//*-*              ====================================================

   Int_t len;
   if (fLeafCount) {
      len = Int_t(fLeafCount->GetValue());
      if (len > fLeafCount->GetMaximum()) {
         printf("ERROR leaf:%s, len=%d and max=%d\n",GetName(),len,fLeafCount->GetMaximum());
         len = fLeafCount->GetMaximum();
      }
      return len*fLen;
   } else {
      return fLen;
   }
}

//______________________________________________________________________________
Int_t TLeaf::ResetAddress(void *add, Bool_t destructor)
{
//*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-*
//*-*                  ============================
//
//  This function is called by all TLeafX::SetAddress

   Int_t todelete = 0;
   if (TestBit(kNewValue)) todelete = 1;
   if (destructor) return todelete;

   if (fLeafCount) fNdata = fLen*(fLeafCount->GetMaximum() + 1);
   else            fNdata = fLen;

   ResetBit(kNewValue);
   if (!add) SetBit(kNewValue);
   return todelete;
}

//_______________________________________________________________________
void TLeaf::Streamer(TBuffer &b)
{
//*-*-*-*-*-*-*-*-*Stream a class object*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-*              =========================================

   if (b.IsReading()) {
      UInt_t R__s, R__c;
      Version_t R__v = b.ReadVersion(&R__s, &R__c);
      if (R__v > 1) {
         TLeaf::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
      } else {
         //====process old versions before automatic schema evolution
         TNamed::Streamer(b);
         b >> fLen;
         b >> fLenType;
         b >> fOffset;
         b >> fIsRange;
         b >> fIsUnsigned;
         b >> fLeafCount;
         b.CheckByteCount(R__s, R__c, TLeaf::IsA());
         //====end of old versions
      }
      if (fLen == 0) fLen = 1;
      ResetBit(kNewValue);
      SetAddress();
   } else {
      TLeaf::Class()->WriteBuffer(b,this);
   }
}
<|endoftext|>


<commit_before>#pragma once

#define GLM_SWIZZLE
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/vec1.hpp>

#include "../c.hxx"
#include "../gl_type.hxx"

#include "get.hxx"

#include "../../destruct_invoker.hxx"

namespace wonder_rabbit_project
{
  namespace wonderland
  {
    namespace renderer
    {
      namespace glew
      {
        struct misc_t
        {
          template < class T = void >
          static inline auto flush()
            -> void
          { c::glFlush(); }

          template < class T = void >
          static inline auto clear_color( const glm::vec4& color )
            -> void
          { c::glClearColor( color.r, color.g, color.b, color.a ); }

          template < class T = void >
          static inline auto clear_color( const glm::vec3& color )
            -> void
          { c::glClearColor( color.r, color.g, color.b, 1.0f ); }

          template < class T = void >
          static inline auto clear_color( const glm::vec1& color )
            -> void
          { clear_color( color.r ); }

          template < class T = void >
          static inline auto clear_color( const float color )
            -> void
          { c::glClearColor( color, color, color, 1.0f ); }

          template < class T = void >
          static inline auto clear
          ( gl_type::GLbitfield flag
            = GL_COLOR_BUFFER_BIT
            | GL_DEPTH_BUFFER_BIT
            | GL_STENCIL_BUFFER_BIT
          )
            -> void
          { c::glClear( glew::gl_type::GLint( flag ) ); }

          template < class T = void >
          static inline auto color_mask
          ( const bool r
          , const bool g
          , const bool b
          , const bool a
          )
            -> void
          { c::glColorMask( r, g, b, a ); }

          template < class T = void >
          static inline auto color_mask
          ( const gl_type::GLuint buffer_index
          , const bool r
          , const bool g
          , const bool b
          , const bool a
          )
            -> void
          { c::glColorMaski( buffer_index, r, g, b, a ); }

          template < class T = void >
          static inline auto color_mask( const bool all )
            -> void
          { color_mask( all, all, all, all ); }

          template < class T = void >
          static inline auto color_mask( const gl_type::GLuint buffer_index, const bool all )
            -> void
          { color_mask( buffer_index, all, all, all, all ); }

          template < class T = void >
          static inline auto color_mask( const glm::bvec4& rgba )
            -> void
          { color_mask( rgba[0], rgba[1], rgba[2], rgba[3] ); }

          template < class T = void >
          static inline auto color_mask( const gl_type::GLuint buffer_index, const glm::bvec4& rgba )
            -> void
          { color_mask( buffer_index, rgba[0], rgba[1], rgba[2], rgba[3] ); }

          template < class T = void >
          static inline auto color_mask()
            -> glm::bvec4
          { return get_t::get< GL_COLOR_WRITEMASK, glm::bvec4 >(); }

          template < class ... Ts >
          static inline auto scoped_color_mask
          ( const Ts& ... rgba )
            -> destruct_invoker_t
          {
            const auto backup = color_mask();
            color_mask( rgba ... );
            return destruct_invoker_t( [ backup ]{ color_mask( backup ); } );
          }

          template < class T = void >
          static inline auto cull_face( const gl_type::GLenum flag = GL_BACK )
            -> void
          { c::glCullFace( flag ); }

          template < class T = void >
          static inline auto scoped_cull_face( const gl_type::GLenum flag = GL_FRONT )
            -> destruct_invoker_t
          {
            const auto backup = get_t::get< GL_CULL_FACE_MODE >();
            cull_face( flag );
            return destruct_invoker_t( [ backup ]{ cull_face( backup ); } );
          }

        };
      }
    }
  }
}<commit_msg>support polygon_offset series.<commit_after>#pragma once

#define GLM_SWIZZLE
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/vec1.hpp>

#include "../c.hxx"
#include "../gl_type.hxx"

#include "get.hxx"
#include "enable.hxx"

#include "../../destruct_invoker.hxx"

namespace wonder_rabbit_project
{
  namespace wonderland
  {
    namespace renderer
    {
      namespace glew
      {
        struct misc_t
        {
          template < class T = void >
          static inline auto flush()
            -> void
          { c::glFlush(); }

          template < class T = void >
          static inline auto clear_color( const glm::vec4& color )
            -> void
          { c::glClearColor( color.r, color.g, color.b, color.a ); }

          template < class T = void >
          static inline auto clear_color( const glm::vec3& color )
            -> void
          { c::glClearColor( color.r, color.g, color.b, 1.0f ); }

          template < class T = void >
          static inline auto clear_color( const glm::vec1& color )
            -> void
          { clear_color( color.r ); }

          template < class T = void >
          static inline auto clear_color( const float color )
            -> void
          { c::glClearColor( color, color, color, 1.0f ); }

          template < class T = void >
          static inline auto clear
          ( gl_type::GLbitfield flag
            = GL_COLOR_BUFFER_BIT
            | GL_DEPTH_BUFFER_BIT
            | GL_STENCIL_BUFFER_BIT
          )
            -> void
          { c::glClear( glew::gl_type::GLint( flag ) ); }

          template < class T = void >
          static inline auto color_mask
          ( const bool r
          , const bool g
          , const bool b
          , const bool a
          )
            -> void
          { c::glColorMask( r, g, b, a ); }

          template < class T = void >
          static inline auto color_mask
          ( const gl_type::GLuint buffer_index
          , const bool r
          , const bool g
          , const bool b
          , const bool a
          )
            -> void
          { c::glColorMaski( buffer_index, r, g, b, a ); }

          template < class T = void >
          static inline auto color_mask( const bool all )
            -> void
          { color_mask( all, all, all, all ); }

          template < class T = void >
          static inline auto color_mask( const gl_type::GLuint buffer_index, const bool all )
            -> void
          { color_mask( buffer_index, all, all, all, all ); }

          template < class T = void >
          static inline auto color_mask( const glm::bvec4& rgba )
            -> void
          { color_mask( rgba[0], rgba[1], rgba[2], rgba[3] ); }

          template < class T = void >
          static inline auto color_mask( const gl_type::GLuint buffer_index, const glm::bvec4& rgba )
            -> void
          { color_mask( buffer_index, rgba[0], rgba[1], rgba[2], rgba[3] ); }

          template < class T = void >
          static inline auto color_mask()
            -> glm::bvec4
          { return get_t::get< GL_COLOR_WRITEMASK, glm::bvec4 >(); }

          template < class ... Ts >
          static inline auto scoped_color_mask
          ( const Ts& ... rgba )
            -> destruct_invoker_t
          {
            const auto backup = color_mask();
            color_mask( rgba ... );
            return destruct_invoker_t( [ backup ]{ color_mask( backup ); } );
          }

          template < class T = void >
          static inline auto cull_face( const gl_type::GLenum flag = GL_BACK )
            -> void
          { c::glCullFace( flag ); }

          template < class T = void >
          static inline auto scoped_cull_face( const gl_type::GLenum flag = GL_FRONT )
            -> destruct_invoker_t
          {
            const auto backup = get_t::get< GL_CULL_FACE_MODE >();
            cull_face( flag );
            return destruct_invoker_t( [ backup ]{ cull_face( backup ); } );
          }

          template < class T = void >
          static inline auto polygon_offset( gl_type::GLfloat factor, gl_type::GLfloat units )
            -> void
          { c::glPolygonOffset( factor, units ); }

          template < class T = void >
          static inline auto scoped_polygon_offset( gl_type::GLfloat factor, gl_type::GLfloat units )
            -> destruct_invoker_t
          {
            const auto backup_factor = polygon_offset_factor();
            const auto backup_units  = polygon_offset_units();
            polygon_offset( factor, units );
            return destruct_invoker_t( [ backup_factor, backup_units ]{ polygon_offset( backup_factor, backup_units ); } );
          }

          template < class T = void >
          static inline auto polygon_offset_factor()
            -> gl_type::GLfloat
          { return get_t::get< GL_POLYGON_OFFSET_FACTOR, gl_type::GLfloat >(); }

          template < class T = void >
          static inline auto polygon_offset_units()
            -> gl_type::GLfloat
          { return get_t::get< GL_POLYGON_OFFSET_UNITS, gl_type::GLfloat >(); }

        };
      }
    }
  }
}<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/video_engine/test/common/flags.h"
#include "webrtc/video_engine/test/common/run_tests.h"

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  webrtc::test::flags::Init(&argc, &argv);

  return webrtc::test::RunAllTests();
}
<commit_msg>Call SetExecutablePath from test_main.cc<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"

#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/video_engine/test/common/flags.h"
#include "webrtc/video_engine/test/common/run_tests.h"

int main(int argc, char* argv[]) {
  ::testing::InitGoogleTest(&argc, argv);
  webrtc::test::flags::Init(&argc, &argv);
  webrtc::test::SetExecutablePath(argv[0]);

  return webrtc::test::RunAllTests();
}
<|endoftext|>


<commit_before><commit_msg>More debug log<commit_after><|endoftext|>


<commit_before>#include <config.h>
#include <cassert>
#include <logger/davix_logger_internal.h>
#include <auth/davixauth.h>
#include <params/davixrequestparams.hpp>
#include <libs/time_utils.h>

namespace Davix {

const char * default_agent = "libdavix/0.0.9";
volatile int state_value =0;

inline int get_requeste_uid(){
    state_value +=1;
    return state_value;
}

#define SESSION_FLAG_KEEP_ALIVE 0x01

struct RequestParamsInternal{
    RequestParamsInternal() :
        _ssl_check(true),
        _redirection(true),
        _ca_path(),
        _cli_cert(),
        _idlogpass(),
        _callb(NULL),
        _callb_userdata(NULL),
        _call_loginpswwd(NULL),
        _call_loginpswwd_userdata(NULL),
        ops_timeout(),
        connexion_timeout(),
        agent_string(default_agent),
        _proto(DAVIX_PROTOCOL_WEBDAV),
        _session_flag(SESSION_FLAG_KEEP_ALIVE),
        _state_uid(get_requeste_uid())
    {
        timespec_clear(&connexion_timeout);
        timespec_clear(&ops_timeout);
        connexion_timeout.tv_sec = DAVIX_DEFAULT_CONN_TIMEOUT;
        ops_timeout.tv_sec = DAVIX_DEFAULT_OPS_TIMEOUT;
    }

    virtual ~RequestParamsInternal(){
        if(_idlogpass.second.empty() == false){
            // eradicate password from memory
            for(std::string::iterator it = _idlogpass.second.begin(); it < _idlogpass.second.end(); ++it)
                *it = 'a';
        }

    }
    RequestParamsInternal(const RequestParamsInternal & param_private):
        _ssl_check(param_private._ssl_check),
        _redirection(param_private._redirection),
        _ca_path(param_private._ca_path),
        _cli_cert(param_private._cli_cert),
        _idlogpass(param_private._idlogpass),
        _callb(param_private._callb),
        _callb_userdata(param_private._callb_userdata),
        _call_loginpswwd(param_private._call_loginpswwd),
        _call_loginpswwd_userdata(param_private._call_loginpswwd_userdata),
        ops_timeout(),
        connexion_timeout(),
        agent_string(param_private.agent_string),
        _proto(param_private._proto),
        _session_flag(param_private._session_flag),
        _state_uid(param_private._state_uid){

        timespec_copy(&(connexion_timeout), &(param_private.connexion_timeout));
        timespec_copy(&(ops_timeout), &(param_private.ops_timeout));
    }
    bool _ssl_check; // ssl CA check
    bool _redirection; // redirection support

    // CA management
    std::vector<std::string> _ca_path;

    // auth info
    X509Credential _cli_cert;
    std::pair<std::string,std::string> _idlogpass;
    authCallbackClientCertX509 _callb;
    void* _callb_userdata;
    authCallbackLoginPasswordBasic _call_loginpswwd;
    void* _call_loginpswwd_userdata;

    // timeout management
    struct timespec ops_timeout;
    struct timespec connexion_timeout;

    // user agent
    std::string agent_string;

    // proto
    davix_request_protocol_t  _proto;

    // session flag
    int _session_flag;

    // ssl state value, a state uid is used to check if two copy of a requestParam struct are equal
    int _state_uid;

    // method
    inline void regenerateStateUid(){
        _state_uid = get_requeste_uid();
    }

private:
    RequestParamsInternal & operator=(const RequestParamsInternal & params);
};

RequestParams::RequestParams() :
    d_ptr(new RequestParamsInternal())
{

}

RequestParams::RequestParams(const RequestParams& params) :
    d_ptr(new RequestParamsInternal(*(params.d_ptr))){

}

RequestParams::~RequestParams(){
   delete d_ptr;
}

RequestParams::RequestParams(const RequestParams* params) :
    d_ptr( ((params)?(new RequestParamsInternal(*(params->d_ptr))):(new RequestParamsInternal())) ){

}

RequestParams & RequestParams::operator=(const RequestParams & orig){
    if(d_ptr != orig.d_ptr)
        delete d_ptr;
    d_ptr = new RequestParamsInternal(*(orig.d_ptr));
    return *this;
}

bool RequestParams::getSSLCACheck() const{
    return d_ptr->_ssl_check;
}

void RequestParams::setSSLCAcheck(bool chk){
    d_ptr->regenerateStateUid();
    d_ptr->_ssl_check = chk;
}

void RequestParams::setClientCertX509(const X509Credential & cli_cert){
    d_ptr->regenerateStateUid();
    d_ptr->_cli_cert = cli_cert;
}

void RequestParams::setClientLoginPassword(const std::string & login, const std::string & password){
    d_ptr->regenerateStateUid();
    d_ptr->_idlogpass = std::make_pair(login, password);
}

const std::pair<std::string, std::string> & RequestParams::getClientLoginPassword() const{
    return d_ptr->_idlogpass;
}

const X509Credential & RequestParams::getClientCertX509() const{
    return d_ptr->_cli_cert;
}

/// set a callback for X509 client side dynamic authentication
/// this function overwrite \ref setClientCertX509
void RequestParams::setClientCertCallbackX509(authCallbackClientCertX509 callback, void* userdata){
    d_ptr->regenerateStateUid();
    d_ptr->_callb = callback;
    d_ptr->_callb_userdata = userdata;
}

/// return the current client side callback for authentification with the current user data
std::pair<authCallbackClientCertX509,void*> RequestParams::getClientCertCallbackX509() const{
    return std::pair<authCallbackClientCertX509,void*>(d_ptr->_callb, d_ptr->_callb_userdata);
}

/// set a callback for X509 client side dynamic authentication
/// this function overwrite \ref setClientCertX509
void RequestParams::setClientLoginPasswordCallback(authCallbackLoginPasswordBasic callback, void* userdata){
    d_ptr->regenerateStateUid();
    d_ptr->_call_loginpswwd = callback;
    d_ptr->_call_loginpswwd_userdata = userdata;
}

/// return the current client side callback for authentification with the current user data
std::pair<authCallbackLoginPasswordBasic,void*> RequestParams::getClientLoginPasswordCallback() const{
    return std::pair<authCallbackLoginPasswordBasic,void*>(d_ptr->_call_loginpswwd, d_ptr->_call_loginpswwd_userdata);
}

void RequestParams::addCertificateAuthorityPath(const std::string &path){
    d_ptr->regenerateStateUid();
    d_ptr->_ca_path.push_back(path);
}

const std::vector<std::string> & RequestParams::listCertificateAuthorityPath() const{
    return d_ptr->_ca_path;
}

void RequestParams::setConnectionTimeout(struct timespec *conn_timeout1){
    timespec_copy(&(d_ptr->connexion_timeout),conn_timeout1);
}

void RequestParams::setOperationTimeout(struct timespec *ops_timeout1){
    timespec_copy(&(d_ptr->ops_timeout), ops_timeout1);
}

const struct timespec* RequestParams::getConnectionTimeout() const {
    return &d_ptr->connexion_timeout;
}

const struct timespec* RequestParams::getOperationTimeout() const {
    return &d_ptr->ops_timeout;
}

void RequestParams::setTransparentRedirectionSupport(bool redirection){
    d_ptr->regenerateStateUid();
    d_ptr->_redirection = redirection;
}

bool RequestParams::getTransparentRedirectionSupport() const{
    return d_ptr->_redirection;
}

const std::string & RequestParams::getUserAgent() const{
    return d_ptr->agent_string;
}

void RequestParams::setUserAgent(const std::string &user_agent){
    d_ptr->regenerateStateUid();
    d_ptr->agent_string = user_agent;
}

const davix_request_protocol_t RequestParams::getProtocol() const {
    return d_ptr->_proto;
}

void RequestParams::setProtocol(const davix_request_protocol_t proto){
    d_ptr->_proto = proto;
}

void RequestParams::setKeepAlive(const bool keep_alive_flag){
    d_ptr->regenerateStateUid();
    if(keep_alive_flag)
        d_ptr->_session_flag |= SESSION_FLAG_KEEP_ALIVE;
    else
        d_ptr->_session_flag &= ~(SESSION_FLAG_KEEP_ALIVE);
}

const bool RequestParams::getKeepAlive() const{
    return d_ptr->_session_flag & SESSION_FLAG_KEEP_ALIVE;
}

void* RequestParams::getParmState() const{
    // suppress useless warning
    #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
    return (void*) (d_ptr->_state_uid);
}

} // namespace Davix

////////////////////////////////////////////////
////////////////////////////////////////////////
///// C bindings
////////////////////////////////////////////////
////////////////////////////////////////////////

DAVIX_C_DECL_BEGIN

int davix_params_set_ssl_check(davix_params_t params, bool ssl_check, davix_error_t* err){
    davix_return_val_if_fail(params != NULL, -1);
    Davix::RequestParams* p = (Davix::RequestParams*)(params);
    p->setSSLCAcheck(ssl_check);
    return 0;
}

davix_params_t davix_params_new(){
    return (struct davix_request_params*) new Davix::RequestParams();
}

davix_params_t davix_params_copy(davix_params_t p){
    return (struct davix_request_params*) new Davix::RequestParams(*(Davix::RequestParams*) p);
}

void davix_params_free(davix_params_t p){
    if(p){
        delete ((Davix::RequestParams*) p);
    }
}

bool davix_params_get_keep_alive(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getKeepAlive();
}

/// enable or disable http keep alive
void davix_params_set_keep_alive(davix_params_t params, bool keep_alive){
    assert(params);
    ((Davix::RequestParams*) params)->setKeepAlive(keep_alive);
}

void davix_params_set_protocol(davix_params_t params, davix_request_protocol_t protocol){
    assert(params);
    ((Davix::RequestParams*) params)->setProtocol(protocol);
}

davix_request_protocol_t davix_params_get_protocol(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getProtocol();
}

void davix_params_set_trans_redirect(davix_params_t params, bool redirection){
    assert(params);
    ((Davix::RequestParams*) params)->setTransparentRedirectionSupport(redirection);
}

bool davix_params_get_trans_redirect(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getTransparentRedirectionSupport();
}

void davix_params_set_user_agent(davix_params_t params, const char* user_agent){
    assert(params && user_agent);
    ((Davix::RequestParams*) params)->setUserAgent(user_agent);
}

const char* davix_params_get_user_agent(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getUserAgent().c_str();
}

void davix_params_set_conn_timeout(davix_params_t params, unsigned int timeout){
    assert(params);
    struct timespec t;
    t.tv_sec = timeout;
    t.tv_nsec =0;
    return ((Davix::RequestParams*) params)->setConnectionTimeout(&t);
}

unsigned int davix_params_get_conn_timeout(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getConnectionTimeout()->tv_sec;
}

void davix_params_set_ops_timeout(davix_params_t params, unsigned int timeout){
    assert(params);
    struct timespec t;
    t.tv_sec = timeout;
    t.tv_nsec =0;
    return ((Davix::RequestParams*) params)->setOperationTimeout(&t);
}

unsigned int davix_params_get_ops_timeout(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getOperationTimeout()->tv_sec;
}

void davix_params_set_client_cert_X509(davix_params_t params, davix_x509_cert_t cred){
    assert(params && cred);
    ((Davix::RequestParams*) params)->setClientCertX509(*(Davix::X509Credential*) cred);
}

davix_x509_cert_t  davix_params_get_client_cert_X509(davix_params_t params){
    assert(params);
    return (davix_x509_cert_t) &((Davix::RequestParams*) params)->getClientCertX509();
}

/// set login/password for HTTP Authentication
void davix_params_set_login_passwd(davix_params_t params, const char* login, const char*  password){
    assert(params && login && password);
    ((Davix::RequestParams*) params)->setClientLoginPassword(login, password);
}

DAVIX_C_DECL_END
<commit_msg>- move warning suppressor t oglobal scope.. triggers errors on SL6 else<commit_after>#include <config.h>
#include <cassert>
#include <logger/davix_logger_internal.h>
#include <auth/davixauth.h>
#include <params/davixrequestparams.hpp>
#include <libs/time_utils.h>

namespace Davix {

const char * default_agent = "libdavix/0.0.9";
volatile int state_value =0;

inline int get_requeste_uid(){
    state_value +=1;
    return state_value;
}

#define SESSION_FLAG_KEEP_ALIVE 0x01

struct RequestParamsInternal{
    RequestParamsInternal() :
        _ssl_check(true),
        _redirection(true),
        _ca_path(),
        _cli_cert(),
        _idlogpass(),
        _callb(NULL),
        _callb_userdata(NULL),
        _call_loginpswwd(NULL),
        _call_loginpswwd_userdata(NULL),
        ops_timeout(),
        connexion_timeout(),
        agent_string(default_agent),
        _proto(DAVIX_PROTOCOL_WEBDAV),
        _session_flag(SESSION_FLAG_KEEP_ALIVE),
        _state_uid(get_requeste_uid())
    {
        timespec_clear(&connexion_timeout);
        timespec_clear(&ops_timeout);
        connexion_timeout.tv_sec = DAVIX_DEFAULT_CONN_TIMEOUT;
        ops_timeout.tv_sec = DAVIX_DEFAULT_OPS_TIMEOUT;
    }

    virtual ~RequestParamsInternal(){
        if(_idlogpass.second.empty() == false){
            // eradicate password from memory
            for(std::string::iterator it = _idlogpass.second.begin(); it < _idlogpass.second.end(); ++it)
                *it = 'a';
        }

    }
    RequestParamsInternal(const RequestParamsInternal & param_private):
        _ssl_check(param_private._ssl_check),
        _redirection(param_private._redirection),
        _ca_path(param_private._ca_path),
        _cli_cert(param_private._cli_cert),
        _idlogpass(param_private._idlogpass),
        _callb(param_private._callb),
        _callb_userdata(param_private._callb_userdata),
        _call_loginpswwd(param_private._call_loginpswwd),
        _call_loginpswwd_userdata(param_private._call_loginpswwd_userdata),
        ops_timeout(),
        connexion_timeout(),
        agent_string(param_private.agent_string),
        _proto(param_private._proto),
        _session_flag(param_private._session_flag),
        _state_uid(param_private._state_uid){

        timespec_copy(&(connexion_timeout), &(param_private.connexion_timeout));
        timespec_copy(&(ops_timeout), &(param_private.ops_timeout));
    }
    bool _ssl_check; // ssl CA check
    bool _redirection; // redirection support

    // CA management
    std::vector<std::string> _ca_path;

    // auth info
    X509Credential _cli_cert;
    std::pair<std::string,std::string> _idlogpass;
    authCallbackClientCertX509 _callb;
    void* _callb_userdata;
    authCallbackLoginPasswordBasic _call_loginpswwd;
    void* _call_loginpswwd_userdata;

    // timeout management
    struct timespec ops_timeout;
    struct timespec connexion_timeout;

    // user agent
    std::string agent_string;

    // proto
    davix_request_protocol_t  _proto;

    // session flag
    int _session_flag;

    // ssl state value, a state uid is used to check if two copy of a requestParam struct are equal
    int _state_uid;

    // method
    inline void regenerateStateUid(){
        _state_uid = get_requeste_uid();
    }

private:
    RequestParamsInternal & operator=(const RequestParamsInternal & params);
};

RequestParams::RequestParams() :
    d_ptr(new RequestParamsInternal())
{

}

RequestParams::RequestParams(const RequestParams& params) :
    d_ptr(new RequestParamsInternal(*(params.d_ptr))){

}

RequestParams::~RequestParams(){
   delete d_ptr;
}

RequestParams::RequestParams(const RequestParams* params) :
    d_ptr( ((params)?(new RequestParamsInternal(*(params->d_ptr))):(new RequestParamsInternal())) ){

}

RequestParams & RequestParams::operator=(const RequestParams & orig){
    if(d_ptr != orig.d_ptr)
        delete d_ptr;
    d_ptr = new RequestParamsInternal(*(orig.d_ptr));
    return *this;
}

bool RequestParams::getSSLCACheck() const{
    return d_ptr->_ssl_check;
}

void RequestParams::setSSLCAcheck(bool chk){
    d_ptr->regenerateStateUid();
    d_ptr->_ssl_check = chk;
}

void RequestParams::setClientCertX509(const X509Credential & cli_cert){
    d_ptr->regenerateStateUid();
    d_ptr->_cli_cert = cli_cert;
}

void RequestParams::setClientLoginPassword(const std::string & login, const std::string & password){
    d_ptr->regenerateStateUid();
    d_ptr->_idlogpass = std::make_pair(login, password);
}

const std::pair<std::string, std::string> & RequestParams::getClientLoginPassword() const{
    return d_ptr->_idlogpass;
}

const X509Credential & RequestParams::getClientCertX509() const{
    return d_ptr->_cli_cert;
}

/// set a callback for X509 client side dynamic authentication
/// this function overwrite \ref setClientCertX509
void RequestParams::setClientCertCallbackX509(authCallbackClientCertX509 callback, void* userdata){
    d_ptr->regenerateStateUid();
    d_ptr->_callb = callback;
    d_ptr->_callb_userdata = userdata;
}

/// return the current client side callback for authentification with the current user data
std::pair<authCallbackClientCertX509,void*> RequestParams::getClientCertCallbackX509() const{
    return std::pair<authCallbackClientCertX509,void*>(d_ptr->_callb, d_ptr->_callb_userdata);
}

/// set a callback for X509 client side dynamic authentication
/// this function overwrite \ref setClientCertX509
void RequestParams::setClientLoginPasswordCallback(authCallbackLoginPasswordBasic callback, void* userdata){
    d_ptr->regenerateStateUid();
    d_ptr->_call_loginpswwd = callback;
    d_ptr->_call_loginpswwd_userdata = userdata;
}

/// return the current client side callback for authentification with the current user data
std::pair<authCallbackLoginPasswordBasic,void*> RequestParams::getClientLoginPasswordCallback() const{
    return std::pair<authCallbackLoginPasswordBasic,void*>(d_ptr->_call_loginpswwd, d_ptr->_call_loginpswwd_userdata);
}

void RequestParams::addCertificateAuthorityPath(const std::string &path){
    d_ptr->regenerateStateUid();
    d_ptr->_ca_path.push_back(path);
}

const std::vector<std::string> & RequestParams::listCertificateAuthorityPath() const{
    return d_ptr->_ca_path;
}

void RequestParams::setConnectionTimeout(struct timespec *conn_timeout1){
    timespec_copy(&(d_ptr->connexion_timeout),conn_timeout1);
}

void RequestParams::setOperationTimeout(struct timespec *ops_timeout1){
    timespec_copy(&(d_ptr->ops_timeout), ops_timeout1);
}

const struct timespec* RequestParams::getConnectionTimeout() const {
    return &d_ptr->connexion_timeout;
}

const struct timespec* RequestParams::getOperationTimeout() const {
    return &d_ptr->ops_timeout;
}

void RequestParams::setTransparentRedirectionSupport(bool redirection){
    d_ptr->regenerateStateUid();
    d_ptr->_redirection = redirection;
}

bool RequestParams::getTransparentRedirectionSupport() const{
    return d_ptr->_redirection;
}

const std::string & RequestParams::getUserAgent() const{
    return d_ptr->agent_string;
}

void RequestParams::setUserAgent(const std::string &user_agent){
    d_ptr->regenerateStateUid();
    d_ptr->agent_string = user_agent;
}

const davix_request_protocol_t RequestParams::getProtocol() const {
    return d_ptr->_proto;
}

void RequestParams::setProtocol(const davix_request_protocol_t proto){
    d_ptr->_proto = proto;
}

void RequestParams::setKeepAlive(const bool keep_alive_flag){
    d_ptr->regenerateStateUid();
    if(keep_alive_flag)
        d_ptr->_session_flag |= SESSION_FLAG_KEEP_ALIVE;
    else
        d_ptr->_session_flag &= ~(SESSION_FLAG_KEEP_ALIVE);
}

const bool RequestParams::getKeepAlive() const{
    return d_ptr->_session_flag & SESSION_FLAG_KEEP_ALIVE;
}

// suppress useless warning
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
void* RequestParams::getParmState() const{

    return (void*) (d_ptr->_state_uid);
}

} // namespace Davix

////////////////////////////////////////////////
////////////////////////////////////////////////
///// C bindings
////////////////////////////////////////////////
////////////////////////////////////////////////

DAVIX_C_DECL_BEGIN

int davix_params_set_ssl_check(davix_params_t params, bool ssl_check, davix_error_t* err){
    davix_return_val_if_fail(params != NULL, -1);
    Davix::RequestParams* p = (Davix::RequestParams*)(params);
    p->setSSLCAcheck(ssl_check);
    return 0;
}

davix_params_t davix_params_new(){
    return (struct davix_request_params*) new Davix::RequestParams();
}

davix_params_t davix_params_copy(davix_params_t p){
    return (struct davix_request_params*) new Davix::RequestParams(*(Davix::RequestParams*) p);
}

void davix_params_free(davix_params_t p){
    if(p){
        delete ((Davix::RequestParams*) p);
    }
}

bool davix_params_get_keep_alive(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getKeepAlive();
}

/// enable or disable http keep alive
void davix_params_set_keep_alive(davix_params_t params, bool keep_alive){
    assert(params);
    ((Davix::RequestParams*) params)->setKeepAlive(keep_alive);
}

void davix_params_set_protocol(davix_params_t params, davix_request_protocol_t protocol){
    assert(params);
    ((Davix::RequestParams*) params)->setProtocol(protocol);
}

davix_request_protocol_t davix_params_get_protocol(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getProtocol();
}

void davix_params_set_trans_redirect(davix_params_t params, bool redirection){
    assert(params);
    ((Davix::RequestParams*) params)->setTransparentRedirectionSupport(redirection);
}

bool davix_params_get_trans_redirect(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getTransparentRedirectionSupport();
}

void davix_params_set_user_agent(davix_params_t params, const char* user_agent){
    assert(params && user_agent);
    ((Davix::RequestParams*) params)->setUserAgent(user_agent);
}

const char* davix_params_get_user_agent(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getUserAgent().c_str();
}

void davix_params_set_conn_timeout(davix_params_t params, unsigned int timeout){
    assert(params);
    struct timespec t;
    t.tv_sec = timeout;
    t.tv_nsec =0;
    return ((Davix::RequestParams*) params)->setConnectionTimeout(&t);
}

unsigned int davix_params_get_conn_timeout(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getConnectionTimeout()->tv_sec;
}

void davix_params_set_ops_timeout(davix_params_t params, unsigned int timeout){
    assert(params);
    struct timespec t;
    t.tv_sec = timeout;
    t.tv_nsec =0;
    return ((Davix::RequestParams*) params)->setOperationTimeout(&t);
}

unsigned int davix_params_get_ops_timeout(davix_params_t params){
    assert(params);
    return ((Davix::RequestParams*) params)->getOperationTimeout()->tv_sec;
}

void davix_params_set_client_cert_X509(davix_params_t params, davix_x509_cert_t cred){
    assert(params && cred);
    ((Davix::RequestParams*) params)->setClientCertX509(*(Davix::X509Credential*) cred);
}

davix_x509_cert_t  davix_params_get_client_cert_X509(davix_params_t params){
    assert(params);
    return (davix_x509_cert_t) &((Davix::RequestParams*) params)->getClientCertX509();
}

/// set login/password for HTTP Authentication
void davix_params_set_login_passwd(davix_params_t params, const char* login, const char*  password){
    assert(params && login && password);
    ((Davix::RequestParams*) params)->setClientLoginPassword(login, password);
}

DAVIX_C_DECL_END
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 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
 *
 *****************************************************************************/
// mapnik
#include <mapnik/feature_factory.hpp>
#include <mapnik/geometry.hpp>

#include <mapnik/util/geometry_to_wkt.hpp>

#include <string>
#include <vector>

// yajl
#include "yajl/yajl_parse.h"

#include "jit_featureset.hpp"

mapnik::transcoder* tr = new mapnik::transcoder("utf-8");

static int gj_start_map(void * ctx) {
    return 1;
}

static int gj_map_key(void * ctx, const unsigned char* key, size_t t) {
    std::string key_ = std::string((const char*) key, t);
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_properties) {
        cs->property_name = key_;
    } else {
        if (key_ == "features") {
            cs->state = parser_in_features;
        } else if (key_ == "geometry") {
            cs->state = parser_in_geometry;
        } else if ((cs->state == parser_in_geometry) &&
            (key_ == "type")) {
            cs->state = parser_in_type;
        } else if (key_ == "properties") {
            cs->state = parser_in_properties;
        } else if (key_ == "coordinates") {
            cs->state = parser_in_coordinates;
        }
    }
    return 1;
}

static int gj_end_map(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);

    if ((cs->state == parser_in_properties) ||
        (cs->state == parser_in_geometry)) {
        cs->state = parser_in_feature;
    } else if (cs->state == parser_in_feature) {
        if (cs->geometry_type == "Point") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::Point);
            pt->move_to(
                cs->point_cache.at(0).at(0),
                cs->point_cache.at(0).at(1));
            cs->feature->add_geometry(pt);
        } else if (cs->geometry_type == "LineString") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::LineString);

            pt->set_capacity(cs->point_cache.at(0).size() / 2);
            pt->move_to(
                cs->point_cache.at(0).at(0),
                cs->point_cache.at(0).at(1));

            for (int i = 2;
                i < cs->point_cache.at(0).size();
                i += 2) {
                pt->line_to(
                    cs->point_cache.at(0).at(i),
                    cs->point_cache.at(0).at(i + 1));
            }
            cs->feature->add_geometry(pt);
        } else if (cs->geometry_type == "MultiLineString") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::MultiLineString);

            for (int i = 0; i < cs->point_cache.size(); i++) {
                pt->set_capacity(cs->point_cache.at(i).size() / 2);
                pt->move_to(
                    cs->point_cache.at(i).at(0),
                    cs->point_cache.at(i).at(1));

                for (int j = 2;
                    j < cs->point_cache.at(i).size();
                    j += 2) {
                    pt->line_to(
                        cs->point_cache.at(i).at(j),
                        cs->point_cache.at(i).at(j + 1));
                }
            }
            cs->feature->add_geometry(pt);
        }
        cs->state = parser_in_features;
        cs->done = 1;
    }
    return 1;
}

static int gj_null(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_properties) {
        boost::put(*(cs)->feature,
            cs->property_name, mapnik::value_null());
    }
    return 1;
}

static int gj_boolean(void * ctx, int x) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_properties) {
        boost::put(*(cs)->feature, cs->property_name, x);
    }
    return 1;
}

static int gj_number(void * ctx, const char* str, size_t t) {
    fm *cs = static_cast<fm*>(ctx);
    double x = strtod(str, NULL);

    if (cs->state == parser_in_coordinates) {
        if (cs->coord_dimensions == 2) {
            cs->point_cache.at(0).push_back(x);
        } else if (cs->coord_dimensions == 3) {
            cs->point_cache.back().push_back(x);
        }
    }
    if (cs->state == parser_in_properties) {
        boost::put(*(cs)->feature, cs->property_name, x);
    }
    return 1;
}

static int gj_string(void * ctx, const unsigned char* str, size_t t) {
    fm *cs = static_cast<fm*>(ctx);
    std::string str_ = std::string((const char*) str, t);
    if (cs->state == parser_in_type) {
        cs->geometry_type = str_;
    } else if (cs->state == parser_in_properties) {
        UnicodeString ustr = tr->transcode(str_.c_str());
        boost::put(*(cs)->feature, cs->property_name, ustr);
    }
    return 1;
}

static int gj_start_array(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_coordinates) {
        if (cs->coord_dimensions == 1) {
            std::vector <double> sub_cache;
            cs->point_cache.push_back(sub_cache);
        }
        cs->coord_dimensions++;
    }
    return 1;
}

static int gj_end_array(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_coordinates) {
        cs->coord_dimensions--;
        if (cs->coord_dimensions < 1) {
            cs->state = parser_in_geometry;
        }
    } else if (cs->state == parser_in_features) {
        cs->state = parser_outside;
    }
    return 1;
}

static yajl_callbacks callbacks = {
    gj_null,
    gj_boolean,
    NULL,
    NULL,
    gj_number,
    gj_string,
    gj_start_map,
    gj_map_key,
    gj_end_map,
    gj_start_array,
    gj_end_array
};

jit_featureset::jit_featureset(
    mapnik::box2d<double> const& box,
    std::string input_string,
    std::string const& encoding)
    : box_(box),
      feature_id_(1),
      input_string_(input_string),
      tr_(new mapnik::transcoder(encoding)) {

    std::clog << "starting and done is " << state_bundle.done << std::endl;

    state_bundle.state = parser_outside;
    state_bundle.done = 0;

    hand = yajl_alloc(
        &callbacks, NULL,
        &state_bundle);

    yajl_config(hand, yajl_allow_comments, 1);
    yajl_config(hand, yajl_allow_trailing_garbage, 1);

    mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));
    state_bundle.feature = feature;

    for (itt_ = 0; itt_ < input_string_.length(); itt_++) {
        int parse_result;

        parse_result = yajl_parse(hand,
                (const unsigned char*) &input_string_[itt_], 1);

        if (parse_result == yajl_status_error) {
            unsigned char *str = yajl_get_error(hand,
                1,  (const unsigned char*) input_string_.c_str(),
                input_string_.length());
            std::ostringstream errmsg;
            errmsg << "GeoJSON Plugin: invalid GeoJSON detected: " << (const char*) str << "\n";
            yajl_free_error(hand, str);
            throw mapnik::datasource_exception(errmsg.str());
        } else if (state_bundle.done == 1) {
            features_.push_back(state_bundle.feature);

            feature_id_++;
            mapnik::feature_ptr
              feature(mapnik::feature_factory::create(feature_id_));

            // reset
            state_bundle.point_cache.clear();
            state_bundle.done = 0;
            state_bundle.geometry_type = "";
            state_bundle.feature = feature;
        }
    }

    yajl_free(hand);

    std::clog << "JIT: done parsing features\n";
    std::clog << "JIT: collected " << feature_id_ << " features\n";
    std::clog << "JIT: itt ended at " << itt_ << " \n";

    feature_id_ = 0;
}

jit_featureset::~jit_featureset() { }

mapnik::feature_ptr jit_featureset::next() {
    feature_id_++;
    if (feature_id_ <= features_.size()) {
        return features_.at(feature_id_ - 1);
    } else {
        return mapnik::feature_ptr();
    }
}
<commit_msg>Support Polygon geometries. Fixes #6<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 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
 *
 *****************************************************************************/
// mapnik
#include <mapnik/feature_factory.hpp>
#include <mapnik/geometry.hpp>

#include <mapnik/util/geometry_to_wkt.hpp>

#include <string>
#include <vector>

// yajl
#include "yajl/yajl_parse.h"

#include "jit_featureset.hpp"

mapnik::transcoder* tr = new mapnik::transcoder("utf-8");

static int gj_start_map(void * ctx) {
    return 1;
}

static int gj_map_key(void * ctx, const unsigned char* key, size_t t) {
    std::string key_ = std::string((const char*) key, t);
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_properties) {
        cs->property_name = key_;
    } else {
        if (key_ == "features") {
            cs->state = parser_in_features;
        } else if (key_ == "geometry") {
            cs->state = parser_in_geometry;
        } else if ((cs->state == parser_in_geometry) &&
            (key_ == "type")) {
            cs->state = parser_in_type;
        } else if (key_ == "properties") {
            cs->state = parser_in_properties;
        } else if (key_ == "coordinates") {
            cs->state = parser_in_coordinates;
        }
    }
    return 1;
}

static int gj_end_map(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);

    if ((cs->state == parser_in_properties) ||
        (cs->state == parser_in_geometry)) {
        cs->state = parser_in_feature;
    } else if (cs->state == parser_in_feature) {
        if (cs->geometry_type == "Point") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::Point);
            pt->move_to(
                cs->point_cache.at(0).at(0),
                cs->point_cache.at(0).at(1));
            cs->feature->add_geometry(pt);
        } else if (cs->geometry_type == "Polygon") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::Polygon);

            pt->set_capacity(cs->point_cache.at(0).size() / 2);
            pt->move_to(
                cs->point_cache.at(0).at(0),
                cs->point_cache.at(0).at(1));

            for (int i = 2;
                i < cs->point_cache.at(0).size();
                i += 2) {
                pt->line_to(
                    cs->point_cache.at(0).at(i),
                    cs->point_cache.at(0).at(i + 1));
            }
            cs->feature->add_geometry(pt);
        } else if (cs->geometry_type == "LineString") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::LineString);

            pt->set_capacity(cs->point_cache.at(0).size() / 2);
            pt->move_to(
                cs->point_cache.at(0).at(0),
                cs->point_cache.at(0).at(1));

            for (int i = 2;
                i < cs->point_cache.at(0).size();
                i += 2) {
                pt->line_to(
                    cs->point_cache.at(0).at(i),
                    cs->point_cache.at(0).at(i + 1));
            }
            cs->feature->add_geometry(pt);
        } else if (cs->geometry_type == "MultiLineString") {
            mapnik::geometry_type * pt;
            pt = new mapnik::geometry_type(mapnik::MultiLineString);

            for (int i = 0; i < cs->point_cache.size(); i++) {
                pt->set_capacity(cs->point_cache.at(i).size() / 2);
                pt->move_to(
                    cs->point_cache.at(i).at(0),
                    cs->point_cache.at(i).at(1));

                for (int j = 2;
                    j < cs->point_cache.at(i).size();
                    j += 2) {
                    pt->line_to(
                        cs->point_cache.at(i).at(j),
                        cs->point_cache.at(i).at(j + 1));
                }
            }
            cs->feature->add_geometry(pt);
        }
        cs->state = parser_in_features;
        cs->done = 1;
    }
    return 1;
}

static int gj_null(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_properties) {
        boost::put(*(cs)->feature,
            cs->property_name, mapnik::value_null());
    }
    return 1;
}

static int gj_boolean(void * ctx, int x) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_properties) {
        boost::put(*(cs)->feature, cs->property_name, x);
    }
    return 1;
}

static int gj_number(void * ctx, const char* str, size_t t) {
    fm *cs = static_cast<fm*>(ctx);
    double x = strtod(str, NULL);

    if (cs->state == parser_in_coordinates) {
        if (cs->coord_dimensions == 2) {
            cs->point_cache.at(0).push_back(x);
        } else if (cs->coord_dimensions == 3) {
            cs->point_cache.back().push_back(x);
        }
    }
    if (cs->state == parser_in_properties) {
        boost::put(*(cs)->feature, cs->property_name, x);
    }
    return 1;
}

static int gj_string(void * ctx, const unsigned char* str, size_t t) {
    fm *cs = static_cast<fm*>(ctx);
    std::string str_ = std::string((const char*) str, t);
    if (cs->state == parser_in_type) {
        cs->geometry_type = str_;
    } else if (cs->state == parser_in_properties) {
        UnicodeString ustr = tr->transcode(str_.c_str());
        boost::put(*(cs)->feature, cs->property_name, ustr);
    }
    return 1;
}

static int gj_start_array(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_coordinates) {
        if (cs->coord_dimensions == 1) {
            std::vector <double> sub_cache;
            cs->point_cache.push_back(sub_cache);
        }
        cs->coord_dimensions++;
    }
    return 1;
}

static int gj_end_array(void * ctx) {
    fm *cs = static_cast<fm*>(ctx);
    if (cs->state == parser_in_coordinates) {
        cs->coord_dimensions--;
        if (cs->coord_dimensions < 1) {
            cs->state = parser_in_geometry;
        }
    } else if (cs->state == parser_in_features) {
        cs->state = parser_outside;
    }
    return 1;
}

static yajl_callbacks callbacks = {
    gj_null,
    gj_boolean,
    NULL,
    NULL,
    gj_number,
    gj_string,
    gj_start_map,
    gj_map_key,
    gj_end_map,
    gj_start_array,
    gj_end_array
};

jit_featureset::jit_featureset(
    mapnik::box2d<double> const& box,
    std::string input_string,
    std::string const& encoding)
    : box_(box),
      feature_id_(1),
      input_string_(input_string),
      tr_(new mapnik::transcoder(encoding)) {

    std::clog << "starting and done is " << state_bundle.done << std::endl;

    state_bundle.state = parser_outside;
    state_bundle.done = 0;

    hand = yajl_alloc(
        &callbacks, NULL,
        &state_bundle);

    yajl_config(hand, yajl_allow_comments, 1);
    yajl_config(hand, yajl_allow_trailing_garbage, 1);

    mapnik::feature_ptr feature(mapnik::feature_factory::create(feature_id_));
    state_bundle.feature = feature;

    for (itt_ = 0; itt_ < input_string_.length(); itt_++) {
        int parse_result;

        parse_result = yajl_parse(hand,
                (const unsigned char*) &input_string_[itt_], 1);

        if (parse_result == yajl_status_error) {
            unsigned char *str = yajl_get_error(hand,
                1,  (const unsigned char*) input_string_.c_str(),
                input_string_.length());
            std::ostringstream errmsg;
            errmsg << "GeoJSON Plugin: invalid GeoJSON detected: " << (const char*) str << "\n";
            yajl_free_error(hand, str);
            throw mapnik::datasource_exception(errmsg.str());
        } else if (state_bundle.done == 1) {
            features_.push_back(state_bundle.feature);

            feature_id_++;
            mapnik::feature_ptr
              feature(mapnik::feature_factory::create(feature_id_));

            // reset
            state_bundle.point_cache.clear();
            state_bundle.done = 0;
            state_bundle.geometry_type = "";
            state_bundle.feature = feature;
        }
    }

    yajl_free(hand);

    std::clog << "JIT: done parsing features\n";
    std::clog << "JIT: collected " << feature_id_ << " features\n";
    std::clog << "JIT: itt ended at " << itt_ << " \n";

    feature_id_ = 0;
}

jit_featureset::~jit_featureset() { }

mapnik::feature_ptr jit_featureset::next() {
    feature_id_++;
    if (feature_id_ <= features_.size()) {
        return features_.at(feature_id_ - 1);
    } else {
        return mapnik::feature_ptr();
    }
}
<|endoftext|>


<commit_before>/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

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

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

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

//#define NDEBUG
#include "radioInterface.h"
#include <Logger.h>

GSM::Time VectorQueue::nextTime() const
{
  GSM::Time retVal;
  ScopedLock lock(mLock);
  while (mQ.size()==0) mWriteSignal.wait(mLock);
  return mQ.top()->time();
}

radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() < targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() == targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

RadioInterface::RadioInterface(RadioDevice *wRadio,
                               int wReceiveOffset,
			       int wRadioOversampling,
			       int wTransceiverOversampling,
			       GSM::Time wStartTime)

{
  underrun = false;

  sendCursor = 0;
  rcvCursor = 0;
  mOn = false;

  mRadio = wRadio;
  receiveOffset = wReceiveOffset;
  samplesPerSymbol = wRadioOversampling;
  mClock.set(wStartTime);
  powerScaling = 1.0;
  loadTest = false;
}

RadioInterface::~RadioInterface(void) {
  if (rcvBuffer!=NULL) delete rcvBuffer;
  //mReceiveFIFO.clear();
}

double RadioInterface::fullScaleInputValue(void) {
  return mRadio->fullScaleInputValue();
}

double RadioInterface::fullScaleOutputValue(void) {
  return mRadio->fullScaleOutputValue();
}

void RadioInterface::setPowerAttenuation(double dBAtten)
{
  float HWdBAtten = mRadio->setTxGain(-dBAtten);
  dBAtten -= (-HWdBAtten);
  float linearAtten = powf(10.0F,0.1F*dBAtten);
  if (linearAtten < 1.0)
    powerScaling = 1.0;
  else
    powerScaling = 1.0/sqrt(linearAtten);
  LOG(INFO) << "setting HW gain to " << HWdBAtten << " and power scaling to " << powerScaling;
}

short *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, double scale, bool zeroOut)
{

  signalVector::iterator itr = wVector.begin();
  short *shortItr = retVector;
  if (zeroOut) {
    while (itr < wVector.end()) {
      *shortItr++ = 0;
      *shortItr++ = 0;
      itr++;
    }
  }
  else if (scale != 1.0) {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real()*scale);
      *shortItr++ = (short) (itr->imag()*scale);
      itr++;
    }
  }
  else {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real());
      *shortItr++ = (short) (itr->imag());
      itr++;
    }
  }

  return retVector;

}

void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)
{

  signalVector::iterator itr = newVector.begin();
  short *shortItr = shortVector;
  while (itr < newVector.end()) {
    *itr++ = Complex<float>(*shortItr,*(shortItr+1));
    //LOG(DEBUG) << (*(itr-1));
    shortItr += 2;
  }

}

bool started = false;

void RadioInterface::pushBuffer(void) {

  if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;

  // send resampleVector
  int samplesWritten = mRadio->writeSamples(sendBuffer,
					  INCHUNK*samplesPerSymbol,
					  &underrun,
					  writeTimestamp);
  //LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;

  writeTimestamp += (TIMESTAMP) samplesWritten;

  if (sendCursor > 2*samplesWritten)
    memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));
  sendCursor = sendCursor - 2*samplesWritten;
}

void RadioInterface::pullBuffer(void)
{

  bool localUnderrun;

   // receive receiveVector
  short* shortVector = rcvBuffer+rcvCursor;
  //LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp;
  int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);
  underrun |= localUnderrun;
  readTimestamp += (TIMESTAMP) samplesRead;
  while (samplesRead < OUTCHUNK*samplesPerSymbol) {
    int oldSamplesRead = samplesRead;
    samplesRead += mRadio->readSamples(shortVector+2*samplesRead,
				     OUTCHUNK*samplesPerSymbol-samplesRead,
				     &overrun,
				     readTimestamp,
				     &localUnderrun);
    underrun |= localUnderrun;
    readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
  }
  //LOG(DEBUG) << "samplesRead " << samplesRead;

  rcvCursor += samplesRead*2;

}

bool RadioInterface::tuneTx(double freq)
{
  return mRadio->setTxFreq(freq);
}

bool RadioInterface::tuneRx(double freq)
{
  return mRadio->setRxFreq(freq);
}

void RadioInterface::start()
{
  LOG(INFO) << "starting radio interface...";
  mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
                                     (void*)this);
  writeTimestamp = mRadio->initialWriteTimestamp();
  readTimestamp = mRadio->initialReadTimestamp();
  mRadio->start();
  LOG(DEBUG) << "Radio started";
  mRadio->updateAlignment(writeTimestamp-10000);
  mRadio->updateAlignment(writeTimestamp-10000);

  sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];
  rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];

  mOn = true;

}

void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
  while (1) {
    radioInterface->alignRadio();
    pthread_testcancel();
  }
  return NULL;
}

void RadioInterface::alignRadio() {
  sleep(60);
  mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}

void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {

  if (!mOn) return;

  radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);

  sendCursor += (radioBurst.size()*2);

  pushBuffer();
}

void RadioInterface::driveReceiveRadio() {

  if (!mOn) return;

  if (mReceiveFIFO.size() > 8) return;

  pullBuffer();

  GSM::Time rcvClock = mClock.get();
  rcvClock.decTN(receiveOffset);
  unsigned tN = rcvClock.TN();
  int rcvSz = rcvCursor/2;
  int readSz = 0;
  const int symbolsPerSlot = gSlotLen + 8;

  // while there's enough data in receive buffer, form received
  //    GSM bursts and pass up to Transceiver
  // Using the 157-156-156-156 symbols per timeslot format.
  while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
    signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
    unRadioifyVector(rcvBuffer+readSz*2,rxVector);
    GSM::Time tmpTime = rcvClock;
    if (rcvClock.FN() >= 0) {
      //LOG(DEBUG) << "FN: " << rcvClock.FN();
      radioVector *rxBurst = NULL;
      if (!loadTest)
        rxBurst = new radioVector(rxVector,tmpTime);
      else {
	if (tN % 4 == 0)
	  rxBurst = new radioVector(*finalVec9,tmpTime);
        else
          rxBurst = new radioVector(*finalVec,tmpTime);
      }
      mReceiveFIFO.put(rxBurst);
    }
    mClock.incTN();
    rcvClock.incTN();
    //if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
    //LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
    readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
    rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;

    tN = rcvClock.TN();
  }

  if (readSz > 0) {
    memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));
    rcvCursor = rcvCursor-2*readSz;
  }
}

<commit_msg>uhd: set attenuation relative to max RF gain<commit_after>/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
*
* This software is distributed under the terms of the GNU Affero Public License.
* See the COPYING file in the main directory for details.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.

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

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

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

//#define NDEBUG
#include "radioInterface.h"
#include <Logger.h>

GSM::Time VectorQueue::nextTime() const
{
  GSM::Time retVal;
  ScopedLock lock(mLock);
  while (mQ.size()==0) mWriteSignal.wait(mLock);
  return mQ.top()->time();
}

radioVector* VectorQueue::getStaleBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() < targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

radioVector* VectorQueue::getCurrentBurst(const GSM::Time& targTime)
{
  ScopedLock lock(mLock);
  if ((mQ.size()==0)) {
    return NULL;
  }
  if (mQ.top()->time() == targTime) {
    radioVector* retVal = mQ.top();
    mQ.pop();
    return retVal;
  }
  return NULL;
}

RadioInterface::RadioInterface(RadioDevice *wRadio,
                               int wReceiveOffset,
			       int wRadioOversampling,
			       int wTransceiverOversampling,
			       GSM::Time wStartTime)

{
  underrun = false;

  sendCursor = 0;
  rcvCursor = 0;
  mOn = false;

  mRadio = wRadio;
  receiveOffset = wReceiveOffset;
  samplesPerSymbol = wRadioOversampling;
  mClock.set(wStartTime);
  powerScaling = 1.0;
  loadTest = false;
}

RadioInterface::~RadioInterface(void) {
  if (rcvBuffer!=NULL) delete rcvBuffer;
  //mReceiveFIFO.clear();
}

double RadioInterface::fullScaleInputValue(void) {
  return mRadio->fullScaleInputValue();
}

double RadioInterface::fullScaleOutputValue(void) {
  return mRadio->fullScaleOutputValue();
}

void RadioInterface::setPowerAttenuation(double dBAtten)
{
  double HWatten = mRadio->setTxGain(mRadio->maxTxGain() - atten);
  atten -= (-HWatten);
  if (atten < 1.0)
    powerScaling = 1.0;
  else
    powerScaling = 1.0/sqrt(linearAtten);
  LOG(INFO) << "setting HW gain to " << HWdBAtten << " and power scaling to " << powerScaling;
}

short *RadioInterface::radioifyVector(signalVector &wVector, short *retVector, double scale, bool zeroOut)
{

  signalVector::iterator itr = wVector.begin();
  short *shortItr = retVector;
  if (zeroOut) {
    while (itr < wVector.end()) {
      *shortItr++ = 0;
      *shortItr++ = 0;
      itr++;
    }
  }
  else if (scale != 1.0) {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real()*scale);
      *shortItr++ = (short) (itr->imag()*scale);
      itr++;
    }
  }
  else {
    while (itr < wVector.end()) {
      *shortItr++ = (short) (itr->real());
      *shortItr++ = (short) (itr->imag());
      itr++;
    }
  }

  return retVector;

}

void RadioInterface::unRadioifyVector(short *shortVector, signalVector& newVector)
{

  signalVector::iterator itr = newVector.begin();
  short *shortItr = shortVector;
  while (itr < newVector.end()) {
    *itr++ = Complex<float>(*shortItr,*(shortItr+1));
    //LOG(DEBUG) << (*(itr-1));
    shortItr += 2;
  }

}

bool started = false;

void RadioInterface::pushBuffer(void) {

  if (sendCursor < 2*INCHUNK*samplesPerSymbol) return;

  // send resampleVector
  int samplesWritten = mRadio->writeSamples(sendBuffer,
					  INCHUNK*samplesPerSymbol,
					  &underrun,
					  writeTimestamp);
  //LOG(DEBUG) << "writeTimestamp: " << writeTimestamp << ", samplesWritten: " << samplesWritten;

  writeTimestamp += (TIMESTAMP) samplesWritten;

  if (sendCursor > 2*samplesWritten)
    memcpy(sendBuffer,sendBuffer+samplesWritten*2,sizeof(short)*2*(sendCursor-2*samplesWritten));
  sendCursor = sendCursor - 2*samplesWritten;
}

void RadioInterface::pullBuffer(void)
{

  bool localUnderrun;

   // receive receiveVector
  short* shortVector = rcvBuffer+rcvCursor;
  //LOG(DEBUG) << "Reading USRP samples at timestamp " << readTimestamp;
  int samplesRead = mRadio->readSamples(shortVector,OUTCHUNK*samplesPerSymbol,&overrun,readTimestamp,&localUnderrun);
  underrun |= localUnderrun;
  readTimestamp += (TIMESTAMP) samplesRead;
  while (samplesRead < OUTCHUNK*samplesPerSymbol) {
    int oldSamplesRead = samplesRead;
    samplesRead += mRadio->readSamples(shortVector+2*samplesRead,
				     OUTCHUNK*samplesPerSymbol-samplesRead,
				     &overrun,
				     readTimestamp,
				     &localUnderrun);
    underrun |= localUnderrun;
    readTimestamp += (TIMESTAMP) (samplesRead - oldSamplesRead);
  }
  //LOG(DEBUG) << "samplesRead " << samplesRead;

  rcvCursor += samplesRead*2;

}

bool RadioInterface::tuneTx(double freq)
{
  return mRadio->setTxFreq(freq);
}

bool RadioInterface::tuneRx(double freq)
{
  return mRadio->setRxFreq(freq);
}

void RadioInterface::start()
{
  LOG(INFO) << "starting radio interface...";
  mAlignRadioServiceLoopThread.start((void * (*)(void*))AlignRadioServiceLoopAdapter,
                                     (void*)this);
  writeTimestamp = mRadio->initialWriteTimestamp();
  readTimestamp = mRadio->initialReadTimestamp();
  mRadio->start();
  LOG(DEBUG) << "Radio started";
  mRadio->updateAlignment(writeTimestamp-10000);
  mRadio->updateAlignment(writeTimestamp-10000);

  sendBuffer = new short[2*2*INCHUNK*samplesPerSymbol];
  rcvBuffer = new short[2*2*OUTCHUNK*samplesPerSymbol];

  mOn = true;

}

void *AlignRadioServiceLoopAdapter(RadioInterface *radioInterface)
{
  while (1) {
    radioInterface->alignRadio();
    pthread_testcancel();
  }
  return NULL;
}

void RadioInterface::alignRadio() {
  sleep(60);
  mRadio->updateAlignment(writeTimestamp+ (TIMESTAMP) 10000);
}

void RadioInterface::driveTransmitRadio(signalVector &radioBurst, bool zeroBurst) {

  if (!mOn) return;

  radioifyVector(radioBurst, sendBuffer+sendCursor, powerScaling, zeroBurst);

  sendCursor += (radioBurst.size()*2);

  pushBuffer();
}

void RadioInterface::driveReceiveRadio() {

  if (!mOn) return;

  if (mReceiveFIFO.size() > 8) return;

  pullBuffer();

  GSM::Time rcvClock = mClock.get();
  rcvClock.decTN(receiveOffset);
  unsigned tN = rcvClock.TN();
  int rcvSz = rcvCursor/2;
  int readSz = 0;
  const int symbolsPerSlot = gSlotLen + 8;

  // while there's enough data in receive buffer, form received
  //    GSM bursts and pass up to Transceiver
  // Using the 157-156-156-156 symbols per timeslot format.
  while (rcvSz > (symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol) {
    signalVector rxVector((symbolsPerSlot + (tN % 4 == 0))*samplesPerSymbol);
    unRadioifyVector(rcvBuffer+readSz*2,rxVector);
    GSM::Time tmpTime = rcvClock;
    if (rcvClock.FN() >= 0) {
      //LOG(DEBUG) << "FN: " << rcvClock.FN();
      radioVector *rxBurst = NULL;
      if (!loadTest)
        rxBurst = new radioVector(rxVector,tmpTime);
      else {
	if (tN % 4 == 0)
	  rxBurst = new radioVector(*finalVec9,tmpTime);
        else
          rxBurst = new radioVector(*finalVec,tmpTime);
      }
      mReceiveFIFO.put(rxBurst);
    }
    mClock.incTN();
    rcvClock.incTN();
    //if (mReceiveFIFO.size() >= 16) mReceiveFIFO.wait(8);
    //LOG(DEBUG) << "receiveFIFO: wrote radio vector at time: " << mClock.get() << ", new size: " << mReceiveFIFO.size() ;
    readSz += (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;
    rcvSz -= (symbolsPerSlot+(tN % 4 == 0))*samplesPerSymbol;

    tN = rcvClock.TN();
  }

  if (readSz > 0) {
    memcpy(rcvBuffer,rcvBuffer+2*readSz,sizeof(short)*2*(rcvCursor-readSz));
    rcvCursor = rcvCursor-2*readSz;
  }
}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <vector>

// void clear() noexcept;

//#include <vector>
//#include <cassert>

//#include "test_macros.h"
//#include "min_allocator.h"
//#include "asan_testing.h"

void main()
{
    {
    int a[] = {1, 2, 3};
    vector<int> c(a, a+3);
    //ASSERT_NOEXCEPT(c.clear());
    c.clear();
    assert(c.empty());
    //LIBCPP_ASSERT(c.__invariants());
    //LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
    }
#if TEST_STD_VER >= 11
    {
    int a[] = {1, 2, 3};
    vector<int, min_allocator<int>> c(a, a+3);
    ASSERT_NOEXCEPT(c.clear());
    c.clear();
    assert(c.empty());
    LIBCPP_ASSERT(c.__invariants());
    LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
    }
#endif
}
<commit_msg>tests/libcxx/vector<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <vector>

// void clear() noexcept;

//#include <vector>
//#include <cassert>

//#include "test_macros.h"
//#include "min_allocator.h"
//#include "asan_testing.h"

void main()
{
    {
    int a[] = {1, 2, 3};
    vector<int> c(a, a+3);
    //ASSERT_NOEXCEPT(c.clear());
    c.clear();
    assert(c.empty());
    //LIBCPP_ASSERT(c.__invariants());
    //LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
    }
//#if TEST_STD_VER >= 11
#ifdef LIBCPP_TEST_MIN_ALLOCATOR
    {
    int a[] = {1, 2, 3};
    vector<int, min_allocator<int>> c(a, a+3);
    ASSERT_NOEXCEPT(c.clear());
    c.clear();
    assert(c.empty());
    LIBCPP_ASSERT(c.__invariants());
    LIBCPP_ASSERT(is_contiguous_container_asan_correct(c));
    }
#endif
}
<|endoftext|>