<commit_before>/*
 * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

#include <QStandardPaths>
#include <QDir>
#include <QDebug>
#include <QThread>

#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include <iostream>

#include <QOpenGLContext>
#include <QOffscreenSurface>
#include <QOpenGLFunctions>

int getMaxTextureSize()
{
    // Create a temp context - required if this is called from another thread
    QOpenGLContext ctx;
    if ( !ctx.create() )
    {
        // TODO handle the error
        qDebug() << "No OpenGL context could be created, this is clearly bad...";
        exit(-1);
    }

    // rather than using a QWindow - which actually dosen't seem to work in this case either!
    QOffscreenSurface surface;
    surface.setFormat( ctx.format() );
    surface.create();

    ctx.makeCurrent(&surface);

    // Now the call works
    QOpenGLFunctions glFuncs(QOpenGLContext::currentContext());
    int maxSize = 0;
    glFuncs.glEnable(GL_TEXTURE_2D);
    glFuncs.glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);

    return maxSize;
}

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("Peruse");

    QCommandLineParser parser;
    // TODO file option for opening comics by passing them through on the command line
    parser.addHelpOption();
    parser.process(app);

    if (parser.positionalArguments().size() > 1) {
        parser.showHelp(1);
    }

    QQmlEngine engine;

#ifdef Q_OS_WIN
    // Because windows is a bit funny with paths and whatnot, just so the thing with the lib paths...
    QDir appdir(qApp->applicationDirPath());
    appdir.cdUp();
    engine.addImportPath(appdir.canonicalPath() + "/lib/qml");
    engine.rootContext()->setContextProperty("osIsWindows", true);
    // Hey, let's try and avoid all those extra stale processes, right?
    qputenv("KDE_FORK_SLAVES", "true");
#endif

    QQmlContext* objectContext = engine.rootContext();
    QString platformEnv(qgetenv("PLASMA_PLATFORM"));
    engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv);
    // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for
    // things like the archive book model to create imageproviders for the archives
    engine.rootContext()->setContextProperty("globalQmlEngine", &engine);
    engine.rootContext()->setContextProperty("maxTextureSize", getMaxTextureSize());

    QString path;
    if (platformEnv.startsWith("phone")) {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml");
    } else {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml");
    }
    int rt = 0;
    QQmlComponent component(&engine, path);
    if (component.isError())
    {
        qCritical() << "Failed to load the component from disk. Reported error was:" << component.errorString();
        rt = -1;
    }
    else
    {
        if(component.status() == QQmlComponent::Ready)
        {
            QObject* obj = component.create(objectContext);
            if(obj)
            {
                rt = app.exec();
            }
            else
            {
                qCritical() << "Failed to create an object from our component";
                rt = -2;
            }
        }
        else
        {
            qCritical() << "Failed to make the Qt Quick component ready. Status is:" << component.status();
            rt = -3;
        }
    }

    return rt;
}
<commit_msg>Don't complain about missing properties ;) (oops)<commit_after>/*
 * Copyright (C) 2015 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

#include <QStandardPaths>
#include <QDir>
#include <QDebug>
#include <QThread>

#include <KLocalizedString>

#include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption>

#include <iostream>

#include <QOpenGLContext>
#include <QOffscreenSurface>
#include <QOpenGLFunctions>

int getMaxTextureSize()
{
    // Create a temp context - required if this is called from another thread
    QOpenGLContext ctx;
    if ( !ctx.create() )
    {
        // TODO handle the error
        qDebug() << "No OpenGL context could be created, this is clearly bad...";
        exit(-1);
    }

    // rather than using a QWindow - which actually dosen't seem to work in this case either!
    QOffscreenSurface surface;
    surface.setFormat( ctx.format() );
    surface.create();

    ctx.makeCurrent(&surface);

    // Now the call works
    QOpenGLFunctions glFuncs(QOpenGLContext::currentContext());
    int maxSize = 0;
    glFuncs.glEnable(GL_TEXTURE_2D);
    glFuncs.glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxSize);

    return maxSize;
}

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    app.setApplicationDisplayName("Peruse");

    QCommandLineParser parser;
    // TODO file option for opening comics by passing them through on the command line
    parser.addHelpOption();
    parser.process(app);

    if (parser.positionalArguments().size() > 1) {
        parser.showHelp(1);
    }

    QQmlEngine engine;

    bool osIsWindows = false;
#ifdef Q_OS_WIN
    // Because windows is a bit funny with paths and whatnot, just so the thing with the lib paths...
    QDir appdir(qApp->applicationDirPath());
    appdir.cdUp();
    engine.addImportPath(appdir.canonicalPath() + "/lib/qml");
    osIsWindows = true;
    // Hey, let's try and avoid all those extra stale processes, right?
    qputenv("KDE_FORK_SLAVES", "true");
#endif
    engine.rootContext()->setContextProperty("osIsWindows", osIsWindows);

    QQmlContext* objectContext = engine.rootContext();
    QString platformEnv(qgetenv("PLASMA_PLATFORM"));
    engine.rootContext()->setContextProperty("PLASMA_PLATFORM", platformEnv);
    // Yes, i realise this is a touch on the ugly side. I have found no better way to allow for
    // things like the archive book model to create imageproviders for the archives
    engine.rootContext()->setContextProperty("globalQmlEngine", &engine);
    engine.rootContext()->setContextProperty("maxTextureSize", getMaxTextureSize());

    QString path;
    if (platformEnv.startsWith("phone")) {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/MobileMain.qml");
    } else {
        path = QStandardPaths::locate(QStandardPaths::DataLocation, "qml/Main.qml");
    }
    int rt = 0;
    QQmlComponent component(&engine, path);
    if (component.isError())
    {
        qCritical() << "Failed to load the component from disk. Reported error was:" << component.errorString();
        rt = -1;
    }
    else
    {
        if(component.status() == QQmlComponent::Ready)
        {
            QObject* obj = component.create(objectContext);
            if(obj)
            {
                rt = app.exec();
            }
            else
            {
                qCritical() << "Failed to create an object from our component";
                rt = -2;
            }
        }
        else
        {
            qCritical() << "Failed to make the Qt Quick component ready. Status is:" << component.status();
            rt = -3;
        }
    }

    return rt;
}
<|endoftext|>


<commit_before>#include "arpTable.hpp"

using namespace std;
using namespace headers;

constexpr array<uint8_t, 6> ARPTable::nextHop::invalidMac;

void ARPTable::createCurrentTable(std::shared_ptr<RoutingTable> routingTable){
	logDebug("ARPTable::createCurrentTable constructing tables for mapping");

	// create a new table;
	shared_ptr<table> newTable = make_shared<table>(std::vector<nextHop>(), directlyConnected);
	auto next_hop_addresses = routingTable->getNextHopMapping();

	newTable->nextHops.resize(next_hop_addresses->size());
	for(auto nh : *next_hop_addresses){
		if(nh.interface->netmapIndex == uint16_t_max){
			logDebug("invalid nh interface");
			abort();
		}
		newTable->nextHops[nh.index].netmapInterface = nh.interface->netmapIndex;
		newTable->nextHops[nh.index].mac = {{0}}; // just initialize
		if(mapping.count(nh.nh_ip)){
			newTable->nextHops[nh.index].mac = mapping[nh.nh_ip].mac;
		}
	}

	currentTable = newTable;
};

void ARPTable::prepareRequest(uint32_t ip, uint16_t iface, frame& frame){
	logDebug("ARPTable::prepareRequest Preparing ARP request now");

	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	shared_ptr<Interface> iface_ptr;
	for(auto i : interfaces){
		if(i->netmapIndex == iface){
			iface_ptr = i;
			break;
		}
	}

	if(iface_ptr == nullptr){
		abort();
	}

	ether_hdr->s_mac = iface_ptr->mac;
	for(int i=0; i<6; i++){
		ether_hdr->d_mac[i] = 0xff;
	}

	arp_hdr->hw_type = htons(0x0001);
	arp_hdr->proto_type = htons(0x0800);
	arp_hdr->hw_len = 6;
	arp_hdr->proto_len = 4;
	arp_hdr->op = arp::OP_REQUEST;

	arp_hdr->s_hw_addr = iface_ptr->mac;
	if(iface_ptr->IPs.empty()){
		fatal("Cannot send ARP request without an IP address on interface");
	}
	arp_hdr->s_proto_addr = iface_ptr->IPs.front();
	arp_hdr->t_hw_addr = {{0}};
	arp_hdr->t_proto_addr = htonl(ip);

	frame.len = sizeof(ether) + sizeof(arp);
}

void ARPTable::handleReply(frame& frame){
	logDebug("ARPTable::handleReply Looking at ARP reply now");

	// ARP is stateless -> doesn't mapper if we actually sent a request
	uint32_t ip;
	std::array<uint8_t, 6> mac;
	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	if(ether_hdr->ethertype != htons(0x0806)){
		logErr("Frame falsely sent to ARPTable::handleReply()");
		return;
	}

	if(ntohs(arp_hdr->op) != arp::OP_REPLY){
		// This is not a reply
		logErr("Frame falsely sent to ARPTable::handleReply()");
		return;
	}

	ip = ntohl(arp_hdr->s_proto_addr);
	mac = arp_hdr->s_hw_addr;

	nextHop nextHop;

	nextHop.mac = mac;
	nextHop.netmapInterface = frame.iface & frame::IFACE_ID;

	auto next_hop_addresses = routingTable->getNextHopMapping();

	// Check if this is a registered next hop
	for(auto& nh : *next_hop_addresses){
		if(nh.nh_ip == ip && nh.interface->netmapIndex == (frame.iface & frame::IFACE_ID)){
			mapping.insert({ip, nextHop});
			currentTable->nextHops[nh.index].mac = mac;

			return;
		}
	}

	// In case we reach this, the node is directly connected
	directlyConnected.insert({ip, nextHop});
}

void ARPTable::handleRequest(frame& frame){
	logDebug("ARPTable::handleRequest looking at request now");
	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	if(ether_hdr->ethertype != htons(0x0806)){
		logErr("Frame falsely sent to ARPTable::handleRequest()");
		return;
	}

	if(ntohs(arp_hdr->op) != arp::OP_REQUEST){
		logErr("Frame falsely sent to ARPTable::handleRequest()");
		return;
	}

	shared_ptr<Interface> iface_ptr;
	for(auto i : interfaces){
		if(i->netmapIndex == (frame.iface & frame::IFACE_ID)){
			iface_ptr = i;
			break;
		}
	}

	if(iface_ptr == nullptr){
		abort();
	}

	// Check if we are asked
	if(!count(iface_ptr->IPs.begin(), iface_ptr->IPs.end(),
			ntohl(arp_hdr->t_proto_addr))){
		logDebug("Got ARP request for some other node (IP: "
				 + ip_to_str(ntohl(arp_hdr->t_proto_addr)) + "), discarding");
		frame.iface = frame::IFACE_DISCARD;
		return;
	}

	// Turn the request into a reply
	arp_hdr->op = htons(arp::OP_REPLY);

	arp_hdr->t_hw_addr = arp_hdr->s_hw_addr;
	uint32_t t_ip = arp_hdr->t_proto_addr;
	arp_hdr->t_proto_addr = arp_hdr->s_proto_addr;

	arp_hdr->s_hw_addr = iface_ptr->mac;
	arp_hdr->s_proto_addr = t_ip;

	ether_hdr->s_mac = iface_ptr->mac;
	for(int i=0; i<6; i++){
		ether_hdr->d_mac[i] = 0xff;
	}

}

void ARPTable::handleFrame(frame& frame){
	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	if(ether_hdr->ethertype != htons(0x0806)){
		logErr("Frame falsely sent to ARPTable::handleFrame()");
		return;
	}

	if(ntohs(arp_hdr->op) == arp::OP_REQUEST){
		handleRequest(frame);
	} else if(ntohs(arp_hdr->op) == arp::OP_REPLY){
		handleReply(frame);
	} else {
		logErr("Unknown ARP OP detected");
	}
}
<commit_msg>use different initialization method<commit_after>#include "arpTable.hpp"

using namespace std;
using namespace headers;

constexpr array<uint8_t, 6> ARPTable::nextHop::invalidMac;

void ARPTable::createCurrentTable(std::shared_ptr<RoutingTable> routingTable){
	logDebug("ARPTable::createCurrentTable constructing tables for mapping");

	// create a new table;
	shared_ptr<table> newTable = make_shared<table>(std::vector<nextHop>(), directlyConnected);
	auto next_hop_addresses = routingTable->getNextHopMapping();

	newTable->nextHops.resize(next_hop_addresses->size());
	for(auto nh : *next_hop_addresses){
		if(nh.interface->netmapIndex == uint16_t_max){
			logDebug("invalid nh interface");
			abort();
		}
		newTable->nextHops[nh.index].netmapInterface = nh.interface->netmapIndex;
		//newTable->nextHops[nh.index].mac = {{0}}; // just initialize
		for(int i=0; i<6; i++){
			newTable->nextHops[nh.index].mac[i] = 0;
		}
		if(mapping.count(nh.nh_ip)){
			newTable->nextHops[nh.index].mac = mapping[nh.nh_ip].mac;
		}
	}

	currentTable = newTable;
};

void ARPTable::prepareRequest(uint32_t ip, uint16_t iface, frame& frame){
	logDebug("ARPTable::prepareRequest Preparing ARP request now");

	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	shared_ptr<Interface> iface_ptr;
	for(auto i : interfaces){
		if(i->netmapIndex == iface){
			iface_ptr = i;
			break;
		}
	}

	if(iface_ptr == nullptr){
		abort();
	}

	ether_hdr->s_mac = iface_ptr->mac;
	for(int i=0; i<6; i++){
		ether_hdr->d_mac[i] = 0xff;
	}

	arp_hdr->hw_type = htons(0x0001);
	arp_hdr->proto_type = htons(0x0800);
	arp_hdr->hw_len = 6;
	arp_hdr->proto_len = 4;
	arp_hdr->op = arp::OP_REQUEST;

	arp_hdr->s_hw_addr = iface_ptr->mac;
	if(iface_ptr->IPs.empty()){
		fatal("Cannot send ARP request without an IP address on interface");
	}
	arp_hdr->s_proto_addr = iface_ptr->IPs.front();
	//arp_hdr->t_hw_addr = {{0}};
	for(int i=0; i<6; i++){
		arp_hdr->t_hw_addr[i] = 0;
	}
	arp_hdr->t_proto_addr = htonl(ip);

	frame.len = sizeof(ether) + sizeof(arp);
}

void ARPTable::handleReply(frame& frame){
	logDebug("ARPTable::handleReply Looking at ARP reply now");

	// ARP is stateless -> doesn't mapper if we actually sent a request
	uint32_t ip;
	std::array<uint8_t, 6> mac;
	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	if(ether_hdr->ethertype != htons(0x0806)){
		logErr("Frame falsely sent to ARPTable::handleReply()");
		return;
	}

	if(ntohs(arp_hdr->op) != arp::OP_REPLY){
		// This is not a reply
		logErr("Frame falsely sent to ARPTable::handleReply()");
		return;
	}

	ip = ntohl(arp_hdr->s_proto_addr);
	mac = arp_hdr->s_hw_addr;

	nextHop nextHop;

	nextHop.mac = mac;
	nextHop.netmapInterface = frame.iface & frame::IFACE_ID;

	auto next_hop_addresses = routingTable->getNextHopMapping();

	// Check if this is a registered next hop
	for(auto& nh : *next_hop_addresses){
		if(nh.nh_ip == ip && nh.interface->netmapIndex == (frame.iface & frame::IFACE_ID)){
			mapping.insert({ip, nextHop});
			currentTable->nextHops[nh.index].mac = mac;

			return;
		}
	}

	// In case we reach this, the node is directly connected
	directlyConnected.insert({ip, nextHop});
}

void ARPTable::handleRequest(frame& frame){
	logDebug("ARPTable::handleRequest looking at request now");
	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	if(ether_hdr->ethertype != htons(0x0806)){
		logErr("Frame falsely sent to ARPTable::handleRequest()");
		return;
	}

	if(ntohs(arp_hdr->op) != arp::OP_REQUEST){
		logErr("Frame falsely sent to ARPTable::handleRequest()");
		return;
	}

	shared_ptr<Interface> iface_ptr;
	for(auto i : interfaces){
		if(i->netmapIndex == (frame.iface & frame::IFACE_ID)){
			iface_ptr = i;
			break;
		}
	}

	if(iface_ptr == nullptr){
		abort();
	}

	// Check if we are asked
	if(!count(iface_ptr->IPs.begin(), iface_ptr->IPs.end(),
			ntohl(arp_hdr->t_proto_addr))){
		logDebug("Got ARP request for some other node (IP: "
				 + ip_to_str(ntohl(arp_hdr->t_proto_addr)) + "), discarding");
		frame.iface = frame::IFACE_DISCARD;
		return;
	}

	// Turn the request into a reply
	arp_hdr->op = htons(arp::OP_REPLY);

	arp_hdr->t_hw_addr = arp_hdr->s_hw_addr;
	uint32_t t_ip = arp_hdr->t_proto_addr;
	arp_hdr->t_proto_addr = arp_hdr->s_proto_addr;

	arp_hdr->s_hw_addr = iface_ptr->mac;
	arp_hdr->s_proto_addr = t_ip;

	ether_hdr->s_mac = iface_ptr->mac;
	for(int i=0; i<6; i++){
		ether_hdr->d_mac[i] = 0xff;
	}

}

void ARPTable::handleFrame(frame& frame){
	ether* ether_hdr = reinterpret_cast<ether*>(frame.buf_ptr);
	arp* arp_hdr = reinterpret_cast<arp*>(frame.buf_ptr + sizeof(ether));

	if(ether_hdr->ethertype != htons(0x0806)){
		logErr("Frame falsely sent to ARPTable::handleFrame()");
		return;
	}

	if(ntohs(arp_hdr->op) == arp::OP_REQUEST){
		handleRequest(frame);
	} else if(ntohs(arp_hdr->op) == arp::OP_REPLY){
		handleReply(frame);
	} else {
		logErr("Unknown ARP OP detected");
	}
}
<|endoftext|>


<commit_before>#include <llvm/ADT/StringRef.h>
#include <llvm/Support/ErrorHandling.h>
#include "decl.h"
#include "../support/utility.h"

using namespace delta;

const FuncType* FuncDecl::getFuncType() const {
    auto paramTypes = map(params, *[](const ParamDecl& p) -> Type { return p.type; });
    return &llvm::cast<FuncType>(*FuncType::get(returnType, std::move(paramTypes)));
}

bool FuncDecl::signatureMatches(const FuncDecl& other, bool matchReceiver) const {
    if (name != other.name) return false;
    if (matchReceiver && receiverType != other.receiverType) return false;
    if (mutating != other.mutating) return false;
    if (returnType != other.returnType) return false;
    if (params != other.params) return false;
    return true;
}

Type TypeDecl::getType(llvm::ArrayRef<Type> genericArgs, bool isMutable) const {
    assert(genericArgs.size() == genericParams.size());
    return BasicType::get(name, genericArgs, isMutable);
}

Type TypeDecl::getTypeForPassing(llvm::ArrayRef<Type> genericArgs, bool isMutable) const {
    switch (tag) {
        case TypeTag::Struct: case TypeTag::Union:
            return getType(genericArgs, isMutable);
        case TypeTag::Class: case TypeTag::Interface:
            return PtrType::get(getType(genericArgs, isMutable), true);
    }
}

unsigned TypeDecl::getFieldIndex(llvm::StringRef fieldName) const {
    for (unsigned index = 0, size = fields.size(); index < size; ++index) {
        if (fields[index].name == fieldName) return index;
    }
    fatalError("unknown field");
}

SrcLoc Decl::getSrcLoc() const {
    switch (getKind()) {
        case DeclKind::ParamDecl:  return getParamDecl().srcLoc;
        case DeclKind::FuncDecl:   return getFuncDecl().srcLoc;
        case DeclKind::GenericParamDecl: return getGenericParamDecl().srcLoc;
        case DeclKind::InitDecl:   return getInitDecl().srcLoc;
        case DeclKind::DeinitDecl: return getDeinitDecl().srcLoc;
        case DeclKind::TypeDecl:   return getTypeDecl().srcLoc;
        case DeclKind::VarDecl:    return getVarDecl().srcLoc;
        case DeclKind::FieldDecl:  return getFieldDecl().srcLoc;
        case DeclKind::ImportDecl: return getImportDecl().srcLoc;
    }
    llvm_unreachable("all cases handled");
}
<commit_msg>Fix gcc warning "control reaches end of non-void function"<commit_after>#include <llvm/ADT/StringRef.h>
#include <llvm/Support/ErrorHandling.h>
#include "decl.h"
#include "../support/utility.h"

using namespace delta;

const FuncType* FuncDecl::getFuncType() const {
    auto paramTypes = map(params, *[](const ParamDecl& p) -> Type { return p.type; });
    return &llvm::cast<FuncType>(*FuncType::get(returnType, std::move(paramTypes)));
}

bool FuncDecl::signatureMatches(const FuncDecl& other, bool matchReceiver) const {
    if (name != other.name) return false;
    if (matchReceiver && receiverType != other.receiverType) return false;
    if (mutating != other.mutating) return false;
    if (returnType != other.returnType) return false;
    if (params != other.params) return false;
    return true;
}

Type TypeDecl::getType(llvm::ArrayRef<Type> genericArgs, bool isMutable) const {
    assert(genericArgs.size() == genericParams.size());
    return BasicType::get(name, genericArgs, isMutable);
}

Type TypeDecl::getTypeForPassing(llvm::ArrayRef<Type> genericArgs, bool isMutable) const {
    switch (tag) {
        case TypeTag::Struct: case TypeTag::Union:
            return getType(genericArgs, isMutable);
        case TypeTag::Class: case TypeTag::Interface:
            return PtrType::get(getType(genericArgs, isMutable), true);
    }
    llvm_unreachable("invalid type tag");
}

unsigned TypeDecl::getFieldIndex(llvm::StringRef fieldName) const {
    for (unsigned index = 0, size = fields.size(); index < size; ++index) {
        if (fields[index].name == fieldName) return index;
    }
    fatalError("unknown field");
}

SrcLoc Decl::getSrcLoc() const {
    switch (getKind()) {
        case DeclKind::ParamDecl:  return getParamDecl().srcLoc;
        case DeclKind::FuncDecl:   return getFuncDecl().srcLoc;
        case DeclKind::GenericParamDecl: return getGenericParamDecl().srcLoc;
        case DeclKind::InitDecl:   return getInitDecl().srcLoc;
        case DeclKind::DeinitDecl: return getDeinitDecl().srcLoc;
        case DeclKind::TypeDecl:   return getTypeDecl().srcLoc;
        case DeclKind::VarDecl:    return getVarDecl().srcLoc;
        case DeclKind::FieldDecl:  return getFieldDecl().srcLoc;
        case DeclKind::ImportDecl: return getImportDecl().srcLoc;
    }
    llvm_unreachable("all cases handled");
}
<|endoftext|>


<commit_before>#include <llvm/ADT/StringRef.h>
#include <llvm/Support/ErrorHandling.h>
#include "decl.h"
#include "../support/utility.h"

using namespace delta;

const FuncType* FuncDecl::getFuncType() const {
    auto paramTypes = map(params, *[](const ParamDecl& p) { return p.type; });
    return &llvm::cast<FuncType>(*FuncType::get(returnType, std::move(paramTypes)));
}

bool FuncDecl::signatureMatches(const FuncDecl& other, bool matchReceiver) const {
    if (name != other.name) return false;
    if (matchReceiver && receiverType != other.receiverType) return false;
    if (mutating != other.mutating) return false;
    if (returnType != other.returnType) return false;
    if (params != other.params) return false;
    return true;
}

llvm::StringRef InitDecl::getTypeName() const {
    return type.which() ? boost::get<TypeDecl*>(type)->name : boost::get<std::string>(type);
}

llvm::StringRef DeinitDecl::getTypeName() const {
    return type.which() ? boost::get<TypeDecl*>(type)->name : boost::get<std::string>(type);
}

Type TypeDecl::getType(bool isMutable) const {
    return BasicType::get(name, isMutable);
}

Type TypeDecl::getTypeForPassing(bool isMutable) const {
    return tag == TypeTag::Struct ? getType(isMutable) : PtrType::get(getType(isMutable), true);
}

unsigned TypeDecl::getFieldIndex(llvm::StringRef fieldName) const {
    for (unsigned index = 0, size = fields.size(); index < size; ++index) {
        if (fields[index].name == fieldName) return index;
    }
    fatalError("unknown field");
}

SrcLoc Decl::getSrcLoc() const {
    switch (getKind()) {
        case DeclKind::ParamDecl:  return getParamDecl().srcLoc;
        case DeclKind::FuncDecl:   return getFuncDecl().srcLoc;
        case DeclKind::GenericParamDecl: return getGenericParamDecl().srcLoc;
        case DeclKind::GenericFuncDecl: return getGenericFuncDecl().func->srcLoc;
        case DeclKind::InitDecl:   return getInitDecl().srcLoc;
        case DeclKind::DeinitDecl: return getDeinitDecl().srcLoc;
        case DeclKind::TypeDecl:   return getTypeDecl().srcLoc;
        case DeclKind::VarDecl:    return getVarDecl().srcLoc;
        case DeclKind::FieldDecl:  return getFieldDecl().srcLoc;
        case DeclKind::ImportDecl: return getImportDecl().srcLoc;
    }
    llvm_unreachable("all cases handled");
}
<commit_msg>Fix libstdc++ error "multiple overloads of 'address' instantiate to the same signature"<commit_after>#include <llvm/ADT/StringRef.h>
#include <llvm/Support/ErrorHandling.h>
#include "decl.h"
#include "../support/utility.h"

using namespace delta;

const FuncType* FuncDecl::getFuncType() const {
    auto paramTypes = map(params, *[](const ParamDecl& p) -> Type { return p.type; });
    return &llvm::cast<FuncType>(*FuncType::get(returnType, std::move(paramTypes)));
}

bool FuncDecl::signatureMatches(const FuncDecl& other, bool matchReceiver) const {
    if (name != other.name) return false;
    if (matchReceiver && receiverType != other.receiverType) return false;
    if (mutating != other.mutating) return false;
    if (returnType != other.returnType) return false;
    if (params != other.params) return false;
    return true;
}

llvm::StringRef InitDecl::getTypeName() const {
    return type.which() ? boost::get<TypeDecl*>(type)->name : boost::get<std::string>(type);
}

llvm::StringRef DeinitDecl::getTypeName() const {
    return type.which() ? boost::get<TypeDecl*>(type)->name : boost::get<std::string>(type);
}

Type TypeDecl::getType(bool isMutable) const {
    return BasicType::get(name, isMutable);
}

Type TypeDecl::getTypeForPassing(bool isMutable) const {
    return tag == TypeTag::Struct ? getType(isMutable) : PtrType::get(getType(isMutable), true);
}

unsigned TypeDecl::getFieldIndex(llvm::StringRef fieldName) const {
    for (unsigned index = 0, size = fields.size(); index < size; ++index) {
        if (fields[index].name == fieldName) return index;
    }
    fatalError("unknown field");
}

SrcLoc Decl::getSrcLoc() const {
    switch (getKind()) {
        case DeclKind::ParamDecl:  return getParamDecl().srcLoc;
        case DeclKind::FuncDecl:   return getFuncDecl().srcLoc;
        case DeclKind::GenericParamDecl: return getGenericParamDecl().srcLoc;
        case DeclKind::GenericFuncDecl: return getGenericFuncDecl().func->srcLoc;
        case DeclKind::InitDecl:   return getInitDecl().srcLoc;
        case DeclKind::DeinitDecl: return getDeinitDecl().srcLoc;
        case DeclKind::TypeDecl:   return getTypeDecl().srcLoc;
        case DeclKind::VarDecl:    return getVarDecl().srcLoc;
        case DeclKind::FieldDecl:  return getFieldDecl().srcLoc;
        case DeclKind::ImportDecl: return getImportDecl().srcLoc;
    }
    llvm_unreachable("all cases handled");
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "perfetto/ext/base/uuid.h"

#include <random>

#include "perfetto/ext/base/time.h"

namespace perfetto {
namespace base {

// See https://www.ietf.org/rfc/rfc4122.txt
std::array<uint8_t, 16> Uuidv4() {
  static std::minstd_rand rng(static_cast<size_t>(GetBootTimeNs().count()));
  std::array<uint8_t, 16> uuid;
  for (size_t i = 0; i < 16; ++i)
    uuid[i] = static_cast<uint8_t>(rng());

  // version:
  uuid[6] = (uuid[6] & 0x0f) | 0x40;
  // clock_seq_hi_and_reserved:
  uuid[8] = (uuid[8] & 0x3f) | 0x80;

  return uuid;
}

}  // namespace base
}  // namespace perfetto
<commit_msg>base: fix build of UUID on mac<commit_after>/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "perfetto/ext/base/uuid.h"

#include <random>

#include "perfetto/ext/base/time.h"

namespace perfetto {
namespace base {

// See https://www.ietf.org/rfc/rfc4122.txt
std::array<uint8_t, 16> Uuidv4() {
  static std::minstd_rand rng(static_cast<uint32_t>(GetBootTimeNs().count()));
  std::array<uint8_t, 16> uuid;
  for (size_t i = 0; i < 16; ++i)
    uuid[i] = static_cast<uint8_t>(rng());

  // version:
  uuid[6] = (uuid[6] & 0x0f) | 0x40;
  // clock_seq_hi_and_reserved:
  uuid[8] = (uuid[8] & 0x3f) | 0x80;

  return uuid;
}

}  // namespace base
}  // namespace perfetto
<|endoftext|>


<commit_before>#include "fid/base_fid.h"

namespace fid {

void BaseFid::Init()
{
  // Initialize the health properly.
  health_ = 100.0;

  // Resize the temp array (maybe others?)
  temp_.reserve(wf_.size());

  // Initialize the BaseFid for analysis
  LoadParams();
  CenterFid();
  CalcNoise();
  CalcMaxAmp();
  FindFidRange();
  InitHook();

  CalcFreq();

  // Flag the FID as bad if it's negative.
  if (freq_ < 0.0) {
    health_ = 0.0;
  }

  // Else calculate a health based on signal to noise.
  if (max_amp_ < noise_ * snr_thresh_) {
    health_ *= max_amp_ / (noise_ * snr_thresh_);
  }

  // And factor fid duration into health.
  if (f_wf_ - i_wf_ < wf_.size() * len_thresh_) {
    health_ *= (f_wf_ - i_wf_) / (wf_.size() * len_thresh_);
  }
}

// Load FID data from a formatted text file.
void BaseFid::LoadTextData(std::string filename)
{
  // open the file first
  std::ifstream in(filename);

  // shrink vectors
  wf_.resize(0);
  tm_.resize(0);

  double wf_temp;
  double tm_temp;

  while (in.good()) {
    in >> tm_temp >> wf_temp;
    tm_.push_back(tm_temp);
    wf_.push_back(wf_temp);
  }
}

// Load all the current parameters in the fid::params namespace.
void BaseFid::LoadParams()
{
  edge_width_ = params::edge_width;
  edge_ignore_ = params::edge_ignore;
  start_amplitude_ = params::start_amplitude;
  low_pass_freq_ = params::low_pass_freq;
  fft_peak_width_ = params::fft_peak_width;
  centroid_thresh_ = params::centroid_thresh;
  hyst_thresh_ = params::hyst_thresh;
  snr_thresh_ = params::snr_thresh;
  len_thresh_ = params::len_thresh;
  freq_method_ = params::freq_method;
}

void BaseFid::CenterFid()
{
  int w = edge_width_;
  double sum  = std::accumulate(wf_.begin(), wf_.begin() + w, 0.0);
  double avg = sum / w; // to pass into lambda
  mean_ = avg; // save to class

  std::for_each(wf_.begin(), wf_.end(), [avg](double& x){ x -= avg; });
}

void BaseFid::CalcNoise()
{
  // Grab a new handle to the noise window width for aesthetics.
  int i = edge_ignore_;
  int f = edge_width_ + i;

  // Find the noise level in the head and tail.
  double head = stdev(wf_.begin() + i, wf_.begin() + f);
  double tail = stdev(wf_.rbegin() + i, wf_.rbegin() + f);

  // Take the smaller of the two.
  noise_ = (tail < head) ? (tail) : (head);
}

void BaseFid::CalcMaxAmp()
{
  auto mm = std::minmax_element(wf_.begin(), wf_.end());

  if (std::abs(*mm.first) > std::abs(*mm.second)) {

    max_amp_ = std::abs(*mm.first);

  } else {

    max_amp_ = std::abs(*mm.second);
  }
}

void BaseFid::FindFidRange()
{
  // Find the starting and ending points
  double thresh = start_amplitude_ * max_amp_;
  bool checks_out = false;

  // Find the first element with magnitude larger than thresh
  auto it_1 = wf_.begin() + edge_ignore_;

  while (!checks_out) {

    // Check if the point is above threshold.
    auto it_i = std::find_if(it_1, wf_.end(),
      [thresh](double x) {
        return std::abs(x) > thresh;
    });

    // Make sure the point is not with one of the vector's end.
    if ((it_i != wf_.end()) && (it_i + 1 != wf_.end())) {

      // Check if the next point is also over threshold.
      checks_out = std::abs(*(it_i + 1)) > thresh;

      // Increase the comparison starting point.
      it_1 = it_i + 1;

      // Turn the iterator into an index
      if (checks_out) {
        i_wf_ = std::distance(wf_.begin(), it_i);
      }

    } else {

      // If we have reached the end, mark it as the last.
      i_wf_ = std::distance(wf_.begin(), wf_.end());
      break;
    }
  }

  // Find the next element with magnitude lower than thresh
  auto it_2 = std::find_if(wf_.begin() + i_wf_, wf_.end(),
      [thresh](double x) {
        return std::abs(x) < 0.8 * thresh;
  });

  if ((it_2 != wf_.end()) && (it_2 + 1 != wf_.end())) {

    checks_out = false;

  } else {

    f_wf_ = std::distance(wf_.begin(), wf_.end());
    checks_out = true;
  }

  while (!checks_out) {

    // Find the range around a peak.
    auto it_i = std::find_if(it_2, wf_.end(),
      [thresh](double x) {
        return std::abs(x) > 0.8 * thresh;
    });

    auto it_f = std::find_if(it_i + 1, wf_.end(),
      [thresh](double x) {
        return std::abs(x) < 0.8 * thresh;
    });

    // Now check if the peak actually made it over threshold.
    if ((it_i != wf_.end()) && (it_f != wf_.end())) {

      auto mm = std::minmax_element(it_i, it_f);

      if ((*mm.first < -thresh) || (*mm.second > thresh)) {

        it_2 = it_f;

      } else {

        checks_out = true;
      }

      // Turn the iterator into an index
      if (checks_out) {
        f_wf_ = std::distance(wf_.begin(), it_f);
      }

    } else {

      f_wf_ = std::distance(wf_.begin(), wf_.end());
      break;
    }
  }

  // Gradients can cause a waist in the amplitude.
  // Mark the signal as bad if it didn't find signal above threshold.
  if (i_wf_ > wf_.size() * 0.95 || i_wf_ >= f_wf_) {

    health_ = 0.0;

    i_wf_ = 0;
    f_wf_ = wf_.size() * 0.01;
  }
}

// Save the interanl TGraph.
void BaseFid::SaveGraph(std::string filename, std::string title)
{
  gr_.SetTitle(title.c_str());
  gr_.Draw();
  c1_.Print(filename.c_str());
}

// Save a plot of FID waveform.
void BaseFid::SavePlot(std::string filename, std::string title)
{
  // If no title supplied give a reasonable default.
  if (title == "") {

    title = std::string("FID; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; time [ms]; amplitude [a.u.]");
  }

  gr_ = TGraph(wf_.size(), &tm_[0], &wf_[0]);

  SaveGraph(filename, title);
}

// Print the time series fit from an FID.
void BaseFid::SaveTimeFit(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Time Series Fit; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; time [ms]; amplitude [a.u.]");
  }

  // Copy the current time fit graph.
  gr_ = gr_time_series_;
  SaveGraph(filename, title);
}

// Print the time series fit from an FID.
void BaseFid::SaveFreqFit(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Frequency Series Fit; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; freq [kHz]; amplitude [a.u.]");
  }

  // Copy the current time fit graph.
  gr_ = gr_freq_series_;
  SaveGraph(filename, title);
}

void BaseFid::SaveTimeRes(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Time Series Fit Residuals; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; time [ms]; amplitude [a.u.]");
  }

  // Copy the current time fit.
  gr_ = gr_time_series_;

  // Set the points
  for (uint i = 0; i < res_.size(); ++i){
    static double x, y;

    gr_.GetPoint(i, x, y);
    gr_.SetPoint(i, x, res_[i]);
  }

  SaveGraph(filename, title);
}

void BaseFid::SaveFreqRes(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Freq Series Fit Residuals; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; freq [kHz]; amplitude [a.u.]");
  }

  // Copy the current time fit.
  gr_ = gr_freq_series_;

  // Set the points
  for (uint i = 0; i < res_.size(); ++i){
    static double x, y;

    gr_.GetPoint(i, x, y);
    gr_.SetPoint(i, x, res_[i]);
  }

  SaveGraph(filename, title);
}

// Save the FID data to a text file as "<time> <amp>".
void BaseFid::SaveData(std::string filename)
{
  // open the file first
  std::ofstream out(filename);

  for (int i = 0; i < tm_.size(); ++i) {
    out << tm_[i] << " " << wf_[i] << std::endl;
  }
}

void BaseFid::DiagnosticInfo(std::ostream& out)
{
  using std::endl;

  // Save the flags, set them to defaults.
  auto flags = out.flags();
  std::ofstream testout;
  out.flags(testout.flags());

  out << std::string(80, '<') << endl << std::string(4, ' ');
  out << "Diagostic Information for Fid @ " << this << endl;
  out << std::string(80, '<') << endl;

  out << "    Fid Waveform Characteristics" << endl;
  out << "        mean:       " << mean_ << endl;
  out << "        amplitude:  " << max_amp_ << endl;
  out << "        noise:      " << noise_ << endl;
  out << "        start time: " << i_wf_;
  out << " (" << tm_[i_wf_] << " ms)" << endl;
  out << "        stop time:  " << f_wf_ - 1;
  out << " (" << tm_[f_wf_ - 1] << " ms)" << endl;
  out << "        health:     " << health_ << endl;
  out << std::string(80, '>') << endl << endl;

  // Restore set flags.
  out.flags(flags);
}

void BaseFid::DiagnosticPlot(std::string dirname, std::string filestub)
{
  boost::filesystem::path dir(dirname);
  boost::filesystem::create_directories(dir);

  SaveFreqFit(dir.string() + filestub + std::string("_freq_fit.png"));
  SaveTimeFit(dir.string() + filestub + std::string("_time_fit.png"));
  SaveFreqRes(dir.string() + filestub + std::string("_freq_res.png"));
  SaveTimeRes(dir.string() + filestub + std::string("_time_res.png"));
}

void BaseFid::DiagnosticDump(std::string dirname, std::string filestub)
{
  // Make the plots first, that will create the directory if needed.
  DiagnosticPlot(dirname, filestub);

  std::ofstream out;
  boost::filesystem::path dir(dirname);

  std::string str = dir.string() + std::string("libfid.log");
  out.open(str , std::ofstream::out | std::ofstream::app);

  DiagnosticInfo(out);
  out.close();
}

} // fid
<commit_msg>Residual plot needed to allocate new TGraph, bug fixed.<commit_after>#include "fid/base_fid.h"

namespace fid {

void BaseFid::Init()
{
  // Initialize the health properly.
  health_ = 100.0;

  // Resize the temp array (maybe others?)
  temp_.reserve(wf_.size());

  // Initialize the BaseFid for analysis
  LoadParams();
  CenterFid();
  CalcNoise();
  CalcMaxAmp();
  FindFidRange();
  InitHook();

  CalcFreq();

  // Flag the FID as bad if it's negative.
  if (freq_ < 0.0) {
    health_ = 0.0;
  }

  // Else calculate a health based on signal to noise.
  if (max_amp_ < noise_ * snr_thresh_) {
    health_ *= max_amp_ / (noise_ * snr_thresh_);
  }

  // And factor fid duration into health.
  if (f_wf_ - i_wf_ < wf_.size() * len_thresh_) {
    health_ *= (f_wf_ - i_wf_) / (wf_.size() * len_thresh_);
  }
}

// Load FID data from a formatted text file.
void BaseFid::LoadTextData(std::string filename)
{
  // open the file first
  std::ifstream in(filename);

  // shrink vectors
  wf_.resize(0);
  tm_.resize(0);

  double wf_temp;
  double tm_temp;

  while (in.good()) {
    in >> tm_temp >> wf_temp;
    tm_.push_back(tm_temp);
    wf_.push_back(wf_temp);
  }
}

// Load all the current parameters in the fid::params namespace.
void BaseFid::LoadParams()
{
  edge_width_ = params::edge_width;
  edge_ignore_ = params::edge_ignore;
  start_amplitude_ = params::start_amplitude;
  low_pass_freq_ = params::low_pass_freq;
  fft_peak_width_ = params::fft_peak_width;
  centroid_thresh_ = params::centroid_thresh;
  hyst_thresh_ = params::hyst_thresh;
  snr_thresh_ = params::snr_thresh;
  len_thresh_ = params::len_thresh;
  freq_method_ = params::freq_method;
}

void BaseFid::CenterFid()
{
  int w = edge_width_;
  double sum  = std::accumulate(wf_.begin(), wf_.begin() + w, 0.0);
  double avg = sum / w; // to pass into lambda
  mean_ = avg; // save to class

  std::for_each(wf_.begin(), wf_.end(), [avg](double& x){ x -= avg; });
}

void BaseFid::CalcNoise()
{
  // Grab a new handle to the noise window width for aesthetics.
  int i = edge_ignore_;
  int f = edge_width_ + i;

  // Find the noise level in the head and tail.
  double head = stdev(wf_.begin() + i, wf_.begin() + f);
  double tail = stdev(wf_.rbegin() + i, wf_.rbegin() + f);

  // Take the smaller of the two.
  noise_ = (tail < head) ? (tail) : (head);
}

void BaseFid::CalcMaxAmp()
{
  auto mm = std::minmax_element(wf_.begin(), wf_.end());

  if (std::abs(*mm.first) > std::abs(*mm.second)) {

    max_amp_ = std::abs(*mm.first);

  } else {

    max_amp_ = std::abs(*mm.second);
  }
}

void BaseFid::FindFidRange()
{
  // Find the starting and ending points
  double thresh = start_amplitude_ * max_amp_;
  bool checks_out = false;

  // Find the first element with magnitude larger than thresh
  auto it_1 = wf_.begin() + edge_ignore_;

  while (!checks_out) {

    // Check if the point is above threshold.
    auto it_i = std::find_if(it_1, wf_.end(),
      [thresh](double x) {
        return std::abs(x) > thresh;
    });

    // Make sure the point is not with one of the vector's end.
    if ((it_i != wf_.end()) && (it_i + 1 != wf_.end())) {

      // Check if the next point is also over threshold.
      checks_out = std::abs(*(it_i + 1)) > thresh;

      // Increase the comparison starting point.
      it_1 = it_i + 1;

      // Turn the iterator into an index
      if (checks_out) {
        i_wf_ = std::distance(wf_.begin(), it_i);
      }

    } else {

      // If we have reached the end, mark it as the last.
      i_wf_ = std::distance(wf_.begin(), wf_.end());
      break;
    }
  }

  // Find the next element with magnitude lower than thresh
  auto it_2 = std::find_if(wf_.begin() + i_wf_, wf_.end(),
      [thresh](double x) {
        return std::abs(x) < 0.8 * thresh;
  });

  if ((it_2 != wf_.end()) && (it_2 + 1 != wf_.end())) {

    checks_out = false;

  } else {

    f_wf_ = std::distance(wf_.begin(), wf_.end());
    checks_out = true;
  }

  while (!checks_out) {

    // Find the range around a peak.
    auto it_i = std::find_if(it_2, wf_.end(),
      [thresh](double x) {
        return std::abs(x) > 0.8 * thresh;
    });

    auto it_f = std::find_if(it_i + 1, wf_.end(),
      [thresh](double x) {
        return std::abs(x) < 0.8 * thresh;
    });

    // Now check if the peak actually made it over threshold.
    if ((it_i != wf_.end()) && (it_f != wf_.end())) {

      auto mm = std::minmax_element(it_i, it_f);

      if ((*mm.first < -thresh) || (*mm.second > thresh)) {

        it_2 = it_f;

      } else {

        checks_out = true;
      }

      // Turn the iterator into an index
      if (checks_out) {
        f_wf_ = std::distance(wf_.begin(), it_f);
      }

    } else {

      f_wf_ = std::distance(wf_.begin(), wf_.end());
      break;
    }
  }

  // Gradients can cause a waist in the amplitude.
  // Mark the signal as bad if it didn't find signal above threshold.
  if (i_wf_ > wf_.size() * 0.95 || i_wf_ >= f_wf_) {

    health_ = 0.0;

    i_wf_ = 0;
    f_wf_ = wf_.size() * 0.01;
  }
}

// Save the interanl TGraph.
void BaseFid::SaveGraph(std::string filename, std::string title)
{
  gr_.SetTitle(title.c_str());
  gr_.Draw();
  c1_.Print(filename.c_str());
}

// Save a plot of FID waveform.
void BaseFid::SavePlot(std::string filename, std::string title)
{
  // If no title supplied give a reasonable default.
  if (title == "") {

    title = std::string("FID; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; time [ms]; amplitude [a.u.]");
  }

  gr_ = TGraph(wf_.size(), &tm_[0], &wf_[0]);

  SaveGraph(filename, title);
}

// Print the time series fit from an FID.
void BaseFid::SaveTimeFit(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Time Series Fit; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; time [ms]; amplitude [a.u.]");
  }

  // Copy the current time fit graph.
  gr_ = gr_time_series_;
  SaveGraph(filename, title);
}

// Print the time series fit from an FID.
void BaseFid::SaveFreqFit(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Frequency Series Fit; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; freq [kHz]; amplitude [a.u.]");
  }

  // Copy the current time fit graph.
  gr_ = gr_freq_series_;
  SaveGraph(filename, title);
}

void BaseFid::SaveTimeRes(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Time Series Fit Residuals; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; time [ms]; amplitude [a.u.]");
  }

  // Copy the current time fit.
  gr_ = TGraph(res_.size());

  // Set the points
  for (uint i = 0; i < res_.size(); ++i){
    static double x, y;

    gr_time_series_.GetPoint(i, x, y);
    gr_.SetPoint(i, x, res_[i]);
  }

  SaveGraph(filename, title);
}

void BaseFid::SaveFreqRes(std::string filename, std::string title)
{
  if (title == "") {

    title = std::string("Freq Series Fit Residuals; time [ms]; amplitude [a.u.]");

  } else {

    // In case they didn't append x/y labels.
    title.append("; freq [kHz]; amplitude [a.u.]");
  }

  // Copy the current time fit.
  gr_ = TGraph(res_.size());

  // Set the points
  for (uint i = 0; i < res_.size(); ++i){
    static double x, y;

    gr_freq_series_.GetPoint(i, x, y);
    gr_.SetPoint(i, x, res_[i]);
  }

  SaveGraph(filename, title);
}

// Save the FID data to a text file as "<time> <amp>".
void BaseFid::SaveData(std::string filename)
{
  // open the file first
  std::ofstream out(filename);

  for (int i = 0; i < tm_.size(); ++i) {
    out << tm_[i] << " " << wf_[i] << std::endl;
  }
}

void BaseFid::DiagnosticInfo(std::ostream& out)
{
  using std::endl;

  // Save the flags, set them to defaults.
  auto flags = out.flags();
  std::ofstream testout;
  out.flags(testout.flags());

  out << std::string(80, '<') << endl << std::string(4, ' ');
  out << "Diagostic Information for Fid @ " << this << endl;
  out << std::string(80, '<') << endl;

  out << "    Fid Waveform Characteristics" << endl;
  out << "        mean:       " << mean_ << endl;
  out << "        amplitude:  " << max_amp_ << endl;
  out << "        noise:      " << noise_ << endl;
  out << "        start time: " << i_wf_;
  out << " (" << tm_[i_wf_] << " ms)" << endl;
  out << "        stop time:  " << f_wf_ - 1;
  out << " (" << tm_[f_wf_ - 1] << " ms)" << endl;
  out << "        health:     " << health_ << endl;
  out << std::string(80, '>') << endl << endl;

  // Restore set flags.
  out.flags(flags);
}

void BaseFid::DiagnosticPlot(std::string dirname, std::string filestub)
{
  boost::filesystem::path dir(dirname);
  boost::filesystem::create_directories(dir);

  SaveFreqFit(dir.string() + filestub + std::string("_freq_fit.png"));
  SaveTimeFit(dir.string() + filestub + std::string("_time_fit.png"));
  SaveFreqRes(dir.string() + filestub + std::string("_freq_res.png"));
  SaveTimeRes(dir.string() + filestub + std::string("_time_res.png"));
}

void BaseFid::DiagnosticDump(std::string dirname, std::string filestub)
{
  // Make the plots first, that will create the directory if needed.
  DiagnosticPlot(dirname, filestub);

  std::ofstream out;
  boost::filesystem::path dir(dirname);

  std::string str = dir.string() + std::string("libfid.log");
  out.open(str , std::ofstream::out | std::ofstream::app);

  DiagnosticInfo(out);
  out.close();
}

} // fid
<|endoftext|>


<commit_before>/*
* Certificate Message
* (C) 2004-2006,2012 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/tls_messages.h>
#include <botan/tls_extensions.h>
#include <botan/internal/tls_reader.h>
#include <botan/internal/tls_handshake_io.h>
#include <botan/internal/tls_handshake_hash.h>
#include <botan/loadstor.h>
#include <botan/data_src.h>

namespace Botan {

namespace TLS {

/**
* Create a new Certificate message
*/
Certificate::Certificate(Handshake_IO& io,
                         Handshake_Hash& hash,
                         const std::vector<X509_Certificate>& cert_list) :
   m_certs(cert_list)
   {
   hash.update(io.send(*this));
   }

/**
* Deserialize a Certificate message
*/
Certificate::Certificate(const std::vector<uint8_t>& buf, const Policy& policy)
   {
   if(buf.size() < 3)
      throw Decoding_Error("Certificate: Message malformed");

   const size_t total_size = make_uint32(0, buf[0], buf[1], buf[2]);

   if(total_size != buf.size() - 3)
      throw Decoding_Error("Certificate: Message malformed");

   const size_t max_size = policy.maximum_certificate_chain_size();
   if(max_size > 0 && total_size > max_size)
      throw Decoding_Error("Certificate chain exceeds policy specified maximum size");

   const uint8_t* certs = buf.data() + 3;

   while(size_t remaining_bytes = buf.data() + buf.size() - certs)
      {
      if(remaining_bytes < 3)
         throw Decoding_Error("Certificate: Message malformed");

      const size_t cert_size = make_uint32(0, certs[0], certs[1], certs[2]);

      if(remaining_bytes < (3 + cert_size))
         throw Decoding_Error("Certificate: Message malformed");

      DataSource_Memory cert_buf(&certs[3], cert_size);
      m_certs.push_back(X509_Certificate(cert_buf));

      certs += cert_size + 3;
      }
   }

/**
* Serialize a Certificate message
*/
std::vector<uint8_t> Certificate::serialize() const
   {
   std::vector<uint8_t> buf(3);

   for(size_t i = 0; i != m_certs.size(); ++i)
      {
      std::vector<uint8_t> raw_cert = m_certs[i].BER_encode();
      const size_t cert_size = raw_cert.size();
      for(size_t j = 0; j != 3; ++j)
         {
         buf.push_back(get_byte(j+1, static_cast<uint32_t>(cert_size)));
         }
      buf += raw_cert;
      }

   const size_t buf_size = buf.size() - 3;
   for(size_t i = 0; i != 3; ++i)
      buf[i] = get_byte(i+1, static_cast<uint32_t>(buf_size));

   return buf;
   }

}

}
<commit_msg>Prohibit a TLS peer from using a v1/v2 leaf certificate<commit_after>/*
* Certificate Message
* (C) 2004-2006,2012,2020 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/tls_messages.h>
#include <botan/tls_extensions.h>
#include <botan/tls_exceptn.h>
#include <botan/tls_alert.h>
#include <botan/internal/tls_reader.h>
#include <botan/internal/tls_handshake_io.h>
#include <botan/internal/tls_handshake_hash.h>
#include <botan/loadstor.h>
#include <botan/data_src.h>

namespace Botan {

namespace TLS {

/**
* Create a new Certificate message
*/
Certificate::Certificate(Handshake_IO& io,
                         Handshake_Hash& hash,
                         const std::vector<X509_Certificate>& cert_list) :
   m_certs(cert_list)
   {
   hash.update(io.send(*this));
   }

/**
* Deserialize a Certificate message
*/
Certificate::Certificate(const std::vector<uint8_t>& buf, const Policy& policy)
   {
   if(buf.size() < 3)
      throw Decoding_Error("Certificate: Message malformed");

   const size_t total_size = make_uint32(0, buf[0], buf[1], buf[2]);

   if(total_size != buf.size() - 3)
      throw Decoding_Error("Certificate: Message malformed");

   const size_t max_size = policy.maximum_certificate_chain_size();
   if(max_size > 0 && total_size > max_size)
      throw Decoding_Error("Certificate chain exceeds policy specified maximum size");

   const uint8_t* certs = buf.data() + 3;

   while(size_t remaining_bytes = buf.data() + buf.size() - certs)
      {
      if(remaining_bytes < 3)
         throw Decoding_Error("Certificate: Message malformed");

      const size_t cert_size = make_uint32(0, certs[0], certs[1], certs[2]);

      if(remaining_bytes < (3 + cert_size))
         throw Decoding_Error("Certificate: Message malformed");

      DataSource_Memory cert_buf(&certs[3], cert_size);
      m_certs.push_back(X509_Certificate(cert_buf));

      certs += cert_size + 3;
      }

   /*
   * TLS 1.0 through 1.2 all seem to require that the certificate be
   * precisely a v3 certificate. In fact the strict wording would seem
   * to require that every certificate in the chain be v3. But often
   * the intermediates are outside of the control of the server.
   * But, require that the leaf certificate be v3
   */
   if(m_certs.size() > 0 && m_certs[0].x509_version() != 3)
      {
      throw TLS_Exception(Alert::BAD_CERTIFICATE,
                          "The leaf certificate must be v3");
      }
   }

/**
* Serialize a Certificate message
*/
std::vector<uint8_t> Certificate::serialize() const
   {
   std::vector<uint8_t> buf(3);

   for(size_t i = 0; i != m_certs.size(); ++i)
      {
      std::vector<uint8_t> raw_cert = m_certs[i].BER_encode();
      const size_t cert_size = raw_cert.size();
      for(size_t j = 0; j != 3; ++j)
         {
         buf.push_back(get_byte(j+1, static_cast<uint32_t>(cert_size)));
         }
      buf += raw_cert;
      }

   const size_t buf_size = buf.size() - 3;
   for(size_t i = 0; i != 3; ++i)
      buf[i] = get_byte(i+1, static_cast<uint32_t>(buf_size));

   return buf;
   }

}

}
<|endoftext|>


<commit_before>#include "targetver.h"
#include "spipc.h"

#include <stdio.h>
#include <tchar.h>
#include <thread>
#include <atomic>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
#include <boost/thread/thread.hpp>

namespace spipc { namespace testing {
class Memory_Transport: public sprot::Transport_Interface
{
    public:

        Memory_Transport();
        virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);
        virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);

    private:

        std::vector <unsigned char> buf_;
        static const size_t buf_reserve_ = 1024 * 1024;
        boost::interprocess::named_mutex condition_mutex_;
        boost::interprocess::named_condition data_available_;
        boost::interprocess::named_condition buffer_empty_;

        void reset();
};

Memory_Transport::Memory_Transport():
data_available_(boost::interprocess::open_or_create, "mem_trans_data_avail"),
buffer_empty_(boost::interprocess::open_or_create, "mem_trans_buffer_empty"),
condition_mutex_(boost::interprocess::open_or_create, "mem_trans_cond_mutex")
{
    reset();
}

void Memory_Transport::reset()
{
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);

    std::vector<unsigned char> empty;
    buf_.swap(empty);
    buf_.reserve(buf_reserve_);
}

size_t Memory_Transport::write(const void* buf, size_t buf_size, size_t timeout)
{
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);
    boost::system_time to(boost::get_system_time() + boost::posix_time::millisec(timeout));
    while (buf_.size() != 0)
        if (!buffer_empty_.timed_wait(lock, to))
        {
            data_available_.notify_all();
            return 0;
        }

    buf_.insert(buf_.end(), (unsigned char*)buf, (unsigned char*)buf + buf_size);
    data_available_.notify_all();

    return buf_size;
}

size_t Memory_Transport::read(void* buf, size_t buf_size, size_t timeout)
{
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);
    boost::system_time to(boost::get_system_time() + boost::posix_time::millisec(timeout));
    while (buf_.size() == 0)
        if (!data_available_.timed_wait(lock, to))
        {
            buffer_empty_.notify_all();
            return 0;
        }

    size_t read_bytes = buf_size > buf_.size() ? buf_.size() : buf_size;
    memcpy(buf, &(buf_[0]), read_bytes);
    buf_.resize(0);
    buffer_empty_.notify_all();

    return read_bytes;
}

std::recursive_mutex g_test_mutex;
std::vector<std::string> g_written_items;

void th1_mem_trans_test(Memory_Transport* trans)
{
    srand(std::this_thread::get_id().hash());

    std::vector<std::string> written_items;
    static std::atomic_int counter{0};
    while (counter++ < 100000)
    {
        int rnd_sz = 1 + rand() % 12;

        std::vector<char> to_write;
        for (int i = 0; i < rnd_sz; ++i)
            to_write.push_back(65 + rand() % 20);
        to_write.push_back(0);

        char* write_buf = &(*to_write.begin());
        //printf("Writing: %s (%d bytes)\n", write_buf, rnd_sz + 1);

        trans->write(write_buf, rnd_sz + 1);
        written_items.push_back(write_buf);

        //std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);
    g_written_items.insert(g_written_items.end(), written_items.begin(), written_items.end());
}

std::vector<std::string> g_read_items;
//volatile bool g_stop_reading = false;

void th2_mem_trans_test(Memory_Transport* trans)
{
    static std::atomic_int counter{0};
    srand(std::this_thread::get_id().hash());

    std::vector<std::string> read_items;

    while (counter++ < 100000)
    {
        char read_buf[256];
        memset(read_buf, 0, sizeof(read_buf));
        trans->read(read_buf, sizeof(read_buf), 1000);

        //if (g_stop_reading)
            //break;

        read_items.push_back(read_buf);
        //printf("Reading: %s\n", read_buf);

        //std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);
    g_read_items.insert(g_read_items.end(), read_items.begin(), read_items.end());
}

bool N_threads_mem_transport_test()
{
    Memory_Transport trans;

    std::thread writer(th1_mem_trans_test, &trans);
    std::thread reader(th2_mem_trans_test, &trans);
    std::thread writer2(th1_mem_trans_test, &trans);
    std::thread reader2(th2_mem_trans_test, &trans);
    std::thread writer3(th1_mem_trans_test, &trans);
    std::thread reader3(th2_mem_trans_test, &trans);
    std::thread writer4(th1_mem_trans_test, &trans);
    std::thread writer5(th1_mem_trans_test, &trans);
    std::thread writer6(th1_mem_trans_test, &trans);

    writer.join();
    writer2.join();
    writer3.join();
    writer4.join();
    writer5.join();
    writer6.join();

    //g_stop_reading = true;

    reader.join();
    reader2.join();
    reader3.join();

    if (g_read_items.size() != g_written_items.size())
    {
        printf("ERROR: number of read items (%u) != number of written items (%u).", g_read_items.size(), g_written_items.size());
        return false;
    }

    if (g_read_items.size() == 0)
    {
        printf("ERROR: number of read items is 0.");
        return false;
    }

    for (std::vector<std::string>::iterator i = g_written_items.begin(); i != g_written_items.end();)
    {
        bool increment_i = true;

        for (std::vector<std::string>::iterator j = g_read_items.begin(); j != g_read_items.end();)
        {
            if (*i == *j)
            {
                g_written_items.erase(i);
                g_read_items.erase(j);

                i = g_written_items.begin();
                increment_i = false;

                break;
            }

            ++j;
        }

        if (increment_i)
            ++i;
    }

    if (g_read_items.size() != g_written_items.size())
    {
        printf("ERROR: there was a corruption during read/write because not all written items were read.\n");

        printf("Leftovers in g_read_items:\n");
        for (size_t i = 0; i < g_read_items.size(); ++i)
            printf("%s ", g_read_items[i].c_str());

        printf("\nLeftovers in g_written_items:\n");
        for (size_t i = 0; i < g_written_items.size(); ++i)
            printf("%s ", g_written_items[i].c_str());
        printf("\n");

        return false;
    }

    if (g_read_items.size() != 0)
    {
        printf("ERROR: read/write problem detected.\n");

        printf("Leftovers in g_read_items:\n");
        for (size_t i = 0; i < g_read_items.size(); ++i)
            printf("%s ", g_read_items[i].c_str());

        printf("\nLeftovers in g_written_items:\n");
        for (size_t i = 0; i < g_written_items.size(); ++i)
            printf("%s ", g_written_items[i].c_str());
        printf("\n");

        return false;
    }

    return true;
}

void run_all_tests()
{
    if (!N_threads_mem_transport_test())
        printf("N_threads_mem_transport_test failed.\n");

    printf("tests finished OK.\n");
}

}};

int _tmain(int argc, _TCHAR* argv[])
{
    spipc::testing::run_all_tests();
	return 0;
}
<commit_msg>Mem transport is now shared mem transport.<commit_after>#include "targetver.h"
#include "spipc.h"

#include <stdio.h>
#include <tchar.h>
#include <thread>
#include <atomic>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/thread/thread.hpp>

namespace spipc { namespace testing {
class Shared_Memory_Transport: public sprot::Transport_Interface
{
    public:

        Shared_Memory_Transport();
        ~Shared_Memory_Transport();

        virtual size_t read(void* buf, size_t buf_size, size_t timeout = infinite_wait);
        virtual size_t write(const void* buf, size_t buf_size, size_t timeout = infinite_wait);

    private:

        typedef boost::interprocess::allocator<unsigned char, boost::interprocess::managed_shared_memory::segment_manager> uchar_alloc;
        typedef boost::interprocess::vector<unsigned char, uchar_alloc> shared_vector;

        static const size_t buf_reserve_ = 1024 * 1024;
        static const size_t shared_reserve_ = buf_reserve_ + 1024;
        const char* shared_mem_name_ = "mem_trans_shared_buff";

        boost::interprocess::managed_shared_memory shared_mem_;
        uchar_alloc allocator_;
        shared_vector buf_;

        boost::interprocess::named_mutex condition_mutex_;
        boost::interprocess::named_condition data_available_;
        boost::interprocess::named_condition buffer_empty_;

        void reset();
};

Shared_Memory_Transport::~Shared_Memory_Transport()
{
    {
        boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);
        boost::interprocess::shared_memory_object::remove(shared_mem_name_);
    }
}

Shared_Memory_Transport::Shared_Memory_Transport():
shared_mem_(boost::interprocess::open_or_create, shared_mem_name_, shared_reserve_),
data_available_(boost::interprocess::open_or_create, "mem_trans_data_avail"),
buffer_empty_(boost::interprocess::open_or_create, "mem_trans_buffer_empty"),
condition_mutex_(boost::interprocess::open_or_create, "mem_trans_cond_mutex"),
allocator_(shared_mem_.get_segment_manager()),
buf_(allocator_)
{
    reset();
}

void Shared_Memory_Transport::reset()
{
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);

    shared_vector empty(allocator_);
    buf_.swap(empty);
    buf_.reserve(buf_reserve_);
}

size_t Shared_Memory_Transport::write(const void* buf, size_t buf_size, size_t timeout)
{
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);
    boost::system_time to(boost::get_system_time() + boost::posix_time::millisec(timeout));
    while (buf_.size() != 0)
        if (!buffer_empty_.timed_wait(lock, to))
        {
            data_available_.notify_all();
            return 0;
        }

    buf_.insert(buf_.end(), (unsigned char*)buf, (unsigned char*)buf + buf_size);
    data_available_.notify_all();

    return buf_size;
}

size_t Shared_Memory_Transport::read(void* buf, size_t buf_size, size_t timeout)
{
    boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(condition_mutex_);
    boost::system_time to(boost::get_system_time() + boost::posix_time::millisec(timeout));
    while (buf_.size() == 0)
        if (!data_available_.timed_wait(lock, to))
        {
            buffer_empty_.notify_all();
            return 0;
        }

    size_t read_bytes = buf_size > buf_.size() ? buf_.size() : buf_size;
    memcpy(buf, &(buf_[0]), read_bytes);
    buf_.resize(0);
    buffer_empty_.notify_all();

    return read_bytes;
}

std::recursive_mutex g_test_mutex;
std::vector<std::string> g_written_items;

void th1_mem_trans_test(Shared_Memory_Transport* trans)
{
    srand(std::this_thread::get_id().hash());

    std::vector<std::string> written_items;
    static std::atomic_int counter{0};
    while (counter++ < 100000)
    {
        int rnd_sz = 1 + rand() % 12;

        std::vector<char> to_write;
        for (int i = 0; i < rnd_sz; ++i)
            to_write.push_back(65 + rand() % 20);
        to_write.push_back(0);

        char* write_buf = &(*to_write.begin());
        //printf("Writing: %s (%d bytes)\n", write_buf, rnd_sz + 1);

        trans->write(write_buf, rnd_sz + 1);
        written_items.push_back(write_buf);

        //std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);
    g_written_items.insert(g_written_items.end(), written_items.begin(), written_items.end());
}

std::vector<std::string> g_read_items;
//volatile bool g_stop_reading = false;

void th2_mem_trans_test(Shared_Memory_Transport* trans)
{
    static std::atomic_int counter{0};
    srand(std::this_thread::get_id().hash());

    std::vector<std::string> read_items;

    while (counter++ < 100000)
    {
        char read_buf[256];
        memset(read_buf, 0, sizeof(read_buf));
        trans->read(read_buf, sizeof(read_buf), 1000);

        //if (g_stop_reading)
            //break;

        read_items.push_back(read_buf);
        //printf("Reading: %s\n", read_buf);

        //std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    std::lock_guard<std::recursive_mutex> lock(g_test_mutex);
    g_read_items.insert(g_read_items.end(), read_items.begin(), read_items.end());
}

bool N_threads_mem_transport_test()
{
    Shared_Memory_Transport trans;

    std::thread writer(th1_mem_trans_test, &trans);
    std::thread reader(th2_mem_trans_test, &trans);
    std::thread writer2(th1_mem_trans_test, &trans);
    std::thread reader2(th2_mem_trans_test, &trans);
    std::thread writer3(th1_mem_trans_test, &trans);
    std::thread reader3(th2_mem_trans_test, &trans);
    std::thread writer4(th1_mem_trans_test, &trans);
    std::thread writer5(th1_mem_trans_test, &trans);
    std::thread writer6(th1_mem_trans_test, &trans);

    writer.join();
    writer2.join();
    writer3.join();
    writer4.join();
    writer5.join();
    writer6.join();

    //g_stop_reading = true;

    reader.join();
    reader2.join();
    reader3.join();

    if (g_read_items.size() != g_written_items.size())
    {
        printf("ERROR: number of read items (%u) != number of written items (%u).", g_read_items.size(), g_written_items.size());
        return false;
    }

    if (g_read_items.size() == 0)
    {
        printf("ERROR: number of read items is 0.");
        return false;
    }

    for (std::vector<std::string>::iterator i = g_written_items.begin(); i != g_written_items.end();)
    {
        bool increment_i = true;

        for (std::vector<std::string>::iterator j = g_read_items.begin(); j != g_read_items.end();)
        {
            if (*i == *j)
            {
                g_written_items.erase(i);
                g_read_items.erase(j);

                i = g_written_items.begin();
                increment_i = false;

                break;
            }

            ++j;
        }

        if (increment_i)
            ++i;
    }

    if (g_read_items.size() != g_written_items.size())
    {
        printf("ERROR: there was a corruption during read/write because not all written items were read.\n");

        printf("Leftovers in g_read_items:\n");
        for (size_t i = 0; i < g_read_items.size(); ++i)
            printf("%s ", g_read_items[i].c_str());

        printf("\nLeftovers in g_written_items:\n");
        for (size_t i = 0; i < g_written_items.size(); ++i)
            printf("%s ", g_written_items[i].c_str());
        printf("\n");

        return false;
    }

    if (g_read_items.size() != 0)
    {
        printf("ERROR: read/write problem detected.\n");

        printf("Leftovers in g_read_items:\n");
        for (size_t i = 0; i < g_read_items.size(); ++i)
            printf("%s ", g_read_items[i].c_str());

        printf("\nLeftovers in g_written_items:\n");
        for (size_t i = 0; i < g_written_items.size(); ++i)
            printf("%s ", g_written_items[i].c_str());
        printf("\n");

        return false;
    }

    return true;
}

void run_all_tests()
{
    if (!N_threads_mem_transport_test())
        printf("N_threads_mem_transport_test failed.\n");

    printf("tests finished OK.\n");
}

}};

int _tmain(int argc, _TCHAR* argv[])
{
    spipc::testing::run_all_tests();
	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Const correctness<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

#include "chainparams.h"
#include "clientversion.h"
#include "compat.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "httpserver.h"
#include "httprpc.h"
#include "utilstrencodings.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>

#include <stdio.h>

/* Introduction text for doxygen: */

/*! \mainpage Developer documentation
 *
 * \section intro_sec Introduction
 *
 * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoininfo.org/),
 * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate
 * with no central authority: managing transactions and issuing money are carried out collectively by the network.
 *
 * The software is a community-driven open source project, released under the MIT license.
 *
 * \section Navigation
 * Use the buttons Namespaces, Classes or Files at the top of the page to start navigating the code.
 */

void WaitForShutdown(boost::thread_group* threadGroup)
{
    bool fShutdown = ShutdownRequested();
    // Tell the main threads to shutdown.
    while (!fShutdown)
    {
        MilliSleep(200);
        fShutdown = ShutdownRequested();
    }
    if (threadGroup)
    {
        Interrupt(*threadGroup);
        threadGroup->join_all();
    }
}

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    CScheduler scheduler;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (mapArgs.count("-?") || mapArgs.count("-h") ||  mapArgs.count("-help") || mapArgs.count("-version"))
    {
        std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (mapArgs.count("-version"))
        {
            strUsage += FormatParagraph(LicenseInfo());
        }
        else
        {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  bitcoind [options]                     " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }

    try
    {
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs);
        } catch (const std::exception& e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        try {
            SelectParams(ChainNameFromCommandLine());
        } catch (const std::exception& e) {
            fprintf(stderr, "Error: %s\n", e.what());
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in vcored any longer. Use the vcore-cli utility instead.\n");
            exit(1);
        }
        if (GetBoolArg("-daemon", false))
        {
#if HAVE_DECL_DAEMON
            fprintf(stdout, "V Core server starting\n");

            // Daemonize
            if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
                fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno));
                return false;
            }
#else
            fprintf(stderr, "Error: -daemon is not supported on this operating system\n");
            return false;
#endif // HAVE_DECL_DAEMON
        }
        SoftSetBoolArg("-server", true);

        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        fRet = AppInit2(threadGroup, scheduler);
    }
    catch (const std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}

int main(int argc, char* argv[])
{
    SetupEnvironment();

    // Connect vcored signal handlers
    noui_connect();

    return (AppInit(argc, argv) ? 0 : 1);
}
<commit_msg>rebranding straggler<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif

#include "chainparams.h"
#include "clientversion.h"
#include "compat.h"
#include "rpc/server.h"
#include "init.h"
#include "noui.h"
#include "scheduler.h"
#include "util.h"
#include "httpserver.h"
#include "httprpc.h"
#include "utilstrencodings.h"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>

#include <stdio.h>

/* Introduction text for doxygen: */

/*! \mainpage Developer documentation
 *
 * \section intro_sec Introduction
 *
 * This is the developer documentation of the reference client for an experimental new digital currency called V (https://www.vcore.org/),
 * which enables instant payments to anyone, anywhere in the world. V Core uses peer-to-peer technology to operate
 * with no central authority: managing transactions and issuing money are carried out collectively by the network.
 *
 * The software is a community-driven open source project, released under the MIT license.
 *
 * \section Navigation
 * Use the buttons Namespaces, Classes or Files at the top of the page to start navigating the code.
 */

void WaitForShutdown(boost::thread_group* threadGroup)
{
    bool fShutdown = ShutdownRequested();
    // Tell the main threads to shutdown.
    while (!fShutdown)
    {
        MilliSleep(200);
        fShutdown = ShutdownRequested();
    }
    if (threadGroup)
    {
        Interrupt(*threadGroup);
        threadGroup->join_all();
    }
}

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
    boost::thread_group threadGroup;
    CScheduler scheduler;

    bool fRet = false;

    //
    // Parameters
    //
    // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
    ParseParameters(argc, argv);

    // Process help and version before taking care about datadir
    if (mapArgs.count("-?") || mapArgs.count("-h") ||  mapArgs.count("-help") || mapArgs.count("-version"))
    {
        std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n";

        if (mapArgs.count("-version"))
        {
            strUsage += FormatParagraph(LicenseInfo());
        }
        else
        {
            strUsage += "\n" + _("Usage:") + "\n" +
                  "  bitcoind [options]                     " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n";

            strUsage += "\n" + HelpMessage(HMM_BITCOIND);
        }

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }

    try
    {
        if (!boost::filesystem::is_directory(GetDataDir(false)))
        {
            fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
            return false;
        }
        try
        {
            ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME), mapArgs, mapMultiArgs);
        } catch (const std::exception& e) {
            fprintf(stderr,"Error reading configuration file: %s\n", e.what());
            return false;
        }
        // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
        try {
            SelectParams(ChainNameFromCommandLine());
        } catch (const std::exception& e) {
            fprintf(stderr, "Error: %s\n", e.what());
            return false;
        }

        // Command-line RPC
        bool fCommandLine = false;
        for (int i = 1; i < argc; i++)
            if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "bitcoin:"))
                fCommandLine = true;

        if (fCommandLine)
        {
            fprintf(stderr, "Error: There is no RPC client functionality in vcored any longer. Use the vcore-cli utility instead.\n");
            exit(1);
        }
        if (GetBoolArg("-daemon", false))
        {
#if HAVE_DECL_DAEMON
            fprintf(stdout, "V Core server starting\n");

            // Daemonize
            if (daemon(1, 0)) { // don't chdir (1), do close FDs (0)
                fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno));
                return false;
            }
#else
            fprintf(stderr, "Error: -daemon is not supported on this operating system\n");
            return false;
#endif // HAVE_DECL_DAEMON
        }
        SoftSetBoolArg("-server", true);

        // Set this early so that parameter interactions go to console
        InitLogging();
        InitParameterInteraction();
        fRet = AppInit2(threadGroup, scheduler);
    }
    catch (const std::exception& e) {
        PrintExceptionContinue(&e, "AppInit()");
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInit()");
    }

    if (!fRet)
    {
        Interrupt(threadGroup);
        // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
        // the startup-failure cases to make sure they don't result in a hang due to some
        // thread-blocking-waiting-for-another-thread-during-startup case
    } else {
        WaitForShutdown(&threadGroup);
    }
    Shutdown();

    return fRet;
}

int main(int argc, char* argv[])
{
    SetupEnvironment();

    // Connect vcored signal handlers
    noui_connect();

    return (AppInit(argc, argv) ? 0 : 1);
}
<|endoftext|>


<commit_before>/*!
 * \file main.cc
 *
 * \brief The control component for BPEL2oWFN
 *
 * This file controls the behaviour of BPEL2oWFN and is the interface to the
 * environment.
 *
 * \author
 *          - responsible: Christian Gierds <gierds@informatik.hu-berlin.de>
 *          - last changes of: \$Author: gierds $
 *
 * \date
 *          - created: 2005/10/18
 *          - last changed: \$Date: 2005/12/13 15:29:26 $
 *
 * \note    This file is part of the tool BPEL2oWFN and was created during the
 *          project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See
 *          http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
 *          for details.
 *
 * \version \$Revision: 1.41 $
 *          - 2005-11-15 (gierds) Moved command line evaluation to helpers.cc.
 *            Added option to created (abstracted) low level nets.
 *            Added option for LoLA output.
 *          - 2005-11-15 (nlohmann) Call Exception::info() to signal error.
 *          - 2005-11-16 (gierds) Use of error() and cleanup() as defined in
 *            helpers.cc
 *          - 2005-12-13 (gierds) Added variables in order to handle creation
 *            of oWFNs.
 *
 */

#include "main.h"

/// The Petri Net
PetriNet *TheNet = new PetriNet();

// some file names and pointers

/// Filename of input file.
std::string filename = "<STDIN>";

/// Filename of dot output file
std::string dot_filename = "";
/// Pointer to dot output file
std::ostream * dot_output = &std::cout;

/// Filename of lola output file
std::string lola_filename = "";
/// Pointer to lola output file
std::ostream * lola_output = &std::cout;

/// Filename of owfn output file
std::string owfn_filename = "";
/// Pointer to owfn output file
std::ostream * owfn_output = &std::cout;

/// Filename of PN info file
std::string info_filename = "";
/// Pointer to PN info file
std::ostream * info_output = &std::cout;

// different modes controlled by command line

/// read from file
bool mode_file = false;
/// print the Petri Net
bool mode_petri_net = false;
/// simplify Petri Net
bool mode_simplify_petri_net = false;
/// paint Petri Net for lola
bool mode_lola_petri_net = false;
/// paint Petri Net for lola and output to file
bool mode_lola_2_file = false;
/// paint Petri Net for owfn
bool mode_owfn_petri_net = false;
/// paint Petri Net for owfn and output to file
bool mode_owfn_2_file = false;
/// paint Petri Net with dot
bool mode_dot_petri_net = false;
/// paint Petri Net with dot and output to file
bool mode_dot_2_file = false;
/// pretty printer
bool mode_pretty_printer = false;
/// print AST
bool mode_ast = false;
/// print the "low level" Petri Net
bool mode_low_level_petri_net = false;

/**
 * Entry point for BPEL2oWFN.
 * Controls the behaviour of input and output.
 *
 * \param argc	number of command line arguments
 * \param argv	array with command line arguments
 *
 * \returns Error code (0 if everything went well)
 */
int main( int argc, char *argv[])
{

  try
  {
    /***
     * Reading command line arguments and triggering appropriate behaviour.
     * In case of false parameters call command line help function and exit.
     */
    parse_command_line(argc, argv);

    trace(TRACE_INFORMATION, "Parsing ...\n");

    // invoke Bison parser
    int error = yyparse();

    if (!error)
    {
      trace(TRACE_INFORMATION, "Parsing complete.\n");

      symMan.printScope();

      if (mode_ast)
      {
        TheProcess->print();
      }

      if (mode_pretty_printer)
      {
        TheProcess->unparse(kc::printer, kc::xml);
      }
      if (mode_petri_net)
      {
        TheProcess->unparse(kc::pseudoPrinter, kc::petrinet);
      }
    }

    // make low level ?
    if (mode_low_level_petri_net)
    {
      TheNet->makeLowLevel();
    }
    // simplify net ?
    if (mode_simplify_petri_net)
    {
      TheNet->simplify();
    }
    // create LoLA output ?
    if (mode_lola_petri_net)
    {
      TheNet->lolaOut();
    }
    // create dot output ?
    if (mode_dot_petri_net)
    {
      TheNet->drawDot();
    }
    // output info file ?
    if (mode_petri_net && mode_file )
    {
      TheNet->printInformation();
    }

    cleanup();

    return error;
  }
  catch (Exception& e)
  {
    // output info file ?
    if (mode_petri_net && mode_file )
    {
      // in case of an exception, the Petri Net information might help us!
      TheNet->printInformation();
    }
    error(e);
  }

  return 0;
}
<commit_msg>+ renamed call drawDOT to dotOut<commit_after>/*!
 * \file main.cc
 *
 * \brief The control component for BPEL2oWFN
 *
 * This file controls the behaviour of BPEL2oWFN and is the interface to the
 * environment.
 *
 * \author
 *          - responsible: Christian Gierds <gierds@informatik.hu-berlin.de>
 *          - last changes of: \$Author: nlohmann $
 *
 * \date
 *          - created: 2005/10/18
 *          - last changed: \$Date: 2005/12/13 21:50:17 $
 *
 * \note    This file is part of the tool BPEL2oWFN and was created during the
 *          project "Tools4BPEL" at the Humboldt-Universitt zu Berlin. See
 *          http://www.informatik.hu-berlin.de/top/forschung/projekte/tools4bpel
 *          for details.
 *
 * \version \$Revision: 1.42 $
 *          - 2005-11-15 (gierds) Moved command line evaluation to helpers.cc.
 *            Added option to created (abstracted) low level nets.
 *            Added option for LoLA output.
 *          - 2005-11-15 (nlohmann) Call Exception::info() to signal error.
 *          - 2005-11-16 (gierds) Use of error() and cleanup() as defined in
 *            helpers.cc
 *          - 2005-12-13 (gierds) Added variables in order to handle creation
 *            of oWFNs.
 *
 */

#include "main.h"

/// The Petri Net
PetriNet *TheNet = new PetriNet();

// some file names and pointers

/// Filename of input file.
std::string filename = "<STDIN>";

/// Filename of dot output file
std::string dot_filename = "";
/// Pointer to dot output file
std::ostream * dot_output = &std::cout;

/// Filename of lola output file
std::string lola_filename = "";
/// Pointer to lola output file
std::ostream * lola_output = &std::cout;

/// Filename of owfn output file
std::string owfn_filename = "";
/// Pointer to owfn output file
std::ostream * owfn_output = &std::cout;

/// Filename of PN info file
std::string info_filename = "";
/// Pointer to PN info file
std::ostream * info_output = &std::cout;

// different modes controlled by command line

/// read from file
bool mode_file = false;
/// print the Petri Net
bool mode_petri_net = false;
/// simplify Petri Net
bool mode_simplify_petri_net = false;
/// paint Petri Net for lola
bool mode_lola_petri_net = false;
/// paint Petri Net for lola and output to file
bool mode_lola_2_file = false;
/// paint Petri Net for owfn
bool mode_owfn_petri_net = false;
/// paint Petri Net for owfn and output to file
bool mode_owfn_2_file = false;
/// paint Petri Net with dot
bool mode_dot_petri_net = false;
/// paint Petri Net with dot and output to file
bool mode_dot_2_file = false;
/// pretty printer
bool mode_pretty_printer = false;
/// print AST
bool mode_ast = false;
/// print the "low level" Petri Net
bool mode_low_level_petri_net = false;

/**
 * Entry point for BPEL2oWFN.
 * Controls the behaviour of input and output.
 *
 * \param argc	number of command line arguments
 * \param argv	array with command line arguments
 *
 * \returns Error code (0 if everything went well)
 */
int main( int argc, char *argv[])
{

  try
  {
    /***
     * Reading command line arguments and triggering appropriate behaviour.
     * In case of false parameters call command line help function and exit.
     */
    parse_command_line(argc, argv);

    trace(TRACE_INFORMATION, "Parsing ...\n");

    // invoke Bison parser
    int error = yyparse();

    if (!error)
    {
      trace(TRACE_INFORMATION, "Parsing complete.\n");

      symMan.printScope();

      if (mode_ast)
      {
        TheProcess->print();
      }

      if (mode_pretty_printer)
      {
        TheProcess->unparse(kc::printer, kc::xml);
      }
      if (mode_petri_net)
      {
        TheProcess->unparse(kc::pseudoPrinter, kc::petrinet);
      }
    }

    // make low level ?
    if (mode_low_level_petri_net)
    {
      TheNet->makeLowLevel();
    }
    // simplify net ?
    if (mode_simplify_petri_net)
    {
      TheNet->simplify();
    }
    // create LoLA output ?
    if (mode_lola_petri_net)
    {
      TheNet->lolaOut();
    }
    // create dot output ?
    if (mode_dot_petri_net)
    {
      TheNet->dotOut();
    }
    // output info file ?
    if (mode_petri_net && mode_file )
    {
      TheNet->printInformation();
    }

    cleanup();

    return error;
  }
  catch (Exception& e)
  {
    // output info file ?
    if (mode_petri_net && mode_file )
    {
      // in case of an exception, the Petri Net information might help us!
      TheNet->printInformation();
    }
    error(e);
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <bson.h>
#include "hphp/runtime/base/base-includes.h"

static bool
cbson_loads_visit_int64 (const bson_iter_t *iter,
                         const char*        key,
                         int64_t          v_int64,
                         Array             *output)
{
  output->add(String(key),v_int64);

  return false;
}

static bool
cbson_loads_visit_bool (const bson_iter_t *iter,
                        const char        *key,
                        bool        v_bool,
                        Array       *output)
{
   output->add(String(key), v_bool);
   return false;
}

static bool
cbson_loads_visit_array (const bson_iter_t *iter,
                        const char        *key,
                        const bson_t     v_array,
                        Array           *output)
{
   return false;
}
static const bson_visitor_t gLoadsVisitors = {
   .visit_double = cbson_loads_visit_double,
   .visit_utf8 = cbson_loads_visit_utf8,
   .visit_array = cbson_loads_visit_array,
   .visit_bool = cbson_loads_visit_bool,
   .visit_int64 = cbson_loads_visit_int64;
};

<commit_msg>doing bson to array<commit_after>#include <bson.h>
#include "hphp/runtime/base/base-includes.h"

static bool
cbson_loads_visit_int64 (const bson_iter_t *iter,
                         const char*        key,
                         int64_t          v_int64,
                         Array             *output)
{
  output->add(String(key),v_int64);

  return false;
}

static bool
cbson_loads_visit_bool (const bson_iter_t *iter,
                        const char        *key,
                        bool        v_bool,
                        Array       *output)
{
   output->add(String(key), v_bool);
   return false;
}

static bool
cbson_loads_visit_array (const bson_iter_t *iter,
                        const char        *key,
                        const bson_t     v_array,
                        Array           *output)
{

   return false;
}
static const bson_visitor_t gLoadsVisitors = {
   .visit_double = cbson_loads_visit_double,
   .visit_utf8 = cbson_loads_visit_utf8,
   .visit_array = cbson_loads_visit_array,
   .visit_bool = cbson_loads_visit_bool,
   .visit_int64 = cbson_loads_visit_int64;
};

<|endoftext|>


<commit_before>#include "calendar.h"

#include <QDebug>
#include <calformat.h>
#include <extendedstorage.h>
#include <extendedcalendar.h>

void CalendarTest::test()
{
//  const KDateTime &dateTime = KDateTime::fromString("20140919T100000Z");
//  qDebug() << dateTime.toString();
//  const KTimeZone &timezone = dateTime.timeZone();
}
<commit_msg>Added playing with timezones (kcalcore)<commit_after>#include "calendar.h"

#include <uuid.h>

#include <QDebug>
#include <calformat.h>
#include <icaltimezones.h>
#include <extendedstorage.h>
#include <extendedcalendar.h>

using namespace KCalCore;

static MSTimeZone createTimezone();

void CalendarTest::test()
{
  MSTimeZone tz = createTimezone();
  uuid_t out;
  uuid_generate_random(out);
//  qDebug() << (const char *)out;

  ICalTimeZones timezones;
  qDebug() << "Initial timezone count:" << timezones.count();
  ICalTimeZoneSource source;
  const ICalTimeZone &timezone1 = source.parse(&tz/*, timezones*/);
  qDebug() << "Transitions 1:" << timezone1.transitions().length();
  Q_UNUSED(timezone1);
  qDebug() << "Timezone count1:" << timezones.count() << ", " << tz.Bias;
  MSTimeZone tz2 = createTimezone();
  const ICalTimeZone &timezone2 = source.parse(&tz2/*, timezones*/);
  qDebug() << "Transitions 2:" << timezone2.transitions().length();
  qDebug() << "Timezone count2:" << timezones.count() << ", " << tz2.Bias;
  Q_UNUSED(timezone2);
  qDebug() << "Timezone test 1:" << timezone1.utcOffsets();
  qDebug() << "Timezone test 2:" << timezone2.utcOffsets();

  qDebug() << "ICAL 1:" << timezone1.vtimezone();
  qDebug() << "ICAL 2:" << timezone2.vtimezone();
}

MSTimeZone createTimezone()
{
  MSTimeZone timezone;
  memset(&timezone.StandardDate, 0, sizeof (timezone.StandardDate));
  memset(&timezone.DaylightDate, 0, sizeof (timezone.DaylightDate));

  static int n = 0;
  QByteArray stdName = QByteArray::fromHex(
    "28 00 55 00  54 00 43 00 2b 00 30 00 34 00 3a 00 "
    "30 00 30 00  29 00 20 00 4d 00 6f 00 73 00 63 00 "
    "6f 00 77 00  2c 00 20 00 53 00 74 00 2e 00 20 00 "
    "50 00 65 00  74 00 65 00 72 00 73 00 62 00 75 00 ");
  stdName[2] = stdName[2] + n; ++n;
  QByteArray dayName = QByteArray::fromHex(
    "28 00 55 00  54 00 43 00 2b 00 30 00 34 00 3a 00"
    "30 00 30 00  29 00 20 00 4d 00 6f 00 73 00 63 00"
    "6f 00 77 00  2c 00 20 00 53 00 74 00 2e 00 20 00"
    "50 00 65 00  74 00 65 00 72 00 73 00 62 00 75 00");

  const QString &stdNameString = QString::fromUtf16(reinterpret_cast<const ushort*>(stdName.constData()));
  const QString &dayNameString = QString::fromUtf16(reinterpret_cast<const ushort*>(dayName.constData()));

  qDebug() << "Std buffer length:" << stdName.length() << ", name:" << stdNameString;
  qDebug() << "Day buffer length:" << dayName.length() << ", name:" << dayNameString;
  timezone.StandardName = stdNameString;
  timezone.DaylightName = dayNameString;
  timezone.Bias = (int)0xFFFFFF4CU - 60 * n;

  timezone.StandardBias = 0;
  timezone.DaylightBias = 0;
  qDebug() << "Bias" << timezone.Bias << ", std:" << timezone.StandardBias << ", day:" << timezone.DaylightBias;

  return timezone;
}

/*
00000000  4c ff ff ff                                         | Bias (4 bytes)
00000004  28 00 55 00  54 00 43 00  2b 00 30 00  34 00 3a 00  | StandardName (64 bytes)
00000014  30 00 30 00  29 00 20 00  4d 00 6f 00  73 00 63 00  |
00000024  6f 00 77 00  2c 00 20 00  53 00 74 00  2e 00 20 00  |
00000034  50 00 65 00  74 00 65 00  72 00 73 00  62 00 75 00  |
00000044  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  | StandardDate (16 bytes)
00000058  00 00 00 00                                         | StandardBias ( 4 bytes)
00000058  28 00 55 00  54 00 43 00  2b 00 30 00  34 00 3a 00  | DaylightName (64 bytes)
00000068  30 00 30 00  29 00 20 00  4d 00 6f 00  73 00 63 00  |
00000078  6f 00 77 00  2c 00 20 00  53 00 74 00  2e 00 20 00  |
00000088  50 00 65 00  74 00 65 00  72 00 73 00  62 00 75 00  |
00000098  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  | DaylightDate (16 bytes)
000000A8  00 00 00 00                                         | DaylightBias ( 4 bytes)

typedef struct _MSSystemTime {
  qint16 wYear;
  qint16 wMonth;
  qint16 wDayOfWeek;
  qint16 wDay;
  qint16 wHour;
  qint16 wMinute;
  qint16 wSecond;
  qint16 wMilliseconds;
} MSSystemTime;

typedef struct _MSTimeZone {
  long         Bias;
  QString      StandardName;
  MSSystemTime StandardDate;
  long         StandardBias;
  QString      DaylightName;
  MSSystemTime DaylightDate;
  long         DaylightBias;
} MSTimeZone;
*/
<|endoftext|>