<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// NOTE: These tests are run as part of "unit_tests" (in chrome/test/unit)
// rather than as part of test_shell_tests because they rely on being able
// to instantiate a MessageLoop of type TYPE_IO.  test_shell_tests uses
// TYPE_UI, which URLRequest doesn't allow.
//

#include "webkit/fileapi/file_system_operation.h"

#include "base/message_loop.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_temp_dir.h"
#include "base/message_loop.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_job.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/blob/blob_data.h"
#include "webkit/blob/blob_storage_controller.h"
#include "webkit/blob/blob_url_request_job.h"
#include "webkit/fileapi/file_system_callback_dispatcher.h"
#include "webkit/fileapi/file_system_file_util.h"

namespace fileapi {
namespace {
class MockDispatcher;
}  // namespace (anonymous)

class FileSystemOperationWriteTest : public testing::Test {
 public:
  FileSystemOperationWriteTest()
      : loop_(MessageLoop::TYPE_IO),
        status_(base::PLATFORM_FILE_OK),
        bytes_written_(0),
        complete_(false) {}

  FileSystemOperation* operation();

  void set_failure_status(base::PlatformFileError status) {
    EXPECT_FALSE(complete_);
    EXPECT_EQ(status_, base::PLATFORM_FILE_OK);
    EXPECT_NE(status, base::PLATFORM_FILE_OK);
    complete_ = true;
    status_ = status;
  }
  base::PlatformFileError status() const { return status_; }
  void add_bytes_written(int64 bytes, bool complete) {
    bytes_written_ += bytes;
    EXPECT_FALSE(complete_);
    complete_ = complete;
  }
  int64 bytes_written() const { return bytes_written_; }
  bool complete() const { return complete_; }

  virtual void SetUp();
  virtual void TearDown();

 protected:
  GURL URLForRelativePath(const std::string& path) const {
    // Only the path will actually get used.
    return GURL("file://").Resolve(file_.value()).Resolve(path);
  }

  GURL URLForPath(const FilePath& path) const {
    // Only the path will actually get used.
    return GURL("file://").Resolve(path.value());
  }

  MessageLoop loop_;

  ScopedTempDir dir_;
  FilePath file_;

  // For post-operation status.
  base::PlatformFileError status_;
  int64 bytes_written_;
  bool complete_;

  DISALLOW_COPY_AND_ASSIGN(FileSystemOperationWriteTest);
};

namespace {

class TestURLRequestContext : public net::URLRequestContext {
 public:
  webkit_blob::BlobStorageController* blob_storage_controller() {
    return &blob_storage_controller_;
  }

 private:
  webkit_blob::BlobStorageController blob_storage_controller_;
};

static net::URLRequestJob* BlobURLRequestJobFactory(net::URLRequest* request,
                                                    const std::string& scheme) {
  webkit_blob::BlobStorageController* blob_storage_controller =
      static_cast<TestURLRequestContext*>(request->context())->
          blob_storage_controller();
  return new webkit_blob::BlobURLRequestJob(
      request,
      blob_storage_controller->GetBlobDataFromUrl(request->url()),
      base::MessageLoopProxy::CreateForCurrentThread());
}

class MockDispatcher : public FileSystemCallbackDispatcher {
 public:
  MockDispatcher(FileSystemOperationWriteTest* test) : test_(test) { }

  virtual void DidFail(base::PlatformFileError status) {
    test_->set_failure_status(status);
    MessageLoop::current()->Quit();
  }

  virtual void DidSucceed() {
    ADD_FAILURE();
  }

  virtual void DidReadMetadata(
      const base::PlatformFileInfo& info,
      const FilePath& platform_path) {
    ADD_FAILURE();
  }

  virtual void DidReadDirectory(
      const std::vector<base::FileUtilProxy::Entry>& entries,
      bool /* has_more */) {
    ADD_FAILURE();
  }

  virtual void DidOpenFileSystem(const std::string&, const GURL&) {
    ADD_FAILURE();
  }

  virtual void DidWrite(int64 bytes, bool complete) {
    test_->add_bytes_written(bytes, complete);
    MessageLoop::current()->Quit();
  }

 private:
  FileSystemOperationWriteTest* test_;
};

}  // namespace (anonymous)

void FileSystemOperationWriteTest::SetUp() {
  ASSERT_TRUE(dir_.CreateUniqueTempDir());
  file_util::CreateTemporaryFileInDir(dir_.path(), &file_);
  net::URLRequest::RegisterProtocolFactory("blob", &BlobURLRequestJobFactory);
}

void FileSystemOperationWriteTest::TearDown() {
  net::URLRequest::RegisterProtocolFactory("blob", NULL);
}

FileSystemOperation* FileSystemOperationWriteTest::operation() {
  FileSystemOperation* operation = new FileSystemOperation(
      new MockDispatcher(this),
      base::MessageLoopProxy::CreateForCurrentThread(),
      NULL,
      FileSystemFileUtil::GetInstance());
  operation->file_system_operation_context()->set_src_type(
      kFileSystemTypeTemporary);
  operation->file_system_operation_context()->set_dest_type(
      kFileSystemTypeTemporary);
  return operation;
}

TEST_F(FileSystemOperationWriteTest, TestWriteSuccess) {
  GURL blob_url("blob:success");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("Hello, world!\n");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(14, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteZero) {
  GURL blob_url("blob:zero");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteInvalidBlobUrl) {
  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());

  operation()->Write(url_request_context, URLForPath(file_),
      GURL("blob:invalid"), 0);
  MessageLoop::current()->Run();

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteInvalidFile) {
  GURL blob_url("blob:writeinvalidfile");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("It\'ll not be written.");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context,
                     URLForRelativePath("nonexist"), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteDir) {
  GURL blob_url("blob:writedir");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("It\'ll not be written, too.");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context, URLForPath(dir_.path()), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_ACCESS_DENIED, status());
  EXPECT_TRUE(complete());
}

// TODO(ericu,dmikurube): Add tests for Cancel.

}  // namespace fileapi
<commit_msg>Nit fix FileSystemOperationWriteTest about when exiting the thread and remove unnecessary lines.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// NOTE: These tests are run as part of "unit_tests" (in chrome/test/unit)
// rather than as part of test_shell_tests because they rely on being able
// to instantiate a MessageLoop of type TYPE_IO.  test_shell_tests uses
// TYPE_UI, which URLRequest doesn't allow.
//

#include "base/message_loop.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_temp_dir.h"
#include "base/message_loop.h"
#include "googleurl/src/gurl.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_job.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/blob/blob_data.h"
#include "webkit/blob/blob_storage_controller.h"
#include "webkit/blob/blob_url_request_job.h"
#include "webkit/fileapi/file_system_callback_dispatcher.h"
#include "webkit/fileapi/file_system_file_util.h"
#include "webkit/fileapi/file_system_operation.h"

namespace fileapi {

class FileSystemOperationWriteTest : public testing::Test {
 public:
  FileSystemOperationWriteTest()
      : loop_(MessageLoop::TYPE_IO),
        status_(base::PLATFORM_FILE_OK),
        bytes_written_(0),
        complete_(false) {}

  FileSystemOperation* operation();

  void set_failure_status(base::PlatformFileError status) {
    EXPECT_FALSE(complete_);
    EXPECT_EQ(status_, base::PLATFORM_FILE_OK);
    EXPECT_NE(status, base::PLATFORM_FILE_OK);
    complete_ = true;
    status_ = status;
  }
  base::PlatformFileError status() const { return status_; }
  void add_bytes_written(int64 bytes, bool complete) {
    bytes_written_ += bytes;
    EXPECT_FALSE(complete_);
    complete_ = complete;
  }
  int64 bytes_written() const { return bytes_written_; }
  bool complete() const { return complete_; }

  virtual void SetUp();
  virtual void TearDown();

 protected:
  GURL URLForRelativePath(const std::string& path) const {
    // Only the path will actually get used.
    return GURL("file://").Resolve(file_.value()).Resolve(path);
  }

  GURL URLForPath(const FilePath& path) const {
    // Only the path will actually get used.
    return GURL("file://").Resolve(path.value());
  }

  MessageLoop loop_;

  ScopedTempDir dir_;
  FilePath file_;

  // For post-operation status.
  base::PlatformFileError status_;
  int64 bytes_written_;
  bool complete_;

  DISALLOW_COPY_AND_ASSIGN(FileSystemOperationWriteTest);
};

namespace {

class TestURLRequestContext : public net::URLRequestContext {
 public:
  webkit_blob::BlobStorageController* blob_storage_controller() {
    return &blob_storage_controller_;
  }

 private:
  webkit_blob::BlobStorageController blob_storage_controller_;
};

static net::URLRequestJob* BlobURLRequestJobFactory(net::URLRequest* request,
                                                    const std::string& scheme) {
  webkit_blob::BlobStorageController* blob_storage_controller =
      static_cast<TestURLRequestContext*>(request->context())->
          blob_storage_controller();
  return new webkit_blob::BlobURLRequestJob(
      request,
      blob_storage_controller->GetBlobDataFromUrl(request->url()),
      base::MessageLoopProxy::CreateForCurrentThread());
}

class MockDispatcher : public FileSystemCallbackDispatcher {
 public:
  MockDispatcher(FileSystemOperationWriteTest* test) : test_(test) { }

  virtual void DidFail(base::PlatformFileError status) {
    test_->set_failure_status(status);
    MessageLoop::current()->Quit();
  }

  virtual void DidSucceed() {
    ADD_FAILURE();
  }

  virtual void DidReadMetadata(
      const base::PlatformFileInfo& info,
      const FilePath& platform_path) {
    ADD_FAILURE();
  }

  virtual void DidReadDirectory(
      const std::vector<base::FileUtilProxy::Entry>& entries,
      bool /* has_more */) {
    ADD_FAILURE();
  }

  virtual void DidOpenFileSystem(const std::string&, const GURL&) {
    ADD_FAILURE();
  }

  virtual void DidWrite(int64 bytes, bool complete) {
    test_->add_bytes_written(bytes, complete);
    if (complete)
      MessageLoop::current()->Quit();
  }

 private:
  FileSystemOperationWriteTest* test_;
};

}  // namespace (anonymous)

void FileSystemOperationWriteTest::SetUp() {
  ASSERT_TRUE(dir_.CreateUniqueTempDir());
  file_util::CreateTemporaryFileInDir(dir_.path(), &file_);
  net::URLRequest::RegisterProtocolFactory("blob", &BlobURLRequestJobFactory);
}

void FileSystemOperationWriteTest::TearDown() {
  net::URLRequest::RegisterProtocolFactory("blob", NULL);
}

FileSystemOperation* FileSystemOperationWriteTest::operation() {
  FileSystemOperation* operation = new FileSystemOperation(
      new MockDispatcher(this),
      base::MessageLoopProxy::CreateForCurrentThread(),
      NULL,
      FileSystemFileUtil::GetInstance());
  operation->file_system_operation_context()->set_src_type(
      kFileSystemTypeTemporary);
  operation->file_system_operation_context()->set_dest_type(
      kFileSystemTypeTemporary);
  return operation;
}

TEST_F(FileSystemOperationWriteTest, TestWriteSuccess) {
  GURL blob_url("blob:success");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("Hello, world!\n");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(14, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteZero) {
  GURL blob_url("blob:zero");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context, URLForPath(file_), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteInvalidBlobUrl) {
  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());

  operation()->Write(url_request_context, URLForPath(file_),
      GURL("blob:invalid"), 0);
  MessageLoop::current()->Run();

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_OK, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteInvalidFile) {
  GURL blob_url("blob:writeinvalidfile");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("It\'ll not be written.");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context,
                     URLForRelativePath("nonexist"), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_NOT_FOUND, status());
  EXPECT_TRUE(complete());
}

TEST_F(FileSystemOperationWriteTest, TestWriteDir) {
  GURL blob_url("blob:writedir");
  scoped_refptr<webkit_blob::BlobData> blob_data(new webkit_blob::BlobData());
  blob_data->AppendData("It\'ll not be written, too.");

  scoped_refptr<TestURLRequestContext> url_request_context(
      new TestURLRequestContext());
  url_request_context->blob_storage_controller()->
      RegisterBlobUrl(blob_url, blob_data);

  operation()->Write(url_request_context, URLForPath(dir_.path()), blob_url, 0);
  MessageLoop::current()->Run();

  url_request_context->blob_storage_controller()->UnregisterBlobUrl(blob_url);

  EXPECT_EQ(0, bytes_written());
  EXPECT_EQ(base::PLATFORM_FILE_ERROR_ACCESS_DENIED, status());
  EXPECT_TRUE(complete());
}

// TODO(ericu,dmikurube): Add tests for Cancel.

}  // namespace fileapi
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007-2014 Frank Mertens.
 *
 * Use of this source is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 */

#include <flux/Singleton>
#ifndef NDEBUG
#include <flux/SyntaxDebugger>
#endif
#include <flux/syntax>
#include <flux/Format>
#include <flux/Pattern>
#include <flux/PatternSyntax>

namespace flux {

typedef syntax::NODE NODE;

PatternSyntax::PatternSyntax()
{
    SYNTAX("pattern");

    any_ = DEFINE("Any", CHAR('#'));
    gap_ = DEFINE("Gap", CHAR('*'));
    boi_ = DEFINE("Boi", GLUE(BOI(), CHAR('^')));
    eoi_ = DEFINE("Eoi", GLUE(CHAR('^'), EOI()));

    char_ =
        DEFINE("Char",
            CHOICE(
                EXCEPT("#*\\[](){}|^:"),
                GLUE(
                    CHAR('\\'),
                    EXPECT("Invalid escape sequence",
                        CHOICE(
                            RANGE(
                                "#*\\[](){}|^:"
                                "nstrf"
                            ),
                            GLUE(
                                CHAR('x'),
                                REPEAT(2, 2,
                                    CHOICE(
                                        RANGE('0', '9'),
                                        RANGE('a', 'f'),
                                        RANGE('A', 'F')
                                    )
                                )
                            )
                        )
                    )
                )
            )
        );

    string_ =
        DEFINE("String",
            REPEAT(2,
                REF("Char")
            )
        );

    rangeMinMax_ =
        DEFINE("RangeMinMax",
            GLUE(
                CHAR('['),
                CHOICE(
                    GLUE(
                        REPEAT(0, 1, CHAR('^')),
                        CHOICE(
                            GLUE(
                                STRING(".."),
                                REF("Char")
                            ),
                            GLUE(
                                REF("Char"),
                                STRING(".."),
                                REF("Char")
                            ),
                            GLUE(
                                REF("Char"),
                                STRING("..")
                            )
                        )
                    ),
                    STRING("..")
                ),
                EXPECT("Expected closing ']'",
                    CHAR(']')
                )
            )
        );

    rangeExplicit_ =
        DEFINE("RangeExplicit",
            GLUE(
                CHAR('['),
                REPEAT(0, 1, CHAR('^')),
                REPEAT(1, REF("Char")),
                EXPECT("Expected closing ']'",
                    CHAR(']')
                )
            )
        );

    DEFINE("Range",
        GLUE(
            AHEAD(CHAR('[')),
            EXPECT("Expected range definition",
                CHOICE(
                    REF("RangeMinMax"),
                    REF("RangeExplicit")
                )
            )
        )
    );

    DEFINE("Number",
        REPEAT(1, 20,
            RANGE('0', '9')
        )
    );

    minRepeat_ = DEFINE("MinRepeat", INLINE("Number"));
    maxRepeat_ = DEFINE("MaxRepeat", INLINE("Number"));

    repeat_ =
        DEFINE("Repeat",
            GLUE(
                CHAR('{'),
                REPEAT(0, 1, RANGE("<~>")),
                REPEAT(0, 1,
                    GLUE(
                        REPEAT(0, 1, REF("MinRepeat")),
                        STRING(".."),
                        REPEAT(0, 1, REF("MaxRepeat")),
                        EXPECT("Expected ':' after repeat counts",
                            CHAR(':')
                        )
                    )
                ),
                EXPECT("Expected repeat expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing '}'",
                    CHAR('}')
                )
            )
        );

    sequence_ =
        DEFINE("Sequence",
            REPEAT(
                CHOICE(
                    REF("Repeat"),
                    REF("String"),
                    REF("Char"),
                    REF("Any"),
                    REF("Gap"),
                    INLINE("Range"),
                    REF("Boi"),
                    REF("Eoi"),
                    REF("Group"),
                    REF("Behind"),
                    REF("Ahead"),
                    REF("Capture"),
                    REF("Replay")
                )
            )
        );

    group_ =
        DEFINE("Group",
            GLUE(
                CHAR('('),
                NOT(AHEAD(CHAR('?'))),
                REF("Choice"),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    ahead_ =
        DEFINE("Ahead",
            GLUE(
                STRING("(?>"),
                REPEAT(0, 1, CHAR('!')),
                REPEAT(0, 1, CHAR(':')),
                EXPECT("Expected ahead expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    behind_ =
        DEFINE("Behind",
            GLUE(
                STRING("(?<"),
                REPEAT(0, 1, CHAR('!')),
                REPEAT(0, 1, CHAR(':')),
                EXPECT("Expected behind expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    identifier_ =
        DEFINE("CaptureIdentifier",
            REPEAT(
                CHOICE(
                    RANGE('a', 'z'),
                    RANGE('A', 'Z'),
                    RANGE('0', '9'),
                    CHAR('_')
                )
            )
        );

    capture_ =
        DEFINE("Capture",
            GLUE(
                STRING("(?@"),
                REF("CaptureIdentifier"),
                REPEAT(0, 1, CHAR(':')),
                EXPECT("Expected capture expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    replay_ =
        DEFINE("Replay",
            GLUE(
                STRING("(?="),
                REF("CaptureIdentifier"),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    choice_ =
        DEFINE("Choice",
            GLUE(
                REF("Sequence"),
                REPEAT(
                    GLUE(
                        CHAR('|'),
                        REF("Sequence")
                    )
                )
            )
        );

    pattern_ =
        DEFINE("Pattern",
            GLUE(
                REF("Choice"),
                EOI()
            )
        );

    ENTRY("Pattern");
    LINK();
}

void PatternSyntax::compile(const ByteArray *text, SyntaxDefinition *definition) const
{
    Ref<SyntaxState> state = match(text);
    if (!state->valid()) throw SyntaxError(text, state);
    NODE entry;
    if (text->count() == 0) entry = definition->PASS();
    else entry = compileChoice(text, state->rootToken()->firstChild(), definition);
    definition->DEFINE("Expression", entry);
    definition->ENTRY("Expression");
    definition->LINK();
}

NODE PatternSyntax::compileChoice(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    if (token->countChildren() == 1)
        return compileSequence(text, token->firstChild(), definition);
    NODE node = new syntax::LazyChoiceNode;
    for (Token *child = token->firstChild(); child; child = child->nextSibling())
        node->appendChild(compileSequence(text, child, definition));
    return definition->debug(node, "Choice");
}

NODE PatternSyntax::compileSequence(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    NODE node = new syntax::GlueNode;
    for (Token *child = token->firstChild(); child; child = child->nextSibling()) {
        if (child->rule() == string_) node->appendChild(definition->STRING(readString(text, child)));
        else if (child->rule() == char_) node->appendChild(definition->CHAR(readChar(text, child)));
        else if (child->rule() == any_) node->appendChild(definition->ANY());
        else if (child->rule() == gap_) node->appendChild(definition->GREEDY_REPEAT(definition->ANY()));
        else if (child->rule() == rangeMinMax_) node->appendChild(compileRangeMinMax(text, child, definition));
        else if (child->rule() == rangeExplicit_) node->appendChild(compileRangeExplicit(text, child, definition));
        else if (child->rule() == repeat_) { node->appendChild(compileRepeat(text, child, definition)); }
        else if (child->rule() == boi_) node->appendChild(definition->BOI());
        else if (child->rule() == eoi_) node->appendChild(definition->EOI());
        else if (child->rule() == group_) node->appendChild(compileChoice(text, child->firstChild(), definition));
        else if (child->rule() == ahead_) node->appendChild(compileAhead(text, child, definition));
        else if (child->rule() == behind_) node->appendChild(compileBehind(text, child, definition));
        else if (child->rule() == capture_) node->appendChild(compileCapture(text, child, definition));
        else if (child->rule() == replay_) node->appendChild(compileReference(text, child, definition));
    }
    if (node->firstChild() == node->lastChild()) {
        NODE child = node->firstChild();
        child->unlink();
        return child;
    }
    return definition->debug(node, "Glue");
}

NODE PatternSyntax::compileAhead(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    return (text->at(token->i0() + 3) != '!') ?
        definition->AHEAD(compileChoice(text, token->firstChild(), definition)) :
        definition->NOT(compileChoice(text, token->firstChild(), definition));
}

NODE PatternSyntax::compileBehind(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    return (text->at(token->i0() + 3) != '!') ?
        definition->BEHIND(compileChoice(text, token->firstChild(), definition)) :
        definition->NOT_BEHIND(compileChoice(text, token->firstChild(), definition));
}

NODE PatternSyntax::compileCapture(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    String name = text->copy(token->firstChild());
    return definition->CAPTURE(name, compileChoice(text, token->lastChild(), definition));
}

NODE PatternSyntax::compileReference(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    String name = text->copy(token->firstChild());
    return definition->REPLAY(name);
}

char PatternSyntax::readChar(const ByteArray *text, Token *token) const
{
    return (token->i1() - token->i0() > 1) ?
        text->copy(token)->unescapeInsitu()->at(0) :
        text->at(token->i0());
}

String PatternSyntax::readString(const ByteArray *text, Token *token) const
{
    String s(token->countChildren());
    int i = 0;
    for (Token *child = token->firstChild(); child; child = child->nextSibling())
        s->at(i++) = readChar(text, child);
    return s;
}

NODE PatternSyntax::compileRangeMinMax(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    int n = token->countChildren();
    bool invert = (text->at(token->i0() + 1) == '^');
    if (n == 2) {
        Token *min = token->firstChild();
        Token *max = min->nextSibling();
        char a = readChar(text, min);
        char b = readChar(text, max);
        return  invert ? definition->EXCEPT(a, b) : definition->RANGE(a, b);
    }
    else if (n == 1) {
        Token *child = token->firstChild();
        char ch = readChar(text, child);
        return invert ?
            ( (child->i0() - token->i0() <= 2) ? definition->BELOW(ch)            : definition->GREATER(ch)        ) :
            ( (child->i0() - token->i0() <= 2) ? definition->GREATER_OR_EQUAL(ch) : definition->BELOW_OR_EQUAL(ch) );
    }
    return definition->ANY();
}

NODE PatternSyntax::compileRangeExplicit(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    Token *child = token->firstChild();
    bool invert = (text->at(token->i0() + 1) == '^');
    int n = token->countChildren();
    String s(n);
    for (int i = 0; i < n; ++i) {
        s->at(i) = readChar(text, child);
        child = child->nextSibling();
    }
    return invert ? definition->EXCEPT(s) : definition->RANGE(s);
}

NODE PatternSyntax::compileRepeat(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    Token *child = token->firstChild(), *min = 0, *max = 0;
    while (child) {
        if (child->rule() == minRepeat_) min = child;
        else if (child->rule() == maxRepeat_) max = child;
        child = child->nextSibling();
    }
    int minRepeat = min ? text->copy(min)->toInt() : 0;
    int maxRepeat = max ? text->copy(max)->toInt() : intMax;
    char modifier = text->at(token->i0() + 1);
    NODE node = compileChoice(text, token->lastChild(), definition);
    if (modifier == '<')
        return definition->LAZY_REPEAT(minRepeat, node);
    else if (modifier == '~')
        return definition->REPEAT(minRepeat, maxRepeat, node);
    // else if (modifier == '>');
    return definition->GREEDY_REPEAT(minRepeat, maxRepeat, node);
}

const PatternSyntax *patternSyntax() { return Singleton<PatternSyntax>::instance(); }

} // namespace flux
<commit_msg>Fix: Pattern: compilation of empty name captures<commit_after>/*
 * Copyright (C) 2007-2014 Frank Mertens.
 *
 * Use of this source is governed by a BSD-style license that can be
 * found in the LICENSE file.
 *
 */

#include <flux/Singleton>
#ifndef NDEBUG
#include <flux/SyntaxDebugger>
#endif
#include <flux/syntax>
#include <flux/Format>
#include <flux/Pattern>
#include <flux/PatternSyntax>

namespace flux {

typedef syntax::NODE NODE;

PatternSyntax::PatternSyntax()
{
    SYNTAX("pattern");

    any_ = DEFINE("Any", CHAR('#'));
    gap_ = DEFINE("Gap", CHAR('*'));
    boi_ = DEFINE("Boi", GLUE(BOI(), CHAR('^')));
    eoi_ = DEFINE("Eoi", GLUE(CHAR('^'), EOI()));

    char_ =
        DEFINE("Char",
            CHOICE(
                EXCEPT("#*\\[](){}|^:"),
                GLUE(
                    CHAR('\\'),
                    EXPECT("Invalid escape sequence",
                        CHOICE(
                            RANGE(
                                "#*\\[](){}|^:"
                                "nstrf"
                            ),
                            GLUE(
                                CHAR('x'),
                                REPEAT(2, 2,
                                    CHOICE(
                                        RANGE('0', '9'),
                                        RANGE('a', 'f'),
                                        RANGE('A', 'F')
                                    )
                                )
                            )
                        )
                    )
                )
            )
        );

    string_ =
        DEFINE("String",
            REPEAT(2,
                REF("Char")
            )
        );

    rangeMinMax_ =
        DEFINE("RangeMinMax",
            GLUE(
                CHAR('['),
                CHOICE(
                    GLUE(
                        REPEAT(0, 1, CHAR('^')),
                        CHOICE(
                            GLUE(
                                STRING(".."),
                                REF("Char")
                            ),
                            GLUE(
                                REF("Char"),
                                STRING(".."),
                                REF("Char")
                            ),
                            GLUE(
                                REF("Char"),
                                STRING("..")
                            )
                        )
                    ),
                    STRING("..")
                ),
                EXPECT("Expected closing ']'",
                    CHAR(']')
                )
            )
        );

    rangeExplicit_ =
        DEFINE("RangeExplicit",
            GLUE(
                CHAR('['),
                REPEAT(0, 1, CHAR('^')),
                REPEAT(1, REF("Char")),
                EXPECT("Expected closing ']'",
                    CHAR(']')
                )
            )
        );

    DEFINE("Range",
        GLUE(
            AHEAD(CHAR('[')),
            EXPECT("Expected range definition",
                CHOICE(
                    REF("RangeMinMax"),
                    REF("RangeExplicit")
                )
            )
        )
    );

    DEFINE("Number",
        REPEAT(1, 20,
            RANGE('0', '9')
        )
    );

    minRepeat_ = DEFINE("MinRepeat", INLINE("Number"));
    maxRepeat_ = DEFINE("MaxRepeat", INLINE("Number"));

    repeat_ =
        DEFINE("Repeat",
            GLUE(
                CHAR('{'),
                REPEAT(0, 1, RANGE("<~>")),
                REPEAT(0, 1,
                    GLUE(
                        REPEAT(0, 1, REF("MinRepeat")),
                        STRING(".."),
                        REPEAT(0, 1, REF("MaxRepeat")),
                        EXPECT("Expected ':' after repeat counts",
                            CHAR(':')
                        )
                    )
                ),
                EXPECT("Expected repeat expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing '}'",
                    CHAR('}')
                )
            )
        );

    sequence_ =
        DEFINE("Sequence",
            REPEAT(
                CHOICE(
                    REF("Repeat"),
                    REF("String"),
                    REF("Char"),
                    REF("Any"),
                    REF("Gap"),
                    INLINE("Range"),
                    REF("Boi"),
                    REF("Eoi"),
                    REF("Group"),
                    REF("Behind"),
                    REF("Ahead"),
                    REF("Capture"),
                    REF("Replay")
                )
            )
        );

    group_ =
        DEFINE("Group",
            GLUE(
                CHAR('('),
                NOT(CHAR('?')),
                REF("Choice"),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    ahead_ =
        DEFINE("Ahead",
            GLUE(
                STRING("(?>"),
                REPEAT(0, 1, CHAR('!')),
                REPEAT(0, 1, CHAR(':')),
                EXPECT("Expected ahead expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    behind_ =
        DEFINE("Behind",
            GLUE(
                STRING("(?<"),
                REPEAT(0, 1, CHAR('!')),
                REPEAT(0, 1, CHAR(':')),
                EXPECT("Expected behind expression",
                    REF("Choice")
                ),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    identifier_ =
        DEFINE("CaptureIdentifier",
            REPEAT(
                CHOICE(
                    RANGE('a', 'z'),
                    RANGE('A', 'Z'),
                    RANGE('0', '9'),
                    CHAR('_')
                )
            )
        );

    capture_ =
        DEFINE("Capture",
            GLUE(
                STRING("(?@"),
                REPEAT(0, 1,
                    GLUE(
                        REF("CaptureIdentifier"),
                        CHAR(':')
                    )
                ),
                EXPECT("Expected capture expression",
                    LENGTH(1,
                        REF("Choice")
                    )
                ),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    replay_ =
        DEFINE("Replay",
            GLUE(
                STRING("(?="),
                REF("CaptureIdentifier"),
                EXPECT("Expected closing ')'",
                    CHAR(')')
                )
            )
        );

    choice_ =
        DEFINE("Choice",
            GLUE(
                REF("Sequence"),
                REPEAT(
                    GLUE(
                        CHAR('|'),
                        REF("Sequence")
                    )
                )
            )
        );

    pattern_ =
        DEFINE("Pattern",
            GLUE(
                REF("Choice"),
                EOI()
            )
        );

    ENTRY("Pattern");
    LINK();
}

void PatternSyntax::compile(const ByteArray *text, SyntaxDefinition *definition) const
{
    Ref<SyntaxState> state = match(text);
    if (!state->valid()) throw SyntaxError(text, state);
    NODE entry;
    if (text->count() == 0) entry = definition->PASS();
    else entry = compileChoice(text, state->rootToken()->firstChild(), definition);
    definition->DEFINE("Expression", entry);
    definition->ENTRY("Expression");
    definition->LINK();
}

NODE PatternSyntax::compileChoice(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    if (token->countChildren() == 1)
        return compileSequence(text, token->firstChild(), definition);
    NODE node = new syntax::LazyChoiceNode;
    for (Token *child = token->firstChild(); child; child = child->nextSibling())
        node->appendChild(compileSequence(text, child, definition));
    return definition->debug(node, "Choice");
}

NODE PatternSyntax::compileSequence(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    NODE node = new syntax::GlueNode;
    for (Token *child = token->firstChild(); child; child = child->nextSibling()) {
        if (child->rule() == string_) node->appendChild(definition->STRING(readString(text, child)));
        else if (child->rule() == char_) node->appendChild(definition->CHAR(readChar(text, child)));
        else if (child->rule() == any_) node->appendChild(definition->ANY());
        else if (child->rule() == gap_) node->appendChild(definition->GREEDY_REPEAT(definition->ANY()));
        else if (child->rule() == rangeMinMax_) node->appendChild(compileRangeMinMax(text, child, definition));
        else if (child->rule() == rangeExplicit_) node->appendChild(compileRangeExplicit(text, child, definition));
        else if (child->rule() == repeat_) { node->appendChild(compileRepeat(text, child, definition)); }
        else if (child->rule() == boi_) node->appendChild(definition->BOI());
        else if (child->rule() == eoi_) node->appendChild(definition->EOI());
        else if (child->rule() == group_) node->appendChild(compileChoice(text, child->firstChild(), definition));
        else if (child->rule() == ahead_) node->appendChild(compileAhead(text, child, definition));
        else if (child->rule() == behind_) node->appendChild(compileBehind(text, child, definition));
        else if (child->rule() == capture_) node->appendChild(compileCapture(text, child, definition));
        else if (child->rule() == replay_) node->appendChild(compileReference(text, child, definition));
    }
    if (node->firstChild() == node->lastChild()) {
        NODE child = node->firstChild();
        child->unlink();
        return child;
    }
    return definition->debug(node, "Glue");
}

NODE PatternSyntax::compileAhead(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    return (text->at(token->i0() + 3) != '!') ?
        definition->AHEAD(compileChoice(text, token->firstChild(), definition)) :
        definition->NOT(compileChoice(text, token->firstChild(), definition));
}

NODE PatternSyntax::compileBehind(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    return (text->at(token->i0() + 3) != '!') ?
        definition->BEHIND(compileChoice(text, token->firstChild(), definition)) :
        definition->NOT_BEHIND(compileChoice(text, token->firstChild(), definition));
}

NODE PatternSyntax::compileCapture(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    String name;
    if (token->firstChild() != token->lastChild())
        name = text->copy(token->firstChild());
    return definition->CAPTURE(name, compileChoice(text, token->lastChild(), definition));
}

NODE PatternSyntax::compileReference(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    String name = text->copy(token->firstChild());
    return definition->REPLAY(name);
}

char PatternSyntax::readChar(const ByteArray *text, Token *token) const
{
    return (token->i1() - token->i0() > 1) ?
        text->copy(token)->unescapeInsitu()->at(0) :
        text->at(token->i0());
}

String PatternSyntax::readString(const ByteArray *text, Token *token) const
{
    String s(token->countChildren());
    int i = 0;
    for (Token *child = token->firstChild(); child; child = child->nextSibling())
        s->at(i++) = readChar(text, child);
    return s;
}

NODE PatternSyntax::compileRangeMinMax(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    int n = token->countChildren();
    bool invert = (text->at(token->i0() + 1) == '^');
    if (n == 2) {
        Token *min = token->firstChild();
        Token *max = min->nextSibling();
        char a = readChar(text, min);
        char b = readChar(text, max);
        return  invert ? definition->EXCEPT(a, b) : definition->RANGE(a, b);
    }
    else if (n == 1) {
        Token *child = token->firstChild();
        char ch = readChar(text, child);
        return invert ?
            ( (child->i0() - token->i0() <= 2) ? definition->BELOW(ch)            : definition->GREATER(ch)        ) :
            ( (child->i0() - token->i0() <= 2) ? definition->GREATER_OR_EQUAL(ch) : definition->BELOW_OR_EQUAL(ch) );
    }
    return definition->ANY();
}

NODE PatternSyntax::compileRangeExplicit(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    Token *child = token->firstChild();
    bool invert = (text->at(token->i0() + 1) == '^');
    int n = token->countChildren();
    String s(n);
    for (int i = 0; i < n; ++i) {
        s->at(i) = readChar(text, child);
        child = child->nextSibling();
    }
    return invert ? definition->EXCEPT(s) : definition->RANGE(s);
}

NODE PatternSyntax::compileRepeat(const ByteArray *text, Token *token, SyntaxDefinition *definition) const
{
    Token *child = token->firstChild(), *min = 0, *max = 0;
    while (child) {
        if (child->rule() == minRepeat_) min = child;
        else if (child->rule() == maxRepeat_) max = child;
        child = child->nextSibling();
    }
    int minRepeat = min ? text->copy(min)->toInt() : 0;
    int maxRepeat = max ? text->copy(max)->toInt() : intMax;
    char modifier = text->at(token->i0() + 1);
    NODE node = compileChoice(text, token->lastChild(), definition);
    if (modifier == '<')
        return definition->LAZY_REPEAT(minRepeat, node);
    else if (modifier == '~')
        return definition->REPEAT(minRepeat, maxRepeat, node);
    // else if (modifier == '>');
    return definition->GREEDY_REPEAT(minRepeat, maxRepeat, node);
}

const PatternSyntax *patternSyntax() { return Singleton<PatternSyntax>::instance(); }

} // namespace flux
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2011.  All rights reserved
 */
#include	"../../StroikaPreComp.h"

#if		qPlatform_Windows
	#include	<io.h>
#elif	qPlatform_POSIX
	#include	<unistd.h>
#endif
#include	<cstdlib>

#include	"Socket.h"

using	namespace	Stroika::Foundation;
using	namespace	Stroika::Foundation::IO;
using	namespace	Stroika::Foundation::IO::Network;

class	Socket::Rep_ {
	public:
		NativeSocket	fSD_;
	public:
		Rep_ ()
			{
			}
		Rep_ (NativeSocket sd)
			: fSD_ (sd)
			{
			}

	public:
		void	Close ()
			{
				#if		qPlatform_Windows
					::_close (fSD_);
				#elif	qPlatform_POSIX
					::close (fSD_);
				#else
					AssertNotImplemented ();
				#endif
			}
	public:
		size_t	Read (Byte* buffer, size_t bufSize) override
			{
				// Must do erorr checking and throw exceptions!!!
				#if		qPlatform_Windows
					return ::_read (fSD_, buffer, bufSize);
				#elif	qPlatform_POSIX
					return ::read (fSD_, buffer, bufSize);
				#else
					AssertNotImplemented ();
				#endif
			}
	public:
		void	Write (const Byte* buffer, size_t bufSize) override
			{
				// Must do erorr checking and throw exceptions!!!
				#if		qPlatform_Windows
					int		n	=	::_write (fSD_, buffer, bufSize);
				#elif	qPlatform_POSIX
					int		n	=	::write (fSD_, buffer, bufSize);
				#else
					AssertNotImplemented ();
				#endif
			}
	public:
		void	Bind (const Socket::BindProperties& bindProperties)
			{
			//
			}

	public:
		Socket	Accept ()
			{
				return Socket ();
			}

};

Socket::Socket ()
{
}

Socket::Socket (const Socket& s)
{
}

Socket::Socket (NativeSocket sd)
{
}

Socket::~Socket ()
{
}

const Socket& Socket::operator= (const Socket& s)
{
	return *this;
}

void	Socket::Bind (const BindProperties& bindProperties)
{
	fRep_->Bind (bindProperties);
}

Socket	Socket::Accept ()
{
	return fRep_->Accept ();
}

size_t	Socket::Read (Byte* buffer, size_t bufSize)
{
	return fRep_->Read (buffer, bufSize);
}

void	Socket::Write (const Byte* buffer, size_t bufSize)
{
	fRep_->Write (buffer, bufSize);
}

void	Socket::Close ()
{
	fRep_->Close ();
}
<commit_msg>a little more progress on Socket implementatioatn (bind/accept first draft)<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2011.  All rights reserved
 */
#include	"../../StroikaPreComp.h"

#include	<sys/types.h>

#if		qPlatform_Windows
	#include	<winsock2.h>
	#include	<ws2tcpip.h>
	#include	<io.h>
#elif	qPlatform_POSIX
	#include	<unistd.h>
	#include	<sys/socket.h>
#endif

#include	<cstdlib>

#include	"Socket.h"

using	namespace	Stroika::Foundation;
using	namespace	Stroika::Foundation::IO;
using	namespace	Stroika::Foundation::IO::Network;

class	Socket::Rep_ {
	public:
		NativeSocket	fSD_;
	public:
		Rep_ ()
			{
			}
		Rep_ (NativeSocket sd)
			: fSD_ (sd)
			{
			}

	public:
		void	Close ()
			{
				#if		qPlatform_Windows
					::_close (fSD_);
				#elif	qPlatform_POSIX
					::close (fSD_);
				#else
					AssertNotImplemented ();
				#endif
			}
	public:
		size_t	Read (Byte* buffer, size_t bufSize) override
			{
				// Must do erorr checking and throw exceptions!!!
				#if		qPlatform_Windows
					return ::_read (fSD_, buffer, bufSize);
				#elif	qPlatform_POSIX
					return ::read (fSD_, buffer, bufSize);
				#else
					AssertNotImplemented ();
				#endif
			}
	public:
		void	Write (const Byte* buffer, size_t bufSize) override
			{
				// Must do erorr checking and throw exceptions!!!
				#if		qPlatform_Windows
					int		n	=	::_write (fSD_, buffer, bufSize);
				#elif	qPlatform_POSIX
					int		n	=	::write (fSD_, buffer, bufSize);
				#else
					AssertNotImplemented ();
				#endif
			}
	public:
		void	Bind (const Socket::BindProperties& bindProperties)
			{
				addrinfo hints;
				addrinfo* res = nullptr;
				memset ((void*)&hints, 0, sizeof(hints));
				hints.ai_family = AF_UNSPEC;
			    hints.ai_socktype = SOCK_STREAM;
				hints.ai_flags = AI_PASSIVE;
				string	tmp	=	bindProperties.fHostName.AsUTF8<string> ();	// BAD - SB tstring - or??? not sure what...
				if (getaddrinfo (tmp.c_str (), nullptr, &hints, &res) < 0) {
					// throw
				}
				fSD_ = socket(AF_INET, SOCK_STREAM, 0);

				if (::bind (fSD_, res->ai_addr, res->ai_addrlen) < 0) {
					// throw
				}
			}

	public:
		Socket	Accept ()
			{
				sockaddr	peer;
				memset (&peer, 0, sizeof (peer));

				int	sz	=	sizeof (peer);
				int r = accept(fSD_, &peer, &sz);
// must update Socket object so CTOR also takes (optional) sockaddr (for the peer - mostly to answer  other quesiutona later)
				if (r < 0) {
					// throw...
				}
				return Socket (r);
			}

};

Socket::Socket ()
{
}

Socket::Socket (const Socket& s)
{
}

Socket::Socket (NativeSocket sd)
{
}

Socket::~Socket ()
{
}

const Socket& Socket::operator= (const Socket& s)
{
	return *this;
}

void	Socket::Bind (const BindProperties& bindProperties)
{
	fRep_->Bind (bindProperties);
}

Socket	Socket::Accept ()
{
	return fRep_->Accept ();
}

size_t	Socket::Read (Byte* buffer, size_t bufSize)
{
	return fRep_->Read (buffer, bufSize);
}

void	Socket::Write (const Byte* buffer, size_t bufSize)
{
	fRep_->Write (buffer, bufSize);
}

void	Socket::Close ()
{
	fRep_->Close ();
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkInteractionTestHelper.h>
#include <mitkStandaloneDataStorage.h>
#include <mitkToolManager.h>
#include <mitkGlobalInteraction.h>
#include <mitkDataNode.h>

class mitkToolInteractionTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkToolInteractionTestSuite);
  MITK_TEST(AddToolInteractionTest);
  MITK_TEST(AddToolInteraction_4D_Test);
  CPPUNIT_TEST_SUITE_END();

private:
//  mitk::DataNode::Pointer testPointSetNode;
  mitk::InteractionTestHelper::Pointer m_InteractionTestHelper;
  mitk::DataStorage* m_DataStorage;
  mitk::ToolManager::Pointer m_ToolManager;

public:

  int GetToolIDFromToolName (const std::string& toolName)
  {
    //find tool from toolname
    int numberOfTools = m_ToolManager->GetTools().size();
    int toolId = 0;
    for(; toolId < numberOfTools; ++toolId)
    {
      mitk::Tool* currentTool = m_ToolManager->GetToolById(toolId);
      if(toolName.compare( currentTool->GetNameOfClass() ) == 0)
      {
        return toolId;
      }
    }
    return -1;
  }

  void RunTestWithParameters(const std::string& patientImagePath,
                             const std::string& referenceSegmentationImage,
                             const std::string& toolName,
                             const std::string& interactionPattern)
  {
    //Create test helper to initialize all necessary objects for interaction
    m_InteractionTestHelper = mitk::InteractionTestHelper::New(GetTestDataFilePath(interactionPattern));

    //Use data storage of test helper
    m_DataStorage = m_InteractionTestHelper->GetDataStorage().GetPointer();

    //create ToolManager
    m_ToolManager = mitk::ToolManager::New(m_DataStorage);
    m_ToolManager->InitializeTools();
    m_ToolManager->RegisterClient();//This is needed because there must be at least one registered. Otherwise tools can't be activated.

    //Load patient image
    mitk::Image::Pointer patientImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(patientImagePath));
    CPPUNIT_ASSERT(patientImage.IsNotNull());
    mitk::DataNode::Pointer patientImageNode = mitk::DataNode::New();
    patientImageNode->SetData(patientImage);

    //Activate tool to work with
    int toolID = GetToolIDFromToolName(toolName);
    mitk::Tool* tool = m_ToolManager->GetToolById(toolID);

    CPPUNIT_ASSERT(tool != NULL);

    //Create empty segmentation working image
    mitk::DataNode::Pointer workingImageNode = mitk::DataNode::New();
    const std::string organName = "test";
    mitk::Color color;//actually it dosn't matter which color we are using
    color.SetRed(1);  //but CreateEmptySegmentationNode expects a color parameter
    color.SetGreen(0);
    color.SetBlue(0);
    workingImageNode = tool->CreateEmptySegmentationNode(patientImage, organName, color);

    CPPUNIT_ASSERT(workingImageNode.IsNotNull());
    CPPUNIT_ASSERT(workingImageNode->GetData() != NULL);

    //add images to datastorage
    m_InteractionTestHelper->AddNodeToStorage(patientImageNode);
    m_InteractionTestHelper->AddNodeToStorage(workingImageNode);

    //set reference and working image
    m_ToolManager->SetWorkingData(workingImageNode);
    m_ToolManager->SetReferenceData(patientImageNode);

    //load interaction events
    m_ToolManager->ActivateTool(toolID);

    CPPUNIT_ASSERT(m_ToolManager->GetActiveTool() != NULL);

    //Start Interaction
    m_InteractionTestHelper->PlaybackInteraction();

    //load reference segmentation image
    mitk::Image::Pointer segmentationReferenceImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(referenceSegmentationImage));
    mitk::Image* currentSegmentationImage = dynamic_cast<mitk::Image*>(workingImageNode->GetData());

    CPPUNIT_ASSERT(currentSegmentationImage != NULL);

    //compare reference with interaction result
    MITK_ASSERT_EQUAL(segmentationReferenceImage.GetPointer(), currentSegmentationImage, "Reference equals interaction result." );
  }

  void setUp()
  {
  }

  void tearDown()
  {
    m_ToolManager->ActivateTool(-1);
    m_ToolManager = NULL;
    m_InteractionTestHelper = NULL;
  }

  void AddToolInteractionTest()
  {
    RunTestWithParameters("Pic3D.nrrd", "Segmentation/ReferenceSegmentations/AddTool.nrrd", "AddContourTool", "Segmentation/InteractionPatterns/AddTool.xml");
  }

  void AddToolInteraction_4D_Test()
  {
    m_InteractionTestHelper->SetTimeStep(1);
    RunTestWithParameters("US4DCyl.nrrd", "Segmentation/ReferenceSegmentations/AddTool_4D.nrrd", "AddContourTool", "Segmentation/InteractionPatterns/AddTool_4D.xml");
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkToolInteraction)
<commit_msg>Changed test helper.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkTestingMacros.h"
#include <mitkTestingConfig.h>
#include <mitkTestFixture.h>

#include <mitkIOUtil.h>
#include <mitkInteractionTestHelper.h>
#include <mitkStandaloneDataStorage.h>
#include <mitkToolManager.h>
#include <mitkGlobalInteraction.h>
#include <mitkDataNode.h>

class mitkToolInteractionTestSuite : public mitk::TestFixture
{

  CPPUNIT_TEST_SUITE(mitkToolInteractionTestSuite);
  MITK_TEST(AddToolInteractionTest);
  MITK_TEST(AddToolInteraction_4D_Test);
  CPPUNIT_TEST_SUITE_END();

private:

  mitk::DataStorage* m_DataStorage;
  mitk::ToolManager::Pointer m_ToolManager;

public:

  int GetToolIDFromToolName (const std::string& toolName)
  {
    //find tool from toolname
    int numberOfTools = m_ToolManager->GetTools().size();
    int toolId = 0;
    for(; toolId < numberOfTools; ++toolId)
    {
      mitk::Tool* currentTool = m_ToolManager->GetToolById(toolId);
      if(toolName.compare( currentTool->GetNameOfClass() ) == 0)
      {
        return toolId;
      }
    }
    return -1;
  }

  void RunTestWithParameters(const std::string& patientImagePath,
                             const std::string& referenceSegmentationImage,
                             const std::string& toolName,
                             const std::string& interactionPattern)
  {
    //Create test helper to initialize all necessary objects for interaction
    mitk::InteractionTestHelper m_InteractionTestHelper(GetTestDataFilePath(interactionPattern));

    //Use data storage of test helper
    m_DataStorage = m_InteractionTestHelper.GetDataStorage().GetPointer();

    //create ToolManager
    m_ToolManager = mitk::ToolManager::New(m_DataStorage);
    m_ToolManager->InitializeTools();
    m_ToolManager->RegisterClient();//This is needed because there must be at least one registered. Otherwise tools can't be activated.

    //Load patient image
    mitk::Image::Pointer patientImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(patientImagePath));
    CPPUNIT_ASSERT(patientImage.IsNotNull());
    mitk::DataNode::Pointer patientImageNode = mitk::DataNode::New();
    patientImageNode->SetData(patientImage);

    //Activate tool to work with
    int toolID = GetToolIDFromToolName(toolName);
    mitk::Tool* tool = m_ToolManager->GetToolById(toolID);

    CPPUNIT_ASSERT(tool != NULL);

    //Create empty segmentation working image
    mitk::DataNode::Pointer workingImageNode = mitk::DataNode::New();
    const std::string organName = "test";
    mitk::Color color;//actually it dosn't matter which color we are using
    color.SetRed(1);  //but CreateEmptySegmentationNode expects a color parameter
    color.SetGreen(0);
    color.SetBlue(0);
    workingImageNode = tool->CreateEmptySegmentationNode(patientImage, organName, color);

    CPPUNIT_ASSERT(workingImageNode.IsNotNull());
    CPPUNIT_ASSERT(workingImageNode->GetData() != NULL);

    //add images to datastorage
    m_InteractionTestHelper.AddNodeToStorage(patientImageNode);
    m_InteractionTestHelper.AddNodeToStorage(workingImageNode);

    //set reference and working image
    m_ToolManager->SetWorkingData(workingImageNode);
    m_ToolManager->SetReferenceData(patientImageNode);

    //load interaction events
    m_ToolManager->ActivateTool(toolID);

    CPPUNIT_ASSERT(m_ToolManager->GetActiveTool() != NULL);

    //Start Interaction
    m_InteractionTestHelper.PlaybackInteraction();

    //load reference segmentation image
    mitk::Image::Pointer segmentationReferenceImage = mitk::IOUtil::LoadImage(GetTestDataFilePath(referenceSegmentationImage));
    mitk::Image* currentSegmentationImage = dynamic_cast<mitk::Image*>(workingImageNode->GetData());

    CPPUNIT_ASSERT(currentSegmentationImage != NULL);

    //compare reference with interaction result
    MITK_ASSERT_EQUAL(segmentationReferenceImage.GetPointer(), currentSegmentationImage, "Reference equals interaction result." );
  }

  void setUp()
  {
  }

  void tearDown()
  {
    m_ToolManager->ActivateTool(-1);
    m_ToolManager = NULL;
  }

  void AddToolInteractionTest()
  {
    RunTestWithParameters("Pic3D.nrrd", "Segmentation/ReferenceSegmentations/AddTool.nrrd", "AddContourTool", "Segmentation/InteractionPatterns/AddTool.xml");
  }

  void AddToolInteraction_4D_Test()
  {
    m_InteractionTestHelper->SetTimeStep(1);
    RunTestWithParameters("US4DCyl.nrrd", "Segmentation/ReferenceSegmentations/AddTool_4D.nrrd", "AddContourTool", "Segmentation/InteractionPatterns/AddTool_4D.xml");
  }

};

MITK_TEST_SUITE_REGISTRATION(mitkToolInteraction)
<|endoftext|>


<commit_before>/**
 * @file Cosa/Keypad.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013-2015, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/Keypad.hh"

void
Keypad::Key::on_change(uint16_t value)
{
  uint8_t nr = 0;
  while (value < (uint16_t) pgm_read_word(&m_map[nr])) nr++;
  if (UNLIKELY(nr == m_latest)) return;
  if (nr != 0)
    m_keypad->on_key_down(nr);
  else
    m_keypad->on_key_up(m_latest);
  m_latest = nr;
}

void
Keypad::run()
{
  m_key.sample_request(Event::SAMPLE_COMPLETED_TYPE);
}
<commit_msg>Fixed power management.<commit_after>/**
 * @file Cosa/Keypad.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2013-2015, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Cosa/Keypad.hh"

void
Keypad::Key::on_change(uint16_t value)
{
  uint8_t nr = 0;
  while (value < (uint16_t) pgm_read_word(&m_map[nr])) nr++;
  if (UNLIKELY(nr == m_latest)) return;
  if (nr != 0)
    m_keypad->on_key_down(nr);
  else
    m_keypad->on_key_up(m_latest);
  m_latest = nr;
}

void
Keypad::run()
{
  m_key.powerup();
  m_key.sample_request(Event::SAMPLE_COMPLETED_TYPE);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// STL
#include <memory>
#include <string>

// po6
#include <po6/net/ipaddr.h>
#include <po6/net/location.h>

// e
#include <e/convert.h>
#include <e/timer.h>

// HyperDex
#include "hyperclient/hyperclient.h"

const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                          "11", "12", "13", "14", "15", "16", "17", "18", "19",
                          "20", "21", "22", "23", "24", "25", "26", "27", "28",
                          "29", "30", "31", "32"};

static int
usage();

static void
validate_search(hyperclient* cl,
                uint32_t num,
                const char* space,
                const struct hyperclient_attribute* eq,
                size_t eq_sz,
                const struct hyperclient_range_query* rn,
                size_t rn_sz,
                const char* type);

int
main(int argc, char* argv[])
{
    if (argc != 5)
    {
        return usage();
    }

    const char* ip;
    uint16_t port;
    const char* space = argv[3];
    uint32_t numbers;

    try
    {
        ip = argv[1];
    }
    catch (std::invalid_argument& e)
    {
        std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        port = e::convert::to_uint16_t(argv[2]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The port number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The port number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        numbers = e::convert::to_uint32_t(argv[4]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        hyperclient cl(ip, port);

        for (uint32_t num = 0; num < numbers; ++num)
        {
            hyperclient_attribute attrs[32];

            for (size_t i = 0; i < 32; ++i)
            {
                attrs[i].attr = colnames[i];
                attrs[i].datatype = HYPERDATATYPE_STRING;

                if ((num & (1 << i)))
                {
                    attrs[i].value = "ONE";
                    attrs[i].value_sz = 3;
                }
                else
                {
                    attrs[i].value = "ZERO";
                    attrs[i].value_sz = 4;
                }
            }

            uint64_t numle = htole64(num);
            hyperclient_returncode pstatus;
            int64_t pid = cl.put(space, reinterpret_cast<const char*>(&numle),
                                 sizeof(uint32_t), attrs, 32, &pstatus);

            if (pid < 0)
            {
                std::cerr << "put error " << pstatus << " " << (-1 - pid) << std::endl;
                return EXIT_FAILURE;
            }

            hyperclient_returncode lstatus;
            int64_t lid = cl.loop(-1, &lstatus);

            if (pid != lid)
            {
                std::cerr << "loop error " << pstatus << std::endl;
                return EXIT_FAILURE;
            }
        }

        std::cerr << "Starting searches." << std::endl;
        e::stopwatch stopw;
        stopw.start();

        for (uint32_t num = 0; num < numbers; ++num)
        {
            hyperclient_attribute attrs[32];

            for (size_t i = 0; i < 32; ++i)
            {
                attrs[i].attr = colnames[i];
                attrs[i].datatype = HYPERDATATYPE_STRING;

                if ((num & (1 << i)))
                {
                    attrs[i].value = "ONE";
                    attrs[i].value_sz = 3;
                }
                else
                {
                    attrs[i].value = "ZERO";
                    attrs[i].value_sz = 4;
                }
            }

            validate_search(&cl, num, space, attrs, 32, NULL, 0, "equality");

            hyperclient_range_query rn;
            rn.attr = "num";
            rn.lower = num;
            rn.upper = num + 1;

            validate_search(&cl, num, space, NULL, 0, &rn, 1, "range");
        }

        std::cerr << "test took " << stopw.peek() << " nanoseconds for " << numbers << " searches" << std::endl;
    }
    catch (po6::error& e)
    {
        std::cerr << "There was a system error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::runtime_error& e)
    {
        std::cerr << "There was a runtime error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::bad_alloc& e)
    {
        std::cerr << "There was a memory allocation error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::exception& e)
    {
        std::cerr << "There was a generic error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

int
usage()
{
    std::cerr << "Usage:  binary <coordinator ip> <coordinator port> <space name> <numbers>\n"
              << "This will create <numbers> points whose key is a number [0, <numbers>) and "
              << "then perform searches over the bits of the number.  The space should have 32 "
              << "secondary dimensions so that all bits of a number may be stored."
              << std::endl;
    return EXIT_FAILURE;
}

void
validate_search(hyperclient* cl,
                uint32_t num,
                const char* space,
                const struct hyperclient_attribute* eq,
                size_t eq_sz,
                const struct hyperclient_range_query* rn,
                size_t rn_sz,
                const char* type)
{
    hyperclient_returncode sstatus;
    hyperclient_attribute* attrs;
    size_t attrs_sz;
    int64_t sid = cl->search(space, eq, eq_sz, rn, rn_sz, &sstatus, &attrs, &attrs_sz);

    if (sid < 0)
    {
        std::cerr << "invalid " << type << " search returns(" << sid << ", " << sstatus << ")" << std::endl;
        abort();
    }

    hyperclient_returncode lstatus;
    int64_t lid = cl->loop(-1, &lstatus);

    if (lid < 0)
    {
        std::cerr << type << " search's loop returns(" << lid << ", " << lstatus << ")" << std::endl;
        abort();
    }

    if (lid != sid)
    {
        std::cerr << "for the " << type << " search, the ids do not match " << sid << " " << lid << std::endl;
        abort();
    }

    if (sstatus != HYPERCLIENT_SUCCESS)
    {
        std::cerr << "for the " << type << " search, the first loop did not return a result." << std::endl;
        abort();
    }

    if (attrs_sz != 33)
    {
        std::cerr << "for the " << type << " search, there are not 1+32 attributes" << std::endl;
        abort();
    }

    if (strcmp(attrs[0].attr, "num") != 0)
    {
        std::cerr << "for the " << type << " search, attribute 0 (the key) is not named num" << std::endl;
        abort();
    }

    if (attrs[0].value_sz != sizeof(num)
            || memcmp(&num, attrs[0].value, sizeof(num)))
    {
        std::cerr << "for the " << type << " search, attribute 0 (the key) != " << num << std::endl;
        abort();
    }

    if (memcmp(&num, attrs[0].value, std::min(sizeof(num), attrs[0].value_sz)) != 0)
    {
        std::cerr << "for the " << type << " search, the result's key does not match" << std::endl;
        abort();
    }

    for (size_t i = 0; i < 32; ++i)
    {
        if (strcmp(attrs[i + 1].attr, colnames[i]) != 0)
        {
            std::cerr << "for the " << type << " search, secondary attribute " << i << " is not named " << colnames[i] << std::endl;
            abort();
        }

        if ((num & (1 << i))
                && !(attrs[i + 1].value_sz == 3 && memcmp(attrs[i + 1].value, "ONE", 3) == 0))
        {
            std::cerr << "for the " << type << " search, secondary attribute " << i << " != ONE" << std::endl;
            abort();
        }
        else if (!(num & (1 << i))
                && !(attrs[i + 1].value_sz == 4 && memcmp(attrs[i + 1].value, "ZERO", 4) == 0))
        {
            std::cerr << "for the " << type << " search, secondary attribute " << i << " != ZERO" << std::endl;
            abort();
        }
    }

    hyperclient_destroy_attrs(attrs, attrs_sz);

    lid = cl->loop(-1, &lstatus);

    if (lid < 0)
    {
        std::cerr << type << " search's 2nd loop returns(" << lid << ", " << lstatus << ")" << std::endl;
        abort();
    }

    if (lid != sid)
    {
        std::cerr << "for the " << type << " search's 2nd loop, the ids do not match " << sid << " " << lid << std::endl;
        abort();
    }

    if (sstatus != HYPERCLIENT_SEARCHDONE)
    {
        std::cerr << type << " search's 2nd loop is not a SEARCHDONE message";
        abort();
    }
}
<commit_msg>Don't use non-portable endianness in binary-test.cc<commit_after>// Copyright (c) 2011, Cornell University
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of HyperDex nor the names of its contributors may be
//       used to endorse or promote products derived from this software without
//       specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// STL
#include <memory>
#include <string>

// po6
#include <po6/net/ipaddr.h>
#include <po6/net/location.h>

// e
#include <e/convert.h>
#include <e/endian.h>
#include <e/timer.h>

// HyperDex
#include "hyperclient/hyperclient.h"

const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                          "11", "12", "13", "14", "15", "16", "17", "18", "19",
                          "20", "21", "22", "23", "24", "25", "26", "27", "28",
                          "29", "30", "31", "32"};

static int
usage();

static void
validate_search(hyperclient* cl,
                uint32_t num,
                const char* space,
                const struct hyperclient_attribute* eq,
                size_t eq_sz,
                const struct hyperclient_range_query* rn,
                size_t rn_sz,
                const char* type);

int
main(int argc, char* argv[])
{
    if (argc != 5)
    {
        return usage();
    }

    const char* ip;
    uint16_t port;
    const char* space = argv[3];
    uint32_t numbers;

    try
    {
        ip = argv[1];
    }
    catch (std::invalid_argument& e)
    {
        std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        port = e::convert::to_uint16_t(argv[2]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The port number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The port number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        numbers = e::convert::to_uint32_t(argv[4]);
    }
    catch (std::domain_error& e)
    {
        std::cerr << "The number must be an integer." << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::out_of_range& e)
    {
        std::cerr << "The number must be suitably small." << std::endl;
        return EXIT_FAILURE;
    }

    try
    {
        hyperclient cl(ip, port);

        for (uint32_t num = 0; num < numbers; ++num)
        {
            hyperclient_attribute attrs[32];

            for (size_t i = 0; i < 32; ++i)
            {
                attrs[i].attr = colnames[i];
                attrs[i].datatype = HYPERDATATYPE_STRING;

                if ((num & (1 << i)))
                {
                    attrs[i].value = "ONE";
                    attrs[i].value_sz = 3;
                }
                else
                {
                    attrs[i].value = "ZERO";
                    attrs[i].value_sz = 4;
                }
            }

            uint8_t bufle[sizeof(uint64_t)];
            e::pack64le(num, bufle);
            hyperclient_returncode pstatus;
            int64_t pid = cl.put(space, reinterpret_cast<const char*>(bufle), sizeof(uint32_t), attrs, 32, &pstatus);

            if (pid < 0)
            {
                std::cerr << "put error " << pstatus << " " << (-1 - pid) << std::endl;
                return EXIT_FAILURE;
            }

            hyperclient_returncode lstatus;
            int64_t lid = cl.loop(-1, &lstatus);

            if (pid != lid)
            {
                std::cerr << "loop error " << pstatus << std::endl;
                return EXIT_FAILURE;
            }
        }

        std::cerr << "Starting searches." << std::endl;
        e::stopwatch stopw;
        stopw.start();

        for (uint32_t num = 0; num < numbers; ++num)
        {
            hyperclient_attribute attrs[32];

            for (size_t i = 0; i < 32; ++i)
            {
                attrs[i].attr = colnames[i];
                attrs[i].datatype = HYPERDATATYPE_STRING;

                if ((num & (1 << i)))
                {
                    attrs[i].value = "ONE";
                    attrs[i].value_sz = 3;
                }
                else
                {
                    attrs[i].value = "ZERO";
                    attrs[i].value_sz = 4;
                }
            }

            validate_search(&cl, num, space, attrs, 32, NULL, 0, "equality");

            hyperclient_range_query rn;
            rn.attr = "num";
            rn.lower = num;
            rn.upper = num + 1;

            validate_search(&cl, num, space, NULL, 0, &rn, 1, "range");
        }

        std::cerr << "test took " << stopw.peek() << " nanoseconds for " << numbers << " searches" << std::endl;
    }
    catch (po6::error& e)
    {
        std::cerr << "There was a system error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::runtime_error& e)
    {
        std::cerr << "There was a runtime error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::bad_alloc& e)
    {
        std::cerr << "There was a memory allocation error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    catch (std::exception& e)
    {
        std::cerr << "There was a generic error:  " << e.what() << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

int
usage()
{
    std::cerr << "Usage:  binary <coordinator ip> <coordinator port> <space name> <numbers>\n"
              << "This will create <numbers> points whose key is a number [0, <numbers>) and "
              << "then perform searches over the bits of the number.  The space should have 32 "
              << "secondary dimensions so that all bits of a number may be stored."
              << std::endl;
    return EXIT_FAILURE;
}

void
validate_search(hyperclient* cl,
                uint32_t num,
                const char* space,
                const struct hyperclient_attribute* eq,
                size_t eq_sz,
                const struct hyperclient_range_query* rn,
                size_t rn_sz,
                const char* type)
{
    hyperclient_returncode sstatus;
    hyperclient_attribute* attrs;
    size_t attrs_sz;
    int64_t sid = cl->search(space, eq, eq_sz, rn, rn_sz, &sstatus, &attrs, &attrs_sz);

    if (sid < 0)
    {
        std::cerr << "invalid " << type << " search returns(" << sid << ", " << sstatus << ")" << std::endl;
        abort();
    }

    hyperclient_returncode lstatus;
    int64_t lid = cl->loop(-1, &lstatus);

    if (lid < 0)
    {
        std::cerr << type << " search's loop returns(" << lid << ", " << lstatus << ")" << std::endl;
        abort();
    }

    if (lid != sid)
    {
        std::cerr << "for the " << type << " search, the ids do not match " << sid << " " << lid << std::endl;
        abort();
    }

    if (sstatus != HYPERCLIENT_SUCCESS)
    {
        std::cerr << "for the " << type << " search, the first loop did not return a result." << std::endl;
        abort();
    }

    if (attrs_sz != 33)
    {
        std::cerr << "for the " << type << " search, there are not 1+32 attributes" << std::endl;
        abort();
    }

    if (strcmp(attrs[0].attr, "num") != 0)
    {
        std::cerr << "for the " << type << " search, attribute 0 (the key) is not named num" << std::endl;
        abort();
    }

    if (attrs[0].value_sz != sizeof(num)
            || memcmp(&num, attrs[0].value, sizeof(num)))
    {
        std::cerr << "for the " << type << " search, attribute 0 (the key) != " << num << std::endl;
        abort();
    }

    if (memcmp(&num, attrs[0].value, std::min(sizeof(num), attrs[0].value_sz)) != 0)
    {
        std::cerr << "for the " << type << " search, the result's key does not match" << std::endl;
        abort();
    }

    for (size_t i = 0; i < 32; ++i)
    {
        if (strcmp(attrs[i + 1].attr, colnames[i]) != 0)
        {
            std::cerr << "for the " << type << " search, secondary attribute " << i << " is not named " << colnames[i] << std::endl;
            abort();
        }

        if ((num & (1 << i))
                && !(attrs[i + 1].value_sz == 3 && memcmp(attrs[i + 1].value, "ONE", 3) == 0))
        {
            std::cerr << "for the " << type << " search, secondary attribute " << i << " != ONE" << std::endl;
            abort();
        }
        else if (!(num & (1 << i))
                && !(attrs[i + 1].value_sz == 4 && memcmp(attrs[i + 1].value, "ZERO", 4) == 0))
        {
            std::cerr << "for the " << type << " search, secondary attribute " << i << " != ZERO" << std::endl;
            abort();
        }
    }

    hyperclient_destroy_attrs(attrs, attrs_sz);

    lid = cl->loop(-1, &lstatus);

    if (lid < 0)
    {
        std::cerr << type << " search's 2nd loop returns(" << lid << ", " << lstatus << ")" << std::endl;
        abort();
    }

    if (lid != sid)
    {
        std::cerr << "for the " << type << " search's 2nd loop, the ids do not match " << sid << " " << lid << std::endl;
        abort();
    }

    if (sstatus != HYPERCLIENT_SEARCHDONE)
    {
        std::cerr << type << " search's 2nd loop is not a SEARCHDONE message";
        abort();
    }
}
<|endoftext|>


<commit_before>#include "location.h"
#include "world.h"
#include "state.h"
#include "a_star.h"

#include <iostream>

using namespace std;

int main(){
	/* Test location class */
	Location loc(1, 3);
	loc.print();

	/* Test world class */
	int i,j;
	Matrix map;
	vector<int> tmp;
	for (i = 0; i < 10; i++){
		tmp.clear();

		for (j = 0; j < 10; j++) {
			tmp.push_back(EMPTY);
		}

		map.push_back(tmp);
	}

	vector<Location> boxes;
	vector<Location> targets;
	for (i = 1; i < 5; i++) {
		boxes.push_back(Location(i,i));
		targets.push_back(Location(i+1,i));
		map.at(i).at(i) = BOX;
		map.at(i+1).at(i) = TARGET;
	}

	map.at(1).at(5) = ROBOT;

	World world(&map, new Location(1,1), &boxes, &targets);
	world.printWorld();
	//world.printConfig();

	State state(world);
	state.printState("Starting");

	//AStar astar(state);
	//cout << "Output of AStar::printClosed()" << endl;
	//astar.printClosed();

	//astar.solve();
	//vector<State> solution = astar.solve();
	//astar.printSolution();

  	cout << "Hello World!" << endl;
  return 1;
}
<commit_msg>updated helloworld file<commit_after>#include "location.h"
#include "world.h"
#include "state.h"
#include "a_star.h"

#include <iostream>

using namespace std;

int main(){
	/* Test location class */
	Location loc(1, 3);
	loc.print();

	/* Test world class */
	int i,j;
	Matrix map;
	vector<int> tmp;
	for (i = 0; i < 10; i++){
		tmp.clear();

		for (j = 0; j < 10; j++) {
			tmp.push_back(EMPTY);
		}

		map.push_back(tmp);
	}

	vector<Location> boxes;
	vector<Location> targets;
	for (i = 1; i < 5; i++) {
		boxes.push_back(Location(i,i));
		targets.push_back(Location(i+1,i));
		map.at(i).at(i) = BOX;
		map.at(i+1).at(i) = TARGET;
	}

	map.at(1).at(5) = ROBOT;

	World world(&map, new Location(1,8), &boxes, &targets);
	world.printWorld();
	//world.printConfig();

	State state(world);
	state.printState("Starting");

	AStar astar(state);
	cout << "Output of AStar::printClosed()" << endl;
	astar.printClosed();

	astar.solve();
	//vector<State> solution = astar.solve();
	//astar.printSolution();

  	cout << "Hello World!" << endl;
  return 1;
}
<|endoftext|>


<commit_before>#include "darkfeed/util/hashing.hpp"
#include <gtest/gtest.h>

using namespace darkfeed;

TEST(CRC32C, SliceBy8Empty)
{
    const char *empty = "";
    unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};
    std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, empty, 0));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32C, SliceBy8Alphabet)
{
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, alphabet, 26));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

#ifdef HAS_SSE_4_2

TEST(CRC32C, IntelEmpty)
{
    const char *empty = "";
    unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};
    std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, empty, 0));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32C, IntelAlphabet)
{
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, alphabet, 26));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}
#endif

TEST(CRC32CCStrHasher, Alphabet)
{
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    CRC32CCStrHasher hasher;
    std::uint32_t crc = hasher(alphabet);
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32CStrHasher, Alphabet)
{
    std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    CRC32CStrHasher hasher;
    std::uint32_t crc = hasher(alphabet);
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}
<commit_msg>[cpp] Add test for hardware accelerated (SSE4.3) CRC32C symbol hasher<commit_after>#include "darkfeed/util/hashing.hpp"
#include <gtest/gtest.h>

using namespace darkfeed;

TEST(CRC32C, SliceBy8Empty)
{
    const char *empty = "";
    unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};
    std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, empty, 0));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32C, SliceBy8Alphabet)
{
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    std::uint32_t crc = CRC32C_FINISH(crc32cSlicingBy8(CRC32C_INIT, alphabet, 26));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

#ifdef HAS_SSE_4_2

TEST(CRC32C, IntelEmpty)
{
    const char *empty = "";
    unsigned char expected_arr[] = {0x00, 0x00, 0x00, 0x00};
    std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, empty, 0));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32C, IntelAlphabet)
{
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    std::uint32_t crc = CRC32C_FINISH(crc32cIntelC(CRC32C_INIT, alphabet, 26));
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}
#endif

TEST(CRC32CCStrHasher, Alphabet)
{
    const char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    CRC32CCStrHasher hasher;
    std::uint32_t crc = hasher(alphabet);
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32CStrHasher, Alphabet)
{
    std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
    unsigned char expected_arr[] = {0x25, 0xef, 0xe6, 0x9e};
    CRC32CStrHasher hasher;
    std::uint32_t crc = hasher(alphabet);
    ASSERT_EQ(*(std::uint32_t *) expected_arr, crc);
}

TEST(CRC32CSymHasher, BaseCase)
{
    Symbol s(MIC::XNYS, "BRK.PR.A");
    ASSERT_STREQ("BRK", s.root);
    ASSERT_EQ(IssueType::preferred, s.issue_type);
    ASSERT_EQ('A', s.series);
    CRC32CSymHasher h;
    auto h1 = h(s);
    auto sc = s;
    auto h2 = h(sc);
    ASSERT_EQ(h1, h2);
    Symbol s2(MIC::XNYS, "BRK.A");
    ASSERT_STREQ("BRK", s2.root);
    ASSERT_EQ(IssueType::normal, s2.issue_type);
    ASSERT_EQ('A', s2.series);
    auto h3 = h(s2);
    ASSERT_NE(h1, h3);
}
<|endoftext|>