<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.2  2002/02/20 18:17:01  tng
 * [Bug 5977] Warnings on generating apiDocs.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:08  peiyongz
 * sane_include
 *
 * Revision 1.10  2001/11/21 16:14:32  tng
 * Schema: New method InputSource::get/setIssueFatalErrorIfNotFound to tell the parser whether to issue fatal error or not if cannot find it (the InputSource).  This is required for schema processing as it shouldn't be a fatal error if the schema is not found.
 *
 * Revision 1.9  2000/03/02 19:54:35  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.8  2000/02/24 20:12:55  abagchi
 * Swat for removing Log from API docs
 *
 * Revision 1.7  2000/02/12 03:42:21  rahulj
 * Fixed DOC++ documentation formatting errors.
 *
 * Revision 1.6  2000/02/12 03:31:55  rahulj
 * Removed duplicate CVS Log entries.
 *
 * Revision 1.5  2000/02/12 01:27:19  aruna1
 * Documentation updated
 *
 * Revision 1.4  2000/02/09 02:15:28  abagchi
 * Documented destructor
 *
 * Revision 1.3  2000/02/06 07:47:58  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.2  2000/01/12 00:15:39  roddey
 * Changes to deal with multiply nested, relative pathed, entities and to deal
 * with the new URL class changes.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:46  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:01  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#ifndef INPUTSOURCE_HPP
#define INPUTSOURCE_HPP

#include <xercesc/util/XercesDefs.hpp>

class BinInputStream;

/**
  * A single input source for an XML entity.
  *
  *
This class encapsulates information about an input source in a
  * single object, which may include a public identifier or a system
  * identifier

  *
  *
There are two places that the application will deliver this input
  * source to the parser: as the argument to the Parser::parse method, or as
  * the return value of the EntityResolver::resolveEntity method.

  *
  *
InputSource is never used directly, but is the base class for a number
  * of derived classes for particular types of input sources. Derivatives are
  * provided (in the internal/ directory) for URL input sources, memory buffer
  * input sources, and so on.

  *
  *
When it is time to parse the input described by an input source, it
  * will be asked to create a binary stream for that source. That stream will
  * be used to input the data of the source. The derived class provides the
  * implementation of the makeStream() method, and provides a type of stream
  * of the correct type for the input source it represents.
  *
  *
An InputSource object belongs to the application: the parser never
  * modifies them in any way. They are always passed by const reference so
  * the parser will make a copy of any input sources that it must keep
  * around beyond the call.

  *
  * @see Parser#parse
  * @see EntityResolver#resolveEntity
  */
class SAX_EXPORT InputSource
{
public:
    // -----------------------------------------------------------------------
    //  All constructors are hidden, just the destructor is available
    // -----------------------------------------------------------------------
    /** @name Destructor */
    //@{
  /**
    * Destructor
    *
    */
    virtual ~InputSource();
    //@}

    // -----------------------------------------------------------------------
    /** @name Virtual input source interface */
    //@{
  /**
    * Makes the byte stream for this input source.
    *
    *
The derived class must create and return a binary input stream of an
    * appropriate type for its kind of data source. The returned stream must
    * be dynamically allocated and becomes the parser's property.
    *

    *
    * @see BinInputStream
    */
    virtual BinInputStream* makeStream() const = 0;

    //@}

    // -----------------------------------------------------------------------
    /** @name Getter methods */
    //@{
  /**
    * An input source can be set to force the parser to assume a particular
    * encoding for the data that input source reprsents, via the setEncoding()
    * method. This method returns name of the encoding that is to be forced.
    * If the encoding has never been forced, it returns a null pointer.
    *
    * @return The forced encoding, or null if none was supplied.
    * @see #setEncoding
    */
    const XMLCh* getEncoding() const;

  /**
    * Get the public identifier for this input source.
    *
    * @return The public identifier, or null if none was supplied.
    * @see #setPublicId
    */
    const XMLCh* getPublicId() const;

  /**
    * Get the system identifier for this input source.
    *
    *
If the system ID is a URL, it will be fully resolved.

    *
    * @return The system identifier.
    * @see #setSystemId
    */
    const XMLCh* getSystemId() const;

  /**
    * Get the flag that indicates if the parser should issue fatal error if this input source
    * is not found.
    *
    * @return True if the parser should issue fatal error if this input source is not found.
    *         False if the parser issue warning message instead.
    * @see #setIssueFatalErrorIfNotFound
    */
    const bool getIssueFatalErrorIfNotFound() const;

    //@}

    // -----------------------------------------------------------------------
    /** @name Setter methods */
    //@{

  /**
    * Set the encoding which will be required for use with the XML text read
    * via a stream opened by this input source.
    *
    *
This is usually not set, allowing the encoding to be sensed in the
    * usual XML way. However, in some cases, the encoding in the file is known
    * to be incorrect because of intermediate transcoding, for instance
    * encapsulation within a MIME document.
    *
    * @param encodingStr The name of the encoding to force.
    */
    void setEncoding(const XMLCh* const encodingStr);

  /**
    * Set the public identifier for this input source.
    *
    *
The public identifier is always optional: if the application writer
    * includes one, it will be provided as part of the location information.

    *
    * @param publicId The public identifier as a string.
    * @see Locator#getPublicId
    * @see SAXParseException#getPublicId
    * @see #getPublicId
    */
    void setPublicId(const XMLCh* const publicId);

  /**
    * Set the system identifier for this input source.
    *
    *
Set the system identifier for this input source.
    *
    *
The system id is always required. The public id may be used to map
    * to another system id, but the system id must always be present as a fall
    * back.
    *
    *
If the system ID is a URL, it must be fully resolved.

    *
    * @param systemId The system identifier as a string.
    * @see #getSystemId
    * @see Locator#getSystemId
    * @see SAXParseException#getSystemId
    */
    void setSystemId(const XMLCh* const systemId);

  /**
    * Indicates if the parser should issue fatal error if this input source
    * is not found.  If set to false, the parser issue warning message instead.
    *
    * @param  flag True if the parser should issue fatal error if this input source is not found.
    *               If set to false, the parser issue warning message instead.  (Default: true)
    *
    * @see #getIssueFatalErrorIfNotFound
    */
    void setIssueFatalErrorIfNotFound(const bool flag);

    //@}

protected :
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    /** @name Constructors and Destructor */
    //@{
    /** Default constructor */
    InputSource();

    /** Constructor with a system identifier as XMLCh type.
      * @param systemId The system identifier (URI).
      */
    InputSource(const XMLCh* const systemId);

    /** Constructor with a system and public identifiers
      * @param systemId The system identifier (URI).
      * @param publicId The public identifier as in the entity definition.
      */
    InputSource
    (
        const   XMLCh* const    systemId
        , const XMLCh* const    publicId
    );

    /** Constructor witha system identifier as string
      * @param systemId The system identifier (URI).
      */
    InputSource(const char* const systemId);

    /** Constructor witha system and public identifiers. Both as string
      * @param systemId The system identifier (URI).
      * @param publicId The public identifier as in the entity definition.
      */
    InputSource
    (
        const   char* const systemId
        , const char* const publicId
    );

    //@}

private:
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    InputSource(const InputSource&);
    void operator=(const InputSource&);

    // -----------------------------------------------------------------------
    //  Private data members
    //
    //  fEncoding
    //      This is the encoding to use. Usually this is null, which means
    //      to use the information found in the file itself. But, if set,
    //      this encoding will be used without question.
    //
    //  fPublicId
    //      This is the optional public id for the input source. It can be
    //      null if none is desired.
    //
    //  fSystemId
    //      This is the system id for the input source. This is what is
    //      actually used to open the source.
    //
    //  fFatalErrorIfNotFound
    // -----------------------------------------------------------------------
    XMLCh*  fEncoding;
    XMLCh*  fPublicId;
    XMLCh*  fSystemId;
    bool    fFatalErrorIfNotFound;
};

// ---------------------------------------------------------------------------
//  InputSource: Getter methods
// ---------------------------------------------------------------------------
inline const XMLCh* InputSource::getEncoding() const
{
    return fEncoding;
}

inline const XMLCh* InputSource::getPublicId() const
{
    return fPublicId;
}

inline const XMLCh* InputSource::getSystemId() const
{
    return fSystemId;
}

inline const bool InputSource::getIssueFatalErrorIfNotFound() const
{
    return fFatalErrorIfNotFound;
}

// ---------------------------------------------------------------------------
//  InputSource: Setter methods
// ---------------------------------------------------------------------------
inline void InputSource::setIssueFatalErrorIfNotFound(const bool flag)
{
    fFatalErrorIfNotFound = flag;
}

#endif
<commit_msg>Since the derived class Wrapper4DOMInputSource has overwritten the set/getEncoding, SystemId, PublicId ... etc., these functions has to be virtual for them to work.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Log$
 * Revision 1.3  2002/09/30 18:26:18  tng
 * Since the derived class Wrapper4DOMInputSource has overwritten the set/getEncoding, SystemId, PublicId ... etc., these functions has to be virtual for them to work.
 *
 * Revision 1.2  2002/02/20 18:17:01  tng
 * [Bug 5977] Warnings on generating apiDocs.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:08  peiyongz
 * sane_include
 *
 * Revision 1.10  2001/11/21 16:14:32  tng
 * Schema: New method InputSource::get/setIssueFatalErrorIfNotFound to tell the parser whether to issue fatal error or not if cannot find it (the InputSource).  This is required for schema processing as it shouldn't be a fatal error if the schema is not found.
 *
 * Revision 1.9  2000/03/02 19:54:35  roddey
 * This checkin includes many changes done while waiting for the
 * 1.1.0 code to be finished. I can't list them all here, but a list is
 * available elsewhere.
 *
 * Revision 1.8  2000/02/24 20:12:55  abagchi
 * Swat for removing Log from API docs
 *
 * Revision 1.7  2000/02/12 03:42:21  rahulj
 * Fixed DOC++ documentation formatting errors.
 *
 * Revision 1.6  2000/02/12 03:31:55  rahulj
 * Removed duplicate CVS Log entries.
 *
 * Revision 1.5  2000/02/12 01:27:19  aruna1
 * Documentation updated
 *
 * Revision 1.4  2000/02/09 02:15:28  abagchi
 * Documented destructor
 *
 * Revision 1.3  2000/02/06 07:47:58  rahulj
 * Year 2K copyright swat.
 *
 * Revision 1.2  2000/01/12 00:15:39  roddey
 * Changes to deal with multiply nested, relative pathed, entities and to deal
 * with the new URL class changes.
 *
 * Revision 1.1.1.1  1999/11/09 01:07:46  twl
 * Initial checkin
 *
 * Revision 1.2  1999/11/08 20:45:01  rahul
 * Swat for adding in Product name and CVS comment log variable.
 *
 */

#ifndef INPUTSOURCE_HPP
#define INPUTSOURCE_HPP

#include <xercesc/util/XercesDefs.hpp>

class BinInputStream;

/**
  * A single input source for an XML entity.
  *
  *
This class encapsulates information about an input source in a
  * single object, which may include a public identifier or a system
  * identifier

  *
  *
There are two places that the application will deliver this input
  * source to the parser: as the argument to the Parser::parse method, or as
  * the return value of the EntityResolver::resolveEntity method.

  *
  *
InputSource is never used directly, but is the base class for a number
  * of derived classes for particular types of input sources. Derivatives are
  * provided (in the internal/ directory) for URL input sources, memory buffer
  * input sources, and so on.

  *
  *
When it is time to parse the input described by an input source, it
  * will be asked to create a binary stream for that source. That stream will
  * be used to input the data of the source. The derived class provides the
  * implementation of the makeStream() method, and provides a type of stream
  * of the correct type for the input source it represents.
  *
  *
An InputSource object belongs to the application: the parser never
  * modifies them in any way. They are always passed by const reference so
  * the parser will make a copy of any input sources that it must keep
  * around beyond the call.

  *
  * @see Parser#parse
  * @see EntityResolver#resolveEntity
  */
class SAX_EXPORT InputSource
{
public:
    // -----------------------------------------------------------------------
    //  All constructors are hidden, just the destructor is available
    // -----------------------------------------------------------------------
    /** @name Destructor */
    //@{
  /**
    * Destructor
    *
    */
    virtual ~InputSource();
    //@}

    // -----------------------------------------------------------------------
    /** @name Virtual input source interface */
    //@{
  /**
    * Makes the byte stream for this input source.
    *
    *
The derived class must create and return a binary input stream of an
    * appropriate type for its kind of data source. The returned stream must
    * be dynamically allocated and becomes the parser's property.
    *

    *
    * @see BinInputStream
    */
    virtual BinInputStream* makeStream() const = 0;

    //@}

    // -----------------------------------------------------------------------
    /** @name Getter methods */
    //@{
  /**
    * An input source can be set to force the parser to assume a particular
    * encoding for the data that input source reprsents, via the setEncoding()
    * method. This method returns name of the encoding that is to be forced.
    * If the encoding has never been forced, it returns a null pointer.
    *
    * @return The forced encoding, or null if none was supplied.
    * @see #setEncoding
    */
    virtual const XMLCh* getEncoding() const;

  /**
    * Get the public identifier for this input source.
    *
    * @return The public identifier, or null if none was supplied.
    * @see #setPublicId
    */
    virtual const XMLCh* getPublicId() const;

  /**
    * Get the system identifier for this input source.
    *
    *
If the system ID is a URL, it will be fully resolved.

    *
    * @return The system identifier.
    * @see #setSystemId
    */
    virtual const XMLCh* getSystemId() const;

  /**
    * Get the flag that indicates if the parser should issue fatal error if this input source
    * is not found.
    *
    * @return True if the parser should issue fatal error if this input source is not found.
    *         False if the parser issue warning message instead.
    * @see #setIssueFatalErrorIfNotFound
    */
    virtual const bool getIssueFatalErrorIfNotFound() const;

    //@}

    // -----------------------------------------------------------------------
    /** @name Setter methods */
    //@{

  /**
    * Set the encoding which will be required for use with the XML text read
    * via a stream opened by this input source.
    *
    *
This is usually not set, allowing the encoding to be sensed in the
    * usual XML way. However, in some cases, the encoding in the file is known
    * to be incorrect because of intermediate transcoding, for instance
    * encapsulation within a MIME document.
    *
    * @param encodingStr The name of the encoding to force.
    */
    virtual void setEncoding(const XMLCh* const encodingStr);

  /**
    * Set the public identifier for this input source.
    *
    *
The public identifier is always optional: if the application writer
    * includes one, it will be provided as part of the location information.

    *
    * @param publicId The public identifier as a string.
    * @see Locator#getPublicId
    * @see SAXParseException#getPublicId
    * @see #getPublicId
    */
    virtual void setPublicId(const XMLCh* const publicId);

  /**
    * Set the system identifier for this input source.
    *
    *
Set the system identifier for this input source.
    *
    *
The system id is always required. The public id may be used to map
    * to another system id, but the system id must always be present as a fall
    * back.
    *
    *
If the system ID is a URL, it must be fully resolved.

    *
    * @param systemId The system identifier as a string.
    * @see #getSystemId
    * @see Locator#getSystemId
    * @see SAXParseException#getSystemId
    */
    virtual void setSystemId(const XMLCh* const systemId);

  /**
    * Indicates if the parser should issue fatal error if this input source
    * is not found.  If set to false, the parser issue warning message instead.
    *
    * @param  flag True if the parser should issue fatal error if this input source is not found.
    *               If set to false, the parser issue warning message instead.  (Default: true)
    *
    * @see #getIssueFatalErrorIfNotFound
    */
    virtual void setIssueFatalErrorIfNotFound(const bool flag);

    //@}

protected :
    // -----------------------------------------------------------------------
    //  Hidden constructors
    // -----------------------------------------------------------------------
    /** @name Constructors and Destructor */
    //@{
    /** Default constructor */
    InputSource();

    /** Constructor with a system identifier as XMLCh type.
      * @param systemId The system identifier (URI).
      */
    InputSource(const XMLCh* const systemId);

    /** Constructor with a system and public identifiers
      * @param systemId The system identifier (URI).
      * @param publicId The public identifier as in the entity definition.
      */
    InputSource
    (
        const   XMLCh* const    systemId
        , const XMLCh* const    publicId
    );

    /** Constructor witha system identifier as string
      * @param systemId The system identifier (URI).
      */
    InputSource(const char* const systemId);

    /** Constructor witha system and public identifiers. Both as string
      * @param systemId The system identifier (URI).
      * @param publicId The public identifier as in the entity definition.
      */
    InputSource
    (
        const   char* const systemId
        , const char* const publicId
    );

    //@}

private:
    // -----------------------------------------------------------------------
    //  Unimplemented constructors and operators
    // -----------------------------------------------------------------------
    InputSource(const InputSource&);
    void operator=(const InputSource&);

    // -----------------------------------------------------------------------
    //  Private data members
    //
    //  fEncoding
    //      This is the encoding to use. Usually this is null, which means
    //      to use the information found in the file itself. But, if set,
    //      this encoding will be used without question.
    //
    //  fPublicId
    //      This is the optional public id for the input source. It can be
    //      null if none is desired.
    //
    //  fSystemId
    //      This is the system id for the input source. This is what is
    //      actually used to open the source.
    //
    //  fFatalErrorIfNotFound
    // -----------------------------------------------------------------------
    XMLCh*  fEncoding;
    XMLCh*  fPublicId;
    XMLCh*  fSystemId;
    bool    fFatalErrorIfNotFound;
};

// ---------------------------------------------------------------------------
//  InputSource: Getter methods
// ---------------------------------------------------------------------------
inline const XMLCh* InputSource::getEncoding() const
{
    return fEncoding;
}

inline const XMLCh* InputSource::getPublicId() const
{
    return fPublicId;
}

inline const XMLCh* InputSource::getSystemId() const
{
    return fSystemId;
}

inline const bool InputSource::getIssueFatalErrorIfNotFound() const
{
    return fFatalErrorIfNotFound;
}

// ---------------------------------------------------------------------------
//  InputSource: Setter methods
// ---------------------------------------------------------------------------
inline void InputSource::setIssueFatalErrorIfNotFound(const bool flag)
{
    fFatalErrorIfNotFound = flag;
}

#endif
<|endoftext|>


<commit_before>/*
 * This file is part of Peli - universal JSON interaction library
 * Copyright (C) 2014  Alexey Chernov <4ernov@gmail.com>
 *
 * Peli 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cassert>

#include "peli/json/value.h"

using namespace std;

using namespace peli;

int main(int, char**)
{
	json::value v1(json::make_value<json::object>());
	json::object& obj1(v1);
	obj1["test"] = json::value(52);

	json::value v2;

	static_assert(noexcept(json::value() = std::move(v2)), "Move assignment isn't noexcept");

	v2 = std::move(v1);

	json::object& obj2(v2);
	obj2["tost"] = json::value(false);

	return 0;
}
<commit_msg>Fix static assertion of exception safety of move assignment<commit_after>/*
 * This file is part of Peli - universal JSON interaction library
 * Copyright (C) 2014  Alexey Chernov <4ernov@gmail.com>
 *
 * Peli 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 3 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, see <http://www.gnu.org/licenses/>.
 *
 */

#include <cassert>

#include "peli/json/value.h"

using namespace std;

using namespace peli;

int main(int, char**)
{
	json::value v1(json::make_value<json::object>());
	json::object& obj1(v1);
	obj1["test"] = json::value(52);

	json::value v2;

	static_assert(noexcept(declval<json::value>().operator=(std::move(v2))), "Move assignment isn't noexcept");

	v2 = std::move(v1);

	json::object& obj2(v2);
	obj2["tost"] = json::value(false);

	return 0;
}
<|endoftext|>


<commit_before>#include "VisPlugin.h"
#include <cairo/cairo.h>
#include <math.h>

#define MIN_FREQ 100
#define MAX_FREQ 22050
#define PALETTE_RED {0.196, 0, 1, 1}
#define PALETTE_GREEN {0, 0.863, 0.878, 0.274}
#define PALETTE_BLUE {0.784, 0.314, 0, 0}
#define PALETTE_LENGTH 4

class SpecCent: public VisPlugin {

private:

  // given a list of gradient values, return the value of a point
  // on that gradient
  //
  // e.g. colour={1.0, 0.5, 0.0}
  // colourmap(0.25, colour, 3) returns 0.75
  double colourmap(double value, double colour[], int length)
  {
    int iter=0;
    double step = 1.0/(double)length;
    if (value>1) return 0;
    while (value > step*(iter+1)) iter++;
    double weight = (value-step*(double)iter)/step;
    return (1.0-weight)*colour[iter] + weight*colour[iter+1];
  }

  double red(double value)
  {
    double colours[] = PALETTE_RED;
    return colourmap(value, colours, PALETTE_LENGTH);
  }

  double green(double value)
  {
    double colours[] = PALETTE_GREEN;
    return colourmap(value, colours, PALETTE_LENGTH);
  }

  double blue(double value)
  {
    double colours[] = PALETTE_BLUE;
    return colourmap(value, colours, PALETTE_LENGTH);
  }

public:

    virtual double getVersion() const {
        return 0.1;
    }

    virtual int ARGB(Plugin::FeatureSet features, int width,
        int height, unsigned char *bitmap)
    {
      const double lower = MIN_FREQ;
      const double higher = MAX_FREQ;
      const double lower_log = log10(lower);
      const double higher_log = log10(higher);

      // set up cairo surface
      cairo_surface_t *surface;
      cairo_format_t format = CAIRO_FORMAT_ARGB32;
      int stride = cairo_format_stride_for_width(format, width);
      surface = cairo_image_surface_create_for_data (bitmap, format, width,
          height, stride);

      // set up cairo context
      cairo_t *cr;
      cr = cairo_create(surface);
      cairo_scale(cr, width, height);
      cairo_set_source_rgba(cr, 0, 0, 0, 1);
      cairo_paint(cr);

      // find number of frames for peak/spec centroid
      unsigned int peakFrames = features[0].size();
      unsigned int scFrames = features[1].size();
      double scScale = (double)scFrames/(double)peakFrames;

      // for each peak frame, draw a coloured line
      for (unsigned int peakFrame=0; peakFrame<peakFrames; peakFrame++)
      {
        // find spectral contrast, clip and scale
        double sc = features[1].at(floor(scScale*peakFrame)).values[0];
        if (sc < lower) sc=lower;
        if (sc > higher) sc=higher;
        sc = (log10(sc)-lower_log)/(higher_log-lower_log);

        // get peak values
        double peak1 = features[0].at(peakFrame).values[0];
        double peak2 = features[0].at(peakFrame).values[1];

        // draw waveform
        cairo_set_source_rgba(cr, red(sc), green(sc), blue(sc), 1.0);
        cairo_line_to(cr, (double)peakFrame/(double)peakFrames,
                          0.5-(peak1*0.5));
        cairo_line_to(cr, (double)peakFrame/(double)peakFrames,
                          0.5-(peak2*0.5));
        cairo_set_line_width (cr, 1.0/(double)peakFrames);
        cairo_stroke (cr);
      }

      // clean up
      cairo_destroy(cr);
      cairo_surface_destroy (surface);

      return 0;
    }

    virtual VampOutputList getVampPlugins()
    {
      VampOutputList pluginList;

      VampPlugin bbcPeaks = {"bbc-vamp-plugins:bbc-peaks", 0, 0};
      VampOutput peaks = {bbcPeaks, "peaks"};
      VampPlugin libxSpecCent = {"vamp-libxtract:spectral_centroid", 0, 0};
      VampOutput specCent = {libxSpecCent, "spectral_centroid"};

      pluginList.push_back(peaks);
      pluginList.push_back(specCent);
      return pluginList;
    }
};

extern "C" VisPlugin* create() {
    return new SpecCent;
}

extern "C" void destroy(VisPlugin* p) {
    delete p;
}
<commit_msg>Changed colour to color so as not to confuse the yanks.<commit_after>#include "VisPlugin.h"
#include <cairo/cairo.h>
#include <math.h>

#define MIN_FREQ 100
#define MAX_FREQ 22050
#define PALETTE_RED {0.196, 0, 1, 1}
#define PALETTE_GREEN {0, 0.863, 0.878, 0.274}
#define PALETTE_BLUE {0.784, 0.314, 0, 0}
#define PALETTE_LENGTH 4

class SpecCent: public VisPlugin {

private:

  // given a list of gradient values, return the value of a point
  // on that gradient
  //
  // e.g. color={1.0, 0.5, 0.0}
  // colormap(0.25, color, 3) returns 0.75
  double colormap(double value, double color[], int length)
  {
    int iter=0;
    double step = 1.0/(double)length;
    if (value>1) return 0;
    while (value > step*(iter+1)) iter++;
    double weight = (value-step*(double)iter)/step;
    return (1.0-weight)*color[iter] + weight*color[iter+1];
  }

  double red(double value)
  {
    double colors[] = PALETTE_RED;
    return colormap(value, colors, PALETTE_LENGTH);
  }

  double green(double value)
  {
    double colors[] = PALETTE_GREEN;
    return colormap(value, colors, PALETTE_LENGTH);
  }

  double blue(double value)
  {
    double colors[] = PALETTE_BLUE;
    return colormap(value, colors, PALETTE_LENGTH);
  }

public:

    virtual double getVersion() const {
        return 0.1;
    }

    virtual int ARGB(Plugin::FeatureSet features, int width,
        int height, unsigned char *bitmap)
    {
      const double lower = MIN_FREQ;
      const double higher = MAX_FREQ;
      const double lower_log = log10(lower);
      const double higher_log = log10(higher);

      // set up cairo surface
      cairo_surface_t *surface;
      cairo_format_t format = CAIRO_FORMAT_ARGB32;
      int stride = cairo_format_stride_for_width(format, width);
      surface = cairo_image_surface_create_for_data (bitmap, format, width,
          height, stride);

      // set up cairo context
      cairo_t *cr;
      cr = cairo_create(surface);
      cairo_scale(cr, width, height);
      cairo_set_source_rgba(cr, 0, 0, 0, 1);
      cairo_paint(cr);

      // find number of frames for peak/spec centroid
      unsigned int peakFrames = features[0].size();
      unsigned int scFrames = features[1].size();
      double scScale = (double)scFrames/(double)peakFrames;

      // for each peak frame, draw a colored line
      for (unsigned int peakFrame=0; peakFrame<peakFrames; peakFrame++)
      {
        // find spectral contrast, clip and scale
        double sc = features[1].at(floor(scScale*peakFrame)).values[0];
        if (sc < lower) sc=lower;
        if (sc > higher) sc=higher;
        sc = (log10(sc)-lower_log)/(higher_log-lower_log);

        // get peak values
        double peak1 = features[0].at(peakFrame).values[0];
        double peak2 = features[0].at(peakFrame).values[1];

        // draw waveform
        cairo_set_source_rgba(cr, red(sc), green(sc), blue(sc), 1.0);
        cairo_line_to(cr, (double)peakFrame/(double)peakFrames,
                          0.5-(peak1*0.5));
        cairo_line_to(cr, (double)peakFrame/(double)peakFrames,
                          0.5-(peak2*0.5));
        cairo_set_line_width (cr, 1.0/(double)peakFrames);
        cairo_stroke (cr);
      }

      // clean up
      cairo_destroy(cr);
      cairo_surface_destroy (surface);

      return 0;
    }

    virtual VampOutputList getVampPlugins()
    {
      VampOutputList pluginList;

      VampPlugin bbcPeaks = {"bbc-vamp-plugins:bbc-peaks", 0, 0};
      VampOutput peaks = {bbcPeaks, "peaks"};
      VampPlugin libxSpecCent = {"vamp-libxtract:spectral_centroid", 0, 0};
      VampOutput specCent = {libxSpecCent, "spectral_centroid"};

      pluginList.push_back(peaks);
      pluginList.push_back(specCent);
      return pluginList;
    }
};

extern "C" VisPlugin* create() {
    return new SpecCent;
}

extern "C" void destroy(VisPlugin* p) {
    delete p;
}
<|endoftext|>


<commit_before>#include <cmath>
#include <stdlib.h>
#include <assert.h>

#include "ys_matrix.h"

double ran_uniform() {
    return rand()/((double)RAND_MAX + 1);
}

using namespace ys;

int main(void) {
    DMatrix<double> dmatrix(100, 1000);
    for (int i = 0; i < dmatrix.getDimX(); ++i) {
    for (int j = 0; j < dmatrix.getDimY(); ++j) {
        dmatrix(i, j) = ran_uniform();
    }
    }
    dmatrix.save("tmpfile");
    DMatrix<double> dmatrix1();
    dmatrix1.load("tmpfile");
    for (int i = 0; i < dmatrix1.getDimX(); ++i) {
    for (int j = 0; j < dmatrix1.getDimY(); ++j) {
        assert (dmatrix1[i][j] = dmatrix[i][j]);
    }
    }

    DMatrix<double> dmatrix2();
    dmatrix2 = dmatrix;
    for (int i = 0; i < dmatrix2.getDimX(); ++i) {
    for (int j = 0; j < dmatrix2.getDimY(); ++j) {
        assert (dmatrix1[i][j] = dmatrix2[i][j]);
    }
    }

    DMatrix<double> dmatrix3();
    dmatrix3.assign(dmatrix1);
    for (int i = 0; i < dmatrix3.getDimX(); ++i) {
    for (int j = 0; j < dmatrix3.getDimY(); ++j) {
        assert (dmatrix3[i][j] = dmatrix2[i][j]);
    }
    }

    DMatrix<double> dmatrix4(dmatrix2);
    for (int i = 0; i < dmatrix4.getDimX(); ++i) {
    for (int j = 0; j < dmatrix4.getDimY(); ++j) {
        assert (dmatrix4[i][j] = dmatrix[i][j]);
    }
    }
    return 0;
}
<commit_msg>modify<commit_after>#include <cmath>
#include <stdlib.h>
#include <assert.h>

#include "ys_matrix.h"

double ran_uniform() {
    return rand()/((double)RAND_MAX + 1);
}

using namespace ys;

int main(void) {
    DMatrix<double> dmatrix(100, 1000);
    for (int i = 0; i < dmatrix.getDimX(); ++i) {
    for (int j = 0; j < dmatrix.getDimY(); ++j) {
        dmatrix(i, j) = ran_uniform();
    }
    }
    dmatrix.save("tmpfile");
    DMatrix<double> dmatrix1;
    dmatrix1.load("tmpfile");
    for (int i = 0; i < dmatrix1.getDimX(); ++i) {
    for (int j = 0; j < dmatrix1.getDimY(); ++j) {
        assert (dmatrix1[i][j] = dmatrix[i][j]);
    }
    }

    DMatrix<double> dmatrix2;
    dmatrix2 = dmatrix;
    for (int i = 0; i < dmatrix2.getDimX(); ++i) {
    for (int j = 0; j < dmatrix2.getDimY(); ++j) {
        assert (dmatrix1[i][j] = dmatrix2[i][j]);
    }
    }

    DMatrix<double> dmatrix3;
    dmatrix3.assign(dmatrix1);
    for (int i = 0; i < dmatrix3.getDimX(); ++i) {
    for (int j = 0; j < dmatrix3.getDimY(); ++j) {
        assert (dmatrix3[i][j] = dmatrix2[i][j]);
    }
    }

    DMatrix<double> dmatrix4(dmatrix2);
    for (int i = 0; i < dmatrix4.getDimX(); ++i) {
    for (int j = 0; j < dmatrix4.getDimY(); ++j) {
        assert (dmatrix4[i][j] = dmatrix[i][j]);
    }
    }
    return 0;
}
<|endoftext|>


<commit_before>#include "mediamodel.h"
#include "mediascanner.h"
#include "dbreader.h"
#include "backend.h"

#define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__

MediaModel::MediaModel(QObject *parent)
    : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0)
{
}

MediaModel::~MediaModel()
{
}

QString MediaModel::part() const
{
    return m_structure.split("|").value(m_cursor.length());
}

QString MediaModel::mediaType() const
{
    return m_mediaType;
}

void MediaModel::setMediaType(const QString &type)
{
    m_mediaType = type;
    emit mediaTypeChanged();

    initialize();

    QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
    QSqlRecord record = driver->record(m_mediaType);
    if (record.isEmpty())
        qWarning() << "Table " << type << " is not valid it seems";

    QHash<int, QByteArray> hash = roleNames();
    hash.insert(Qt::UserRole, "dotdot");
    hash.insert(Qt::UserRole+1, "isLeaf");

    for (int i = 0; i < record.count(); i++) {
        hash.insert(Qt::UserRole + i + 2, record.fieldName(i).toUtf8());
    }

    setRoleNames(hash);
}

void MediaModel::addSearchPath(const QString &path, const QString &name)
{
    QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection, Q_ARG(QString, "picture"), Q_ARG(QString, path), Q_ARG(QString, name));
}

void MediaModel::removeSearchPath(int index)
{
    Q_UNUSED(index);
}

QString MediaModel::structure() const
{
    return m_structure;
}

void MediaModel::setStructure(const QString &str)
{
    m_structure = str;
    emit structureChanged();

    initialize();
}

void MediaModel::enter(int index)
{
    Q_UNUSED(index);

    if (m_cursor.count() + 1 == m_structure.split("|").count() &&  index != 0 /* up on leaf node is OK */) {
        DEBUG << "Refusing to enter leaf node";
        return;
    }

    if (index == 0 && !m_cursor.isEmpty()) {
        back();
        return;
    }

    DEBUG << "Entering " << index;

    m_cursor.append(m_data[index]);

    initialize();

    emit partChanged();
}

void MediaModel::back()
{
    m_cursor.removeLast();
    initialize();
    emit partChanged();
}

QVariant MediaModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    const QHash<QString, QVariant> &data = m_data[index.row()];
    const QHash<int, QByteArray> hash = roleNames();
    return data.value(hash.value(role));
}

QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const
{
    if (parent.isValid())
        return QModelIndex();

    return createIndex(row, col);
}

QModelIndex MediaModel::parent(const QModelIndex &idx) const
{
    Q_UNUSED(idx);
    return QModelIndex();
}

int MediaModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_data.count();
}

int MediaModel::columnCount(const QModelIndex &idx) const
{
    Q_UNUSED(idx);
    return 1;
}

bool MediaModel::hasChildren(const QModelIndex &parent) const
{
    return !parent.isValid();
}

bool MediaModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty())
        return false;
    return !m_loading && !m_loaded;
}

void MediaModel::fetchMore(const QModelIndex &parent)
{
    if (!canFetchMore(parent))
        return;

    initialize();

    QSqlQuery q = query();
    DEBUG << q.lastQuery();

    m_loading = true;

    QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q));
}

void MediaModel::initialize()
{
    beginResetModel();

    m_data.clear();

    DbReader *newReader = new DbReader;
    if (m_reader) {
        disconnect(m_reader, 0, this, 0);
        m_reader->stop();
        m_reader->deleteLater();
    }
    m_reader = newReader;

    if (!m_readerThread) {
        m_readerThread = new QThread(this);
        m_readerThread->start();
    }
    m_reader->moveToThread(m_readerThread);
    QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase()));
    connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)),
            this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *)));

    m_loading = m_loaded = false;

    endResetModel();
}

void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node)
{
    Q_ASSERT(reader == m_reader);
    Q_UNUSED(reader);
    Q_UNUSED(node);

    DEBUG << "Received response from db of size " << records.size();

    if (records.isEmpty())
        return;

    if (!m_cursor.isEmpty()) {
        beginInsertRows(QModelIndex(), 0, records.count());
        QHash<QString, QVariant> data;
        data.insert("display", tr(".."));
        data.insert("dotdot", true);
        data.insert("isLeaf", false);
        m_data.append(data);
    } else {
        beginInsertRows(QModelIndex(), 0, records.count() - 1);
    }

    bool isLeaf = false;
    if (m_cursor.count() + 1 == m_structure.split("|").count())
        isLeaf = true;

    for (int i = 0; i < records.count(); i++) {
        QHash<QString, QVariant> data;
        for (int j = 0; j < records[i].count(); j++) {
            data.insert(records[i].fieldName(j), records[i].value(j));
        }

        QStringList cols = m_structure.split("|").value(m_cursor.count()).split(",");
        QStringList displayString;
        for (int j = 0; j < cols.count(); j++) {
            displayString << records[i].value(cols[j]).toString();
        }
        data.insert("display", displayString.join(", "));
        data.insert("dotdot", false);
        data.insert("isLeaf", isLeaf);

        m_data.append(data);

    }

    m_loading = false;
    m_loaded = true;

    endInsertRows();
}

void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records)
{
    Q_UNUSED(records);
    // not implemented yet
}

QSqlQuery MediaModel::query()
{
    QString q;
    QStringList parts = m_structure.split("|");
    QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
    QString curPart = parts[m_cursor.count()];
    QStringList curParts = curPart.split(",");
    QStringList escapedCurParts;
    for (int i = 0; i < curParts.count(); i++)
        escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName));
    QString escapedCurPart = escapedCurParts.join(",");

    QSqlQuery query(Backend::instance()->mediaDatabase());
    query.setForwardOnly(true);

    QStringList placeHolders;
    const bool lastPart = m_cursor.count() == parts.count()-1;
    QString queryString = QString("SELECT %1 FROM %2 ").arg(lastPart ? "*" : escapedCurPart).arg(driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName));

    if (!m_cursor.isEmpty()) {
        QStringList where;
        for (int i = 0; i < m_cursor.count(); i++) {
            QString part = parts[i];
            QStringList subParts = part.split(",");
            for (int j = 0; j < subParts.count(); j++) {
                where.append(subParts[j] + " = ?");
                placeHolders << m_cursor[i].value(subParts[j]).toString();
            }
        }

        queryString.append(QString("WHERE %1 ").arg(where.join(" AND ")));
    }

    if (!lastPart)
        queryString.append(QString("GROUP BY %1 ").arg(escapedCurPart));

    queryString.append(QString("ORDER BY %1").arg(escapedCurPart));

    query.prepare(queryString);

    foreach(const QString &placeHolder, placeHolders)
        query.addBindValue(placeHolder);

    return query;
}

<commit_msg>Code beautification<commit_after>#include "mediamodel.h"
#include "mediascanner.h"
#include "dbreader.h"
#include "backend.h"

#define DEBUG if (1) qDebug() << __PRETTY_FUNCTION__

MediaModel::MediaModel(QObject *parent)
    : QAbstractItemModel(parent), m_loading(false), m_loaded(false), m_reader(0), m_readerThread(0)
{
}

MediaModel::~MediaModel()
{
}

QString MediaModel::part() const
{
    return m_structure.split("|").value(m_cursor.length());
}

QString MediaModel::mediaType() const
{
    return m_mediaType;
}

void MediaModel::setMediaType(const QString &type)
{
    if (type == m_mediaType)
        return;

    initialize();

    m_mediaType = type;
    emit mediaTypeChanged();

    // Add the fields of the table as role names
    QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
    QSqlRecord record = driver->record(m_mediaType);
    if (record.isEmpty())
        qWarning() << "Table " << type << " is not valid it seems";

    QHash<int, QByteArray> hash = roleNames();
    hash.insert(Qt::UserRole, "dotdot");
    hash.insert(Qt::UserRole+1, "isLeaf");

    for (int i = 0; i < record.count(); i++) {
        hash.insert(Qt::UserRole + i + 2, record.fieldName(i).toUtf8());
    }

    setRoleNames(hash);
}

void MediaModel::addSearchPath(const QString &path, const QString &name)
{
    if (m_mediaType.isEmpty()) {
        qWarning() << m_mediaType << " is not set yet";
        return;
    }

    QMetaObject::invokeMethod(MediaScanner::instance(), "addSearchPath", Qt::QueuedConnection,
                              Q_ARG(QString, m_mediaType), Q_ARG(QString, path), Q_ARG(QString, name));
}

void MediaModel::removeSearchPath(int index)
{
    Q_UNUSED(index);
}

QString MediaModel::structure() const
{
    return m_structure;
}

void MediaModel::setStructure(const QString &str)
{
    m_structure = str;
    initialize();
    emit structureChanged();
}

void MediaModel::enter(int index)
{
    Q_UNUSED(index);

    if (m_cursor.count() + 1 == m_structure.split("|").count() &&  index != 0 /* up on leaf node is OK */) {
        DEBUG << "Refusing to enter leaf node";
        return;
    }

    if (index == 0 && !m_cursor.isEmpty()) {
        back();
        return;
    }

    DEBUG << "Entering " << index;

    m_cursor.append(m_data[index]);

    initialize();

    emit partChanged();
}

void MediaModel::back()
{
    m_cursor.removeLast();
    initialize();
    emit partChanged();
}

QVariant MediaModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    const QHash<QString, QVariant> &data = m_data[index.row()];
    const QHash<int, QByteArray> hash = roleNames();
    return data.value(hash.value(role));
}

QModelIndex MediaModel::index(int row, int col, const QModelIndex &parent) const
{
    if (parent.isValid())
        return QModelIndex();

    return createIndex(row, col);
}

QModelIndex MediaModel::parent(const QModelIndex &idx) const
{
    Q_UNUSED(idx);
    return QModelIndex();
}

int MediaModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;
    return m_data.count();
}

int MediaModel::columnCount(const QModelIndex &idx) const
{
    Q_UNUSED(idx);
    return 1;
}

bool MediaModel::hasChildren(const QModelIndex &parent) const
{
    return !parent.isValid();
}

bool MediaModel::canFetchMore(const QModelIndex &parent) const
{
    if (parent.isValid() || m_mediaType.isEmpty() || m_structure.isEmpty())
        return false;
    return !m_loading && !m_loaded;
}

void MediaModel::fetchMore(const QModelIndex &parent)
{
    if (!canFetchMore(parent))
        return;

    initialize();

    QSqlQuery q = query();
    DEBUG << q.lastQuery();

    m_loading = true;

    QMetaObject::invokeMethod(m_reader, "execute", Qt::QueuedConnection, Q_ARG(QSqlQuery, q));
}

void MediaModel::initialize()
{
    beginResetModel();

    m_data.clear();

    if (m_reader) {
        disconnect(m_reader, 0, this, 0);
        m_reader->stop();
        m_reader->deleteLater();
    }
    m_reader = new DbReader;

    if (!m_readerThread) {
        m_readerThread = new QThread(this);
        m_readerThread->start();
    }
    m_reader->moveToThread(m_readerThread);
    QMetaObject::invokeMethod(m_reader, "initialize", Q_ARG(QSqlDatabase, Backend::instance()->mediaDatabase()));
    connect(m_reader, SIGNAL(dataReady(DbReader *, QList<QSqlRecord>, void *)),
            this, SLOT(handleDataReady(DbReader *, QList<QSqlRecord>, void *)));

    m_loading = m_loaded = false;

    endResetModel();
}

void MediaModel::handleDataReady(DbReader *reader, const QList<QSqlRecord> &records, void *node)
{
    Q_ASSERT(reader == m_reader);
    Q_UNUSED(reader);
    Q_UNUSED(node);

    DEBUG << "Received response from db of size " << records.size();

    if (records.isEmpty())
        return;

    if (!m_cursor.isEmpty()) {
        beginInsertRows(QModelIndex(), 0, records.count());
        QHash<QString, QVariant> data;
        data.insert("display", tr(".."));
        data.insert("dotdot", true);
        data.insert("isLeaf", false);
        m_data.append(data);
    } else {
        beginInsertRows(QModelIndex(), 0, records.count() - 1);
    }

    const bool isLeaf = m_cursor.count() + 1 == m_structure.split("|").count();

    for (int i = 0; i < records.count(); i++) {
        QHash<QString, QVariant> data;
        for (int j = 0; j < records[i].count(); j++) {
            data.insert(records[i].fieldName(j), records[i].value(j));
        }

        QStringList cols = m_structure.split("|").value(m_cursor.count()).split(",");
        QStringList displayString;
        for (int j = 0; j < cols.count(); j++) {
            displayString << records[i].value(cols[j]).toString();
        }
        data.insert("display", displayString.join(", "));
        data.insert("dotdot", false);
        data.insert("isLeaf", isLeaf);

        m_data.append(data);

    }

    m_loading = false;
    m_loaded = true;

    endInsertRows();
}

void MediaModel::handleDatabaseUpdated(const QList<QSqlRecord> &records)
{
    Q_UNUSED(records);
    // not implemented yet
}

QSqlQuery MediaModel::query()
{
    QString q;
    QStringList parts = m_structure.split("|");
    QSqlDriver *driver = Backend::instance()->mediaDatabase().driver();
    QString curPart = parts[m_cursor.count()];
    QStringList curParts = curPart.split(",");
    QStringList escapedCurParts;
    for (int i = 0; i < curParts.count(); i++)
        escapedCurParts.append(driver->escapeIdentifier(curParts[i], QSqlDriver::FieldName));
    QString escapedCurPart = escapedCurParts.join(",");

    QSqlQuery query(Backend::instance()->mediaDatabase());
    query.setForwardOnly(true);

    QStringList placeHolders;
    const bool lastPart = m_cursor.count() == parts.count()-1;
    QString queryString = QString("SELECT %1 FROM %2 ").arg(lastPart ? "*" : escapedCurPart).arg(driver->escapeIdentifier(m_mediaType, QSqlDriver::TableName));

    if (!m_cursor.isEmpty()) {
        QStringList where;
        for (int i = 0; i < m_cursor.count(); i++) {
            QString part = parts[i];
            QStringList subParts = part.split(",");
            for (int j = 0; j < subParts.count(); j++) {
                where.append(subParts[j] + " = ?");
                placeHolders << m_cursor[i].value(subParts[j]).toString();
            }
        }

        queryString.append(QString("WHERE %1 ").arg(where.join(" AND ")));
    }

    if (!lastPart)
        queryString.append(QString("GROUP BY %1 ").arg(escapedCurPart));

    queryString.append(QString("ORDER BY %1").arg(escapedCurPart));

    query.prepare(queryString);

    foreach(const QString &placeHolder, placeHolders)
        query.addBindValue(placeHolder);

    return query;
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include <string>
#include "util/test.h"
#include "util/exception.h"
#include "util/sstream.h"
using namespace lean;

static void tst1() {
    try {
        throw exception(std::string("foo"));
    } catch (exception & ex) {
        lean_assert(std::string("foo") == ex.what());
    }
}

static void tst2() {
    try {
        throw parser_exception(std::string("foo"), 10, 100);
    } catch (parser_exception & ex) {
        lean_assert(std::string("(line: 10, pos: 100) foo") == ex.what());
    }
}

static void tst3() {
    try {
        throw parser_exception(sstream() << "msg " << 10 << " " << 20, 10, 100);
    } catch (parser_exception & ex) {
        lean_assert(std::string("(line: 10, pos: 100) msg 10 20") == ex.what());
    }
}

int main() {
    tst1();
    tst2();
    tst3();
    return has_violations() ? 1 : 0;
}
<commit_msg>test(exception): add tests for improving coverage<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Leonardo de Moura
*/
#include <string>
#include "util/test.h"
#include "util/exception.h"
#include "util/sstream.h"
using namespace lean;

static void tst1() {
    try {
        throw exception(std::string("foo"));
    } catch (exception & ex) {
        lean_assert(std::string("foo") == ex.what());
    }
}

static void tst2() {
    try {
        throw parser_exception(std::string("foo"), 10, 100);
    } catch (parser_exception & ex) {
        lean_assert(std::string("(line: 10, pos: 100) foo") == ex.what());
    }
}

static void tst3() {
    try {
        throw parser_exception(sstream() << "msg " << 10 << " " << 20, 10, 100);
    } catch (parser_exception & ex) {
        lean_assert(std::string("(line: 10, pos: 100) msg 10 20") == ex.what());
    }
}

static void tst4() {
    try {
        throw interrupted();
    } catch (exception & ex) {
        lean_assert(std::string("interrupted") == ex.what());
    }
}

int main() {
    tst1();
    tst2();
    tst3();
    tst4();
    return has_violations() ? 1 : 0;
}
<|endoftext|>


<commit_before>/*
  +----------------------------------------------------------------------+
  | Swoole                                                               |
  +----------------------------------------------------------------------+
  | This source file is subject to version 2.0 of the Apache license,    |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.apache.org/licenses/LICENSE-2.0.html                      |
  | If you did not receive a copy of the Apache2.0 license and are unable|
  | to obtain it through the world-wide-web, please send a note to       |
  | license@swoole.com so we can mail you a copy immediately.            |
  +----------------------------------------------------------------------+
  | Author: Tianfeng Han  <rango@swoole.com>                             |
  +----------------------------------------------------------------------+
*/

#include "swoole.h"
#include "swoole_memory.h"

namespace swoole {

struct FixedPoolSlice {
    uint8_t lock;
    FixedPoolSlice *next;
    FixedPoolSlice *prev;
    char data[0];
};

struct FixedPoolImpl {
    void *memory;
    size_t size;

    FixedPoolSlice *head;
    FixedPoolSlice *tail;

    // total memory size
    uint32_t slice_num;

    // memory usage
    uint32_t slice_use;

    // Fixed slice size, not include the memory used by FixedPoolSlice
    uint32_t slice_size;
    bool shared;
    bool allocated;

    void init();
};

/**
 * create new FixedPool, random alloc/free fixed size memory
 */
FixedPool::FixedPool(uint32_t slice_num, uint32_t slice_size, bool shared) {
    if (slice_num < 2) {
        throw Exception(SW_ERROR_INVALID_PARAMS);
    }
    slice_size = SW_MEM_ALIGNED_SIZE(slice_size);
    size_t size = slice_num * (sizeof(FixedPoolSlice) + slice_size);
    size_t alloc_size = size + sizeof(*impl);
    void *memory = shared ? ::sw_shm_malloc(alloc_size) : ::sw_malloc(alloc_size);
    if (!memory) {
        throw std::bad_alloc();
    }

    impl = (FixedPoolImpl *) memory;
    memory = (char *) memory + sizeof(*impl);
    sw_memset_zero(impl, sizeof(*impl));

    impl->shared = shared;
    impl->slice_num = slice_num;
    impl->slice_size = slice_size;
    impl->size = size;
    impl->memory = memory;
    impl->allocated = true;
    impl->init();
}

/**
 * create new FixedPool, Using the given memory
 */
FixedPool::FixedPool(uint32_t slice_size, void *memory, size_t size, bool shared) {
    impl = (FixedPoolImpl *) memory;
    memory = (char *) memory + sizeof(*impl);
    sw_memset_zero(impl, sizeof(*impl));
    impl->shared = shared;
    impl->slice_size = slice_size;
    impl->size = size - sizeof(*impl);
    uint32_t slice_num = impl->size / (slice_size + sizeof(FixedPoolSlice));
    if (slice_num < 2) {
        throw Exception(SW_ERROR_INVALID_PARAMS);
    }
    impl->slice_num = slice_num;
    impl->memory = memory;
    impl->allocated = false;
    impl->init();
}

size_t FixedPool::sizeof_struct_slice() {
    return sizeof(FixedPoolSlice);
}

size_t FixedPool::sizeof_struct_impl() {
    return sizeof(FixedPoolImpl);
}

/**
 * linked list
 */
void FixedPoolImpl::init() {
    FixedPoolSlice *slice;
    void *cur = memory;
    void *max = (char *) memory + size;
    do {
        slice = (FixedPoolSlice *) cur;
        sw_memset_zero(slice, sizeof(FixedPoolSlice));

        if (head != nullptr) {
            head->prev = slice;
            slice->next = head;
        } else {
            tail = slice;
        }

        head = slice;
        cur = (char *) cur + (sizeof(FixedPoolSlice) + slice_size);

        if (cur < max) {
            slice->prev = (FixedPoolSlice *) cur;
        } else {
            slice->prev = nullptr;
            break;
        }

    } while (1);
}

uint32_t FixedPool::get_number_of_spare_slice() {
    return impl->slice_num - impl->slice_use;
}

uint32_t FixedPool::get_number_of_total_slice() {
    return impl->slice_num;
}

uint32_t FixedPool::get_slice_size() {
    return impl->slice_size;
}

void *FixedPool::alloc(uint32_t size) {
    FixedPoolSlice *slice = impl->head;
    if (slice->lock) {
        swoole_set_last_error(SW_ERROR_MALLOC_FAIL);
        return nullptr;
    }

    slice->lock = 1;
    impl->slice_use++;

    // move next slice to head (idle list)
    impl->head = slice->next;
    impl->head->prev = nullptr;

    // move this slice to tail (busy list)
    impl->tail->next = slice;
    slice->next = nullptr;
    slice->prev = impl->tail;
    impl->tail = slice;

    return slice->data;
}

void FixedPool::free(void *ptr) {
    FixedPoolSlice *slice = (FixedPoolSlice *) ((char *) ptr - sizeof(FixedPoolSlice));

    assert(ptr > impl->memory && (char *) ptr < (char *) impl->memory + impl->size);
    assert(slice->lock == 1);

    impl->slice_use--;
    slice->lock = 0;

    if (slice == impl->head) {
        return;
    }

    if (slice == impl->tail) {
        slice->prev->next = nullptr;
        impl->tail = slice->prev;
    } else {
        slice->prev->next = slice->next;
        slice->next->prev = slice->prev;
    }

    // move slice to head (idle)
    slice->prev = nullptr;
    slice->next = impl->head;
    impl->head->prev = slice;
    impl->head = slice;
}

FixedPool::~FixedPool() {
    if (!impl->allocated) {
        return;
    }
    if (impl->shared) {
        ::sw_shm_free(impl);
    } else {
        ::sw_free(impl);
    }
}

void FixedPool::debug(int max_lines) {
    int line = 0;
    FixedPoolSlice *slice = impl->head;

    printf("===============================%s=================================\n", __FUNCTION__);
    while (slice != nullptr) {
        if (slice->next == slice) {
            printf("-------------------@@@@@@@@@@@@@@@@@@@@@@----------------\n");
        }

        printf("#%d\t", line);
        printf("slice[%p]\t", slice);
        printf("prev=%p\t", slice->prev);
        printf("next=%p\t", slice->next);
        printf("tag=%d\t", slice->lock);
        printf("data=%p\n", slice->data);

        slice = slice->next;
        if (line++ > max_lines) {
            break;
        }
    }
}

}  // namespace swoole
<commit_msg>Add assertion<commit_after>/*
  +----------------------------------------------------------------------+
  | Swoole                                                               |
  +----------------------------------------------------------------------+
  | This source file is subject to version 2.0 of the Apache license,    |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.apache.org/licenses/LICENSE-2.0.html                      |
  | If you did not receive a copy of the Apache2.0 license and are unable|
  | to obtain it through the world-wide-web, please send a note to       |
  | license@swoole.com so we can mail you a copy immediately.            |
  +----------------------------------------------------------------------+
  | Author: Tianfeng Han  <rango@swoole.com>                             |
  +----------------------------------------------------------------------+
*/

#include "swoole.h"
#include "swoole_memory.h"

namespace swoole {

struct FixedPoolSlice {
    uint8_t lock;
    FixedPoolSlice *next;
    FixedPoolSlice *prev;
    char data[0];
};

struct FixedPoolImpl {
    void *memory;
    size_t size;

    FixedPoolSlice *head;
    FixedPoolSlice *tail;

    // total memory size
    uint32_t slice_num;

    // memory usage
    uint32_t slice_use;

    // Fixed slice size, not include the memory used by FixedPoolSlice
    uint32_t slice_size;
    bool shared;
    bool allocated;

    void init();
};

/**
 * create new FixedPool, random alloc/free fixed size memory
 */
FixedPool::FixedPool(uint32_t slice_num, uint32_t slice_size, bool shared) {
    if (slice_num < 2) {
        throw Exception(SW_ERROR_INVALID_PARAMS);
    }
    slice_size = SW_MEM_ALIGNED_SIZE(slice_size);
    size_t size = slice_num * (sizeof(FixedPoolSlice) + slice_size);
    size_t alloc_size = size + sizeof(*impl);
    void *memory = shared ? ::sw_shm_malloc(alloc_size) : ::sw_malloc(alloc_size);
    if (!memory) {
        throw std::bad_alloc();
    }

    impl = (FixedPoolImpl *) memory;
    memory = (char *) memory + sizeof(*impl);
    sw_memset_zero(impl, sizeof(*impl));

    impl->shared = shared;
    impl->slice_num = slice_num;
    impl->slice_size = slice_size;
    impl->size = size;
    impl->memory = memory;
    impl->allocated = true;
    impl->init();
}

/**
 * create new FixedPool, Using the given memory
 */
FixedPool::FixedPool(uint32_t slice_size, void *memory, size_t size, bool shared) {
    impl = (FixedPoolImpl *) memory;
    memory = (char *) memory + sizeof(*impl);
    sw_memset_zero(impl, sizeof(*impl));
    impl->shared = shared;
    impl->slice_size = slice_size;
    impl->size = size - sizeof(*impl);
    uint32_t slice_num = impl->size / (slice_size + sizeof(FixedPoolSlice));
    if (slice_num < 2) {
        throw Exception(SW_ERROR_INVALID_PARAMS);
    }
    impl->slice_num = slice_num;
    impl->memory = memory;
    impl->allocated = false;
    impl->init();
}

size_t FixedPool::sizeof_struct_slice() {
    return sizeof(FixedPoolSlice);
}

size_t FixedPool::sizeof_struct_impl() {
    return sizeof(FixedPoolImpl);
}

/**
 * linked list
 */
void FixedPoolImpl::init() {
    FixedPoolSlice *slice;
    void *cur = memory;
    void *max = (char *) memory + size;
    do {
        slice = (FixedPoolSlice *) cur;
        sw_memset_zero(slice, sizeof(FixedPoolSlice));

        if (head != nullptr) {
            head->prev = slice;
            slice->next = head;
        } else {
            tail = slice;
        }

        head = slice;
        cur = (char *) cur + (sizeof(FixedPoolSlice) + slice_size);

        if (cur < max) {
            slice->prev = (FixedPoolSlice *) cur;
        } else {
            slice->prev = nullptr;
            break;
        }

    } while (1);
}

uint32_t FixedPool::get_number_of_spare_slice() {
    return impl->slice_num - impl->slice_use;
}

uint32_t FixedPool::get_number_of_total_slice() {
    return impl->slice_num;
}

uint32_t FixedPool::get_slice_size() {
    return impl->slice_size;
}

void *FixedPool::alloc(uint32_t size) {
    FixedPoolSlice *slice = impl->head;
    if (slice->lock) {
        swoole_set_last_error(SW_ERROR_MALLOC_FAIL);
        assert(get_number_of_spare_slice() == 0);
        return nullptr;
    }

    slice->lock = 1;
    impl->slice_use++;

    // move next slice to head (idle list)
    impl->head = slice->next;
    impl->head->prev = nullptr;

    // move this slice to tail (busy list)
    impl->tail->next = slice;
    slice->next = nullptr;
    slice->prev = impl->tail;
    impl->tail = slice;

    return slice->data;
}

void FixedPool::free(void *ptr) {
    FixedPoolSlice *slice = (FixedPoolSlice *) ((char *) ptr - sizeof(FixedPoolSlice));

    assert(ptr > impl->memory && (char *) ptr < (char *) impl->memory + impl->size);
    assert(slice->lock == 1);

    impl->slice_use--;
    slice->lock = 0;

    if (slice == impl->head) {
        return;
    }

    if (slice == impl->tail) {
        slice->prev->next = nullptr;
        impl->tail = slice->prev;
    } else {
        slice->prev->next = slice->next;
        slice->next->prev = slice->prev;
    }

    // move slice to head (idle)
    slice->prev = nullptr;
    slice->next = impl->head;
    impl->head->prev = slice;
    impl->head = slice;
}

FixedPool::~FixedPool() {
    if (!impl->allocated) {
        return;
    }
    if (impl->shared) {
        ::sw_shm_free(impl);
    } else {
        ::sw_free(impl);
    }
}

void FixedPool::debug(int max_lines) {
    int line = 0;
    FixedPoolSlice *slice = impl->head;

    printf("===============================%s=================================\n", __FUNCTION__);
    while (slice != nullptr) {
        if (slice->next == slice) {
            printf("-------------------@@@@@@@@@@@@@@@@@@@@@@----------------\n");
        }

        printf("#%d\t", line);
        printf("slice[%p]\t", slice);
        printf("prev=%p\t", slice->prev);
        printf("next=%p\t", slice->next);
        printf("tag=%d\t", slice->lock);
        printf("data=%p\n", slice->data);

        slice = slice->next;
        if (line++ > max_lines) {
            break;
        }
    }
}

}  // namespace swoole
<|endoftext|>


<commit_before>#include "orwell/com/Receiver.hpp"

//std
#include <iostream>
#include <unistd.h>

#include <zmq.hpp>

#include <sstream>

#include "orwell/support/GlobalLogger.hpp"
#include "orwell/com/RawMessage.hpp"

using std::string;

namespace orwell {
namespace com {

Receiver::Receiver(
		std::string const & iUrl,
		unsigned int const iSocketType,
		ConnectionMode const iConnectionMode,
		zmq::context_t & ioZmqContext,
		unsigned int const iSleep)
	: m_zmqSocket(new zmq::socket_t(ioZmqContext, iSocketType))
	, m_url(iUrl)
{
	int aLinger = 10; // linger 0.01 second max after being closed
	m_zmqSocket->setsockopt(ZMQ_LINGER, &aLinger, sizeof(aLinger));

	if (ZMQ_SUB == iSocketType)
	{
		string atag;
		m_zmqSocket->setsockopt(ZMQ_SUBSCRIBE, atag.c_str(), atag.size());
	}
	if (ConnectionMode::BIND == iConnectionMode)
	{
		m_zmqSocket->bind(iUrl.c_str());
		ORWELL_LOG_INFO("Puller binds on " << iUrl.c_str());
	}
	else
	{
		assert(ConnectionMode::CONNECT == iConnectionMode);
		m_zmqSocket->connect(iUrl.c_str());
		ORWELL_LOG_INFO("Subscriber connects to " << iUrl.c_str() << " - it subscribes to everything");
	}
	if (iSleep > 0)
	{
		sleep(iSleep);
	}
}

Receiver::Receiver(Receiver const & iOther)
{
}

Receiver::~Receiver()
{
	delete(m_zmqSocket);
}

bool Receiver::receiveString(
		std::string & oMessage,
		bool const iBlocking)
{
	zmq::message_t aZmqMessage;

	int aFlags = 0;
	if (not iBlocking)
	{
		aFlags = ZMQ_NOBLOCK;
	}
	bool const aReceived = m_zmqSocket->recv(&aZmqMessage, aFlags);
	if (aReceived)
	{
		ORWELL_LOG_DEBUG("message received");
		oMessage = string(static_cast<char*>(aZmqMessage.data()), aZmqMessage.size());
	}
	return aReceived;
}

bool Receiver::receive(RawMessage & oMessage)
{
	zmq::message_t aZmqMessage;
	string aType;
	string aPayload;
	string aDest;

	std::string aMessageData;
	bool const aReceived = receiveString(aMessageData);
	if (aReceived)
	{
		size_t aEndDestFlag = aMessageData.find( " ", 0 );
		if (string::npos != aEndDestFlag)
		{
			aDest = aMessageData.substr(0, aEndDestFlag);

			size_t aEndTypeFlag = aMessageData.find(" ", aEndDestFlag + 1);
			if ( aEndTypeFlag != string::npos )
			{
				aType = aMessageData.substr( aEndDestFlag + 1, aEndTypeFlag - aEndDestFlag - 1 );
				aPayload = aMessageData.substr( aEndTypeFlag + 1 );
			}
		}

		oMessage._type = aType;
		oMessage._routingId = aDest;
		oMessage._payload = aPayload;
		ORWELL_LOG_DEBUG("Received " << aZmqMessage.size() << " bytes : type=" << aType << "- dest=" << aDest << "-");
	}
	return aReceived;
}

std::string const & Receiver::getUrl() const
{
	return m_url;
}

}}

<commit_msg>Remove wrong message size in logs.<commit_after>#include "orwell/com/Receiver.hpp"

//std
#include <iostream>
#include <unistd.h>

#include <zmq.hpp>

#include <sstream>

#include "orwell/support/GlobalLogger.hpp"
#include "orwell/com/RawMessage.hpp"

using std::string;

namespace orwell
{
namespace com
{

Receiver::Receiver(
		std::string const & iUrl,
		unsigned int const iSocketType,
		ConnectionMode const iConnectionMode,
		zmq::context_t & ioZmqContext,
		unsigned int const iSleep)
	: m_zmqSocket(new zmq::socket_t(ioZmqContext, iSocketType))
	, m_url(iUrl)
{
	int aLinger = 10; // linger 0.01 second max after being closed
	m_zmqSocket->setsockopt(ZMQ_LINGER, &aLinger, sizeof(aLinger));

	if (ZMQ_SUB == iSocketType)
	{
		string atag;
		m_zmqSocket->setsockopt(ZMQ_SUBSCRIBE, atag.c_str(), atag.size());
	}
	if (ConnectionMode::BIND == iConnectionMode)
	{
		m_zmqSocket->bind(iUrl.c_str());
		ORWELL_LOG_INFO("Puller binds on " << iUrl.c_str());
	}
	else
	{
		assert(ConnectionMode::CONNECT == iConnectionMode);
		m_zmqSocket->connect(iUrl.c_str());
		ORWELL_LOG_INFO("Subscriber connects to " << iUrl.c_str() << " - it subscribes to everything");
	}
	if (iSleep > 0)
	{
		sleep(iSleep);
	}
}

Receiver::Receiver(Receiver const & iOther)
{
}

Receiver::~Receiver()
{
	delete(m_zmqSocket);
}

bool Receiver::receiveString(
		std::string & oMessage,
		bool const iBlocking)
{
	zmq::message_t aZmqMessage;

	int aFlags = 0;
	if (not iBlocking)
	{
		aFlags = ZMQ_NOBLOCK;
	}
	bool const aReceived = m_zmqSocket->recv(&aZmqMessage, aFlags);
	if (aReceived)
	{
		ORWELL_LOG_DEBUG("message received");
		oMessage = string(static_cast<char*>(aZmqMessage.data()), aZmqMessage.size());
	}
	return aReceived;
}

bool Receiver::receive(RawMessage & oMessage)
{
	string aType;
	string aPayload;
	string aDest;

	std::string aMessageData;
	bool const aReceived = receiveString(aMessageData);
	if (aReceived)
	{
		size_t aEndDestFlag = aMessageData.find( " ", 0 );
		if (string::npos != aEndDestFlag)
		{
			aDest = aMessageData.substr(0, aEndDestFlag);

			size_t aEndTypeFlag = aMessageData.find(" ", aEndDestFlag + 1);
			if ( aEndTypeFlag != string::npos )
			{
				aType = aMessageData.substr( aEndDestFlag + 1, aEndTypeFlag - aEndDestFlag - 1 );
				aPayload = aMessageData.substr( aEndTypeFlag + 1 );
			}
		}

		oMessage._type = aType;
		oMessage._routingId = aDest;
		oMessage._payload = aPayload;
		ORWELL_LOG_DEBUG("Received message : type=" << aType << "- dest=" << aDest << "-");
	}
	return aReceived;
}

std::string const & Receiver::getUrl() const
{
	return m_url;
}

}
}

<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>

#ifdef WIN32
    #define _WIN32_WINNT 0x0500
    #include <windows.h>
#endif

#if defined(__sgi)
    #include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
    #include <cctype>
    using std::tolower;
#endif

using namespace std;

std::string osgDB::getFilePath(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return std::string();
        return std::string(fileName,0,slash2);
    }
    if (slash2==std::string::npos) return std::string(fileName,0,slash1);
    return std::string(fileName, 0, slash1>slash2 ?  slash1 : slash2);
}

std::string osgDB::getSimpleFileName(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return fileName;
        return std::string(fileName.begin()+slash2+1,fileName.end());
    }
    if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
    return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}

std::string osgDB::getFileExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot+1,fileName.end());
}

std::string osgDB::getFileExtensionIncludingDot(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot,fileName.end());
}

std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
    {
        new_fileName[slash]='\\';
    }
    return new_fileName;
}

std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
    {
        new_fileName[slash]='/';
    }

    return new_fileName;
}

bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#if defined(WIN32) && !defined(__CYGWIN__)
    return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
    return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}

std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#if defined(WIN32) && !defined(__CYGWIN__)
    return convertFileNameToWindowsStyle(fileName);
#else
    return convertFileNameToUnixStyle(fileName);
#endif
}

std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
    return convertToLowerCase(osgDB::getFileExtension(filename));
}

std::string osgDB::convertToLowerCase(const std::string& str)
{
    std::string lowcase_str(str);
    for(std::string::iterator itr=lowcase_str.begin();
        itr!=lowcase_str.end();
        ++itr)
    {
        *itr = tolower(*itr);
    }
    return lowcase_str;
}

// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    std::string::size_type back_slash = fileName.find_last_of('\\');
    std::string::size_type slash = fileName.find_last_of('/');
    if (dot==std::string::npos || (dot<back_slash && dot<slash)) return fileName;
    return std::string(fileName.begin(),fileName.begin()+dot);
}

std::string osgDB::getStrippedName(const std::string& fileName)
{
    std::string simpleName = getSimpleFileName(fileName);
    return getNameLessExtension( simpleName );
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
    if (lhs.size()!=rhs.size()) return false;
    std::string::const_iterator litr = lhs.begin();
    std::string::const_iterator ritr = rhs.begin();
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*ritr)) return false;
        ++litr;
        ++ritr;
    }
    return true;
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
    if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
    std::string::const_iterator litr = lhs.begin();
    const char* cptr = rhs;
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*cptr)) return false;
        ++litr;
        ++cptr;
    }
    return true;
}

bool osgDB::containsServerAddress(const std::string& filename)
{
    // need to check for ://
    std::string::size_type pos(filename.find("://"));
    if (pos == std::string::npos)
        return false;
    std::string proto(filename.substr(0, pos));

    return Registry::instance()->isProtocolRegistered(proto);
}

std::string osgDB::getServerProtocol(const std::string& filename)
{
    std::string::size_type pos(filename.find("://"));
    if (pos != std::string::npos)
        return filename.substr(0,pos);

    return "";
}

std::string osgDB::getServerAddress(const std::string& filename)
{
    std::string::size_type pos(filename.find("://"));

    if (pos != std::string::npos)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',pos+3);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos+3,pos_slash-pos-3);
        }
        else
        {
            return filename.substr(pos+3,std::string::npos);
        }
    }
    return "";
}

std::string osgDB::getServerFileName(const std::string& filename)
{
    std::string::size_type pos(filename.find_first_of("://"));

    if (pos != std::string::npos)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',pos+3);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos_slash+1,std::string::npos);
        }
        else
        {
            return "";
        }

    }
    return filename;
}

std::string osgDB::concatPaths(const std::string& left, const std::string& right)
{
#if defined(WIN32) && !defined(__CYGWIN__)
    const char delimiterNative  = '\\';
    const char delimiterForeign = '/';
#else
    const char delimiterNative  = '/';
    const char delimiterForeign = '\\';
#endif

    if(left.empty())
    {
        return(right);
    }
    char lastChar = left[left.size() - 1];

    if(lastChar == delimiterNative)
    {
        return left + right;
    }
    else if(lastChar == delimiterForeign)
    {
        return left.substr(0, left.size() - 1) + delimiterNative + right;
    }
    else // lastChar != a delimiter
    {
        return left + delimiterNative + right;
    }
}

std::string osgDB::getRealPath(const std::string& path)
{
#if defined(WIN32)  && !defined(__CYGWIN__)
    // Not unicode compatible should give an error if UNICODE defined
    char retbuf[MAX_PATH + 1];
    char tempbuf1[MAX_PATH + 1];
    GetFullPathName(path.c_str(), sizeof(retbuf), retbuf, NULL);
    // Force drive letter to upper case
    if ((retbuf[1] == ':') && islower(retbuf[0]))
        retbuf[0] = _toupper(retbuf[0]);
    if (fileExists(std::string(retbuf)))
    {
        // Canonicalise the full path
        GetShortPathName(retbuf, tempbuf1, sizeof(tempbuf1));
        GetLongPathName(tempbuf1, retbuf, sizeof(retbuf));
        return std::string(retbuf);
    }
    else
    {
        // Canonicalise the directories
        std::string FilePath = getFilePath(retbuf);
        char tempbuf2[MAX_PATH + 1];
        if (0 == GetShortPathName(FilePath.c_str(), tempbuf1, sizeof(tempbuf1)))
            return std::string(retbuf);
        if (0 == GetLongPathName(tempbuf1, tempbuf2, sizeof(tempbuf2)))
            return std::string(retbuf);
        FilePath = std::string(tempbuf2);
        FilePath.append("\\");
        FilePath.append(getSimpleFileName(std::string(retbuf)));
        return FilePath;
    }
#else
    char resolved_path[PATH_MAX];
    char* result = realpath(path.c_str(), resolved_path);

    if (result) return std::string(resolved_path);
    else return path;
#endif
}
<commit_msg>Replaced find_first_of with find<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <limits.h>

#include <osgDB/FileNameUtils>
#include <osgDB/FileUtils>

#ifdef WIN32
    #define _WIN32_WINNT 0x0500
    #include <windows.h>
#endif

#if defined(__sgi)
    #include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
    #include <cctype>
    using std::tolower;
#endif

using namespace std;

std::string osgDB::getFilePath(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return std::string();
        return std::string(fileName,0,slash2);
    }
    if (slash2==std::string::npos) return std::string(fileName,0,slash1);
    return std::string(fileName, 0, slash1>slash2 ?  slash1 : slash2);
}

std::string osgDB::getSimpleFileName(const std::string& fileName)
{
    std::string::size_type slash1 = fileName.find_last_of('/');
    std::string::size_type slash2 = fileName.find_last_of('\\');
    if (slash1==std::string::npos)
    {
        if (slash2==std::string::npos) return fileName;
        return std::string(fileName.begin()+slash2+1,fileName.end());
    }
    if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
    return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}

std::string osgDB::getFileExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot+1,fileName.end());
}

std::string osgDB::getFileExtensionIncludingDot(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    if (dot==std::string::npos) return std::string("");
    return std::string(fileName.begin()+dot,fileName.end());
}

std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
    {
        new_fileName[slash]='\\';
    }
    return new_fileName;
}

std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
    std::string new_fileName(fileName);

    std::string::size_type slash = 0;
    while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
    {
        new_fileName[slash]='/';
    }

    return new_fileName;
}

bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#if defined(WIN32) && !defined(__CYGWIN__)
    return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
    return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}

std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#if defined(WIN32) && !defined(__CYGWIN__)
    return convertFileNameToWindowsStyle(fileName);
#else
    return convertFileNameToUnixStyle(fileName);
#endif
}

std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
    return convertToLowerCase(osgDB::getFileExtension(filename));
}

std::string osgDB::convertToLowerCase(const std::string& str)
{
    std::string lowcase_str(str);
    for(std::string::iterator itr=lowcase_str.begin();
        itr!=lowcase_str.end();
        ++itr)
    {
        *itr = tolower(*itr);
    }
    return lowcase_str;
}

// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
    std::string::size_type dot = fileName.find_last_of('.');
    std::string::size_type back_slash = fileName.find_last_of('\\');
    std::string::size_type slash = fileName.find_last_of('/');
    if (dot==std::string::npos || (dot<back_slash && dot<slash)) return fileName;
    return std::string(fileName.begin(),fileName.begin()+dot);
}

std::string osgDB::getStrippedName(const std::string& fileName)
{
    std::string simpleName = getSimpleFileName(fileName);
    return getNameLessExtension( simpleName );
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
    if (lhs.size()!=rhs.size()) return false;
    std::string::const_iterator litr = lhs.begin();
    std::string::const_iterator ritr = rhs.begin();
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*ritr)) return false;
        ++litr;
        ++ritr;
    }
    return true;
}

bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
    if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
    std::string::const_iterator litr = lhs.begin();
    const char* cptr = rhs;
    while (litr!=lhs.end())
    {
        if (tolower(*litr)!=tolower(*cptr)) return false;
        ++litr;
        ++cptr;
    }
    return true;
}

bool osgDB::containsServerAddress(const std::string& filename)
{
    // need to check for ://
    std::string::size_type pos(filename.find("://"));
    if (pos == std::string::npos)
        return false;
    std::string proto(filename.substr(0, pos));

    return Registry::instance()->isProtocolRegistered(proto);
}

std::string osgDB::getServerProtocol(const std::string& filename)
{
    std::string::size_type pos(filename.find("://"));
    if (pos != std::string::npos)
        return filename.substr(0,pos);

    return "";
}

std::string osgDB::getServerAddress(const std::string& filename)
{
    std::string::size_type pos(filename.find("://"));

    if (pos != std::string::npos)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',pos+3);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos+3,pos_slash-pos-3);
        }
        else
        {
            return filename.substr(pos+3,std::string::npos);
        }
    }
    return "";
}

std::string osgDB::getServerFileName(const std::string& filename)
{
    std::string::size_type pos(filename.find("://"));

    if (pos != std::string::npos)
    {
        std::string::size_type pos_slash = filename.find_first_of('/',pos+3);
        if (pos_slash!=std::string::npos)
        {
            return filename.substr(pos_slash+1,std::string::npos);
        }
        else
        {
            return "";
        }

    }
    return filename;
}

std::string osgDB::concatPaths(const std::string& left, const std::string& right)
{
#if defined(WIN32) && !defined(__CYGWIN__)
    const char delimiterNative  = '\\';
    const char delimiterForeign = '/';
#else
    const char delimiterNative  = '/';
    const char delimiterForeign = '\\';
#endif

    if(left.empty())
    {
        return(right);
    }
    char lastChar = left[left.size() - 1];

    if(lastChar == delimiterNative)
    {
        return left + right;
    }
    else if(lastChar == delimiterForeign)
    {
        return left.substr(0, left.size() - 1) + delimiterNative + right;
    }
    else // lastChar != a delimiter
    {
        return left + delimiterNative + right;
    }
}

std::string osgDB::getRealPath(const std::string& path)
{
#if defined(WIN32)  && !defined(__CYGWIN__)
    // Not unicode compatible should give an error if UNICODE defined
    char retbuf[MAX_PATH + 1];
    char tempbuf1[MAX_PATH + 1];
    GetFullPathName(path.c_str(), sizeof(retbuf), retbuf, NULL);
    // Force drive letter to upper case
    if ((retbuf[1] == ':') && islower(retbuf[0]))
        retbuf[0] = _toupper(retbuf[0]);
    if (fileExists(std::string(retbuf)))
    {
        // Canonicalise the full path
        GetShortPathName(retbuf, tempbuf1, sizeof(tempbuf1));
        GetLongPathName(tempbuf1, retbuf, sizeof(retbuf));
        return std::string(retbuf);
    }
    else
    {
        // Canonicalise the directories
        std::string FilePath = getFilePath(retbuf);
        char tempbuf2[MAX_PATH + 1];
        if (0 == GetShortPathName(FilePath.c_str(), tempbuf1, sizeof(tempbuf1)))
            return std::string(retbuf);
        if (0 == GetLongPathName(tempbuf1, tempbuf2, sizeof(tempbuf2)))
            return std::string(retbuf);
        FilePath = std::string(tempbuf2);
        FilePath.append("\\");
        FilePath.append(getSimpleFileName(std::string(retbuf)));
        return FilePath;
    }
#else
    char resolved_path[PATH_MAX];
    char* result = realpath(path.c_str(), resolved_path);

    if (result) return std::string(resolved_path);
    else return path;
#endif
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/lib/syscall_time.C $                                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2010,2014              */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <time.h>
#include <sys/time.h>
#include <sys/syscall.h>
#include <errno.h>
#include <kernel/timemgr.H>

using namespace Systemcalls;

void nanosleep(uint64_t sec, uint64_t nsec)
{
    // If the delay is short then simpleDelay() will perform the delay
    if(unlikely(!TimeManager::simpleDelay(sec, nsec)))
    {
        _syscall2(TIME_NANOSLEEP, (void*)sec, (void*)nsec);
    }
}

int clock_gettime(clockid_t clk_id, timespec_t* tp)
{
    if (unlikely(NULL == tp)) { return -EFAULT; }

    int rc = 0;

    switch(clk_id)
    {
        case CLOCK_REALTIME: // TODO: Need a message to the FSP to get the
                             //       real-time.
            rc = -EINVAL;
            break;

        case CLOCK_MONOTONIC:
            TimeManager::convertTicksToSec(getTB(), tp->tv_sec, tp->tv_nsec);
            break;

        default:
            rc = -EINVAL;
            break;
    }

    return rc;
}
<commit_msg>Handle overruns in nanosleep<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/lib/syscall_time.C $                                      */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2010,2018                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <time.h>
#include <sys/time.h>
#include <sys/syscall.h>
#include <errno.h>
#include <kernel/timemgr.H>
#include <kernel/console.H>
#include <sys/task.h>

using namespace Systemcalls;

void nanosleep(uint64_t i_sec, uint64_t i_nsec)
{
    uint64_t l_sec = i_sec + i_nsec/NS_PER_SEC;
    uint64_t l_nsec = i_nsec%NS_PER_SEC;
    // If the delay is short then simpleDelay() will perform the delay
    if(unlikely(!TimeManager::simpleDelay(l_sec, l_nsec)))
    {
        _syscall2(TIME_NANOSLEEP, (void*)l_sec, (void*)l_nsec);
    }
}

int clock_gettime(clockid_t clk_id, timespec_t* tp)
{
    if (unlikely(NULL == tp)) { return -EFAULT; }

    int rc = 0;

    switch(clk_id)
    {
        case CLOCK_REALTIME: // TODO: Need a message to the FSP to get the
                             //       real-time.
            rc = -EINVAL;
            break;

        case CLOCK_MONOTONIC:
            TimeManager::convertTicksToSec(getTB(), tp->tv_sec, tp->tv_nsec);
            break;

        default:
            rc = -EINVAL;
            break;
    }

    return rc;
}
<|endoftext|>