<commit_before>#include "paxos/logging.hpp"
#include "paxos/sender.hpp"

#include <boost/asio/io_service.hpp>

using boost::asio::ip::tcp;

BoostTransport::BoostTransport()
    : io_service_(),
      socket_(io_service_)
{
}

BoostTransport::~BoostTransport()
{
    socket_.close();
}

void
BoostTransport::Connect(std::string hostname, short port)
{
    tcp::resolver resolver(io_service_);
    auto endpoint = resolver.resolve({hostname, std::to_string(port)});
    boost::asio::connect(socket_, endpoint);
}

void
BoostTransport::Write(std::string content)
{
    boost::asio::write(socket_, boost::asio::buffer(content.c_str(), content.size()));
}
<commit_msg>Add try-block handling failed connections<commit_after>#include "paxos/logging.hpp"
#include "paxos/sender.hpp"

#include <boost/asio/io_service.hpp>

using boost::asio::ip::tcp;

BoostTransport::BoostTransport()
    : io_service_(),
      socket_(io_service_)
{
}

BoostTransport::~BoostTransport()
{
    socket_.close();
}

void
BoostTransport::Connect(std::string hostname, short port)
{
    tcp::resolver resolver(io_service_);
    auto endpoint = resolver.resolve({hostname, std::to_string(port)});
    try
    {
        boost::asio::connect(socket_, endpoint);
    }
    catch (const boost::system::system_error& e)
    {
        LOG(LogLevel::Warning) << "Could not connect to " << hostname << ":" << port;
    }
}

void
BoostTransport::Write(std::string content)
{
    try
    {
        boost::asio::write(socket_, boost::asio::buffer(content.c_str(), content.size()));
    }
    catch (const boost::system::system_error& e)
    {
        LOG(LogLevel::Warning) << "Could not write to transport";
    }
}
<|endoftext|>


<commit_before>/*
 * type.cc
 * Copyright (C) 2016 romgrk <romgrk@Romgrk-ARCH>
 *
 * Distributed under terms of the GPL license.
 */

#include "gi.h"
#include "type.h"
#include "util.h"
#include "debug.h"

using v8::FunctionTemplate;
using v8::Persistent;

namespace GNodeJS {

void ClassDestroyed(const v8::WeakCallbackInfo<GIBaseInfo> &info) {
    GIBaseInfo *gi_info = info.GetParameter ();
    GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info);
    void *type_data = g_type_get_qdata (gtype, GNodeJS::template_quark());

    Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) type_data;
    delete persistent;

    g_type_set_qdata (gtype, GNodeJS::template_quark(), NULL);
    g_base_info_unref (gi_info);
}

char *GetInfoName (GIBaseInfo* info) {
    const char* info_name = g_base_info_get_name (info);

    if (info_name == NULL)
        return g_strdup ("(NULL)");

    char* name = g_strdup (info_name);

    GIBaseInfo *parent;
    while ((parent = g_base_info_get_container (info)) != NULL) {
        char *new_name = g_strconcat (g_base_info_get_name(parent), ".", name, NULL);
        g_free (name);
        name = new_name;
    }

    char *new_name = g_strconcat (g_base_info_get_namespace(info), ".", name, NULL);
    g_free (name);
    name = new_name;

    return name;
}

char *GetTypeName (GITypeInfo *type_info) {
    GITypeTag type_tag = g_type_info_get_tag (type_info);

    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
            return g_strdup("Boolean");

        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_INT32:
        case GI_TYPE_TAG_INT64:
        case GI_TYPE_TAG_UINT8:
        case GI_TYPE_TAG_UINT16:
        case GI_TYPE_TAG_UINT32:
        case GI_TYPE_TAG_UINT64:
        case GI_TYPE_TAG_FLOAT:
        case GI_TYPE_TAG_DOUBLE:
            return g_strdup("Number");

        case GI_TYPE_TAG_GTYPE:
            return g_strdup("GType");

        case GI_TYPE_TAG_UNICHAR:
            return g_strdup("Char");

        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
            return g_strdup("String");

        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info = g_type_info_get_interface (type_info);
            auto result = g_strdup_printf("%s.%s",
                    g_base_info_get_namespace(info), g_base_info_get_name(info));
            g_base_info_unref (info);
            return result;
        }

        case GI_TYPE_TAG_ARRAY:
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        {
            GITypeInfo *elem_info = g_type_info_get_param_type(type_info, 0);
            auto elem_name = GetTypeName (elem_info);
            auto result = g_strdup_printf("%s[]", elem_name);

            g_base_info_unref(elem_info);
            g_free(elem_name);

            return result;
        }

        case GI_TYPE_TAG_GHASH:
        case GI_TYPE_TAG_ERROR:
        case GI_TYPE_TAG_VOID:
        default:
            return g_strdup(g_type_tag_to_string(type_tag));
    }
}

gsize GetTypeSize (GITypeInfo *type_info) {
    gsize size = 0;

    GITypeTag type_tag = g_type_info_get_tag (type_info);

    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_UINT8:
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_UINT16:
        case GI_TYPE_TAG_INT32:
        case GI_TYPE_TAG_UINT32:
        case GI_TYPE_TAG_INT64:
        case GI_TYPE_TAG_UINT64:
        case GI_TYPE_TAG_FLOAT:
        case GI_TYPE_TAG_DOUBLE:
        case GI_TYPE_TAG_GTYPE:
        case GI_TYPE_TAG_UNICHAR:
        {
            size = GetTypeTagSize (type_tag);
            break;
        }

        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info;
            GIInfoType info_type;

            info = g_type_info_get_interface (type_info);
            info_type = g_base_info_get_type (info);

            size = sizeof (gpointer);

            switch (info_type) {
                case GI_INFO_TYPE_STRUCT:
                    if (!g_type_info_is_pointer (type_info)) {
                        size = g_struct_info_get_size ( (GIStructInfo *) info);
                    }
                    break;
                case GI_INFO_TYPE_UNION:
                    if (!g_type_info_is_pointer (type_info)) {
                        size = g_union_info_get_size ( (GIUnionInfo *) info);
                    }
                    break;
                case GI_INFO_TYPE_ENUM:
                case GI_INFO_TYPE_FLAGS:
                    if (!g_type_info_is_pointer (type_info)) {
                        size = GetTypeTagSize (g_enum_info_get_storage_type ( (GIEnumInfo *) info));
                    }
                    break;
                case GI_INFO_TYPE_BOXED:
                case GI_INFO_TYPE_OBJECT:
                case GI_INFO_TYPE_INTERFACE:
                case GI_INFO_TYPE_CALLBACK:
                    break;
                case GI_INFO_TYPE_VFUNC:
                case GI_INFO_TYPE_FUNCTION:
                case GI_INFO_TYPE_CONSTANT:
                case GI_INFO_TYPE_VALUE:
                case GI_INFO_TYPE_SIGNAL:
                case GI_INFO_TYPE_PROPERTY:
                case GI_INFO_TYPE_FIELD:
                case GI_INFO_TYPE_ARG:
                case GI_INFO_TYPE_TYPE:
                case GI_INFO_TYPE_INVALID:
                case GI_INFO_TYPE_UNRESOLVED:
                default:
                    printf("info type: %s\n", g_info_type_to_string(info_type));
                    g_assert_not_reached();
                    break;
            }

            g_base_info_unref (info);
            break;
        }
        case GI_TYPE_TAG_ARRAY:
        case GI_TYPE_TAG_VOID:
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        case GI_TYPE_TAG_GHASH:
        case GI_TYPE_TAG_ERROR:
            size = sizeof(gpointer);
            break;
    }

    return size;
}

gsize GetTypeTagSize (GITypeTag type_tag) {
    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
            return sizeof (gboolean);
            break;
        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_UINT8:
            return sizeof (gint8);
            break;
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_UINT16:
            return sizeof (gint16);
            break;
        case GI_TYPE_TAG_INT32:
        case GI_TYPE_TAG_UINT32:
            return sizeof (gint32);
            break;
        case GI_TYPE_TAG_INT64:
        case GI_TYPE_TAG_UINT64:
            return sizeof (gint64);
            break;
        case GI_TYPE_TAG_FLOAT:
            return sizeof (gfloat);
            break;
        case GI_TYPE_TAG_DOUBLE:
            return sizeof (gdouble);
            break;
        case GI_TYPE_TAG_GTYPE:
            return sizeof (GType);
            break;
        case GI_TYPE_TAG_UNICHAR:
            return sizeof (gunichar);
            break;
        case GI_TYPE_TAG_VOID:
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
        case GI_TYPE_TAG_ARRAY:
        case GI_TYPE_TAG_INTERFACE:
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        case GI_TYPE_TAG_GHASH:
        case GI_TYPE_TAG_ERROR:
            g_assert_not_reached ();
    }

    return 0;
}

GITypeTag GetStorageType (GITypeInfo *type_info) {
    GITypeTag type_tag = g_type_info_get_tag (type_info);

    if (type_tag == GI_TYPE_TAG_INTERFACE) {
        GIBaseInfo *interface = g_type_info_get_interface (type_info);
        GIInfoType interface_type = g_base_info_get_type (interface);

        if (interface_type == GI_INFO_TYPE_ENUM || interface_type == GI_INFO_TYPE_FLAGS)
            type_tag = g_enum_info_get_storage_type ((GIEnumInfo *)interface);

        g_base_info_unref (interface);
    }

    return type_tag;
}

};

<commit_msg>type.cc: remove license header<commit_after>
#include "gi.h"
#include "type.h"
#include "util.h"
#include "debug.h"

using v8::FunctionTemplate;
using v8::Persistent;

namespace GNodeJS {

void ClassDestroyed(const v8::WeakCallbackInfo<GIBaseInfo> &info) {
    GIBaseInfo *gi_info = info.GetParameter ();
    GType gtype = g_registered_type_info_get_g_type ((GIRegisteredTypeInfo *) gi_info);
    void *type_data = g_type_get_qdata (gtype, GNodeJS::template_quark());

    Persistent<FunctionTemplate> *persistent = (Persistent<FunctionTemplate> *) type_data;
    delete persistent;

    g_type_set_qdata (gtype, GNodeJS::template_quark(), NULL);
    g_base_info_unref (gi_info);
}

char *GetInfoName (GIBaseInfo* info) {
    const char* info_name = g_base_info_get_name (info);

    if (info_name == NULL)
        return g_strdup ("(NULL)");

    char* name = g_strdup (info_name);

    GIBaseInfo *parent;
    while ((parent = g_base_info_get_container (info)) != NULL) {
        char *new_name = g_strconcat (g_base_info_get_name(parent), ".", name, NULL);
        g_free (name);
        name = new_name;
    }

    char *new_name = g_strconcat (g_base_info_get_namespace(info), ".", name, NULL);
    g_free (name);
    name = new_name;

    return name;
}

char *GetTypeName (GITypeInfo *type_info) {
    GITypeTag type_tag = g_type_info_get_tag (type_info);

    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
            return g_strdup("Boolean");

        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_INT32:
        case GI_TYPE_TAG_INT64:
        case GI_TYPE_TAG_UINT8:
        case GI_TYPE_TAG_UINT16:
        case GI_TYPE_TAG_UINT32:
        case GI_TYPE_TAG_UINT64:
        case GI_TYPE_TAG_FLOAT:
        case GI_TYPE_TAG_DOUBLE:
            return g_strdup("Number");

        case GI_TYPE_TAG_GTYPE:
            return g_strdup("GType");

        case GI_TYPE_TAG_UNICHAR:
            return g_strdup("Char");

        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
            return g_strdup("String");

        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info = g_type_info_get_interface (type_info);
            auto result = g_strdup_printf("%s.%s",
                    g_base_info_get_namespace(info), g_base_info_get_name(info));
            g_base_info_unref (info);
            return result;
        }

        case GI_TYPE_TAG_ARRAY:
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        {
            GITypeInfo *elem_info = g_type_info_get_param_type(type_info, 0);
            auto elem_name = GetTypeName (elem_info);
            auto result = g_strdup_printf("%s[]", elem_name);

            g_base_info_unref(elem_info);
            g_free(elem_name);

            return result;
        }

        case GI_TYPE_TAG_GHASH:
        case GI_TYPE_TAG_ERROR:
        case GI_TYPE_TAG_VOID:
        default:
            return g_strdup(g_type_tag_to_string(type_tag));
    }
}

gsize GetTypeSize (GITypeInfo *type_info) {
    gsize size = 0;

    GITypeTag type_tag = g_type_info_get_tag (type_info);

    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_UINT8:
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_UINT16:
        case GI_TYPE_TAG_INT32:
        case GI_TYPE_TAG_UINT32:
        case GI_TYPE_TAG_INT64:
        case GI_TYPE_TAG_UINT64:
        case GI_TYPE_TAG_FLOAT:
        case GI_TYPE_TAG_DOUBLE:
        case GI_TYPE_TAG_GTYPE:
        case GI_TYPE_TAG_UNICHAR:
        {
            size = GetTypeTagSize (type_tag);
            break;
        }

        case GI_TYPE_TAG_INTERFACE:
        {
            GIBaseInfo *info;
            GIInfoType info_type;

            info = g_type_info_get_interface (type_info);
            info_type = g_base_info_get_type (info);

            size = sizeof (gpointer);

            switch (info_type) {
                case GI_INFO_TYPE_STRUCT:
                    if (!g_type_info_is_pointer (type_info)) {
                        size = g_struct_info_get_size ( (GIStructInfo *) info);
                    }
                    break;
                case GI_INFO_TYPE_UNION:
                    if (!g_type_info_is_pointer (type_info)) {
                        size = g_union_info_get_size ( (GIUnionInfo *) info);
                    }
                    break;
                case GI_INFO_TYPE_ENUM:
                case GI_INFO_TYPE_FLAGS:
                    if (!g_type_info_is_pointer (type_info)) {
                        size = GetTypeTagSize (g_enum_info_get_storage_type ( (GIEnumInfo *) info));
                    }
                    break;
                case GI_INFO_TYPE_BOXED:
                case GI_INFO_TYPE_OBJECT:
                case GI_INFO_TYPE_INTERFACE:
                case GI_INFO_TYPE_CALLBACK:
                    break;
                case GI_INFO_TYPE_VFUNC:
                case GI_INFO_TYPE_FUNCTION:
                case GI_INFO_TYPE_CONSTANT:
                case GI_INFO_TYPE_VALUE:
                case GI_INFO_TYPE_SIGNAL:
                case GI_INFO_TYPE_PROPERTY:
                case GI_INFO_TYPE_FIELD:
                case GI_INFO_TYPE_ARG:
                case GI_INFO_TYPE_TYPE:
                case GI_INFO_TYPE_INVALID:
                case GI_INFO_TYPE_UNRESOLVED:
                default:
                    printf("info type: %s\n", g_info_type_to_string(info_type));
                    g_assert_not_reached();
                    break;
            }

            g_base_info_unref (info);
            break;
        }
        case GI_TYPE_TAG_ARRAY:
        case GI_TYPE_TAG_VOID:
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        case GI_TYPE_TAG_GHASH:
        case GI_TYPE_TAG_ERROR:
            size = sizeof(gpointer);
            break;
    }

    return size;
}

gsize GetTypeTagSize (GITypeTag type_tag) {
    switch (type_tag) {
        case GI_TYPE_TAG_BOOLEAN:
            return sizeof (gboolean);
            break;
        case GI_TYPE_TAG_INT8:
        case GI_TYPE_TAG_UINT8:
            return sizeof (gint8);
            break;
        case GI_TYPE_TAG_INT16:
        case GI_TYPE_TAG_UINT16:
            return sizeof (gint16);
            break;
        case GI_TYPE_TAG_INT32:
        case GI_TYPE_TAG_UINT32:
            return sizeof (gint32);
            break;
        case GI_TYPE_TAG_INT64:
        case GI_TYPE_TAG_UINT64:
            return sizeof (gint64);
            break;
        case GI_TYPE_TAG_FLOAT:
            return sizeof (gfloat);
            break;
        case GI_TYPE_TAG_DOUBLE:
            return sizeof (gdouble);
            break;
        case GI_TYPE_TAG_GTYPE:
            return sizeof (GType);
            break;
        case GI_TYPE_TAG_UNICHAR:
            return sizeof (gunichar);
            break;
        case GI_TYPE_TAG_VOID:
        case GI_TYPE_TAG_UTF8:
        case GI_TYPE_TAG_FILENAME:
        case GI_TYPE_TAG_ARRAY:
        case GI_TYPE_TAG_INTERFACE:
        case GI_TYPE_TAG_GLIST:
        case GI_TYPE_TAG_GSLIST:
        case GI_TYPE_TAG_GHASH:
        case GI_TYPE_TAG_ERROR:
            g_assert_not_reached ();
    }

    return 0;
}

GITypeTag GetStorageType (GITypeInfo *type_info) {
    GITypeTag type_tag = g_type_info_get_tag (type_info);

    if (type_tag == GI_TYPE_TAG_INTERFACE) {
        GIBaseInfo *interface = g_type_info_get_interface (type_info);
        GIInfoType interface_type = g_base_info_get_type (interface);

        if (interface_type == GI_INFO_TYPE_ENUM || interface_type == GI_INFO_TYPE_FLAGS)
            type_tag = g_enum_info_get_storage_type ((GIEnumInfo *)interface);

        g_base_info_unref (interface);
    }

    return type_tag;
}

};

<|endoftext|>


<commit_before>#include "condor_common.h"
#include "condor_debug.h"
#include "condor_attributes.h"

#include "classad/classad.h"
#include "compat_classad.h"
#include "ToE.h"
#include "iso_dates.h"
#include "utc_time.h"

namespace ToE {

const int OfItsOwnAccord = 0;
const int DeactivateClaim = 1;
const int DeactivateClaimForcibly = 2;

const char * strings[] = {
    "OF_ITS_OWN_ACCORD",
    "DEACTIVATE_CLAIM",
    "DEACTIVATE_CLAIM_FORCIBLY"
};

const char * itself = "itself";

// Append the toe ad to the .job.ad file.  This avoids a race
// condition where the startd replaces the .update.ad with a
// new after the ToE tag is written but before the post script
// gets a chance to look at it.  Using append mode means that
// we don't need locking to ensure the job ad file remains
// syntactically valid.  (The last writer will win, but the
// only case where that could be wrong is if the starter sees
// the job terminate of its own accord but the startd is
// ordered to terminate the job between when the starter writes
// this file and when the post-script runs.)
//
// On Windows, the C runtime library emulates append mode, which
// means it won't work for the purpose we're using it for.  We
// should probably wrap this knowledge up in a function somewhere
// if we aren't going to fixe safefile.
bool
writeTag( classad::ClassAd * toe, const std::string & jobAdFileName ) {
#ifndef WINDOWS
    FILE * jobAdFile = safe_fopen_wrapper_follow( jobAdFileName.c_str(), "a" );
#else
    FILE * jobAdFile = NULL;
    HANDLE hf = CreateFile( jobAdFileName.c_str(),
        FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
    if( hf == INVALID_HANDLE_VALUE ) {
        dprintf( D_ALWAYS, "Failed to open .job.ad file: %d\n", GetLastError() );
        jobAdFile = NULL;
    } else {
        int fd = _open_osfhandle((intptr_t)hf, O_APPEND);
        if( fd == -1 ) {
            dprintf( D_ALWAYS, "Failed to _open .job.ad file: %d\n", _doserrno );
        }
        jobAdFile = fdopen( fd, "a" );
    }
#endif

    if(! jobAdFile) {
        dprintf( D_ALWAYS, "Failed to write ToE tag to .job.ad file (%d): %s\n",
            errno, strerror(errno) );
        return false;
    } else {
        fPrintAd( jobAdFile, * toe );
        fclose( jobAdFile );
    }

    return true;
}

bool
decode( classad::ClassAd * ca, Tag & tag ) {
    if(! ca) { return false; }

    ca->EvaluateAttrString( "Who", tag.who );
    ca->EvaluateAttrString( "How", tag.how );
    long long when;
    ca->EvaluateAttrNumber( "When", when );
    ca->EvaluateAttrNumber( "HowCode", (int &)tag.howCode );

    if( ca->EvaluateAttrBool( ATTR_ON_EXIT_BY_SIGNAL, tag.exitBySignal )) {
        ca->EvaluateAttrNumber(
            tag.exitBySignal ? ATTR_ON_EXIT_SIGNAL : ATTR_ON_EXIT_CODE,
            tag.signalOrExitCode
        );
    }

    char whenStr[ISO8601_DateAndTimeBufferMax];
    struct tm eventTime;
    // time_t is a signed long int on all Linux platforms.  We send
    // it over the wire via ClassAds in a (signed) long long, which
    // is 64 bits on all platforms.  This conversion should be a no
    // op on 64-bit platforms, but will correctly preserve the sign
    // bit on 32-bit platforms.
    time_t ttWhen = (time_t)when;
    gmtime_r( & ttWhen, & eventTime );
    // We should also respect the time format flag, once local times
    // round-trip between differente machines (e.g., once we write
    // time zones as part of our time stamps).
    time_to_iso8601( whenStr, eventTime, ISO8601_ExtendedFormat,
        ISO8601_DateAndTime, true );
    tag.when.assign( whenStr );

    return true;
}

bool
Tag::writeToString( std::string & out ) const {
    return formatstr_cat( out,
        "\n\tJob terminated by %s at %s (using method %d: %s).\n",
        who.c_str(), when.c_str(), howCode, how.c_str() ) >= 0;
}

bool
Tag::readFromString( const std::string & in ) {
    std::string line = in;

	const char * endWhoStr = " at ";
	size_t endWho = line.find( endWhoStr );
	if( endWho == std::string::npos ) { return false; }
	std::string whoStr = line.substr( 0, endWho );
	this->who = whoStr.c_str();
	line = line.substr( endWho + strlen(endWhoStr), INT_MAX );

	const char * endWhenStr = " (using method ";
	size_t endWhen = line.find( endWhenStr );
	if( endWhen == std::string::npos ) { return false; }
	std::string whenStr = line.substr( 0, endWhen );
	line = line.substr( endWhen + strlen(endWhenStr), INT_MAX );
	// This code gets more complicated if we don't assume UTC i/o.
	struct tm eventTime;
	iso8601_to_time( whenStr.c_str(), & eventTime, NULL, NULL );
	formatstr( when, "%ld", timegm(&eventTime) );

	const char * endHowCodeStr = ": ";
	size_t endHowCode = line.find( endHowCodeStr );
	if( endHowCode == std::string::npos ) { return false; }
	std::string howCodeStr = line.substr( 0, endHowCode );
	line = line.substr( endHowCode + strlen(endHowCodeStr), INT_MAX );
	char * end = NULL;
	long lhc = strtol( howCodeStr.c_str(), & end, 10 );
	if( end && *end == '\0' ) {
		this->howCode = lhc;
	} else {
		return false;
	}

	const char * endHowStr = ").";
	size_t endHow = line.find( endHowStr );
	if( endHow == std::string::npos ) { return false; }
	std::string how = line.substr( 0, endHow );
	line = line.substr( endHow + strlen(endHowStr), INT_MAX );
	if(! line.empty()) { return false; }
	this->how = how.c_str();

    return true;
}

bool
encode( const Tag & tag, classad::ClassAd * ca ) {
    if(! ca) { return false; }

    ca->InsertAttr( "Who", tag.who );
    ca->InsertAttr( "How", tag.how );
    ca->InsertAttr( "When",tag.when );
    ca->InsertAttr( "HowCode", (int)tag.howCode );

    if( tag.howCode == ToE::OfItsOwnAccord ) {
        ca->InsertAttr( ATTR_ON_EXIT_BY_SIGNAL, tag.exitBySignal );
        ca->InsertAttr(
            tag.exitBySignal ? ATTR_ON_EXIT_SIGNAL : ATTR_ON_EXIT_CODE,
            tag.signalOrExitCode
        );
    }

    return true;
}

};
<commit_msg>Remove string copies in Tag::readFromString(). HTCONDOR-754<commit_after>#include "condor_common.h"
#include "condor_debug.h"
#include "condor_attributes.h"

#include "classad/classad.h"
#include "compat_classad.h"
#include "ToE.h"
#include "iso_dates.h"
#include "utc_time.h"

namespace ToE {

const int OfItsOwnAccord = 0;
const int DeactivateClaim = 1;
const int DeactivateClaimForcibly = 2;

const char * strings[] = {
    "OF_ITS_OWN_ACCORD",
    "DEACTIVATE_CLAIM",
    "DEACTIVATE_CLAIM_FORCIBLY"
};

const char * itself = "itself";

// Append the toe ad to the .job.ad file.  This avoids a race
// condition where the startd replaces the .update.ad with a
// new after the ToE tag is written but before the post script
// gets a chance to look at it.  Using append mode means that
// we don't need locking to ensure the job ad file remains
// syntactically valid.  (The last writer will win, but the
// only case where that could be wrong is if the starter sees
// the job terminate of its own accord but the startd is
// ordered to terminate the job between when the starter writes
// this file and when the post-script runs.)
//
// On Windows, the C runtime library emulates append mode, which
// means it won't work for the purpose we're using it for.  We
// should probably wrap this knowledge up in a function somewhere
// if we aren't going to fixe safefile.
bool
writeTag( classad::ClassAd * toe, const std::string & jobAdFileName ) {
#ifndef WINDOWS
    FILE * jobAdFile = safe_fopen_wrapper_follow( jobAdFileName.c_str(), "a" );
#else
    FILE * jobAdFile = NULL;
    HANDLE hf = CreateFile( jobAdFileName.c_str(),
        FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
    if( hf == INVALID_HANDLE_VALUE ) {
        dprintf( D_ALWAYS, "Failed to open .job.ad file: %d\n", GetLastError() );
        jobAdFile = NULL;
    } else {
        int fd = _open_osfhandle((intptr_t)hf, O_APPEND);
        if( fd == -1 ) {
            dprintf( D_ALWAYS, "Failed to _open .job.ad file: %d\n", _doserrno );
        }
        jobAdFile = fdopen( fd, "a" );
    }
#endif

    if(! jobAdFile) {
        dprintf( D_ALWAYS, "Failed to write ToE tag to .job.ad file (%d): %s\n",
            errno, strerror(errno) );
        return false;
    } else {
        fPrintAd( jobAdFile, * toe );
        fclose( jobAdFile );
    }

    return true;
}

bool
decode( classad::ClassAd * ca, Tag & tag ) {
    if(! ca) { return false; }

    ca->EvaluateAttrString( "Who", tag.who );
    ca->EvaluateAttrString( "How", tag.how );
    long long when;
    ca->EvaluateAttrNumber( "When", when );
    ca->EvaluateAttrNumber( "HowCode", (int &)tag.howCode );

    if( ca->EvaluateAttrBool( ATTR_ON_EXIT_BY_SIGNAL, tag.exitBySignal )) {
        ca->EvaluateAttrNumber(
            tag.exitBySignal ? ATTR_ON_EXIT_SIGNAL : ATTR_ON_EXIT_CODE,
            tag.signalOrExitCode
        );
    }

    char whenStr[ISO8601_DateAndTimeBufferMax];
    struct tm eventTime;
    // time_t is a signed long int on all Linux platforms.  We send
    // it over the wire via ClassAds in a (signed) long long, which
    // is 64 bits on all platforms.  This conversion should be a no
    // op on 64-bit platforms, but will correctly preserve the sign
    // bit on 32-bit platforms.
    time_t ttWhen = (time_t)when;
    gmtime_r( & ttWhen, & eventTime );
    // We should also respect the time format flag, once local times
    // round-trip between differente machines (e.g., once we write
    // time zones as part of our time stamps).
    time_to_iso8601( whenStr, eventTime, ISO8601_ExtendedFormat,
        ISO8601_DateAndTime, true );
    tag.when.assign( whenStr );

    return true;
}

bool
Tag::writeToString( std::string & out ) const {
    return formatstr_cat( out,
        "\n\tJob terminated by %s at %s (using method %d: %s).\n",
        who.c_str(), when.c_str(), howCode, how.c_str() ) >= 0;
}

bool
Tag::readFromString( const std::string & in ) {
	size_t startPos = 0;

	const char * endWhoStr = " at ";
	size_t endWho = in.find( endWhoStr );
	if( endWho == std::string::npos ) { return false; }
	this->who = in.substr( startPos, endWho );
	startPos = endWho + strlen(endWhoStr);

	const char * endWhenStr = " (using method ";
	size_t endWhen = in.find( endWhenStr, startPos );
	if( endWhen == std::string::npos ) { return false; }
	std::string whenStr = in.substr( startPos, endWhen );
	startPos = endWhen + strlen(endWhenStr);
	// This code gets more complicated if we don't assume UTC i/o.
	struct tm eventTime;
	iso8601_to_time( whenStr.c_str(), & eventTime, NULL, NULL );
	formatstr( when, "%ld", timegm(&eventTime) );

	const char * endHowCodeStr = ": ";
	size_t endHowCode = in.find( endHowCodeStr, startPos );
	if( endHowCode == std::string::npos ) { return false; }
	std::string howCodeStr = in.substr( startPos, endHowCode );
	startPos = endHowCode + strlen(endHowCodeStr);
	char * end = NULL;
	long lhc = strtol( howCodeStr.c_str(), & end, 10 );
	if( end && *end == '\0' ) {
		this->howCode = lhc;
	} else {
		return false;
	}

	const char * endHowStr = ").";
	size_t endHow = in.find( endHowStr, startPos );
	if( endHow == std::string::npos ) { return false; }
	this->how = in.substr( startPos, endHow );
	startPos = endHow + strlen(endHowStr);
	if(startPos < in.length()) { return false; }

    return true;
}

bool
encode( const Tag & tag, classad::ClassAd * ca ) {
    if(! ca) { return false; }

    ca->InsertAttr( "Who", tag.who );
    ca->InsertAttr( "How", tag.how );
    ca->InsertAttr( "When",tag.when );
    ca->InsertAttr( "HowCode", (int)tag.howCode );

    if( tag.howCode == ToE::OfItsOwnAccord ) {
        ca->InsertAttr( ATTR_ON_EXIT_BY_SIGNAL, tag.exitBySignal );
        ca->InsertAttr(
            tag.exitBySignal ? ATTR_ON_EXIT_SIGNAL : ATTR_ON_EXIT_CODE,
            tag.signalOrExitCode
        );
    }

    return true;
}

};
<|endoftext|>


<commit_before>/*
  This file is part of Pack My Sprites.

  Pack My Sprites is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License.

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

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

#define PMS_TO_STR_BIS(v) # v
#define PMS_TO_STR(v) PMS_TO_STR_BIS(v)

#define PMS_MAJOR_VERSION 1
#define PMS_MINOR_VERSION 1
#define PMS_RELEASE_NUMBER 0
#define PMS_VERSION_STRING "Pack My Sprites, "                          \
  PMS_TO_STR(PMS_MAJOR_VERSION) "." PMS_TO_STR(PMS_MINOR_VERSION)       \
  "." PMS_TO_STR(PMS_RELEASE_NUMBER)
<commit_msg>Version is 1.2<commit_after>/*
  This file is part of Pack My Sprites.

  Pack My Sprites is free software: you can redistribute it and/or modify
  it under the terms of the GNU Affero General Public License as published by
  the Free Software Foundation, either version 3 of the License.

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

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

#define PMS_TO_STR_BIS(v) # v
#define PMS_TO_STR(v) PMS_TO_STR_BIS(v)

#define PMS_MAJOR_VERSION 1
#define PMS_MINOR_VERSION 2
#define PMS_RELEASE_NUMBER 0
#define PMS_VERSION_STRING "Pack My Sprites, "                          \
  PMS_TO_STR(PMS_MAJOR_VERSION) "." PMS_TO_STR(PMS_MINOR_VERSION)       \
  "." PMS_TO_STR(PMS_RELEASE_NUMBER)
<|endoftext|>


<commit_before>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

CV_ENUM(CvtMode, CV_YUV2BGR, CV_YUV2RGB, //YUV
        CV_YUV420i2BGR, CV_YUV420i2RGB, CV_YUV420sp2BGR, CV_YUV420sp2RGB, //YUV420
        CV_RGB2GRAY, CV_RGBA2GRAY, CV_BGR2GRAY, CV_BGRA2GRAY, //Gray
        CV_GRAY2RGB, CV_GRAY2RGBA, /*CV_GRAY2BGR, CV_GRAY2BGRA*/ //Gray2
        CV_BGR2HSV, CV_RGB2HSV, CV_BGR2HLS, CV_RGB2HLS, //H
        CV_BGR2YCrCb, CV_RGB2YCrCb
        )

typedef std::tr1::tuple<Size, CvtMode> Size_CvtMode_t;
typedef perf::TestBaseWithParam<Size_CvtMode_t> Size_CvtMode;

typedef std::tr1::tuple<Size, CvtMode, int> Size_CvtMode_OutChNum_t;
typedef perf::TestBaseWithParam<Size_CvtMode_OutChNum_t> Size_CvtMode_OutChNum;

PERF_TEST_P(Size_CvtMode_OutChNum, cvtColorYUV,
            testing::Combine(
                testing::Values(TYPICAL_MAT_SIZES),
                testing::Values((int)CV_YUV2BGR, (int)CV_YUV2RGB),
                testing::Values(3, 4)
                )
            )
{
    Size sz = get<0>(GetParam());
    int mode = get<1>(GetParam());
    int ch = get<2>(GetParam());

    Mat src(sz, CV_8UC3);
    Mat dst(sz, CV_8UC(ch));

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode, ch);

    SANITY_CHECK(dst, 1);
}

PERF_TEST_P(Size_CvtMode_OutChNum, cvtColorYUV420,
            testing::Combine(
                testing::Values(szVGA, sz720p, sz1080p, Size(130, 60)),
                testing::Values((int)CV_YUV420i2BGR, (int)CV_YUV420i2RGB, (int)CV_YUV420sp2BGR, (int)CV_YUV420sp2RGB),
                testing::Values(3, 4)
                )
            )
{
    Size sz = get<0>(GetParam());
    int mode = get<1>(GetParam());
    int ch = get<2>(GetParam());

    Mat src(sz.height + sz.height / 2, sz.width, CV_8UC1);
    Mat dst(sz, CV_8UC(ch));

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode, ch);

    SANITY_CHECK(dst, 1);
}

PERF_TEST_P(Size_CvtMode, cvtColorGray,
            testing::Combine(
                testing::Values(TYPICAL_MAT_SIZES),
                testing::Values((int)CV_RGB2GRAY, (int)CV_RGBA2GRAY, (int)CV_BGR2GRAY, (int)CV_BGRA2GRAY)
                )
            )
{
    Size sz = get<0>(GetParam());
    int mode = get<1>(GetParam());

    Mat src(sz, CV_8UC((mode==CV_RGBA2GRAY || mode==CV_BGRA2GRAY) ? 4 : 3));
    Mat dst(sz, CV_8UC1);

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode);

    SANITY_CHECK(dst, 1);
}

PERF_TEST_P(Size_CvtMode, cvtColorGray2,
            testing::Combine(
                testing::Values(TYPICAL_MAT_SIZES),
                testing::Values((int)CV_GRAY2RGB, (int)CV_GRAY2RGBA)
                )
            )
{
    Size sz = get<0>(GetParam());
    int mode = get<1>(GetParam());

    Mat src(sz, CV_8UC1);
    Mat dst(sz, CV_8UC((mode==CV_GRAY2RGBA || mode==CV_GRAY2BGRA) ? 4 : 3));

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode);

    SANITY_CHECK(dst);
}

PERF_TEST_P(Size_CvtMode, cvtColorH,
            testing::Combine(
                testing::Values(TYPICAL_MAT_SIZES),
                testing::Values((int)CV_BGR2HSV, (int)CV_RGB2HSV, (int)CV_BGR2HLS, (int)CV_RGB2HLS)
                )
            )
{
    Size sz = get<0>(GetParam());
    int mode = get<1>(GetParam());

    Mat src(sz, CV_8UC3);
    Mat dst(sz, CV_8UC3);

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode);

    SANITY_CHECK(dst, 1);
}

typedef std::tr1::tuple<Size, CvtMode, int> Size_CvtMode_Ch_t;
typedef perf::TestBaseWithParam<Size_CvtMode_Ch_t> Size_CvtMode_Ch;

PERF_TEST_P(Size_CvtMode_Ch, cvtColorYCrCb,
            testing::Combine(
                testing::Values(TYPICAL_MAT_SIZES),
                testing::Values((int)CV_BGR2YCrCb, (int)CV_RGB2YCrCb),
                testing::Values(3, 4)
                )
            )
{
    Size sz = get<0>(GetParam());
    int mode = get<1>(GetParam());
    int ch = get<2>(GetParam());

    Mat src(sz, CV_8UC(ch));
    Mat dst(sz, CV_8UC3);

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode);

    SANITY_CHECK(dst, 1);
}

CV_ENUM(CvtInBGR565Type, CV_RGB2BGR565, CV_RGBA2BGR565, CV_BGR2BGR565, CV_BGRA2BGR565)

typedef std::tr1::tuple<Size, CvtInBGR565Type> Size_CvtInBGR565Type_t;
typedef perf::TestBaseWithParam<Size_CvtInBGR565Type_t> Size_CvtInBGR565Type;

PERF_TEST_P( Size_CvtInBGR565Type, cvtColor_toBGR565,
             testing::Combine
             (
                 testing::Values(TYPICAL_MAT_SIZES),
                 testing::ValuesIn(CvtInBGR565Type::all())
             )
           )
{
    Size sz = get<0>(GetParam());
    CvtInBGR565Type code = get<1>(GetParam());

    Mat src;
    if ( code == CV_RGB2BGR565 || code == CV_BGR2BGR565 )
        src.create(sz, CV_8UC3);
    else
        src.create(sz, CV_8UC4);

    randu(src, 0, 255);

    Mat dst;

    TEST_CYCLE() cvtColor( src, dst, code );

    SANITY_CHECK(dst);
}

CV_ENUM(CvtMode2, CV_RGB2BGR, CV_RGB2RGBA, CV_RGB2BGRA, CV_RGBA2RGB, CV_RGBA2BGR, CV_RGBA2BGRA)

typedef std::tr1::tuple<Size, CvtMode2> Size_CvtMode2_t;
typedef perf::TestBaseWithParam<Size_CvtMode2_t> Size_CvtMode2;

PERF_TEST_P( Size_CvtMode2, cvtColor_C3toC4_and_back,
             testing::Combine
             (
                 testing::Values(TYPICAL_MAT_SIZES),
                 testing::ValuesIn(CvtMode2::all())
             )
           )
{
    Size sz = get<0>(GetParam());
    CvtMode2 code = get<1>(GetParam());

    Mat src;
    if ( code == CV_RGB2BGR || code == CV_RGB2RGBA || code == CV_RGB2BGRA )
        src.create(sz, CV_8UC3);
    else
        src.create(sz, CV_8UC4);

    randu(src, 0, 255);

    Mat dst;
    TEST_CYCLE() cvtColor( src, dst, code );

    SANITY_CHECK(dst);
}<commit_msg>Added exhaustive perf test for cvtColor instead of several small tests<commit_after>#include "perf_precomp.hpp"

using namespace std;
using namespace cv;
using namespace perf;
using std::tr1::make_tuple;
using std::tr1::get;

//extra color conversions supported implicitly
enum
{
	CX_BGRA2HLS      = CV_COLORCVT_MAX + CV_BGR2HLS,
	CX_BGRA2HLS_FULL = CV_COLORCVT_MAX + CV_BGR2HLS_FULL,
	CX_BGRA2HSV      = CV_COLORCVT_MAX + CV_BGR2HSV,
	CX_BGRA2HSV_FULL = CV_COLORCVT_MAX + CV_BGR2HSV_FULL,
	CX_BGRA2Lab      = CV_COLORCVT_MAX + CV_BGR2Lab,
	CX_BGRA2Luv      = CV_COLORCVT_MAX + CV_BGR2Luv,
	CX_BGRA2XYZ      = CV_COLORCVT_MAX + CV_BGR2XYZ,
	CX_BGRA2YCrCb    = CV_COLORCVT_MAX + CV_BGR2YCrCb,
	CX_BGRA2YUV      = CV_COLORCVT_MAX + CV_BGR2YUV,
	CX_HLS2BGRA      = CV_COLORCVT_MAX + CV_HLS2BGR,
	CX_HLS2BGRA_FULL = CV_COLORCVT_MAX + CV_HLS2BGR_FULL,
	CX_HLS2RGBA      = CV_COLORCVT_MAX + CV_HLS2RGB,
	CX_HLS2RGBA_FULL = CV_COLORCVT_MAX + CV_HLS2RGB_FULL,
	CX_HSV2BGRA      = CV_COLORCVT_MAX + CV_HSV2BGR,
	CX_HSV2BGRA_FULL = CV_COLORCVT_MAX + CV_HSV2BGR_FULL,
	CX_HSV2RGBA      = CV_COLORCVT_MAX + CV_HSV2RGB,
	CX_HSV2RGBA_FULL = CV_COLORCVT_MAX + CV_HSV2RGB_FULL,
	CX_Lab2BGRA      = CV_COLORCVT_MAX + CV_Lab2BGR,
	CX_Lab2LBGRA     = CV_COLORCVT_MAX + CV_Lab2LBGR,
	CX_Lab2LRGBA     = CV_COLORCVT_MAX + CV_Lab2LRGB,
	CX_Lab2RGBA      = CV_COLORCVT_MAX + CV_Lab2RGB,
	CX_LBGRA2Lab     = CV_COLORCVT_MAX + CV_LBGR2Lab,
	CX_LBGRA2Luv     = CV_COLORCVT_MAX + CV_LBGR2Luv,
	CX_LRGBA2Lab     = CV_COLORCVT_MAX + CV_LRGB2Lab,
	CX_LRGBA2Luv     = CV_COLORCVT_MAX + CV_LRGB2Luv,
	CX_Luv2BGRA      = CV_COLORCVT_MAX + CV_Luv2BGR,
	CX_Luv2LBGRA     = CV_COLORCVT_MAX + CV_Luv2LBGR,
	CX_Luv2LRGBA     = CV_COLORCVT_MAX + CV_Luv2LRGB,
	CX_Luv2RGBA      = CV_COLORCVT_MAX + CV_Luv2RGB,
	CX_RGBA2HLS      = CV_COLORCVT_MAX + CV_RGB2HLS,
	CX_RGBA2HLS_FULL = CV_COLORCVT_MAX + CV_RGB2HLS_FULL,
	CX_RGBA2HSV      = CV_COLORCVT_MAX + CV_RGB2HSV,
	CX_RGBA2HSV_FULL = CV_COLORCVT_MAX + CV_RGB2HSV_FULL,
	CX_RGBA2Lab      = CV_COLORCVT_MAX + CV_RGB2Lab,
	CX_RGBA2Luv      = CV_COLORCVT_MAX + CV_RGB2Luv,
	CX_RGBA2XYZ      = CV_COLORCVT_MAX + CV_RGB2XYZ,
	CX_RGBA2YCrCb    = CV_COLORCVT_MAX + CV_RGB2YCrCb,
	CX_RGBA2YUV      = CV_COLORCVT_MAX + CV_RGB2YUV,
	CX_XYZ2BGRA      = CV_COLORCVT_MAX + CV_XYZ2BGR,
	CX_XYZ2RGBA      = CV_COLORCVT_MAX + CV_XYZ2RGB,
	CX_YCrCb2BGRA    = CV_COLORCVT_MAX + CV_YCrCb2BGR,
	CX_YCrCb2RGBA    = CV_COLORCVT_MAX + CV_YCrCb2RGB,
	CX_YUV2BGRA      = CV_COLORCVT_MAX + CV_YUV2BGR,
	CX_YUV2RGBA      = CV_COLORCVT_MAX + CV_YUV2RGB
};

CV_ENUM(CvtMode,
	CV_BayerBG2BGR, CV_BayerBG2BGR_VNG, CV_BayerBG2GRAY,
	CV_BayerGB2BGR, CV_BayerGB2BGR_VNG, CV_BayerGB2GRAY,
	CV_BayerGR2BGR, CV_BayerGR2BGR_VNG, CV_BayerGR2GRAY,
	CV_BayerRG2BGR, CV_BayerRG2BGR_VNG, CV_BayerRG2GRAY,

	CV_BGR2BGR555, CV_BGR2BGR565, CV_BGR2BGRA, CV_BGR2GRAY,
	CV_BGR2HLS, CV_BGR2HLS_FULL, CV_BGR2HSV, CV_BGR2HSV_FULL,
	CV_BGR2Lab, CV_BGR2Luv, CV_BGR2RGB, CV_BGR2RGBA, CV_BGR2XYZ,
	CV_BGR2YCrCb, CV_BGR2YUV, CV_BGR5552BGR, CV_BGR5552BGRA,

	CV_BGR5552GRAY, CV_BGR5552RGB, CV_BGR5552RGBA, CV_BGR5652BGR,
	CV_BGR5652BGRA, CV_BGR5652GRAY, CV_BGR5652RGB, CV_BGR5652RGBA,

	CV_BGRA2BGR, CV_BGRA2BGR555, CV_BGRA2BGR565, CV_BGRA2GRAY, CV_BGRA2RGBA,
	CX_BGRA2HLS, CX_BGRA2HLS_FULL, CX_BGRA2HSV, CX_BGRA2HSV_FULL,
	CX_BGRA2Lab, CX_BGRA2Luv, CX_BGRA2XYZ,
	CX_BGRA2YCrCb, CX_BGRA2YUV,

	CV_GRAY2BGR, CV_GRAY2BGR555, CV_GRAY2BGR565, CV_GRAY2BGRA,

	CV_HLS2BGR, CV_HLS2BGR_FULL, CV_HLS2RGB, CV_HLS2RGB_FULL,
	CX_HLS2BGRA, CX_HLS2BGRA_FULL, CX_HLS2RGBA, CX_HLS2RGBA_FULL,

	CV_HSV2BGR, CV_HSV2BGR_FULL, CV_HSV2RGB, CV_HSV2RGB_FULL,
	CX_HSV2BGRA, CX_HSV2BGRA_FULL, CX_HSV2RGBA,	CX_HSV2RGBA_FULL,

	CV_Lab2BGR, CV_Lab2LBGR, CV_Lab2LRGB, CV_Lab2RGB,
	CX_Lab2BGRA, CX_Lab2LBGRA, CX_Lab2LRGBA, CX_Lab2RGBA,

	CV_LBGR2Lab, CV_LBGR2Luv, CV_LRGB2Lab, CV_LRGB2Luv,
	CX_LBGRA2Lab, CX_LBGRA2Luv, CX_LRGBA2Lab, CX_LRGBA2Luv,

	CV_Luv2BGR, CV_Luv2LBGR, CV_Luv2LRGB, CV_Luv2RGB,
	CX_Luv2BGRA, CX_Luv2LBGRA, CX_Luv2LRGBA, CX_Luv2RGBA,

	CV_RGB2BGR555, CV_RGB2BGR565, CV_RGB2GRAY,
	CV_RGB2HLS, CV_RGB2HLS_FULL, CV_RGB2HSV, CV_RGB2HSV_FULL,
	CV_RGB2Lab, CV_RGB2Luv, CV_RGB2XYZ, CV_RGB2YCrCb, CV_RGB2YUV,

	CV_RGBA2BGR, CV_RGBA2BGR555, CV_RGBA2BGR565, CV_RGBA2GRAY,
	CX_RGBA2HLS, CX_RGBA2HLS_FULL, CX_RGBA2HSV, CX_RGBA2HSV_FULL,
	CX_RGBA2Lab, CX_RGBA2Luv, CX_RGBA2XYZ,
	CX_RGBA2YCrCb, CX_RGBA2YUV,

	CV_XYZ2BGR, CV_XYZ2RGB, CX_XYZ2BGRA, CX_XYZ2RGBA,

	CV_YCrCb2BGR, CV_YCrCb2RGB, CX_YCrCb2BGRA, CX_YCrCb2RGBA,
	CV_YUV2BGR, CV_YUV2RGB, CX_YUV2BGRA, CX_YUV2RGBA
	)

CV_ENUM(CvtMode2, CV_YUV420i2BGR, CV_YUV420i2BGRA, CV_YUV420i2RGB, CV_YUV420i2RGBA, CV_YUV420sp2BGR, CV_YUV420sp2BGRA, CV_YUV420sp2RGB, CV_YUV420sp2RGBA)

struct ChPair
{
	ChPair(int _scn, int _dcn): scn(_scn), dcn(_dcn) {}
	int scn, dcn;
};

ChPair getConversionInfo(int cvtMode)
{
	switch(cvtMode)
	{
	case CV_BayerBG2GRAY: case CV_BayerGB2GRAY:
	case CV_BayerGR2GRAY: case CV_BayerRG2GRAY:
		return ChPair(1,1);
	case CV_GRAY2BGR555: case CV_GRAY2BGR565:
		return ChPair(1,2);
	case CV_BayerBG2BGR: case CV_BayerBG2BGR_VNG:
	case CV_BayerGB2BGR: case CV_BayerGB2BGR_VNG:
	case CV_BayerGR2BGR: case CV_BayerGR2BGR_VNG:
	case CV_BayerRG2BGR: case CV_BayerRG2BGR_VNG:
	case CV_GRAY2BGR: case CV_YUV420i2BGR:
	case CV_YUV420i2RGB: case CV_YUV420sp2BGR:
	case CV_YUV420sp2RGB:
		return ChPair(1,3);
	case CV_GRAY2BGRA: case CV_YUV420i2BGRA:
	case CV_YUV420i2RGBA: case CV_YUV420sp2BGRA:
	case CV_YUV420sp2RGBA:
		return ChPair(1,4);
	case CV_BGR5552GRAY: case CV_BGR5652GRAY:
		return ChPair(2,1);
	case CV_BGR5552BGR: case CV_BGR5552RGB:
	case CV_BGR5652BGR: case CV_BGR5652RGB:
		return ChPair(2,3);
	case CV_BGR5552BGRA: case CV_BGR5552RGBA:
	case CV_BGR5652BGRA: case CV_BGR5652RGBA:
		return ChPair(2,4);
	case CV_BGR2GRAY: case CV_RGB2GRAY:
		return ChPair(3,1);
	case CV_BGR2BGR555: case CV_BGR2BGR565:
	case CV_RGB2BGR555: case CV_RGB2BGR565:
		return ChPair(3,2);
	case CV_BGR2HLS: case CV_BGR2HLS_FULL:
	case CV_BGR2HSV: case CV_BGR2HSV_FULL:
	case CV_BGR2Lab: case CV_BGR2Luv:
	case CV_BGR2RGB: case CV_BGR2XYZ:
	case CV_BGR2YCrCb: case CV_BGR2YUV:
	case CV_HLS2BGR: case CV_HLS2BGR_FULL:
	case CV_HLS2RGB: case CV_HLS2RGB_FULL:
	case CV_HSV2BGR: case CV_HSV2BGR_FULL:
	case CV_HSV2RGB: case CV_HSV2RGB_FULL:
	case CV_Lab2BGR: case CV_Lab2LBGR:
	case CV_Lab2LRGB: case CV_Lab2RGB:
	case CV_LBGR2Lab: case CV_LBGR2Luv:
	case CV_LRGB2Lab: case CV_LRGB2Luv:
	case CV_Luv2BGR: case CV_Luv2LBGR:
	case CV_Luv2LRGB: case CV_Luv2RGB:
	case CV_RGB2HLS: case CV_RGB2HLS_FULL:
	case CV_RGB2HSV: case CV_RGB2HSV_FULL:
	case CV_RGB2Lab: case CV_RGB2Luv:
	case CV_RGB2XYZ: case CV_RGB2YCrCb:
	case CV_RGB2YUV: case CV_XYZ2BGR:
	case CV_XYZ2RGB: case CV_YCrCb2BGR:
	case CV_YCrCb2RGB: case CV_YUV2BGR:
	case CV_YUV2RGB:
		return ChPair(3,3);
	case CV_BGR2BGRA: case CV_BGR2RGBA:
	case CX_HLS2BGRA: case CX_HLS2BGRA_FULL:
	case CX_HLS2RGBA: case CX_HLS2RGBA_FULL:
	case CX_HSV2BGRA: case CX_HSV2BGRA_FULL:
	case CX_HSV2RGBA: case CX_HSV2RGBA_FULL:
	case CX_Lab2BGRA: case CX_Lab2LBGRA:
	case CX_Lab2LRGBA: case CX_Lab2RGBA:
	case CX_Luv2BGRA: case CX_Luv2LBGRA:
	case CX_Luv2LRGBA: case CX_Luv2RGBA:
	case CX_XYZ2BGRA: case CX_XYZ2RGBA:
	case CX_YCrCb2BGRA: case CX_YCrCb2RGBA:
	case CX_YUV2BGRA: case CX_YUV2RGBA:
		return ChPair(3,4);
	case CV_BGRA2GRAY: case CV_RGBA2GRAY:
		return ChPair(4,1);
	case CV_BGRA2BGR555: case CV_BGRA2BGR565:
	case CV_RGBA2BGR555: case CV_RGBA2BGR565:
		return ChPair(4,2);
	case CV_BGRA2BGR: case CX_BGRA2HLS:
	case CX_BGRA2HLS_FULL: case CX_BGRA2HSV:
	case CX_BGRA2HSV_FULL: case CX_BGRA2Lab:
	case CX_BGRA2Luv: case CX_BGRA2XYZ:
	case CX_BGRA2YCrCb: case CX_BGRA2YUV:
	case CX_LBGRA2Lab: case CX_LBGRA2Luv:
	case CX_LRGBA2Lab: case CX_LRGBA2Luv:
	case CV_RGBA2BGR: case CX_RGBA2HLS:
	case CX_RGBA2HLS_FULL: case CX_RGBA2HSV:
	case CX_RGBA2HSV_FULL: case CX_RGBA2Lab:
	case CX_RGBA2Luv: case CX_RGBA2XYZ:
	case CX_RGBA2YCrCb: case CX_RGBA2YUV:
		return ChPair(4,3);
	case CV_BGRA2RGBA:
		return ChPair(4,4);
	default:
		ADD_FAILURE() << "Unknown conversion type";
		break;
	};
	return ChPair(0,0);
}

typedef std::tr1::tuple<Size, CvtMode> Size_CvtMode_t;
typedef perf::TestBaseWithParam<Size_CvtMode_t> Size_CvtMode;

PERF_TEST_P(Size_CvtMode, cvtColor8u,
            testing::Combine(
                testing::Values(TYPICAL_MAT_SIZES),
                testing::ValuesIn(CvtMode::all())
                )
            )
{
	Size sz = get<0>(GetParam());
	int mode = get<1>(GetParam());
	ChPair ch = getConversionInfo(mode);
	mode %= CV_COLORCVT_MAX;

	Mat src(sz, CV_8UC(ch.scn));
	Mat dst(sz, CV_8UC(ch.dcn));

	declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode, ch.dcn);

    SANITY_CHECK(dst, 1);
}

typedef std::tr1::tuple<Size, CvtMode2> Size_CvtMode2_t;
typedef perf::TestBaseWithParam<Size_CvtMode2_t> Size_CvtMode2;

PERF_TEST_P(Size_CvtMode2, cvtColorYUV420,
            testing::Combine(
                testing::Values(szVGA, sz720p, sz1080p, Size(130, 60)),
                testing::ValuesIn(CvtMode2::all())
                )
            )
{
    Size sz = get<0>(GetParam());
	int mode = get<1>(GetParam());
	ChPair ch = getConversionInfo(mode);

    Mat src(sz.height + sz.height / 2, sz.width, CV_8UC(ch.scn));
    Mat dst(sz, CV_8UC(ch.dcn));

    declare.in(src, WARMUP_RNG).out(dst);

    TEST_CYCLE() cvtColor(src, dst, mode, ch.dcn);

    SANITY_CHECK(dst, 1);
}<|endoftext|>


<commit_before>#include "ghost/timing.h"
#include "ghost/util.h"

#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <numeric>
#include <algorithm>

using namespace std;

typedef struct
{
    /**
     * @brief User-defined callback function to compute a region's performance.
     */
    ghost_compute_performance_func_t perfFunc;
    /**
     * @brief Argument to perfFunc.
     */
    void *perfFuncArg;
    /**
     * @brief The unit of performance.
     */
    const char *perfUnit;
}
ghost_timing_perfFunc_t;

/**
 * @brief Region timing accumulator
 */
typedef struct
{
    /**
     * @brief The runtimes of this region.
     */
    vector<double> times;
    /**
     * @brief The last start time of this region.
     */
    double start;

    vector<ghost_timing_perfFunc_t> perfFuncs;
}
ghost_timing_region_accu_t;

static map<string,ghost_timing_region_accu_t> timings;

void ghost_timing_tick(const char *tag)
{
    double start = 0.;
    ghost_timing_wc(&start);

    timings[tag].start = start;
}

void ghost_timing_tock(const char *tag)
{
    double end;
    ghost_timing_wc(&end);
    ghost_timing_region_accu_t *ti = &timings[string(tag)];
    ti->times.push_back(end-ti->start);
}

void ghost_timing_set_perfFunc(const char *tag, ghost_compute_performance_func_t func, void *arg, size_t sizeofarg, const char *unit)
{
    ghost_timing_perfFunc_t pf;
    pf.perfFunc = func;
    pf.perfUnit = unit;

    for (std::vector<ghost_timing_perfFunc_t>::iterator it = timings[tag].perfFuncs.begin();
            it != timings[tag].perfFuncs.end(); ++it) {
        if (it->perfFunc == func && !strcmp(it->perfUnit,unit)) {
            return;
        }
    }

    ghost_malloc((void **)&(pf.perfFuncArg),sizeofarg);
    memcpy(pf.perfFuncArg,arg,sizeofarg);
    timings[tag].perfFuncs.push_back(pf);
}

ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag)
{
    ghost_timing_region_accu_t ti = timings[string(tag)];
    if (!ti.times.size()) {
        *ri = NULL;
        return GHOST_SUCCESS;
    }

    ghost_error_t ret = GHOST_SUCCESS;
    GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret);
    (*ri)->nCalls =  ti.times.size();
    (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end());
    (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end());
    (*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.);
    (*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls;
    if ((*ri)->nCalls > 10) {
        (*ri)->skip10avgTime = accumulate(ti.times.begin()+10,ti.times.end(),0.)/((*ri)->nCalls-10);
    } else {
        (*ri)->skip10avgTime = 0.;
    }

    GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret);
    memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double));

    goto out;

err:
    ERROR_LOG("Freeing region info");
    if (*ri) {
        free((*ri)->times); (*ri)->times = NULL;
    }
    free(*ri); (*ri) = NULL;
out:

    return ret;
}

void ghost_timing_region_destroy(ghost_timing_region_t * ri)
{
    if (ri) {
        free(ri->times); ri->times = NULL;
    }
    free(ri);
}

ghost_error_t ghost_timing_summarystring(char **str)
{
    stringstream buffer;
    map<string,ghost_timing_region_accu_t>::iterator iter;
    vector<ghost_timing_perfFunc_t>::iterator pf_iter;

    size_t maxRegionLen = 0;
    size_t maxCallsLen = 0;
    size_t maxUnitLen = 0;

    stringstream tmp;
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        int regLen = 0;
        for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
            if (pf_iter->perfUnit) {
                tmp << iter->first.length();
                maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen);
                regLen = strlen(pf_iter->perfUnit);
                tmp.str("");
            }

        }
        tmp << regLen+iter->first.length();
        maxRegionLen = max(regLen+iter->first.length(),maxRegionLen);
        tmp.str("");

        tmp << iter->second.times.size();
        maxCallsLen = max(maxCallsLen,tmp.str().length());
        tmp.str("");

    }
    if (maxCallsLen < 5) {
        maxCallsLen = 5;
    }

    buffer << left << setw(maxRegionLen+4) << "Region" << right << " | ";
    buffer << setw(maxCallsLen+3) << "Calls | ";
    buffer << "   t_min | ";
    buffer << "   t_max | ";
    buffer << "   t_avg | ";
    buffer << "   t_s10 | ";
    buffer << "   t_acc" << endl;
    buffer << string(maxRegionLen+maxCallsLen+7+5*11,'-') << endl;

    buffer.precision(2);
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        ghost_timing_region_t *region = NULL;
        ghost_timing_region_create(&region,iter->first.c_str());

        if (region) {
            buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) <<
                region->nCalls << " | " <<
                region->minTime << " | " <<
                region->maxTime << " | " <<
                region->avgTime << " | " <<
                region->skip10avgTime << " | " <<
                region->accTime << endl;

            ghost_timing_region_destroy(region);
        }
    }

    int printed = 0;
    buffer.precision(2);
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        if (!printed) {
            buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | ";
            buffer << setw(maxCallsLen+3) << "Calls | ";
            buffer << "   P_max | ";
            buffer << "   P_min | ";
            buffer << "   P_avg | ";
            buffer << "P_skip10" << endl;;
            buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl;
        }
        printed = 1;

        ghost_timing_region_t *region = NULL;
        ghost_timing_region_create(&region,iter->first.c_str());

        if (region) {
            for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
                ghost_compute_performance_func_t pf = pf_iter->perfFunc;
                void *pfa = pf_iter->perfFuncArg;

                double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.;
                int err = pf(&P_min,region->maxTime,pfa);
                if (err) {
                    ERROR_LOG("Error in calling performance computation callback!");
                }
                err = pf(&P_max,region->minTime,pfa);
                if (err) {
                    ERROR_LOG("Error in calling performance computation callback!");
                }
                err = pf(&P_avg,region->avgTime,pfa);
                if (err) {
                    ERROR_LOG("Error in calling performance computation callback!");
                }
                if (region->nCalls > 10) {
                    err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa);
                    if (err) {
                        ERROR_LOG("Error in calling performance computation callback!");
                    }
                }

                buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first <<
                    right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) <<
                    region->nCalls << " | " <<
                    P_max << " | " <<
                    P_min << " | " <<
                    P_avg << " | " <<
                    P_skip10 << endl;
            }
            ghost_timing_region_destroy(region);
        }
    }

    // clear all timings to prevent memory leaks
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
            if( pf_iter->perfFuncArg != NULL )
                free(pf_iter->perfFuncArg);
            pf_iter->perfFuncArg = NULL;
        }
    }
    timings.clear();

    GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1));
    strcpy(*str,buffer.str().c_str());

    return GHOST_SUCCESS;
}
<commit_msg>don't fail if the tag is NULL<commit_after>#include "ghost/timing.h"
#include "ghost/util.h"

#include <map>
#include <vector>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <numeric>
#include <algorithm>

using namespace std;

typedef struct
{
    /**
     * @brief User-defined callback function to compute a region's performance.
     */
    ghost_compute_performance_func_t perfFunc;
    /**
     * @brief Argument to perfFunc.
     */
    void *perfFuncArg;
    /**
     * @brief The unit of performance.
     */
    const char *perfUnit;
}
ghost_timing_perfFunc_t;

/**
 * @brief Region timing accumulator
 */
typedef struct
{
    /**
     * @brief The runtimes of this region.
     */
    vector<double> times;
    /**
     * @brief The last start time of this region.
     */
    double start;

    vector<ghost_timing_perfFunc_t> perfFuncs;
}
ghost_timing_region_accu_t;

static map<string,ghost_timing_region_accu_t> timings;

void ghost_timing_tick(const char *tag)
{
    double start = 0.;
    ghost_timing_wc(&start);

    timings[tag].start = start;
}

void ghost_timing_tock(const char *tag)
{
    double end;
    ghost_timing_wc(&end);
    ghost_timing_region_accu_t *ti = &timings[string(tag)];
    ti->times.push_back(end-ti->start);
}

void ghost_timing_set_perfFunc(const char *tag, ghost_compute_performance_func_t func, void *arg, size_t sizeofarg, const char *unit)
{
    if (!tag) {
        WARNING_LOG("Empty tag! This should not have happened...");
        return;
    }

    ghost_timing_perfFunc_t pf;
    pf.perfFunc = func;
    pf.perfUnit = unit;

    for (std::vector<ghost_timing_perfFunc_t>::iterator it = timings[tag].perfFuncs.begin();
            it != timings[tag].perfFuncs.end(); ++it) {
        if (it->perfFunc == func && !strcmp(it->perfUnit,unit)) {
            return;
        }
    }

    ghost_malloc((void **)&(pf.perfFuncArg),sizeofarg);
    memcpy(pf.perfFuncArg,arg,sizeofarg);
    timings[tag].perfFuncs.push_back(pf);
}

ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag)
{
    ghost_timing_region_accu_t ti = timings[string(tag)];
    if (!ti.times.size()) {
        *ri = NULL;
        return GHOST_SUCCESS;
    }

    ghost_error_t ret = GHOST_SUCCESS;
    GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret);
    (*ri)->nCalls =  ti.times.size();
    (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end());
    (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end());
    (*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.);
    (*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls;
    if ((*ri)->nCalls > 10) {
        (*ri)->skip10avgTime = accumulate(ti.times.begin()+10,ti.times.end(),0.)/((*ri)->nCalls-10);
    } else {
        (*ri)->skip10avgTime = 0.;
    }

    GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret);
    memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double));

    goto out;

err:
    ERROR_LOG("Freeing region info");
    if (*ri) {
        free((*ri)->times); (*ri)->times = NULL;
    }
    free(*ri); (*ri) = NULL;
out:

    return ret;
}

void ghost_timing_region_destroy(ghost_timing_region_t * ri)
{
    if (ri) {
        free(ri->times); ri->times = NULL;
    }
    free(ri);
}

ghost_error_t ghost_timing_summarystring(char **str)
{
    stringstream buffer;
    map<string,ghost_timing_region_accu_t>::iterator iter;
    vector<ghost_timing_perfFunc_t>::iterator pf_iter;

    size_t maxRegionLen = 0;
    size_t maxCallsLen = 0;
    size_t maxUnitLen = 0;

    stringstream tmp;
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        int regLen = 0;
        for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
            if (pf_iter->perfUnit) {
                tmp << iter->first.length();
                maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen);
                regLen = strlen(pf_iter->perfUnit);
                tmp.str("");
            }

        }
        tmp << regLen+iter->first.length();
        maxRegionLen = max(regLen+iter->first.length(),maxRegionLen);
        tmp.str("");

        tmp << iter->second.times.size();
        maxCallsLen = max(maxCallsLen,tmp.str().length());
        tmp.str("");

    }
    if (maxCallsLen < 5) {
        maxCallsLen = 5;
    }

    buffer << left << setw(maxRegionLen+4) << "Region" << right << " | ";
    buffer << setw(maxCallsLen+3) << "Calls | ";
    buffer << "   t_min | ";
    buffer << "   t_max | ";
    buffer << "   t_avg | ";
    buffer << "   t_s10 | ";
    buffer << "   t_acc" << endl;
    buffer << string(maxRegionLen+maxCallsLen+7+5*11,'-') << endl;

    buffer.precision(2);
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        ghost_timing_region_t *region = NULL;
        ghost_timing_region_create(&region,iter->first.c_str());

        if (region) {
            buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) <<
                region->nCalls << " | " <<
                region->minTime << " | " <<
                region->maxTime << " | " <<
                region->avgTime << " | " <<
                region->skip10avgTime << " | " <<
                region->accTime << endl;

            ghost_timing_region_destroy(region);
        }
    }

    int printed = 0;
    buffer.precision(2);
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        if (!printed) {
            buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | ";
            buffer << setw(maxCallsLen+3) << "Calls | ";
            buffer << "   P_max | ";
            buffer << "   P_min | ";
            buffer << "   P_avg | ";
            buffer << "P_skip10" << endl;;
            buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl;
        }
        printed = 1;

        ghost_timing_region_t *region = NULL;
        ghost_timing_region_create(&region,iter->first.c_str());

        if (region) {
            for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
                ghost_compute_performance_func_t pf = pf_iter->perfFunc;
                void *pfa = pf_iter->perfFuncArg;

                double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.;
                int err = pf(&P_min,region->maxTime,pfa);
                if (err) {
                    ERROR_LOG("Error in calling performance computation callback!");
                }
                err = pf(&P_max,region->minTime,pfa);
                if (err) {
                    ERROR_LOG("Error in calling performance computation callback!");
                }
                err = pf(&P_avg,region->avgTime,pfa);
                if (err) {
                    ERROR_LOG("Error in calling performance computation callback!");
                }
                if (region->nCalls > 10) {
                    err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa);
                    if (err) {
                        ERROR_LOG("Error in calling performance computation callback!");
                    }
                }

                buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first <<
                    right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) <<
                    region->nCalls << " | " <<
                    P_max << " | " <<
                    P_min << " | " <<
                    P_avg << " | " <<
                    P_skip10 << endl;
            }
            ghost_timing_region_destroy(region);
        }
    }

    // clear all timings to prevent memory leaks
    for (iter = timings.begin(); iter != timings.end(); ++iter) {
        for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) {
            if( pf_iter->perfFuncArg != NULL )
                free(pf_iter->perfFuncArg);
            pf_iter->perfFuncArg = NULL;
        }
    }
    timings.clear();

    GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1));
    strcpy(*str,buffer.str().c_str());

    return GHOST_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef SPROUT_TOKENS_HEADER
#define SPROUT_TOKENS_HEADER

#include <vector>
#include <sstream>
#include <iostream>

template <class Type, class Value>
struct Token {
    Type type;
    Value value;

    Token() :
        type(),
        value()
    {
    }

    Token(const Type& type) :
        type(type),
        value()
    {
    }

    Token(const Type& type, const Value& value) :
        type(type),
        value(value)
    {
    }
};

template <class Type, class Value>
struct Node {
    Token<Type, Value> token;
    std::vector<Node<Type, Value>> _children;

    Node() :
        Node(Token<Type, Value>())
    {
    }

    Node(const Token<Type, Value>& token) :
        token(token)
    {
    }

    Node(const Token<Type, Value>& token, std::vector<Node<Type, Value>> children) :
        token(token),
        _children(children)
    {
    }

    Node(const Type& type, const Value& value) :
        token(Token<Type, Value>(type, value))
    {
    }

    const Type& type() const
    {
        return token.type;
    }

    std::string typeName() const
    {
        std::stringstream str;
        str << type();
        return str.str();
    }

    const Value& value() const
    {
        return token.value;
    }

    void setValue(const Value& value)
    {
        token.value = value;
    }

    std::string valueString() const
    {
        std::stringstream str;
        str << value();
        return str.str();
    }

    void insert(const Node<Type, Value>& child)
    {
        _children.push_back(child);
    }

    const Node<Type, Value>& operator[](const int index) const
    {
        return _children[index];
    }

    Node<Type, Value>& operator[](const int index)
    {
        return _children[index];
    }

    Node<Type, Value>& operator=(const Node<Type, Value>& other)
    {
        if (this == &other) {
            return *this;
        }
        token = other.token;
        _children = other._children;
        return *this;
    }

    const std::vector<Node<Type, Value>>& children() const
    {
        return _children;
    }

    std::vector<Node<Type, Value>>& children()
    {
        return _children;
    }

    void dump(std::stringstream& str, const std::string& indent) const
    {
        str << typeName();
        if (!value().isNull()) {
            str << ":" << valueString();
        }
        if (!_children.empty()) {
            auto childIndent = indent + "    ";
            str << " [\n" << childIndent;
            for (unsigned int i = 0; i < _children.size(); ++i) {
                if (i > 0) {
                    str << ",\n" << childIndent;
                }
                _children[i].dump(str, childIndent);
            }
            str << "\n" << indent << "]";
        }
    }

    std::string dump() const
    {
        std::stringstream str;
        dump(str, "");
        return str.str();
    }
};

#endif // SPROUT_TOKENS_HEADER

// vim: set ts=4 sw=4 :
<commit_msg>Added Node::setType<commit_after>#ifndef SPROUT_TOKENS_HEADER
#define SPROUT_TOKENS_HEADER

#include <vector>
#include <sstream>
#include <iostream>

template <class Type, class Value>
struct Token {
    Type type;
    Value value;

    Token() :
        type(),
        value()
    {
    }

    Token(const Type& type) :
        type(type),
        value()
    {
    }

    Token(const Type& type, const Value& value) :
        type(type),
        value(value)
    {
    }
};

template <class Type, class Value>
struct Node {
    Token<Type, Value> token;
    std::vector<Node<Type, Value>> _children;

    Node() :
        Node(Token<Type, Value>())
    {
    }

    Node(const Token<Type, Value>& token) :
        token(token)
    {
    }

    Node(const Token<Type, Value>& token, std::vector<Node<Type, Value>> children) :
        token(token),
        _children(children)
    {
    }

    Node(const Type& type, const Value& value) :
        token(Token<Type, Value>(type, value))
    {
    }

    const Type& type() const
    {
        return token.type;
    }

    void setType(const Type& type)
    {
        token.type = type;
    }

    std::string typeName() const
    {
        std::stringstream str;
        str << type();
        return str.str();
    }

    const Value& value() const
    {
        return token.value;
    }

    void setValue(const Value& value)
    {
        token.value = value;
    }

    std::string valueString() const
    {
        std::stringstream str;
        str << value();
        return str.str();
    }

    void insert(const Node<Type, Value>& child)
    {
        _children.push_back(child);
    }

    const Node<Type, Value>& operator[](const int index) const
    {
        return _children[index];
    }

    Node<Type, Value>& operator[](const int index)
    {
        return _children[index];
    }

    Node<Type, Value>& operator=(const Node<Type, Value>& other)
    {
        if (this == &other) {
            return *this;
        }
        token = other.token;
        _children = other._children;
        return *this;
    }

    const std::vector<Node<Type, Value>>& children() const
    {
        return _children;
    }

    std::vector<Node<Type, Value>>& children()
    {
        return _children;
    }

    void dump(std::stringstream& str, const std::string& indent) const
    {
        str << typeName();
        if (!value().isNull()) {
            str << ":" << valueString();
        }
        if (!_children.empty()) {
            auto childIndent = indent + "    ";
            str << " [\n" << childIndent;
            for (unsigned int i = 0; i < _children.size(); ++i) {
                if (i > 0) {
                    str << ",\n" << childIndent;
                }
                _children[i].dump(str, childIndent);
            }
            str << "\n" << indent << "]";
        }
    }

    std::string dump() const
    {
        std::stringstream str;
        dump(str, "");
        return str.str();
    }
};

#endif // SPROUT_TOKENS_HEADER

// vim: set ts=4 sw=4 :
<|endoftext|>


<commit_before>// Copyright 2012 the V8 project authors. All rights reserved.
// 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.

#include <string.h>

#include "v8.h"
#include "zone-inl.h"

namespace v8 {
namespace internal {

// Segments represent chunks of memory: They have starting address
// (encoded in the this pointer) and a size in bytes. Segments are
// chained together forming a LIFO structure with the newest segment
// available as segment_head_. Segments are allocated using malloc()
// and de-allocated using free().

class Segment {
 public:
  void Initialize(Segment* next, int size) {
    next_ = next;
    size_ = size;
  }

  Segment* next() const { return next_; }
  void clear_next() { next_ = NULL; }

  int size() const { return size_; }
  int capacity() const { return size_ - sizeof(Segment); }

  Address start() const { return address(sizeof(Segment)); }
  Address end() const { return address(size_); }

 private:
  // Computes the address of the nth byte in this segment.
  Address address(int n) const {
    return Address(this) + n;
  }

  Segment* next_;
  int size_;
};

Zone::Zone(Isolate* isolate)
    : allocation_size_(0),
      segment_bytes_allocated_(0),
      position_(0),
      limit_(0),
      segment_head_(NULL),
      isolate_(isolate) {
}

Zone::~Zone() {
  DeleteAll();
  DeleteKeptSegment();

  ASSERT(segment_bytes_allocated_ == 0);
}

void Zone::DeleteAll() {
#ifdef DEBUG
  // Constant byte value used for zapping dead memory in debug mode.
  static const unsigned char kZapDeadByte = 0xcd;
#endif

  // Find a segment with a suitable size to keep around.
  Segment* keep = NULL;
  // Traverse the chained list of segments, zapping (in debug mode)
  // and freeing every segment except the one we wish to keep.
  for (Segment* current = segment_head_; current != NULL; ) {
    Segment* next = current->next();
    if (keep == NULL && current->size() <= kMaximumKeptSegmentSize) {
      // Unlink the segment we wish to keep from the list.
      keep = current;
      keep->clear_next();
    } else {
      int size = current->size();
#ifdef DEBUG
      // Zap the entire current segment (including the header).
      memset(current, kZapDeadByte, size);
#endif
      DeleteSegment(current, size);
    }
    current = next;
  }

  // If we have found a segment we want to keep, we must recompute the
  // variables 'position' and 'limit' to prepare for future allocate
  // attempts. Otherwise, we must clear the position and limit to
  // force a new segment to be allocated on demand.
  if (keep != NULL) {
    Address start = keep->start();
    position_ = RoundUp(start, kAlignment);
    limit_ = keep->end();
#ifdef DEBUG
    // Zap the contents of the kept segment (but not the header).
    memset(start, kZapDeadByte, keep->capacity());
#endif
  } else {
    position_ = limit_ = 0;
  }

  // Update the head segment to be the kept segment (if any).
  segment_head_ = keep;
}

void Zone::DeleteKeptSegment() {
#ifdef DEBUG
  // Constant byte value used for zapping dead memory in debug mode.
  static const unsigned char kZapDeadByte = 0xcd;
#endif

  ASSERT(segment_head_ == NULL || segment_head_->next() == NULL);
  if (segment_head_ != NULL) {
    int size = segment_head_->size();
#ifdef DEBUG
    // Zap the entire kept segment (including the header).
    memset(segment_head_, kZapDeadByte, size);
#endif
    DeleteSegment(segment_head_, size);
    segment_head_ = NULL;
  }

  ASSERT(segment_bytes_allocated_ == 0);
}

// Creates a new segment, sets it size, and pushes it to the front
// of the segment chain. Returns the new segment.
Segment* Zone::NewSegment(int size) {
  Segment* result = reinterpret_cast<Segment*>(Malloced::New(size));
  adjust_segment_bytes_allocated(size);
  if (result != NULL) {
    result->Initialize(segment_head_, size);
    segment_head_ = result;
  }
  return result;
}

// Deletes the given segment. Does not touch the segment chain.
void Zone::DeleteSegment(Segment* segment, int size) {
  adjust_segment_bytes_allocated(-size);
  Malloced::Delete(segment);
}

Address Zone::NewExpand(int size) {
  // Make sure the requested size is already properly aligned and that
  // there isn't enough room in the Zone to satisfy the request.
  ASSERT(size == RoundDown(size, kAlignment));
  ASSERT(size > limit_ - position_);

  // Compute the new segment size. We use a 'high water mark'
  // strategy, where we increase the segment size every time we expand
  // except that we employ a maximum segment size when we delete. This
  // is to avoid excessive malloc() and free() overhead.
  Segment* head = segment_head_;
  int old_size = (head == NULL) ? 0 : head->size();
  static const int kSegmentOverhead = sizeof(Segment) + kAlignment;
  int new_size_no_overhead = size + (old_size << 1);
  int new_size = kSegmentOverhead + new_size_no_overhead;
  // Guard against integer overflow.
  if (new_size_no_overhead < size || new_size < kSegmentOverhead) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }
  if (new_size < kMinimumSegmentSize) {
    new_size = kMinimumSegmentSize;
  } else if (new_size > kMaximumSegmentSize) {
    // Limit the size of new segments to avoid growing the segment size
    // exponentially, thus putting pressure on contiguous virtual address space.
    // All the while making sure to allocate a segment large enough to hold the
    // requested size.
    new_size = Max(kSegmentOverhead + size, kMaximumSegmentSize);
  }
  Segment* segment = NewSegment(new_size);
  if (segment == NULL) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }

  // Recompute 'top' and 'limit' based on the new segment.
  Address result = RoundUp(segment->start(), kAlignment);
  position_ = result + size;
  // Check for address overflow.
  if (position_ < result) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }
  limit_ = segment->end();
  ASSERT(position_ <= limit_);
  return result;
}

} }  // namespace v8::internal
<commit_msg>Use unsigned integer arithmetic in Zone::NewExpand.<commit_after>// Copyright 2012 the V8 project authors. All rights reserved.
// 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.

#include <string.h>

#include "v8.h"
#include "zone-inl.h"

namespace v8 {
namespace internal {

// Segments represent chunks of memory: They have starting address
// (encoded in the this pointer) and a size in bytes. Segments are
// chained together forming a LIFO structure with the newest segment
// available as segment_head_. Segments are allocated using malloc()
// and de-allocated using free().

class Segment {
 public:
  void Initialize(Segment* next, int size) {
    next_ = next;
    size_ = size;
  }

  Segment* next() const { return next_; }
  void clear_next() { next_ = NULL; }

  int size() const { return size_; }
  int capacity() const { return size_ - sizeof(Segment); }

  Address start() const { return address(sizeof(Segment)); }
  Address end() const { return address(size_); }

 private:
  // Computes the address of the nth byte in this segment.
  Address address(int n) const {
    return Address(this) + n;
  }

  Segment* next_;
  int size_;
};

Zone::Zone(Isolate* isolate)
    : allocation_size_(0),
      segment_bytes_allocated_(0),
      position_(0),
      limit_(0),
      segment_head_(NULL),
      isolate_(isolate) {
}

Zone::~Zone() {
  DeleteAll();
  DeleteKeptSegment();

  ASSERT(segment_bytes_allocated_ == 0);
}

void Zone::DeleteAll() {
#ifdef DEBUG
  // Constant byte value used for zapping dead memory in debug mode.
  static const unsigned char kZapDeadByte = 0xcd;
#endif

  // Find a segment with a suitable size to keep around.
  Segment* keep = NULL;
  // Traverse the chained list of segments, zapping (in debug mode)
  // and freeing every segment except the one we wish to keep.
  for (Segment* current = segment_head_; current != NULL; ) {
    Segment* next = current->next();
    if (keep == NULL && current->size() <= kMaximumKeptSegmentSize) {
      // Unlink the segment we wish to keep from the list.
      keep = current;
      keep->clear_next();
    } else {
      int size = current->size();
#ifdef DEBUG
      // Zap the entire current segment (including the header).
      memset(current, kZapDeadByte, size);
#endif
      DeleteSegment(current, size);
    }
    current = next;
  }

  // If we have found a segment we want to keep, we must recompute the
  // variables 'position' and 'limit' to prepare for future allocate
  // attempts. Otherwise, we must clear the position and limit to
  // force a new segment to be allocated on demand.
  if (keep != NULL) {
    Address start = keep->start();
    position_ = RoundUp(start, kAlignment);
    limit_ = keep->end();
#ifdef DEBUG
    // Zap the contents of the kept segment (but not the header).
    memset(start, kZapDeadByte, keep->capacity());
#endif
  } else {
    position_ = limit_ = 0;
  }

  // Update the head segment to be the kept segment (if any).
  segment_head_ = keep;
}

void Zone::DeleteKeptSegment() {
#ifdef DEBUG
  // Constant byte value used for zapping dead memory in debug mode.
  static const unsigned char kZapDeadByte = 0xcd;
#endif

  ASSERT(segment_head_ == NULL || segment_head_->next() == NULL);
  if (segment_head_ != NULL) {
    int size = segment_head_->size();
#ifdef DEBUG
    // Zap the entire kept segment (including the header).
    memset(segment_head_, kZapDeadByte, size);
#endif
    DeleteSegment(segment_head_, size);
    segment_head_ = NULL;
  }

  ASSERT(segment_bytes_allocated_ == 0);
}

// Creates a new segment, sets it size, and pushes it to the front
// of the segment chain. Returns the new segment.
Segment* Zone::NewSegment(int size) {
  Segment* result = reinterpret_cast<Segment*>(Malloced::New(size));
  adjust_segment_bytes_allocated(size);
  if (result != NULL) {
    result->Initialize(segment_head_, size);
    segment_head_ = result;
  }
  return result;
}

// Deletes the given segment. Does not touch the segment chain.
void Zone::DeleteSegment(Segment* segment, int size) {
  adjust_segment_bytes_allocated(-size);
  Malloced::Delete(segment);
}

Address Zone::NewExpand(int size) {
  // Make sure the requested size is already properly aligned and that
  // there isn't enough room in the Zone to satisfy the request.
  ASSERT(size == RoundDown(size, kAlignment));
  ASSERT(size > limit_ - position_);

  // Compute the new segment size. We use a 'high water mark'
  // strategy, where we increase the segment size every time we expand
  // except that we employ a maximum segment size when we delete. This
  // is to avoid excessive malloc() and free() overhead.
  Segment* head = segment_head_;
  const size_t old_size = (head == NULL) ? 0 : head->size();
  static const size_t kSegmentOverhead = sizeof(Segment) + kAlignment;
  const size_t new_size_no_overhead = size + (old_size << 1);
  size_t new_size = kSegmentOverhead + new_size_no_overhead;
  const size_t min_new_size = kSegmentOverhead + static_cast<size_t>(size);
  // Guard against integer overflow.
  if (new_size_no_overhead < static_cast<size_t>(size) ||
      new_size < static_cast<size_t>(kSegmentOverhead)) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }
  if (new_size < static_cast<size_t>(kMinimumSegmentSize)) {
    new_size = kMinimumSegmentSize;
  } else if (new_size > static_cast<size_t>(kMaximumSegmentSize)) {
    // Limit the size of new segments to avoid growing the segment size
    // exponentially, thus putting pressure on contiguous virtual address space.
    // All the while making sure to allocate a segment large enough to hold the
    // requested size.
    new_size = Max(min_new_size, static_cast<size_t>(kMaximumSegmentSize));
  }
  if (new_size > INT_MAX) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }
  Segment* segment = NewSegment(static_cast<int>(new_size));
  if (segment == NULL) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }

  // Recompute 'top' and 'limit' based on the new segment.
  Address result = RoundUp(segment->start(), kAlignment);
  position_ = result + size;
  // Check for address overflow.
  // (Should not happen since the segment is guaranteed to accomodate
  // size bytes + header and alignment padding)
  if (reinterpret_cast<uintptr_t>(position_)
      < reinterpret_cast<uintptr_t>(result)) {
    V8::FatalProcessOutOfMemory("Zone");
    return NULL;
  }
  limit_ = segment->end();
  ASSERT(position_ <= limit_);
  return result;
}

} }  // namespace v8::internal
<|endoftext|>


<commit_before>#ifdef USE_MMAP

#include "File-Vector/file_vector.hpp"

class stream_range {
    file_vector<char> file;

public:
    using iterator = file_vector<char>::const_iterator;

    iterator const last;
    iterator const first;

    stream_range(stream_range const&) = delete;

    stream_range(char const* name) : file(name), first(file.cbegin()), last(file.cend()) {
        cout << "using mmap" << endl;
    }
};

#else

#include <streambuf>
#include <fstream>

class stream_range {
    fstream file;
    streambuf *rd;
    streamoff pos;

public:
    class iterator {
        friend class stream_range;

        iterator(stream_range *r, streamoff pos) : r(r), pos(pos), sym(r->rd->sgetc()) {
            r->pos = pos;
        }

        stream_range *r;
        streamoff pos;
        int sym;

    public:
        int operator* () const {
            return sym;
        }

        bool operator== (iterator const& i) const {
            return (r == i.r) && (sym == i.sym) && (pos == i.pos);
        }

        bool operator!= (iterator const& i) const {
            return (r != i.r) || (sym != i.sym) || (pos != i.pos);
        }

        streamoff operator- (iterator const& i) const {
            return pos - i.pos;
        }

        iterator& operator++ () {
            if (r->pos != pos) {
                r->pos = r->rd->pubseekoff(++pos, ios_base::beg);
                sym = r->rd->sgetc();
            } else {
                r->pos = ++pos;
                sym = r->rd->snextc();
            }
            return *this;
        }

        iterator& operator-- () {
            --pos;
            if (r->pos != pos) {
                r->pos = r->rd->pubseekoff(pos, ios_base::beg);
            }
            sym = r->rd->sgetc();
            return *this;
        }

        iterator& operator= (iterator const& i) {
            r = i.r;
            pos = i.pos;
            sym = i.sym;
            return *this;
        }
    };

    friend class stream_range::iterator;

    iterator const last;
    iterator const first;

    stream_range(stream_range const&) = delete;

    stream_range(char const* name) : file(name, ios_base::in),
        rd(file.rdbuf()), pos(0),
        last(this, rd->pubseekoff(0, ios_base::end)),
        first(this, rd->pubseekoff(0, ios_base::beg)
    ) {
        cout << "using fstream" << endl;
        if (!file.is_open()) {
            throw runtime_error("unable to open file");
        }
    }
};

#endif
<commit_msg>add multiple includeguard<commit_after>#ifndef STREAM_ITERATOR_HPP
#define STREAM_ITERATOR_HPP

#ifdef USE_MMAP

#include "File-Vector/file_vector.hpp"

class stream_range {
    file_vector<char> file;

public:
    using iterator = file_vector<char>::const_iterator;

    iterator const last;
    iterator const first;

    stream_range(stream_range const&) = delete;

    stream_range(char const* name) : file(name), first(file.cbegin()), last(file.cend()) {
        cout << "using mmap" << endl;
    }
};

#else // USE_MMAP

#include <streambuf>
#include <fstream>

class stream_range {
    fstream file;
    streambuf *rd;
    streamoff pos;

public:
    class iterator {
        friend class stream_range;

        iterator(stream_range *r, streamoff pos) : r(r), pos(pos), sym(r->rd->sgetc()) {
            r->pos = pos;
        }

        stream_range *r;
        streamoff pos;
        int sym;

    public:
        int operator* () const {
            return sym;
        }

        bool operator== (iterator const& i) const {
            return (r == i.r) && (sym == i.sym) && (pos == i.pos);
        }

        bool operator!= (iterator const& i) const {
            return (r != i.r) || (sym != i.sym) || (pos != i.pos);
        }

        streamoff operator- (iterator const& i) const {
            return pos - i.pos;
        }

        iterator& operator++ () {
            if (r->pos != pos) {
                r->pos = r->rd->pubseekoff(++pos, ios_base::beg);
                sym = r->rd->sgetc();
            } else {
                r->pos = ++pos;
                sym = r->rd->snextc();
            }
            return *this;
        }

        iterator& operator-- () {
            --pos;
            if (r->pos != pos) {
                r->pos = r->rd->pubseekoff(pos, ios_base::beg);
            }
            sym = r->rd->sgetc();
            return *this;
        }

        iterator& operator= (iterator const& i) {
            r = i.r;
            pos = i.pos;
            sym = i.sym;
            return *this;
        }
    };

    friend class stream_range::iterator;

    iterator const last;
    iterator const first;

    stream_range(stream_range const&) = delete;

    stream_range(char const* name) : file(name, ios_base::in),
        rd(file.rdbuf()), pos(0),
        last(this, rd->pubseekoff(0, ios_base::end)),
        first(this, rd->pubseekoff(0, ios_base::beg)
    ) {
        cout << "using fstream" << endl;
        if (!file.is_open()) {
            throw runtime_error("unable to open file");
        }
    }
};

#endif // USE_MMAP
#endif // STREAM_ITERATOR_HPP
<|endoftext|>


<commit_before>#include "strings.h"

BOOST_AUTO_TEST_CASE(std_string_variants)
{
    BOOST_REQUIRE((std::is_same_v<std::string, std::basic_string<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::wstring, std::basic_string<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::u16string, std::basic_string<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::u32string, std::basic_string<XXX>>));
}

BOOST_AUTO_TEST_CASE(std_string_related_types)
{
    BOOST_REQUIRE((std::is_same_v<std::string::traits_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::value_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::reference, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::const_reference, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::reverse_iterator, std::reverse_iterator<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::string::const_reverse_iterator, std::reverse_iterator<XXX>>));
}

BOOST_AUTO_TEST_CASE(std_string_accessors)
{
    std::string s{"Hello, world!"};

    BOOST_REQUIRE_EQUAL(xxx, s[0]);
    BOOST_REQUIRE_EQUAL('w', s.at(xxx));
    BOOST_REQUIRE_THROW(s.at(1000), XXX);
    BOOST_REQUIRE_EQUAL(xxx, s.front());
    BOOST_REQUIRE_EQUAL(xxx, s.back());
    BOOST_REQUIRE((std::is_same_v<decltype(s.data()), XXX>));
    BOOST_REQUIRE((std::is_same_v<decltype(s.c_str()), XXX>));
}

BOOST_AUTO_TEST_CASE(std_string_allocators)
{
    BOOST_REQUIRE((std::is_same_v<std::string::allocator_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::size_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::difference_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::pointer, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::const_pointer, XXX>));
}
<commit_msg>Add test cases for std::string<commit_after>#include "strings.h"

BOOST_AUTO_TEST_CASE(std_string_variants)
{
    BOOST_REQUIRE((std::is_same_v<std::string, std::basic_string<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::wstring, std::basic_string<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::u16string, std::basic_string<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::u32string, std::basic_string<XXX>>));
}

BOOST_AUTO_TEST_CASE(std_string_related_types)
{
    BOOST_REQUIRE((std::is_same_v<std::string::traits_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::value_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::reference, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::const_reference, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::reverse_iterator, std::reverse_iterator<XXX>>));
    BOOST_REQUIRE((std::is_same_v<std::string::const_reverse_iterator, std::reverse_iterator<XXX>>));
}

BOOST_AUTO_TEST_CASE(std_string_constructors)
{
    std::string const s1;
    BOOST_REQUIRE_EQUAL(xxx, s1.length());

    std::string const s2{5, 'E'};
    BOOST_REQUIRE_EQUAL(xxx, s2.length());

    std::string const s3{s2};
    BOOST_REQUIRE_EQUAL(xxx, s3.length());

    std::string const s4{s2, 1};
    BOOST_REQUIRE_EQUAL(xxx, s4.length());

    std::string const hw{"Hello, world!"};
    std::string const s5{hw, 1, 4};
    BOOST_REQUIRE_EQUAL(xxx, s5);

    std::string const s6{"Hello, world!"};
    BOOST_REQUIRE_EQUAL(xxx, s6.length());

    std::string const s7{"Hello, world!", 5};
    BOOST_REQUIRE_EQUAL(xxx, s7);

    std::string const s8{s7.begin(), s7.begin() + 1};
    BOOST_REQUIRE_EQUAL(xxx, s8);

    std::string const s9{'H', 'e', 'l', 'l', 'o'};
    BOOST_REQUIRE_EQUAL(xxx, s9);
}

BOOST_AUTO_TEST_CASE(std_string_literals)
{
    using namespace std::literals::string_literals;
    auto s1{"Hello, world!"s};
    auto s2{L"Hello, world!"s};
    auto s3{u"Hello, world!"s};
    auto s4{U"Hello, world!"s};
    BOOST_REQUIRE((std::is_same_v<decltype(s1), XXX>));
    BOOST_REQUIRE((std::is_same_v<decltype(s2), XXX>));
    BOOST_REQUIRE((std::is_same_v<decltype(s3), XXX>));
    BOOST_REQUIRE((std::is_same_v<decltype(s4), XXX>));
}

BOOST_AUTO_TEST_CASE(std_string_accessors)
{
    std::string s{"Hello, world!"};

    BOOST_REQUIRE_EQUAL(xxx, s[0]);
    BOOST_REQUIRE_EQUAL('w', s.at(xxx));
    BOOST_REQUIRE_THROW(s.at(1000), XXX);
    BOOST_REQUIRE_EQUAL(xxx, s.front());
    BOOST_REQUIRE_EQUAL(xxx, s.back());
    BOOST_REQUIRE((std::is_same_v<decltype(s.data()), XXX>));
    BOOST_REQUIRE((std::is_same_v<decltype(s.c_str()), XXX>));
}

BOOST_AUTO_TEST_CASE(string_iterators)
{
}

BOOST_AUTO_TEST_CASE(std_string_allocators)
{
    BOOST_REQUIRE((std::is_same_v<std::string::allocator_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::size_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::difference_type, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::pointer, XXX>));
    BOOST_REQUIRE((std::is_same_v<std::string::const_pointer, XXX>));
}
<|endoftext|>


<commit_before>#include <build-bot/worker.h>

namespace dsn {
namespace build_bot {
    namespace priv {
        class Worker : public dsn::log::Base<Worker> {
            std::string m_url;
            std::string m_branch;
            std::string m_revision;
            std::string m_configFile;
            std::string m_profileName;
            std::string m_buildDir;
            std::string m_repoName;

        public:
            Worker(const std::string& build_directory,
                   const std::string& repo_name,
                   const std::string& url, const std::string& branch, const std::string& revision,
                   const std::string& config_file, const std::string& profile_name)
                : m_buildDir(build_directory)
                , m_url(url)
                , m_branch(branch)
                , m_revision(revision)
                , m_configFile(config_file)
                , m_profileName(profile_name)
                , m_repoName(repo_name)
            {
            }

            void run()
            {
                BOOST_LOG_SEV(log, severity::debug) << "Worker started for repo " << m_url << "/" << m_branch << " (" << m_revision << ")"
                                                    << ", profile=" << m_profileName << "; config=" << m_configFile;
            }
        };
    }
}
}

using namespace dsn::build_bot;

Worker::Worker(const std::string& build_directory,
               const std::string& repo_name,
               const std::string& url, const std::string& branch, const std::string& revision,
               const std::string& config_file, const std::string& profile_name)
    : m_impl(new priv::Worker(build_directory, repo_name, url, branch, revision, config_file, profile_name))
{
}

Worker::~Worker()
{
}

void Worker::run()
{
    return m_impl->run();
}
<commit_msg>Generate random build ID<commit_after>#include <build-bot/worker.h>

#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>

namespace dsn {
namespace build_bot {
    namespace priv {
        class Worker : public dsn::log::Base<Worker> {
        private:
            std::string m_url;
            std::string m_branch;
            std::string m_revision;
            std::string m_configFile;
            std::string m_profileName;
            std::string m_buildDir;
            std::string m_repoName;

            std::string generateBuildId()
            {
                std::string res;
                boost::random::random_device rng;
                boost::random::uniform_int_distribution<> dist(0, BUILD_ID_CHARS.size() - 1);

                for (size_t i = 0; i < BUILD_ID_LENGTH; i++)
                    res += BUILD_ID_CHARS[dist(rng)];

                return res;
            }

            std::string m_buildId;

            static const std::string BUILD_ID_CHARS;
            static const size_t BUILD_ID_LENGTH;

        public:
            Worker(const std::string& build_directory,
                   const std::string& repo_name,
                   const std::string& url, const std::string& branch, const std::string& revision,
                   const std::string& config_file, const std::string& profile_name)
                : m_buildDir(build_directory)
                , m_url(url)
                , m_branch(branch)
                , m_revision(revision)
                , m_configFile(config_file)
                , m_profileName(profile_name)
                , m_repoName(repo_name)
            {
            }

            void run()
            {

                m_buildId = generateBuildId();
                BOOST_LOG_SEV(log, severity::info) << "Worker started for repo " << m_repoName
                                                   << " (profile: " << m_profileName << ", config: " << m_configFile << ") - Build ID: " << m_buildId;
            }
        };

        const std::string Worker::BUILD_ID_CHARS{ "0123456789abcdef" };
        const size_t Worker::BUILD_ID_LENGTH{ 8 };
    }
}
}

using namespace dsn::build_bot;

Worker::Worker(const std::string& build_directory,
               const std::string& repo_name,
               const std::string& url, const std::string& branch, const std::string& revision,
               const std::string& config_file, const std::string& profile_name)
    : m_impl(new priv::Worker(build_directory, repo_name, url, branch, revision, config_file, profile_name))
{
}

Worker::~Worker()
{
}

void Worker::run()
{
    return m_impl->run();
}
<|endoftext|>