<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/cursor.hxx
 *
 *   DESCRIPTION
 *      definition of the iterator/container-style cursor classes
 *   C++-style wrappers for SQL cursors
 *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/pipeline instead.
 *
 * Copyright (c) 2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/libcompiler.h"

#include <limits>
#include <string>

#include "pqxx/result"

namespace pqxx
{
class transaction_base;

/// Common definitions for cursor types
/** @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT cursor_base
{
public:
  typedef result::size_type size_type;

  operator void *() const { return m_done ? 0 : &s_dummy; }		//[t81]
  bool operator!() const { return m_done; }				//[t81]

  static size_type all() throw ();					//[t81]
  static size_type next() throw () { return 1; }			//[t81]
  static size_type prior() throw () { return -1; }			//[]
  static size_type backward_all() throw ();				//[]

  const PGSTD::string &name() const throw () { return m_name; }		//[t81]

protected:
  cursor_base(transaction_base *context, const PGSTD::string &cname) :
  	m_context(context), m_done(false), m_name(cname)
  {
    m_name += "_";
    m_name += to_string(get_unique_cursor_num());
  }

  transaction_base *m_context;
  bool m_done;

private:
  int get_unique_cursor_num();

  PGSTD::string m_name;

  /// Purely to give us a non-null pointer to return
  static unsigned char s_dummy;

  /// Not allowed
  cursor_base();
  /// Not allowed
  cursor_base(const cursor_base &);
  /// Not allowed
  cursor_base &operator=(const cursor_base &);
};

inline cursor_base::size_type cursor_base::all() throw ()
{
#ifdef _WIN32
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MAX;
#else
  return PGSTD::numeric_limits<size_type>::max();
#endif
}

inline cursor_base::size_type cursor_base::backward_all() throw ()
{
#ifdef _WIN32
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MIN + 1;
#else
  return PGSTD::numeric_limits<size_type>::min() + 1;
#endif
}

/// Simple read-only cursor represented as a stream of results
/** Data is fetched from the cursor as a sequence of result objects.  Each of
 * these will contain the number of rows defined as the stream's stride, except
 * of course the last block of data which may contain fewer rows.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT icursorstream : public cursor_base
{
public:
  /// Set up a read-only, forward-only cursor
  /** Roughly equivalent to a C++ Standard Library istream, this cursor type
   * supports only two operations: reading a block of rows while moving forward,
   * and moving forward without reading any data.
   *
   * @param context transaction context that this cursor will be active in
   * @param query SQL query whose results this cursor shall iterate
   * @param basename suggested name for the SQL cursor; a unique code will be
   * appended by the library to ensure its uniqueness
   * @param stride the number of rows to fetch per read operation; must be a
   * positive number
   */
  icursorstream(transaction_base &context,
      const PGSTD::string &query,
      const PGSTD::string &basename,
      size_type stride=1);						//[t81]

  /// Read new value into given result object; same as operator >>
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &get(result &res) { res = fetch(); return *this; }	//[]
  /// Read new value into given result object; same as get(result &)
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &operator>>(result &res) { return get(res); }		//[t81]
  /// Move given number of rows forward (ignoring stride) without reading data
  icursorstream &ignore(PGSTD::streamsize n=1);				//[]

  /// Change stride, i.e. the number of rows to fetch per read operation
  /**
   * @param stride must be a positive number
   */
  void set_stride(size_type stride);					//[t81]

private:
  void declare(const PGSTD::string &query);
  result fetch();

  size_type m_stride;
};

/// Approximate istream_iterator for icursorstream
/** A rough equivalent of the C++ Standard Library's istream_iterator or
 * input_iterator, this class supports only two basic operations: reading the
 * current element, and moving forward.  In addition to the minimal guarantees
 * for istream_iterators, this class supports multiple successive reads of the
 * same position (the current result set is cached in the iterator) even after
 * copying and even after new data have been read from the stream.
 *
 * The iterator has no concept of its own position, however.  Moving an iterator
 * forward moves the underlying stream forward and reads the data from the new
 * position, regardless of "where the iterator was" in the stream.  Comparison
 * of iterators is only supported for detecting the end of a stream.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT icursor_iterator :
  public PGSTD::iterator<PGSTD::input_iterator_tag,
  	result,
	cursor_base::size_type,
	const result *,
	const result &>
{
public:
  typedef icursorstream istream_type;
  typedef istream_type::size_type size_type;

  icursor_iterator() : m_stream(0), m_here(), m_fresh(true) {}		//[]
  icursor_iterator(istream_type &s) :					//[]
    m_stream(&s), m_here(), m_fresh(false) {}
  icursor_iterator(const icursor_iterator &rhs) : 			//[]
    m_stream(rhs.m_stream), m_here(rhs.m_here), m_fresh(rhs.m_fresh) {}

  const result &operator*() const { refresh(); return m_here; }		//[]
  const result *operator->() const { refresh(); return &m_here; }	//[]

  icursor_iterator &operator++() { read(); return *this; }		//[]

  icursor_iterator operator++(int)					//[]
  	{ icursor_iterator old(*this); read(); return old; }

  icursor_iterator &operator+=(size_type n)				//[]
  {
    m_stream->ignore(n);
    m_fresh = false;
    return *this;
  }

  icursor_iterator &operator=(const icursor_iterator &rhs)		//[]
  {
    m_here = rhs.m_here;	// (Already protected against self-assignment)
    m_stream = rhs.m_stream;	// (Does not throw, so we're exception-safe)
    m_fresh = rhs.m_fresh;
    return *this;
  }

  bool operator==(const icursor_iterator &rhs) const throw ()		//[]
  	{ return m_here.empty() && rhs.m_here.empty(); }
  bool operator!=(const icursor_iterator &rhs) const throw ()		//[]
  	{ return !operator==(rhs); }

private:
  void read() const
  {
    m_stream->get(m_here);
    m_fresh = true;
  }
  void refresh() const { if (!m_fresh) read(); }
  icursorstream *m_stream;
  mutable result m_here;
  mutable bool m_fresh;
};

} // namespace pqxx

<commit_msg>Fixed ifdefs for MSVC compiler workaround<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/cursor.hxx
 *
 *   DESCRIPTION
 *      definition of the iterator/container-style cursor classes
 *   C++-style wrappers for SQL cursors
 *   DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/pipeline instead.
 *
 * Copyright (c) 2004, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/libcompiler.h"

#include <limits>
#include <string>

#include "pqxx/result"

namespace pqxx
{
class transaction_base;

/// Common definitions for cursor types
/** @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT cursor_base
{
public:
  typedef result::size_type size_type;

  operator void *() const { return m_done ? 0 : &s_dummy; }		//[t81]
  bool operator!() const { return m_done; }				//[t81]

  static size_type all() throw ();					//[t81]
  static size_type next() throw () { return 1; }			//[t81]
  static size_type prior() throw () { return -1; }			//[]
  static size_type backward_all() throw ();				//[]

  const PGSTD::string &name() const throw () { return m_name; }		//[t81]

protected:
  cursor_base(transaction_base *context, const PGSTD::string &cname) :
  	m_context(context), m_done(false), m_name(cname)
  {
    m_name += "_";
    m_name += to_string(get_unique_cursor_num());
  }

  transaction_base *m_context;
  bool m_done;

private:
  int get_unique_cursor_num();

  PGSTD::string m_name;

  /// Purely to give us a non-null pointer to return
  static unsigned char s_dummy;

  /// Not allowed
  cursor_base();
  /// Not allowed
  cursor_base(const cursor_base &);
  /// Not allowed
  cursor_base &operator=(const cursor_base &);
};

inline cursor_base::size_type cursor_base::all() throw ()
{
#ifdef _MSC_VER
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MAX;
#else
  return PGSTD::numeric_limits<size_type>::max();
#endif
}

inline cursor_base::size_type cursor_base::backward_all() throw ()
{
#ifdef _MSC_VER
  // Microsoft's compiler defines max() and min() macros!  Others may as well
  return INT_MIN + 1;
#else
  return PGSTD::numeric_limits<size_type>::min() + 1;
#endif
}

/// Simple read-only cursor represented as a stream of results
/** Data is fetched from the cursor as a sequence of result objects.  Each of
 * these will contain the number of rows defined as the stream's stride, except
 * of course the last block of data which may contain fewer rows.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT icursorstream : public cursor_base
{
public:
  /// Set up a read-only, forward-only cursor
  /** Roughly equivalent to a C++ Standard Library istream, this cursor type
   * supports only two operations: reading a block of rows while moving forward,
   * and moving forward without reading any data.
   *
   * @param context transaction context that this cursor will be active in
   * @param query SQL query whose results this cursor shall iterate
   * @param basename suggested name for the SQL cursor; a unique code will be
   * appended by the library to ensure its uniqueness
   * @param stride the number of rows to fetch per read operation; must be a
   * positive number
   */
  icursorstream(transaction_base &context,
      const PGSTD::string &query,
      const PGSTD::string &basename,
      size_type stride=1);						//[t81]

  /// Read new value into given result object; same as operator >>
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &get(result &res) { res = fetch(); return *this; }	//[]
  /// Read new value into given result object; same as get(result &)
  /** The result set may continue any number of rows from zero to the chosen
   * stride, inclusive.  An empty result will only be returned if there are no
   * more rows to retrieve.
   */
  icursorstream &operator>>(result &res) { return get(res); }		//[t81]
  /// Move given number of rows forward (ignoring stride) without reading data
  icursorstream &ignore(PGSTD::streamsize n=1);				//[]

  /// Change stride, i.e. the number of rows to fetch per read operation
  /**
   * @param stride must be a positive number
   */
  void set_stride(size_type stride);					//[t81]

private:
  void declare(const PGSTD::string &query);
  result fetch();

  size_type m_stride;
};

/// Approximate istream_iterator for icursorstream
/** A rough equivalent of the C++ Standard Library's istream_iterator or
 * input_iterator, this class supports only two basic operations: reading the
 * current element, and moving forward.  In addition to the minimal guarantees
 * for istream_iterators, this class supports multiple successive reads of the
 * same position (the current result set is cached in the iterator) even after
 * copying and even after new data have been read from the stream.
 *
 * The iterator has no concept of its own position, however.  Moving an iterator
 * forward moves the underlying stream forward and reads the data from the new
 * position, regardless of "where the iterator was" in the stream.  Comparison
 * of iterators is only supported for detecting the end of a stream.
 *
 * @warning This code is experimental.  It is not fully covered by libpqxx'
 * regression tests, and may see considerable change before becoming part of a
 * stable release.  Use with care.
 */
class PQXX_LIBEXPORT icursor_iterator :
  public PGSTD::iterator<PGSTD::input_iterator_tag,
  	result,
	cursor_base::size_type,
	const result *,
	const result &>
{
public:
  typedef icursorstream istream_type;
  typedef istream_type::size_type size_type;

  icursor_iterator() : m_stream(0), m_here(), m_fresh(true) {}		//[]
  icursor_iterator(istream_type &s) :					//[]
    m_stream(&s), m_here(), m_fresh(false) {}
  icursor_iterator(const icursor_iterator &rhs) : 			//[]
    m_stream(rhs.m_stream), m_here(rhs.m_here), m_fresh(rhs.m_fresh) {}

  const result &operator*() const { refresh(); return m_here; }		//[]
  const result *operator->() const { refresh(); return &m_here; }	//[]

  icursor_iterator &operator++() { read(); return *this; }		//[]

  icursor_iterator operator++(int)					//[]
  	{ icursor_iterator old(*this); read(); return old; }

  icursor_iterator &operator+=(size_type n)				//[]
  {
    m_stream->ignore(n);
    m_fresh = false;
    return *this;
  }

  icursor_iterator &operator=(const icursor_iterator &rhs)		//[]
  {
    m_here = rhs.m_here;	// (Already protected against self-assignment)
    m_stream = rhs.m_stream;	// (Does not throw, so we're exception-safe)
    m_fresh = rhs.m_fresh;
    return *this;
  }

  bool operator==(const icursor_iterator &rhs) const throw ()		//[]
  	{ return m_here.empty() && rhs.m_here.empty(); }
  bool operator!=(const icursor_iterator &rhs) const throw ()		//[]
  	{ return !operator==(rhs); }

private:
  void read() const
  {
    m_stream->get(m_here);
    m_fresh = true;
  }
  void refresh() const { if (!m_fresh) read(); }
  icursorstream *m_stream;
  mutable result m_here;
  mutable bool m_fresh;
};

} // namespace pqxx

<|endoftext|>


<commit_before>/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "Timer.h"
#include "us_ticker_api.h"

namespace mbed {

Timer::Timer() : _running(), _start(), _time() {
    reset();
}

void Timer::start() {
    _start = us_ticker_read();
    _running = 1;
}

void Timer::stop() {
    _time += slicetime();
    _running = 0;
}

int Timer::read_us() {
    return _time + slicetime();
}

float Timer::read() {
    return (float)read_us() / 1000000.0f;
}

int Timer::read_ms() {
    return read_us() / 1000;
}

int Timer::slicetime() {
    if (_running) {
        return us_ticker_read() - _start;
    } else {
        return 0;
    }
}

void Timer::reset() {
    _start = us_ticker_read();
    _time = 0;
}

#ifdef MBED_OPERATORS
Timer::operator float() {
    return read();
}
#endif

} // namespace mbed
<commit_msg>[API] Timer-start behavior (bug)fix<commit_after>/* mbed Microcontroller Library
 * Copyright (c) 2006-2013 ARM Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "Timer.h"
#include "us_ticker_api.h"

namespace mbed {

Timer::Timer() : _running(), _start(), _time() {
    reset();
}

void Timer::start() {
    if (!_running) {
        _start = us_ticker_read();
        _running = 1;
    }
}

void Timer::stop() {
    _time += slicetime();
    _running = 0;
}

int Timer::read_us() {
    return _time + slicetime();
}

float Timer::read() {
    return (float)read_us() / 1000000.0f;
}

int Timer::read_ms() {
    return read_us() / 1000;
}

int Timer::slicetime() {
    if (_running) {
        return us_ticker_read() - _start;
    } else {
        return 0;
    }
}

void Timer::reset() {
    _start = us_ticker_read();
    _time = 0;
}

#ifdef MBED_OPERATORS
Timer::operator float() {
    return read();
}
#endif

} // namespace mbed
<|endoftext|>


<commit_before><commit_msg>coverity#984152 Uninitialized pointer field<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SwXMLSectionList.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2005-01-05 11:47:12 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#ifndef _SW_XMLSECTIONLIST_HXX
#include <SwXMLSectionList.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;

sal_Char __READONLY_DATA sXML_np__office[] = "_ooffice";
sal_Char __READONLY_DATA sXML_np__text[] = "_otext";

// #110680#
SwXMLSectionList::SwXMLSectionList(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    SvStrings & rNewSectionList)
:   SvXMLImport( xServiceFactory ),
    rSectionList ( rNewSectionList )
{
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),
                            GetXMLToken(XML_N_OFFICE_OOO),
                            XML_NAMESPACE_OFFICE );
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),
                            GetXMLToken(XML_N_TEXT_OOO),
                            XML_NAMESPACE_TEXT );
}

SwXMLSectionList::~SwXMLSectionList ( void )
    throw()
{
}

SvXMLImportContext *SwXMLSectionList::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if  (nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken ( rLocalName, XML_BODY ) ||
         nPrefix == XML_NAMESPACE_TEXT &&
        (IsXMLToken ( rLocalName, XML_P ) ||
         IsXMLToken ( rLocalName, XML_H ) ||
         IsXMLToken ( rLocalName, XML_A ) ||
         IsXMLToken ( rLocalName, XML_SPAN ) ||
         IsXMLToken ( rLocalName, XML_SECTION ) ||
         IsXMLToken ( rLocalName, XML_INDEX_BODY ) ||
         IsXMLToken ( rLocalName, XML_INDEX_TITLE )||
         IsXMLToken ( rLocalName, XML_INSERTION ) ||
         IsXMLToken ( rLocalName, XML_DELETION ) ) )
        pContext = new SvXMLSectionListContext (*this, nPrefix, rLocalName, xAttrList);
    else
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    return pContext;
}

SvXMLSectionListContext::SvXMLSectionListContext(
   SwXMLSectionList& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
   rLocalRef(rImport),
   SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SvXMLSectionListContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    String sName;

    if (nPrefix == XML_NAMESPACE_TEXT && ( IsXMLToken ( rLocalName, XML_SECTION ) ||
                                           IsXMLToken ( rLocalName, XML_BOOKMARK) ) )
    {
        sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;

        for (sal_Int16 i=0; i < nAttrCount; i++)
        {
            const OUString& rAttrName = xAttrList->getNameByIndex( i );
            OUString aLocalName;
            sal_uInt16 nPrefix = rLocalRef.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            if (XML_NAMESPACE_TEXT == nPrefix && IsXMLToken ( aLocalName, XML_NAME ) )
                sName = rAttrValue;
        }
        if ( sName.Len() )
            rLocalRef.rSectionList.Insert ( new String(sName), rLocalRef.rSectionList.Count() );
    }

    pContext = new SvXMLSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    return pContext;
}
SvXMLSectionListContext::~SvXMLSectionListContext ( void )
{
}

SvXMLIgnoreSectionListContext::SvXMLIgnoreSectionListContext(
   SwXMLSectionList& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
   rLocalRef(rImport),
   SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLIgnoreSectionListContext::~SvXMLIgnoreSectionListContext ( void )
{
}
SvXMLImportContext *SvXMLIgnoreSectionListContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    return  new SvXMLIgnoreSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.406); FILE MERGED 2005/09/05 13:40:35 rt 1.5.406.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: SwXMLSectionList.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 04:43:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#pragma hdrstop

#define _SVSTDARR_STRINGSDTOR
#define _SVSTDARR_STRINGS
#include <svtools/svstdarr.hxx>
#ifndef _SW_XMLSECTIONLIST_HXX
#include <SwXMLSectionList.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::rtl;
using namespace ::xmloff::token;

sal_Char __READONLY_DATA sXML_np__office[] = "_ooffice";
sal_Char __READONLY_DATA sXML_np__text[] = "_otext";

// #110680#
SwXMLSectionList::SwXMLSectionList(
    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
    SvStrings & rNewSectionList)
:   SvXMLImport( xServiceFactory ),
    rSectionList ( rNewSectionList )
{
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__office ) ),
                            GetXMLToken(XML_N_OFFICE_OOO),
                            XML_NAMESPACE_OFFICE );
    GetNamespaceMap().Add( OUString( RTL_CONSTASCII_USTRINGPARAM ( sXML_np__text ) ),
                            GetXMLToken(XML_N_TEXT_OOO),
                            XML_NAMESPACE_TEXT );
}

SwXMLSectionList::~SwXMLSectionList ( void )
    throw()
{
}

SvXMLImportContext *SwXMLSectionList::CreateContext(
        sal_uInt16 nPrefix,
        const OUString& rLocalName,
        const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if  (nPrefix == XML_NAMESPACE_OFFICE && IsXMLToken ( rLocalName, XML_BODY ) ||
         nPrefix == XML_NAMESPACE_TEXT &&
        (IsXMLToken ( rLocalName, XML_P ) ||
         IsXMLToken ( rLocalName, XML_H ) ||
         IsXMLToken ( rLocalName, XML_A ) ||
         IsXMLToken ( rLocalName, XML_SPAN ) ||
         IsXMLToken ( rLocalName, XML_SECTION ) ||
         IsXMLToken ( rLocalName, XML_INDEX_BODY ) ||
         IsXMLToken ( rLocalName, XML_INDEX_TITLE )||
         IsXMLToken ( rLocalName, XML_INSERTION ) ||
         IsXMLToken ( rLocalName, XML_DELETION ) ) )
        pContext = new SvXMLSectionListContext (*this, nPrefix, rLocalName, xAttrList);
    else
        pContext = SvXMLImport::CreateContext( nPrefix, rLocalName, xAttrList );
    return pContext;
}

SvXMLSectionListContext::SvXMLSectionListContext(
   SwXMLSectionList& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
   rLocalRef(rImport),
   SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLImportContext *SvXMLSectionListContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    String sName;

    if (nPrefix == XML_NAMESPACE_TEXT && ( IsXMLToken ( rLocalName, XML_SECTION ) ||
                                           IsXMLToken ( rLocalName, XML_BOOKMARK) ) )
    {
        sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;

        for (sal_Int16 i=0; i < nAttrCount; i++)
        {
            const OUString& rAttrName = xAttrList->getNameByIndex( i );
            OUString aLocalName;
            sal_uInt16 nPrefix = rLocalRef.GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName);
            const OUString& rAttrValue = xAttrList->getValueByIndex( i );
            if (XML_NAMESPACE_TEXT == nPrefix && IsXMLToken ( aLocalName, XML_NAME ) )
                sName = rAttrValue;
        }
        if ( sName.Len() )
            rLocalRef.rSectionList.Insert ( new String(sName), rLocalRef.rSectionList.Count() );
    }

    pContext = new SvXMLSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);
    return pContext;
}
SvXMLSectionListContext::~SvXMLSectionListContext ( void )
{
}

SvXMLIgnoreSectionListContext::SvXMLIgnoreSectionListContext(
   SwXMLSectionList& rImport,
   sal_uInt16 nPrefix,
   const OUString& rLocalName,
   const com::sun::star::uno::Reference<
   com::sun::star::xml::sax::XAttributeList > & xAttrList ) :
   rLocalRef(rImport),
   SvXMLImportContext ( rImport, nPrefix, rLocalName )
{
}

SvXMLIgnoreSectionListContext::~SvXMLIgnoreSectionListContext ( void )
{
}
SvXMLImportContext *SvXMLIgnoreSectionListContext::CreateChildContext(
    sal_uInt16 nPrefix,
    const OUString& rLocalName,
    const Reference< xml::sax::XAttributeList > & xAttrList )
{
    return  new SvXMLIgnoreSectionListContext (rLocalRef, nPrefix, rLocalName, xAttrList);
}
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is [Open Source Virtual Machine.].
 *
 * The Initial Developer of the Original Code is
 * Adobe System Incorporated.
 * Portions created by the Initial Developer are Copyright (C) 2004-2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "MMgc.h"
#include "GC.h"

#ifdef USE_MMAP
#include <sys/mman.h>
#endif

#if defined(__MACH__)
#include <mach/mach.h>
#endif

#ifdef _MAC
#define MAP_ANONYMOUS MAP_ANON
#endif

#if (defined(MMGC_IA32) || defined(MMGC_AMD64)) && defined(MEMORY_INFO)
#include <dlfcn.h>
#endif

namespace MMgc
{
#ifndef USE_MMAP
	void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc)
	{
		char *ptr, *ptr2, *aligned_ptr;
		int align_mask = align_size - 1;

		int alloc_size = size + align_size + sizeof(int);
		ptr=(char *)m_malloc(alloc_size);

		if(ptr==NULL) return(NULL);

		ptr2 = ptr + sizeof(int);
		aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));

		ptr2 = aligned_ptr - sizeof(int);
		*((int *)ptr2)=(int)(aligned_ptr - ptr);

		return(aligned_ptr);
	}

	void aligned_free(void *ptr, GCFreeFuncPtr m_free)
	{
		int *ptr2=(int *)ptr - 1;
		char *unaligned_ptr = (char*) ptr - *ptr2;
		m_free(unaligned_ptr);
	}
#endif /* !USE_MMAP */

#ifdef MMGC_AVMPLUS
#ifdef USE_MMAP
	int GCHeap::vmPageSize()
	{
		long v = sysconf(_SC_PAGESIZE);
		if (v == -1) v = 4096; // Mac 10.1 needs this
		return v;
	}

	void* GCHeap::ReserveCodeMemory(void* address,
									size_t size)
	{
		return mmap(address,
					size,
					PROT_NONE,
					MAP_PRIVATE | MAP_ANONYMOUS,
					VM_MAKE_TAG(VM_MEMORY_APPLICATION_SPECIFIC_1+1), 0);
	}

	void GCHeap::ReleaseCodeMemory(void* address,
								   size_t size)
	{
		if (munmap(address, size) != 0)
			GCAssert(false);
	}

	bool GCHeap::SetGuardPage(void* /*address*/)
	{
		return false;
	}

#ifdef AVMPLUS_JIT_READONLY
	/**
	 * SetPageProtection changes the page access protections on a block of pages,
	 * to make JIT-ted code executable or not.
	 *
	 * If executableFlag is true, the memory is made executable and read-only.
	 *
	 * If executableFlag is false, the memory is made non-executable and
	 * read-write.
	 */
	void GCHeap::SetPageProtection(void *address,
							   size_t size,
							   bool executableFlag,
							   bool writeableFlag)
	{
		// mprotect requires that the addresses be aligned on page boundaries
		void *endAddress = (void*) ((char*)address + size);
		void *beginPage = (void*) ((size_t)address & ~0xFFF);
		void *endPage   = (void*) (((size_t)endAddress + 0xFFF) & ~0xFFF);
		size_t sizePaged = (size_t)endPage - (size_t)beginPage;

		int flags = PROT_READ;
		if (executableFlag) {
			flags |= PROT_EXEC;
		}
		if (writeableFlag) {
			flags |= PROT_WRITE;
		}
		int retval = mprotect(beginPage, sizePaged, flags);

		GCAssert(retval == 0);
		(void)retval;
	}
#endif /* AVMPLUS_JIT_READONLY */

	void* GCHeap::CommitCodeMemory(void* address,
								   size_t size)
	{
		if (size == 0)
			size = GCHeap::kNativePageSize;  // default of one page

#ifdef AVMPLUS_JIT_READONLY
		int res = mprotect (address, size, PROT_READ | PROT_WRITE);
#else
		int res = mprotect (address, size, PROT_READ | PROT_WRITE | PROT_EXEC);
#endif /* AVMPLUS_JIT_READONLY */

		if (res != 0)
			address = 0;
		else
			address = (void*)( (uintptr)address + size );

		committedCodeMemory += size;
		return address;
	}

	void* GCHeap::DecommitCodeMemory(void* address,
									 size_t size)
	{
		if (size == 0)
			size = GCHeap::kNativePageSize;  // default of one page

		// this doesn't "decommit" it, it just makes it unwritable, Mac OS still backs it with real pages :-(
		int res = mprotect (address, size, PROT_NONE);
		GCAssert(res == 0);
		(void) res;
		committedCodeMemory -= size;
		return (address);
	}
#else
	int GCHeap::vmPageSize()
	{
		return 4096;
	}

	void* GCHeap::ReserveCodeMemory(void* ,
									size_t size)
	{
		return aligned_malloc(size, 4096, m_malloc);
	}

	void GCHeap::ReleaseCodeMemory(void* address,
								   size_t )
	{
		aligned_free(address, m_free);
	}

	bool GCHeap::SetGuardPage(void *)
	{
		return false;
	}

#ifdef AVMPLUS_JIT_READONLY
	void GCHeap::SetExecuteBit(void *,
							   size_t ,
							   bool )
	{
		// No-op on Mac CFM
	}
#endif /* AVMPLUS_JIT_READONLY */

	void* GCHeap::CommitCodeMemory(void* address,
								   size_t size)
	{
		committedCodeMemory += size;
		return address;
	}
	void* GCHeap::DecommitCodeMemory(void* address,
									 size_t size)
	{
		committedCodeMemory -= size;
		return address;
	}
#endif /* USE_MMAP */
#endif /* MMGC_AVMPLUS */

#ifdef USE_MMAP
	char* GCHeap::ReserveMemory(char *address, size_t size)
	{
		char *addr = (char*)mmap(address,
					 size,
					 PROT_NONE,
					 MAP_PRIVATE | MAP_ANONYMOUS,
					 VM_MAKE_TAG(VM_MEMORY_APPLICATION_SPECIFIC_1), 0);

		// the man page for mmap documents it returns -1 to signal failure.
		if (addr == (char *)-1) return NULL;

		if(address && address != addr) {
			// behave like windows and fail if we didn't get the right address
			ReleaseMemory(addr, size);
			return NULL;
		}
		return addr;
	}

	bool GCHeap::CommitMemory(char *address, size_t size)
	{
		int res = mprotect (address, size, PROT_READ | PROT_WRITE);
		GCAssert(res == 0);
		return (res == 0);
	}

	bool GCHeap::DecommitMemory(char *address, size_t size)
	{
		// FIXME: this doesn't actually untie the pages from real memory
		int res = mprotect (address, size, PROT_NONE);
		GCAssert(res == 0);
		return (res == 0);
	}

	bool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size)
	{
		return CommitMemory(address, size);
	}

	bool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size)
	{
		return DecommitMemory(address, size);
	}

	void GCHeap::ReleaseMemory(char *address, size_t size)
	{
		int result = munmap(address, size);
		GCAssert(result == 0);
		(void)result;
	}
#else

	char* GCHeap::AllocateMemory(size_t size)
	{
		return (char *) aligned_malloc(size, 4096, m_malloc);
		//return (char *) MPAllocateAligned(size, kMPAllocate4096ByteAligned, 0);
	}

	void GCHeap::ReleaseMemory(char *address)
	{
		aligned_free(address, m_free);
		//MPFree(address);
	}
#endif

#ifdef MEMORY_INFO

#ifdef MMGC_PPC
	// no idea how to do this with codewarrior
	void GetInfoFromPC(sintptr pc, char *buff, int /*buffSize*/)
	{
		sprintf(buff, "0x%x", (uint32)pc);
	}

	void GetStackTrace(sintptr *trace, int len, int skip)
	{
	  register int stackp;
	  sintptr pc;
	  asm("mr %0,r1" : "=r" (stackp));
	  while(skip--) {
	    stackp = *(int*)stackp;
	  }
	  int i=0;
	  // save space for 0 terminator
	  len--;
	  while(i<len && stackp) {
	    pc = *((sintptr*)stackp+2);
	    trace[i++]=pc;
	    stackp = *(int*)stackp;
	  }
	  trace[i] = 0;
	}
#endif

#if (defined(MMGC_IA32) || defined(MMGC_AMD64))

	void GetInfoFromPC(sintptr pc, char *buff, int buffSize)
	{
		Dl_info dlip;
		dladdr((void * const)pc, &dlip);
		snprintf(buff, buffSize, "0x%08x:%s", (uint32)pc, dlip.dli_sname);
	}

	void GetStackTrace(sintptr* trace, int len, int skip)
	{
		void **ebp;
		#ifdef MMGC_IA32
		asm("mov %%ebp, %0" : "=r" (ebp));
		#else
		asm("mov %%rbp, %0" : "=r" (ebp));
		#endif
		while(skip-- && *ebp)
		{
			ebp = (void**)(*ebp);
		}

		len--;
		int i=0;
		while(i<len && *ebp)
		{
			trace[i++] = *((sintptr*)ebp+1);
			ebp = (void**)(*ebp);
		}
		trace[i] = 0;
	}
#endif

#endif

	size_t GCHeap::GetPrivateBytes()
	{
		size_t private_bytes = 0;
		kern_return_t ret;
		task_t task = mach_task_self();

		vm_size_t pagesize = 0;
		ret = host_page_size(mach_host_self(), &pagesize);

		vm_address_t addr = VM_MIN_ADDRESS;
		vm_size_t size = 0;
		while (true)
		{
			mach_msg_type_number_t count = VM_REGION_TOP_INFO_COUNT;
			vm_region_top_info_data_t info;
			mach_port_t object_name;

			addr += size;

#ifdef MMGC_64BIT
			ret = vm_region_64(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);
#else
			ret = vm_region(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);
#endif

			if (ret != KERN_SUCCESS)
				break;
			private_bytes += info.private_pages_resident;
		}
		return private_bytes;
	}
}
<commit_msg>Fix 10.4 builds<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is [Open Source Virtual Machine.].
 *
 * The Initial Developer of the Original Code is
 * Adobe System Incorporated.
 * Portions created by the Initial Developer are Copyright (C) 2004-2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Adobe AS3 Team
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "MMgc.h"
#include "GC.h"

#ifdef USE_MMAP
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#endif

#if defined(__MACH__)
#include <mach/mach.h>
#endif

#ifdef _MAC
#define MAP_ANONYMOUS MAP_ANON
#endif

#if (defined(MMGC_IA32) || defined(MMGC_AMD64)) && defined(MEMORY_INFO)
#include <dlfcn.h>
#endif

namespace MMgc
{
#ifndef USE_MMAP
	void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc)
	{
		char *ptr, *ptr2, *aligned_ptr;
		int align_mask = align_size - 1;

		int alloc_size = size + align_size + sizeof(int);
		ptr=(char *)m_malloc(alloc_size);

		if(ptr==NULL) return(NULL);

		ptr2 = ptr + sizeof(int);
		aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));

		ptr2 = aligned_ptr - sizeof(int);
		*((int *)ptr2)=(int)(aligned_ptr - ptr);

		return(aligned_ptr);
	}

	void aligned_free(void *ptr, GCFreeFuncPtr m_free)
	{
		int *ptr2=(int *)ptr - 1;
		char *unaligned_ptr = (char*) ptr - *ptr2;
		m_free(unaligned_ptr);
	}
#endif /* !USE_MMAP */

#ifdef MMGC_AVMPLUS
#ifdef USE_MMAP
	static int get_major_version()
	{
		int mib[2];
		mib[0]=CTL_KERN;
		mib[1]=KERN_OSRELEASE;
		char buf[10];
		size_t siz=sizeof(buf);
		sysctl(mib, 2, &buf, &siz, NULL, 0);
		return strtol(buf, 0, 10);
	}

    static int get_mmap_fdes(int delta)
	{
	  // ensure runtime version
	  if(get_major_version() >= 9) // 9 == 10.5
		  return VM_MAKE_TAG(VM_MEMORY_APPLICATION_SPECIFIC_1+delta);
	  else
		  return -1;
	}

	int GCHeap::vmPageSize()
	{
		long v = sysconf(_SC_PAGESIZE);
		if (v == -1) v = 4096; // Mac 10.1 needs this
		return v;
	}

	void* GCHeap::ReserveCodeMemory(void* address,
									size_t size)
	{
		return mmap(address,
					size,
					PROT_NONE,
					MAP_PRIVATE | MAP_ANONYMOUS,
					get_mmap_fdes(1), 0);
	}

	void GCHeap::ReleaseCodeMemory(void* address,
								   size_t size)
	{
		if (munmap(address, size) != 0)
			GCAssert(false);
	}

	bool GCHeap::SetGuardPage(void* /*address*/)
	{
		return false;
	}

#ifdef AVMPLUS_JIT_READONLY
	/**
	 * SetPageProtection changes the page access protections on a block of pages,
	 * to make JIT-ted code executable or not.
	 *
	 * If executableFlag is true, the memory is made executable and read-only.
	 *
	 * If executableFlag is false, the memory is made non-executable and
	 * read-write.
	 */
	void GCHeap::SetPageProtection(void *address,
							   size_t size,
							   bool executableFlag,
							   bool writeableFlag)
	{
		// mprotect requires that the addresses be aligned on page boundaries
		void *endAddress = (void*) ((char*)address + size);
		void *beginPage = (void*) ((size_t)address & ~0xFFF);
		void *endPage   = (void*) (((size_t)endAddress + 0xFFF) & ~0xFFF);
		size_t sizePaged = (size_t)endPage - (size_t)beginPage;

		int flags = PROT_READ;
		if (executableFlag) {
			flags |= PROT_EXEC;
		}
		if (writeableFlag) {
			flags |= PROT_WRITE;
		}
		int retval = mprotect(beginPage, sizePaged, flags);

		GCAssert(retval == 0);
		(void)retval;
	}
#endif /* AVMPLUS_JIT_READONLY */

	void* GCHeap::CommitCodeMemory(void* address,
								   size_t size)
	{
		if (size == 0)
			size = GCHeap::kNativePageSize;  // default of one page

#ifdef AVMPLUS_JIT_READONLY
		int res = mprotect (address, size, PROT_READ | PROT_WRITE);
#else
		int res = mprotect (address, size, PROT_READ | PROT_WRITE | PROT_EXEC);
#endif /* AVMPLUS_JIT_READONLY */

		if (res != 0)
			address = 0;
		else
			address = (void*)( (uintptr)address + size );

		committedCodeMemory += size;
		return address;
	}

	void* GCHeap::DecommitCodeMemory(void* address,
									 size_t size)
	{
		if (size == 0)
			size = GCHeap::kNativePageSize;  // default of one page

		// this doesn't "decommit" it, it just makes it unwritable, Mac OS still backs it with real pages :-(
		int res = mprotect (address, size, PROT_NONE);
		GCAssert(res == 0);
		(void) res;
		committedCodeMemory -= size;
		return (address);
	}
#else
	int GCHeap::vmPageSize()
	{
		return 4096;
	}

	void* GCHeap::ReserveCodeMemory(void* ,
									size_t size)
	{
		return aligned_malloc(size, 4096, m_malloc);
	}

	void GCHeap::ReleaseCodeMemory(void* address,
								   size_t )
	{
		aligned_free(address, m_free);
	}

	bool GCHeap::SetGuardPage(void *)
	{
		return false;
	}

#ifdef AVMPLUS_JIT_READONLY
	void GCHeap::SetExecuteBit(void *,
							   size_t ,
							   bool )
	{
		// No-op on Mac CFM
	}
#endif /* AVMPLUS_JIT_READONLY */

	void* GCHeap::CommitCodeMemory(void* address,
								   size_t size)
	{
		committedCodeMemory += size;
		return address;
	}
	void* GCHeap::DecommitCodeMemory(void* address,
									 size_t size)
	{
		committedCodeMemory -= size;
		return address;
	}
#endif /* USE_MMAP */
#endif /* MMGC_AVMPLUS */

#ifdef USE_MMAP
	char* GCHeap::ReserveMemory(char *address, size_t size)
	{
		char *addr = (char*)mmap(address,
					 size,
					 PROT_NONE,
					 MAP_PRIVATE | MAP_ANONYMOUS,
					 get_mmap_fdes(0), 0);

		// the man page for mmap documents it returns -1 to signal failure.
		if (addr == (char *)-1) return NULL;

		if(address && address != addr) {
			// behave like windows and fail if we didn't get the right address
			ReleaseMemory(addr, size);
			return NULL;
		}
		return addr;
	}

	bool GCHeap::CommitMemory(char *address, size_t size)
	{
		int res = mprotect (address, size, PROT_READ | PROT_WRITE);
		GCAssert(res == 0);
		return (res == 0);
	}

	bool GCHeap::DecommitMemory(char *address, size_t size)
	{
		// FIXME: this doesn't actually untie the pages from real memory
		int res = mprotect (address, size, PROT_NONE);
		GCAssert(res == 0);
		return (res == 0);
	}

	bool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size)
	{
		return CommitMemory(address, size);
	}

	bool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size)
	{
		return DecommitMemory(address, size);
	}

	void GCHeap::ReleaseMemory(char *address, size_t size)
	{
		int result = munmap(address, size);
		GCAssert(result == 0);
		(void)result;
	}
#else

	char* GCHeap::AllocateMemory(size_t size)
	{
		return (char *) aligned_malloc(size, 4096, m_malloc);
		//return (char *) MPAllocateAligned(size, kMPAllocate4096ByteAligned, 0);
	}

	void GCHeap::ReleaseMemory(char *address)
	{
		aligned_free(address, m_free);
		//MPFree(address);
	}
#endif

#ifdef MEMORY_INFO

#ifdef MMGC_PPC
	// no idea how to do this with codewarrior
	void GetInfoFromPC(sintptr pc, char *buff, int /*buffSize*/)
	{
		sprintf(buff, "0x%x", (uint32)pc);
	}

	void GetStackTrace(sintptr *trace, int len, int skip)
	{
	  register int stackp;
	  sintptr pc;
	  asm("mr %0,r1" : "=r" (stackp));
	  while(skip--) {
	    stackp = *(int*)stackp;
	  }
	  int i=0;
	  // save space for 0 terminator
	  len--;
	  while(i<len && stackp) {
	    pc = *((sintptr*)stackp+2);
	    trace[i++]=pc;
	    stackp = *(int*)stackp;
	  }
	  trace[i] = 0;
	}
#endif

#if (defined(MMGC_IA32) || defined(MMGC_AMD64))

	void GetInfoFromPC(sintptr pc, char *buff, int buffSize)
	{
		Dl_info dlip;
		dladdr((void * const)pc, &dlip);
		snprintf(buff, buffSize, "0x%08x:%s", (uint32)pc, dlip.dli_sname);
	}

	void GetStackTrace(sintptr* trace, int len, int skip)
	{
		void **ebp;
		#ifdef MMGC_IA32
		asm("mov %%ebp, %0" : "=r" (ebp));
		#else
		asm("mov %%rbp, %0" : "=r" (ebp));
		#endif
		while(skip-- && *ebp)
		{
			ebp = (void**)(*ebp);
		}

		len--;
		int i=0;
		while(i<len && *ebp)
		{
			trace[i++] = *((sintptr*)ebp+1);
			ebp = (void**)(*ebp);
		}
		trace[i] = 0;
	}
#endif

#endif

	size_t GCHeap::GetPrivateBytes()
	{
		size_t private_bytes = 0;
		kern_return_t ret;
		task_t task = mach_task_self();

		vm_size_t pagesize = 0;
		ret = host_page_size(mach_host_self(), &pagesize);

		vm_address_t addr = VM_MIN_ADDRESS;
		vm_size_t size = 0;
		while (true)
		{
			mach_msg_type_number_t count = VM_REGION_TOP_INFO_COUNT;
			vm_region_top_info_data_t info;
			mach_port_t object_name;

			addr += size;

#ifdef MMGC_64BIT
			ret = vm_region_64(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);
#else
			ret = vm_region(task, &addr, &size, VM_REGION_TOP_INFO, (vm_region_info_t)&info, &count, &object_name);
#endif

			if (ret != KERN_SUCCESS)
				break;
			private_bytes += info.private_pages_resident;
		}
		return private_bytes;
	}
}
<|endoftext|>


<commit_before><commit_msg>Delete Circle.cpp<commit_after><|endoftext|>


<commit_before>#include <HgVbo.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>

#include <string.h>

HgVboMemory<vbo_layout_vc> staticVbo;
HgVboMemory<vbo_layout_vnu> staticVboVNU;

static void* _currentVbo;

static uint16_t struct_size(VBO_TYPE type) {
	if (type == VBO_VC) return sizeof(vbo_layout_vc);
	if (type == VBO_VNU) return sizeof(vbo_layout_vnu);
	if (type == VBO_INDEX8) return sizeof(uint8_t);
	if (type == VBO_INDEX16) return sizeof(uint16_t);
	if (type == VBO_COLOR8) return sizeof(color);

	fprintf(stderr, "Unknown vbo type:%d\n", type);
	assert(!"Unknown vbo type");
	return 0;
}

static VBO_TYPE getVboType(const vbo_layout_vc& x) { return VBO_VC; }
static VBO_TYPE getVboType(const vbo_layout_vnu& x) { return VBO_VNU; }
static VBO_TYPE getVboType(const uint8_t& x) { return VBO_INDEX8; }
static VBO_TYPE getVboType(const uint16_t& x) { return VBO_INDEX16; }
static VBO_TYPE getVboType(const color& x) { return VBO_VC; }

template<typename T>
HgVboMemory<T>::HgVboMemory()
	:buffer(nullptr)
{

}

template<typename T>
HgVboMemory<T>::~HgVboMemory() {
	if (buffer != nullptr) free(buffer);
	buffer = nullptr;

	destroy();
}

template<typename T>
void HgVboMemory<T>::init() {
	type = getVboType(*buffer);
	stride = sizeof(T);
}

template<typename T>
T* HgVboMemory<T>::resize(uint32_t count) {
	T* buf = (T*)realloc(buffer, count * sizeof(*buf));
	assert(buf != NULL);
	buffer = buf;

	return buf;
}

template<typename T>
void HgVboMemory<T>::clear() {
	if (buffer != nullptr) free(buffer);
	buffer = NULL;
	count = 0;
}

template<typename T>
void HgVboMemory<T>::destroy() {
	if (vbo_id>0) glDeleteBuffers(1, &vbo_id);
	if (vao_id>0) glDeleteBuffers(1, &vao_id);
	vao_id = vbo_id = 0;
	clear();
}

template<typename T>
uint32_t HgVboMemory<T>::add_data(void* data, uint16_t vertex_count) {
	T* buf = buffer = resize(count + vertex_count);
	buf = buf + count;

	memcpy(buf, data, sizeof(*buf)*vertex_count);

	uint32_t offset = count;
	count += vertex_count;
	needsUpdate = true;

	return offset;
}

template<typename T>
void HgVboMemory<T>::hgvbo_sendogl() {
	if (vbo_id == 0) glGenBuffers(1, &vbo_id);
	if (vao_id == 0) glGenVertexArrays(1, &vao_id);

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
	glBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);

	glBindVertexArray(vao_id);

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
	//minimize calls to glVertexAttribPointer, use same format for all meshes in a VBO

	glVertexAttribPointer(L_VERTEX, 3, GL_FLOAT, GL_FALSE, stride, NULL);
	glEnableVertexAttribArray(L_VERTEX); //enable access to attribute

	if (type == VBO_VC) {
		glVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)sizeof(vertex));
		glEnableVertexAttribArray(L_COLOR);
	}
	else if (type == VBO_VN) {
		glVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));
		glEnableVertexAttribArray(L_NORMAL);
	}
	else if (type == VBO_VNU) {
		glVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));
		glEnableVertexAttribArray(L_NORMAL);
		glVertexAttribPointer(L_UV, 2, GL_UNSIGNED_SHORT, GL_FALSE, stride, (void*)(sizeof(vertex)+sizeof(normal)));
		glEnableVertexAttribArray(L_UV);
	}
	else {
		fprintf(stderr, "Unknown vbo type:%d\n", type);
		assert(!"Unknown vbo type");
	}

	needsUpdate = false;
}

template<typename T>
void HgVboMemory<T>::use() {
	if ((_currentVbo == this) && (needsUpdate == false)) return;

	_currentVbo = this;

	if (needsUpdate) {
		hgvbo_sendogl();
	}

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id); //is this needed or does the vao_id do this for us?
	glBindVertexArray(vao_id);
}

//8 bit index
template<>
void HgVboMemory<uint8_t>::use() {
	if (vbo_id == 0) {
		GLuint buf_id;
		glGenBuffers(1, &buf_id);
		vbo_id = buf_id;
	}

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id);

	if (needsUpdate) {
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);
		needsUpdate = false;
	}
}

template<>
void HgVboMemory<color>::use() {
	if (vbo_id == 0) {
		GLuint buf_id;
		glGenBuffers(1, &buf_id);
		vbo_id = buf_id;
/*
		glGenVertexArrays(1, &vbo->vao_id);
		glBindVertexArray(vbo->vao_id);
		glVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)0);
		glEnableVertexAttribArray(L_COLOR);
		*/
	}

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id);

	if (needsUpdate) {
		color* c = buffer;
		glBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);
		needsUpdate = false;
	}

	glVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
	glEnableVertexAttribArray(L_COLOR);
}<commit_msg>fix constructor<commit_after>#include <HgVbo.h>
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>

#include <string.h>

HgVboMemory<vbo_layout_vc> staticVbo;
HgVboMemory<vbo_layout_vnu> staticVboVNU;

static void* _currentVbo;

static uint16_t struct_size(VBO_TYPE type) {
	if (type == VBO_VC) return sizeof(vbo_layout_vc);
	if (type == VBO_VNU) return sizeof(vbo_layout_vnu);
	if (type == VBO_INDEX8) return sizeof(uint8_t);
	if (type == VBO_INDEX16) return sizeof(uint16_t);
	if (type == VBO_COLOR8) return sizeof(color);

	fprintf(stderr, "Unknown vbo type:%d\n", type);
	assert(!"Unknown vbo type");
	return 0;
}

static VBO_TYPE getVboType(const vbo_layout_vc& x) { return VBO_VC; }
static VBO_TYPE getVboType(const vbo_layout_vnu& x) { return VBO_VNU; }
static VBO_TYPE getVboType(const uint8_t& x) { return VBO_INDEX8; }
static VBO_TYPE getVboType(const uint16_t& x) { return VBO_INDEX16; }
static VBO_TYPE getVboType(const color& x) { return VBO_VC; }

template<typename T>
HgVboMemory<T>::HgVboMemory()
	:buffer(nullptr), count(0), vbo_id(0), vao_id(0), needsUpdate(0), stride(0), type(0)
{
}

template<typename T>
HgVboMemory<T>::~HgVboMemory() {
	if (buffer != nullptr) free(buffer);
	buffer = nullptr;

	destroy();
}

template<typename T>
void HgVboMemory<T>::init() {
	type = getVboType(*buffer);
	stride = sizeof(T);
}

template<typename T>
T* HgVboMemory<T>::resize(uint32_t count) {
	T* buf = (T*)realloc(buffer, count * sizeof(*buf));
	assert(buf != NULL);
	buffer = buf;

	return buf;
}

template<typename T>
void HgVboMemory<T>::clear() {
	if (buffer != nullptr) free(buffer);
	buffer = NULL;
	count = 0;
}

template<typename T>
void HgVboMemory<T>::destroy() {
	if (vbo_id>0) glDeleteBuffers(1, &vbo_id);
	if (vao_id>0) glDeleteBuffers(1, &vao_id);
	vao_id = vbo_id = 0;
	clear();
}

template<typename T>
uint32_t HgVboMemory<T>::add_data(void* data, uint16_t vertex_count) {
	T* buf = buffer = resize(count + vertex_count);
	buf = buf + count;

	memcpy(buf, data, sizeof(*buf)*vertex_count);

	uint32_t offset = count;
	count += vertex_count;
	needsUpdate = true;

	return offset;
}

template<typename T>
void HgVboMemory<T>::hgvbo_sendogl() {
	if (vbo_id == 0) glGenBuffers(1, &vbo_id);
	if (vao_id == 0) glGenVertexArrays(1, &vao_id);

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
	glBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);

	glBindVertexArray(vao_id);

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
	//minimize calls to glVertexAttribPointer, use same format for all meshes in a VBO

	glVertexAttribPointer(L_VERTEX, 3, GL_FLOAT, GL_FALSE, stride, NULL);
	glEnableVertexAttribArray(L_VERTEX); //enable access to attribute

	if (type == VBO_VC) {
		glVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, stride, (void*)sizeof(vertex));
		glEnableVertexAttribArray(L_COLOR);
	}
	else if (type == VBO_VN) {
		glVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));
		glEnableVertexAttribArray(L_NORMAL);
	}
	else if (type == VBO_VNU) {
		glVertexAttribPointer(L_NORMAL, 4, GL_FLOAT, GL_FALSE, stride, (void*)sizeof(vertex));
		glEnableVertexAttribArray(L_NORMAL);
		glVertexAttribPointer(L_UV, 2, GL_UNSIGNED_SHORT, GL_FALSE, stride, (void*)(sizeof(vertex)+sizeof(normal)));
		glEnableVertexAttribArray(L_UV);
	}
	else {
		fprintf(stderr, "Unknown vbo type:%d\n", type);
		assert(!"Unknown vbo type");
	}

	needsUpdate = false;
}

template<typename T>
void HgVboMemory<T>::use() {
	if ((_currentVbo == this) && (needsUpdate == false)) return;

	_currentVbo = this;

	if (needsUpdate) {
		hgvbo_sendogl();
	}

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id); //is this needed or does the vao_id do this for us?
	glBindVertexArray(vao_id);
}

//8 bit index
template<>
void HgVboMemory<uint8_t>::use() {
	if (vbo_id == 0) {
		GLuint buf_id;
		glGenBuffers(1, &buf_id);
		vbo_id = buf_id;
	}

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id);

	if (needsUpdate) {
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);
		needsUpdate = false;
	}
}

template<>
void HgVboMemory<color>::use() {
	if (vbo_id == 0) {
		GLuint buf_id;
		glGenBuffers(1, &buf_id);
		vbo_id = buf_id;
/*
		glGenVertexArrays(1, &vbo->vao_id);
		glBindVertexArray(vbo->vao_id);
		glVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)0);
		glEnableVertexAttribArray(L_COLOR);
		*/
	}

	glBindBuffer(GL_ARRAY_BUFFER, vbo_id);

	if (needsUpdate) {
		color* c = buffer;
		glBufferData(GL_ARRAY_BUFFER, count * stride, buffer, GL_STATIC_DRAW);
		needsUpdate = false;
	}

	glVertexAttribPointer(L_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, NULL);
	glEnableVertexAttribArray(L_COLOR);
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2015, Intel Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "ArrayParameter.h"
#include <sstream> // for istringstream
#include "Tokenizer.h"
#include "ParameterType.h"
#include "ParameterAccessContext.h"
#include "ConfigurationAccessContext.h"
#include "ParameterBlackboard.h"
#include "Utility.h"
#include <assert.h>

#define base CParameter

using std::string;

CArrayParameter::CArrayParameter(const string &strName, const CTypeElement *pTypeElement)
    : base(strName, pTypeElement)
{
}

size_t CArrayParameter::getFootPrint() const
{
    return getSize() * getArrayLength();
}

// Array length
size_t CArrayParameter::getArrayLength() const
{
    return getTypeElement()->getArrayLength();
}

// Element properties
void CArrayParameter::showProperties(string &strResult) const
{
    base::showProperties(strResult);

    // Array length
    strResult += "Array length: ";
    strResult += std::to_string(getArrayLength());
    strResult += "\n";
}

// User set/get
bool CArrayParameter::accessValue(CPathNavigator &pathNavigator, string &strValue, bool bSet,
                                  CParameterAccessContext &parameterAccessContext) const
{
    size_t index;

    if (!getIndex(pathNavigator, index, parameterAccessContext)) {

        return false;
    }

    if (bSet) {
        // Set
        if (index == (size_t)-1) {

            // No index provided, start with 0
            index = 0;
        }

        // Actually set values
        if (!setValues(index, getOffset() - parameterAccessContext.getBaseOffset(), strValue,
                       parameterAccessContext)) {
            return false;
        }

        // Synchronize
        if (!sync(parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    } else {
        // Get
        if (index == (size_t)-1) {

            // Whole array requested
            strValue = getValues(getOffset() - parameterAccessContext.getBaseOffset(),
                                 parameterAccessContext);

        } else {
            // Scalar requested
            CParameter::doGetValue(strValue, getOffset() + index * getSize(),
                                   parameterAccessContext);
        }
    }

    return true;
}

/// Actual parameter access
// String access
bool CArrayParameter::doSetValue(const string &value, size_t offset,
                                 CParameterAccessContext &parameterAccessContext) const
{
    return setValues(0, offset, value, parameterAccessContext);
}

void CArrayParameter::doGetValue(string &value, size_t offset,
                                 CParameterAccessContext &parameterAccessContext) const
{
    // Whole array requested
    value = getValues(offset, parameterAccessContext);
}

// Boolean
bool CArrayParameter::access(std::vector<bool> &abValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(abValues, bSet, parameterAccessContext);
}

// Integer
bool CArrayParameter::access(std::vector<uint32_t> &auiValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(auiValues, bSet, parameterAccessContext);
}

// Signed Integer Access
bool CArrayParameter::access(std::vector<int32_t> &aiValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(aiValues, bSet, parameterAccessContext);
}

// Double Access
bool CArrayParameter::access(std::vector<double> &adValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(adValues, bSet, parameterAccessContext);
}

// String Access
bool CArrayParameter::access(std::vector<string> &astrValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(astrValues, bSet, parameterAccessContext);
}

// Dump
string CArrayParameter::logValue(CParameterAccessContext &context) const
{
    // Dump values
    return getValues(0, context);
}

// Used for simulation and virtual subsystems
void CArrayParameter::setDefaultValues(CParameterAccessContext &parameterAccessContext) const
{
    // Get default value from type
    uint32_t uiDefaultValue =
        static_cast<const CParameterType *>(getTypeElement())->getDefaultValue();

    // Write blackboard
    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Process
    size_t valueIndex;
    size_t size = getSize();
    size_t offset = getOffset();
    size_t arrayLength = getArrayLength();

    for (valueIndex = 0; valueIndex < arrayLength; valueIndex++) {

        // Beware this code works on little endian architectures only!
        pBlackboard->writeInteger(&uiDefaultValue, size, offset);

        offset += size;
    }
}

// Index from path
bool CArrayParameter::getIndex(CPathNavigator &pathNavigator, size_t &index,
                               CParameterAccessContext &parameterAccessContext) const
{
    index = (size_t)-1;

    string *pStrChildName = pathNavigator.next();

    if (pStrChildName) {

        // Check index is numeric
        std::istringstream iss(*pStrChildName);

        iss >> index;

        if (!iss) {

            parameterAccessContext.setError("Expected numerical expression as last item in " +
                                            pathNavigator.getCurrentPath());

            return false;
        }

        if (index >= getArrayLength()) {
            std::ostringstream oss;

            oss << "Provided index out of range (max is " << getArrayLength() - 1 << ")";

            parameterAccessContext.setError(oss.str());

            return false;
        }

        // Check no other item provided in path
        pStrChildName = pathNavigator.next();

        if (pStrChildName) {

            // Should be leaf element
            parameterAccessContext.setError("Path not found: " + pathNavigator.getCurrentPath());

            return false;
        }
    }

    return true;
}

// Common set value processing
bool CArrayParameter::setValues(size_t uiStartIndex, size_t offset, const string &strValue,
                                CParameterAccessContext &parameterAccessContext) const
{
    // Deal with value(s)
    Tokenizer tok(strValue, Tokenizer::defaultDelimiters + ",");

    std::vector<string> astrValues = tok.split();
    size_t nbValues = astrValues.size();

    // Check number of provided values
    if (nbValues + uiStartIndex > getArrayLength()) {

        // Out of bounds
        parameterAccessContext.setError("Too many values provided");

        return false;
    }

    // Process
    size_t valueIndex;
    size_t size = getSize();
    offset += uiStartIndex * size;

    for (valueIndex = 0; valueIndex < nbValues; valueIndex++) {

        if (!doSet(astrValues[valueIndex], offset, parameterAccessContext)) {

            // Append parameter path to error
            parameterAccessContext.appendToError(" " + getPath() + "/" +
                                                 std::to_string(valueIndex + uiStartIndex));

            return false;
        }

        offset += size;
    }
    return true;
}

// Common get value processing
string CArrayParameter::getValues(size_t offset,
                                  CParameterAccessContext &parameterAccessContext) const
{
    size_t size = getSize();
    size_t arrayLength = getArrayLength();

    string output;

    bool bFirst = true;

    for (size_t valueIndex = 0; valueIndex < arrayLength; valueIndex++) {
        string strReadValue;

        doGet(strReadValue, offset, parameterAccessContext);

        if (!bFirst) {

            output += " ";
        } else {

            bFirst = false;
        }

        output += strReadValue;

        offset += size;
    }

    return output;
}

// Generic Access
template <typename type>
bool CArrayParameter::accessValues(std::vector<type> &values, bool bSet,
                                   CParameterAccessContext &parameterAccessContext) const
{
    if (bSet) {

        // Set Value
        if (!setValues(values, parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
        if (!sync(parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    } else {
        // Get Value
        if (!getValues(values, parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    }
    return true;
}

template <typename type>
bool CArrayParameter::setValues(const std::vector<type> &values,
                                CParameterAccessContext &parameterAccessContext) const
{
    size_t nbValues = getArrayLength();
    size_t size = getSize();
    size_t offset = getOffset();

    assert(values.size() == nbValues);

    // Process
    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {

        if (!doSet(values[valueIndex], offset, parameterAccessContext)) {

            return false;
        }

        offset += size;
    }

    return true;
}

template <typename type>
bool CArrayParameter::getValues(std::vector<type> &values,
                                CParameterAccessContext &parameterAccessContext) const
{
    size_t nbValues = getArrayLength();
    size_t size = getSize();
    size_t offset = getOffset();

    values.clear();

    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {
        type readValue;

        if (!doGet(readValue, offset, parameterAccessContext)) {

            return false;
        }

        values.push_back(readValue);

        offset += size;
    }
    return true;
}

template <typename type>
bool CArrayParameter::doSet(type value, size_t offset,
                            CParameterAccessContext &parameterAccessContext) const
{
    uint32_t uiData;

    if (!static_cast<const CParameterType *>(getTypeElement())
             ->toBlackboard(value, uiData, parameterAccessContext)) {

        return false;
    }
    // Write blackboard
    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Beware this code works on little endian architectures only!
    pBlackboard->writeInteger(&uiData, getSize(), offset);

    return true;
}

template <typename type>
bool CArrayParameter::doGet(type &value, size_t offset,
                            CParameterAccessContext &parameterAccessContext) const
{
    uint32_t uiData = 0;

    // Read blackboard
    const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Beware this code works on little endian architectures only!
    pBlackboard->readInteger(&uiData, getSize(), offset);

    return static_cast<const CParameterType *>(getTypeElement())
        ->fromBlackboard(value, uiData, parameterAccessContext);
}
<commit_msg>Fix dumpElement for ArrayParameters<commit_after>/*
 * Copyright (c) 2011-2015, Intel Corporation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
#include "ArrayParameter.h"
#include <sstream> // for istringstream
#include "Tokenizer.h"
#include "ParameterType.h"
#include "ParameterAccessContext.h"
#include "ConfigurationAccessContext.h"
#include "ParameterBlackboard.h"
#include "Utility.h"
#include <assert.h>

#define base CParameter

using std::string;

CArrayParameter::CArrayParameter(const string &strName, const CTypeElement *pTypeElement)
    : base(strName, pTypeElement)
{
}

size_t CArrayParameter::getFootPrint() const
{
    return getSize() * getArrayLength();
}

// Array length
size_t CArrayParameter::getArrayLength() const
{
    return getTypeElement()->getArrayLength();
}

// Element properties
void CArrayParameter::showProperties(string &strResult) const
{
    base::showProperties(strResult);

    // Array length
    strResult += "Array length: ";
    strResult += std::to_string(getArrayLength());
    strResult += "\n";
}

// User set/get
bool CArrayParameter::accessValue(CPathNavigator &pathNavigator, string &strValue, bool bSet,
                                  CParameterAccessContext &parameterAccessContext) const
{
    size_t index;

    if (!getIndex(pathNavigator, index, parameterAccessContext)) {

        return false;
    }

    if (bSet) {
        // Set
        if (index == (size_t)-1) {

            // No index provided, start with 0
            index = 0;
        }

        // Actually set values
        if (!setValues(index, getOffset() - parameterAccessContext.getBaseOffset(), strValue,
                       parameterAccessContext)) {
            return false;
        }

        // Synchronize
        if (!sync(parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    } else {
        // Get
        if (index == (size_t)-1) {

            // Whole array requested
            strValue = getValues(getOffset() - parameterAccessContext.getBaseOffset(),
                                 parameterAccessContext);

        } else {
            // Scalar requested
            CParameter::doGetValue(strValue, getOffset() + index * getSize(),
                                   parameterAccessContext);
        }
    }

    return true;
}

/// Actual parameter access
// String access
bool CArrayParameter::doSetValue(const string &value, size_t offset,
                                 CParameterAccessContext &parameterAccessContext) const
{
    return setValues(0, offset, value, parameterAccessContext);
}

void CArrayParameter::doGetValue(string &value, size_t offset,
                                 CParameterAccessContext &parameterAccessContext) const
{
    // Whole array requested
    value = getValues(offset, parameterAccessContext);
}

// Boolean
bool CArrayParameter::access(std::vector<bool> &abValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(abValues, bSet, parameterAccessContext);
}

// Integer
bool CArrayParameter::access(std::vector<uint32_t> &auiValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(auiValues, bSet, parameterAccessContext);
}

// Signed Integer Access
bool CArrayParameter::access(std::vector<int32_t> &aiValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(aiValues, bSet, parameterAccessContext);
}

// Double Access
bool CArrayParameter::access(std::vector<double> &adValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(adValues, bSet, parameterAccessContext);
}

// String Access
bool CArrayParameter::access(std::vector<string> &astrValues, bool bSet,
                             CParameterAccessContext &parameterAccessContext) const
{
    return accessValues(astrValues, bSet, parameterAccessContext);
}

// Dump
string CArrayParameter::logValue(CParameterAccessContext &context) const
{
    // Dump values
    return getValues(getOffset() - context.getBaseOffset(), context);
}

// Used for simulation and virtual subsystems
void CArrayParameter::setDefaultValues(CParameterAccessContext &parameterAccessContext) const
{
    // Get default value from type
    uint32_t uiDefaultValue =
        static_cast<const CParameterType *>(getTypeElement())->getDefaultValue();

    // Write blackboard
    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Process
    size_t valueIndex;
    size_t size = getSize();
    size_t offset = getOffset();
    size_t arrayLength = getArrayLength();

    for (valueIndex = 0; valueIndex < arrayLength; valueIndex++) {

        // Beware this code works on little endian architectures only!
        pBlackboard->writeInteger(&uiDefaultValue, size, offset);

        offset += size;
    }
}

// Index from path
bool CArrayParameter::getIndex(CPathNavigator &pathNavigator, size_t &index,
                               CParameterAccessContext &parameterAccessContext) const
{
    index = (size_t)-1;

    string *pStrChildName = pathNavigator.next();

    if (pStrChildName) {

        // Check index is numeric
        std::istringstream iss(*pStrChildName);

        iss >> index;

        if (!iss) {

            parameterAccessContext.setError("Expected numerical expression as last item in " +
                                            pathNavigator.getCurrentPath());

            return false;
        }

        if (index >= getArrayLength()) {
            std::ostringstream oss;

            oss << "Provided index out of range (max is " << getArrayLength() - 1 << ")";

            parameterAccessContext.setError(oss.str());

            return false;
        }

        // Check no other item provided in path
        pStrChildName = pathNavigator.next();

        if (pStrChildName) {

            // Should be leaf element
            parameterAccessContext.setError("Path not found: " + pathNavigator.getCurrentPath());

            return false;
        }
    }

    return true;
}

// Common set value processing
bool CArrayParameter::setValues(size_t uiStartIndex, size_t offset, const string &strValue,
                                CParameterAccessContext &parameterAccessContext) const
{
    // Deal with value(s)
    Tokenizer tok(strValue, Tokenizer::defaultDelimiters + ",");

    std::vector<string> astrValues = tok.split();
    size_t nbValues = astrValues.size();

    // Check number of provided values
    if (nbValues + uiStartIndex > getArrayLength()) {

        // Out of bounds
        parameterAccessContext.setError("Too many values provided");

        return false;
    }

    // Process
    size_t valueIndex;
    size_t size = getSize();
    offset += uiStartIndex * size;

    for (valueIndex = 0; valueIndex < nbValues; valueIndex++) {

        if (!doSet(astrValues[valueIndex], offset, parameterAccessContext)) {

            // Append parameter path to error
            parameterAccessContext.appendToError(" " + getPath() + "/" +
                                                 std::to_string(valueIndex + uiStartIndex));

            return false;
        }

        offset += size;
    }
    return true;
}

// Common get value processing
string CArrayParameter::getValues(size_t offset,
                                  CParameterAccessContext &parameterAccessContext) const
{
    size_t size = getSize();
    size_t arrayLength = getArrayLength();

    string output;

    bool bFirst = true;

    for (size_t valueIndex = 0; valueIndex < arrayLength; valueIndex++) {
        string strReadValue;

        doGet(strReadValue, offset, parameterAccessContext);

        if (!bFirst) {

            output += " ";
        } else {

            bFirst = false;
        }

        output += strReadValue;

        offset += size;
    }

    return output;
}

// Generic Access
template <typename type>
bool CArrayParameter::accessValues(std::vector<type> &values, bool bSet,
                                   CParameterAccessContext &parameterAccessContext) const
{
    if (bSet) {

        // Set Value
        if (!setValues(values, parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
        if (!sync(parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    } else {
        // Get Value
        if (!getValues(values, parameterAccessContext)) {

            appendParameterPathToError(parameterAccessContext);
            return false;
        }
    }
    return true;
}

template <typename type>
bool CArrayParameter::setValues(const std::vector<type> &values,
                                CParameterAccessContext &parameterAccessContext) const
{
    size_t nbValues = getArrayLength();
    size_t size = getSize();
    size_t offset = getOffset();

    assert(values.size() == nbValues);

    // Process
    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {

        if (!doSet(values[valueIndex], offset, parameterAccessContext)) {

            return false;
        }

        offset += size;
    }

    return true;
}

template <typename type>
bool CArrayParameter::getValues(std::vector<type> &values,
                                CParameterAccessContext &parameterAccessContext) const
{
    size_t nbValues = getArrayLength();
    size_t size = getSize();
    size_t offset = getOffset();

    values.clear();

    for (size_t valueIndex = 0; valueIndex < nbValues; valueIndex++) {
        type readValue;

        if (!doGet(readValue, offset, parameterAccessContext)) {

            return false;
        }

        values.push_back(readValue);

        offset += size;
    }
    return true;
}

template <typename type>
bool CArrayParameter::doSet(type value, size_t offset,
                            CParameterAccessContext &parameterAccessContext) const
{
    uint32_t uiData;

    if (!static_cast<const CParameterType *>(getTypeElement())
             ->toBlackboard(value, uiData, parameterAccessContext)) {

        return false;
    }
    // Write blackboard
    CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Beware this code works on little endian architectures only!
    pBlackboard->writeInteger(&uiData, getSize(), offset);

    return true;
}

template <typename type>
bool CArrayParameter::doGet(type &value, size_t offset,
                            CParameterAccessContext &parameterAccessContext) const
{
    uint32_t uiData = 0;

    // Read blackboard
    const CParameterBlackboard *pBlackboard = parameterAccessContext.getParameterBlackboard();

    // Beware this code works on little endian architectures only!
    pBlackboard->readInteger(&uiData, getSize(), offset);

    return static_cast<const CParameterType *>(getTypeElement())
        ->fromBlackboard(value, uiData, parameterAccessContext);
}
<|endoftext|>