<commit_before>#pragma once
#include <experimental/optional>
#include <sdbusplus/server.hpp>

#include "types.hpp"

namespace ipmi
{

constexpr auto MAPPER_BUS_NAME = "xyz.openbmc_project.ObjectMapper";
constexpr auto MAPPER_OBJ = "/xyz/openbmc_project/object_mapper";
constexpr auto MAPPER_INTF = "xyz.openbmc_project.ObjectMapper";

constexpr auto ROOT = "/";
constexpr auto HOST_MATCH = "host0";

constexpr auto PROP_INTF = "org.freedesktop.DBus.Properties";
constexpr auto DELETE_INTERFACE = "xyz.openbmc_project.Object.Delete";

constexpr auto METHOD_GET = "Get";
constexpr auto METHOD_GET_ALL = "GetAll";
constexpr auto METHOD_SET = "Set";

/** @class ServiceCache
 *  @brief Caches lookups of service names from the object mapper.
 *  @details Most ipmi commands need to talk to other dbus daemons to perform
 *           their intended actions on the BMC. This usually means they will
 *           first look up the service name providing the interface they
 *           require. This class reduces the number of such calls by caching
 *           the lookup for a specific service.
 */
class ServiceCache {
    public:
        /** @brief Creates a new service cache for the given interface
         *         and path.
         *
         *  @param[in] intf - The interface used for each lookup
         *  @param[in] path - The path used for each lookup
         */
        ServiceCache(const std::string& intf, const std::string& path);
        ServiceCache(std::string&& intf, std::string&& path);

        /** @brief Gets the service name from the cache or does in a
         *         lookup when invalid.
         *
         *  @param[in] bus - The bus associated with and used for looking
         *                   up the service.
         */
        const std::string& getService(sdbusplus::bus::bus& bus);

        /** @brief Invalidates the current service name */
        void invalidate();

        /** @brief A wrapper around sdbusplus bus.new_method_call
         *
         *  @param[in] bus - The bus used for calling the method
         *  @param[in] intf - The interface containing the method
         *  @param[in] method - The method name
         *  @return The message containing the method call.
         */
        sdbusplus::message::message newMethodCall(sdbusplus::bus::bus& bus,
                                                  const char *intf,
                                                  const char *method);
    private:
        /** @brief DBUS interface provided by the service */
        const std::string intf;
        /** @brief DBUS path provided by the service */
        const std::string path;
        /** @brief The name of the service if valid */
        std::experimental::optional<std::string> cachedService;
        /** @brief The name of the bus used in the service lookup */
        std::experimental::optional<std::string> cachedBusName;

        /** @brief Check to see if the current cache is valid
         *
         * @param[in] bus - The bus used for the service lookup
         * @return True if the cache is valid false otherwise.
         */
        bool isValid(sdbusplus::bus::bus& bus) const;
};

/**
 * @brief Get the DBUS Service name for the input dbus path
 *
 * @param[in] bus - DBUS Bus Object
 * @param[in] intf - DBUS Interface
 * @param[in] path - DBUS Object Path
 *
 */
std::string getService(sdbusplus::bus::bus& bus,
                       const std::string& intf,
                       const std::string& path);

/** @brief Gets the dbus object info implementing the given interface
 *         from the given subtree.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] interface - Dbus interface.
 *  @param[in] subtreePath - subtree from where the search should start.
 *  @param[in] match - identifier for object.
 *  @return On success returns the object having objectpath and servicename.
 */
DbusObjectInfo getDbusObject(sdbusplus::bus::bus& bus,
                             const std::string& interface,
                             const std::string& subtreePath = ROOT,
                             const std::string& match = {});

/** @brief Get the ipObject of first dbus IP object of Non-LinkLocalIPAddress
 *         type from the given subtree, if not available gets IP object of
 *         LinkLocalIPAddress type.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] interface - Dbus interface.
 *  @param[in] subtreePath - subtree from where the search should start.
 *  @param[in] match - identifier for object.
 *  @return On success returns the object having objectpath and servicename.
 */
DbusObjectInfo getIPObject(sdbusplus::bus::bus& bus,
                           const std::string& interface,
                           const std::string& subtreePath,
                           const std::string& match);

/** @brief Gets the value associated with the given object
 *         and the interface.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] property - name of the property.
 *  @return On success returns the value of the property.
 */
Value getDbusProperty(sdbusplus::bus::bus& bus,
                      const std::string& service,
                      const std::string& objPath,
                      const std::string& interface,
                      const std::string& property);

/** @brief Gets all the properties associated with the given object
 *         and the interface.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @return On success returns the map of name value pair.
 */
PropertyMap getAllDbusProperties(sdbusplus::bus::bus& bus,
                                 const std::string& service,
                                 const std::string& objPath,
                                 const std::string& interface);

/** @brief Gets all managed objects associated with the given object
 *         path and service.
 *  @param[in] bus - D-Bus Bus Object.
 *  @param[in] service - D-Bus service name.
 *  @param[in] objPath - D-Bus object path.
 *  @return On success returns the map of name value pair.
 */
ObjectValueTree getManagedObjects(sdbusplus::bus::bus& bus,
                                 const std::string& service,
                                 const std::string& objPath);

/** @brief Sets the property value of the given object.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] property - name of the property.
 *  @param[in] value - value which needs to be set.
 */
void setDbusProperty(sdbusplus::bus::bus& bus,
                     const std::string& service,
                     const std::string& objPath,
                     const std::string& interface,
                     const std::string& property,
                     const Value& value);

/** @brief  Gets all the dbus objects from the given service root
 *          which matches the object identifier.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] serviceRoot - Service root path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] match - Identifier for a path.
 *  @returns map of object path and service info.
 */
ObjectTree getAllDbusObjects(sdbusplus::bus::bus& bus,
                             const std::string& serviceRoot,
                             const std::string& interface,
                             const std::string& match);

/** @brief Deletes all the dbus objects from the given service root
           which matches the object identifier.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] serviceRoot - Service root path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] match - Identifier for object.
 */
void deleteAllDbusObjects(sdbusplus::bus::bus& bus,
                          const std::string& serviceRoot,
                          const std::string& interface,
                          const std::string& match = {});

/** @brief Gets the ancestor objects of the given object
           which implements the given interface.
 *  @param[in] bus - Dbus bus object.
 *  @param[in] path - Child Dbus object path.
 *  @param[in] interfaces - Dbus interface list.
 *  @return map of object path and service info.
 */
ObjectTree getAllAncestors(sdbusplus::bus::bus& bus,
                           const std::string& path,
                           InterfaceList&& interfaces);

namespace method_no_args
{

/** @brief Calls the Dbus method which waits for response.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] method - Dbus method.
 */
void callDbusMethod(sdbusplus::bus::bus& bus,
                    const std::string& service,
                    const std::string& objPath,
                    const std::string& interface,
                    const std::string& method);

} //namespace method_no_args

namespace network
{

constexpr auto ROOT = "/xyz/openbmc_project/network";
constexpr auto SERVICE = "xyz.openbmc_project.Network";
constexpr auto IP_TYPE = "ipv4";
constexpr auto IPV4_PREFIX = "169.254";
constexpr auto IPV6_PREFIX = "fe80";
constexpr auto IP_INTERFACE = "xyz.openbmc_project.Network.IP";
constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress";
constexpr auto SYSTEMCONFIG_INTERFACE = "xyz.openbmc_project.Network.SystemConfiguration";
constexpr auto ETHERNET_INTERFACE = "xyz.openbmc_project.Network.EthernetInterface";
constexpr auto IP_CREATE_INTERFACE = "xyz.openbmc_project.Network.IP.Create";
constexpr auto VLAN_CREATE_INTERFACE = "xyz.openbmc_project.Network.VLAN.Create";
constexpr auto VLAN_INTERFACE = "xyz.openbmc_project.Network.VLAN";

/* @brief converts the given subnet into prefix notation.
 * @param[in] addressFamily - IP address family(AF_INET/AF_INET6).
 * @param[in] mask - Subnet Mask.
 * @returns prefix.
 */
uint8_t toPrefix(int addressFamily, const std::string& subnetMask);

/** @brief Sets the ip on the system.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] protocolType - Protocol type
 *  @param[in] ipaddress - IPaddress.
 *  @param[in] prefix - Prefix length.
 */
void createIP(sdbusplus::bus::bus& bus,
              const std::string& service,
              const std::string& objPath,
              const std::string& protocolType,
              const std::string& ipaddress,
              uint8_t prefix);

/** @brief Creates the VLAN on the given interface.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - EthernetInterface.
 *  @param[in] vlanID - Vlan ID.
 */
void createVLAN(sdbusplus::bus::bus& bus,
                const std::string& service,
                const std::string& objPath,
                const std::string& interface,
                uint32_t vlanID);

/** @brief Gets the vlan id from the given object path.
 *  @param[in] path - Dbus object path.
 */
uint32_t getVLAN(const std::string& path);

} //namespace network
} // namespace ipmi

<commit_msg>utils/ServiceCache: Make isValid public<commit_after>#pragma once
#include <experimental/optional>
#include <sdbusplus/server.hpp>

#include "types.hpp"

namespace ipmi
{

constexpr auto MAPPER_BUS_NAME = "xyz.openbmc_project.ObjectMapper";
constexpr auto MAPPER_OBJ = "/xyz/openbmc_project/object_mapper";
constexpr auto MAPPER_INTF = "xyz.openbmc_project.ObjectMapper";

constexpr auto ROOT = "/";
constexpr auto HOST_MATCH = "host0";

constexpr auto PROP_INTF = "org.freedesktop.DBus.Properties";
constexpr auto DELETE_INTERFACE = "xyz.openbmc_project.Object.Delete";

constexpr auto METHOD_GET = "Get";
constexpr auto METHOD_GET_ALL = "GetAll";
constexpr auto METHOD_SET = "Set";

/** @class ServiceCache
 *  @brief Caches lookups of service names from the object mapper.
 *  @details Most ipmi commands need to talk to other dbus daemons to perform
 *           their intended actions on the BMC. This usually means they will
 *           first look up the service name providing the interface they
 *           require. This class reduces the number of such calls by caching
 *           the lookup for a specific service.
 */
class ServiceCache {
    public:
        /** @brief Creates a new service cache for the given interface
         *         and path.
         *
         *  @param[in] intf - The interface used for each lookup
         *  @param[in] path - The path used for each lookup
         */
        ServiceCache(const std::string& intf, const std::string& path);
        ServiceCache(std::string&& intf, std::string&& path);

        /** @brief Gets the service name from the cache or does in a
         *         lookup when invalid.
         *
         *  @param[in] bus - The bus associated with and used for looking
         *                   up the service.
         */
        const std::string& getService(sdbusplus::bus::bus& bus);

        /** @brief Invalidates the current service name */
        void invalidate();

        /** @brief A wrapper around sdbusplus bus.new_method_call
         *
         *  @param[in] bus - The bus used for calling the method
         *  @param[in] intf - The interface containing the method
         *  @param[in] method - The method name
         *  @return The message containing the method call.
         */
        sdbusplus::message::message newMethodCall(sdbusplus::bus::bus& bus,
                                                  const char *intf,
                                                  const char *method);

        /** @brief Check to see if the current cache is valid
         *
         * @param[in] bus - The bus used for the service lookup
         * @return True if the cache is valid false otherwise.
         */
        bool isValid(sdbusplus::bus::bus& bus) const;
    private:
        /** @brief DBUS interface provided by the service */
        const std::string intf;
        /** @brief DBUS path provided by the service */
        const std::string path;
        /** @brief The name of the service if valid */
        std::experimental::optional<std::string> cachedService;
        /** @brief The name of the bus used in the service lookup */
        std::experimental::optional<std::string> cachedBusName;
};

/**
 * @brief Get the DBUS Service name for the input dbus path
 *
 * @param[in] bus - DBUS Bus Object
 * @param[in] intf - DBUS Interface
 * @param[in] path - DBUS Object Path
 *
 */
std::string getService(sdbusplus::bus::bus& bus,
                       const std::string& intf,
                       const std::string& path);

/** @brief Gets the dbus object info implementing the given interface
 *         from the given subtree.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] interface - Dbus interface.
 *  @param[in] subtreePath - subtree from where the search should start.
 *  @param[in] match - identifier for object.
 *  @return On success returns the object having objectpath and servicename.
 */
DbusObjectInfo getDbusObject(sdbusplus::bus::bus& bus,
                             const std::string& interface,
                             const std::string& subtreePath = ROOT,
                             const std::string& match = {});

/** @brief Get the ipObject of first dbus IP object of Non-LinkLocalIPAddress
 *         type from the given subtree, if not available gets IP object of
 *         LinkLocalIPAddress type.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] interface - Dbus interface.
 *  @param[in] subtreePath - subtree from where the search should start.
 *  @param[in] match - identifier for object.
 *  @return On success returns the object having objectpath and servicename.
 */
DbusObjectInfo getIPObject(sdbusplus::bus::bus& bus,
                           const std::string& interface,
                           const std::string& subtreePath,
                           const std::string& match);

/** @brief Gets the value associated with the given object
 *         and the interface.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] property - name of the property.
 *  @return On success returns the value of the property.
 */
Value getDbusProperty(sdbusplus::bus::bus& bus,
                      const std::string& service,
                      const std::string& objPath,
                      const std::string& interface,
                      const std::string& property);

/** @brief Gets all the properties associated with the given object
 *         and the interface.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @return On success returns the map of name value pair.
 */
PropertyMap getAllDbusProperties(sdbusplus::bus::bus& bus,
                                 const std::string& service,
                                 const std::string& objPath,
                                 const std::string& interface);

/** @brief Gets all managed objects associated with the given object
 *         path and service.
 *  @param[in] bus - D-Bus Bus Object.
 *  @param[in] service - D-Bus service name.
 *  @param[in] objPath - D-Bus object path.
 *  @return On success returns the map of name value pair.
 */
ObjectValueTree getManagedObjects(sdbusplus::bus::bus& bus,
                                 const std::string& service,
                                 const std::string& objPath);

/** @brief Sets the property value of the given object.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] property - name of the property.
 *  @param[in] value - value which needs to be set.
 */
void setDbusProperty(sdbusplus::bus::bus& bus,
                     const std::string& service,
                     const std::string& objPath,
                     const std::string& interface,
                     const std::string& property,
                     const Value& value);

/** @brief  Gets all the dbus objects from the given service root
 *          which matches the object identifier.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] serviceRoot - Service root path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] match - Identifier for a path.
 *  @returns map of object path and service info.
 */
ObjectTree getAllDbusObjects(sdbusplus::bus::bus& bus,
                             const std::string& serviceRoot,
                             const std::string& interface,
                             const std::string& match);

/** @brief Deletes all the dbus objects from the given service root
           which matches the object identifier.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] serviceRoot - Service root path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] match - Identifier for object.
 */
void deleteAllDbusObjects(sdbusplus::bus::bus& bus,
                          const std::string& serviceRoot,
                          const std::string& interface,
                          const std::string& match = {});

/** @brief Gets the ancestor objects of the given object
           which implements the given interface.
 *  @param[in] bus - Dbus bus object.
 *  @param[in] path - Child Dbus object path.
 *  @param[in] interfaces - Dbus interface list.
 *  @return map of object path and service info.
 */
ObjectTree getAllAncestors(sdbusplus::bus::bus& bus,
                           const std::string& path,
                           InterfaceList&& interfaces);

namespace method_no_args
{

/** @brief Calls the Dbus method which waits for response.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - Dbus interface.
 *  @param[in] method - Dbus method.
 */
void callDbusMethod(sdbusplus::bus::bus& bus,
                    const std::string& service,
                    const std::string& objPath,
                    const std::string& interface,
                    const std::string& method);

} //namespace method_no_args

namespace network
{

constexpr auto ROOT = "/xyz/openbmc_project/network";
constexpr auto SERVICE = "xyz.openbmc_project.Network";
constexpr auto IP_TYPE = "ipv4";
constexpr auto IPV4_PREFIX = "169.254";
constexpr auto IPV6_PREFIX = "fe80";
constexpr auto IP_INTERFACE = "xyz.openbmc_project.Network.IP";
constexpr auto MAC_INTERFACE = "xyz.openbmc_project.Network.MACAddress";
constexpr auto SYSTEMCONFIG_INTERFACE = "xyz.openbmc_project.Network.SystemConfiguration";
constexpr auto ETHERNET_INTERFACE = "xyz.openbmc_project.Network.EthernetInterface";
constexpr auto IP_CREATE_INTERFACE = "xyz.openbmc_project.Network.IP.Create";
constexpr auto VLAN_CREATE_INTERFACE = "xyz.openbmc_project.Network.VLAN.Create";
constexpr auto VLAN_INTERFACE = "xyz.openbmc_project.Network.VLAN";

/* @brief converts the given subnet into prefix notation.
 * @param[in] addressFamily - IP address family(AF_INET/AF_INET6).
 * @param[in] mask - Subnet Mask.
 * @returns prefix.
 */
uint8_t toPrefix(int addressFamily, const std::string& subnetMask);

/** @brief Sets the ip on the system.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] protocolType - Protocol type
 *  @param[in] ipaddress - IPaddress.
 *  @param[in] prefix - Prefix length.
 */
void createIP(sdbusplus::bus::bus& bus,
              const std::string& service,
              const std::string& objPath,
              const std::string& protocolType,
              const std::string& ipaddress,
              uint8_t prefix);

/** @brief Creates the VLAN on the given interface.
 *  @param[in] bus - DBUS Bus Object.
 *  @param[in] service - Dbus service name.
 *  @param[in] objPath - Dbus object path.
 *  @param[in] interface - EthernetInterface.
 *  @param[in] vlanID - Vlan ID.
 */
void createVLAN(sdbusplus::bus::bus& bus,
                const std::string& service,
                const std::string& objPath,
                const std::string& interface,
                uint32_t vlanID);

/** @brief Gets the vlan id from the given object path.
 *  @param[in] path - Dbus object path.
 */
uint32_t getVLAN(const std::string& path);

} //namespace network
} // namespace ipmi

<|endoftext|>


<commit_before>#include "Graph.h"

Graph::Graph()
{
    //ctor
}

Graph::~Graph()
{
    //dtor
}
<commit_msg>Delete Graph.cpp<commit_after><|endoftext|>


<commit_before>#include <QString>
#include <typeinfo>
#include "kernel.h"
#include "range.h"
#include "domainitem.h"
#include "itemrange.h"
#include "identifieritem.h"
#include "identifierrange.h"

using namespace Ilwis;

IndexedIdentifierRange::IndexedIdentifierRange() : _count(0)
{
}

bool IndexedIdentifierRange::contains(const QString& item ) const{
    if (_start->prefix() != "") {
        if ( _start->prefix() != item.left(_start->prefix().size()))
            return false;
    }
    int index = item.indexOf("_");
    if ( index != -1) {
        QString num = item.mid(index);
        bool ok;
        quint32 itemIndex = num.toULong(&ok);
        return ok && itemIndex < _count;
    }
    return false;
}

bool IndexedIdentifierRange::isValid() const{
    return _count != 0;
}

bool IndexedIdentifierRange::operator==(const IndexedIdentifierRange& range){
    return _start == range._start;
}

QString IndexedIdentifierRange::value(quint32 index) const{
    return _start->name(index);
}
quint32 IndexedIdentifierRange::count() const{
    return _count;
}

void IndexedIdentifierRange::count(quint32 nr)
{
    _count = nr;
}

SPDomainItem IndexedIdentifierRange::item(const QString& nam) const{
    return SPDomainItem();
}

Range *IndexedIdentifierRange::clone() const
{
    IndexedIdentifierRange *irange = new IndexedIdentifierRange();
    irange->_count = _count;
    irange->add(_start.data());

    return irange;

}

SPDomainItem IndexedIdentifierRange::item(quint32 index) const{
    if ( index >= _count)
        return SPDomainItem();
    return SPDomainItem( new IndexedIdentifier(_start->prefix(), index));
}

void IndexedIdentifierRange::add(DomainItem *thing)
{
    if (!thing->isValid())
        return;

    IndexedIdentifier *ii = dynamic_cast<IndexedIdentifier *>(thing);
    _start = SPIndexedIdentifier(ii);
    _count = ii->_count;

    return;
}

QString IndexedIdentifierRange::toString() const
{
    QString res;
    for(quint32 i=_start->index(); i < _start->index() + _count; ++i) {
        if ( res!= "")
            res = res +  ",";
        if ( _start->prefix() != "")
            res += _start->prefix() + "_";
        res += QString::number(i);
    }
    return res;
}

void IndexedIdentifierRange::remove(const QString& item)
{
}

//-------------------------------------------------------------------------
NamedIdentifierRange::NamedIdentifierRange()
{
}

NamedIdentifierRange::~NamedIdentifierRange()
{
}

bool NamedIdentifierRange::contains(const QString& name) const
{
    if ( name == "" || name == "?")
        return false;

    SPDomainItem it = item(name);
    return it && it->isValid();
}

bool NamedIdentifierRange::isValid() const
{
    return _items.size() != 0;
}

void NamedIdentifierRange::add(DomainItem *thing)
{
    if (!thing)
        return ;

    if (!thing->isValid()) {
        delete thing;
        return;
    }

    if ( item(thing->name()) != 0) {
        delete thing;
        return ;
    }

    SPNamedIdentifier nid(static_cast<NamedIdentifier *>(thing));
    _items[thing->name()] = nid;
    _indexes.push_back(nid);

    return ;
}

bool NamedIdentifierRange::operator==(const ItemRange &range) const
{
    if ( _items.count() != range.count())
        return false;

    for(int i = 0; i < _indexes.count(); ++i) {
        if (!contains(range.item(i)->name()))
            return false;
    }

    return true;
}

void NamedIdentifierRange::remove(const QString &name)
{
    SPDomainItem it = item(name);
    if (!it)
        return ;

    _items.remove(name);
    int ind = _indexes.indexOf(it.dynamicCast<NamedIdentifier>());
    _indexes.remove(ind);

    return ;
}

QString NamedIdentifierRange::value(quint32 index) const
{
    SPNamedIdentifier it = item(index).dynamicCast<NamedIdentifier>();
    if (!it)
        return sUNDEF;

    return it->name();
}

SPDomainItem NamedIdentifierRange::item(quint32 index) const {
    if ( index <= 0 || index >= count())
        return SPDomainItem();

    return _indexes[index];
}

SPDomainItem NamedIdentifierRange::item(const QString& nam) const{
    auto iter = _items.find(nam);
    if (iter != _items.end())
        return iter.value();

    return SPDomainItem();
}

quint32 NamedIdentifierRange::count() const
{
    return _items.size();
}

Range *NamedIdentifierRange::clone() const
{
    NamedIdentifierRange *nir = new NamedIdentifierRange();
    for(const auto &iter: _items) {
        nir->add( (*iter).clone());
    }
    return nir;
}

NamedIdentifierRange &NamedIdentifierRange::operator <<(const QString &item)
{
   this->add(new NamedIdentifier(item));

    return *this;
}

QString NamedIdentifierRange::toString() const {
    QString res;
    foreach(SPNamedIdentifier item, _indexes) {
        if (res!= "")
            res += ",";
        res += item->name();
    }
    return res;
}

<commit_msg>items should of course add a clone and not the pointer itself ( causes crash of course due to double deletes)<commit_after>#include <QString>
#include <typeinfo>
#include "kernel.h"
#include "range.h"
#include "domainitem.h"
#include "itemrange.h"
#include "identifieritem.h"
#include "identifierrange.h"

using namespace Ilwis;

IndexedIdentifierRange::IndexedIdentifierRange() : _count(0)
{
}

bool IndexedIdentifierRange::contains(const QString& item ) const{
    if (_start->prefix() != "") {
        if ( _start->prefix() != item.left(_start->prefix().size()))
            return false;
    }
    int index = item.indexOf("_");
    if ( index != -1) {
        QString num = item.mid(index);
        bool ok;
        quint32 itemIndex = num.toULong(&ok);
        return ok && itemIndex < _count;
    }
    return false;
}

bool IndexedIdentifierRange::isValid() const{
    return _count != 0;
}

bool IndexedIdentifierRange::operator==(const IndexedIdentifierRange& range){
    return _start == range._start;
}

QString IndexedIdentifierRange::value(quint32 index) const{
    return _start->name(index);
}
quint32 IndexedIdentifierRange::count() const{
    return _count;
}

void IndexedIdentifierRange::count(quint32 nr)
{
    _count = nr;
}

SPDomainItem IndexedIdentifierRange::item(const QString& nam) const{
    return SPDomainItem();
}

Range *IndexedIdentifierRange::clone() const
{
    IndexedIdentifierRange *irange = new IndexedIdentifierRange();
    irange->_count = _count;
    irange->add(_start->clone());

    return irange;

}

SPDomainItem IndexedIdentifierRange::item(quint32 index) const{
    if ( index >= _count)
        return SPDomainItem();
    return SPDomainItem( new IndexedIdentifier(_start->prefix(), index));
}

void IndexedIdentifierRange::add(DomainItem *thing)
{
    if (!thing->isValid())
        return;

    IndexedIdentifier *ii = dynamic_cast<IndexedIdentifier *>(thing);
    _start = SPIndexedIdentifier(ii);
    _count = ii->_count;

    return;
}

QString IndexedIdentifierRange::toString() const
{
    QString res;
    for(quint32 i=_start->index(); i < _start->index() + _count; ++i) {
        if ( res!= "")
            res = res +  ",";
        if ( _start->prefix() != "")
            res += _start->prefix() + "_";
        res += QString::number(i);
    }
    return res;
}

void IndexedIdentifierRange::remove(const QString& item)
{
}

//-------------------------------------------------------------------------
NamedIdentifierRange::NamedIdentifierRange()
{
}

NamedIdentifierRange::~NamedIdentifierRange()
{
}

bool NamedIdentifierRange::contains(const QString& name) const
{
    if ( name == "" || name == "?")
        return false;

    SPDomainItem it = item(name);
    return it && it->isValid();
}

bool NamedIdentifierRange::isValid() const
{
    return _items.size() != 0;
}

void NamedIdentifierRange::add(DomainItem *thing)
{
    if (!thing)
        return ;

    if (!thing->isValid()) {
        delete thing;
        return;
    }

    if ( item(thing->name()) != 0) {
        delete thing;
        return ;
    }

    SPNamedIdentifier nid(static_cast<NamedIdentifier *>(thing));
    _items[thing->name()] = nid;
    _indexes.push_back(nid);

    return ;
}

bool NamedIdentifierRange::operator==(const ItemRange &range) const
{
    if ( _items.count() != range.count())
        return false;

    for(int i = 0; i < _indexes.count(); ++i) {
        if (!contains(range.item(i)->name()))
            return false;
    }

    return true;
}

void NamedIdentifierRange::remove(const QString &name)
{
    SPDomainItem it = item(name);
    if (!it)
        return ;

    _items.remove(name);
    int ind = _indexes.indexOf(it.dynamicCast<NamedIdentifier>());
    _indexes.remove(ind);

    return ;
}

QString NamedIdentifierRange::value(quint32 index) const
{
    SPNamedIdentifier it = item(index).dynamicCast<NamedIdentifier>();
    if (!it)
        return sUNDEF;

    return it->name();
}

SPDomainItem NamedIdentifierRange::item(quint32 index) const {
    if ( index <= 0 || index >= count())
        return SPDomainItem();

    return _indexes[index];
}

SPDomainItem NamedIdentifierRange::item(const QString& nam) const{
    auto iter = _items.find(nam);
    if (iter != _items.end())
        return iter.value();

    return SPDomainItem();
}

quint32 NamedIdentifierRange::count() const
{
    return _items.size();
}

Range *NamedIdentifierRange::clone() const
{
    NamedIdentifierRange *nir = new NamedIdentifierRange();
    for(const auto &iter: _items) {
        nir->add( (*iter).clone());
    }
    return nir;
}

NamedIdentifierRange &NamedIdentifierRange::operator <<(const QString &item)
{
   this->add(new NamedIdentifier(item));

    return *this;
}

QString NamedIdentifierRange::toString() const {
    QString res;
    foreach(SPNamedIdentifier item, _indexes) {
        if (res!= "")
            res += ",";
        res += item->name();
    }
    return res;
}

<|endoftext|>


<commit_before>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: xiaofeng@google.com (Feng Xiao)

#include <google/protobuf/compiler/java/java_shared_code_generator.h>

#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif

#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>

namespace google {
namespace protobuf {
namespace compiler {
namespace java {

SharedCodeGenerator::SharedCodeGenerator(const FileDescriptor* file,
                                         const Options& options)
    : name_resolver_(new ClassNameResolver), file_(file), options_(options) {}

SharedCodeGenerator::~SharedCodeGenerator() {
}

void SharedCodeGenerator::Generate(GeneratorContext* context,
                                   std::vector<string>* file_list,
                                   std::vector<string>* annotation_file_list) {
  string java_package = FileJavaPackage(file_);
  string package_dir = JavaPackageToDir(java_package);

  if (HasDescriptorMethods(file_, options_.enforce_lite)) {
    // Generate descriptors.
    string classname = name_resolver_->GetDescriptorClassName(file_);
    string filename = package_dir + classname + ".java";
    file_list->push_back(filename);
    google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
    GeneratedCodeInfo annotations;
    io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
        &annotations);
    google::protobuf::scoped_ptr<io::Printer> printer(
        new io::Printer(output.get(), '$',
                        options_.annotate_code ? &annotation_collector : NULL));
    string info_relative_path = classname + ".java.pb.meta";
    string info_full_path = filename + ".pb.meta";
    printer->Print(
        "// Generated by the protocol buffer compiler.  DO NOT EDIT!\n"
        "// source: $filename$\n"
        "\n",
        "filename", file_->name());
    if (!java_package.empty()) {
      printer->Print(
        "package $package$;\n"
        "\n",
        "package", java_package);
    }
    PrintGeneratedAnnotation(printer.get(), '$',
                             options_.annotate_code ? info_relative_path : "");
    printer->Print(
        "public final class $classname$ {\n"
        "  public static com.google.protobuf.Descriptors.FileDescriptor\n"
        "      descriptor;\n"
        "  static {\n",
        "classname", classname);
    printer->Annotate("classname", file_->name());
    printer->Indent();
    printer->Indent();
    GenerateDescriptors(printer.get());
    printer->Outdent();
    printer->Outdent();
    printer->Print(
      "  }\n"
      "}\n");

    if (options_.annotate_code) {
      google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
          context->Open(info_full_path));
      annotations.SerializeToZeroCopyStream(info_output.get());
      annotation_file_list->push_back(info_full_path);
    }

    printer.reset();
    output.reset();
  }
}

void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
  // Embed the descriptor.  We simply serialize the entire FileDescriptorProto
  // and embed it as a string literal, which is parsed and built into real
  // descriptors at initialization time.  We unfortunately have to put it in
  // a string literal, not a byte array, because apparently using a literal
  // byte array causes the Java compiler to generate *instructions* to
  // initialize each and every byte of the array, e.g. as if you typed:
  //   b[0] = 123; b[1] = 456; b[2] = 789;
  // This makes huge bytecode files and can easily hit the compiler's internal
  // code size limits (error "code to large").  String literals are apparently
  // embedded raw, which is what we want.
  FileDescriptorProto file_proto;
  file_->CopyTo(&file_proto);

  string file_data;
  file_proto.SerializeToString(&file_data);

  printer->Print(
    "java.lang.String[] descriptorData = {\n");
  printer->Indent();

  // Only write 40 bytes per line.
  static const int kBytesPerLine = 40;
  for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
    if (i > 0) {
      // Every 400 lines, start a new string literal, in order to avoid the
      // 64k length limit.
      if (i % 400 == 0) {
        printer->Print(",\n");
      } else {
        printer->Print(" +\n");
      }
    }
    printer->Print("\"$data$\"",
      "data", CEscape(file_data.substr(i, kBytesPerLine)));
  }

  printer->Outdent();
  printer->Print("\n};\n");

  // -----------------------------------------------------------------
  // Create the InternalDescriptorAssigner.

  printer->Print(
    "com.google.protobuf.Descriptors.FileDescriptor."
    "InternalDescriptorAssigner assigner =\n"
    "    new com.google.protobuf.Descriptors.FileDescriptor."
    "    InternalDescriptorAssigner() {\n"
    "      public com.google.protobuf.ExtensionRegistry assignDescriptors(\n"
    "          com.google.protobuf.Descriptors.FileDescriptor root) {\n"
    "        descriptor = root;\n"
    // Custom options will be handled when immutable messages' outer class is
    // loaded. Here we just return null and let custom options be unknown
    // fields.
    "        return null;\n"
    "      }\n"
    "    };\n");

  // -----------------------------------------------------------------
  // Find out all dependencies.
  std::vector<std::pair<string, string> > dependencies;
  for (int i = 0; i < file_->dependency_count(); i++) {
    string filename = file_->dependency(i)->name();
    string classname = FileJavaPackage(file_->dependency(i)) + "." +
                       name_resolver_->GetDescriptorClassName(
                           file_->dependency(i));
    dependencies.push_back(std::make_pair(filename, classname));
  }

  // -----------------------------------------------------------------
  // Invoke internalBuildGeneratedFileFrom() to build the file.
  printer->Print(
    "com.google.protobuf.Descriptors.FileDescriptor\n"
    "  .internalBuildGeneratedFileFrom(descriptorData,\n");
  printer->Print(
    "    new com.google.protobuf.Descriptors.FileDescriptor[] {\n");

  for (int i = 0; i < dependencies.size(); i++) {
    const string& dependency = dependencies[i].second;
    printer->Print(
        "      $dependency$.getDescriptor(),\n",
        "dependency", dependency);
  }

  printer->Print(
    "    }, assigner);\n");
}

}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google
<commit_msg>Ensure that for Java, imports of .proto files with empty packages works<commit_after>// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Author: xiaofeng@google.com (Feng Xiao)

#include <google/protobuf/compiler/java/java_shared_code_generator.h>

#include <memory>
#ifndef _SHARED_PTR_H
#include <google/protobuf/stubs/shared_ptr.h>
#endif

#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/stubs/strutil.h>

namespace google {
namespace protobuf {
namespace compiler {
namespace java {

SharedCodeGenerator::SharedCodeGenerator(const FileDescriptor* file,
                                         const Options& options)
    : name_resolver_(new ClassNameResolver), file_(file), options_(options) {}

SharedCodeGenerator::~SharedCodeGenerator() {
}

void SharedCodeGenerator::Generate(GeneratorContext* context,
                                   std::vector<string>* file_list,
                                   std::vector<string>* annotation_file_list) {
  string java_package = FileJavaPackage(file_);
  string package_dir = JavaPackageToDir(java_package);

  if (HasDescriptorMethods(file_, options_.enforce_lite)) {
    // Generate descriptors.
    string classname = name_resolver_->GetDescriptorClassName(file_);
    string filename = package_dir + classname + ".java";
    file_list->push_back(filename);
    google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> output(context->Open(filename));
    GeneratedCodeInfo annotations;
    io::AnnotationProtoCollector<GeneratedCodeInfo> annotation_collector(
        &annotations);
    google::protobuf::scoped_ptr<io::Printer> printer(
        new io::Printer(output.get(), '$',
                        options_.annotate_code ? &annotation_collector : NULL));
    string info_relative_path = classname + ".java.pb.meta";
    string info_full_path = filename + ".pb.meta";
    printer->Print(
        "// Generated by the protocol buffer compiler.  DO NOT EDIT!\n"
        "// source: $filename$\n"
        "\n",
        "filename", file_->name());
    if (!java_package.empty()) {
      printer->Print(
        "package $package$;\n"
        "\n",
        "package", java_package);
    }
    PrintGeneratedAnnotation(printer.get(), '$',
                             options_.annotate_code ? info_relative_path : "");
    printer->Print(
        "public final class $classname$ {\n"
        "  public static com.google.protobuf.Descriptors.FileDescriptor\n"
        "      descriptor;\n"
        "  static {\n",
        "classname", classname);
    printer->Annotate("classname", file_->name());
    printer->Indent();
    printer->Indent();
    GenerateDescriptors(printer.get());
    printer->Outdent();
    printer->Outdent();
    printer->Print(
      "  }\n"
      "}\n");

    if (options_.annotate_code) {
      google::protobuf::scoped_ptr<io::ZeroCopyOutputStream> info_output(
          context->Open(info_full_path));
      annotations.SerializeToZeroCopyStream(info_output.get());
      annotation_file_list->push_back(info_full_path);
    }

    printer.reset();
    output.reset();
  }
}

void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) {
  // Embed the descriptor.  We simply serialize the entire FileDescriptorProto
  // and embed it as a string literal, which is parsed and built into real
  // descriptors at initialization time.  We unfortunately have to put it in
  // a string literal, not a byte array, because apparently using a literal
  // byte array causes the Java compiler to generate *instructions* to
  // initialize each and every byte of the array, e.g. as if you typed:
  //   b[0] = 123; b[1] = 456; b[2] = 789;
  // This makes huge bytecode files and can easily hit the compiler's internal
  // code size limits (error "code to large").  String literals are apparently
  // embedded raw, which is what we want.
  FileDescriptorProto file_proto;
  file_->CopyTo(&file_proto);

  string file_data;
  file_proto.SerializeToString(&file_data);

  printer->Print(
    "java.lang.String[] descriptorData = {\n");
  printer->Indent();

  // Only write 40 bytes per line.
  static const int kBytesPerLine = 40;
  for (int i = 0; i < file_data.size(); i += kBytesPerLine) {
    if (i > 0) {
      // Every 400 lines, start a new string literal, in order to avoid the
      // 64k length limit.
      if (i % 400 == 0) {
        printer->Print(",\n");
      } else {
        printer->Print(" +\n");
      }
    }
    printer->Print("\"$data$\"",
      "data", CEscape(file_data.substr(i, kBytesPerLine)));
  }

  printer->Outdent();
  printer->Print("\n};\n");

  // -----------------------------------------------------------------
  // Create the InternalDescriptorAssigner.

  printer->Print(
    "com.google.protobuf.Descriptors.FileDescriptor."
    "InternalDescriptorAssigner assigner =\n"
    "    new com.google.protobuf.Descriptors.FileDescriptor."
    "    InternalDescriptorAssigner() {\n"
    "      public com.google.protobuf.ExtensionRegistry assignDescriptors(\n"
    "          com.google.protobuf.Descriptors.FileDescriptor root) {\n"
    "        descriptor = root;\n"
    // Custom options will be handled when immutable messages' outer class is
    // loaded. Here we just return null and let custom options be unknown
    // fields.
    "        return null;\n"
    "      }\n"
    "    };\n");

  // -----------------------------------------------------------------
  // Find out all dependencies.
  std::vector<std::pair<string, string> > dependencies;
  for (int i = 0; i < file_->dependency_count(); i++) {
    string filename = file_->dependency(i)->name();
    string package = FileJavaPackage(file_->dependency(i));
    string classname = name_resolver_->GetDescriptorClassName(
        file_->dependency(i));
    string full_name;
    if (package.empty()) {
      full_name = classname;
    } else {
      full_name = package + "." + classname;
    }
    dependencies.push_back(std::make_pair(filename, full_name));
  }

  // -----------------------------------------------------------------
  // Invoke internalBuildGeneratedFileFrom() to build the file.
  printer->Print(
    "com.google.protobuf.Descriptors.FileDescriptor\n"
    "  .internalBuildGeneratedFileFrom(descriptorData,\n");
  printer->Print(
    "    new com.google.protobuf.Descriptors.FileDescriptor[] {\n");

  for (int i = 0; i < dependencies.size(); i++) {
    const string& dependency = dependencies[i].second;
    printer->Print(
        "      $dependency$.getDescriptor(),\n",
        "dependency", dependency);
  }

  printer->Print(
    "    }, assigner);\n");
}

}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google
<|endoftext|>


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

#ifndef __FRAMEWORK_HELPER_TIMERHELPER_HXX_
#include <helper/timerhelper.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//........................................................................
namespace framework
{
//........................................................................

    //====================================================================
    //= OTimerHelper
    //====================================================================
    //--------------------------------------------------------------------
    OTimerHelper::OTimerHelper( const ::vos::TTimeValue& _rExpireTime  )
        : ThreadHelpBase ( &Application::GetSolarMutex()    )
        , OTimer         ( _rExpireTime                     )
    {
    }

    //--------------------------------------------------------------------
    void SAL_CALL OTimerHelper::onShot()
    {
        ResetableGuard aGuard( m_aLock );
        if( m_pListener != NULL )
        {
            m_pListener->timerExpired();
        }
    }

//........................................................................
}   // namespace framework
//........................................................................

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

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

#ifndef __FRAMEWORK_HELPER_TIMERHELPER_HXX_
#include <helper/timerhelper.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//........................................................................
namespace framework
{
//........................................................................

    //====================================================================
    //= OTimerHelper
    //====================================================================
    //--------------------------------------------------------------------
    OTimerHelper::OTimerHelper( const ::vos::TTimeValue& _rExpireTime  )
        : ThreadHelpBase ( &Application::GetSolarMutex()    )
        , OTimer         ( _rExpireTime                     )
    {
    }

    //--------------------------------------------------------------------
    void SAL_CALL OTimerHelper::onShot()
    {
        ResetableGuard aGuard( m_aLock );
        if( m_pListener != NULL )
        {
            m_pListener->timerExpired();
        }
    }

//........................................................................
}   // namespace framework
//........................................................................

<|endoftext|>


<commit_before>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include <rapicorn.hh>

namespace {
using namespace Rapicorn;

static void
add_button_row (ContainerH area, uint row)
{
  WidgetH child = area.create_child ("RapicornExamples:button-row", Strings ("id=row#" + string_from_uint (row)));
  ContainerH brow = ContainerH::down_cast (child);
  for (uint i = 0; i < 50; i++)
    {
      Strings args = Strings ("test-button-text=\"(" + string_from_uint (row) + "," + string_from_uint (i) + ")\"");
      child = brow.create_child ("RapicornExamples:test-button", args);
      ButtonAreaH button = child.component<ButtonAreaH> (".Button");
      button.on_click (string_printf ("Widget::print('Button-Click: (%d,%d)')", row, i));
    }
}

extern "C" int
main (int   argc,
      char *argv[])
{
  // initialize Rapicorn
  ApplicationH app = init_app (__PRETTY_FILE__, &argc, argv);

  // find and load GUI definitions relative to argv[0]
  app.auto_load ("RapicornExamples", "scroller.xml", argv[0]);

  // create main window
  WindowH window = app.create_window ("RapicornExamples:main-shell");

  // create button rows
  ContainerH mshell = window;
  for (uint i = 0; i < 50; i++)
    add_button_row (mshell, i);

  // show main window
  window.show();

  // run event loops while windows are on screen
  return app.run_and_exit();
}

} // anon
<commit_msg>EXAMPLES: use string_format() instead of printf-variants<commit_after>// Licensed GNU LGPL v3 or later: http://www.gnu.org/licenses/lgpl.html
#include <rapicorn.hh>

namespace {
using namespace Rapicorn;

static void
add_button_row (ContainerH area, uint row)
{
  WidgetH child = area.create_child ("RapicornExamples:button-row", Strings ("id=row#" + string_from_uint (row)));
  ContainerH brow = ContainerH::down_cast (child);
  for (uint i = 0; i < 50; i++)
    {
      Strings args = Strings ("test-button-text=\"(" + string_from_uint (row) + "," + string_from_uint (i) + ")\"");
      child = brow.create_child ("RapicornExamples:test-button", args);
      ButtonAreaH button = child.component<ButtonAreaH> (".Button");
      button.on_click (string_format ("Widget::print('Button-Click: (%d,%d)')", row, i));
    }
}

extern "C" int
main (int   argc,
      char *argv[])
{
  // initialize Rapicorn
  ApplicationH app = init_app (__PRETTY_FILE__, &argc, argv);

  // find and load GUI definitions relative to argv[0]
  app.auto_load ("RapicornExamples", "scroller.xml", argv[0]);

  // create main window
  WindowH window = app.create_window ("RapicornExamples:main-shell");

  // create button rows
  ContainerH mshell = window;
  for (uint i = 0; i < 50; i++)
    add_button_row (mshell, i);

  // show main window
  window.show();

  // run event loops while windows are on screen
  return app.run_and_exit();
}

} // anon
<|endoftext|>


<commit_before>// Copyright 2019 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

#include "iree/base/api.h"
#include "iree/hal/api.h"
#include "iree/hal/cts/cts_test_base.h"
#include "iree/hal/testing/driver_registry.h"
#include "iree/testing/gtest.h"
#include "iree/testing/status_matchers.h"

// TODO(scotttodd): split into several tests, for example:
//     command_buffer_recording_test (recording/lifetime)
//     command_buffer_dispatch_test
//     command_buffer_fill_test (filling buffers)
//     command_buffer_e2e_test (barriers, dispatches)

namespace iree {
namespace hal {
namespace cts {

using ::testing::ContainerEq;

class CommandBufferTest : public CtsTestBase {
 public:
  CommandBufferTest() {
    // TODO(#4680): command buffer recording so that this can run on sync HAL.
    SkipUnavailableDriver("dylib-sync");
    SkipUnavailableDriver("vmvx-sync");
  }

 protected:
  static constexpr iree_device_size_t kBufferSize = 4096;
};

TEST_P(CommandBufferTest, Create) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_DISPATCH, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  EXPECT_TRUE((iree_hal_command_buffer_allowed_categories(command_buffer) &
               IREE_HAL_COMMAND_CATEGORY_DISPATCH) ==
              IREE_HAL_COMMAND_CATEGORY_DISPATCH);

  iree_hal_command_buffer_release(command_buffer);
}

TEST_P(CommandBufferTest, BeginEnd) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_DISPATCH, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  iree_hal_command_buffer_release(command_buffer);
}

TEST_P(CommandBufferTest, SubmitEmpty) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_DISPATCH, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_DISPATCH,
                                            command_buffer));

  iree_hal_command_buffer_release(command_buffer);
}

TEST_P(CommandBufferTest, FillBufferWithRepeatedBytes) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_TRANSFER, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  iree_hal_buffer_t* device_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL | IREE_HAL_MEMORY_TYPE_HOST_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &device_buffer));

  std::vector<uint8_t> reference_buffer(kBufferSize);

  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));

  // Fill the device buffer with segments of different values so that we can
  // test both fill and offset/size.
  uint8_t val1 = 0x07;
  IREE_ASSERT_OK(iree_hal_command_buffer_fill_buffer(
      command_buffer, device_buffer,
      /*target_offset=*/0, /*length=*/kBufferSize / 4, /*pattern=*/&val1,
      /*pattern_length=*/sizeof(val1)));
  std::memset(reference_buffer.data(), val1, kBufferSize / 4);

  uint8_t val2 = 0xbe;
  IREE_ASSERT_OK(
      iree_hal_command_buffer_fill_buffer(command_buffer, device_buffer,
                                          /*target_offset=*/kBufferSize / 4,
                                          /*length=*/kBufferSize / 4,
                                          /*pattern=*/&val2,
                                          /*pattern_length=*/sizeof(val2)));
  std::memset(reference_buffer.data() + kBufferSize / 4, val2, kBufferSize / 4);

  uint8_t val3 = 0x54;
  IREE_ASSERT_OK(
      iree_hal_command_buffer_fill_buffer(command_buffer, device_buffer,
                                          /*target_offset=*/kBufferSize / 2,
                                          /*length=*/kBufferSize / 2,
                                          /*pattern=*/&val3,
                                          /*pattern_length=*/sizeof(val3)));
  std::memset(reference_buffer.data() + kBufferSize / 2, val3, kBufferSize / 2);

  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_TRANSFER,
                                            command_buffer));

  // Read the device buffer and compare.
  std::vector<uint8_t> actual_data(kBufferSize);
  IREE_ASSERT_OK(iree_hal_buffer_read_data(device_buffer, /*source_offset=*/0,
                                           /*target_buffer=*/actual_data.data(),
                                           /*data_length=*/kBufferSize));
  EXPECT_THAT(actual_data, ContainerEq(reference_buffer));

  // Must release the command buffer before resources used by it.
  iree_hal_command_buffer_release(command_buffer);
  iree_hal_buffer_release(device_buffer);
}

TEST_P(CommandBufferTest, CopyWholeBuffer) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_TRANSFER, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  // Create and fill a host buffer.
  iree_hal_buffer_t* host_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_HOST_VISIBLE | IREE_HAL_MEMORY_TYPE_HOST_CACHED |
          IREE_HAL_MEMORY_TYPE_DEVICE_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &host_buffer));
  uint8_t i8_val = 0x54;
  IREE_ASSERT_OK(iree_hal_buffer_fill(host_buffer, /*byte_offset=*/0,
                                      /*byte_length=*/kBufferSize, &i8_val,
                                      /*pattern_length=*/sizeof(i8_val)));
  std::vector<uint8_t> reference_buffer(kBufferSize);
  std::memset(reference_buffer.data(), i8_val, kBufferSize);

  // Create a device buffer.
  iree_hal_buffer_t* device_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL | IREE_HAL_MEMORY_TYPE_HOST_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &device_buffer));

  // Copy the host buffer to the device buffer.
  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_copy_buffer(
      command_buffer, /*source_buffer=*/host_buffer, /*source_offset=*/0,
      /*target_buffer=*/device_buffer, /*target_offset=*/0,
      /*length=*/kBufferSize));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_TRANSFER,
                                            command_buffer));

  // Read the device buffer and compare.
  std::vector<uint8_t> actual_data(kBufferSize);
  IREE_ASSERT_OK(iree_hal_buffer_read_data(device_buffer, /*source_offset=*/0,
                                           /*target_buffer=*/actual_data.data(),
                                           /*data_length=*/kBufferSize));
  EXPECT_THAT(actual_data, ContainerEq(reference_buffer));

  // Must release the command buffer before resources used by it.
  iree_hal_command_buffer_release(command_buffer);
  iree_hal_buffer_release(device_buffer);
  iree_hal_buffer_release(host_buffer);
}

TEST_P(CommandBufferTest, CopySubBuffer) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_TRANSFER, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  iree_hal_buffer_t* device_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL | IREE_HAL_MEMORY_TYPE_HOST_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &device_buffer));

  // Create another host buffer with a smaller size.
  iree_hal_buffer_t* host_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_HOST_VISIBLE | IREE_HAL_MEMORY_TYPE_HOST_CACHED |
          IREE_HAL_MEMORY_TYPE_DEVICE_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize / 2, &host_buffer));

  // Fill the host buffer.
  uint8_t i8_val = 0x88;
  IREE_ASSERT_OK(iree_hal_buffer_fill(host_buffer, /*byte_offset=*/0,
                                      /*byte_length=*/kBufferSize / 2, &i8_val,
                                      /*pattern_length=*/sizeof(i8_val)));
  std::vector<uint8_t> reference_buffer(kBufferSize);
  std::memset(reference_buffer.data() + 8, i8_val, kBufferSize / 2 - 4);

  // Copy the host buffer to the device buffer; zero fill the untouched bytes.
  uint8_t zero_val = 0x0;
  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_fill_buffer(
      command_buffer, device_buffer, /*target_offset=*/0, /*length=*/8,
      &zero_val, /*pattern_length=*/sizeof(zero_val)));
  IREE_ASSERT_OK(iree_hal_command_buffer_copy_buffer(
      command_buffer, /*source_buffer=*/host_buffer, /*source_offset=*/4,
      /*target_buffer=*/device_buffer, /*target_offset=*/8,
      /*length=*/kBufferSize / 2 - 4));
  IREE_ASSERT_OK(iree_hal_command_buffer_fill_buffer(
      command_buffer, device_buffer, /*target_offset=*/8 + kBufferSize / 2 - 4,
      /*length=*/IREE_WHOLE_BUFFER, &zero_val,
      /*pattern_length=*/sizeof(zero_val)));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_TRANSFER,
                                            command_buffer));

  // Read the device buffer and compare.
  std::vector<uint8_t> actual_data(kBufferSize);
  IREE_ASSERT_OK(iree_hal_buffer_read_data(device_buffer, /*source_offset=*/0,
                                           /*target_buffer=*/actual_data.data(),
                                           /*data_length=*/kBufferSize));
  EXPECT_THAT(actual_data, ContainerEq(reference_buffer));

  // Must release the command buffer before resources used by it.
  iree_hal_command_buffer_release(command_buffer);
  iree_hal_buffer_release(device_buffer);
  iree_hal_buffer_release(host_buffer);
}

INSTANTIATE_TEST_SUITE_P(
    AllDrivers, CommandBufferTest,
    ::testing::ValuesIn(testing::EnumerateAvailableDrivers()),
    GenerateTestName());

}  // namespace cts
}  // namespace hal
}  // namespace iree
<commit_msg>Use explicit buffer length in CopySubBuffer test (#7241)<commit_after>// Copyright 2019 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

#include <cstdint>
#include <cstring>
#include <string>
#include <vector>

#include "iree/base/api.h"
#include "iree/hal/api.h"
#include "iree/hal/cts/cts_test_base.h"
#include "iree/hal/testing/driver_registry.h"
#include "iree/testing/gtest.h"
#include "iree/testing/status_matchers.h"

// TODO(scotttodd): split into several tests, for example:
//     command_buffer_recording_test (recording/lifetime)
//     command_buffer_dispatch_test
//     command_buffer_fill_test (filling buffers)
//     command_buffer_e2e_test (barriers, dispatches)

namespace iree {
namespace hal {
namespace cts {

using ::testing::ContainerEq;

class CommandBufferTest : public CtsTestBase {
 public:
  CommandBufferTest() {
    // TODO(#4680): command buffer recording so that this can run on sync HAL.
    SkipUnavailableDriver("dylib-sync");
    SkipUnavailableDriver("vmvx-sync");
  }

 protected:
  static constexpr iree_device_size_t kBufferSize = 4096;
};

TEST_P(CommandBufferTest, Create) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_DISPATCH, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  EXPECT_TRUE((iree_hal_command_buffer_allowed_categories(command_buffer) &
               IREE_HAL_COMMAND_CATEGORY_DISPATCH) ==
              IREE_HAL_COMMAND_CATEGORY_DISPATCH);

  iree_hal_command_buffer_release(command_buffer);
}

TEST_P(CommandBufferTest, BeginEnd) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_DISPATCH, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  iree_hal_command_buffer_release(command_buffer);
}

TEST_P(CommandBufferTest, SubmitEmpty) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_DISPATCH, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_DISPATCH,
                                            command_buffer));

  iree_hal_command_buffer_release(command_buffer);
}

TEST_P(CommandBufferTest, FillBufferWithRepeatedBytes) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_TRANSFER, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  iree_hal_buffer_t* device_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL | IREE_HAL_MEMORY_TYPE_HOST_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &device_buffer));

  std::vector<uint8_t> reference_buffer(kBufferSize);

  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));

  // Fill the device buffer with segments of different values so that we can
  // test both fill and offset/size.
  uint8_t val1 = 0x07;
  IREE_ASSERT_OK(iree_hal_command_buffer_fill_buffer(
      command_buffer, device_buffer,
      /*target_offset=*/0, /*length=*/kBufferSize / 4, /*pattern=*/&val1,
      /*pattern_length=*/sizeof(val1)));
  std::memset(reference_buffer.data(), val1, kBufferSize / 4);

  uint8_t val2 = 0xbe;
  IREE_ASSERT_OK(
      iree_hal_command_buffer_fill_buffer(command_buffer, device_buffer,
                                          /*target_offset=*/kBufferSize / 4,
                                          /*length=*/kBufferSize / 4,
                                          /*pattern=*/&val2,
                                          /*pattern_length=*/sizeof(val2)));
  std::memset(reference_buffer.data() + kBufferSize / 4, val2, kBufferSize / 4);

  uint8_t val3 = 0x54;
  IREE_ASSERT_OK(
      iree_hal_command_buffer_fill_buffer(command_buffer, device_buffer,
                                          /*target_offset=*/kBufferSize / 2,
                                          /*length=*/kBufferSize / 2,
                                          /*pattern=*/&val3,
                                          /*pattern_length=*/sizeof(val3)));
  std::memset(reference_buffer.data() + kBufferSize / 2, val3, kBufferSize / 2);

  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_TRANSFER,
                                            command_buffer));

  // Read the device buffer and compare.
  std::vector<uint8_t> actual_data(kBufferSize);
  IREE_ASSERT_OK(iree_hal_buffer_read_data(device_buffer, /*source_offset=*/0,
                                           /*target_buffer=*/actual_data.data(),
                                           /*data_length=*/kBufferSize));
  EXPECT_THAT(actual_data, ContainerEq(reference_buffer));

  // Must release the command buffer before resources used by it.
  iree_hal_command_buffer_release(command_buffer);
  iree_hal_buffer_release(device_buffer);
}

TEST_P(CommandBufferTest, CopyWholeBuffer) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_TRANSFER, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  // Create and fill a host buffer.
  iree_hal_buffer_t* host_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_HOST_VISIBLE | IREE_HAL_MEMORY_TYPE_HOST_CACHED |
          IREE_HAL_MEMORY_TYPE_DEVICE_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &host_buffer));
  uint8_t i8_val = 0x54;
  IREE_ASSERT_OK(iree_hal_buffer_fill(host_buffer, /*byte_offset=*/0,
                                      /*byte_length=*/kBufferSize, &i8_val,
                                      /*pattern_length=*/sizeof(i8_val)));
  std::vector<uint8_t> reference_buffer(kBufferSize);
  std::memset(reference_buffer.data(), i8_val, kBufferSize);

  // Create a device buffer.
  iree_hal_buffer_t* device_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL | IREE_HAL_MEMORY_TYPE_HOST_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &device_buffer));

  // Copy the host buffer to the device buffer.
  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_copy_buffer(
      command_buffer, /*source_buffer=*/host_buffer, /*source_offset=*/0,
      /*target_buffer=*/device_buffer, /*target_offset=*/0,
      /*length=*/kBufferSize));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_TRANSFER,
                                            command_buffer));

  // Read the device buffer and compare.
  std::vector<uint8_t> actual_data(kBufferSize);
  IREE_ASSERT_OK(iree_hal_buffer_read_data(device_buffer, /*source_offset=*/0,
                                           /*target_buffer=*/actual_data.data(),
                                           /*data_length=*/kBufferSize));
  EXPECT_THAT(actual_data, ContainerEq(reference_buffer));

  // Must release the command buffer before resources used by it.
  iree_hal_command_buffer_release(command_buffer);
  iree_hal_buffer_release(device_buffer);
  iree_hal_buffer_release(host_buffer);
}

TEST_P(CommandBufferTest, CopySubBuffer) {
  iree_hal_command_buffer_t* command_buffer;
  IREE_ASSERT_OK(iree_hal_command_buffer_create(
      device_, IREE_HAL_COMMAND_BUFFER_MODE_ONE_SHOT,
      IREE_HAL_COMMAND_CATEGORY_TRANSFER, IREE_HAL_QUEUE_AFFINITY_ANY,
      &command_buffer));

  iree_hal_buffer_t* device_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_DEVICE_LOCAL | IREE_HAL_MEMORY_TYPE_HOST_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize, &device_buffer));

  // Create another host buffer with a smaller size.
  iree_hal_buffer_t* host_buffer;
  IREE_ASSERT_OK(iree_hal_allocator_allocate_buffer(
      device_allocator_,
      IREE_HAL_MEMORY_TYPE_HOST_VISIBLE | IREE_HAL_MEMORY_TYPE_HOST_CACHED |
          IREE_HAL_MEMORY_TYPE_DEVICE_VISIBLE,
      IREE_HAL_BUFFER_USAGE_ALL, kBufferSize / 2, &host_buffer));

  // Fill the host buffer.
  uint8_t i8_val = 0x88;
  IREE_ASSERT_OK(iree_hal_buffer_fill(host_buffer, /*byte_offset=*/0,
                                      /*byte_length=*/kBufferSize / 2, &i8_val,
                                      /*pattern_length=*/sizeof(i8_val)));
  std::vector<uint8_t> reference_buffer(kBufferSize);
  std::memset(reference_buffer.data() + 8, i8_val, kBufferSize / 2 - 4);

  // Copy the host buffer to the device buffer; zero fill the untouched bytes.
  uint8_t zero_val = 0x0;
  IREE_ASSERT_OK(iree_hal_command_buffer_begin(command_buffer));
  IREE_ASSERT_OK(iree_hal_command_buffer_fill_buffer(
      command_buffer, device_buffer, /*target_offset=*/0, /*length=*/8,
      &zero_val, /*pattern_length=*/sizeof(zero_val)));
  IREE_ASSERT_OK(iree_hal_command_buffer_copy_buffer(
      command_buffer, /*source_buffer=*/host_buffer, /*source_offset=*/4,
      /*target_buffer=*/device_buffer, /*target_offset=*/8,
      /*length=*/kBufferSize / 2 - 4));
  IREE_ASSERT_OK(iree_hal_command_buffer_fill_buffer(
      command_buffer, device_buffer, /*target_offset=*/8 + kBufferSize / 2 - 4,
      /*length=*/kBufferSize - (8 + kBufferSize / 2 - 4), &zero_val,
      /*pattern_length=*/sizeof(zero_val)));
  IREE_ASSERT_OK(iree_hal_command_buffer_end(command_buffer));

  IREE_ASSERT_OK(SubmitCommandBufferAndWait(IREE_HAL_COMMAND_CATEGORY_TRANSFER,
                                            command_buffer));

  // Read the device buffer and compare.
  std::vector<uint8_t> actual_data(kBufferSize);
  IREE_ASSERT_OK(iree_hal_buffer_read_data(device_buffer, /*source_offset=*/0,
                                           /*target_buffer=*/actual_data.data(),
                                           /*data_length=*/kBufferSize));
  EXPECT_THAT(actual_data, ContainerEq(reference_buffer));

  // Must release the command buffer before resources used by it.
  iree_hal_command_buffer_release(command_buffer);
  iree_hal_buffer_release(device_buffer);
  iree_hal_buffer_release(host_buffer);
}

INSTANTIATE_TEST_SUITE_P(
    AllDrivers, CommandBufferTest,
    ::testing::ValuesIn(testing::EnumerateAvailableDrivers()),
    GenerateTestName());

}  // namespace cts
}  // namespace hal
}  // namespace iree
<|endoftext|>


<commit_before>#include <cpp3ds/Input.h>
#include <cpp3ds/utils.h>

namespace cpp3ds {

	int Input::getHID(){
		last_hid = read_word(HID);
		return last_hid;
	}

	bool Input::isDown(Button button) {
		return (!(read_word(HID) & button));
	}

}
<commit_msg>Invert bits for better style ;)<commit_after>#include <cpp3ds/Input.h>
#include <cpp3ds/utils.h>

namespace cpp3ds {

	int Input::getHID(){
		last_hid = read_word(HID);
		return last_hid;
	}

	bool Input::isDown(Button button) {
		return (~read_word(HID) & button);
	}

}
<|endoftext|>


<commit_before>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "ConstantDT.h"
#include "FEProblem.h"
#include "Transient.h"

namespace
{
const std::string dt_name = "dt";
const std::string growth_factor_name = "growth_factor";
}

template<>
InputParameters validParams<ConstantDT>()
{
  InputParameters params = validParams<TimeStepper>();
  params.addRequiredParam<Real>( dt_name, "Size of the time step" );
  params.addRangeCheckedParam<Real>( growth_factor_name, 2, growth_factor_name + ">=1",
    "Maximum ratio of new to previous timestep sizes following a step that required the time"
    " step to be cut due to a failed solve." );
  return params;
}

ConstantDT::ConstantDT(const std::string & name, InputParameters parameters) :
    TimeStepper( name, parameters ),
    _constant_dt( getParam<Real>( dt_name ) ),
    _growth_factor( getParam<Real>( growth_factor_name ) )
{
}

Real
ConstantDT::computeInitialDT()
{
  return _constant_dt;
}

Real
ConstantDT::computeDT()
{
  return std::min( _constant_dt, _growth_factor * getCurrentDT() );
}
<commit_msg>small style modifications refs #3765 #3764<commit_after>/****************************************************************/
/*               DO NOT MODIFY THIS HEADER                      */
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*           (c) 2010 Battelle Energy Alliance, LLC             */
/*                   ALL RIGHTS RESERVED                        */
/*                                                              */
/*          Prepared by Battelle Energy Alliance, LLC           */
/*            Under Contract No. DE-AC07-05ID14517              */
/*            With the U. S. Department of Energy               */
/*                                                              */
/*            See COPYRIGHT for full restrictions               */
/****************************************************************/

#include "ConstantDT.h"

template<>
InputParameters validParams<ConstantDT>()
{
  InputParameters params = validParams<TimeStepper>();
  params.addRequiredParam<Real>("dt", "Size of the time step");
  params.addRangeCheckedParam<Real>("growth_factor", 2, "growth_factor>=1",
    "Maximum ratio of new to previous timestep sizes following a step that required the time"
    " step to be cut due to a failed solve.");
  return params;
}

ConstantDT::ConstantDT(const std::string & name, InputParameters parameters) :
    TimeStepper(name, parameters),
    _constant_dt(getParam<Real>("dt")),
    _growth_factor(getParam<Real>("growth_factor"))
{
}

Real
ConstantDT::computeInitialDT()
{
  return _constant_dt;
}

Real
ConstantDT::computeDT()
{
  return std::min(_constant_dt, _growth_factor * getCurrentDT());
}
<|endoftext|>