<commit_before>// TestValues.cpp : Test XML encoding and decoding of XmlRpcValues.

#include <stdlib.h>

#include "XmlRpcValue.h"

#include <assert.h>
#include <iostream>

using namespace XmlRpc;

void testBoolean()
{
  XmlRpcValue booleanFalse(false);
  XmlRpcValue booleanTrue(true);
  int offset = 0;
  XmlRpcValue booleanFalseXml("<value><boolean>0</boolean></value>", &offset);
  offset = 0;
  XmlRpcValue booleanTrueXml("<value><boolean>1</boolean></value>", &offset);
  assert(booleanFalse != booleanTrue);
  assert(booleanFalse == booleanFalseXml);
  assert(booleanFalse != booleanTrueXml);

  if (bool(booleanFalse))
    assert(false);

  if ( ! bool(booleanTrue))
    assert(false);
}

// Int
void testInt()
{
  XmlRpcValue int0(0);
  XmlRpcValue int1(1);
  XmlRpcValue int10(10);
  XmlRpcValue int_1(-1);
  int offset = 0;
  XmlRpcValue int0Xml("<value><int>0</int></value>", &offset);
  offset = 0;
  XmlRpcValue int9Xml("<value><i4>9</i4></value>", &offset);
  assert(int0 == int0Xml);
  assert(int(int10) - int(int1) == int(int9Xml));
  assert(9 == int(int9Xml));
  assert(int(int10) + int(int_1) == int(int9Xml));
}

void testDouble()
{
  // Double
  XmlRpcValue d(43.7);
  int offset = 0;
  XmlRpcValue dXml("<value><double>56.3</double></value>", &offset);
  assert(double(d) + double(dXml) == 100.0);  // questionable practice...
}

void testString()
{
  // String
  XmlRpcValue s("Now is the time <&");
  char csxml[] = "<value><string>Now is the time <&</string></value>";
  std::string ssxml = csxml;
  int offset = 0;
  XmlRpcValue vscXml(csxml, &offset);
  offset = 0;
  XmlRpcValue vssXml(ssxml, &offset);
  assert(s == vscXml);
  assert(s == vssXml);
  offset = 0;
  XmlRpcValue fromXml(vssXml.toXml(), &offset);
  assert(s == fromXml);

  // Empty or blank strings with no <string> tags
  std::string emptyStringXml("<value></value>");
  offset = 0;
  XmlRpcValue emptyStringVal1(emptyStringXml, &offset);
  XmlRpcValue emptyStringVal2("");
  assert(emptyStringVal1 == emptyStringVal2);

  emptyStringXml = "<value>  </value>";
  offset = 0;
  XmlRpcValue blankStringVal(emptyStringXml, &offset);
  assert(std::string(blankStringVal) == "  ");
}

void testDateTime()
{
  // DateTime
  int offset = 0;
  XmlRpcValue dateTime("<value><dateTime.iso8601>19040101T03:12:35</dateTime.iso8601></value>", &offset);
  struct tm &t = dateTime;
  assert(t.tm_year == (1904 - 1900)&& t.tm_min == 12);
}

void testArray(XmlRpcValue const& d)
{
  // Array
  XmlRpcValue a;
  a.setSize(4);
  a[0] = 1;
  a[1] = std::string("two");
  a[2] = 43.7;
  a[3] = "four";
  assert(int(a[0]) == 1);
  assert(a[2] == d);

  char csaXml[] =
    "<value><array>\n"
    "  <data>\n"
    "    <value><i4>1</i4></value> \n"
    "    <value> <string>two</string></value>\n"
    "    <value><double>43.7</double></value>\n"
    "    <value>four</value>\n"
    "  </data>\n"
    "</array></value>";

  int offset = 0;
  XmlRpcValue aXml(csaXml, &offset);
  assert(a == aXml);
}

void testStruct()
{
  // Struct
  XmlRpcValue struct1;
  struct1["i4"] = 1;
  struct1["str"] = "two";
  struct1["d"] = 43.7;

  XmlRpcValue a;
  a.setSize(4);
  a[0] = 1;
  a[1] = std::string("two");
  a[2] = 43.7;
  a[3] = "four";

  assert(struct1["d"] == a[2]);

  char csStructXml[] =
    "<value><struct>\n"
    "  <member>\n"
    "    <name>i4</name> \n"
    "    <value><i4>1</i4></value> \n"
    "  </member>\n"
    "  <member>\n"
    "    <name>d</name> \n"
    "    <value><double>43.7</double></value>\n"
    "  </member>\n"
    "  <member>\n"
    "    <name>str</name> \n"
    "    <value> <string>two</string></value>\n"
    "  </member>\n"
    "</struct></value>";

  int offset = 0;
  XmlRpcValue structXml(csStructXml, &offset);
  assert(struct1 == structXml);

  XmlRpcValue astruct;
  astruct["array"] = a;
  assert(astruct["array"][2] == struct1["d"]);

  for (int i=0; i<10; i++) {
    XmlRpcValue Event;
    Event["Name"] = "string";

    Event.clear();

    const int NELMTS = 100;
    int ii;

    for (ii=0; ii< NELMTS; ++ii) {
      char buf[40];
      sprintf(buf,"%d", ii);
      Event[std::string(buf)] = buf;
    }

    Event.clear();

    for (ii=0; ii< NELMTS; ++ii) {
      char buf[40];
      sprintf(buf,"%d", ii);
      if (ii != NELMTS/2)
        Event[std::string(buf)] = ii;
      else
        for (int jj=0; jj< NELMTS; ++jj) {
          char bufj[40];
          sprintf(bufj,"%d", jj);
          Event[std::string(buf)][std::string(bufj)] = bufj;
        }
    }

    for (ii=0; ii< NELMTS; ++ii) {
      char buf[40];
      sprintf(buf,"%d", ii);
      if (ii != NELMTS/2)
        assert(Event[std::string(buf)] == XmlRpcValue(ii));
      else
        assert(Event[std::string(buf)].size() == NELMTS);
    }
  }
}

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

  testInt();

  testDouble();

  testString();

  testDateTime();

  testArray(43.7);

  testStruct();

  return 0;
}
<commit_msg>minor tweak for gcc 4.6<commit_after>// TestValues.cpp : Test XML encoding and decoding of XmlRpcValues.

#include <cstdlib>
#include <cstdio>

#include "XmlRpcValue.h"

#include <cassert>
#include <iostream>

using namespace XmlRpc;

void testBoolean()
{
  XmlRpcValue booleanFalse(false);
  XmlRpcValue booleanTrue(true);
  int offset = 0;
  XmlRpcValue booleanFalseXml("<value><boolean>0</boolean></value>", &offset);
  offset = 0;
  XmlRpcValue booleanTrueXml("<value><boolean>1</boolean></value>", &offset);
  assert(booleanFalse != booleanTrue);
  assert(booleanFalse == booleanFalseXml);
  assert(booleanFalse != booleanTrueXml);

  if (bool(booleanFalse))
    assert(false);

  if ( ! bool(booleanTrue))
    assert(false);
}

// Int
void testInt()
{
  XmlRpcValue int0(0);
  XmlRpcValue int1(1);
  XmlRpcValue int10(10);
  XmlRpcValue int_1(-1);
  int offset = 0;
  XmlRpcValue int0Xml("<value><int>0</int></value>", &offset);
  offset = 0;
  XmlRpcValue int9Xml("<value><i4>9</i4></value>", &offset);
  assert(int0 == int0Xml);
  assert(int(int10) - int(int1) == int(int9Xml));
  assert(9 == int(int9Xml));
  assert(int(int10) + int(int_1) == int(int9Xml));
}

void testDouble()
{
  // Double
  XmlRpcValue d(43.7);
  int offset = 0;
  XmlRpcValue dXml("<value><double>56.3</double></value>", &offset);
  assert(double(d) + double(dXml) == 100.0);  // questionable practice...
}

void testString()
{
  // String
  XmlRpcValue s("Now is the time <&");
  char csxml[] = "<value><string>Now is the time <&</string></value>";
  std::string ssxml = csxml;
  int offset = 0;
  XmlRpcValue vscXml(csxml, &offset);
  offset = 0;
  XmlRpcValue vssXml(ssxml, &offset);
  assert(s == vscXml);
  assert(s == vssXml);
  offset = 0;
  XmlRpcValue fromXml(vssXml.toXml(), &offset);
  assert(s == fromXml);

  // Empty or blank strings with no <string> tags
  std::string emptyStringXml("<value></value>");
  offset = 0;
  XmlRpcValue emptyStringVal1(emptyStringXml, &offset);
  XmlRpcValue emptyStringVal2("");
  assert(emptyStringVal1 == emptyStringVal2);

  emptyStringXml = "<value>  </value>";
  offset = 0;
  XmlRpcValue blankStringVal(emptyStringXml, &offset);
  assert(std::string(blankStringVal) == "  ");
}

void testDateTime()
{
  // DateTime
  int offset = 0;
  XmlRpcValue dateTime("<value><dateTime.iso8601>19040101T03:12:35</dateTime.iso8601></value>", &offset);
  struct tm &t = dateTime;
  assert(t.tm_year == (1904 - 1900)&& t.tm_min == 12);
}

void testArray(XmlRpcValue const& d)
{
  // Array
  XmlRpcValue a;
  a.setSize(4);
  a[0] = 1;
  a[1] = std::string("two");
  a[2] = 43.7;
  a[3] = "four";
  assert(int(a[0]) == 1);
  assert(a[2] == d);

  char csaXml[] =
    "<value><array>\n"
    "  <data>\n"
    "    <value><i4>1</i4></value> \n"
    "    <value> <string>two</string></value>\n"
    "    <value><double>43.7</double></value>\n"
    "    <value>four</value>\n"
    "  </data>\n"
    "</array></value>";

  int offset = 0;
  XmlRpcValue aXml(csaXml, &offset);
  assert(a == aXml);
}

void testStruct()
{
  // Struct
  XmlRpcValue struct1;
  struct1["i4"] = 1;
  struct1["str"] = "two";
  struct1["d"] = 43.7;

  XmlRpcValue a;
  a.setSize(4);
  a[0] = 1;
  a[1] = std::string("two");
  a[2] = 43.7;
  a[3] = "four";

  assert(struct1["d"] == a[2]);

  char csStructXml[] =
    "<value><struct>\n"
    "  <member>\n"
    "    <name>i4</name> \n"
    "    <value><i4>1</i4></value> \n"
    "  </member>\n"
    "  <member>\n"
    "    <name>d</name> \n"
    "    <value><double>43.7</double></value>\n"
    "  </member>\n"
    "  <member>\n"
    "    <name>str</name> \n"
    "    <value> <string>two</string></value>\n"
    "  </member>\n"
    "</struct></value>";

  int offset = 0;
  XmlRpcValue structXml(csStructXml, &offset);
  assert(struct1 == structXml);

  XmlRpcValue astruct;
  astruct["array"] = a;
  assert(astruct["array"][2] == struct1["d"]);

  for (int i=0; i<10; i++) {
    XmlRpcValue Event;
    Event["Name"] = "string";

    Event.clear();

    const int NELMTS = 100;
    int ii;

    for (ii=0; ii< NELMTS; ++ii) {
      char buf[40];
      sprintf(buf,"%d", ii);
      Event[std::string(buf)] = buf;
    }

    Event.clear();

    for (ii=0; ii< NELMTS; ++ii) {
      char buf[40];
      sprintf(buf,"%d", ii);
      if (ii != NELMTS/2)
        Event[std::string(buf)] = ii;
      else
        for (int jj=0; jj< NELMTS; ++jj) {
          char bufj[40];
          sprintf(bufj,"%d", jj);
          Event[std::string(buf)][std::string(bufj)] = bufj;
        }
    }

    for (ii=0; ii< NELMTS; ++ii) {
      char buf[40];
      sprintf(buf,"%d", ii);
      if (ii != NELMTS/2)
        assert(Event[std::string(buf)] == XmlRpcValue(ii));
      else
        assert(Event[std::string(buf)].size() == NELMTS);
    }
  }
}

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

  testInt();

  testDouble();

  testString();

  testDateTime();

  testArray(43.7);

  testStruct();

  return 0;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <gtest/internal/gtest-port.h>

#include "VM.h"
#include "Compiler.h"

class VMTest : public testing::Test {
public:
    VM *object;
protected:
    virtual void SetUp() {
        object = VM::instance();
        object->clear();
    }
};

TEST_F(VMTest, TestGetInstance) {
    VM *object2 = VM::instance();

    ASSERT_TRUE(NULL != object);
    ASSERT_TRUE(object == object2);
}

TEST_F(VMTest, TestRun) {
    Compiler *compiler = Compiler::instance();
    vector<Instruction*> insns = compiler->compile("aaaaagaa@a@g@aaa@ a@"); // 2 + 7 = 9

    testing::internal::CaptureStdout();
    object->run(insns);
    ASSERT_STREQ("9", testing::internal::GetCapturedStdout().c_str());
}

TEST_F(VMTest, TestPush) {
    object->push(10);
    ASSERT_EQ(10, object->top());
}

TEST_F(VMTest, TestSwap) {
    object->push(10);
    object->push(20);

    object->swap(0);

    ASSERT_EQ(10, object->top());
    object->pop();
    ASSERT_EQ(20, object->top());
}

TEST_F(VMTest, TestAdd) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->add(NULL);

    ASSERT_EQ(30, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestSub) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->sub(NULL);

    ASSERT_EQ(10, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestMul) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->mul(NULL);

    ASSERT_EQ(200, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestDiv) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->div(NULL);

    ASSERT_EQ(2, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestDiscard) {
    int p1 = 3;
    int p2 = 4;

    object->push(p1);
    object->push(p2);
    object->discard(NULL);

    ASSERT_NE(p2, object->top());
    ASSERT_EQ(p1, object->top());
}

TEST_F(VMTest, TestPop) {
    int p1 = 3;
    int p2 = 4;

    object->push(p1);
    object->push(p2);

    ASSERT_EQ(p2, object->pop());
    ASSERT_NE(p2, object->top());
    ASSERT_EQ(p1, object->pop());
}

TEST_F(VMTest, TestTop) {
    int p1 = 3;
    int p2 = 4;

    object->push(p1);
    object->push(p2);

    ASSERT_EQ(p2, object->top());
    ASSERT_EQ(p2, object->top());
    ASSERT_NE(p1, object->top());
}

TEST_F(VMTest, TestClear) {
    object->push(10);
    object->push(10);
    object->push(10);
    object->clear();

    ASSERT_EQ(0, object->size());
 }

TEST_F(VMTest, TestNum_Out) {
    object->push(20);

    testing::internal::CaptureStdout();
    object->num_out(NULL);
    ASSERT_STREQ("20", testing::internal::GetCapturedStdout().c_str());
}

TEST_F(VMTest, TestSlide) {
    int p1 = 1;
    int p2 = 2;
    int p3 = 3;
    int p4 = 4;
    int size;
    int slide = 3;

    object->push(p1);
    object->push(p2);
    object->push(p3);
    object->push(p4);
    size = object->size();

    object->slide(slide);

    ASSERT_EQ(p4, object->top());
    ASSERT_EQ(size - slide, object->size());
}
<commit_msg>dup() のテストを追加<commit_after>#include <gtest/gtest.h>
#include <gtest/internal/gtest-port.h>

#include "VM.h"
#include "Compiler.h"

class VMTest : public testing::Test {
public:
    VM *object;
protected:
    virtual void SetUp() {
        object = VM::instance();
        object->clear();
    }
};

TEST_F(VMTest, TestGetInstance) {
    VM *object2 = VM::instance();

    ASSERT_TRUE(NULL != object);
    ASSERT_TRUE(object == object2);
}

TEST_F(VMTest, TestRun) {
    Compiler *compiler = Compiler::instance();
    vector<Instruction*> insns;

    // 2 + 7 = 9 を stdout
    insns = compiler->compile("aaaaagaa@a@g@aaa@ a@");
    testing::internal::CaptureStdout();
    object->run(insns);
    ASSERT_STREQ("9", testing::internal::GetCapturedStdout().c_str());

    // 11 * 23 = 253 を stdout
    insns = compiler->compile("aaa@aagaaa@aaag@aa @ a@");
    testing::internal::CaptureStdout();
    object->run(insns);
    ASSERT_STREQ("253", testing::internal::GetCapturedStdout().c_str());
}

TEST_F(VMTest, TestPush) {
    object->push(10);
    ASSERT_EQ(10, object->top());
}

TEST_F(VMTest, TestDup) {
    int p = 10;

    object->push(p);
    object->dup(NULL);

    ASSERT_EQ(p, object->top());
}

TEST_F(VMTest, TestSwap) {
    object->push(10);
    object->push(20);

    object->swap(0);

    ASSERT_EQ(10, object->top());
    object->pop();
    ASSERT_EQ(20, object->top());
}

TEST_F(VMTest, TestAdd) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->add(NULL);

    ASSERT_EQ(30, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestSub) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->sub(NULL);

    ASSERT_EQ(10, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestMul) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->mul(NULL);

    ASSERT_EQ(200, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestDiv) {
    int size = object->size();

    object->push(10);
    object->push(20);
    object->div(NULL);

    ASSERT_EQ(2, object->top());
    ASSERT_EQ(size + 1, object->size());
}

TEST_F(VMTest, TestDiscard) {
    int p1 = 3;
    int p2 = 4;

    object->push(p1);
    object->push(p2);
    object->discard(NULL);

    ASSERT_NE(p2, object->top());
    ASSERT_EQ(p1, object->top());
}

TEST_F(VMTest, TestPop) {
    int p1 = 3;
    int p2 = 4;

    object->push(p1);
    object->push(p2);

    ASSERT_EQ(p2, object->pop());
    ASSERT_NE(p2, object->top());
    ASSERT_EQ(p1, object->pop());
}

TEST_F(VMTest, TestTop) {
    int p1 = 3;
    int p2 = 4;

    object->push(p1);
    object->push(p2);

    ASSERT_EQ(p2, object->top());
    ASSERT_EQ(p2, object->top());
    ASSERT_NE(p1, object->top());
}

TEST_F(VMTest, TestClear) {
    object->push(10);
    object->push(10);
    object->push(10);
    object->clear();

    ASSERT_EQ(0, object->size());
 }

TEST_F(VMTest, TestNum_Out) {
    object->push(20);

    testing::internal::CaptureStdout();
    object->num_out(NULL);
    ASSERT_STREQ("20", testing::internal::GetCapturedStdout().c_str());
}

TEST_F(VMTest, TestSlide) {
    int p1 = 1;
    int p2 = 2;
    int p3 = 3;
    int p4 = 4;
    int size;
    int slide = 3;

    object->push(p1);
    object->push(p2);
    object->push(p3);
    object->push(p4);
    size = object->size();

    object->slide(slide);

    ASSERT_EQ(p4, object->top());
    ASSERT_EQ(size - slide, object->size());
}
<|endoftext|>


<commit_before>#include <client/clone.hpp>
#include <silicium/observable/for_each.hpp>
#include <silicium/observable/coroutine_generator.hpp>
#include <silicium/observable/function.hpp>
#include <silicium/observable/take.hpp>
#include <silicium/observable/ready_future.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/unordered_map.hpp>

namespace Si
{
	template <class T>
	struct is_optional : std::false_type
	{
	};

	template <class T>
	struct is_optional<boost::optional<T>> : std::true_type
	{
	};

	template <class Optional, class Transformation, class = typename std::enable_if<is_optional<typename std::decay<Optional>::type>::value, void>::type>
	auto map(Optional &&value, Transformation &&transform)
		-> boost::optional<decltype(std::forward<Transformation>(transform)(*std::forward<Optional>(value)))>
	{
		if (value)
		{
			return std::forward<Transformation>(transform)(*std::forward<Optional>(value));
		}
		return boost::none;
	}
}

namespace
{
	template <class To, class From>
	To sign_cast(From from)
	{
		BOOST_STATIC_ASSERT(std::is_integral<To>::value);
		BOOST_STATIC_ASSERT(std::is_integral<From>::value);
		BOOST_STATIC_ASSERT(sizeof(To) == sizeof(From));
		return static_cast<To>(from);
	}

	struct writeable_file : fileserver::writeable_file
	{
		virtual boost::system::error_code seek(fileserver::file_offset destination) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(destination);
			BOOST_FAIL("unexpected seek");
			return boost::system::error_code();
		}

		virtual boost::system::error_code write(Si::memory_range const &written) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(written);
			return boost::system::error_code();
		}
	};

	struct readonly_directory_manipulator : fileserver::directory_manipulator
	{
		explicit readonly_directory_manipulator(boost::filesystem::path location)
			: location(std::move(location))
		{
		}

		virtual boost::system::error_code require_exists() SILICIUM_OVERRIDE
		{
			return {};
		}

		virtual std::unique_ptr<fileserver::directory_manipulator> edit_subdirectory(std::string const &name) SILICIUM_OVERRIDE
		{
			return Si::make_unique<readonly_directory_manipulator>(location / name);
		}

		virtual Si::error_or<std::unique_ptr<fileserver::writeable_file>> create_regular_file(std::string const &name) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(name);
			return boost::system::error_code(EACCES, boost::system::system_category());
		}

		virtual Si::error_or<fileserver::read_write_file> read_write_regular_file(std::string const &name) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(name);
			return boost::system::error_code(EACCES, boost::system::system_category());
		}

	private:

		boost::filesystem::path location;
	};

	struct file_service : fileserver::storage_reader
	{
		boost::unordered_map<fileserver::unknown_digest, std::shared_ptr<std::vector<char> const>> files;

		virtual Si::unique_observable<Si::error_or<fileserver::linear_file>> open(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE
		{
			auto it = files.find(name);
			if (it == files.end())
			{
				return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>(boost::system::error_code(fileserver::service_error::file_not_found))));
			}
			auto file = it->second;
			return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>(
				fileserver::linear_file{
					static_cast<fileserver::file_offset>(file->size()),
					Si::erase_unique(Si::take(Si::make_function_observable2([file]() -> Si::error_or<Si::memory_range>
					{
						return Si::make_memory_range(file->data(), file->data() + file->size());
					}), 1))
				}
			)));
		}

		virtual Si::unique_observable<Si::error_or<fileserver::file_offset>> size(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE
		{
			auto it = files.find(name);
			if (it == files.end())
			{
				return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(boost::system::error_code(fileserver::service_error::file_not_found))));
			}
			return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(it->second->size())));
		}
	};
}

BOOST_AUTO_TEST_CASE(client_clone_empty)
{
	fileserver::unknown_digest const root;
	readonly_directory_manipulator dir(".");
	boost::asio::io_service io;
	file_service service;
	service.files.insert(std::make_pair(root, Si::to_shared(std::vector<char>{'{', '}'})));
	bool has_finished = false;
	auto all = Si::for_each(fileserver::clone_directory(root, dir, service, io), [&has_finished](boost::system::error_code ec)
	{
		has_finished = true;
		BOOST_CHECK_EQUAL(boost::system::error_code(), ec);
	});
	all.start();
	io.run();
	BOOST_CHECK(has_finished);
}
<commit_msg>rename memory_storage_reader<commit_after>#include <client/clone.hpp>
#include <silicium/observable/for_each.hpp>
#include <silicium/observable/coroutine_generator.hpp>
#include <silicium/observable/function.hpp>
#include <silicium/observable/take.hpp>
#include <silicium/observable/ready_future.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/unordered_map.hpp>

namespace Si
{
	template <class T>
	struct is_optional : std::false_type
	{
	};

	template <class T>
	struct is_optional<boost::optional<T>> : std::true_type
	{
	};

	template <class Optional, class Transformation, class = typename std::enable_if<is_optional<typename std::decay<Optional>::type>::value, void>::type>
	auto map(Optional &&value, Transformation &&transform)
		-> boost::optional<decltype(std::forward<Transformation>(transform)(*std::forward<Optional>(value)))>
	{
		if (value)
		{
			return std::forward<Transformation>(transform)(*std::forward<Optional>(value));
		}
		return boost::none;
	}
}

namespace
{
	template <class To, class From>
	To sign_cast(From from)
	{
		BOOST_STATIC_ASSERT(std::is_integral<To>::value);
		BOOST_STATIC_ASSERT(std::is_integral<From>::value);
		BOOST_STATIC_ASSERT(sizeof(To) == sizeof(From));
		return static_cast<To>(from);
	}

	struct writeable_file : fileserver::writeable_file
	{
		virtual boost::system::error_code seek(fileserver::file_offset destination) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(destination);
			BOOST_FAIL("unexpected seek");
			return boost::system::error_code();
		}

		virtual boost::system::error_code write(Si::memory_range const &written) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(written);
			return boost::system::error_code();
		}
	};

	struct readonly_directory_manipulator : fileserver::directory_manipulator
	{
		explicit readonly_directory_manipulator(boost::filesystem::path location)
			: location(std::move(location))
		{
		}

		virtual boost::system::error_code require_exists() SILICIUM_OVERRIDE
		{
			return {};
		}

		virtual std::unique_ptr<fileserver::directory_manipulator> edit_subdirectory(std::string const &name) SILICIUM_OVERRIDE
		{
			return Si::make_unique<readonly_directory_manipulator>(location / name);
		}

		virtual Si::error_or<std::unique_ptr<fileserver::writeable_file>> create_regular_file(std::string const &name) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(name);
			return boost::system::error_code(EACCES, boost::system::system_category());
		}

		virtual Si::error_or<fileserver::read_write_file> read_write_regular_file(std::string const &name) SILICIUM_OVERRIDE
		{
			boost::ignore_unused_variable_warning(name);
			return boost::system::error_code(EACCES, boost::system::system_category());
		}

	private:

		boost::filesystem::path location;
	};

	struct memory_storage_reader : fileserver::storage_reader
	{
		boost::unordered_map<fileserver::unknown_digest, std::shared_ptr<std::vector<char> const>> files;

		virtual Si::unique_observable<Si::error_or<fileserver::linear_file>> open(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE
		{
			auto it = files.find(name);
			if (it == files.end())
			{
				return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>(boost::system::error_code(fileserver::service_error::file_not_found))));
			}
			auto file = it->second;
			return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::linear_file>(
				fileserver::linear_file{
					static_cast<fileserver::file_offset>(file->size()),
					Si::erase_unique(Si::take(Si::make_function_observable2([file]() -> Si::error_or<Si::memory_range>
					{
						return Si::make_memory_range(file->data(), file->data() + file->size());
					}), 1))
				}
			)));
		}

		virtual Si::unique_observable<Si::error_or<fileserver::file_offset>> size(fileserver::unknown_digest const &name) SILICIUM_OVERRIDE
		{
			auto it = files.find(name);
			if (it == files.end())
			{
				return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(boost::system::error_code(fileserver::service_error::file_not_found))));
			}
			return Si::erase_unique(Si::make_ready_future(Si::error_or<fileserver::file_offset>(it->second->size())));
		}
	};
}

BOOST_AUTO_TEST_CASE(client_clone_empty)
{
	fileserver::unknown_digest const root;
	readonly_directory_manipulator dir(".");
	boost::asio::io_service io;
	memory_storage_reader service;
	service.files.insert(std::make_pair(root, Si::to_shared(std::vector<char>{'{', '}'})));
	bool has_finished = false;
	auto all = Si::for_each(fileserver::clone_directory(root, dir, service, io), [&has_finished](boost::system::error_code ec)
	{
		has_finished = true;
		BOOST_CHECK_EQUAL(boost::system::error_code(), ec);
	});
	all.start();
	io.run();
	BOOST_CHECK(has_finished);
}
<|endoftext|>


<commit_before>#define GROUP_TEST(regex, anchor, input, n) \
    test_case(_FORMAT(regex, anchor, input)) { \
        re2::StringPiece g2[n]; \
        re2::StringPiece gj[n]; \
        if ( _RE2_RUN(_RE2(regex), input, anchor, g2, n) \
          != _R2J_RUN(_R2J(regex), input, anchor, gj, n)) return Result::Fail("invalid answer"); \
        for (size_t i = 0; i < n; i++) { \
            if (g2[i] != gj[i]) { \
                return Result::Fail( \
                    "group %zu incorrect\n" \
                    "    expected [%d] '%.*s'\n" \
                    "    matched  [%d] '%.*s'", i, g2[i].size(), g2[i].size(), g2[i].data(), \
                                                   gj[i].size(), gj[i].size(), gj[i].data()); \
            } \
        } \
    }

GROUP_TEST("Hello, (.*)!", ANCHOR_START, "Hello, World!", 2);
GROUP_TEST("([^ ]*?), (.*)", UNANCHORED, "Hi there, world!", 3);
GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+))", ANCHOR_BOTH, "0b00010", 6);
GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "0b00010", 6);
GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "30.5e+1j", 6);
<commit_msg>Add two more submatch extraction tests.<commit_after>#define GROUP_TEST(regex, anchor, input, n) \
    test_case(_FORMAT(regex, anchor, input)) { \
        re2::StringPiece g2[n]; \
        re2::StringPiece gj[n]; \
        if ( _RE2_RUN(_RE2(regex), input, anchor, g2, n) \
          != _R2J_RUN(_R2J(regex), input, anchor, gj, n)) return Result::Fail("invalid answer"); \
        for (size_t i = 0; i < n; i++) { \
            if (g2[i] != gj[i]) { \
                return Result::Fail( \
                    "group %zu incorrect\n" \
                    "    expected [%d] '%.*s'\n" \
                    "    matched  [%d] '%.*s'", i, g2[i].size(), g2[i].size(), g2[i].data(), \
                                                   gj[i].size(), gj[i].size(), gj[i].data()); \
            } \
        } \
    }

GROUP_TEST("Hello, (.*)!", ANCHOR_START, "Hello, World!", 2);
GROUP_TEST("([^ ]*?), (.*)", UNANCHORED, "Hi there, world!", 3);
GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+))", ANCHOR_BOTH, "0b00010", 6);
GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "0b00010", 6);
GROUP_TEST("([+-]?(?:(0b)[01]+|(0o)[0-7]+|(0x)[0-9a-f]+|[0-9]+((?:\\.[0-9]+)?(?:e[+-]?[0-9]+)?)(j)?))", ANCHOR_BOTH, "30.5e+1j", 6);
GROUP_TEST("((\\s+)|(\\w+))+",   ANCHOR_START, "submatch test", 4);
GROUP_TEST("(?:(\\s+)|(\\w+))+", ANCHOR_START, "submatch test", 4);
<|endoftext|>


<commit_before>#include <string.h>
#include <iostream.h>
#include <stdlib.h>
#include <string>
using namespace std;

int main()
{
	string SizeE;
	int SizeA, SizeB, SizeD, SizeC;

	cout << "The Breast Measurer v2.0" << endl << "by endura29@hotmail.com" << endl;
	cout << "Enter the Measurement (in inches) just below the breast: ";
	cin >> SizeA;
	cout << "Enter the Measurement (in inches) at the Nipple: ";
	cin >> SizeB;
	//SizeD = (SizeA + 5);
	//SizeC = (SizeB - SizeD);
	SizeC = SizeB - SizeA;

	//if (SizeD % 2)
	//	SizeD++;
	if (SizeC < 0) {
		cout << "\n" << "Now, that's less than a mouthful!!" << endl;
		return 0;
	}

	switch (SizeC)
	{
		case 0:
			SizeE = "AA";
			break;
		case 1:
			SizeE = "A";
			break;
		case 2:
			SizeE = "B";
			break;
		case 3:
			SizeE = "C";
			break;
		case 4:
			SizeE = "D";
			break;
		case 5:
			SizeE = "DD";
			break;
		case 6:
			SizeE = "F";
			break;
		case 7:
			SizeE = "G";
			break;
		case 8:
			SizeE = "H";
			break;
		case 9:
			SizeE = "I";
			break;
		default:
			cout << "Damn, that's a lotta boobs!" << endl;
			return 0;
	}

	cout << "Bra Size: " << SizeA << SizeE.c_str() << endl;

	return 0;
}
<commit_msg>Removed<commit_after><|endoftext|>


<commit_before>#include <silicium/config.hpp>
#include <silicium/bounded_int.hpp>
#include <silicium/variant.hpp>
#include <silicium/array_view.hpp>
#include <silicium/arithmetic/add.hpp>
#include <boost/test/unit_test.hpp>

namespace Si
{
	namespace m3
	{
		struct absorb
		{
		};

		template <class T>
		struct val
		{
			template <class... Args>
			explicit val(Args &&... args)
			    : m_is_set(true)
			{
				new (static_cast<void *>(&get())) T(std::forward<Args>(args)...);
			}

			~val() BOOST_NOEXCEPT
			{
				if (!m_is_set)
				{
					return;
				}
				get().~T();
			}

			val(val &&other) BOOST_NOEXCEPT : m_is_set(other.m_is_set)
			{
				if (m_is_set)
				{
					new (static_cast<void *>(&get())) T(absorb(), other.get());
					other.m_is_set = false;
				}
			}

			val &operator=(val &&other) BOOST_NOEXCEPT
			{
				if (m_is_set)
				{
					if (other.m_is_set)
					{
						get().~T();
						new (static_cast<void *>(&get())) T(absorb(), other.get());
						other.m_is_set = false;
					}
					else
					{
						get().~T();
						m_is_set = false;
					}
				}
				else
				{
					if (other.m_is_set)
					{
						new (static_cast<void *>(&get())) T(absorb(), other.get());
						other.m_is_set = false;
						m_is_set = true;
					}
					else
					{
						// nothing to do
					}
				}
				return *this;
			}

			void release() BOOST_NOEXCEPT
			{
				m_is_set = false;
			}

			T &require()
			{
				if (!m_is_set)
				{
					boost::throw_exception(std::logic_error("expected non-empty val"));
				}
				return get();
			}

		private:
			bool m_is_set;
			std::aligned_storage<sizeof(T), alignof(T)> m_storage;

			T &get()
			{
				return reinterpret_cast<T &>(reinterpret_cast<char &>(m_storage));
			}
		};

		template <class T, class Deleter>
		struct unique_ref : private Deleter
		{
			explicit unique_ref(T &ref, Deleter deleter) BOOST_NOEXCEPT : Deleter(deleter), m_ref(ref)
			{
			}

			unique_ref(val<unique_ref> &&other) BOOST_NOEXCEPT : unique_ref(absorb(), other.require())
			{
				other.release();
			}

			unique_ref(absorb, unique_ref const &other) BOOST_NOEXCEPT : Deleter(other), m_ref(other.m_ref)
			{
			}

			~unique_ref() BOOST_NOEXCEPT
			{
				Deleter::operator()(m_ref);
			}

			SILICIUM_DISABLE_COPY(unique_ref)

			T &ref() const BOOST_NOEXCEPT
			{
				return m_ref;
			}

		private:
			T &m_ref;
		};

		struct new_deleter
		{
			new_deleter() BOOST_NOEXCEPT
			{
			}

			template <class T>
			void operator()(T &deleted) const BOOST_NOEXCEPT
			{
				delete &deleted;
			}
		};

		struct malloc_deleter
		{
			malloc_deleter() BOOST_NOEXCEPT
			{
			}

			template <class T>
			void operator()(T &deleted) const BOOST_NOEXCEPT
			{
				std::free(&deleted);
			}
		};

		template <class T, class... Args>
		val<unique_ref<T, new_deleter>> make_unique(Args &&... args)
		{
			return val<unique_ref<T, new_deleter>>(*new T(std::forward<Args>(args)...), new_deleter());
		}

		template <class T>
		val<unique_ref<T, malloc_deleter>> allocate_array_storage(std::size_t length)
		{
			void *const storage = std::calloc(length, sizeof(T));
			if (!storage)
			{
				boost::throw_exception(std::bad_alloc());
			}
			return val<unique_ref<T, malloc_deleter>>(*static_cast<T *>(storage), malloc_deleter());
		}

		template <class T, class Length>
		struct dynamic_array
		{
			template <class ElementGenerator>
			dynamic_array(Length length, ElementGenerator &&generate_elements) BOOST_NOEXCEPT
			    : m_elements(allocate_array_storage<T>(length.value())),
			      m_length(length)
			{
				for (typename Length::value_type i = 0, c = m_length.value(); i < c; ++i)
				{
					new (static_cast<void *>((&m_elements.ref()) + i)) T(generate_elements());
				}
			}

			Length length() const BOOST_NOEXCEPT
			{
				return m_length;
			}

			array_view<T, Length> as_view() const BOOST_NOEXCEPT
			{
				return array_view<T, Length>(m_elements.ref(), length());
			}

		private:
			unique_ref<T, malloc_deleter> m_elements;
			Length m_length;
		};
	}
}

BOOST_AUTO_TEST_CASE(move3_vector_ref_emplace_back)
{
	typedef Si::bounded_int<std::size_t, 1, 2> length_type;
	Si::m3::dynamic_array<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const v(
	    length_type::literal<1>(), []()
	    {
		    return Si::m3::make_unique<int>(23);
		});
	BOOST_REQUIRE_EQUAL(length_type::literal<1>(), v.length());
	Si::array_view<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const range = v.as_view();
	BOOST_REQUIRE_EQUAL(length_type::literal<1>(), range.length());
	Si::m3::unique_ref<int, Si::m3::new_deleter> const &element = range[Si::literal<std::size_t, 0>()];
	BOOST_CHECK_EQUAL(element.ref(), 23);
}
<commit_msg>use aligned_storage correctly<commit_after>#include <silicium/config.hpp>
#include <silicium/bounded_int.hpp>
#include <silicium/variant.hpp>
#include <silicium/array_view.hpp>
#include <silicium/arithmetic/add.hpp>
#include <boost/test/unit_test.hpp>

namespace Si
{
	namespace m3
	{
		struct absorb
		{
		};

		template <class T>
		struct val
		{
			template <class... Args>
			explicit val(Args &&... args)
			    : m_is_set(true)
			{
				new (static_cast<void *>(&get())) T(std::forward<Args>(args)...);
			}

			~val() BOOST_NOEXCEPT
			{
				if (!m_is_set)
				{
					return;
				}
				get().~T();
			}

			val(val &&other) BOOST_NOEXCEPT : m_is_set(other.m_is_set)
			{
				if (m_is_set)
				{
					new (static_cast<void *>(&get())) T(absorb(), other.get());
					other.m_is_set = false;
				}
			}

			val &operator=(val &&other) BOOST_NOEXCEPT
			{
				if (m_is_set)
				{
					if (other.m_is_set)
					{
						get().~T();
						new (static_cast<void *>(&get())) T(absorb(), other.get());
						other.m_is_set = false;
					}
					else
					{
						get().~T();
						m_is_set = false;
					}
				}
				else
				{
					if (other.m_is_set)
					{
						new (static_cast<void *>(&get())) T(absorb(), other.get());
						other.m_is_set = false;
						m_is_set = true;
					}
					else
					{
						// nothing to do
					}
				}
				return *this;
			}

			void release() BOOST_NOEXCEPT
			{
				m_is_set = false;
			}

			T &require()
			{
				if (!m_is_set)
				{
					boost::throw_exception(std::logic_error("expected non-empty val"));
				}
				return get();
			}

		private:
			bool m_is_set;
			typename std::aligned_storage<sizeof(T), alignof(T)>::type m_storage;

			T &get()
			{
				return reinterpret_cast<T &>(reinterpret_cast<char &>(m_storage));
			}
		};

		template <class T, class Deleter>
		struct unique_ref : private Deleter
		{
			explicit unique_ref(T &ref, Deleter deleter) BOOST_NOEXCEPT : Deleter(deleter), m_ref(ref)
			{
			}

			unique_ref(val<unique_ref> &&other) BOOST_NOEXCEPT : unique_ref(absorb(), other.require())
			{
				other.release();
			}

			unique_ref(absorb, unique_ref const &other) BOOST_NOEXCEPT : Deleter(other), m_ref(other.m_ref)
			{
			}

			~unique_ref() BOOST_NOEXCEPT
			{
				Deleter::operator()(m_ref);
			}

			SILICIUM_DISABLE_COPY(unique_ref)

			T &ref() const BOOST_NOEXCEPT
			{
				return m_ref;
			}

		private:
			T &m_ref;
		};

		struct new_deleter
		{
			new_deleter() BOOST_NOEXCEPT
			{
			}

			template <class T>
			void operator()(T &deleted) const BOOST_NOEXCEPT
			{
				delete &deleted;
			}
		};

		struct malloc_deleter
		{
			malloc_deleter() BOOST_NOEXCEPT
			{
			}

			template <class T>
			void operator()(T &deleted) const BOOST_NOEXCEPT
			{
				std::free(&deleted);
			}
		};

		template <class T, class... Args>
		val<unique_ref<T, new_deleter>> make_unique(Args &&... args)
		{
			return val<unique_ref<T, new_deleter>>(*new T(std::forward<Args>(args)...), new_deleter());
		}

		template <class T>
		val<unique_ref<T, malloc_deleter>> allocate_array_storage(std::size_t length)
		{
			void *const storage = std::calloc(length, sizeof(T));
			if (!storage)
			{
				boost::throw_exception(std::bad_alloc());
			}
			return val<unique_ref<T, malloc_deleter>>(*static_cast<T *>(storage), malloc_deleter());
		}

		template <class T, class Length>
		struct dynamic_array
		{
			template <class ElementGenerator>
			dynamic_array(Length length, ElementGenerator &&generate_elements) BOOST_NOEXCEPT
			    : m_elements(allocate_array_storage<T>(length.value())),
			      m_length(length)
			{
				for (typename Length::value_type i = 0, c = m_length.value(); i < c; ++i)
				{
					new (static_cast<void *>((&m_elements.ref()) + i)) T(generate_elements());
				}
			}

			Length length() const BOOST_NOEXCEPT
			{
				return m_length;
			}

			array_view<T, Length> as_view() const BOOST_NOEXCEPT
			{
				return array_view<T, Length>(m_elements.ref(), length());
			}

		private:
			unique_ref<T, malloc_deleter> m_elements;
			Length m_length;
		};
	}
}

BOOST_AUTO_TEST_CASE(move3_vector_ref_emplace_back)
{
	typedef Si::bounded_int<std::size_t, 1, 2> length_type;
	Si::m3::dynamic_array<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const v(
	    length_type::literal<1>(), []()
	    {
		    return Si::m3::make_unique<int>(23);
		});
	BOOST_REQUIRE_EQUAL(length_type::literal<1>(), v.length());
	Si::array_view<Si::m3::unique_ref<int, Si::m3::new_deleter>, length_type> const range = v.as_view();
	BOOST_REQUIRE_EQUAL(length_type::literal<1>(), range.length());
	Si::m3::unique_ref<int, Si::m3::new_deleter> const &element = range[Si::literal<std::size_t, 0>()];
	BOOST_CHECK_EQUAL(element.ref(), 23);
}
<|endoftext|>


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

#include <cmake.h>
#include <iostream>
#include <stdlib.h>
#include <Context.h>
#include <Msg.h>
#include <test.h>

Context context;

////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
  UnitTest t (12);

  // Ensure environment has no influence.
  unsetenv ("TASKDATA");
  unsetenv ("TASKRC");

  Msg m;
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\n\n\n", "Msg::serialize '' --> '\\n\\n'");

  m.set ("name", "value");
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nname: value\n\n\n", "Msg::serialize 1 var");

  m.set ("foo", "bar");
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\n\n", "Msg::serialize 2 vars");

  m.setPayload ("payload");
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\npayload\n", "Msg::serialize 2 vars + payload");

  Msg m2;
  t.ok (m2.parse ("foo: bar\nname: value\n\npayload\n"), "Msg::parse ok");
  t.is (m2.get ("foo"),   "bar",       "Msg::get");
  t.is (m2.get ("name"),  "value",     "Msg::get");
  t.is (m2.getPayload (), "payload\n", "Msg::getPayload");

  Msg m3;
  t.ok (m3.parse ("foo:bar\nname:   value\n\npayload\n"), "Msg::parse ok");
  t.is (m3.get ("foo"),   "bar",       "Msg::get");
  t.is (m3.get ("name"),  "value",     "Msg::get");
  t.is (m3.getPayload (), "payload\n", "Msg::getPayload");
  return 0;
}

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

#include <cmake.h>
#include <Context.h>
#include <Msg.h>
#include <test.h>

Context context;

////////////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv)
{
  UnitTest t (12);

  Msg m;
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\n\n\n", "Msg::serialize '' --> '\\n\\n'");

  m.set ("name", "value");
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nname: value\n\n\n", "Msg::serialize 1 var");

  m.set ("foo", "bar");
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\n\n", "Msg::serialize 2 vars");

  m.setPayload ("payload");
  t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\npayload\n", "Msg::serialize 2 vars + payload");

  Msg m2;
  t.ok (m2.parse ("foo: bar\nname: value\n\npayload\n"),  "Msg::parse ok");
  t.is (m2.get ("foo"),   "bar",                          "Msg::get");
  t.is (m2.get ("name"),  "value",                        "Msg::get");
  t.is (m2.getPayload (), "payload\n",                    "Msg::getPayload");

  Msg m3;
  t.ok (m3.parse ("foo:bar\nname:   value\n\npayload\n"), "Msg::parse ok");
  t.is (m3.get ("foo"),   "bar",                          "Msg::get");
  t.is (m3.get ("name"),  "value",                        "Msg::get");
  t.is (m3.getPayload (), "payload\n",                    "Msg::getPayload");

  return 0;
}

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


<commit_before>#include "server_ws.hpp"
#include "client_ws.hpp"
#include <iostream>

using namespace std;
using namespace SimpleWeb;

class SocketServerTest : public SocketServerBase<WS> {
public:
    SocketServerTest() :
            SocketServerBase<WS>::SocketServerBase(8080, 1, 5, 300) {}

    void accept() {}

    bool parse_request_test() {
        std::shared_ptr<Connection> connection(new Connection(new WS(asio_io_service)));

        stringstream ss;
        ss << "GET /test/ HTTP/1.1\r\n";
        ss << "TestHeader: test\r\n";
        ss << "TestHeader2:test2\r\n";
        ss << "\r\n";

        parse_handshake(connection, ss);

        if(connection->method!="GET")
            return 0;
        if(connection->path!="/test/")
            return 0;
        if(connection->http_version!="1.1")
            return 0;

        if(connection->header.size()!=2)
            return 0;
        if(connection->header.count("TestHeader")==0)
            return 0;
        if(connection->header["TestHeader"]!="test")
            return 0;

        if(connection->header.count("TestHeader2")==0)
            return 0;
        if(connection->header["TestHeader2"]!="test2")
            return 0;

        return 1;
    }
};

class SocketClientTest : public SocketClientBase<WS> {
public:
    SocketClientTest(const std::string& server_port_path) : SocketClientBase<WS>::SocketClientBase(server_port_path, 80) {}

    void connect() {}

    bool constructor_parse_test1() {
        if(path!="/test")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=8080)
            return 0;

        return 1;
    }

    bool constructor_parse_test2() {
        if(path!="/test")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=80)
            return 0;

        return 1;
    }

    bool constructor_parse_test3() {
        if(path!="/")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=80)
            return 0;

        return 1;
    }

    bool constructor_parse_test4() {
        if(path!="/")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=8080)
            return 0;

        return 1;
    }

    bool parse_response_header_test() {
        connection=std::unique_ptr<Connection>(new Connection(new WS(asio_io_service)));

        stringstream ss;
        ss << "HTTP/1.1 200 OK\r\n";
        ss << "TestHeader: test\r\n";
        ss << "TestHeader2:test2\r\n";
        ss << "\r\n";

        parse_handshake(ss);

        if(connection->header.size()!=2)
            return 0;
        if(connection->header.count("TestHeader")==0)
            return 0;
        if(connection->header["TestHeader"]!="test")
            return 0;

        if(connection->header.count("TestHeader2")==0)
            return 0;
        if(connection->header["TestHeader2"]!="test2")
            return 0;

        return 1;
    }
};

int main(int argc, char** argv) {
    SocketServerTest serverTest;

    if(!serverTest.parse_request_test()) {
        cerr << "FAIL SocketServer::parse_request" << endl;
        return 1;
    }

    SocketClientTest clientTest("test.org:8080/test");
    if(!clientTest.constructor_parse_test1()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    SocketClientTest clientTest2("test.org/test");
    if(!clientTest2.constructor_parse_test2()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    SocketClientTest clientTest3("test.org");
    if(!clientTest3.constructor_parse_test3()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    SocketClientTest clientTest4("test.org:8080");
    if(!clientTest4.constructor_parse_test4()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    if(!clientTest4.parse_response_header_test()) {
        cerr << "FAIL SocketClient::parse_response_header" << endl;
        return 1;
    }

    return 0;
}<commit_msg>Fixed segmentation fault on MSYS2.<commit_after>#include "server_ws.hpp"
#include "client_ws.hpp"
#include <iostream>

using namespace std;
using namespace SimpleWeb;

class SocketServerTest : public SocketServerBase<WS> {
public:
    SocketServerTest() :
            SocketServerBase<WS>::SocketServerBase(8080, 1, 5, 300) {}

    void accept() {}

    bool parse_request_test() {
        std::shared_ptr<Connection> connection(new Connection(new WS(asio_io_service)));

        stringstream ss;
        ss << "GET /test/ HTTP/1.1\r\n";
        ss << "TestHeader: test\r\n";
        ss << "TestHeader2:test2\r\n";
        ss << "\r\n";

        parse_handshake(connection, ss);

        if(connection->method!="GET")
            return 0;
        if(connection->path!="/test/")
            return 0;
        if(connection->http_version!="1.1")
            return 0;

        if(connection->header.size()!=2)
            return 0;
        if(connection->header.count("TestHeader")==0)
            return 0;
        if(connection->header["TestHeader"]!="test")
            return 0;

        if(connection->header.count("TestHeader2")==0)
            return 0;
        if(connection->header["TestHeader2"]!="test2")
            return 0;

        return 1;
    }
};

class SocketClientTest : public SocketClientBase<WS> {
public:
    SocketClientTest(const std::string& server_port_path) : SocketClientBase<WS>::SocketClientBase(server_port_path, 80) {}

    void connect() {}

    bool constructor_parse_test1() {
        if(path!="/test")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=8080)
            return 0;

        return 1;
    }

    bool constructor_parse_test2() {
        if(path!="/test")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=80)
            return 0;

        return 1;
    }

    bool constructor_parse_test3() {
        if(path!="/")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=80)
            return 0;

        return 1;
    }

    bool constructor_parse_test4() {
        if(path!="/")
            return 0;
        if(host!="test.org")
            return 0;
        if(port!=8080)
            return 0;

        return 1;
    }

    bool parse_response_header_test() {
        connection=std::unique_ptr<Connection>(new Connection(new WS(asio_io_service)));

        stringstream ss;
        ss << "HTTP/1.1 200 OK\r\n";
        ss << "TestHeader: test\r\n";
        ss << "TestHeader2:test2\r\n";
        ss << "\r\n";

        parse_handshake(ss);

        if(connection->header.size()!=2)
            return 0;
        if(connection->header.count("TestHeader")==0)
            return 0;
        if(connection->header["TestHeader"]!="test")
            return 0;

        if(connection->header.count("TestHeader2")==0)
            return 0;
        if(connection->header["TestHeader2"]!="test2")
            return 0;

        connection.release();
        return 1;
    }
};

int main(int argc, char** argv) {
    SocketServerTest serverTest;
    if(!serverTest.parse_request_test()) {
        cerr << "FAIL SocketServer::parse_request" << endl;
        return 1;
    }

    SocketClientTest clientTest("test.org:8080/test");
    if(!clientTest.constructor_parse_test1()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    SocketClientTest clientTest2("test.org/test");
    if(!clientTest2.constructor_parse_test2()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    SocketClientTest clientTest3("test.org");
    if(!clientTest3.constructor_parse_test3()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    SocketClientTest clientTest4("test.org:8080");
    if(!clientTest4.constructor_parse_test4()) {
        cerr << "FAIL SocketClient::SocketClient" << endl;
        return 1;
    }

    if(!clientTest4.parse_response_header_test()) {
        cerr << "FAIL SocketClient::parse_response_header" << endl;
        return 1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "../src/levi_regex/r.h"
#include "../src/levi_regex/state_machine.h"

void regex_test() {
    {
        LeviDB::Regex::Result result;
        LeviDB::Regex::StateMachine machine("Hello");
        for (char c:{'H', 'e', 'l', 'l', 'o'}) {
            for (int i = 7; i >= 0; --i) {
                result = machine.send(static_cast<LeviDB::Regex::Input>((c >> i) & 1));
            }
        }
        assert(result.isSuccess());
    }
    {
        LeviDB::Regex::R r("AB", 2, 3, LeviDB::Regex::LAZY);
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr("ABABABAB");
        auto stream4num_machine = LeviDB::Regex::make_stream4num_machine(&r, &usr, result);
        assert(stream4num_machine->item().isContinue());
        stream4num_machine->next();
        assert(stream4num_machine->item().isSuccess() && stream4num_machine->item()._ed == 4);
        stream4num_machine->next();
        assert(stream4num_machine->item().isSuccess() && stream4num_machine->item()._ed == 6);
        stream4num_machine->next();
        assert(!stream4num_machine->valid());

        auto reversed = LeviDB::Regex::make_reversed(LeviDB::Regex::make_stream4num_machine(&r, &usr, result));
        assert(reversed->item().isSuccess() && reversed->item()._ed == 6);
        reversed->next();
        assert(reversed->item().isSuccess() && reversed->item()._ed == 4);
        reversed->next();
        assert(reversed->item().isContinue());
        reversed->next();
        assert(!reversed->valid());
    }
    {
        LeviDB::Regex::R r(std::make_unique<LeviDB::Regex::R>("AB"), 2, 3, LeviDB::Regex::LAZY);
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr("ABABABAB");
        auto stream4num_r = LeviDB::Regex::make_stream4num_r(&r, &usr, result);
        assert(stream4num_r->item().isContinue());
        stream4num_r->next();
        assert(stream4num_r->item().isSuccess() && stream4num_r->item()._ed == 4);
        stream4num_r->next();
        assert(stream4num_r->item().isSuccess() && stream4num_r->item()._ed == 6);
        stream4num_r->next();
        assert(!stream4num_r->valid());
        LeviDB::Regex::cacheClear();
    }
    {
        typedef LeviDB::Regex::R R;
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr("ABABABAB");

        R r = R("AB") & R("AB");
        LeviDB::Regex::Result output;
        auto it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = (R("AB") << R("UNKNOWN", 0, 0)) & (R("AB") << R(std::make_unique<R>("UNKNOWN"), 0, 0));
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = R("A") << R(std::make_unique<R>("B"), 0, 1, LeviDB::Regex::GREEDY);
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            if (!output.isContinue() && output.isSuccess()) {
                assert(output._ed == 2);
                break;
            }
            it->next();
        }
        LeviDB::Regex::cacheClear();

        r = R("A") << R(std::make_unique<R>("B"), 0, 1, LeviDB::Regex::LAZY);
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            if (!output.isContinue() && output.isSuccess()) {
                assert(output._ed == 1);
                break;
            }
            it->next();
        }
        LeviDB::Regex::cacheClear();

        r = R(std::make_unique<R>("AB"), 1, 3);
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            if (!output.isContinue() && output.isSuccess()) {
                assert(output._ed == 6);
                break;
            }
            it->next();
        }
        LeviDB::Regex::cacheClear();

        r = R("AB") & R("AC");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isFail() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = R("AC") | R("AB");
        int meet_success = 0;
        int meet_fail = 0;
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            if (it->item().isContinue()) {
            } else if (it->item().isSuccess()) {
                ++meet_success;
            } else {
                ++meet_fail;
            }
            it->next();
        }
        assert(meet_success == 1 && meet_fail == 1);
        LeviDB::Regex::cacheClear();

        r = ~R("B");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 1);
        LeviDB::Regex::cacheClear();

        r = R("A") << "B";
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = (R("AB", 0, 3) | R("ABABAB")) << R("C");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isFail());
        LeviDB::Regex::cacheClear();

        usr = LeviDB::USR("FGH");
        r = R("A", "Z");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 1);
        LeviDB::Regex::cacheClear();
    }
    {
        LeviDB::Regex::enablePossibleMode();
        LeviDB::Regex::R r("B");
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr;
        usr.mut_src()->resize(1);
        usr.mut_extra().resize(1);
        auto stream4num_machine = LeviDB::Regex::make_stream4num_machine(&r, &usr, result);
        stream4num_machine->next();
        assert(LeviDB::Regex::getPossibleResultRef().isSuccess());
        LeviDB::Regex::getPossibleResultRef() = {};
        LeviDB::Regex::disablePossibleMode();
    }

    std::cout << __FUNCTION__ << std::endl;
}<commit_msg>add more regex test<commit_after>#include <iostream>

#include "../src/levi_regex/r.h"
#include "../src/levi_regex/state_machine.h"

void regex_test() {
    {
        LeviDB::Regex::Result result;
        LeviDB::Regex::StateMachine machine("Hello");
        for (char c:{'H', 'e', 'l', 'l', 'o'}) {
            for (int i = 7; i >= 0; --i) {
                result = machine.send(static_cast<LeviDB::Regex::Input>((c >> i) & 1));
            }
        }
        assert(result.isSuccess());
    }
    {
        LeviDB::Regex::R r("AB", 2, 3, LeviDB::Regex::LAZY);
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr("ABABABAB");
        auto stream4num_machine = LeviDB::Regex::make_stream4num_machine(&r, &usr, result);
        assert(stream4num_machine->item().isContinue());
        stream4num_machine->next();
        assert(stream4num_machine->item().isSuccess() && stream4num_machine->item()._ed == 4);
        stream4num_machine->next();
        assert(stream4num_machine->item().isSuccess() && stream4num_machine->item()._ed == 6);
        stream4num_machine->next();
        assert(!stream4num_machine->valid());

        auto reversed = LeviDB::Regex::make_reversed(LeviDB::Regex::make_stream4num_machine(&r, &usr, result));
        assert(reversed->item().isSuccess() && reversed->item()._ed == 6);
        reversed->next();
        assert(reversed->item().isSuccess() && reversed->item()._ed == 4);
        reversed->next();
        assert(reversed->item().isContinue());
        reversed->next();
        assert(!reversed->valid());
    }
    {
        LeviDB::Regex::R r(std::make_unique<LeviDB::Regex::R>("AB"), 2, 3, LeviDB::Regex::LAZY);
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr("ABABABAB");
        auto stream4num_r = LeviDB::Regex::make_stream4num_r(&r, &usr, result);
        assert(stream4num_r->item().isContinue());
        stream4num_r->next();
        assert(stream4num_r->item().isSuccess() && stream4num_r->item()._ed == 4);
        stream4num_r->next();
        assert(stream4num_r->item().isSuccess() && stream4num_r->item()._ed == 6);
        stream4num_r->next();
        assert(!stream4num_r->valid());
        LeviDB::Regex::cacheClear();
    }
    {
        typedef LeviDB::Regex::R R;
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr("ABABABAB");

        R r = R("AB") & R("AB");
        LeviDB::Regex::Result output;
        auto it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = (R("AB") << R("UNKNOWN", 0, 0)) & (R("AB") << R(std::make_unique<R>("UNKNOWN"), 0, 0));
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = R("A") << R(std::make_unique<R>("B"), 0, 1, LeviDB::Regex::GREEDY);
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            if (!output.isContinue() && output.isSuccess()) {
                assert(output._ed == 2);
                break;
            }
            it->next();
        }
        LeviDB::Regex::cacheClear();

        r = R("A") << R(std::make_unique<R>("B"), 0, 1, LeviDB::Regex::LAZY);
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            if (!output.isContinue() && output.isSuccess()) {
                assert(output._ed == 1);
                break;
            }
            it->next();
        }
        LeviDB::Regex::cacheClear();

        r = R(std::make_unique<R>("AB"), 1, 3);
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            if (!output.isContinue() && output.isSuccess()) {
                assert(output._ed == 6);
                break;
            }
            it->next();
        }
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = R("AB") & R("AC");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isFail() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = R("AC") | R("AB");
        int meet_success = 0;
        int meet_fail = 0;
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            if (it->item().isContinue()) {
            } else if (it->item().isSuccess()) {
                ++meet_success;
            } else {
                ++meet_fail;
            }
            it->next();
        }
        assert(meet_success == 1 && meet_fail == 1);
        LeviDB::Regex::cacheClear();

        r = ~R("B");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 1);
        LeviDB::Regex::cacheClear();

        r = R("A") << "B";
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 2);
        LeviDB::Regex::cacheClear();

        r = (R("AB", 0, 3) | R("ABABAB")) << R("C");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isFail());
        LeviDB::Regex::cacheClear();

        usr = LeviDB::USR("FGH");
        r = R("A", "Z");
        it = LeviDB::Regex::make_imatch_iter(&r, &usr, result);
        while (it->valid()) {
            output = it->item();
            it->next();
        }
        assert(output.isSuccess() && output._ed == 1);
        LeviDB::Regex::cacheClear();
    }
    {
        LeviDB::Regex::enablePossibleMode();
        LeviDB::Regex::R r("B");
        LeviDB::Regex::Result result(0, 0, false);
        LeviDB::USR usr;
        usr.mut_src()->resize(1);
        usr.mut_extra().resize(1);
        auto stream4num_machine = LeviDB::Regex::make_stream4num_machine(&r, &usr, result);
        stream4num_machine->next();
        assert(LeviDB::Regex::getPossibleResultRef().isSuccess());
        LeviDB::Regex::getPossibleResultRef() = {};
        LeviDB::Regex::disablePossibleMode();
    }

    std::cout << __FUNCTION__ << std::endl;
}<|endoftext|>


<commit_before>#include "search.h"
#include "catch.hpp"
#include "board.h"

TEST_CASE("Search works as expected") {
  PSquareTable::init();
  ZKey::init();

  SECTION("Search works as expected after PSquareTable and ZKey are initialized") {
    Board board;

    SECTION("Search finds a checkmate on next move") {
      // Fool's mate
      board.setToFen("rnbqkbnr/pppp1ppp/4p3/8/6P1/5P2/PPPPP2P/RNBQKBNR b KQkq -");

      Search search(board, 5000, 2, false);

      REQUIRE(search.getBestMove().getNotation() == "d8h4");
    }

    SECTION("Search returns the only legal move when checkmate is 1 move away") {
      board.setToFen("r4rk1/ppp2ppp/4p3/8/4p3/4PPbP/PPPB2q1/R2QKR2 w - -");

      Search search(board, 5000, 2, false);

      REQUIRE(search.getBestMove().getNotation() == "f1f2");
    }
  }
}
<commit_msg>Add more search tests<commit_after>#include "search.h"
#include "catch.hpp"
#include "board.h"

TEST_CASE("Search works as expected") {
  PSquareTable::init();
  ZKey::init();

  SECTION("Search works as expected after PSquareTable and ZKey are initialized") {
    Board board;

    SECTION("Search finds a checkmate on next move") {
      // Fool's mate
      board.setToFen("rnbqkbnr/pppp1ppp/4p3/8/6P1/5P2/PPPPP2P/RNBQKBNR b KQkq -");

      Search search(board, 5000, 2, false);

      REQUIRE(search.getBestMove().getNotation() == "d8h4");
    }

    SECTION("Search returns the only legal move when checkmate is 1 move away") {
      board.setToFen("r4rk1/ppp2ppp/4p3/8/4p3/4PPbP/PPPB2q1/R2QKR2 w - -");

      Search search(board, 5000, 2, false);

      REQUIRE(search.getBestMove().getNotation() == "f1f2");
    }

    SECTION("Search recognizes when a check can be made to capture a queen") {
      board.setToFen("8/4N3/8/1k5q/8/8/8/2K2R2 w - -");

      Search search(board, 3, 5000, false);

      REQUIRE(search.getBestMove().getNotation() == "f1f5");
    }
  }
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <algorithm>
#include <utility>

#include <burst/memory.h>

int test1(volatile uint8_t* a, size_t n)
{
#pragma HLS INTERFACE s_axilite port=return bundle=CTRL_BUS
#pragma HLS INTERFACE m_axi depth=512 port=a offset=slave bundle=MASTER_BUS
#pragma HLS INTERFACE s_axilite port=n bundle=CTRL_BUS

    burst::memory mem(a, n);

    auto a_begin = mem.allocate<int>(8);
    auto a_end = a_begin + 8;

    std::fill(a_begin, a_end, 24);

    int arr[] = { 5, 2, 4, 9, 1, -1, 0, 12 };
    std::copy(arr, arr + 8, a_begin);

    std::make_heap(a_begin, a_end);
    std::sort_heap(a_begin, a_end);
    std::swap(a_begin[0], a_begin[1]);
    std::fill(a_begin + 2, a_begin + 6, 23);
    std::rotate(a_begin, a_begin + 2, a_end);

    mem.deallocate(a_begin);

    return 0;
}
<commit_msg>Revert "Simplify test1"<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <algorithm>
#include <utility>

#include <burst/memory.h>

int test1(volatile uint8_t* a, size_t n)
{
#pragma HLS INTERFACE s_axilite port=return bundle=CTRL_BUS
#pragma HLS INTERFACE m_axi depth=512 port=a offset=slave bundle=MASTER_BUS
#pragma HLS INTERFACE s_axilite port=n bundle=CTRL_BUS

    burst::memory mem(a, n);

    auto a_begin = mem.allocate<int>(8);
    auto a_end = a_begin + 8;

    std::fill(a_begin, a_end, 24);

    int arr[] = { 5, 2, 4, 9, 1, -1, 0, 12 };
    std::copy(arr, arr + 8, a_begin);

    std::make_heap(a_begin, a_end);
    std::sort_heap(a_begin, a_end);
    std::swap(a_begin[0], a_begin[1]);
    std::fill(a_begin + 2, a_begin + 6, 23);
    std::rotate(a_begin, a_begin + 2, a_end);

    auto b_begin = mem.allocate<int>(4);

    mem.deallocate(a_begin);
    mem.deallocate(b_begin);

    return 0;
}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <algorithm>
#include <utility>

#include <burst/memory.h>

int test1(volatile uint8_t* a, size_t n)
{
#pragma HLS INTERFACE s_axilite port=return bundle=CTRL_BUS
#pragma HLS INTERFACE m_axi depth=512 port=a offset=slave bundle=MASTER_BUS
#pragma HLS INTERFACE s_axilite port=n bundle=CTRL_BUS

    burst::memory mem(a, n);

    auto a_begin = mem.allocate<int>(8);
    auto a_end = a_begin + 8;

    std::fill(a_begin, a_end, 24);

    int arr[] = { 5, 2, 4, 9, 1, -1, 0, 12 };
    std::copy(arr, arr + 8, a_begin);

    std::make_heap(a_begin, a_end);
    std::sort_heap(a_begin, a_end);
    std::swap(a_begin[0], a_begin[1]);
    std::fill(a_begin + 2, a_begin + 6, 23);
    std::rotate(a_begin, a_begin + 2, a_end);

    auto b_begin = mem.allocate<int>(4);

    mem.deallocate(a_begin);
    mem.deallocate(b_begin);

    return 0;
}
<commit_msg>Simplify test1<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <algorithm>
#include <utility>

#include <burst/memory.h>

int test1(volatile uint8_t* a, size_t n)
{
#pragma HLS INTERFACE s_axilite port=return bundle=CTRL_BUS
#pragma HLS INTERFACE m_axi depth=512 port=a offset=slave bundle=MASTER_BUS
#pragma HLS INTERFACE s_axilite port=n bundle=CTRL_BUS

    burst::memory mem(a, n);

    auto a_begin = mem.allocate<int>(8);
    auto a_end = a_begin + 8;

    std::fill(a_begin, a_end, 24);

    int arr[] = { 5, 2, 4, 9, 1, -1, 0, 12 };
    std::copy(arr, arr + 8, a_begin);

    std::make_heap(a_begin, a_end);
    std::sort_heap(a_begin, a_end);
    std::swap(a_begin[0], a_begin[1]);
    std::fill(a_begin + 2, a_begin + 6, 23);
    std::rotate(a_begin, a_begin + 2, a_end);

    mem.deallocate(a_begin);

    return 0;
}
<|endoftext|>


<commit_before>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>

#include "test.hpp"
#include "setup_transfer.hpp"

using boost::filesystem::remove_all;

void test_swarm()
{
	using namespace libtorrent;

	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000));
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000));
	session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000));

	// this is to avoid everything finish from a single peer
	// immediately. To make the swarm actually connect all
	// three peers before finishing.
	float rate_limit = 40000;
	ses1.set_upload_rate_limit(int(rate_limit));
	ses2.set_download_rate_limit(int(rate_limit));
	ses3.set_download_rate_limit(int(rate_limit));
	ses2.set_upload_rate_limit(int(rate_limit / 2));
	ses3.set_upload_rate_limit(int(rate_limit / 2));

	session_settings settings;
	settings.allow_multiple_connections_per_ip = true;
	ses1.set_settings(settings);
	ses2.set_settings(settings);
	ses3.set_settings(settings);

#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.out_enc_policy = pe_settings::disabled;
	pes.in_enc_policy = pe_settings::disabled;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
	ses3.set_pe_settings(pes);
#endif

	torrent_handle tor1;
	torrent_handle tor2;
	torrent_handle tor3;

	boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false);

	float sum_dl_rate2 = 0.f;
	float sum_dl_rate3 = 0.f;
	int count_dl_rates2 = 0;
	int count_dl_rates3 = 0;

	for (int i = 0; i < 65; ++i)
	{
		std::auto_ptr<alert> a;
		a = ses1.pop_alert();
		if (a.get())
			std::cerr << "ses1: " << a->msg() << "\n";

		a = ses2.pop_alert();
		if (a.get())
			std::cerr << "ses2: " << a->msg() << "\n";

		a = ses3.pop_alert();
		if (a.get())
			std::cerr << "ses3: " << a->msg() << "\n";

		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();
		torrent_status st3 = tor3.status();

		if (st2.progress < 1.f && st2.progress > 0.3f)
		{
			sum_dl_rate2 += st2.download_payload_rate;
			++count_dl_rates2;
		}
		if (st3.progress < 1.f && st3.progress > 0.3f)
		{
			sum_dl_rate3 += st3.download_rate;
			++count_dl_rates3;
		}

		std::cerr
			<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s: "
			<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
			<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
			<< "\033[0m" << int(st2.progress * 100) << "% - "
			<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
			<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
			<< "\033[0m" << int(st3.progress * 100) << "% "
			<< std::endl;

		if (tor2.is_seed() && tor3.is_seed()) break;
		test_sleep(1000);
	}

	TEST_CHECK(tor2.is_seed());
	TEST_CHECK(tor3.is_seed());

	float average2 = sum_dl_rate2 / float(count_dl_rates2);
	float average3 = sum_dl_rate3 / float(count_dl_rates3);

	std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - "
		<< (average3 / 1000.f) << "kB/s" << std::endl;

	TEST_CHECK(std::fabs(average2 - float(rate_limit)) < 3000.f);
	TEST_CHECK(std::fabs(average3 - float(rate_limit)) < 3000.f);
	if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n";
}

int test_main()
{
	using namespace libtorrent;
	using namespace boost::filesystem;

	// in case the previous run was terminated
	try { remove_all("./tmp1"); } catch (std::exception&) {}
	try { remove_all("./tmp2"); } catch (std::exception&) {}
	try { remove_all("./tmp3"); } catch (std::exception&) {}

	test_swarm();

	remove_all("./tmp1");
	remove_all("./tmp2");
	remove_all("./tmp3");

	return 0;
}

<commit_msg>more output in test_swarm<commit_after>#include "libtorrent/session.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/hasher.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/filesystem/operations.hpp>

#include "test.hpp"
#include "setup_transfer.hpp"

using boost::filesystem::remove_all;

void test_swarm()
{
	using namespace libtorrent;

	session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48000, 49000));
	session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49000, 50000));
	session ses3(fingerprint("LT", 0, 1, 0, 0), std::make_pair(50000, 51000));

	// this is to avoid everything finish from a single peer
	// immediately. To make the swarm actually connect all
	// three peers before finishing.
	float rate_limit = 40000;
	ses1.set_upload_rate_limit(int(rate_limit));
	ses2.set_download_rate_limit(int(rate_limit));
	ses3.set_download_rate_limit(int(rate_limit));
	ses2.set_upload_rate_limit(int(rate_limit / 2));
	ses3.set_upload_rate_limit(int(rate_limit / 2));

	session_settings settings;
	settings.allow_multiple_connections_per_ip = true;
	ses1.set_settings(settings);
	ses2.set_settings(settings);
	ses3.set_settings(settings);

#ifndef TORRENT_DISABLE_ENCRYPTION
	pe_settings pes;
	pes.out_enc_policy = pe_settings::disabled;
	pes.in_enc_policy = pe_settings::disabled;
	ses1.set_pe_settings(pes);
	ses2.set_pe_settings(pes);
	ses3.set_pe_settings(pes);
#endif

	torrent_handle tor1;
	torrent_handle tor2;
	torrent_handle tor3;

	boost::tie(tor1, tor2, tor3) = setup_transfer(&ses1, &ses2, &ses3, true, false);

	float sum_dl_rate2 = 0.f;
	float sum_dl_rate3 = 0.f;
	int count_dl_rates2 = 0;
	int count_dl_rates3 = 0;

	for (int i = 0; i < 65; ++i)
	{
		std::auto_ptr<alert> a;
		a = ses1.pop_alert();
		if (a.get())
			std::cerr << "ses1: " << a->msg() << "\n";

		a = ses2.pop_alert();
		if (a.get())
			std::cerr << "ses2: " << a->msg() << "\n";

		a = ses3.pop_alert();
		if (a.get())
			std::cerr << "ses3: " << a->msg() << "\n";

		torrent_status st1 = tor1.status();
		torrent_status st2 = tor2.status();
		torrent_status st3 = tor3.status();

		if (st2.progress < 1.f && st2.progress > 0.3f)
		{
			sum_dl_rate2 += st2.download_payload_rate;
			++count_dl_rates2;
		}
		if (st3.progress < 1.f && st3.progress > 0.3f)
		{
			sum_dl_rate3 += st3.download_rate;
			++count_dl_rates3;
		}

		std::cerr
			<< "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s "
			<< st1.num_peers << ": "
			<< "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s "
			<< "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s "
			<< "\033[0m" << int(st2.progress * 100) << "% "
			<< st2.num_peers << " - "
			<< "\033[32m" << int(st3.download_payload_rate / 1000.f) << "kB/s "
			<< "\033[31m" << int(st3.upload_payload_rate / 1000.f) << "kB/s "
			<< "\033[0m" << int(st3.progress * 100) << "% "
			<< st3.num_peers
			<< std::endl;

		if (tor2.is_seed() && tor3.is_seed()) break;
		test_sleep(1000);
	}

	TEST_CHECK(tor2.is_seed());
	TEST_CHECK(tor3.is_seed());

	float average2 = sum_dl_rate2 / float(count_dl_rates2);
	float average3 = sum_dl_rate3 / float(count_dl_rates3);

	std::cerr << "average rate: " << (average2 / 1000.f) << "kB/s - "
		<< (average3 / 1000.f) << "kB/s" << std::endl;

	TEST_CHECK(std::fabs(average2 - float(rate_limit)) < 3000.f);
	TEST_CHECK(std::fabs(average3 - float(rate_limit)) < 3000.f);
	if (tor2.is_seed() && tor3.is_seed()) std::cerr << "done\n";
}

int test_main()
{
	using namespace libtorrent;
	using namespace boost::filesystem;

	// in case the previous run was terminated
	try { remove_all("./tmp1"); } catch (std::exception&) {}
	try { remove_all("./tmp2"); } catch (std::exception&) {}
	try { remove_all("./tmp3"); } catch (std::exception&) {}

	test_swarm();

	remove_all("./tmp1");
	remove_all("./tmp2");
	remove_all("./tmp3");

	return 0;
}

<|endoftext|>


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

#include <Transformation.h>
#include <ID.h>

namespace test {

  using namespace std;
  using ::testing::Contains;
  using ::testing::Return;
  using ::testing::AllOf;
  using ::testing::Pointee;
  using ::testing::_;

  struct BufferingTestSuite : public ::testing::Test {

    using Events = Transformer::Events;
    using EventTypes = Transformer::EventTypes;

  struct TestTransformer : public BufferedTransformer {
    using EventPtrs = BufferedTransformer::EventPtrs;
    string name;
    TestTransformer(const string& name, const EventType& out, const EventTypes& in)
      : BufferedTransformer(out, in, AbstractPolicy()), name(name) {}
    MOCK_CONST_METHOD1(check, bool(const MetaEvent&));
    MOCK_CONST_METHOD1(execute, Events(const EventPtrs&));
    virtual void print(ostream& o) const { o << name; }
  };

  struct TestTransformation : public Transformation {
    string name;
    TestTransformation(const string& name, size_t arity)
      : Transformation(Type::attribute, arity, EventID::any), name(name) { }

    MOCK_CONST_METHOD1(in, EventTypes(const EventType& goal));
    MOCK_CONST_METHOD2(in, EventTypes(const EventType& goal, const EventType& provided));
    MOCK_CONST_METHOD1(in, EventIDs(EventID goal));
    MOCK_CONST_METHOD3(create, TransPtr(const EventType& out, const EventTypes& in, const AbstractPolicy& policy));
    virtual void print(ostream& o) const { o << name; }
  };

  Events gen(const EventTypes& eTs) const {
    Events e;
    for(const EventType& eT: eTs)
      e.emplace_back(eT);
    return e;
  }

  Events execute(Transformer& t, const Events& in) const {
    Events result;
    for(const MetaEvent& e : in) {
      Events temp = t(e);
      move(temp.begin(), temp.end(), back_inserter(result));
    }
    return result;
  }

  EventType outET, inET0, inET1;
  const id::attribute::ID outID=251, inID0=252, inID1=253;

  BufferingTestSuite() {
    ValueType v(id::type::Float::value(), 1, 1, false);
    AttributeType outAT (outID, v, Scale<>(), Dimensionless());
    AttributeType inAT0 (inID0, v, Scale<>(), Dimensionless());
    AttributeType inAT1 (inID1, v, Scale<>(), Dimensionless());
    outET.add(outAT);
    inET0.add(inAT0);
    inET1.add(inAT1);
  }

};

TEST_F(BufferingTestSuite, singleHetTest) {
  MetaEvent out(outET);
  Events in = gen({inET0, inET1, inET0, inET1});
  out.attribute(outID)->value().set(0,0,3);
  in[0].attribute(inID0)->value().set(0,0,1);
  in[1].attribute(inID1)->value().set(0,0,2);
  in[2].attribute(inID0)->value().set(0,0,10);
  in[3].attribute(inID1)->value().set(0,0,20);
  EXPECT_NE(in[0], in[2]);
  EXPECT_NE(in[1], in[3]);
  TestTransformer t("SingleHet", outET, {inET0, inET1});
  EXPECT_CALL(t, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(t, check(in[0])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(t, check(in[1])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(t, execute( AllOf(
                            Contains(Pointee(in[0])),
                            Contains(Pointee(in[1]))
                          ))).Times(1).WillOnce(Return(Events({out})));
  EXPECT_THAT(execute(t, in), Events({out}));
}

}
<commit_msg>Unut-Test: add buffered transformation tests<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>

#include <Transformation.h>
#include <CompositeTransformation.h>
#include <ID.h>

namespace test {

  using namespace std;
  using ::testing::Contains;
  using ::testing::Return;
  using ::testing::AllOf;
  using ::testing::Pointee;
  using ::testing::UnorderedElementsAre;
  using ::testing::Each;
  using ::testing::SizeIs;
  using ::testing::_;

  struct BufferingTestSuite : public ::testing::Test {

    using Events = Transformer::Events;
    using EventTypes = Transformer::EventTypes;

  struct TestTransformer : public BufferedTransformer {
    using EventPtrs = BufferedTransformer::EventPtrs;
    string name;
    TestTransformer(const string& name, const EventType& out, const EventTypes& in)
      : BufferedTransformer(out, in, AbstractPolicy()), name(name) {}
    MOCK_CONST_METHOD1(check, bool(const MetaEvent&));
    MOCK_CONST_METHOD1(execute, Events(const EventPtrs&));
    virtual void print(ostream& o) const { o << name; }
  };

  struct TestTransformation : public Transformation {
    string name;
    TestTransformation(const string& name, size_t arity)
      : Transformation(Type::attribute, arity, EventID::any), name(name) { }

    MOCK_CONST_METHOD1(in, EventTypes(const EventType& goal));
    MOCK_CONST_METHOD2(in, EventTypes(const EventType& goal, const EventType& provided));
    MOCK_CONST_METHOD1(in, EventIDs(EventID goal));
    MOCK_CONST_METHOD3(create, TransPtr(const EventType& out, const EventTypes& in, const AbstractPolicy& policy));
    virtual void print(ostream& o) const { o << name; }
  };

  Events gen(const EventTypes& eTs) const {
    Events e;
    for(const EventType& eT: eTs)
      e.emplace_back(eT);
    return e;
  }

  Events execute(Transformer& t, const Events& in) const {
    Events result;
    for(const MetaEvent& e : in) {
      Events temp = t(e);
      move(temp.begin(), temp.end(), back_inserter(result));
    }
    return result;
  }

  EventType outET, inET0, inET1, inET2, tET0, tET1;
  const id::attribute::ID outID=250, inID0=251, inID1=252, inID2=253, tID0=254, tID1=255;

  BufferingTestSuite() {
    ValueType v(id::type::Float::value(), 1, 1, false);
    AttributeType outAT (outID, v, Scale<>(), Dimensionless());
    AttributeType inAT0 (inID0, v, Scale<>(), Dimensionless());
    AttributeType inAT1 (inID1, v, Scale<>(), Dimensionless());
    AttributeType inAT2 (inID2, v, Scale<>(), Dimensionless());
    AttributeType tAT0  (tID0,  v, Scale<>(), Dimensionless());
    AttributeType tAT1  (tID1,  v, Scale<>(), Dimensionless());
    outET.add(outAT);
    inET0.add(inAT0);
    inET1.add(inAT1);
    inET2.add(inAT2);
    tET0.add(tAT0);
    tET1.add(tAT1);
  }

};

TEST_F(BufferingTestSuite, singleHetTest) {
  MetaEvent out(outET);
  Events in = gen({inET0, inET1, inET0, inET1});
  out.attribute(outID)->value().set(0,0,3);
  in[0].attribute(inID0)->value().set(0,0,1);
  in[1].attribute(inID1)->value().set(0,0,2);
  in[2].attribute(inID0)->value().set(0,0,10);
  in[3].attribute(inID1)->value().set(0,0,20);
  EXPECT_NE(in[0], in[2]);
  EXPECT_NE(in[1], in[3]);
  TestTransformer t("SingleHet", outET, {inET0, inET1});
  EXPECT_CALL(t, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(t, check(in[0])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(t, check(in[1])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(t, execute( AllOf(
                            Contains(Pointee(in[0])),
                            Contains(Pointee(in[1]))
                          ))).Times(1).WillOnce(Return(Events({out})));
  EXPECT_THAT(execute(t, in), Events({out}));
}

TEST_F(BufferingTestSuite, singleHomTest) {
  MetaEvent out(outET);
  Events in = gen({inET0, inET0, inET0, inET0});
  out.attribute(outID)->value().set(0,0,3);
  in[0].attribute(inID0)->value().set(0,0,1);
  in[1].attribute(inID0)->value().set(0,0,2);
  in[2].attribute(inID0)->value().set(0,0,10);
  in[3].attribute(inID0)->value().set(0,0,20);
  EXPECT_NE(in[0], in[2]);
  EXPECT_NE(in[1], in[3]);
  TestTransformer t("SingleHom", outET, {inET0, inET0});
  EXPECT_CALL(t, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(t, check(in[0])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(t, check(in[1])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(t, execute( UnorderedElementsAre(
                            Pointee(in[0]),
                            Pointee(in[1])
                          ))).Times(2).WillRepeatedly(Return(Events({out})));
  EXPECT_THAT(execute(t, in), Events({out, out}));
}

TEST_F(BufferingTestSuite, multiHetTest) {
  MetaEvent out(outET);
  Events in = gen({inET0, inET1, inET2});
  MetaEvent temp0(tET0), temp1(tET1);
  out.attribute(outID)->value().set(0,0,3);
  in[0].attribute(inID0)->value().set(0,0,1);
  in[1].attribute(inID1)->value().set(0,0,2);
  in[2].attribute(inID2)->value().set(0,0,10);
  temp0.attribute(tID0)->value().set(0,0,5);
  temp1.attribute(tID1)->value().set(0,0,6);
  auto nothing = [](void *){};
  TestTransformer a("a", tET0, {inET0, inET1}), b("b", tET1, {inET1, inET2}), c("c", outET, {tET0, tET1});
  TestTransformation aT("aT", 2), bT("bT", 2), cT("cT", 2);

  EXPECT_CALL(aT, in(tET0)).Times(1).WillOnce(Return(EventTypes({inET0, inET1})));
  EXPECT_CALL(bT, in(tET1)).Times(1).WillOnce(Return(EventTypes({inET1, inET2})));
  EXPECT_CALL(cT, in(outET)).Times(1).WillOnce(Return(EventTypes({tET0, tET1})));

  CompositeTransformation compTrans(TransformationPtr(&cT), outET, EventType());
  compTrans.addTransformation(TransformationPtr(&aT), compTrans.root(), tET0, EventType());
  compTrans.addTransformation(TransformationPtr(&bT), compTrans.root(), tET1, EventType());

  using TransPtr = Transformation::TransPtr;

  EXPECT_CALL(aT, create(tET0,EventTypes({inET0, inET1}),_))
    .Times(1).WillOnce(Return(TransPtr(&a, nothing)));
  EXPECT_CALL(bT, create(tET1,EventTypes({inET1, inET2}),_))
    .Times(1).WillOnce(Return(TransPtr(&b, nothing)));
  EXPECT_CALL(cT, create(outET,EventTypes({tET0, tET1}),_))
    .Times(1).WillOnce(Return(TransPtr(&c, nothing)));

  TransPtr tPtr = compTrans.create(AbstractPolicy());
  ASSERT_NE(tPtr, nullptr);

  EXPECT_CALL(a, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(a, check(in[0])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(a, check(in[1])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(b, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(b, check(in[1])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(b, check(in[2])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(c, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(c, check(temp0)).Times(1).WillOnce(Return(true));
  EXPECT_CALL(c, check(temp1)).Times(1).WillOnce(Return(true));
  EXPECT_CALL(a, execute( UnorderedElementsAre(
                            Pointee(in[0]),
                            Pointee(in[1])
                          ))).Times(1).WillRepeatedly(Return(Events({temp0})));
  EXPECT_CALL(b, execute( UnorderedElementsAre(
                            Pointee(in[1]),
                            Pointee(in[2])
                          ))).Times(1).WillRepeatedly(Return(Events({temp1})));
  EXPECT_CALL(c, execute( UnorderedElementsAre(
                            Pointee(temp0),
                            Pointee(temp1)
                          ))).Times(1).WillRepeatedly(Return(Events({out})));

  EXPECT_THAT(execute(*tPtr, in), Events({out}));
}

TEST_F(BufferingTestSuite, complexTest) {
  MetaEvent out(outET);
  Events in = gen({inET0, inET0, inET1, inET1});
  MetaEvent temp0(tET0), temp1(tET1);
  out.attribute(outID)->value().set(0,0,3);
  in[0].attribute(inID0)->value().set(0,0,1);
  in[1].attribute(inID0)->value().set(0,0,2);
  in[2].attribute(inID1)->value().set(0,0,10);
  in[3].attribute(inID1)->value().set(0,0,9);
  temp0.attribute(tID0)->value().set(0,0,5);
  temp1.attribute(tID1)->value().set(0,0,6);
  auto nothing = [](void *){};
  TestTransformer a("a", tET0, {inET0, inET0}), b("b", tET1, {inET1, inET1}), c("c", outET, {tET0, tET1});
  TestTransformation aT("aT", 2), bT("bT", 2), cT("cT", 2);

  EXPECT_CALL(aT, in(tET0)).Times(1).WillOnce(Return(EventTypes({inET0, inET0})));
  EXPECT_CALL(bT, in(tET1)).Times(1).WillOnce(Return(EventTypes({inET1, inET1})));
  EXPECT_CALL(cT, in(outET)).Times(1).WillOnce(Return(EventTypes({tET0, tET1})));

  CompositeTransformation compTrans(TransformationPtr(&cT), outET, EventType());
  compTrans.addTransformation(TransformationPtr(&aT), compTrans.root(), tET0, EventType());
  compTrans.addTransformation(TransformationPtr(&bT), compTrans.root(), tET1, EventType());

  using TransPtr = Transformation::TransPtr;

  EXPECT_CALL(aT, create(tET0,EventTypes({inET0, inET0}),_))
    .Times(1).WillOnce(Return(TransPtr(&a, nothing)));
  EXPECT_CALL(bT, create(tET1,EventTypes({inET1, inET1}),_))
    .Times(1).WillOnce(Return(TransPtr(&b, nothing)));
  EXPECT_CALL(cT, create(outET,EventTypes({tET0, tET1}),_))
    .Times(1).WillOnce(Return(TransPtr(&c, nothing)));

  TransPtr tPtr = compTrans.create(AbstractPolicy());
  ASSERT_NE(tPtr, nullptr);

  EXPECT_CALL(a, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(a, check(in[0])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(a, check(in[1])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(b, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(b, check(in[2])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(b, check(in[3])).Times(1).WillOnce(Return(true));
  EXPECT_CALL(c, check(_)).WillRepeatedly(Return(false));
  EXPECT_CALL(c, check(temp0)).Times(2).WillRepeatedly(Return(true));
  EXPECT_CALL(c, check(temp1)).Times(2).WillRepeatedly(Return(true));
  EXPECT_CALL(a, execute( UnorderedElementsAre(
                            Pointee(in[0]),
                            Pointee(in[1])
                          ))).Times(2).WillRepeatedly(Return(Events({temp0})));
  EXPECT_CALL(b, execute( UnorderedElementsAre(
                            Pointee(in[2]),
                            Pointee(in[3])
                          ))).Times(2).WillRepeatedly(Return(Events({temp1})));
  EXPECT_CALL(c, execute( UnorderedElementsAre(
                            Pointee(temp0),
                            Pointee(temp1)
                          ))).Times(4).WillRepeatedly(Return(Events({out})));

  EXPECT_THAT(execute(*tPtr, in), AllOf(SizeIs(4), Each(out)));
}

}
<|endoftext|>