<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _LAYOUT_POST_HXX
#define _LAYOUT_POST_HXX

#if ENABLE_LAYOUT

/* Allow re-inclusion for cxx file. */
#undef _LAYOUT_PRE_HXX

#undef AdvancedButton
#undef ApplyButton
#undef Box
#undef Button
#undef CancelButton
#undef CheckBox
#undef ComboBox
#undef Container
#undef Control
#undef Dialog
#undef Edit
#undef ErrorBox
#undef FixedImage
#undef FixedInfo
#undef FixedLine
#undef FixedText
#undef HBox
#undef HelpButton
#undef IgnoreButton
#undef ImageButton
#undef InfoBox
#undef ListBox
#undef MessBox
#undef MessageBox
#undef MetricField
#undef MetricFormatter
#undef MoreButton
#undef MultiLineEdit
#undef MultiListBox
#undef NoButton
#undef NumericField
#undef NumericFormatter
#undef OKButton
#undef Plugin
#undef ProgressBar
#undef PushButton
#undef QueryBox
#undef RadioButton
#undef ResetButton
#undef RetryButton
#undef SfxTabPage
#undef SfxTabDialog
#undef SfxTabPage
#undef SvxFontListBox
#undef SvxLanguageBox
#undef SpinField
#undef TabDialog
#undef TabControl
#undef TabPage
#undef Table
#undef VBox
#undef WarningBox
#undef YesButton

#undef SvxFontListBox
#undef SvxLanguageBox

#undef ModalDialog
#undef ModelessDialog
#undef ScExpandedFixedText
#undef SfxDialog
#undef SfxModalDialog
#undef SfxModelessDialog

#undef Window

#endif /* ENABLE_LAYOUT */

#endif /* _LAYOUT_POST_HXX */

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>remove dups<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _LAYOUT_POST_HXX
#define _LAYOUT_POST_HXX

#if ENABLE_LAYOUT

/* Allow re-inclusion for cxx file. */
#undef _LAYOUT_PRE_HXX

#undef AdvancedButton
#undef ApplyButton
#undef Box
#undef Button
#undef CancelButton
#undef CheckBox
#undef ComboBox
#undef Container
#undef Control
#undef Dialog
#undef Edit
#undef ErrorBox
#undef FixedImage
#undef FixedInfo
#undef FixedLine
#undef FixedText
#undef HBox
#undef HelpButton
#undef IgnoreButton
#undef ImageButton
#undef InfoBox
#undef ListBox
#undef MessBox
#undef MessageBox
#undef MetricField
#undef MetricFormatter
#undef MoreButton
#undef MultiLineEdit
#undef MultiListBox
#undef NoButton
#undef NumericField
#undef NumericFormatter
#undef OKButton
#undef Plugin
#undef ProgressBar
#undef PushButton
#undef QueryBox
#undef RadioButton
#undef ResetButton
#undef RetryButton
#undef SfxTabDialog
#undef SfxTabPage
#undef SvxFontListBox
#undef SvxLanguageBox
#undef SpinField
#undef TabDialog
#undef TabControl
#undef TabPage
#undef Table
#undef VBox
#undef WarningBox
#undef YesButton

#undef SvxFontListBox
#undef SvxLanguageBox

#undef ModalDialog
#undef ModelessDialog
#undef ScExpandedFixedText
#undef SfxDialog
#undef SfxModalDialog
#undef SfxModelessDialog

#undef Window

#endif /* ENABLE_LAYOUT */

#endif /* _LAYOUT_POST_HXX */

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>WaE: switch statement contains 'default' but no 'case' labels<commit_after><|endoftext|>


<commit_before><commit_msg>fix up code that checks a firmware version response<commit_after><|endoftext|>


<commit_before>//#define DEBUG // Allow debugging
#include <os>
#include <net/class_ip6.hpp>
#include <net/ip6/icmp6.hpp>
#include <net/ip6/udp6.hpp>

#include <assert.h>

namespace net
{
  IP6::IP6(const IP6::addr& lo)
  //  : local(lo)
  {
    int ttt;
    printf("IP6: stack: %p\n", &ttt);

    printf("IP6 constructor, addr = %s\n", lo.to_string().c_str());
    assert(sizeof(addr)   == 16);
    assert(sizeof(header) == 40);
    assert(sizeof(options_header) == 8);

    this->local = lo;
  }

  uint8_t IP6::parse6(uint8_t*& reader, uint8_t next)
  {
    switch (next)
    {
    case PROTO_HOPOPT:
    case PROTO_OPTSv6:
      {
        std::cout << ">>> IPv6 options header " << protocol_name(next) << std::endl;

        options_header& opts = *(options_header*) reader;
        reader += opts.size();

        std::cout << "OPTSv6 size: " << opts.size() << std::endl;
        std::cout << "OPTSv6 ext size: " << opts.extended() << std::endl;

        next = opts.next();
        std::cout << "OPTSv6 next: " << protocol_name(next) << std::endl;
      } break;
    case PROTO_ICMPv6:
        break;
    case PROTO_UDP:
        break;

    default:
      std::cout << "Not parsing " << protocol_name(next) << std::endl;
    }

    return next;
  }

	int IP6::bottom(std::shared_ptr<Packet>& pckt)
	{
    std::cout << ">>> IPv6 packet:" << std::endl;

    uint8_t* reader = pckt->buffer();
    full_header& full = *(full_header*) reader;
    reader += sizeof(full_header);

    header& hdr = full.ip6_hdr;

    std::cout << "IPv6 v: " << hdr.version() << " \t";
    std::cout << "class: " << hdr.tclass() << " \t";

    std::cout << "size: " << hdr.size() << " bytes" << std::endl;

    uint8_t next = hdr.next();
    std::cout << "IPv6 next hdr: " << protocol_name(next) << std::endl;
    std::cout << "IPv6 hoplimit: " << hdr.hoplimit() << " hops" << std::endl;

    std::cout << "IPv6 src: " << hdr.source() << std::endl;
    std::cout << "IPv6 dst: " << hdr.dest() << std::endl;

    while (next != PROTO_NoNext)
    {
      auto it = proto_handlers.find(next);
      if (it != proto_handlers.end())
      {
          pckt->_payload = reader;
          return it->second(pckt);
      }
      else
          // just print information
          next = parse6(reader, next);
    }

    std::cout << std::endl;
    return 0;
	};

  std::string IP6::addr::to_string() const
  {
    static const std::string lut = "0123456789abcdef";
    std::string ret(40, 0);
    int counter = 0;

    const uint8_t* octet = i8;

    for (int i = 0; i < 16; i++)
    {
      ret[counter++] = lut[(octet[i] & 0xF0) >> 4];
      ret[counter++] = lut[(octet[i] & 0x0F) >> 0];
      if (i & 1)
        ret[counter++] = ':';
    }
    ret.resize(counter-1);
    return ret;
  }

}
<commit_msg>Moved static outside of function<commit_after>//#define DEBUG // Allow debugging
#include <os>
#include <net/class_ip6.hpp>
#include <net/ip6/icmp6.hpp>
#include <net/ip6/udp6.hpp>

#include <assert.h>

namespace net
{
  IP6::IP6(const IP6::addr& lo)
  //  : local(lo)
  {
    int ttt;
    printf("IP6: stack: %p\n", &ttt);

    printf("IP6 constructor, addr = %s\n", lo.to_string().c_str());
    assert(sizeof(addr)   == 16);
    assert(sizeof(header) == 40);
    assert(sizeof(options_header) == 8);

    this->local = lo;
  }

  uint8_t IP6::parse6(uint8_t*& reader, uint8_t next)
  {
    switch (next)
    {
    case PROTO_HOPOPT:
    case PROTO_OPTSv6:
      {
        std::cout << ">>> IPv6 options header " << protocol_name(next) << std::endl;

        options_header& opts = *(options_header*) reader;
        reader += opts.size();

        std::cout << "OPTSv6 size: " << opts.size() << std::endl;
        std::cout << "OPTSv6 ext size: " << opts.extended() << std::endl;

        next = opts.next();
        std::cout << "OPTSv6 next: " << protocol_name(next) << std::endl;
      } break;
    case PROTO_ICMPv6:
        break;
    case PROTO_UDP:
        break;

    default:
      std::cout << "Not parsing " << protocol_name(next) << std::endl;
    }

    return next;
  }

	int IP6::bottom(std::shared_ptr<Packet>& pckt)
	{
    std::cout << ">>> IPv6 packet:" << std::endl;

    uint8_t* reader = pckt->buffer();
    full_header& full = *(full_header*) reader;
    reader += sizeof(full_header);

    header& hdr = full.ip6_hdr;

    std::cout << "IPv6 v: " << hdr.version() << " \t";
    std::cout << "class: " << hdr.tclass() << " \t";

    std::cout << "size: " << hdr.size() << " bytes" << std::endl;

    uint8_t next = hdr.next();
    std::cout << "IPv6 next hdr: " << protocol_name(next) << std::endl;
    std::cout << "IPv6 hoplimit: " << hdr.hoplimit() << " hops" << std::endl;

    std::cout << "IPv6 src: " << hdr.source() << std::endl;
    std::cout << "IPv6 dst: " << hdr.dest() << std::endl;

    while (next != PROTO_NoNext)
    {
      auto it = proto_handlers.find(next);
      if (it != proto_handlers.end())
      {
          pckt->_payload = reader;
          return it->second(pckt);
      }
      else
          // just print information
          next = parse6(reader, next);
    }

    std::cout << std::endl;
    return 0;
	};

  static const std::string lut = "0123456789abcdef";

  std::string IP6::addr::to_string() const
  {
    std::string ret(40, 0);
    int counter = 0;

    const uint8_t* octet = i8;

    for (int i = 0; i < 16; i++)
    {
      ret[counter++] = lut[(octet[i] & 0xF0) >> 4];
      ret[counter++] = lut[(octet[i] & 0x0F) >> 0];
      if (i & 1)
        ret[counter++] = ':';
    }
    ret.resize(counter-1);
    return ret;
  }

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) DreamLab Onet.pl Sp. z o. o.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <v8.h>
#include <node.h>
#include <Uri.h>

enum parseOptions {
    kProtocol = 1,
    kAuth = 1 << 1,
    kHost = 1 << 2,
    kPort = 1 << 3,
    kQuery = 1 << 4,
    kFragment = 1 << 5,
    kPath = 1 << 6,
    kAll = kProtocol | kAuth | kHost | kPort | kQuery | kFragment | kPath
};

static v8::Persistent<v8::String> protocol_symbol = NODE_PSYMBOL("protocol");
static v8::Persistent<v8::String> auth_symbol = NODE_PSYMBOL("auth");
static v8::Persistent<v8::String> host_symbol = NODE_PSYMBOL("host");
static v8::Persistent<v8::String> port_symbol = NODE_PSYMBOL("port");
static v8::Persistent<v8::String> query_symbol = NODE_PSYMBOL("query");
static v8::Persistent<v8::String> fragment_symbol = NODE_PSYMBOL("fragment");
static v8::Persistent<v8::String> path_symbol = NODE_PSYMBOL("path");

static v8::Handle<v8::Value> parse(const v8::Arguments& args){
    v8::HandleScope scope;

    parseOptions opts = kAll;

    if (args.Length() == 0 || !args[0]->IsString()) {
        v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument has to be string")));
    }

    if (args[1]->IsNumber()) {
        opts = static_cast<parseOptions>(args[1]->Int32Value());
    }

    v8::String::Utf8Value url (args[0]->ToString());

    if (url.length() == 0) {
        v8::ThrowException(v8::Exception::TypeError(v8::String::New("String mustn't be empty")));
    }

    UriParserStateA state;
    UriUriA uri;

    state.uri = &uri;

    if (uriParseUriA(&state, *url) != URI_SUCCESS) {
        return scope.Close(v8::Boolean::New(false));
    }

    v8::PropertyAttribute attrib = (v8::PropertyAttribute) (v8::ReadOnly | v8::DontDelete);
    v8::Local<v8::Object> data = v8::Object::New();

    if (uri.scheme.first && opts & kProtocol) {
        // +1 here because we need : after protocol
        data->Set(protocol_symbol, v8::String::New(uri.scheme.first, strlen(uri.scheme.first) - strlen(uri.scheme.afterLast) + 1), attrib);
    }

    if (uri.userInfo.first && opts & kAuth) {
        char *auth = (char*) uri.userInfo.first;
        const char *delim = ":";
        auth[strlen(uri.userInfo.first) - strlen(uri.userInfo.afterLast)] = '\0';

        v8::Local<v8::Object> authData = v8::Object::New();
        authData->Set(v8::String::New("user"), v8::String::New(strtok(auth, delim))), attrib;
        authData->Set(v8::String::New("password"), v8::String::New(strtok(NULL, delim)), attrib);

        data->Set(auth_symbol, authData, attrib);
    }

    if (uri.hostText.first && opts & kHost) {
        int tmpLength = strlen(uri.hostText.first);

        data->Set(host_symbol, v8::String::New(uri.hostText.first, tmpLength - strlen(uri.hostText.afterLast)), attrib);
    }

    if (uri.portText.first && opts & kPort) {
        data->Set(port_symbol, v8::String::New(uri.portText.first, strlen(uri.portText.first) - strlen(uri.portText.afterLast)), attrib);
    }

    if (uri.query.first && opts & kQuery) {
        char *query = (char*) uri.query.first;
        query[strlen(uri.query.first) - strlen(uri.query.afterLast)] = '\0';
        const char *amp = "&", *sum = "=";
        char *queryParamPtr, *queryParam = strtok_r(query, amp, &queryParamPtr), *queryParamKey, *queryParamValue;

        v8::Local<v8::Object> queryData = v8::Object::New();

        while (queryParam) {
            queryParamKey = strtok(queryParam, sum);
            queryParamValue = strtok(NULL, sum);
            queryParam = strtok_r(NULL, amp, &queryParamPtr);

            queryData->Set(v8::String::New(queryParamKey), v8::String::New(queryParamValue ? queryParamValue : ""), attrib);
        }

        data->Set(query_symbol, queryData, attrib);
        //parsing the path will be easier
        query--;
        query[0] = '\0';
    }

    if (uri.fragment.first && opts & kFragment) {
        data->Set(fragment_symbol, v8::String::New(uri.fragment.first, strlen(uri.fragment.first) - strlen(uri.fragment.afterLast)), attrib);
    }

    if (uri.pathHead && uri.pathHead->text.first && opts & kPath) {
        UriPathSegmentA pathHead = *uri.pathHead;

        char *path = (char*) pathHead.text.first;

        int position = strlen(pathHead.text.first);
        while (pathHead.next) {
            pathHead = *pathHead.next;
        }

        int tmpPosition = strlen(pathHead.text.afterLast);

        if ( (position - tmpPosition) == 0) {
            path = (char *) "/";
        }

        if ((uri.absolutePath || uri.hostText.first) && strlen(path) > 1) {
            path--;
        }

        data->Set(path_symbol, v8::String::New(path), attrib);
    } else if (opts & kPath) {
        data->Set(path_symbol, v8::String::New("/"), attrib);
    }

    uriFreeUriMembersA(&uri);

    return scope.Close(data);
}

extern "C" void init (v8::Handle<v8::Object> target){
    v8::HandleScope scope;

    NODE_SET_METHOD(target, "parse", parse);
    NODE_DEFINE_CONSTANT(target, kProtocol);
    NODE_DEFINE_CONSTANT(target, kAuth);
    NODE_DEFINE_CONSTANT(target, kHost);
    NODE_DEFINE_CONSTANT(target, kPort);
    NODE_DEFINE_CONSTANT(target, kQuery);
    NODE_DEFINE_CONSTANT(target, kFragment);
    NODE_DEFINE_CONSTANT(target, kPath);
    NODE_DEFINE_CONSTANT(target, kAll);
}
<commit_msg>Fixed an issue with the path.<commit_after>/*
 * Copyright (C) DreamLab Onet.pl Sp. z o. o.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <v8.h>
#include <node.h>
#include <Uri.h>

enum parseOptions {
    kProtocol = 1,
    kAuth = 1 << 1,
    kHost = 1 << 2,
    kPort = 1 << 3,
    kQuery = 1 << 4,
    kFragment = 1 << 5,
    kPath = 1 << 6,
    kAll = kProtocol | kAuth | kHost | kPort | kQuery | kFragment | kPath
};

static v8::Persistent<v8::String> protocol_symbol = NODE_PSYMBOL("protocol");
static v8::Persistent<v8::String> auth_symbol = NODE_PSYMBOL("auth");
static v8::Persistent<v8::String> host_symbol = NODE_PSYMBOL("host");
static v8::Persistent<v8::String> port_symbol = NODE_PSYMBOL("port");
static v8::Persistent<v8::String> query_symbol = NODE_PSYMBOL("query");
static v8::Persistent<v8::String> fragment_symbol = NODE_PSYMBOL("fragment");
static v8::Persistent<v8::String> path_symbol = NODE_PSYMBOL("path");

static v8::Handle<v8::Value> parse(const v8::Arguments& args){
    v8::HandleScope scope;

    parseOptions opts = kAll;

    if (args.Length() == 0 || !args[0]->IsString()) {
        v8::ThrowException(v8::Exception::TypeError(v8::String::New("First argument has to be string")));
    }

    if (args[1]->IsNumber()) {
        opts = static_cast<parseOptions>(args[1]->Int32Value());
    }

    v8::String::Utf8Value url (args[0]->ToString());

    if (url.length() == 0) {
        v8::ThrowException(v8::Exception::TypeError(v8::String::New("String mustn't be empty")));
    }

    UriParserStateA state;
    UriUriA uri;

    state.uri = &uri;

    if (uriParseUriA(&state, *url) != URI_SUCCESS) {
        return scope.Close(v8::Boolean::New(false));
    }

    v8::PropertyAttribute attrib = (v8::PropertyAttribute) (v8::ReadOnly | v8::DontDelete);
    v8::Local<v8::Object> data = v8::Object::New();

    if (uri.scheme.first && opts & kProtocol) {
        // +1 here because we need : after protocol
        data->Set(protocol_symbol, v8::String::New(uri.scheme.first, strlen(uri.scheme.first) - strlen(uri.scheme.afterLast) + 1), attrib);
    }

    if (uri.userInfo.first && opts & kAuth) {
        char *auth = (char *) uri.userInfo.first;
        const char *delim = ":";
        auth[strlen(uri.userInfo.first) - strlen(uri.userInfo.afterLast)] = '\0';

        v8::Local<v8::Object> authData = v8::Object::New();
        authData->Set(v8::String::New("user"), v8::String::New(strtok(auth, delim))), attrib;
        authData->Set(v8::String::New("password"), v8::String::New(strtok(NULL, delim)), attrib);

        data->Set(auth_symbol, authData, attrib);
    }

    if (uri.hostText.first && opts & kHost) {
        int tmpLength = strlen(uri.hostText.first);

        data->Set(host_symbol, v8::String::New(uri.hostText.first, tmpLength - strlen(uri.hostText.afterLast)), attrib);
    }

    if (uri.portText.first && opts & kPort) {
        data->Set(port_symbol, v8::String::New(uri.portText.first, strlen(uri.portText.first) - strlen(uri.portText.afterLast)), attrib);
    }

    if (uri.query.first && opts & kQuery) {
        char *query = (char *) uri.query.first;
        query[strlen(uri.query.first) - strlen(uri.query.afterLast)] = '\0';
        const char *amp = "&", *sum = "=";
        char *queryParamPtr, *queryParam = strtok_r(query, amp, &queryParamPtr), *queryParamKey, *queryParamValue;

        v8::Local<v8::Object> queryData = v8::Object::New();

        while (queryParam) {
            queryParamKey = strtok(queryParam, sum);
            queryParamValue = strtok(NULL, sum);
            queryParam = strtok_r(NULL, amp, &queryParamPtr);

            queryData->Set(v8::String::New(queryParamKey), v8::String::New(queryParamValue ? queryParamValue : ""), attrib);
        }

        data->Set(query_symbol, queryData, attrib);
        //parsing the path will be easier
        query--;
        query[0] = '\0';
    }

    if (uri.fragment.first && opts & kFragment) {
        data->Set(fragment_symbol, v8::String::New(uri.fragment.first, strlen(uri.fragment.first) - strlen(uri.fragment.afterLast)), attrib);
    }

    if (uri.pathHead && uri.pathHead->text.first && opts & kPath) {
        UriPathSegmentA pathHead = *uri.pathHead;

        char *path = (char *) pathHead.text.first;

        int position = strlen(pathHead.text.first);
        while (pathHead.next) {
            pathHead = *pathHead.next;
        }

        int tmpPosition = strlen(pathHead.text.afterLast);

        if ((position - tmpPosition) == 0) {
            path = (char *) "/";
        }

        if ((uri.absolutePath || uri.hostText.first) && strlen(path) >= 1) {
            char *isNull = path;

            if(*(--isNull)) {
                path--;
            }
        }

        data->Set(path_symbol, v8::String::New(path), attrib);
    } else if (opts & kPath) {
        data->Set(path_symbol, v8::String::New("/"), attrib);
    }

    uriFreeUriMembersA(&uri);

    return scope.Close(data);
}

extern "C" void init (v8::Handle<v8::Object> target){
    v8::HandleScope scope;

    NODE_SET_METHOD(target, "parse", parse);
    NODE_DEFINE_CONSTANT(target, kProtocol);
    NODE_DEFINE_CONSTANT(target, kAuth);
    NODE_DEFINE_CONSTANT(target, kHost);
    NODE_DEFINE_CONSTANT(target, kPort);
    NODE_DEFINE_CONSTANT(target, kQuery);
    NODE_DEFINE_CONSTANT(target, kFragment);
    NODE_DEFINE_CONSTANT(target, kPath);
    NODE_DEFINE_CONSTANT(target, kAll);
}
<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Test memcached_result_st
 *
 *  Copyright (C) 2013 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not 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.
 *
 */

/*
  Test that we are cycling the servers we are creating during testing.
*/

#include "gear_config.h"

#include <libtest/test.hpp>
using namespace libtest;

#include "libgearman/result.hpp"
#include "libgearman/assert.hpp"

#include "libgearman-1.0/visibility.h"
#include "libgearman-1.0/result.h"

#include <memory>

static test_return_t declare_result_TEST(void*)
{
  gearman_result_st result;
  ASSERT_EQ(0, result.size());
  ASSERT_EQ(0, result.capacity());

  return TEST_SUCCESS;
}

static test_return_t new_result_TEST(void*)
{
  gearman_result_st* result= new gearman_result_st;
  ASSERT_EQ(0, result->size());
  ASSERT_EQ(0, result->capacity());

  delete result;

  return TEST_SUCCESS;
}

static test_return_t declare_result_size_TEST(void*)
{
  gearman_result_st result(2048);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 2048);

  return TEST_SUCCESS;
}

static test_return_t new_result_size_TEST(void*)
{
  gearman_result_st* result= new gearman_result_st(2023);

  ASSERT_EQ(0, result->size());
  ASSERT_TRUE(result->capacity() >= 2023);

  delete result;

  return TEST_SUCCESS;
}

static test_return_t zero_resize_TEST(void*)
{
  gearman_result_st result(89);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 89);

  result.resize(0);
  ASSERT_EQ(0, result.size());
  ASSERT_EQ(0, result.capacity());

  return TEST_SUCCESS;
}

static test_return_t smaller_resize_TEST(void*)
{
  gearman_result_st result(89);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 89);

  result.resize(20);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 20);

  return TEST_SUCCESS;
}

static test_return_t bigger_resize_TEST(void*)
{
  gearman_result_st result(89);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 89);

  result.resize(181);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 181);

  return TEST_SUCCESS;
}

static test_return_t random_resize_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st result(random() % max_block);
    ASSERT_TRUE(result.capacity() >= result.size());
    result.resize(random() % max_block);
    ASSERT_TRUE(result.capacity() >= result.size());
    result.resize(random() % max_block +GEARMAN_VECTOR_BLOCK_SIZE);
    ASSERT_TRUE(result.capacity() >= result.size());
  }

  return TEST_SUCCESS;
}

static test_return_t append_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st result(random() % max_block);
    libtest::vchar_t random_string;
    libtest::vchar::make(random_string, random() % max_block);
    result.append(&random_string[0], random_string.size());

    if (random() % 2)
    {
      result.clear();
    }
  }

  return TEST_SUCCESS;
}

static test_return_t gearman_string_take_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st result((random() % max_block) +1);

    // Now we insert a random string
    libtest::vchar_t random_string;
    libtest::vchar::make(random_string, random() % max_block);
    result.append(&random_string[0], random_string.size());

    gearman_string_t temp= gearman_result_take_string(&result);
    ASSERT_TRUE(gearman_c_str(temp));
    free((void*)(gearman_c_str(temp)));
  }

  return TEST_SUCCESS;
}

static test_return_t gearman_string_allocate_take_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st* result= new gearman_result_st((random() % max_block) +1);

    { // Now we insert a random string
      libtest::vchar_t random_string;
      libtest::vchar::make(random_string, random() % max_block);
      result->append(&random_string[0], random_string.size() +1);
    }

    gearman_string_t temp= gearman_result_take_string(result);
    ASSERT_TRUE(gearman_c_str(temp));
    free((void*)(gearman_c_str(temp)));

    if (random() % 2)
    { // Now we insert a random string
      libtest::vchar_t random_string;
      libtest::vchar::make(random_string, random() % max_block);
      result->append(&random_string[0], random_string.size());
    }

    delete result;
  }

  return TEST_SUCCESS;
}

static test_return_t gearman_result_integer_TEST(void*)
{
  gearman_result_st result;
  ASSERT_TRUE(result.store(8976));

  ASSERT_EQ(0, gearman_result_integer(NULL));
  ASSERT_EQ(8976, gearman_result_integer(&result));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_boolean_TEST(void*)
{
  gearman_result_st result;
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_NULL));

  ASSERT_EQ(false, gearman_result_boolean(NULL));

  ASSERT_TRUE(result.boolean(true));
  ASSERT_EQ(true, gearman_result_boolean(&result));
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN));

  ASSERT_TRUE(result.boolean(false));
  ASSERT_EQ(false, gearman_result_boolean(&result));
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN));

  gearman_result_st result_false;
  ASSERT_TRUE(result_false.boolean(false));
  ASSERT_EQ(false, gearman_result_boolean(&result_false));
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_string_TEST(void*)
{
  gearman_string_t value= { test_literal_param("This is my echo test") };
  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value));

  gearman_string_t ret_value= gearman_result_string(&result);
  ASSERT_EQ(test_literal_param_size(value), test_literal_param_size(ret_value));

  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_store_string_TEST(void*)
{
  gearman_string_t value= { test_literal_param("This is my echo test") };
  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value));

  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_store_integer_TEST(void*)
{
  const int64_t value= __LINE__;
  gearman_result_st result;
  gearman_result_store_integer(&result, value);

  return TEST_SUCCESS;
}

static test_return_t gearman_result_store_value_TEST(void*)
{
  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, NULL, 0));

  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__)));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_size_TEST(void*)
{
  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__)));
  ASSERT_EQ(strlen(__func__), gearman_result_size(&result));

  ASSERT_EQ(0, gearman_result_size(NULL));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_value_TEST(void*)
{
  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__)));

  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, test_literal_param(__func__)));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_is_null_TEST(void*)
{
  gearman_result_st result;
  ASSERT_TRUE(gearman_result_is_null(&result));
  ASSERT_TRUE(gearman_result_is_null(NULL));

  return TEST_SUCCESS;
}

test_st allocate_TESTS[] ={
  { "declare result", 0, declare_result_TEST },
  { "new result", 0, new_result_TEST },
  { "declare result(2048)", 0, declare_result_size_TEST },
  { "new result(2023)", 0, new_result_size_TEST },
  { 0, 0, 0 }
};

test_st resize_TESTS[] ={
  { "zero", 0, zero_resize_TEST },
  { "smaller", 0, smaller_resize_TEST },
  { "bigger", 0, bigger_resize_TEST },
  { "random", 0, random_resize_TEST },
  { 0, 0, 0 }
};

test_st append_TESTS[] ={
  { "append()", 0, append_TEST },
  { 0, 0, 0 }
};

test_st take_TESTS[] ={
  { "gearman_string_take_string()", 0, gearman_string_take_TEST },
  { "new gearman_result_st() gearman_string_take_string()", 0, gearman_string_allocate_take_TEST },
  { 0, 0, 0 }
};

test_st API_TESTS[] ={
  { "gearman_result_integer()", 0, gearman_result_integer_TEST },
  { "gearman_result_boolean()", 0, gearman_result_boolean_TEST },
  { "gearman_result_string()", 0, gearman_result_string_TEST },
  { "gearman_result_store_string()", 0, gearman_result_store_string_TEST },
  { "gearman_result_store_integer()", 0, gearman_result_store_integer_TEST },
  { "gearman_result_store_value()", 0, gearman_result_store_value_TEST },
  { "gearman_result_size()", 0, gearman_result_size_TEST },
  { "gearman_result_value()", 0, gearman_result_value_TEST },
  { "gearman_result_is_null()", 0, gearman_result_is_null_TEST },
  { 0, 0, 0 }
};

collection_st collection[] ={
  {"allocate", NULL, NULL, allocate_TESTS },
  {"resize", NULL, NULL, resize_TESTS },
  {"append", NULL, NULL, append_TESTS },
  {"take", NULL, NULL, take_TESTS },
  {"API", NULL, NULL, API_TESTS },
  {0, 0, 0, 0}
};

void get_world(libtest::Framework *world)
{
  world->collections(collection);
}
<commit_msg>Make sure we always have at least one byte stored in this test.<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Test memcached_result_st
 *
 *  Copyright (C) 2013 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not 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.
 *
 */

/*
  Test that we are cycling the servers we are creating during testing.
*/

#include "gear_config.h"

#include <libtest/test.hpp>
using namespace libtest;

#include "libgearman/result.hpp"
#include "libgearman/assert.hpp"

#include "libgearman-1.0/visibility.h"
#include "libgearman-1.0/result.h"

#include <memory>

static test_return_t declare_result_TEST(void*)
{
  gearman_result_st result;
  ASSERT_EQ(0, result.size());
  ASSERT_EQ(0, result.capacity());

  return TEST_SUCCESS;
}

static test_return_t new_result_TEST(void*)
{
  gearman_result_st* result= new gearman_result_st;
  ASSERT_EQ(0, result->size());
  ASSERT_EQ(0, result->capacity());

  delete result;

  return TEST_SUCCESS;
}

static test_return_t declare_result_size_TEST(void*)
{
  gearman_result_st result(2048);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 2048);

  return TEST_SUCCESS;
}

static test_return_t new_result_size_TEST(void*)
{
  gearman_result_st* result= new gearman_result_st(2023);

  ASSERT_EQ(0, result->size());
  ASSERT_TRUE(result->capacity() >= 2023);

  delete result;

  return TEST_SUCCESS;
}

static test_return_t zero_resize_TEST(void*)
{
  gearman_result_st result(89);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 89);

  result.resize(0);
  ASSERT_EQ(0, result.size());
  ASSERT_EQ(0, result.capacity());

  return TEST_SUCCESS;
}

static test_return_t smaller_resize_TEST(void*)
{
  gearman_result_st result(89);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 89);

  result.resize(20);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 20);

  return TEST_SUCCESS;
}

static test_return_t bigger_resize_TEST(void*)
{
  gearman_result_st result(89);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 89);

  result.resize(181);
  ASSERT_EQ(0, result.size());
  ASSERT_TRUE(result.capacity() >= 181);

  return TEST_SUCCESS;
}

static test_return_t random_resize_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st result(random() % max_block);
    ASSERT_TRUE(result.capacity() >= result.size());
    result.resize(random() % max_block);
    ASSERT_TRUE(result.capacity() >= result.size());
    result.resize(random() % max_block +GEARMAN_VECTOR_BLOCK_SIZE);
    ASSERT_TRUE(result.capacity() >= result.size());
  }

  return TEST_SUCCESS;
}

static test_return_t append_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st result(random() % max_block);
    libtest::vchar_t random_string;
    libtest::vchar::make(random_string, (random() % max_block) +1);
    result.append(&random_string[0], random_string.size());

    if (random() % 2)
    {
      result.clear();
    }
  }

  return TEST_SUCCESS;
}

static test_return_t gearman_string_take_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st result((random() % max_block) +1);

    // Now we insert a random string
    libtest::vchar_t random_string;
    libtest::vchar::make(random_string, (random() % max_block) +1);
    result.append(&random_string[0], random_string.size());

    gearman_string_t temp= gearman_result_take_string(&result);
    ASSERT_TRUE(gearman_c_str(temp));
    free((void*)(gearman_c_str(temp)));
  }

  return TEST_SUCCESS;
}

static test_return_t gearman_string_allocate_take_TEST(void*)
{
  const size_t max_block= 10 * GEARMAN_VECTOR_BLOCK_SIZE;
  for (size_t x= 0; x < 20; x++)
  {
    gearman_result_st* result= new gearman_result_st((random() % max_block) +1);

    { // Now we insert a random string
      libtest::vchar_t random_string;
      libtest::vchar::make(random_string, (random() % max_block) +1);
      result->append(&random_string[0], random_string.size());
    }

    gearman_string_t temp= gearman_result_take_string(result);
    ASSERT_TRUE(gearman_c_str(temp));
    free((void*)(gearman_c_str(temp)));

    if (random() % 2)
    { // Now we insert a random string
      libtest::vchar_t random_string;
      libtest::vchar::make(random_string, (random() % max_block) +1);
      result->append(&random_string[0], random_string.size());
    }

    delete result;
  }

  return TEST_SUCCESS;
}

static test_return_t gearman_result_integer_TEST(void*)
{
  gearman_result_st result;
  ASSERT_TRUE(result.store(8976));

  ASSERT_EQ(0, gearman_result_integer(NULL));
  ASSERT_EQ(8976, gearman_result_integer(&result));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_boolean_TEST(void*)
{
  gearman_result_st result;
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_NULL));

  ASSERT_EQ(false, gearman_result_boolean(NULL));

  ASSERT_TRUE(result.boolean(true));
  ASSERT_EQ(true, gearman_result_boolean(&result));
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN));

  ASSERT_TRUE(result.boolean(false));
  ASSERT_EQ(false, gearman_result_boolean(&result));
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN));

  gearman_result_st result_false;
  ASSERT_TRUE(result_false.boolean(false));
  ASSERT_EQ(false, gearman_result_boolean(&result_false));
  ASSERT_TRUE(result.is_type(GEARMAN_RESULT_BOOLEAN));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_string_TEST(void*)
{
  gearman_string_t value= { test_literal_param("This is my echo test") };
  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value));

  gearman_string_t ret_value= gearman_result_string(&result);
  ASSERT_EQ(test_literal_param_size(value), test_literal_param_size(ret_value));

  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_store_string_TEST(void*)
{
  gearman_string_t value= { test_literal_param("This is my echo test") };
  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_string(NULL, value));

  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_string(&result, value));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_store_integer_TEST(void*)
{
  const int64_t value= __LINE__;
  gearman_result_st result;
  gearman_result_store_integer(&result, value);

  return TEST_SUCCESS;
}

static test_return_t gearman_result_store_value_TEST(void*)
{
  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, NULL, 0));

  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__)));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_size_TEST(void*)
{
  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__)));
  ASSERT_EQ(strlen(__func__), gearman_result_size(&result));

  ASSERT_EQ(0, gearman_result_size(NULL));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_value_TEST(void*)
{
  gearman_result_st result;
  ASSERT_EQ(GEARMAN_SUCCESS, gearman_result_store_value(&result, test_literal_param(__func__)));

  ASSERT_EQ(GEARMAN_INVALID_ARGUMENT, gearman_result_store_value(NULL, test_literal_param(__func__)));

  return TEST_SUCCESS;
}

static test_return_t gearman_result_is_null_TEST(void*)
{
  gearman_result_st result;
  ASSERT_TRUE(gearman_result_is_null(&result));
  ASSERT_TRUE(gearman_result_is_null(NULL));

  return TEST_SUCCESS;
}

test_st allocate_TESTS[] ={
  { "declare result", 0, declare_result_TEST },
  { "new result", 0, new_result_TEST },
  { "declare result(2048)", 0, declare_result_size_TEST },
  { "new result(2023)", 0, new_result_size_TEST },
  { 0, 0, 0 }
};

test_st resize_TESTS[] ={
  { "zero", 0, zero_resize_TEST },
  { "smaller", 0, smaller_resize_TEST },
  { "bigger", 0, bigger_resize_TEST },
  { "random", 0, random_resize_TEST },
  { 0, 0, 0 }
};

test_st append_TESTS[] ={
  { "append()", 0, append_TEST },
  { 0, 0, 0 }
};

test_st take_TESTS[] ={
  { "gearman_string_take_string()", 0, gearman_string_take_TEST },
  { "new gearman_result_st() gearman_string_take_string()", 0, gearman_string_allocate_take_TEST },
  { 0, 0, 0 }
};

test_st API_TESTS[] ={
  { "gearman_result_integer()", 0, gearman_result_integer_TEST },
  { "gearman_result_boolean()", 0, gearman_result_boolean_TEST },
  { "gearman_result_string()", 0, gearman_result_string_TEST },
  { "gearman_result_store_string()", 0, gearman_result_store_string_TEST },
  { "gearman_result_store_integer()", 0, gearman_result_store_integer_TEST },
  { "gearman_result_store_value()", 0, gearman_result_store_value_TEST },
  { "gearman_result_size()", 0, gearman_result_size_TEST },
  { "gearman_result_value()", 0, gearman_result_value_TEST },
  { "gearman_result_is_null()", 0, gearman_result_is_null_TEST },
  { 0, 0, 0 }
};

collection_st collection[] ={
  {"allocate", NULL, NULL, allocate_TESTS },
  {"resize", NULL, NULL, resize_TESTS },
  {"append", NULL, NULL, append_TESTS },
  {"take", NULL, NULL, take_TESTS },
  {"API", NULL, NULL, API_TESTS },
  {0, 0, 0, 0}
};

void get_world(libtest::Framework *world)
{
  world->collections(collection);
}
<|endoftext|>


<commit_before>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014, Willow Garage, Inc.
 *  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 Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Arjun Menon */

#include <ros/ros.h>

#include <moveit/move_group_interface/move_group.h>

#include <moveit/warehouse/planning_scene_storage.h>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <view_controller_msgs/CameraPlacement.h>

#include "moveit_recorder/trajectory_retimer.h"
#include "moveit_recorder/animation_recorder.h"

#include <rosbag/bag.h>
#include <rosbag/query.h>
#include <rosbag/view.h>

#include <algorithm>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "playback");
  ros::NodeHandle node_handle;
  ros::AsyncSpinner spinner(1);
  spinner.start();

  sleep(20); // to let RVIZ come up

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.")
    ("views",boost::program_options::value<std::string>(), "Bag file for viewpoints")
    ("save_dir",boost::program_options::value<std::string>(), "Directory for saving videos");

  boost::program_options::variables_map vm;
  boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
  boost::program_options::store(po, vm);
  boost::program_options::notify(vm);

  if (vm.count("help") || argc == 1) // show help if no parameters passed
  {
    std::cout << desc << std::endl;
    return 1;
  }
  try
  {
    //connect to the DB
    std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
    size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
    moveit_warehouse::PlanningSceneStorage pss(host, port);

    ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);

    // set up the storage directory
    boost::filesystem::path storage_dir( vm.count("save_dir") ? vm["save_dir"].as<std::string>() : "/tmp" );
    boost::filesystem::create_directories( storage_dir );

    // create bag file to track the associated video to the scene, query, and traj that spawned it
    boost::filesystem::path bagpath = storage_dir / "video_lookup.bag";
    rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Write);
    bag.close();

    // load the viewpoints
    std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : "";
    std::vector<view_controller_msgs::CameraPlacement> views;
    rosbag::Bag viewbag;
    viewbag.open(bagfilename, rosbag::bagmode::Read);
    std::vector<std::string> topics; topics.push_back("viewpoints");
    rosbag::View view_t(viewbag, rosbag::TopicQuery(topics));
    BOOST_FOREACH(rosbag::MessageInstance const m, view_t)
    {
      view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>();
      if (i != NULL)
        views.push_back(*i);
    }
    viewbag.close();
    ROS_INFO("%d views loaded",(int)views.size());

    //TODO change these to params
    AnimationRecorder recorder( "/rviz/camera_placement",
                                "planning_scene",
                                "/move_group/display_planned_path",
                                "animation_status",
                                "animation_response",
                                node_handle);

    // ask the warehouse for the scenes
    std::vector<std::string> ps_names;
    pss.getPlanningSceneNames( ps_names );
    ROS_INFO("%d available scenes to display", (int)ps_names.size());

    // iterate over scenes
    std::vector<std::string>::iterator scene_name = ps_names.begin();
    for(; scene_name!=ps_names.end(); ++scene_name)
    {
      ROS_INFO("Retrieving scene %s", scene_name->c_str());
      moveit_warehouse::PlanningSceneWithMetadata pswm;
      pss.getPlanningScene(pswm, *scene_name);
      moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);

      // ask qarehosue for the queries
      std::vector<std::string> pq_names;
      pss.getPlanningQueriesNames( pq_names, *scene_name);
      ROS_INFO("%d available queries to display", (int)pq_names.size());

      // iterate over the queries
      std::vector<std::string>::iterator query_name = pq_names.begin();
      for(; query_name!=pq_names.end(); ++query_name)
      {
        ROS_INFO("Retrieving query %s", query_name->c_str());
        moveit_warehouse::MotionPlanRequestWithMetadata mprwm;
        pss.getPlanningQuery(mprwm, *scene_name, *query_name);
        moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm);

        // ask warehouse for stored trajectories
        std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
        pss.getPlanningResults(planning_results, *scene_name, *query_name);
        ROS_INFO("Loaded %d trajectories", (int)planning_results.size());

        // animate each trajectory
        std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin();
        for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata)
        {
          moveit_msgs::RobotTrajectory rt_msg;
          rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata);
          // retime it
          TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name );
          retimer.configure(ps_msg, mpr_msg);
          bool result = retimer.retime(rt_msg);
          ROS_INFO("Retiming success? %s", result? "yes" : "no" );

          //date and time based filename
          boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
          std::string vid_filename = boost::posix_time::to_simple_string(now);

          // fix filename
          std::replace(vid_filename.begin(), vid_filename.end(), '-','_');
          std::replace(vid_filename.begin(), vid_filename.end(), ' ','_');
          std::replace(vid_filename.begin(), vid_filename.end(), ':','_');

          boost::filesystem::path filename( vid_filename );
          boost::filesystem::path filepath = storage_dir / filename;

          // save into lookup
          rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Append);
          bag.write(filepath.string(), ros::Time::now(), ps_msg);
          bag.write(filepath.string(), ros::Time::now(), mpr_msg);
          bag.write(filepath.string(), ros::Time::now(), rt_msg);

          int view_counter=0;
          std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg;
          for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg)
          {
            AnimationRequest req;

            view_msg->time_from_start = ros::Duration(0.1);
            ros::Time t_now = ros::Time::now();
            view_msg->eye.header.stamp = t_now;
            view_msg->focus.header.stamp = t_now;
            view_msg->up.header.stamp = t_now;

            req.camera_placement = *view_msg;
            req.planning_scene = ps_msg;
            req.motion_plan_request = mpr_msg;
            req.robot_trajectory = rt_msg;

            // same filename, counter for viewpoint
            std::string ext = boost::lexical_cast<std::string>(view_counter++) + ".ogv";
            std_msgs::String filemsg; filemsg.data = req.filepath;
            bag.write(filepath.string(), ros::Time::now(), filemsg);
            std::string video_file = filepath.string()+ext;

            req.filepath = video_file;

            recorder.record(req);
            recorder.startCapture();
            ROS_INFO("RECORDING DONE!");
          }//view
          bag.close();
        }//traj
      }//query
    }//scene
  }
  catch(mongo_ros::DbConnectException &ex)
  {
    ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
        << std::endl << ex.what());
  }

  ROS_INFO("Successfully performed trajectory playback");
  ros::shutdown();
  return 0;
}
<commit_msg>added program option for animation recorder topics<commit_after>/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2014, Willow Garage, Inc.
 *  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 Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Arjun Menon */

#include <ros/ros.h>

#include <moveit/move_group_interface/move_group.h>

#include <moveit/warehouse/planning_scene_storage.h>

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <view_controller_msgs/CameraPlacement.h>

#include "moveit_recorder/trajectory_retimer.h"
#include "moveit_recorder/animation_recorder.h"
#include "moveit_recorder/utils.h"

#include <rosbag/bag.h>
#include <rosbag/query.h>
#include <rosbag/view.h>

#include <algorithm>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "playback");
  ros::NodeHandle node_handle;
  ros::AsyncSpinner spinner(1);
  spinner.start();

  sleep(20); // to let RVIZ come up

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.")
    ("views",boost::program_options::value<std::string>(), "Bag file for viewpoints")
    ("camera_topic",boost::program_options::value<std::string>(), "Topic for publishing to the camera position")
    ("planning_scene_topic",boost::program_options::value<std::string>(), "Topic for publishing the planning scene for recording")
    ("display_traj_topic",boost::program_options::value<std::string>(), "Topic for publishing the trajectory for recorder")
    ("animation_status_topic",boost::program_options::value<std::string>(), "Topic for listening to the completion of the replay")
    ("save_dir",boost::program_options::value<std::string>(), "Directory for saving videos");

  boost::program_options::variables_map vm;
  boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
  boost::program_options::store(po, vm);
  boost::program_options::notify(vm);

  if (vm.count("help") || argc == 1) // show help if no parameters passed
  {
    std::cout << desc << std::endl;
    return 1;
  }
  try
  {
    //connect to the DB
    std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
    size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
    moveit_warehouse::PlanningSceneStorage pss(host, port);
    ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);

    // set up the storage directory
    boost::filesystem::path storage_dir( vm.count("save_dir") ? vm["save_dir"].as<std::string>() : "/tmp" );
    boost::filesystem::create_directories( storage_dir );

    // create bag file to track the associated video to the scene, query, and traj that spawned it
    boost::filesystem::path bagpath = storage_dir / "video_lookup.bag";
    rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Write);
    bag.close();

    // load the viewpoints
    std::string bagfilename = vm.count("views") ? vm["views"].as<std::string>() : "";
    std::vector<view_controller_msgs::CameraPlacement> views;
    rosbag::Bag viewbag;
    viewbag.open(bagfilename, rosbag::bagmode::Read);
    std::vector<std::string> topics; topics.push_back("viewpoints");
    rosbag::View view_t(viewbag, rosbag::TopicQuery(topics));
    BOOST_FOREACH(rosbag::MessageInstance const m, view_t)
    {
      view_controller_msgs::CameraPlacement::ConstPtr i = m.instantiate<view_controller_msgs::CameraPlacement>();
      if (i != NULL)
        views.push_back(*i);
    }
    viewbag.close();
    ROS_INFO("%d views loaded",(int)views.size());

    //TODO change these to params
    std::string camera_placement_topic = utils::get_option(vm, "camera_topic", "/rviz/camera_placement");
    std::string planning_scene_topic =utils:: get_option(vm, "planning_scene_topic", "planning_scene");
    std::string display_traj_topic = utils::get_option(vm, "display_traj_topic", "/move_group/display_planned_path");
    std::string anim_status_topic = utils::get_option(vm, "animation_status_topic", "animation_status");

    AnimationRecorder recorder( camera_placement_topic,
                                planning_scene_topic,
                                display_traj_topic,
                                anim_status_topic,
                                node_handle);

    // ask the warehouse for the scenes
    std::vector<std::string> ps_names;
    pss.getPlanningSceneNames( ps_names );
    ROS_INFO("%d available scenes to display", (int)ps_names.size());

    // iterate over scenes
    std::vector<std::string>::iterator scene_name = ps_names.begin();
    for(; scene_name!=ps_names.end(); ++scene_name)
    {
      ROS_INFO("Retrieving scene %s", scene_name->c_str());
      moveit_warehouse::PlanningSceneWithMetadata pswm;
      pss.getPlanningScene(pswm, *scene_name);
      moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);

      // ask qarehosue for the queries
      std::vector<std::string> pq_names;
      pss.getPlanningQueriesNames( pq_names, *scene_name);
      ROS_INFO("%d available queries to display", (int)pq_names.size());

      // iterate over the queries
      std::vector<std::string>::iterator query_name = pq_names.begin();
      for(; query_name!=pq_names.end(); ++query_name)
      {
        ROS_INFO("Retrieving query %s", query_name->c_str());
        moveit_warehouse::MotionPlanRequestWithMetadata mprwm;
        pss.getPlanningQuery(mprwm, *scene_name, *query_name);
        moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm);

        // ask warehouse for stored trajectories
        std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
        pss.getPlanningResults(planning_results, *scene_name, *query_name);
        ROS_INFO("Loaded %d trajectories", (int)planning_results.size());

        // animate each trajectory
        std::vector<moveit_warehouse::RobotTrajectoryWithMetadata>::iterator traj_w_mdata = planning_results.begin();
        for(; traj_w_mdata!=planning_results.end(); ++traj_w_mdata)
        {
          moveit_msgs::RobotTrajectory rt_msg;
          rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(**traj_w_mdata);
          // retime it
          TrajectoryRetimer retimer( "robot_description", mpr_msg.group_name );
          retimer.configure(ps_msg, mpr_msg);
          bool result = retimer.retime(rt_msg);
          ROS_INFO("Retiming success? %s", result? "yes" : "no" );

          //date and time based filename
          boost::posix_time::ptime now = boost::posix_time::second_clock::local_time();
          std::string vid_filename = boost::posix_time::to_simple_string(now);

          // fix filename
          std::replace(vid_filename.begin(), vid_filename.end(), '-','_');
          std::replace(vid_filename.begin(), vid_filename.end(), ' ','_');
          std::replace(vid_filename.begin(), vid_filename.end(), ':','_');

          boost::filesystem::path filename( vid_filename );
          boost::filesystem::path filepath = storage_dir / filename;

          // save into lookup
          rosbag::Bag bag(bagpath.string(), rosbag::bagmode::Append);
          bag.write(filepath.string(), ros::Time::now(), ps_msg);
          bag.write(filepath.string(), ros::Time::now(), mpr_msg);
          bag.write(filepath.string(), ros::Time::now(), rt_msg);

          int view_counter=0;
          std::vector<view_controller_msgs::CameraPlacement>::iterator view_msg;
          for(view_msg=views.begin(); view_msg!=views.end(); ++view_msg)
          {
            AnimationRequest req;

            view_msg->time_from_start = ros::Duration(0.1);
            ros::Time t_now = ros::Time::now();
            view_msg->eye.header.stamp = t_now;
            view_msg->focus.header.stamp = t_now;
            view_msg->up.header.stamp = t_now;

            req.camera_placement = *view_msg;
            req.planning_scene = ps_msg;
            req.motion_plan_request = mpr_msg;
            req.robot_trajectory = rt_msg;

            // same filename, counter for viewpoint
            std::string ext = boost::lexical_cast<std::string>(view_counter++) + ".ogv";
            std_msgs::String filemsg; filemsg.data = req.filepath;
            bag.write(filepath.string(), ros::Time::now(), filemsg);
            std::string video_file = filepath.string()+ext;

            req.filepath = video_file;

            recorder.record(req);
            recorder.startCapture();
            ROS_INFO("RECORDING DONE!");
          }//view
          bag.close();
        }//traj
      }//query
    }//scene
  }
  catch(mongo_ros::DbConnectException &ex)
  {
    ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
        << std::endl << ex.what());
  }

  ROS_INFO("Successfully performed trajectory playback");
  ros::shutdown();
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>MIOpen add OpenCL backend deprecation Message (#1664)<commit_after><|endoftext|>


<commit_before><commit_msg>fixed formatting<commit_after><|endoftext|>


<commit_before>/* -*- C++ -*-
    This file is part of ThreadWeaver.

    SPDX-FileCopyrightText: 2005-2014 Mirko Boehm <mirko@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include <QtDebug>
#include <QFile>
#include <QFileInfo>
#include <QLocale>
#include <QImageReader>
#include <QBuffer>

#include <ThreadWeaver/ThreadWeaver>
#include <ThreadWeaver/Exception>

#include "Image.h"
#include "Model.h"

//const int Image::ThumbHeight = 75;
//const int Image::ThumbWidth = 120;
const int Image::ThumbHeight = 60;
const int Image::ThumbWidth = 80;
QReadWriteLock Image::Lock;
int Image::ProcessingOrder;

Image::Image(const QString inputFileName, const QString outputFileName, Model *model, int id)
    : m_inputFileName(inputFileName)
    , m_outputFileName(outputFileName)
    , m_model(model)
    , m_id(id)
{
}

Progress Image::progress() const
{
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
    return qMakePair(m_progress.load(), Step_NumberOfSteps);
#else
    return qMakePair(m_progress.loadRelaxed(), Step_NumberOfSteps);
#endif
}

QString Image::description() const
{
    QReadLocker l(&Lock);
    return m_description;
}

QString Image::details() const
{
    QReadLocker l(&Lock);
    return m_details;
}

QString Image::details2() const
{
    QReadLocker l(&Lock);
    return m_details2;
}

int Image::processingOrder() const
{
    return m_processingOrder.loadAcquire();
}

const QString Image::inputFileName() const
{
    return m_inputFileName;
}

const QString Image::outputFileName() const
{
    return m_outputFileName;
}

QImage Image::thumbNail() const
{
    QReadLocker r(&Lock);
    return m_thumbnail;
}

void Image::loadFile()
{
    m_processingOrder.storeRelease(ProcessingOrder++);
    QFile file(m_inputFileName);
    if (!file.open(QIODevice::ReadOnly)) {
        error(Step_LoadFile, tr("Unable to load input file!"));
    }
    m_imageData = file.readAll();
    QFileInfo fi(file);
    QLocale locale;
    QString details2 = tr("%1kB").arg(locale.toString(fi.size()/1024));
    {
        QWriteLocker l(&Lock);
        m_description = fi.fileName();
        m_details2 = details2;
    }
    announceProgress(Step_LoadFile);
}

void Image::loadImage()
{
    m_processingOrder.storeRelease(ProcessingOrder++);
    QBuffer in(&m_imageData);
    in.open(QIODevice::ReadOnly);
    QImageReader reader(&in);
    m_image = reader.read();
    m_imageData.clear();
    if (m_image.isNull()) {
        QWriteLocker l(&Lock);
        m_details = tr("%1!").arg(reader.errorString());
        error(Step_LoadImage, m_details);
    }
    QString details = tr("%1x%2 pixels")
            .arg(m_image.width())
            .arg(m_image.height());
    {
        QWriteLocker l(&Lock);
        m_details = details;
    }
    announceProgress(Step_LoadImage);
}

void Image::computeThumbNail()
{
    m_processingOrder.storeRelease(ProcessingOrder++);
    QImage thumb = m_image.scaled(ThumbWidth, ThumbHeight,  Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
    if (thumb.isNull()) {
        error(Step_ComputeThumbNail, tr("Unable to compute thumbnail!"));
    }
    {   // thumb is implicitly shared, no copy:
        QWriteLocker l(&Lock);
        m_thumbnail = thumb;
    }

    m_image = QImage();
    announceProgress(Step_ComputeThumbNail);
}

void Image::saveThumbNail()
{
    QImage thumb;
    {
        QReadLocker r(&Lock);
        thumb = m_thumbnail;
    }
    if (!thumb.save(m_outputFileName)) {
        error(Step_SaveThumbNail, tr("Unable to save output file!"));
    }
    announceProgress(Step_SaveThumbNail);
}

void Image::announceProgress(Steps step)
{
    m_progress.storeRelease(step);
    if (m_model) {
        m_model->progressChanged();
        m_model->elementChanged(m_id);
    }
}

void Image::error(Image::Steps step, const QString &message)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
    m_failedStep.store(step);
#else
    m_failedStep.storeRelaxed(step);
#endif
    announceProgress(Step_Complete);
    throw ThreadWeaver::JobFailed(message);
}
<commit_msg>QBasicAtomicInteger<T>::storeRelaxed() is available since 5.14<commit_after>/* -*- C++ -*-
    This file is part of ThreadWeaver.

    SPDX-FileCopyrightText: 2005-2014 Mirko Boehm <mirko@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include <QtDebug>
#include <QFile>
#include <QFileInfo>
#include <QLocale>
#include <QImageReader>
#include <QBuffer>

#include <ThreadWeaver/ThreadWeaver>
#include <ThreadWeaver/Exception>

#include "Image.h"
#include "Model.h"

//const int Image::ThumbHeight = 75;
//const int Image::ThumbWidth = 120;
const int Image::ThumbHeight = 60;
const int Image::ThumbWidth = 80;
QReadWriteLock Image::Lock;
int Image::ProcessingOrder;

Image::Image(const QString inputFileName, const QString outputFileName, Model *model, int id)
    : m_inputFileName(inputFileName)
    , m_outputFileName(outputFileName)
    , m_model(model)
    , m_id(id)
{
}

Progress Image::progress() const
{
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
    return qMakePair(m_progress.load(), Step_NumberOfSteps);
#else
    return qMakePair(m_progress.loadRelaxed(), Step_NumberOfSteps);
#endif
}

QString Image::description() const
{
    QReadLocker l(&Lock);
    return m_description;
}

QString Image::details() const
{
    QReadLocker l(&Lock);
    return m_details;
}

QString Image::details2() const
{
    QReadLocker l(&Lock);
    return m_details2;
}

int Image::processingOrder() const
{
    return m_processingOrder.loadAcquire();
}

const QString Image::inputFileName() const
{
    return m_inputFileName;
}

const QString Image::outputFileName() const
{
    return m_outputFileName;
}

QImage Image::thumbNail() const
{
    QReadLocker r(&Lock);
    return m_thumbnail;
}

void Image::loadFile()
{
    m_processingOrder.storeRelease(ProcessingOrder++);
    QFile file(m_inputFileName);
    if (!file.open(QIODevice::ReadOnly)) {
        error(Step_LoadFile, tr("Unable to load input file!"));
    }
    m_imageData = file.readAll();
    QFileInfo fi(file);
    QLocale locale;
    QString details2 = tr("%1kB").arg(locale.toString(fi.size()/1024));
    {
        QWriteLocker l(&Lock);
        m_description = fi.fileName();
        m_details2 = details2;
    }
    announceProgress(Step_LoadFile);
}

void Image::loadImage()
{
    m_processingOrder.storeRelease(ProcessingOrder++);
    QBuffer in(&m_imageData);
    in.open(QIODevice::ReadOnly);
    QImageReader reader(&in);
    m_image = reader.read();
    m_imageData.clear();
    if (m_image.isNull()) {
        QWriteLocker l(&Lock);
        m_details = tr("%1!").arg(reader.errorString());
        error(Step_LoadImage, m_details);
    }
    QString details = tr("%1x%2 pixels")
            .arg(m_image.width())
            .arg(m_image.height());
    {
        QWriteLocker l(&Lock);
        m_details = details;
    }
    announceProgress(Step_LoadImage);
}

void Image::computeThumbNail()
{
    m_processingOrder.storeRelease(ProcessingOrder++);
    QImage thumb = m_image.scaled(ThumbWidth, ThumbHeight,  Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation);
    if (thumb.isNull()) {
        error(Step_ComputeThumbNail, tr("Unable to compute thumbnail!"));
    }
    {   // thumb is implicitly shared, no copy:
        QWriteLocker l(&Lock);
        m_thumbnail = thumb;
    }

    m_image = QImage();
    announceProgress(Step_ComputeThumbNail);
}

void Image::saveThumbNail()
{
    QImage thumb;
    {
        QReadLocker r(&Lock);
        thumb = m_thumbnail;
    }
    if (!thumb.save(m_outputFileName)) {
        error(Step_SaveThumbNail, tr("Unable to save output file!"));
    }
    announceProgress(Step_SaveThumbNail);
}

void Image::announceProgress(Steps step)
{
    m_progress.storeRelease(step);
    if (m_model) {
        m_model->progressChanged();
        m_model->elementChanged(m_id);
    }
}

void Image::error(Image::Steps step, const QString &message)
{
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
    m_failedStep.store(step);
#else
    m_failedStep.storeRelaxed(step);
#endif
    announceProgress(Step_Complete);
    throw ThreadWeaver::JobFailed(message);
}
<|endoftext|>


<commit_before>/*
***************************************
*   Asylum3D @ 2014-12-17
***************************************
*/

#ifndef __ASYLUM3D_HPP__
#define __ASYLUM3D_HPP__

/* Asylum Namespace */
namespace asy {

/***************/
/* Effect Port */
/***************/
class IEffect : public asylum
{
public:
    /* ================ */
    virtual ~IEffect () {}

public:
    /* ==================== */
    virtual void enter () = 0;

    /* ==================== */
    virtual void leave () = 0;
};

/******************/
/* Attribute Port */
/******************/
class IAttrib : public asylum
{
protected:
    int64u  m_type;

public:
    /* ================ */
    virtual ~IAttrib () {}

public:
    /* ===================== */
    virtual void commit () = 0;

    /* ============== */
    int64u type () const
    {
        return (m_type);
    }
};

// Attribute Type
#define ATTR_TYPE_ALPHAOP   0x00000001ULL   // Alpha Blend
#define ATTR_TYPE_TEXTURE   0x00000002ULL   // Have Texture
#define ATTR_TYPE_SPECULAR  0x00000004ULL   // Specular Light
#define ATTR_TYPE_NRML_MAP  0x00000008ULL   // Normal Map
#define ATTR_TYPE_LGHT_MAP  0x00000010ULL   // Light Map

/*************/
/* Mesh Port */
/*************/
class IMesh : public asylum
{
public:
    /* ============== */
    virtual ~IMesh () {}

    /* ===================== */
    virtual void commit () = 0;
};

/****************/
/* Commit Batch */
/****************/
struct commit_batch
{
    IMesh**     mesh;
    IAttrib*    attr;

    /* ====== */
    void free ()
    {
        IMesh*  tmp;
        size_t  idx;

        if (this->attr != NULL)
            delete this->attr;
        if (this->mesh != NULL) {
            for (idx = 0; ; idx++) {
                tmp = this->mesh[idx];
                if (tmp == NULL)
                    break;
                delete tmp;
            }
            mem_free(this->mesh);
        }
    }
};

/***************/
/* Object Base */
/***************/
struct object_base
{
    void*               real;
    sAABB               aabb;
    sSPHERE             ball;
    array<commit_batch> list;
    void (*kill) (void* real);

    /* ====== */
    void free ()
    {
        this->list.free();
        if (this->real != NULL &&
            this->kill != NULL)
            this->kill(this->real);
    }
};

/*******************/
/* Object Instance */
/*******************/
struct object_inst
{
    object_base*    base;

    union {
        mat4x4_t    mat;
        struct {
            vec3d_t rote;
            vec3d_t move;
            vec3d_t scale;
        } sep;
    } trans;

    union {
        sAABB   aabb;
        sSPHERE ball;
    } bound;

    /* ========= */
    void free () {}
};

}   /* namespace */

#endif  /* __ASYLUM3D_HPP__ */
<commit_msg>Asylum: 增加提交管线类型<commit_after>/*
***************************************
*   Asylum3D @ 2014-12-17
***************************************
*/

#ifndef __ASYLUM3D_HPP__
#define __ASYLUM3D_HPP__

/* Asylum Namespace */
namespace asy {

/***************/
/* Effect Port */
/***************/
class IEffect : public asylum
{
public:
    /* ================ */
    virtual ~IEffect () {}

public:
    /* ==================== */
    virtual void enter () = 0;

    /* ==================== */
    virtual void leave () = 0;
};

/******************/
/* Attribute Port */
/******************/
class IAttrib : public asylum
{
protected:
    int64u  m_type;

public:
    /* ================ */
    virtual ~IAttrib () {}

public:
    /* ===================== */
    virtual void commit () = 0;

    /* ============== */
    int64u type () const
    {
        return (m_type);
    }
};

// Attribute Type
#define ATTR_TYPE_ALPHAOP   0x00000001ULL   // Alpha Blend
#define ATTR_TYPE_TEXTURE   0x00000002ULL   // Have Texture
#define ATTR_TYPE_SPECULAR  0x00000004ULL   // Specular Light
#define ATTR_TYPE_NRML_MAP  0x00000008ULL   // Normal Map
#define ATTR_TYPE_LGHT_MAP  0x00000010ULL   // Light Map

/*************/
/* Mesh Port */
/*************/
class IMesh : public asylum
{
public:
    /* ============== */
    virtual ~IMesh () {}

    /* ===================== */
    virtual void commit () = 0;
};

/****************/
/* Commit Batch */
/****************/
struct commit_batch
{
    IMesh**     mesh;
    IAttrib*    attr;

    /* ====== */
    void free ()
    {
        IMesh*  tmp;
        size_t  idx;

        if (this->attr != NULL)
            delete this->attr;
        if (this->mesh != NULL) {
            for (idx = 0; ; idx++) {
                tmp = this->mesh[idx];
                if (tmp == NULL)
                    break;
                delete tmp;
            }
            mem_free(this->mesh);
        }
    }
};

/***************/
/* Object Base */
/***************/
struct object_base
{
    void*               real;
    sAABB               aabb;
    sSPHERE             ball;
    array<commit_batch> list;
    void (*kill) (void* real);

    /* ====== */
    void free ()
    {
        this->list.free();
        if (this->real != NULL &&
            this->kill != NULL)
            this->kill(this->real);
    }
};

/*******************/
/* Object Instance */
/*******************/
struct object_inst
{
    object_base*    base;

    union {
        mat4x4_t    mat;
        struct {
            vec3d_t rote;
            vec3d_t move;
            vec3d_t scale;
        } sep;
    } trans;

    union {
        sAABB   aabb;
        sSPHERE ball;
    } bound;

    /* ========= */
    void free () {}
};

/***************/
/* Commit Pipe */
/***************/
struct commit_pipe
{
    array<cnode_ptr>    stuff_list;     // <commit_batch*>
    array<cnode_ptr>    effect_stack;   // <IEffect*>

    void free ()
    {
        size_t      size;
        IEffect*    ffct;
        cnode_ptr*  data;

        this->stuff_list.free();
        size = this->effect_stack.size();
        data = this->effect_stack.data();
        for (size_t idx = 0; idx < size; idx++) {
            ffct = (IEffect*)(data[idx].ptr);
            delete ffct;
        }
        this->effect_stack.free();
    }
};

}   /* namespace */

#endif  /* __ASYLUM3D_HPP__ */
<|endoftext|>


<commit_before>#include <iostream>
#include <gtest/gtest.h>

TEST(sizeof, test1) {
    char str1[10];
    char str2[] = "Hello World!";

    EXPECT_EQ(10, sizeof(str1));
    EXPECT_EQ(13, sizeof(str2));
}

TEST(memcpy, test1) {
    int a[] = {1, 2, 3};
    int b[3];

    memcpy(b, a, sizeof(int) * 3);

    EXPECT_EQ(1, b[0]);
    EXPECT_EQ(2, b[1]);
    EXPECT_EQ(3, b[2]);
}

TEST(swap, test1) {
    int a = 1;
    int b = 2;

    std::swap(a, b);

    EXPECT_EQ(2, a);
    EXPECT_EQ(1, b);
}

TEST(array, test1) {
    int foo[2] = {1};

    EXPECT_EQ(1, foo[0]);
    EXPECT_EQ(0, foo[1]);
}
<commit_msg>Add array sorting<commit_after>#include <iostream>
#include <algorithm>
#include <gtest/gtest.h>

TEST(sizeof, test1) {
    char str1[10];
    char str2[] = "Hello World!";

    EXPECT_EQ(10, sizeof(str1));
    EXPECT_EQ(13, sizeof(str2));
}

TEST(memcpy, test1) {
    int a[] = {1, 2, 3};
    int b[3];

    memcpy(b, a, sizeof(int) * 3);

    EXPECT_EQ(1, b[0]);
    EXPECT_EQ(2, b[1]);
    EXPECT_EQ(3, b[2]);
}

TEST(swap, test1) {
    int a = 1;
    int b = 2;

    std::swap(a, b);

    EXPECT_EQ(2, a);
    EXPECT_EQ(1, b);
}

TEST(array, test1) {
    int foo[2] = {1};

    EXPECT_EQ(1, foo[0]);
    EXPECT_EQ(0, foo[1]);
}

TEST(array, sorting) {
    int foo[3] = {1, 3, 2};

    std::sort(foo, foo + 3);

    EXPECT_EQ(1, foo[0]);
    EXPECT_EQ(2, foo[1]);
    EXPECT_EQ(3, foo[2]);
}
<|endoftext|>


<commit_before>//===- xray-log-reader.cc - XRay Log Reader Implementation ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XRay log reader implementation.
//
//===----------------------------------------------------------------------===//
#include <sys/types.h>

#include "xray-log-reader.h"
#include "xray-record-yaml.h"
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/FileSystem.h"

using namespace llvm;
using namespace llvm::xray;
using llvm::yaml::Input;

LogReader::LogReader(
    StringRef Filename, Error &Err, bool Sort,
    std::function<Error(StringRef, XRayFileHeader &, std::vector<XRayRecord> &)>
        Loader) {
  ErrorAsOutParameter Guard(&Err);
  int Fd;
  if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
    Err = make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
    return;
  }
  uint64_t FileSize;
  if (auto EC = sys::fs::file_size(Filename, FileSize)) {
    Err = make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
    return;
  }

  std::error_code EC;
  sys::fs::mapped_file_region MappedFile(
      Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
  if (EC) {
    Err = make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
    return;
  }

  if (auto E = Loader(StringRef(MappedFile.data(), MappedFile.size()),
                      FileHeader, Records)) {
    Err = std::move(E);
    return;
  }

  if (Sort)
    std::sort(
        Records.begin(), Records.end(),
        [](const XRayRecord &L, const XRayRecord &R) { return L.TSC < R.TSC; });
}

Error llvm::xray::NaiveLogLoader(StringRef Data, XRayFileHeader &FileHeader,
                                 std::vector<XRayRecord> &Records) {
  // FIXME: Maybe deduce whether the data is little or big-endian using some
  // magic bytes in the beginning of the file?

  // First 32 bytes of the file will always be the header. We assume a certain
  // format here:
  //
  //   (2)   uint16 : version
  //   (2)   uint16 : type
  //   (4)   uint32 : bitfield
  //   (8)   uint64 : cycle frequency
  //   (16)  -      : padding
  //
  if (Data.size() < 32)
    return make_error<StringError>(
        "Not enough bytes for an XRay log.",
        std::make_error_code(std::errc::invalid_argument));

  if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
    return make_error<StringError>(
        "Invalid-sized XRay data.",
        std::make_error_code(std::errc::invalid_argument));

  DataExtractor HeaderExtractor(Data, true, 8);
  uint32_t OffsetPtr = 0;
  FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr);
  FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr);
  uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr);
  FileHeader.ConstantTSC = Bitfield & 1uL;
  FileHeader.NonstopTSC = Bitfield & 1uL << 1;
  FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr);

  if (FileHeader.Version != 1)
    return make_error<StringError>(
        Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
        std::make_error_code(std::errc::invalid_argument));

  // Each record after the header will be 32 bytes, in the following format:
  //
  //   (2)   uint16 : record type
  //   (1)   uint8  : cpu id
  //   (1)   uint8  : type
  //   (4)   sint32 : function id
  //   (8)   uint64 : tsc
  //   (4)   uint32 : thread id
  //   (12)  -      : padding
  for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
    DataExtractor RecordExtractor(S, true, 8);
    uint32_t OffsetPtr = 0;
    Records.emplace_back();
    auto &Record = Records.back();
    Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
    Record.CPU = RecordExtractor.getU8(&OffsetPtr);
    auto Type = RecordExtractor.getU8(&OffsetPtr);
    switch (Type) {
    case 0:
      Record.Type = RecordTypes::ENTER;
      break;
    case 1:
      Record.Type = RecordTypes::EXIT;
      break;
    default:
      return make_error<StringError>(
          Twine("Unknown record type '") + Twine(int{Type}) + "'",
          std::make_error_code(std::errc::protocol_error));
    }
    Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
    Record.TSC = RecordExtractor.getU64(&OffsetPtr);
    Record.TId = RecordExtractor.getU32(&OffsetPtr);
  }
  return Error::success();
}

Error llvm::xray::YAMLLogLoader(StringRef Data, XRayFileHeader &FileHeader,
                                std::vector<XRayRecord> &Records) {

  // Load the documents from the MappedFile.
  YAMLXRayTrace Trace;
  Input In(Data);
  In >> Trace;
  if (In.error())
    return make_error<StringError>("Failed loading YAML Data.", In.error());

  FileHeader.Version = Trace.Header.Version;
  FileHeader.Type = Trace.Header.Type;
  FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
  FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
  FileHeader.CycleFrequency = Trace.Header.CycleFrequency;

  if (FileHeader.Version != 1)
    return make_error<StringError>(
        Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
        std::make_error_code(std::errc::invalid_argument));

  Records.clear();
  std::transform(Trace.Records.begin(), Trace.Records.end(),
                 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
                   return XRayRecord{R.RecordType, R.CPU, R.Type,
                                     R.FuncId,     R.TSC, R.TId};
                 });
  return Error::success();
}
<commit_msg>[XRay] Fixup includes for modules build<commit_after>//===- xray-log-reader.cc - XRay Log Reader Implementation ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// XRay log reader implementation.
//
//===----------------------------------------------------------------------===//
#include "xray-log-reader.h"
#include "xray-record-yaml.h"
#include "llvm/Support/DataExtractor.h"
#include "llvm/Support/FileSystem.h"

using namespace llvm;
using namespace llvm::xray;
using llvm::yaml::Input;

LogReader::LogReader(
    StringRef Filename, Error &Err, bool Sort,
    std::function<Error(StringRef, XRayFileHeader &, std::vector<XRayRecord> &)>
        Loader) {
  ErrorAsOutParameter Guard(&Err);
  int Fd;
  if (auto EC = sys::fs::openFileForRead(Filename, Fd)) {
    Err = make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
    return;
  }
  uint64_t FileSize;
  if (auto EC = sys::fs::file_size(Filename, FileSize)) {
    Err = make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
    return;
  }

  std::error_code EC;
  sys::fs::mapped_file_region MappedFile(
      Fd, sys::fs::mapped_file_region::mapmode::readonly, FileSize, 0, EC);
  if (EC) {
    Err = make_error<StringError>(
        Twine("Cannot read log from '") + Filename + "'", EC);
    return;
  }

  if (auto E = Loader(StringRef(MappedFile.data(), MappedFile.size()),
                      FileHeader, Records)) {
    Err = std::move(E);
    return;
  }

  if (Sort)
    std::sort(
        Records.begin(), Records.end(),
        [](const XRayRecord &L, const XRayRecord &R) { return L.TSC < R.TSC; });
}

Error llvm::xray::NaiveLogLoader(StringRef Data, XRayFileHeader &FileHeader,
                                 std::vector<XRayRecord> &Records) {
  // FIXME: Maybe deduce whether the data is little or big-endian using some
  // magic bytes in the beginning of the file?

  // First 32 bytes of the file will always be the header. We assume a certain
  // format here:
  //
  //   (2)   uint16 : version
  //   (2)   uint16 : type
  //   (4)   uint32 : bitfield
  //   (8)   uint64 : cycle frequency
  //   (16)  -      : padding
  //
  if (Data.size() < 32)
    return make_error<StringError>(
        "Not enough bytes for an XRay log.",
        std::make_error_code(std::errc::invalid_argument));

  if (Data.size() - 32 == 0 || Data.size() % 32 != 0)
    return make_error<StringError>(
        "Invalid-sized XRay data.",
        std::make_error_code(std::errc::invalid_argument));

  DataExtractor HeaderExtractor(Data, true, 8);
  uint32_t OffsetPtr = 0;
  FileHeader.Version = HeaderExtractor.getU16(&OffsetPtr);
  FileHeader.Type = HeaderExtractor.getU16(&OffsetPtr);
  uint32_t Bitfield = HeaderExtractor.getU32(&OffsetPtr);
  FileHeader.ConstantTSC = Bitfield & 1uL;
  FileHeader.NonstopTSC = Bitfield & 1uL << 1;
  FileHeader.CycleFrequency = HeaderExtractor.getU64(&OffsetPtr);

  if (FileHeader.Version != 1)
    return make_error<StringError>(
        Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
        std::make_error_code(std::errc::invalid_argument));

  // Each record after the header will be 32 bytes, in the following format:
  //
  //   (2)   uint16 : record type
  //   (1)   uint8  : cpu id
  //   (1)   uint8  : type
  //   (4)   sint32 : function id
  //   (8)   uint64 : tsc
  //   (4)   uint32 : thread id
  //   (12)  -      : padding
  for (auto S = Data.drop_front(32); !S.empty(); S = S.drop_front(32)) {
    DataExtractor RecordExtractor(S, true, 8);
    uint32_t OffsetPtr = 0;
    Records.emplace_back();
    auto &Record = Records.back();
    Record.RecordType = RecordExtractor.getU16(&OffsetPtr);
    Record.CPU = RecordExtractor.getU8(&OffsetPtr);
    auto Type = RecordExtractor.getU8(&OffsetPtr);
    switch (Type) {
    case 0:
      Record.Type = RecordTypes::ENTER;
      break;
    case 1:
      Record.Type = RecordTypes::EXIT;
      break;
    default:
      return make_error<StringError>(
          Twine("Unknown record type '") + Twine(int{Type}) + "'",
          std::make_error_code(std::errc::protocol_error));
    }
    Record.FuncId = RecordExtractor.getSigned(&OffsetPtr, sizeof(int32_t));
    Record.TSC = RecordExtractor.getU64(&OffsetPtr);
    Record.TId = RecordExtractor.getU32(&OffsetPtr);
  }
  return Error::success();
}

Error llvm::xray::YAMLLogLoader(StringRef Data, XRayFileHeader &FileHeader,
                                std::vector<XRayRecord> &Records) {

  // Load the documents from the MappedFile.
  YAMLXRayTrace Trace;
  Input In(Data);
  In >> Trace;
  if (In.error())
    return make_error<StringError>("Failed loading YAML Data.", In.error());

  FileHeader.Version = Trace.Header.Version;
  FileHeader.Type = Trace.Header.Type;
  FileHeader.ConstantTSC = Trace.Header.ConstantTSC;
  FileHeader.NonstopTSC = Trace.Header.NonstopTSC;
  FileHeader.CycleFrequency = Trace.Header.CycleFrequency;

  if (FileHeader.Version != 1)
    return make_error<StringError>(
        Twine("Unsupported XRay file version: ") + Twine(FileHeader.Version),
        std::make_error_code(std::errc::invalid_argument));

  Records.clear();
  std::transform(Trace.Records.begin(), Trace.Records.end(),
                 std::back_inserter(Records), [&](const YAMLXRayRecord &R) {
                   return XRayRecord{R.RecordType, R.CPU, R.Type,
                                     R.FuncId,     R.TSC, R.TId};
                 });
  return Error::success();
}
<|endoftext|>


<commit_before>#include "includes.h"
#include <sys/types.h>
#include <dirent.h>

void prepare_logdir()
{
    spdlog::drop_all();
#ifdef _WIN32
    system("if not exist logs mkdir logs");
    system("del /F /Q logs\\*");
#else
    auto rv = system("mkdir -p logs");
    if (rv != 0)
    {
        throw std::runtime_error("Failed to mkdir -p logs");
    }
    rv = system("rm -f logs/*");
    if (rv != 0)
    {
        throw std::runtime_error("Failed to rm -f logs/*");
    }
#endif
}

std::string file_contents(const std::string &filename)
{
    std::ifstream ifs(filename);
    if (!ifs)
    {
        throw std::runtime_error("Failed open file ");
    }
    return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
}

std::size_t count_lines(const std::string &filename)
{
    std::ifstream ifs(filename);
    if (!ifs)
    {
        throw std::runtime_error("Failed open file ");
    }

    std::string line;
    size_t counter = 0;
    while (std::getline(ifs, line))
        counter++;
    return counter;
}

std::size_t get_filesize(const std::string &filename)
{
    std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary);
    if (!ifs)
    {
        throw std::runtime_error("Failed open file ");
    }

    return static_cast<std::size_t>(ifs.tellg());
}

// source: https://stackoverflow.com/a/2072890/192001
bool ends_with(std::string const &value, std::string const &ending)
{
    if (ending.size() > value.size())
    {
        return false;
    }
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}

#ifdef _WIN32
std::size_t count_files(const std::string &folder) {}
#else
// Based on: https://stackoverflow.com/a/2802255/192001
std::size_t count_files(const std::string &folder)
{
    size_t counter = 0;
    DIR *dp = opendir(folder.c_str());
    if (dp == nullptr)
    {
        throw std::runtime_error("Failed open folder " + folder);
    }

    struct dirent *ep;
    while (ep = readdir(dp))
    {
        if (ep->d_name[0] != '.')
            counter++;
    }
    (void)closedir(dp);
    return counter;
}
#endif
<commit_msg>Update test utils for windows<commit_after>#include "includes.h"
#include <sys/types.h>
#include <dirent.h>

void prepare_logdir()
{
    spdlog::drop_all();
#ifdef _WIN32
    system("if not exist logs mkdir logs");
    system("del /F /Q logs\\*");
#else
    auto rv = system("mkdir -p logs");
    if (rv != 0)
    {
        throw std::runtime_error("Failed to mkdir -p logs");
    }
    rv = system("rm -f logs/*");
    if (rv != 0)
    {
        throw std::runtime_error("Failed to rm -f logs/*");
    }
#endif
}

std::string file_contents(const std::string &filename)
{
    std::ifstream ifs(filename);
    if (!ifs)
    {
        throw std::runtime_error("Failed open file ");
    }
    return std::string((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
}

std::size_t count_lines(const std::string &filename)
{
    std::ifstream ifs(filename);
    if (!ifs)
    {
        throw std::runtime_error("Failed open file ");
    }

    std::string line;
    size_t counter = 0;
    while (std::getline(ifs, line))
        counter++;
    return counter;
}

std::size_t get_filesize(const std::string &filename)
{
    std::ifstream ifs(filename, std::ifstream::ate | std::ifstream::binary);
    if (!ifs)
    {
        throw std::runtime_error("Failed open file ");
    }

    return static_cast<std::size_t>(ifs.tellg());
}

// source: https://stackoverflow.com/a/2072890/192001
bool ends_with(std::string const &value, std::string const &ending)
{
    if (ending.size() > value.size())
    {
        return false;
    }
    return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}

#ifdef _WIN32
// source: https://stackoverflow.com/a/37416569/192001
std::size_t count_files(const std::string &folder)
{
    counter counter = 0;
    WIN32_FIND_DATA ffd;
    HANDLE hFind = INVALID_HANDLE_VALUE;

    // Start iterating over the files in the path directory.
    hFind = ::FindFirstFileA(path.c_str(), &ffd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do // Managed to locate and create an handle to that folder.
        {
            counter++;
        } while (::FindNextFile(hFind, &ffd) == TRUE);
        ::FindClose(hFind);
    }
    else
    {
        throw std::runtime_error("Failed open folder " + folder);
    }

    return counter;
}
#else
// Based on: https://stackoverflow.com/a/2802255/192001
std::size_t count_files(const std::string &folder)
{
    size_t counter = 0;
    DIR *dp = opendir(folder.c_str());
    if (dp == nullptr)
    {
        throw std::runtime_error("Failed open folder " + folder);
    }

    struct dirent *ep;
    while (ep = readdir(dp))
    {
        if (ep->d_name[0] != '.')
            counter++;
    }
    (void)closedir(dp);
    return counter;
}
#endif
<|endoftext|>