<commit_before>/*
 * Copyright (C) 2019 pengjian.uestc @ gmail.com
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "seastar/core/shared_ptr.hh"
#include "seastar/core/future.hh"
#include "bytes.hh"
#include "gc_clock.hh"
#include "query-request.hh"

using namespace seastar;

namespace service {
class storage_proxy;
class client_state;
}

class service_permit;

namespace redis {

class redis_options;

struct strings_result {
    bytes _result;
    bool _has_result;
    ttl_opt _ttl;
    bytes& result() { return _result; }
    bool has_result() const { return _has_result; }
    gc_clock::duration ttl() { return _ttl.value(); }
    bool has_ttl() { return _ttl.has_value(); }
};

future<lw_shared_ptr<strings_result>> read_strings(service::storage_proxy&, const redis_options&, const bytes&, service_permit);
future<lw_shared_ptr<strings_result>> query_strings(service::storage_proxy&, const redis_options&, const bytes&, service_permit, schema_ptr, query::partition_slice);

future<lw_shared_ptr<std::map<bytes, bytes>>> read_hashes(service::storage_proxy&, const redis_options&, const bytes&, service_permit);
future<lw_shared_ptr<std::map<bytes, bytes>>> read_hashes(service::storage_proxy&, const redis_options&, const bytes&, const bytes&, service_permit);
future<lw_shared_ptr<std::map<bytes, bytes>>> query_hashes(service::storage_proxy&, const redis_options&, const bytes&, service_permit, schema_ptr, query::partition_slice);

}
<commit_msg>redis: Remove seastar namespace import from query_utils.hh<commit_after>/*
 * Copyright (C) 2019 pengjian.uestc @ gmail.com
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "seastar/core/shared_ptr.hh"
#include "seastar/core/future.hh"
#include "bytes.hh"
#include "gc_clock.hh"
#include "query-request.hh"

namespace service {
class storage_proxy;
class client_state;
}

class service_permit;

namespace redis {

class redis_options;

struct strings_result {
    bytes _result;
    bool _has_result;
    ttl_opt _ttl;
    bytes& result() { return _result; }
    bool has_result() const { return _has_result; }
    gc_clock::duration ttl() { return _ttl.value(); }
    bool has_ttl() { return _ttl.has_value(); }
};

seastar::future<seastar::lw_shared_ptr<strings_result>> read_strings(service::storage_proxy&, const redis_options&, const bytes&, service_permit);
seastar::future<seastar::lw_shared_ptr<strings_result>> query_strings(service::storage_proxy&, const redis_options&, const bytes&, service_permit, schema_ptr, query::partition_slice);

seastar::future<seastar::lw_shared_ptr<std::map<bytes, bytes>>> read_hashes(service::storage_proxy&, const redis_options&, const bytes&, service_permit);
seastar::future<seastar::lw_shared_ptr<std::map<bytes, bytes>>> read_hashes(service::storage_proxy&, const redis_options&, const bytes&, const bytes&, service_permit);
seastar::future<seastar::lw_shared_ptr<std::map<bytes, bytes>>> query_hashes(service::storage_proxy&, const redis_options&, const bytes&, service_permit, schema_ptr, query::partition_slice);

}
<|endoftext|>


<commit_before>// Weak reference

#include <memory>

class bar;

class foo
{
public:
	foo(const std::shared_ptr<bar>& b)
	{
		this->forward_reference = b;
	}

private:
	std::shared_ptr<bar> forward_reference;
};

class bar
{
public:
	void set_back_reference(const std::weak_ptr<foo>& f)
	{
		this->back_reference = f;
	}

	void do_something()
	{
		std::shared_ptr<foo> shared_back_reference = this->back_reference.lock();
		if (shared_back_reference) {
			// Use *shared_back_reference
		}
	}

private:
	std::weak_ptr<foo> back_reference;
};

// Maintain a non-owning reference to a shared dynamically allocated
// object to break circular dependencies.
//
// The [`std::weak_ptr`](cpp/memory/weak_ptr) type represents
// a non-owning reference to dynamically allocated object with
// shared ownership ([`std::shared_ptr`](cpp/memory/shared_ptr)). As
// they do not contribute to the reference count of the managed object
// they refer to, the object can be destroyed at any time when all
// `std::shared_ptr`s give up ownership. However, a
// [`std::weak_ptr`](cpp/memory/weak_ptr) can be converted to a
// [`std::shared_ptr`] to provide temporary ownership and safe access to the
// object.
//
// In this sample, we have two classes: `foo` on [7-17], and `bar` on
// [19-33]. A `foo` object has shared ownership of a `bar` ([16]), and
// `bar` requires some form of reference back to the `foo` that owns it.
// If this back reference were a `std::shared_ptr<foo>`, it would introduce
// a circular dependency, making it impossible for either object to be
// destroyed. If it were a normal reference type (`foo&`), it risks
// refering to a deleted object when it attempts to use it, as the
// lifetime of `foo` is independent of `bar`.
//
// The solution is to use a `std::weak_ptr<foo>`, as on [36]. When
// `bar` needs to use `foo`, it checks if bar still exists by calling
// `lock` on the `std::weak_ptr` to take temporary shared ownership
// ([29]). If the returned `std::shared_ptr` is not empty, `bar` can
// safely use it to access the `foo` object ([30-32]).

int main()
{
	std::shared_ptr<bar> b = std::make_shared<bar>();
	std::shared_ptr<foo> f = std::make_shared<foo>(b);

	b->set_back_reference(f);

	b->do_something();
}
<commit_msg>Add C++11 tag to weak reference sample<commit_after>// Weak reference
// C++11

#include <memory>

class bar;

class foo
{
public:
	foo(const std::shared_ptr<bar>& b)
	{
		this->forward_reference = b;
	}

private:
	std::shared_ptr<bar> forward_reference;
};

class bar
{
public:
	void set_back_reference(const std::weak_ptr<foo>& f)
	{
		this->back_reference = f;
	}

	void do_something()
	{
		std::shared_ptr<foo> shared_back_reference = this->back_reference.lock();
		if (shared_back_reference) {
			// Use *shared_back_reference
		}
	}

private:
	std::weak_ptr<foo> back_reference;
};

// Maintain a non-owning reference to a shared dynamically allocated
// object to break circular dependencies.
//
// The [`std::weak_ptr`](cpp/memory/weak_ptr) type represents
// a non-owning reference to dynamically allocated object with
// shared ownership ([`std::shared_ptr`](cpp/memory/shared_ptr)). As
// they do not contribute to the reference count of the managed object
// they refer to, the object can be destroyed at any time when all
// `std::shared_ptr`s give up ownership. However, a
// [`std::weak_ptr`](cpp/memory/weak_ptr) can be converted to a
// [`std::shared_ptr`] to provide temporary ownership and safe access to the
// object.
//
// In this sample, we have two classes: `foo` on [8-18], and `bar` on
// [20-34]. A `foo` object has shared ownership of a `bar` ([17]), and
// `bar` requires some form of reference back to the `foo` that owns it.
// If this back reference were a `std::shared_ptr<foo>`, it would introduce
// a circular dependency, making it impossible for either object to be
// destroyed. If it were a normal reference type (`foo&`), it risks
// refering to a deleted object when it attempts to use it, as the
// lifetime of `foo` is independent of `bar`.
//
// The solution is to use a `std::weak_ptr<foo>`, as on [37]. When
// `bar` needs to use `foo`, it checks if bar still exists by calling
// `lock` on the `std::weak_ptr` to take temporary shared ownership
// ([30]). If the returned `std::shared_ptr` is not empty, `bar` can
// safely use it to access the `foo` object ([31-33]).

int main()
{
	std::shared_ptr<bar> b = std::make_shared<bar>();
	std::shared_ptr<foo> f = std::make_shared<foo>(b);

	b->set_back_reference(f);

	b->do_something();
}
<|endoftext|>


<commit_before>//
//  SamplerVoice.cpp
//  AudioKit Core
//
//  Created by Shane Dunne, revision history on Github.
//  Copyright © 2018 AudioKit. All rights reserved.
//

#include "SamplerVoice.hpp"
#include <stdio.h>

#define MIDDLE_C_HZ 262.626f

namespace AudioKitCore
{
    void SamplerVoice::init(double sampleRate)
    {
        samplingRate = float(sampleRate);
        leftFilter.init(sampleRate);
        rightFilter.init(sampleRate);
        adsrEnvelope.init();
        filterEnvelope.init();
        pitchEnvelope.init();
        volumeRamper.init(0.0f);
        tempGain = 0.0f;
    }

    void SamplerVoice::start(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer)
    {
        sampleBuffer = buffer;
        oscillator.indexPoint = buffer->startPoint;
        oscillator.increment = (buffer->sampleRate / sampleRate) * (frequency / buffer->noteFrequency);
        oscillator.multiplier = 1.0;
        oscillator.isLooping = buffer->isLooping;

        noteVolume = volume;
        adsrEnvelope.start();
        volumeRamper.init(0.0f);

        samplingRate = sampleRate;
        leftFilter.updateSampleRate(double(samplingRate));
        rightFilter.updateSampleRate(double(samplingRate));
        filterEnvelope.start();

        pitchEnvelope.start();

        pitchEnvelopeSemitones = 0.0f;

        glideSemitones = 0.0f;
        if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency)
        {
            // prepare to glide
            glideSemitones = -12.0f * log2f(frequency / noteFrequency);
            if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f;
        }
        noteFrequency = frequency;
        noteNumber = note;
    }

    void SamplerVoice::restartNewNote(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer)
    {
        samplingRate = sampleRate;
        leftFilter.updateSampleRate(double(samplingRate));
        rightFilter.updateSampleRate(double(samplingRate));

        oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency);
        glideSemitones = 0.0f;
        if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency)
        {
            // prepare to glide
            glideSemitones = -12.0f * log2f(frequency / noteFrequency);
            if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f;
        }

        pitchEnvelopeSemitones = 0.0f;

        noteFrequency = frequency;
        noteNumber = note;
        tempNoteVolume = noteVolume;
        newSampleBuffer = buffer;
        adsrEnvelope.restart();
        noteVolume = volume;
        filterEnvelope.restart();
        pitchEnvelope.restart();
    }

    void SamplerVoice::restartNewNoteLegato(unsigned note, float sampleRate, float frequency)
    {
        samplingRate = sampleRate;
        leftFilter.updateSampleRate(double(samplingRate));
        rightFilter.updateSampleRate(double(samplingRate));

        oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency);
        glideSemitones = 0.0f;
        if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency)
        {
            // prepare to glide
            glideSemitones = -12.0f * log2f(frequency / noteFrequency);
            if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f;
        }
        noteFrequency = frequency;
        noteNumber = note;
    }

    void SamplerVoice::restartSameNote(float volume, SampleBuffer *buffer)
    {
        tempNoteVolume = noteVolume;
        newSampleBuffer = buffer;
        adsrEnvelope.restart();
        noteVolume = volume;
        filterEnvelope.restart();
        pitchEnvelope.restart();
    }

    void SamplerVoice::release(bool loopThruRelease)
    {
        if (!loopThruRelease) oscillator.isLooping = false;
        adsrEnvelope.release();
        filterEnvelope.release();
        pitchEnvelope.release();
    }

    void SamplerVoice::stop()
    {
        noteNumber = -1;
        adsrEnvelope.reset();
        volumeRamper.init(0.0f);
        filterEnvelope.reset();
        pitchEnvelope.reset();
    }

    bool SamplerVoice::prepToGetSamples(int sampleCount, float masterVolume, float pitchOffset,
                                        float cutoffMultiple, float keyTracking,
                                        float cutoffEnvelopeStrength, float cutoffEnvelopeVelocityScaling,
                                        float resLinear, float pitchADSRSemitones)
    {
        if (adsrEnvelope.isIdle()) return true;

        if (adsrEnvelope.isPreStarting()) //FIXME: EXHIBIT A
        {
            tempGain = masterVolume * tempNoteVolume;
            volumeRamper.reinit(adsrEnvelope.getSample(), sampleCount);
        }
        else
        {
            tempGain = masterVolume * noteVolume;
            volumeRamper.reinit(adsrEnvelope.getSample(), sampleCount);
        }

        if (*glideSecPerOctave != 0.0f && glideSemitones != 0.0f)
        {
            float seconds = sampleCount / samplingRate;
            float semitones = 12.0f * seconds / *glideSecPerOctave;
            if (glideSemitones < 0.0f)
            {
                glideSemitones += semitones;
                if (glideSemitones > 0.0f) glideSemitones = 0.0f;
            }
            else
            {
                glideSemitones -= semitones;
                if (glideSemitones < 0.0f) glideSemitones = 0.0f;
            }
        }

        float pitchCurveAmount = 1.0f; // >1 = faster curve, 0 < curve < 1 = slower curve - make this a parameter
        if (pitchCurveAmount < 0) { pitchCurveAmount = 0; }
        pitchEnvelopeSemitones = pow(pitchEnvelope.getSample(), pitchCurveAmount) * pitchADSRSemitones;

        float pitchOffsetModified = pitchOffset + glideSemitones + pitchEnvelopeSemitones;
        oscillator.setPitchOffsetSemitones(pitchOffsetModified);

        // negative value of cutoffMultiple means filters are disabled
        if (cutoffMultiple < 0.0f)
        {
            isFilterEnabled = false;
        }
        else
        {
            isFilterEnabled = true;
            float noteHz = noteFrequency * powf(2.0f, (pitchOffsetModified) / 12.0f);
            float baseFrequency = MIDDLE_C_HZ + keyTracking * (noteHz - MIDDLE_C_HZ);
            float envStrength = ((1.0f - cutoffEnvelopeVelocityScaling) + cutoffEnvelopeVelocityScaling * noteVolume);
            double cutoffFrequency = baseFrequency * (1.0f + cutoffMultiple + cutoffEnvelopeStrength * envStrength * filterEnvelope.getSample());
            leftFilter.setParameters(cutoffFrequency, resLinear);
            rightFilter.setParameters(cutoffFrequency, resLinear);
        }

        return false;
    }

    bool SamplerVoice::getSamples(int sampleCount, float *leftOutput, float *rightOutput)
    {
        for (int i=0; i < sampleCount; i++)
        {
            float gain = tempGain * volumeRamper.getNextValue();
            float leftSample, rightSample;
            if (oscillator.getSamplePair(sampleBuffer, sampleCount, &leftSample, &rightSample, gain))
                return true;
            if (isFilterEnabled)
            {
                *leftOutput++ += leftFilter.process(leftSample);
                *rightOutput++ += rightFilter.process(rightSample);
            }
            else
            {
                *leftOutput++ += leftSample;
                *rightOutput++ += rightSample;
            }
        }
        return false;
    }

}
<commit_msg>Revert "fix crash bug for BeatScratch app"<commit_after>//
//  SamplerVoice.cpp
//  AudioKit Core
//
//  Created by Shane Dunne, revision history on Github.
//  Copyright © 2018 AudioKit. All rights reserved.
//

#include "SamplerVoice.hpp"
#include <stdio.h>

#define MIDDLE_C_HZ 262.626f

namespace AudioKitCore
{
    void SamplerVoice::init(double sampleRate)
    {
        samplingRate = float(sampleRate);
        leftFilter.init(sampleRate);
        rightFilter.init(sampleRate);
        adsrEnvelope.init();
        filterEnvelope.init();
        pitchEnvelope.init();
        volumeRamper.init(0.0f);
        tempGain = 0.0f;
    }

    void SamplerVoice::start(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer)
    {
        sampleBuffer = buffer;
        oscillator.indexPoint = buffer->startPoint;
        oscillator.increment = (buffer->sampleRate / sampleRate) * (frequency / buffer->noteFrequency);
        oscillator.multiplier = 1.0;
        oscillator.isLooping = buffer->isLooping;

        noteVolume = volume;
        adsrEnvelope.start();
        volumeRamper.init(0.0f);

        samplingRate = sampleRate;
        leftFilter.updateSampleRate(double(samplingRate));
        rightFilter.updateSampleRate(double(samplingRate));
        filterEnvelope.start();

        pitchEnvelope.start();

        pitchEnvelopeSemitones = 0.0f;

        glideSemitones = 0.0f;
        if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency)
        {
            // prepare to glide
            glideSemitones = -12.0f * log2f(frequency / noteFrequency);
            if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f;
        }
        noteFrequency = frequency;
        noteNumber = note;
    }

    void SamplerVoice::restartNewNote(unsigned note, float sampleRate, float frequency, float volume, SampleBuffer *buffer)
    {
        samplingRate = sampleRate;
        leftFilter.updateSampleRate(double(samplingRate));
        rightFilter.updateSampleRate(double(samplingRate));

        oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency);
        glideSemitones = 0.0f;
        if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency)
        {
            // prepare to glide
            glideSemitones = -12.0f * log2f(frequency / noteFrequency);
            if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f;
        }

        pitchEnvelopeSemitones = 0.0f;

        noteFrequency = frequency;
        noteNumber = note;
        tempNoteVolume = noteVolume;
        newSampleBuffer = buffer;
        adsrEnvelope.restart();
        noteVolume = volume;
        filterEnvelope.restart();
        pitchEnvelope.restart();
    }

    void SamplerVoice::restartNewNoteLegato(unsigned note, float sampleRate, float frequency)
    {
        samplingRate = sampleRate;
        leftFilter.updateSampleRate(double(samplingRate));
        rightFilter.updateSampleRate(double(samplingRate));

        oscillator.increment = (sampleBuffer->sampleRate / sampleRate) * (frequency / sampleBuffer->noteFrequency);
        glideSemitones = 0.0f;
        if (*glideSecPerOctave != 0.0f && noteFrequency != 0.0 && noteFrequency != frequency)
        {
            // prepare to glide
            glideSemitones = -12.0f * log2f(frequency / noteFrequency);
            if (fabsf(glideSemitones) < 0.01f) glideSemitones = 0.0f;
        }
        noteFrequency = frequency;
        noteNumber = note;
    }

    void SamplerVoice::restartSameNote(float volume, SampleBuffer *buffer)
    {
        tempNoteVolume = noteVolume;
        newSampleBuffer = buffer;
        adsrEnvelope.restart();
        noteVolume = volume;
        filterEnvelope.restart();
        pitchEnvelope.restart();
    }

    void SamplerVoice::release(bool loopThruRelease)
    {
        if (!loopThruRelease) oscillator.isLooping = false;
        adsrEnvelope.release();
        filterEnvelope.release();
        pitchEnvelope.release();
    }

    void SamplerVoice::stop()
    {
        noteNumber = -1;
        adsrEnvelope.reset();
        volumeRamper.init(0.0f);
        filterEnvelope.reset();
        pitchEnvelope.reset();
    }

    bool SamplerVoice::prepToGetSamples(int sampleCount, float masterVolume, float pitchOffset,
                                        float cutoffMultiple, float keyTracking,
                                        float cutoffEnvelopeStrength, float cutoffEnvelopeVelocityScaling,
                                        float resLinear, float pitchADSRSemitones)
    {
        if (adsrEnvelope.isIdle()) return true;

        if (adsrEnvelope.isPreStarting()) //FIXME: EXHIBIT A
        {
            tempGain = masterVolume * tempNoteVolume;
            volumeRamper.reinit(adsrEnvelope.getSample(), sampleCount);
            // FIXME - is the following 'if' code (Exhibit B) ever executed if previous
            // 'if (adsrEnvelope.isPreStarting())' (Exhibit A) has already been checked, and is true?
            if (!adsrEnvelope.isPreStarting()) //FIXME: EXHIBIT B
            {
                tempGain = masterVolume * noteVolume;
                volumeRamper.reinit(adsrEnvelope.getSample(), sampleCount);
                sampleBuffer = newSampleBuffer;
                oscillator.increment = (sampleBuffer->sampleRate / samplingRate) * (noteFrequency / sampleBuffer->noteFrequency);
                oscillator.indexPoint = sampleBuffer->startPoint;
                oscillator.isLooping = sampleBuffer->isLooping;
            }
        }
        else
        {
            tempGain = masterVolume * noteVolume;
            volumeRamper.reinit(adsrEnvelope.getSample(), sampleCount);
        }

        if (*glideSecPerOctave != 0.0f && glideSemitones != 0.0f)
        {
            float seconds = sampleCount / samplingRate;
            float semitones = 12.0f * seconds / *glideSecPerOctave;
            if (glideSemitones < 0.0f)
            {
                glideSemitones += semitones;
                if (glideSemitones > 0.0f) glideSemitones = 0.0f;
            }
            else
            {
                glideSemitones -= semitones;
                if (glideSemitones < 0.0f) glideSemitones = 0.0f;
            }
        }

        float pitchCurveAmount = 1.0f; // >1 = faster curve, 0 < curve < 1 = slower curve - make this a parameter
        if (pitchCurveAmount < 0) { pitchCurveAmount = 0; }
        pitchEnvelopeSemitones = pow(pitchEnvelope.getSample(), pitchCurveAmount) * pitchADSRSemitones;

        float pitchOffsetModified = pitchOffset + glideSemitones + pitchEnvelopeSemitones;
        oscillator.setPitchOffsetSemitones(pitchOffsetModified);

        // negative value of cutoffMultiple means filters are disabled
        if (cutoffMultiple < 0.0f)
        {
            isFilterEnabled = false;
        }
        else
        {
            isFilterEnabled = true;
            float noteHz = noteFrequency * powf(2.0f, (pitchOffsetModified) / 12.0f);
            float baseFrequency = MIDDLE_C_HZ + keyTracking * (noteHz - MIDDLE_C_HZ);
            float envStrength = ((1.0f - cutoffEnvelopeVelocityScaling) + cutoffEnvelopeVelocityScaling * noteVolume);
            double cutoffFrequency = baseFrequency * (1.0f + cutoffMultiple + cutoffEnvelopeStrength * envStrength * filterEnvelope.getSample());
            leftFilter.setParameters(cutoffFrequency, resLinear);
            rightFilter.setParameters(cutoffFrequency, resLinear);
        }

        return false;
    }

    bool SamplerVoice::getSamples(int sampleCount, float *leftOutput, float *rightOutput)
    {
        for (int i=0; i < sampleCount; i++)
        {
            float gain = tempGain * volumeRamper.getNextValue();
            float leftSample, rightSample;
            if (oscillator.getSamplePair(sampleBuffer, sampleCount, &leftSample, &rightSample, gain))
                return true;
            if (isFilterEnabled)
            {
                *leftOutput++ += leftFilter.process(leftSample);
                *rightOutput++ += rightFilter.process(rightSample);
            }
            else
            {
                *leftOutput++ += leftSample;
                *rightOutput++ += rightSample;
            }
        }
        return false;
    }

}
<|endoftext|>


<commit_before>// Copyright (C) 2016 Amir Baserinia

// When testing and debugging your code, you might need to print variables.
// The LOG macro provides a very simple technique to do so. You simple call
// it with a variable name. It prints the file name, line number, variable
// name, and variable value to stderr.

// If you run the sample code, you will get something like this:
//	file "macro.cpp", line 15: var = 0
//	file "macro.cpp", line 16: &var = 0x7fffc30d1d6c

#include <iostream>

#ifndef LOG
  #define LOG(X) { \
    std::cerr << "file \"" << __FILE__ << "\", line " << __LINE__ << ": "; \
    std::cerr << #X" = " << (X) << std::endl; \
  }
#endif

int main()
{
	int var;
	LOG(var);
	LOG(&var);
	return 0;
}

<commit_msg>C processor macro for logging variables<commit_after>// Copyright (C) 2016 Amir Baserinia

// When testing and debugging your code, you might need to print variables.
// The LOG macro provides a very simple technique to do so. You simple call
// it with a variable name. It prints the file name, line number, variable
// name, and variable value to stderr.

// If you run the sample code, you will get something like this:
//	file "log.cpp", line 15: var = 0
//	file "log.cpp", line 16: &var = 0x7fffc30d1d6c

#include <iostream>

#ifndef LOG
  #define LOG(X) { \
    std::cerr << "file \"" << __FILE__ << "\", line " << __LINE__ << ": "; \
    std::cerr << #X" = " << (X) << std::endl; \
  }
#endif

int main()
{
	int var;
	LOG(var);
	LOG(&var);
	return 0;
}

<|endoftext|>


<commit_before>#include <Poco/AutoPtr.h>

#include <gtest/gtest.h>
#include <exception>
#include <iostream>
#include <string>
#include <strstream>

#include "db.h"

#ifdef ENABLE_SQLITE3

extern "C" {
    extern DB::Connection *create_sqlite3_connection(void);
};

class SqliteInvalidTest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            connection = create_sqlite3_connection();
            connection->open(".", NULL, 0, NULL, NULL);
        }

        virtual void TearDown() {
            connection->release();
        }

        Poco::AutoPtr <DB::Connection> connection;
};

TEST_F(SqliteInvalidTest, CannotConnectToDatabase) {
    ASSERT_EQ(connection->isConnected(), false);
}

class SqliteDefaultTest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            connection = create_sqlite3_connection();
            connection->open("test.db", NULL, 0, NULL, NULL);
        }

        virtual void TearDown() {
            connection->release();
        }

        Poco::AutoPtr <DB::Connection> connection;
};

TEST_F(SqliteDefaultTest, CanConnectToDatabase) {
    EXPECT_EQ(connection->isConnected(), true);
}

TEST_F(SqliteDefaultTest, CanExecuteSimpleQuery) {
    EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP, updatedOn TIMESTAMP)"), true);
    EXPECT_EQ(connection->execute("DROP TABLE testing"), true);
}

TEST_F(SqliteDefaultTest, CannotExecuteSimpleQuery) {
    EXPECT_EQ(connection->execute("BYE"), false);
}

TEST_F(SqliteDefaultTest, EscapeCharacters) {
    EXPECT_STREQ(connection->escape("be'nden"), "'be''nden'");
}

TEST_F(SqliteDefaultTest, UnixTimeToSQL) {
    const char *t = connection->unixtimeToSql((time_t) 1414965631);
    EXPECT_STREQ(t, "'2014-11-02 22:00:31'");
}

TEST_F(SqliteDefaultTest, ErrorNumberAndMessage) {
    EXPECT_EQ(connection->errorno(), 0);
    EXPECT_STREQ(connection->errormsg(), "not an error");
}

TEST_F(SqliteDefaultTest, VersionString) {
    const char *v = connection->version();
    bool correct = false;
    if (strstr(v, "Sqlite3 Driver v0.2")) {
        correct = true;
    }
    EXPECT_EQ(correct, true);
}

class SqliteTransactionTest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            connection = create_sqlite3_connection();
            connection->open("test.db", NULL, 0, NULL, NULL);
            EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updatedOn TIMESTAMP)"), true);
            connection->beginTrans();
        }

        virtual void TearDown() {
            connection->commitTrans();
            connection->execute("DROP TABLE testing");
            connection->close();
            connection->release();
        }

        Poco::AutoPtr <DB::Connection> connection;
};

TEST_F(SqliteTransactionTest, SingleInsert) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
}

TEST_F(SqliteTransactionTest, SingleSelect) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
    EXPECT_EQ(connection->commitTrans(), true);

    DB::ResultSet *rs = connection->executeQuery("SELECT * FROM testing;");
    EXPECT_NE(rs, (DB::ResultSet *) NULL);
    if (rs) {
    rs->next();
    EXPECT_EQ(rs->findColumn("text"), 1);
    EXPECT_STREQ(rs->getString(1), "benden");
    EXPECT_EQ(rs->findColumn("fl"), 3);
    EXPECT_EQ(rs->findColumn("r"), 6);
    EXPECT_EQ(rs->getInteger(3), 42);
    EXPECT_EQ(rs->getFloat(3), 42.0f);
    EXPECT_EQ(rs->getDouble(3), 42.0F);
    EXPECT_EQ(rs->getLong(3), 42l);
    EXPECT_EQ(rs->getBool(3), false);
    EXPECT_EQ(rs->getShort(3), (short) 42);
    EXPECT_NE(rs->getUnixTime(4), -1);
    EXPECT_EQ(rs->getUnixTime(5), 0);
    EXPECT_EQ(rs->recordCount(), 0);
    rs->close();
    }
}

TEST_F(SqliteTransactionTest, DoubleSelect) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
    EXPECT_EQ(connection->commitTrans(), true);

    DB::Query q(*connection);
    q << "SELECT * FROM testing;";
    DB::ResultSet *rs = connection->executeQuery(q.str());
    EXPECT_NE(rs, (DB::ResultSet *) NULL);
    if (rs) {
    rs->next();
    EXPECT_EQ(rs->findColumn("text"), 1);
    EXPECT_STREQ(rs->getString(1), "benden");
    EXPECT_EQ(rs->findColumn("fl"), 3);
    EXPECT_EQ(rs->findColumn("r"), 6);
    EXPECT_EQ(rs->getInteger(3), 1);
    EXPECT_EQ(rs->getFloat(3), 1.0f);
    EXPECT_EQ(rs->getDouble(3), 1.0F);
    EXPECT_EQ(rs->getLong(3), 1l);
    EXPECT_EQ(rs->getBool(3), true);
    EXPECT_EQ(rs->getShort(3), (short) 1);
    EXPECT_NE(rs->getUnixTime(4), -1);
    EXPECT_EQ(rs->getUnixTime(5), 0);
    rs->close();
    }
}

TEST_F(SqliteTransactionTest, QueryString) {
    connection->setTransactionMode(DB::Connection::READ_UNCOMMITTED);
    connection->setTransactionMode(DB::Connection::READ_COMMITTED);
    connection->setTransactionMode(DB::Connection::REPEATABLE_READ);
    connection->setTransactionMode(DB::Connection::SERIALIZABLE);

    connection->beginTrans();

    DB::Query q(*connection);
    q << "INSERT INTO testing (text,fl) VALUES (" << DB::qstr("benden");
    q << "," << 42.0f << ");";
    EXPECT_EQ(connection->execute(q.str()), true);
    std::cout << q.str() << std::endl;
    std::cout << connection->errormsg() << std::endl;
    unsigned long id = connection->insertId();
    EXPECT_EQ(id, 1);
    EXPECT_EQ(connection->commitTrans(), true);
}

TEST_F(SqliteTransactionTest, RollbackTransaction) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text) VALUES ('benden');"), true);
    EXPECT_EQ(connection->rollbackTrans(), true);
}

TEST_F(SqliteTransactionTest, QueryStringTypes) {
    DB::Query q(*connection);

    q << "INSERT INTO test (text,fl,updatedOn) VALUES (";
    q << DB::qstr("benden") << "," << 42l << "," << DB::unixtime(time(NULL)) << ");";
    EXPECT_EQ(strlen(q.str()), 80);
}

TEST_F(SqliteTransactionTest, QueryStringTypes2) {
    DB::Query q(*connection);
    std::stringstream world;
    world << " World" << std::ends;

    q << std::string("Hello") << world;

    EXPECT_EQ(strlen(q.str()), 11);
}

TEST_F(SqliteTransactionTest, QueryNumberTypes) {
    DB::Query q(*connection);
    double d = 42.2;
    short s = 42;
    unsigned short su = 42;

    q << 42 << " " << d << " " << s << (const unsigned char *) " ";
    q << 42u << " " << 42ul << " " << su;
}

#endif

<commit_msg>Fixed schema for older sqlite3.<commit_after>#include <Poco/AutoPtr.h>

#include <gtest/gtest.h>
#include <exception>
#include <iostream>
#include <string>
#include <strstream>

#include "db.h"

#ifdef ENABLE_SQLITE3

extern "C" {
    extern DB::Connection *create_sqlite3_connection(void);
};

class SqliteInvalidTest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            connection = create_sqlite3_connection();
            connection->open(".", NULL, 0, NULL, NULL);
        }

        virtual void TearDown() {
            connection->release();
        }

        Poco::AutoPtr <DB::Connection> connection;
};

TEST_F(SqliteInvalidTest, CannotConnectToDatabase) {
    ASSERT_EQ(connection->isConnected(), false);
}

class SqliteDefaultTest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            connection = create_sqlite3_connection();
            connection->open("test.db", NULL, 0, NULL, NULL);
        }

        virtual void TearDown() {
            connection->release();
        }

        Poco::AutoPtr <DB::Connection> connection;
};

TEST_F(SqliteDefaultTest, CanConnectToDatabase) {
    EXPECT_EQ(connection->isConnected(), true);
}

TEST_F(SqliteDefaultTest, CanExecuteSimpleQuery) {
    EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP, updatedOn TIMESTAMP)"), true);
    EXPECT_EQ(connection->execute("DROP TABLE testing"), true);
}

TEST_F(SqliteDefaultTest, CannotExecuteSimpleQuery) {
    EXPECT_EQ(connection->execute("BYE"), false);
}

TEST_F(SqliteDefaultTest, EscapeCharacters) {
    EXPECT_STREQ(connection->escape("be'nden"), "'be''nden'");
}

TEST_F(SqliteDefaultTest, UnixTimeToSQL) {
    const char *t = connection->unixtimeToSql((time_t) 1414965631);
    EXPECT_STREQ(t, "'2014-11-02 22:00:31'");
}

TEST_F(SqliteDefaultTest, ErrorNumberAndMessage) {
    EXPECT_EQ(connection->errorno(), 0);
    EXPECT_STREQ(connection->errormsg(), "not an error");
}

TEST_F(SqliteDefaultTest, VersionString) {
    const char *v = connection->version();
    bool correct = false;
    if (strstr(v, "Sqlite3 Driver v0.2")) {
        correct = true;
    }
    EXPECT_EQ(correct, true);
}

class SqliteTransactionTest : public ::testing::Test {
    protected:
        virtual void SetUp() {
            connection = create_sqlite3_connection();
            connection->open("test.db", NULL, 0, NULL, NULL);
            EXPECT_EQ(connection->execute("CREATE TABLE testing (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, text VARCHAR(128), num INTEGER, fl FLOAT, createdOn TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updatedOn TIMESTAMP)"), true);
            connection->beginTrans();
        }

        virtual void TearDown() {
            connection->commitTrans();
            connection->execute("DROP TABLE testing");
            connection->close();
            connection->release();
        }

        Poco::AutoPtr <DB::Connection> connection;
};

TEST_F(SqliteTransactionTest, SingleInsert) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
}

TEST_F(SqliteTransactionTest, SingleSelect) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',42)"), true);
    EXPECT_EQ(connection->commitTrans(), true);

    DB::ResultSet *rs = connection->executeQuery("SELECT * FROM testing;");
    EXPECT_NE(rs, (DB::ResultSet *) NULL);
    if (rs) {
    rs->next();
    EXPECT_EQ(rs->findColumn("text"), 1);
    EXPECT_STREQ(rs->getString(1), "benden");
    EXPECT_EQ(rs->findColumn("fl"), 3);
    EXPECT_EQ(rs->findColumn("r"), 6);
    EXPECT_EQ(rs->getInteger(3), 42);
    EXPECT_EQ(rs->getFloat(3), 42.0f);
    EXPECT_EQ(rs->getDouble(3), 42.0F);
    EXPECT_EQ(rs->getLong(3), 42l);
    EXPECT_EQ(rs->getBool(3), false);
    EXPECT_EQ(rs->getShort(3), (short) 42);
    EXPECT_NE(rs->getUnixTime(4), -1);
    EXPECT_EQ(rs->getUnixTime(5), 0);
    EXPECT_EQ(rs->recordCount(), 0);
    rs->close();
    }
}

TEST_F(SqliteTransactionTest, DoubleSelect) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
    EXPECT_EQ(connection->execute("INSERT INTO testing (text,fl) VALUES ('benden',1)"), true);
    EXPECT_EQ(connection->commitTrans(), true);

    DB::Query q(*connection);
    q << "SELECT * FROM testing;";
    DB::ResultSet *rs = connection->executeQuery(q.str());
    EXPECT_NE(rs, (DB::ResultSet *) NULL);
    if (rs) {
    rs->next();
    EXPECT_EQ(rs->findColumn("text"), 1);
    EXPECT_STREQ(rs->getString(1), "benden");
    EXPECT_EQ(rs->findColumn("fl"), 3);
    EXPECT_EQ(rs->findColumn("r"), 6);
    EXPECT_EQ(rs->getInteger(3), 1);
    EXPECT_EQ(rs->getFloat(3), 1.0f);
    EXPECT_EQ(rs->getDouble(3), 1.0F);
    EXPECT_EQ(rs->getLong(3), 1l);
    EXPECT_EQ(rs->getBool(3), true);
    EXPECT_EQ(rs->getShort(3), (short) 1);
    EXPECT_NE(rs->getUnixTime(4), -1);
    EXPECT_EQ(rs->getUnixTime(5), 0);
    rs->close();
    }
}

TEST_F(SqliteTransactionTest, QueryString) {
    EXPECT_EQ(connection->setTransactionMode(DB::Connection::READ_UNCOMMITTED), true);
    EXPECT_EQ(connection->setTransactionMode(DB::Connection::READ_COMMITTED), true);
    EXPECT_EQ(connection->setTransactionMode(DB::Connection::REPEATABLE_READ), true);
    EXPECT_EQ(connection->setTransactionMode(DB::Connection::SERIALIZABLE), true);

    EXPECT_EQ(connection->beginTrans(), true);

    DB::Query q(*connection);
    q << "INSERT INTO testing (text,fl) VALUES (" << DB::qstr("benden");
    q << "," << 42.0f << ");";
    EXPECT_EQ(connection->execute(q.str()), true);
    std::cout << q.str() << std::endl;
    std::cout << connection->errormsg() << std::endl;
    unsigned long id = connection->insertId();
    EXPECT_EQ(id, 1);
    EXPECT_EQ(connection->commitTrans(), true);
}

TEST_F(SqliteTransactionTest, RollbackTransaction) {
    EXPECT_EQ(connection->execute("INSERT INTO testing (text) VALUES ('benden');"), true);
    EXPECT_EQ(connection->rollbackTrans(), true);
}

TEST_F(SqliteTransactionTest, QueryStringTypes) {
    DB::Query q(*connection);

    q << "INSERT INTO test (text,fl,updatedOn) VALUES (";
    q << DB::qstr("benden") << "," << 42l << "," << DB::unixtime(time(NULL)) << ");";
    EXPECT_EQ(strlen(q.str()), 80);
}

TEST_F(SqliteTransactionTest, QueryStringTypes2) {
    DB::Query q(*connection);
    std::stringstream world;
    world << " World" << std::ends;

    q << std::string("Hello") << world;

    EXPECT_EQ(strlen(q.str()), 11);
}

TEST_F(SqliteTransactionTest, QueryNumberTypes) {
    DB::Query q(*connection);
    double d = 42.2;
    short s = 42;
    unsigned short su = 42;

    q << 42 << " " << d << " " << s << (const unsigned char *) " ";
    q << 42u << " " << 42ul << " " << su;
}

#endif

<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "test.hpp"

namespace {

//TODO Add tests for long

template<typename T>
struct outer {
    int five;
    T inner;
    int special;

    outer() : inner() {}
    outer(size_t n) : inner(n){}
};

} // end of anonymous namespace

TEMPLATE_TEST_CASE_4("alignment/fast/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_vector<ZZZ, 5>;

    type a;
    auto b = a;
    auto* c = new type();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/fast/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_vector<ZZZ, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

ETL_TEST_CASE("alignment/fast/3", "[alignment]") {
    using type = etl::fast_vector<int, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/fast_dyn/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_dyn_vector<ZZZ, 5>;

    type a;
    auto b = a;
    auto* c = new type();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/fast_dyn/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_dyn_vector<ZZZ, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

ETL_TEST_CASE("alignment/fast_dyn/3", "[alignment]") {
    using type = etl::fast_dyn_vector<int, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/dyn/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::dyn_vector<ZZZ>;

    type a(5);
    auto b = a;
    auto* c = new type(5);

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/dyn/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::dyn_vector<ZZZ>;

    outer<type> a(5);
    auto b = a;
    auto* c = new outer<type>(5);

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

ETL_TEST_CASE("alignment/dyn/3", "[alignment]") {
    using type = etl::dyn_vector<int>;

    outer<type> a(5);
    auto b = a;
    auto* c = new outer<type>(5);

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/temporary/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    etl::dyn_matrix<ZZZ> a(3, 3);
    etl::dyn_matrix<ZZZ> b(3, 3);

    auto c = a * b;
    *c;

    REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/temporary/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    etl::dyn_vector<ZZZ> a(3);
    etl::dyn_matrix<ZZZ> b(3, 3);

    auto c = a * b;
    *c;

    REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/temporary/3", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    etl::dyn_matrix<ZZZ> a(3, 3);
    etl::dyn_vector<ZZZ> b(3);

    auto c = a * b;
    *c;

    REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

//TODO Add the following test!
//ETL_TEST_CASE("alignment/temporary/4", "[alignment]") {
    //etl::dyn_matrix<int> a(3, 3);
    //etl::dyn_vector<int> b(3);

    //auto c = a * b;
    //*c;

    //REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
//}
<commit_msg>Fix leaks in the unit tests<commit_after>//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include "test.hpp"

namespace {

//TODO Add tests for long

template<typename T>
struct outer {
    int five;
    T inner;
    int special;

    outer() : inner() {}
    outer(size_t n) : inner(n){}
};

} // end of anonymous namespace

TEMPLATE_TEST_CASE_4("alignment/fast/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_vector<ZZZ, 5>;

    type a;
    auto b = a;
    auto* c = new type();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);

    delete c;
}

TEMPLATE_TEST_CASE_4("alignment/fast/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_vector<ZZZ, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);

    delete c;
}

ETL_TEST_CASE("alignment/fast/3", "[alignment]") {
    using type = etl::fast_vector<int, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);

    delete c;
}

TEMPLATE_TEST_CASE_4("alignment/fast_dyn/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_dyn_vector<ZZZ, 5>;

    type a;
    auto b = a;
    auto* c = new type();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);

    delete c;
}

TEMPLATE_TEST_CASE_4("alignment/fast_dyn/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::fast_dyn_vector<ZZZ, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);

    delete c;
}

ETL_TEST_CASE("alignment/fast_dyn/3", "[alignment]") {
    using type = etl::fast_dyn_vector<int, 5>;

    outer<type> a;
    auto b = a;
    auto* c = new outer<type>();

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);

    delete c;
}

TEMPLATE_TEST_CASE_4("alignment/dyn/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::dyn_vector<ZZZ>;

    type a(5);
    auto b = a;
    auto* c = new type(5);

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);

    delete c;
}

TEMPLATE_TEST_CASE_4("alignment/dyn/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    using type = etl::dyn_vector<ZZZ>;

    outer<type> a(5);
    auto b = a;
    auto* c = new outer<type>(5);

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);

    delete c;
}

ETL_TEST_CASE("alignment/dyn/3", "[alignment]") {
    using type = etl::dyn_vector<int>;

    outer<type> a(5);
    auto b = a;
    auto* c = new outer<type>(5);

    REQUIRE_DIRECT(reinterpret_cast<size_t>(a.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(b.inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
    REQUIRE_DIRECT(reinterpret_cast<size_t>(c->inner.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);

    delete c;
}

TEMPLATE_TEST_CASE_4("alignment/temporary/1", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    etl::dyn_matrix<ZZZ> a(3, 3);
    etl::dyn_matrix<ZZZ> b(3, 3);

    auto c = a * b;
    *c;

    REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/temporary/2", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    etl::dyn_vector<ZZZ> a(3);
    etl::dyn_matrix<ZZZ> b(3, 3);

    auto c = a * b;
    *c;

    REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

TEMPLATE_TEST_CASE_4("alignment/temporary/3", "[alignment]", ZZZ, double, float, std::complex<float>, std::complex<double>) {
    etl::dyn_matrix<ZZZ> a(3, 3);
    etl::dyn_vector<ZZZ> b(3);

    auto c = a * b;
    *c;

    REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<ZZZ>::alignment == 0);
}

//TODO Add the following test!
//ETL_TEST_CASE("alignment/temporary/4", "[alignment]") {
    //etl::dyn_matrix<int> a(3, 3);
    //etl::dyn_vector<int> b(3);

    //auto c = a * b;
    //*c;

    //REQUIRE_DIRECT(reinterpret_cast<size_t>(c.memory_start()) % etl::default_intrinsic_traits<int>::alignment == 0);
//}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include "DPAG.h"
#include <cstdio>
#include <vector>
#include <fstream>
using namespace std;

typedef unsigned int uint;

TEST_CASE("Basic DPAG usage", "[dpag]") {
  uint num_nodes = 10;
  DPAG d(num_nodes);

  CHECK(boost::num_vertices(d) == num_nodes);

  Vertex_d v;
  VertexId vertex_id = boost::get(boost::vertex_index, d);
  vertexIt v_i, v_end;
  outIter out_i, out_end, out_i1;
  EdgeId edge_id = boost::get(boost::edge_index, d);

  // access vertices with iterators and indices
  SECTION("accessing vertices") {
    boost::tie(v_i, v_end) = boost::vertices(d);
    SECTION("first vertex") {
      CHECK(vertex_id[*v_i] == 0);
    }
    SECTION("another vertex") {
      v_i++; v_i++; v_i++;
      CHECK(vertex_id[*v_i] == 3);
    }
  }

  // check looping over edges
  // add edges, check results with iterators
  SECTION("add some edges") {
    boost::add_edge(2,3, EdgeProperty(0), d);
    boost::add_edge(2,8, EdgeProperty(1), d);
    CHECK(boost::num_edges(d) == 2);

    // we've added the right edge
    v = boost::vertex(2, d);
    boost::tie(out_i, out_end)=boost::out_edges(v, d);
    SECTION("accessing first edge") {
      CHECK(target(*out_i, d) == 3);
      CHECK(edge_id[*out_i] == 0);
    }

    SECTION("accessing second and last edge") {
      CHECK(target(*(++out_i), d) == 8);
      CHECK(edge_id[*out_i] == 1);
      CHECK(++out_i == out_end);
    }
  }
}

class DPAGGenerator {
  DPAG** dpags;

public:

  // build a sequence of T steps
  DPAG make_sequence(uint T) {
    DPAG s(T);

    // make the connections go from right to left
    // to emulate RNN unfolding from right to left,
    // i.e. reverse topological sort
    for(uint i=T-1; i>0; --i)
      boost::add_edge(i, i-1, s);

    return s;
  }

  DPAG make_dpag(const char* fname) {
    ifstream is(fname);
    if(!is) {
      fprintf(stderr, "Could not open file %s\n", fname);
      exit(1);
    }

    string line;
    getline(is, line);
    istringstream iss(line);
    int V;
    iss >> V;
    DPAG d(V);

    for(int i=0; i<V; ++i) {
      getline(is, line);
      istringstream iss1(line);
      int v;
      iss1 >> v;
      int target;
      int eindex = 0;
      while(iss1 >> target)
	boost::add_edge(v, target, EdgeProperty(eindex++), d);
    }

    return d;
  }

  DPAG make_grid(uint N) {
    DPAG grid(N);

    return grid;
  }
};

TEST_CASE("DPAG functions with various data structures", "[dpag]") {
  //Vertex_d v;
  vertexIt v_i, v_end;
  outIter out_i, out_end;
  ieIter in_i, in_end;

  DPAGGenerator dg;

  int T = 10;
  DPAG sequence = dg.make_sequence(T);

  CHECK(boost::num_vertices(sequence) == T);

  DPAG dpag = dg.make_dpag("data/test_dpag.gph");

  int N = T;
  DPAG grid = dg.make_grid(N);
  CHECK(boost::num_vertices(grid) == N);

  SECTION("equal - same skeleton") {
    DPAG sequence1 = dg.make_sequence(T);
    CHECK(equal(sequence, sequence1));

    DPAG dpag1 = dg.make_dpag("data/test_dpag.gph");
    CHECK(equal(dpag, dpag1));

    DPAG grid1 = dg.make_grid(N);
    CHECK(equal(grid, grid1));

    SECTION("different edge properties") {
      DPAG sequence2 = dg.make_sequence(T);

      VertexId vertex_id = boost::get(boost::vertex_index, sequence2);
      Vertex_d v = boost::vertex(3, sequence2);
      outIter out_i = boost::out_edges(v, sequence2).first;
      EdgeId edge_id = boost::get(boost::edge_index, sequence2);
      edge_id[*out_i] = 2;
      CHECK_FALSE(equal(sequence, sequence2));
    }
  }

  SECTION("equal - different skeleton") {
    CHECK_FALSE(equal(sequence, dpag));
    CHECK_FALSE(equal(sequence, grid));
    CHECK_FALSE(equal(dpag, grid));
  }

  SECTION("linear sequence") {
    CHECK(max_indegree(sequence) == 1);
    CHECK(max_outdegree(sequence) == 1);

    VertexId vertex_id = boost::get(boost::vertex_index, sequence);
    EdgeId edge_id = boost::get(boost::edge_index, sequence);

    for(boost::tie(v_i, v_end) = boost::vertices(sequence); v_i!=v_end; ++v_i) {
      boost::tie(out_i, out_end)=boost::out_edges(*v_i, sequence);
      boost::tie(in_i, in_end)=boost::in_edges(*v_i, sequence);

      int id = vertex_id[*v_i];
      if(id == 0) {
	CHECK(boost::source(*in_i, sequence) == vertex_id[*(v_i+1)]);
	CHECK(++in_i == in_end);
	CHECK(out_i == out_end);
      } else if(id < T-1) {
	CHECK(boost::target(*out_i, sequence) == vertex_id[*(v_i-1)]);
	CHECK(++out_i == out_end);
	CHECK(boost::source(*in_i, sequence) == vertex_id[*(v_i+1)]);
	CHECK(++in_i == in_end);
      } else {
	CHECK(id == T-1);
	CHECK(boost::target(*out_i, sequence) == vertex_id[*(v_i-1)]);
	CHECK(++out_i == out_end);
	CHECK(in_i == in_end);
      }
    }

    SECTION("topological sort") {
      std::vector<int> top_sort = topological_sort(sequence);
      CHECK(top_sort.size() == boost::num_vertices(sequence));
      for(int i=0; i<boost::num_vertices(sequence); ++i)
	CHECK(top_sort[i] == T-i-1);
    }
  }

  SECTION("DPAG") {
    CHECK(max_indegree(dpag) == 2);
    CHECK(max_outdegree(dpag) == 2);

    VertexId vertex_id = boost::get(boost::vertex_index, dpag);
    EdgeId edge_id = boost::get(boost::edge_index, dpag);

    Vertex_d v = boost::vertex(0, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);

    CHECK(in_i == in_end);
    CHECK(boost::target(*out_i, dpag) == 1);
    CHECK(edge_id[*out_i] == 0);
    CHECK(boost::target(*(++out_i), dpag) == 3);
    CHECK(edge_id[*out_i] == 1);
    CHECK(++out_i == out_end);

    v = boost::vertex(1, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);
    CHECK(boost::source(*in_i, dpag) == 0);
    CHECK(++in_i == in_end);
    CHECK(boost::target(*out_i, dpag) == 2);
    CHECK(edge_id[*out_i] == 0);
    CHECK(boost::target(*(++out_i), dpag) == 3);
    CHECK(edge_id[*out_i] == 1);
    CHECK(++out_i == out_end);

    v = boost::vertex(2, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);
    CHECK(boost::source(*in_i, dpag) == 1);
    CHECK(++in_i == in_end);
    CHECK(out_i == out_end);

    v = boost::vertex(3, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);
    CHECK(boost::source(*in_i, dpag) == 0);
    CHECK(boost::source(*(++in_i), dpag) == 1);
    CHECK(++in_i == in_end);
    CHECK(out_i == out_end);

    SECTION("topological sort") {
      vector<int> top_sort = topological_sort(dpag);
      int V = boost::num_vertices(dpag);
      CHECK(top_sort.size() == V);

      CHECK(top_sort[0] == 0);
      CHECK(top_sort[1] == 1);
      // TODO:: cannot check with complex expressions
      CHECK(0);
      // CHECK(top_sort[2] == 2 || top_sort[2] == 3);
      // CHECK(top_sort[3] == 2 || top_sort[3] == 3);
    }
  }

  SECTION("Grid") {

    SECTION("topological sort") {
    }
  }
}
<commit_msg>Testing grids, incomplete.<commit_after>#include "catch.hpp"

#include "DPAG.h"
#include <cstdio>
#include <vector>
#include <fstream>
using namespace std;

typedef unsigned int uint;

TEST_CASE("Basic DPAG usage", "[dpag]") {
  uint num_nodes = 10;
  DPAG d(num_nodes);

  CHECK(boost::num_vertices(d) == num_nodes);

  Vertex_d v;
  VertexId vertex_id = boost::get(boost::vertex_index, d);
  vertexIt v_i, v_end;
  outIter out_i, out_end, out_i1;
  EdgeId edge_id = boost::get(boost::edge_index, d);

  // access vertices with iterators and indices
  SECTION("accessing vertices") {
    boost::tie(v_i, v_end) = boost::vertices(d);
    SECTION("first vertex") {
      CHECK(vertex_id[*v_i] == 0);
    }
    SECTION("another vertex") {
      v_i++; v_i++; v_i++;
      CHECK(vertex_id[*v_i] == 3);
    }
  }

  // check looping over edges
  // add edges, check results with iterators
  SECTION("add some edges") {
    boost::add_edge(2,3, EdgeProperty(0), d);
    boost::add_edge(2,8, EdgeProperty(1), d);
    CHECK(boost::num_edges(d) == 2);

    // we've added the right edge
    v = boost::vertex(2, d);
    boost::tie(out_i, out_end)=boost::out_edges(v, d);
    SECTION("accessing first edge") {
      CHECK(target(*out_i, d) == 3);
      CHECK(edge_id[*out_i] == 0);
    }

    SECTION("accessing second and last edge") {
      CHECK(target(*(++out_i), d) == 8);
      CHECK(edge_id[*out_i] == 1);
      CHECK(++out_i == out_end);
    }
  }
}

class DPAGGenerator {
  DPAG** dpags;

public:

  // build a sequence of T steps
  DPAG make_sequence(uint T) {
    DPAG s(T);

    // make the connections go from right to left
    // to emulate RNN unfolding from right to left,
    // i.e. reverse topological sort
    for(uint i=T-1; i>0; --i)
      boost::add_edge(i, i-1, s);

    return s;
  }

  DPAG make_dpag(const char* fname) {
    ifstream is(fname);
    if(!is) {
      fprintf(stderr, "Could not open file %s\n", fname);
      exit(1);
    }

    string line;
    getline(is, line);
    istringstream iss(line);
    int V;
    iss >> V;
    DPAG d(V);

    for(int i=0; i<V; ++i) {
      getline(is, line);
      istringstream iss1(line);
      int v;
      iss1 >> v;
      int target;
      int eindex = 0;
      while(iss1 >> target)
	boost::add_edge(v, target, EdgeProperty(eindex++), d);
    }

    return d;
  }

  DPAG make_grid(uint N) {
    DPAG grid(N);

    // build a nwse grid
    for(uint i=0; i<N; ++i) {
      for(uint j=0; j<N; ++j) {
	int edge_index = 0;
	if(j<N-1)
	  boost::add_edge(i*N+j, i*N+j+1, EdgeProperty(edge_index++), grid);
	if(i<N-1)
	  boost::add_edge(i*N+j, (i+1)*N+j, EdgeProperty(edge_index++), grid);
      }
    }

    return grid;
  }
};

TEST_CASE("DPAG functions with various data structures", "[dpag]") {
  //Vertex_d v;
  vertexIt v_i, v_end;
  outIter out_i, out_end;
  ieIter in_i, in_end;

  DPAGGenerator dg;

  int T = 10;
  DPAG sequence = dg.make_sequence(T);

  CHECK(boost::num_vertices(sequence) == T);

  DPAG dpag = dg.make_dpag("data/test_dpag.gph");

  int N = T;
  DPAG grid = dg.make_grid(N);
  CHECK(boost::num_vertices(grid) == N*N);

  SECTION("equal - same skeleton") {
    DPAG sequence1 = dg.make_sequence(T);
    CHECK(equal(sequence, sequence1));

    DPAG dpag1 = dg.make_dpag("data/test_dpag.gph");
    CHECK(equal(dpag, dpag1));

    DPAG grid1 = dg.make_grid(N);
    CHECK(equal(grid, grid1));

    SECTION("different edge properties") {
      DPAG sequence2 = dg.make_sequence(T);

      VertexId vertex_id = boost::get(boost::vertex_index, sequence2);
      Vertex_d v = boost::vertex(3, sequence2);
      outIter out_i = boost::out_edges(v, sequence2).first;
      EdgeId edge_id = boost::get(boost::edge_index, sequence2);
      edge_id[*out_i] = 2;
      CHECK_FALSE(equal(sequence, sequence2));
    }
  }

  SECTION("equal - different skeleton") {
    CHECK_FALSE(equal(sequence, dpag));
    CHECK_FALSE(equal(sequence, grid));
    CHECK_FALSE(equal(dpag, grid));
  }

  SECTION("linear sequence") {
    CHECK(max_indegree(sequence) == 1);
    CHECK(max_outdegree(sequence) == 1);

    VertexId vertex_id = boost::get(boost::vertex_index, sequence);
    EdgeId edge_id = boost::get(boost::edge_index, sequence);

    for(boost::tie(v_i, v_end) = boost::vertices(sequence); v_i!=v_end; ++v_i) {
      boost::tie(out_i, out_end)=boost::out_edges(*v_i, sequence);
      boost::tie(in_i, in_end)=boost::in_edges(*v_i, sequence);

      int id = vertex_id[*v_i];
      if(id == 0) {
	CHECK(boost::source(*in_i, sequence) == vertex_id[*(v_i+1)]);
	CHECK(++in_i == in_end);
	CHECK(out_i == out_end);
      } else if(id < T-1) {
	CHECK(boost::target(*out_i, sequence) == vertex_id[*(v_i-1)]);
	CHECK(++out_i == out_end);
	CHECK(boost::source(*in_i, sequence) == vertex_id[*(v_i+1)]);
	CHECK(++in_i == in_end);
      } else {
	CHECK(id == T-1);
	CHECK(boost::target(*out_i, sequence) == vertex_id[*(v_i-1)]);
	CHECK(++out_i == out_end);
	CHECK(in_i == in_end);
      }
    }

    SECTION("topological sort") {
      std::vector<int> top_sort = topological_sort(sequence);
      CHECK(top_sort.size() == boost::num_vertices(sequence));
      for(uint i=0; i<boost::num_vertices(sequence); ++i)
	CHECK(top_sort[i] == T-i-1);
    }
  }

  SECTION("DPAG") {
    CHECK(max_indegree(dpag) == 2);
    CHECK(max_outdegree(dpag) == 2);

    VertexId vertex_id = boost::get(boost::vertex_index, dpag);
    EdgeId edge_id = boost::get(boost::edge_index, dpag);

    Vertex_d v = boost::vertex(0, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);

    CHECK(in_i == in_end);
    CHECK(boost::target(*out_i, dpag) == 1);
    CHECK(edge_id[*out_i] == 0);
    CHECK(boost::target(*(++out_i), dpag) == 3);
    CHECK(edge_id[*out_i] == 1);
    CHECK(++out_i == out_end);

    v = boost::vertex(1, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);
    CHECK(boost::source(*in_i, dpag) == 0);
    CHECK(++in_i == in_end);
    CHECK(boost::target(*out_i, dpag) == 2);
    CHECK(edge_id[*out_i] == 0);
    CHECK(boost::target(*(++out_i), dpag) == 3);
    CHECK(edge_id[*out_i] == 1);
    CHECK(++out_i == out_end);

    v = boost::vertex(2, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);
    CHECK(boost::source(*in_i, dpag) == 1);
    CHECK(++in_i == in_end);
    CHECK(out_i == out_end);

    v = boost::vertex(3, dpag);
    boost::tie(out_i, out_end)=boost::out_edges(v, dpag);
    boost::tie(in_i, in_end)=boost::in_edges(v, dpag);
    CHECK(boost::source(*in_i, dpag) == 0);
    CHECK(boost::source(*(++in_i), dpag) == 1);
    CHECK(++in_i == in_end);
    CHECK(out_i == out_end);

    SECTION("topological sort") {
      vector<int> top_sort = topological_sort(dpag);
      int V = boost::num_vertices(dpag);
      CHECK(top_sort.size() == V);

      CHECK(top_sort[0] == 0);
      CHECK(top_sort[1] == 1);
      // TODO:: cannot check with complex expressions
      CHECK(0);
      // CHECK(top_sort[2] == 2 || top_sort[2] == 3);
      // CHECK(top_sort[3] == 2 || top_sort[3] == 3);
    }
  }

  SECTION("Grid") {
    CHECK(max_indegree(grid) == 2);
    CHECK(max_outdegree(grid) == 2);

    VertexId vertex_id = boost::get(boost::vertex_index, grid);
    EdgeId edge_id = boost::get(boost::edge_index, grid);

    Vertex_d v = boost::vertex(0, grid);
    boost::tie(out_i, out_end)=boost::out_edges(v, grid);
    boost::tie(in_i, in_end)=boost::in_edges(v, grid);

    v = boost::vertex(0, grid);
    boost::tie(out_i, out_end)=boost::out_edges(v, grid);
    boost::tie(in_i, in_end)=boost::in_edges(v, grid);
    CHECK(in_i == in_end);
    CHECK(boost::target(*out_i, grid) == 1);
    CHECK(edge_id[*out_i] == 0);
    CHECK(boost::target(*(++out_i), grid) == 10);
    CHECK(edge_id[*out_i] == 1);
    CHECK(++out_i == out_end);

    v = boost::vertex(9, grid);
    boost::tie(out_i, out_end)=boost::out_edges(v, grid);
    boost::tie(in_i, in_end)=boost::in_edges(v, grid);
    CHECK(boost::source(*in_i, grid) == 8);
    CHECK(++in_i == in_end);
    CHECK(boost::target(*out_i, grid) == 19);
    CHECK(edge_id[*out_i] == 0);
    CHECK(++out_i == out_end);

    v = boost::vertex(14, grid);
    boost::tie(out_i, out_end)=boost::out_edges(v, grid);
    boost::tie(in_i, in_end)=boost::in_edges(v, grid);
    CHECK(boost::source(*in_i, grid) == 4);
    CHECK(boost::source(*(++in_i), grid) == 13);
    CHECK(++in_i == in_end);
    CHECK(boost::target(*out_i, grid) == 15);
    CHECK(edge_id[*out_i] == 0);
    CHECK(boost::target(*(++out_i), grid) == 24);
    CHECK(edge_id[*out_i] == 1);
    CHECK(++out_i == out_end);

    SECTION("topological sort") {
      vector<int> top_sort = topological_sort(grid);

      CHECK(top_sort.size() == N*N);
      CHECK(top_sort[0] == 0);
      CHECK(top_sort[N*N-1] == N*N-1);

      // TODO: check other relative orders
      CHECK(0);
    }
  }
}
<|endoftext|>


<commit_before>#include <cppcutter.h>
#include "tuishogi.cpp"

namespace tuishogi {

void
test_showState(void)
{
  // Arrange
  using namespace osl;
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI *  *  *  *  * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 *  *  *  *  *  *  *  *  * \n\
P5 *  *  *  *  *  *  *  *  * \n\
P6 *  *  *  *  *  *  *  *  * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA *  *  *  *  * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";

  // Act
  showState(state);

  std::cout << std::flush;
  std::cout.rdbuf(std_out);

  // TODO assert it as a std::string
  std::string str = string_out.str();
  int len = str.length();
  char* actual = new char[len+1];
  memcpy(actual, str.c_str(), len+1);

  // Assert
  cut_assert_equal_string(expected, actual);
}

void
test_isMated(void)
{
  using namespace osl;
  NumEffectState state((SimpleState(HIRATE)));
  bool mated = isMated(state);
  cut_assert_false(mated);
}

}  // namespace tuishogi
<commit_msg>Simplify code of type conversion<commit_after>#include <cppcutter.h>
#include "tuishogi.cpp"

namespace tuishogi {

void
test_showState(void)
{
  // Arrange
  using namespace osl;
  std::stringbuf  string_out;
  std::streambuf* std_out = std::cout.rdbuf(&string_out);
  NumEffectState state((SimpleState(HIRATE)));
  const char* expected = "\
P1-KY-KE-GI-KI-OU-KI-GI-KE-KY\n\
P2 * -HI *  *  *  *  * -KA * \n\
P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\
P4 *  *  *  *  *  *  *  *  * \n\
P5 *  *  *  *  *  *  *  *  * \n\
P6 *  *  *  *  *  *  *  *  * \n\
P7+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\
P8 * +KA *  *  *  *  * +HI * \n\
P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\
+\n\
\n";

  // Act
  showState(state);

  std::cout << std::flush;
  std::cout.rdbuf(std_out);

  // TODO assert it as a std::string
  std::string str = string_out.str();
  const char* actual = str.c_str();

  // Assert
  cut_assert_equal_string(expected, actual);
}

void
test_isMated(void)
{
  using namespace osl;
  NumEffectState state((SimpleState(HIRATE)));
  bool mated = isMated(state);
  cut_assert_false(mated);
}

}  // namespace tuishogi
<|endoftext|>


<commit_before>// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License

#include "../src/collider.h"

#include "catch.hpp"
#include "util.h"

#include <iostream>

#include "../src/nucleus.h"

using namespace trento;

TEST_CASE( "collider" ) {
  constexpr auto N = 5;

  auto var_map = make_var_map({
    {"number-events", N},
    {"quiet", false},
    {"random-seed", static_cast<int64_t>(-1)},
    {"projectile", std::vector<std::string>{"Pb", "Pb"}},
    {"b-min", 0.},
    {"b-max", -1.},
    {"normalization", 1.},
    {"reduced-thickness", 0.},
    {"grid-max", 9.},
    {"grid-step", 0.3},
    {"fluctuation", 1.},
    {"cross-section", 6.4},
    {"nucleon-width", 0.5},
    {"nucleon-min-dist", 0.},
  });

  std::vector<int> nevent, npart;
  std::vector<double> impact, mult;

  // run collider normally and save output
  {
    capture_stdout capture;

    Collider collider{var_map};
    collider.run_events();

    std::string line;
    while (std::getline(capture.stream, line)) {
      nevent.push_back(0);
      impact.push_back(0);
      npart.push_back(0);
      mult.push_back(0);
      std::istringstream(line) >> nevent.back()
                               >> impact.back()
                               >> npart.back()
                               >> mult.back();
    }
  }

  // event numbers should be an integer sequence from zero
  std::vector<int> sequence(N);
  std::iota(sequence.begin(), sequence.end(), 0);
  CHECK( nevent == sequence );

  // verify impact parameters are within min-bias range
  auto impact_max = 2*Nucleus::create("Pb")->radius() + 6*.5;
  CHECK( impact >= std::vector<double>(N, 0.) );
  CHECK( impact <= std::vector<double>(N, impact_max) );

  // verify all events have at least 2 participants and at most 416 for PbPb
  CHECK( npart >= std::vector<int>(N, 2) );
  CHECK( npart <= std::vector<int>(N, 416) );

  // nonzero multiplicity
  CHECK( mult >= std::vector<double>(N, 0.) );
}

TEST_CASE( "fixed impact parameter" ) {
  constexpr auto N = 5;
  constexpr auto bfixed = 4.;

  auto var_map = make_var_map({
    {"number-events", N},
    {"quiet", false},
    {"random-seed", static_cast<int64_t>(-1)},
    {"projectile", std::vector<std::string>{"Au", "Au"}},
    {"b-min", bfixed},
    {"b-max", bfixed},
    {"normalization", 1.},
    {"reduced-thickness", 0.},
    {"grid-max", 9.},
    {"grid-step", 0.3},
    {"fluctuation", 1.},
    {"cross-section", 6.4},
    {"nucleon-width", 0.5},
    {"nucleon-min-dist", 0.2},
  });

  std::vector<double> impact;

  {
    Collider collider{var_map};

    capture_stdout capture;
    collider.run_events();

    std::string line;
    while (std::getline(capture.stream, line)) {
      double x;
      std::istringstream(line) >> x >> x;
      impact.push_back(x);
    }
  }

  // all events have the specified impact parameter
  CHECK( std::all_of(impact.cbegin(), impact.cend(),
    [&bfixed](double b) { return b == Approx(bfixed); }) );
}

TEST_CASE( "random seed" ) {
  std::vector<std::string> output(5);

  // run several collider batches with the same seed
  std::generate(output.begin(), output.end(),
    []() {
      Collider collider{make_var_map({
        {"number-events", 3},
        {"quiet", false},
        {"random-seed", static_cast<int64_t>(2308470)},
        {"projectile", std::vector<std::string>{"p", "U"}},
        {"b-min", 0.},
        {"b-max", -1.},
        {"normalization", 1.},
        {"reduced-thickness", 0.},
        {"grid-max", 9.},
        {"grid-step", 0.3},
        {"fluctuation", 1.},
        {"cross-section", 6.4},
        {"nucleon-width", 0.5},
        {"nucleon-min-dist", 0.4},
      })};

      capture_stdout capture;
      collider.run_events();

      return capture.stream.str();
    });

  // all collider batches are identical
  CHECK( std::all_of(output.cbegin(), output.cend(),
    [&output](const std::string& s) { return s == output.front(); }) );
}
<commit_msg>Use a non-deterministic seed in random seed test.<commit_after>// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License

#include "../src/collider.h"

#include "catch.hpp"
#include "util.h"

#include <iostream>

#include "../src/nucleus.h"

using namespace trento;

TEST_CASE( "collider" ) {
  constexpr auto N = 5;

  auto var_map = make_var_map({
    {"number-events", N},
    {"quiet", false},
    {"random-seed", static_cast<int64_t>(-1)},
    {"projectile", std::vector<std::string>{"Pb", "Pb"}},
    {"b-min", 0.},
    {"b-max", -1.},
    {"normalization", 1.},
    {"reduced-thickness", 0.},
    {"grid-max", 9.},
    {"grid-step", 0.3},
    {"fluctuation", 1.},
    {"cross-section", 6.4},
    {"nucleon-width", 0.5},
    {"nucleon-min-dist", 0.},
  });

  std::vector<int> nevent, npart;
  std::vector<double> impact, mult;

  // run collider normally and save output
  {
    capture_stdout capture;

    Collider collider{var_map};
    collider.run_events();

    std::string line;
    while (std::getline(capture.stream, line)) {
      nevent.push_back(0);
      impact.push_back(0);
      npart.push_back(0);
      mult.push_back(0);
      std::istringstream(line) >> nevent.back()
                               >> impact.back()
                               >> npart.back()
                               >> mult.back();
    }
  }

  // event numbers should be an integer sequence from zero
  std::vector<int> sequence(N);
  std::iota(sequence.begin(), sequence.end(), 0);
  CHECK( nevent == sequence );

  // verify impact parameters are within min-bias range
  auto impact_max = 2*Nucleus::create("Pb")->radius() + 6*.5;
  CHECK( impact >= std::vector<double>(N, 0.) );
  CHECK( impact <= std::vector<double>(N, impact_max) );

  // verify all events have at least 2 participants and at most 416 for PbPb
  CHECK( npart >= std::vector<int>(N, 2) );
  CHECK( npart <= std::vector<int>(N, 416) );

  // nonzero multiplicity
  CHECK( mult >= std::vector<double>(N, 0.) );
}

TEST_CASE( "fixed impact parameter" ) {
  constexpr auto N = 5;
  constexpr auto bfixed = 4.;

  auto var_map = make_var_map({
    {"number-events", N},
    {"quiet", false},
    {"random-seed", static_cast<int64_t>(-1)},
    {"projectile", std::vector<std::string>{"Au", "Au"}},
    {"b-min", bfixed},
    {"b-max", bfixed},
    {"normalization", 1.},
    {"reduced-thickness", 0.},
    {"grid-max", 9.},
    {"grid-step", 0.3},
    {"fluctuation", 1.},
    {"cross-section", 6.4},
    {"nucleon-width", 0.5},
    {"nucleon-min-dist", 0.2},
  });

  std::vector<double> impact;

  {
    Collider collider{var_map};

    capture_stdout capture;
    collider.run_events();

    std::string line;
    while (std::getline(capture.stream, line)) {
      double x;
      std::istringstream(line) >> x >> x;
      impact.push_back(x);
    }
  }

  // all events have the specified impact parameter
  CHECK( std::all_of(impact.cbegin(), impact.cend(),
    [&bfixed](double b) { return b == Approx(bfixed); }) );
}

TEST_CASE( "random seed" ) {
  std::vector<std::string> output(5);

  const auto seed = static_cast<int64_t>(std::random_device{}());

  // run several collider batches with the same seed
  std::generate(output.begin(), output.end(),
    [&seed]() {
      Collider collider{make_var_map({
        {"number-events", 3},
        {"quiet", false},
        {"random-seed", seed},
        {"projectile", std::vector<std::string>{"p", "U"}},
        {"b-min", 0.},
        {"b-max", -1.},
        {"normalization", 1.},
        {"reduced-thickness", 0.},
        {"grid-max", 9.},
        {"grid-step", 0.3},
        {"fluctuation", 1.},
        {"cross-section", 6.4},
        {"nucleon-width", 0.5},
        {"nucleon-min-dist", 0.4},
      })};

      capture_stdout capture;
      collider.run_events();

      return capture.stream.str();
    });

  // all collider batches are identical
  CHECK( std::all_of(output.cbegin(), output.cend(),
    [&output](const std::string& s) { return s == output.front(); }) );
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2015, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "test.hpp"
#include "libtorrent/ip_voter.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/random.hpp"
#include "setup_transfer.hpp" // for rand_v4

using namespace libtorrent;

// test the case where every time we get a new IP. Make sure
// we don't flap
void test_random()
{
	ip_voter ipv;

	bool new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
	TEST_CHECK(new_ip);
	for (int i = 0; i < 1000; ++i)
	{
		new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
		TEST_CHECK(!new_ip);
	}
}

void test_two_ips()
{
	ip_voter ipv;

	address_v4 addr1(address_v4::from_string("51.1.1.1"));
	address_v4 addr2(address_v4::from_string("53.3.3.3"));

	// addr1 is the first address we see, which is the one we pick. Even though
	// we'll have as many votes for addr2, we shouldn't flap, since addr2 never
	// gets an overwhelming majority.
	bool new_ip = ipv.cast_vote(addr1, 1, rand_v4());
	TEST_CHECK(new_ip);
	for (int i = 0; i < 1000; ++i)
	{
		fprintf(stderr, "%d\n", i);
		new_ip = ipv.cast_vote(addr2, 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(addr1, 1, rand_v4());
		TEST_CHECK(!new_ip);

		TEST_CHECK(ipv.external_address() == addr1);
	}
}

void test_one_ip()
{
	ip_voter ipv;

	address_v4 addr1(address_v4::from_string("51.1.1.1"));
	address_v4 addr2(address_v4::from_string("53.3.3.3"));

	bool new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
	TEST_CHECK(new_ip);
	bool switched_ip = false;
	for (int i = 0; i < 1000; ++i)
	{
		new_ip = ipv.cast_vote(addr2, 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(addr1, 1, rand_v4());
		if (new_ip) switched_ip = true;
		new_ip = ipv.cast_vote(addr1, 1, rand_v4());
		if (new_ip) switched_ip = true;

		if (switched_ip)
		{
			TEST_CHECK(ipv.external_address() == addr1);
		}
	}
	TEST_CHECK(switched_ip);
	TEST_CHECK(ipv.external_address() == addr1);
}

int test_main()
{
	test_random();
	test_two_ips();
	test_one_ip();
	return 0;
}

<commit_msg>remove test print<commit_after>/*

Copyright (c) 2015, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "test.hpp"
#include "libtorrent/ip_voter.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/random.hpp"
#include "setup_transfer.hpp" // for rand_v4

using namespace libtorrent;

// test the case where every time we get a new IP. Make sure
// we don't flap
void test_random()
{
	ip_voter ipv;

	bool new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
	TEST_CHECK(new_ip);
	for (int i = 0; i < 1000; ++i)
	{
		new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
		TEST_CHECK(!new_ip);
	}
}

void test_two_ips()
{
	ip_voter ipv;

	address_v4 addr1(address_v4::from_string("51.1.1.1"));
	address_v4 addr2(address_v4::from_string("53.3.3.3"));

	// addr1 is the first address we see, which is the one we pick. Even though
	// we'll have as many votes for addr2, we shouldn't flap, since addr2 never
	// gets an overwhelming majority.
	bool new_ip = ipv.cast_vote(addr1, 1, rand_v4());
	TEST_CHECK(new_ip);
	for (int i = 0; i < 1000; ++i)
	{
		new_ip = ipv.cast_vote(addr2, 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(addr1, 1, rand_v4());
		TEST_CHECK(!new_ip);

		TEST_CHECK(ipv.external_address() == addr1);
	}
}

void test_one_ip()
{
	ip_voter ipv;

	address_v4 addr1(address_v4::from_string("51.1.1.1"));
	address_v4 addr2(address_v4::from_string("53.3.3.3"));

	bool new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
	TEST_CHECK(new_ip);
	bool switched_ip = false;
	for (int i = 0; i < 1000; ++i)
	{
		new_ip = ipv.cast_vote(addr2, 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(rand_v4(), 1, rand_v4());
		TEST_CHECK(!new_ip);
		new_ip = ipv.cast_vote(addr1, 1, rand_v4());
		if (new_ip) switched_ip = true;
		new_ip = ipv.cast_vote(addr1, 1, rand_v4());
		if (new_ip) switched_ip = true;

		if (switched_ip)
		{
			TEST_CHECK(ipv.external_address() == addr1);
		}
	}
	TEST_CHECK(switched_ip);
	TEST_CHECK(ipv.external_address() == addr1);
}

int test_main()
{
	test_random();
	test_two_ips();
	test_one_ip();
	return 0;
}

<|endoftext|>


<commit_before>/*******************************************************************************
 * test/test_template.cpp
 *
 * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
 * Copyright (C) 2017 Marvin Löbel <loebel.marvin@gmail.com>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <gtest/gtest.h>
#include "test/util.hpp"

#include "benchmark/algorithm.hpp"
#include "benchmark/file_util.hpp"
#include "util/common.hpp"
#include "util/debug.hpp"

TEST(wavelet_construction, smoketest) {
  auto& algo_list = algorithm_list::get_algorithm_list();
  for (const auto& a : algo_list) {
    if (a->word_width() == 1) {
      test::roundtrip_batch([&](const std::string& s){
        auto vec = std::vector<uint8_t>(s.begin(), s.end());
        uint64_t levels = no_reduction_alphabet(vec);
        auto bvz = a->compute_bitvector(&vec, vec.size() , levels);
        if (a->is_tree()) {
          auto decoded_s = decode_wt(bvz.raw_bvs(), vec.size());
          ASSERT_EQ(s, decoded_s) << "Failure at " << a->name();
        } else {
          auto decoded_s = decode_wm(bvz.raw_bvs(), bvz.raw_zeros(), vec.size());
          ASSERT_EQ(s, decoded_s) << "Failure at " << a->name();
        }
      });
    }
  }
}

/******************************************************************************/
<commit_msg>Show which algorithms are tested<commit_after>/*******************************************************************************
 * test/test_template.cpp
 *
 * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
 * Copyright (C) 2017 Marvin Löbel <loebel.marvin@gmail.com>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <gtest/gtest.h>
#include "test/util.hpp"

#include "benchmark/algorithm.hpp"
#include "benchmark/file_util.hpp"
#include "util/common.hpp"
#include "util/debug.hpp"

TEST(wavelet_construction, smoketest) {
  auto& algo_list = algorithm_list::get_algorithm_list();
  for (const auto& a : algo_list) {
    if (a->word_width() == 1) {
      a->print_info();
      test::roundtrip_batch([&](const std::string& s){
        auto vec = std::vector<uint8_t>(s.begin(), s.end());
        uint64_t levels = no_reduction_alphabet(vec);
        auto bvz = a->compute_bitvector(&vec, vec.size() , levels);
        if (a->is_tree()) {
          auto decoded_s = decode_wt(bvz.raw_bvs(), vec.size());
          ASSERT_EQ(s, decoded_s) << "Failure at " << a->name();
        } else {
          auto decoded_s = decode_wm(bvz.raw_bvs(), bvz.raw_zeros(), vec.size());
          ASSERT_EQ(s, decoded_s) << "Failure at " << a->name();
        }
      });
    }
  }
}

/******************************************************************************/
<|endoftext|>