<commit_before>// Copyright (c) 2012 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.

#include "chrome/nacl/nacl_validation_query.h"

#include "base/logging.h"
#include "crypto/nss_util.h"
#include "chrome/nacl/nacl_validation_db.h"
#include "native_client/src/trusted/validator/validation_cache.h"

NaClValidationQueryContext::NaClValidationQueryContext(
    NaClValidationDB* db,
    const std::string& profile_key,
    const std::string& nacl_version)
    : db_(db),
      profile_key_(profile_key),
      nacl_version_(nacl_version) {

  // Sanity checks.
  CHECK(profile_key.length() >= 8);
  CHECK(nacl_version.length() >= 4);
}

NaClValidationQuery* NaClValidationQueryContext::CreateQuery() {
  NaClValidationQuery* query = new NaClValidationQuery(db_, profile_key_);
  // Changing the version effectively invalidates existing hashes.
  query->AddData(nacl_version_);
  return query;
}

NaClValidationQuery::NaClValidationQuery(NaClValidationDB* db,
                                         const std::string& profile_key)
    : state_(READY),
      hasher_(crypto::HMAC::SHA256),
      db_(db),
      buffer_length_(0) {
  // Without this line on Linux, HMAC::Init will instantiate a singleton that
  // in turn attempts to open a file.  Disabling this behavior avoids a ~70 ms
  // stall the first time HMAC is used.
  // This function is also called in nacl_helper_linux.cc, but nacl_helper may
  // not be used in all cases.
  // TODO(ncbray) remove when nacl_helper becomes the only code path.
  // http://code.google.com/p/chromium/issues/detail?id=118263
#if defined(OS_LINUX)
  crypto::ForceNSSNoDBInit();
#endif
  CHECK(hasher_.Init(profile_key));
}

void NaClValidationQuery::AddData(const char* data, size_t length) {
  CHECK(state_ == READY);
  CHECK(buffer_length_ >= 0);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  // Chrome's HMAC class doesn't support incremental signing.  Work around
  // this by using a (small) temporary buffer to accumulate data.
  // Check if there is space in the buffer.
  if (buffer_length_ + kDigestLength > (int) sizeof(buffer_)) {
    // Hash the buffer to make space.
    CompressBuffer();
  }
  // Hash the input data into the buffer.  Assumes that sizeof(buffer_) >=
  // kDigestLength * 2 (the buffer can store at least two digests.)
  CHECK(hasher_.Sign(base::StringPiece(data, length),
                     reinterpret_cast<unsigned char*>(buffer_ + buffer_length_),
                     kDigestLength));
  buffer_length_ += kDigestLength;
}

void NaClValidationQuery::AddData(const unsigned char* data, size_t length) {
  AddData(reinterpret_cast<const char*>(data), length);
}

void NaClValidationQuery::AddData(const base::StringPiece& data) {
  AddData(data.data(), data.length());
}

int NaClValidationQuery::QueryKnownToValidate() {
  CHECK(state_ == READY);
  // It is suspicious if we have less than a digest's worth of data.
  CHECK(buffer_length_ >= kDigestLength);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  state_ = GET_CALLED;
  // Ensure the buffer contains only one digest worth of data.
  CompressBuffer();
  return db_->QueryKnownToValidate(std::string(buffer_, buffer_length_));
}

void NaClValidationQuery::SetKnownToValidate() {
  CHECK(state_ == GET_CALLED);
  CHECK(buffer_length_ == kDigestLength);
  state_ = SET_CALLED;
  db_->SetKnownToValidate(std::string(buffer_, buffer_length_));
}

// Reduce the size of the data in the buffer by hashing it and writing it back
// to the buffer.
void NaClValidationQuery::CompressBuffer() {
  // Calculate the digest into a temp buffer.  It is likely safe to calculate it
  // directly back into the buffer, but this is an "accidental" semantic we're
  // avoiding depending on.
  unsigned char temp[kDigestLength];
  CHECK(hasher_.Sign(base::StringPiece(buffer_, buffer_length_), temp,
                     kDigestLength));
  memcpy(buffer_, temp, kDigestLength);
  buffer_length_ = kDigestLength;
}

// OO wrappers

static void* CreateQuery(void* handle) {
  return static_cast<NaClValidationQueryContext*>(handle)->CreateQuery();
}

static void AddData(void* query, const uint8* data, size_t length) {
  static_cast<NaClValidationQuery*>(query)->AddData(data, length);
}

static int QueryKnownToValidate(void* query) {
  return static_cast<NaClValidationQuery*>(query)->QueryKnownToValidate();
}

static void SetKnownToValidate(void* query) {
  static_cast<NaClValidationQuery*>(query)->SetKnownToValidate();
}

static void DestroyQuery(void* query) {
  delete static_cast<NaClValidationQuery*>(query);
}

struct NaClValidationCache* CreateValidationCache(
    NaClValidationDB* db, const std::string& profile_key,
    const std::string& nacl_version) {
  NaClValidationCache* cache =
      static_cast<NaClValidationCache*>(malloc(sizeof(NaClValidationCache)));
  // Make sure any fields introduced in a cross-repo change are zeroed.
  memset(cache, 0, sizeof(*cache));
  cache->handle = new NaClValidationQueryContext(db, profile_key, nacl_version);
  cache->CreateQuery = CreateQuery;
  cache->AddData = AddData;
  cache->QueryKnownToValidate = QueryKnownToValidate;
  cache->SetKnownToValidate = SetKnownToValidate;
  cache->DestroyQuery = DestroyQuery;
  return cache;
}
<commit_msg>Fix linux build with use_openssl=1 in GYP_DEFINES<commit_after>// Copyright (c) 2012 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.

#include "chrome/nacl/nacl_validation_query.h"

#include "base/logging.h"
#include "crypto/nss_util.h"
#include "chrome/nacl/nacl_validation_db.h"
#include "native_client/src/trusted/validator/validation_cache.h"

NaClValidationQueryContext::NaClValidationQueryContext(
    NaClValidationDB* db,
    const std::string& profile_key,
    const std::string& nacl_version)
    : db_(db),
      profile_key_(profile_key),
      nacl_version_(nacl_version) {

  // Sanity checks.
  CHECK(profile_key.length() >= 8);
  CHECK(nacl_version.length() >= 4);
}

NaClValidationQuery* NaClValidationQueryContext::CreateQuery() {
  NaClValidationQuery* query = new NaClValidationQuery(db_, profile_key_);
  // Changing the version effectively invalidates existing hashes.
  query->AddData(nacl_version_);
  return query;
}

NaClValidationQuery::NaClValidationQuery(NaClValidationDB* db,
                                         const std::string& profile_key)
    : state_(READY),
      hasher_(crypto::HMAC::SHA256),
      db_(db),
      buffer_length_(0) {
  // Without this line on Linux, HMAC::Init will instantiate a singleton that
  // in turn attempts to open a file.  Disabling this behavior avoids a ~70 ms
  // stall the first time HMAC is used.
  // This function is also called in nacl_helper_linux.cc, but nacl_helper may
  // not be used in all cases.
  // TODO(ncbray) remove when nacl_helper becomes the only code path.
  // http://code.google.com/p/chromium/issues/detail?id=118263
#if defined(USE_NSS)
  crypto::ForceNSSNoDBInit();
#endif
  CHECK(hasher_.Init(profile_key));
}

void NaClValidationQuery::AddData(const char* data, size_t length) {
  CHECK(state_ == READY);
  CHECK(buffer_length_ >= 0);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  // Chrome's HMAC class doesn't support incremental signing.  Work around
  // this by using a (small) temporary buffer to accumulate data.
  // Check if there is space in the buffer.
  if (buffer_length_ + kDigestLength > (int) sizeof(buffer_)) {
    // Hash the buffer to make space.
    CompressBuffer();
  }
  // Hash the input data into the buffer.  Assumes that sizeof(buffer_) >=
  // kDigestLength * 2 (the buffer can store at least two digests.)
  CHECK(hasher_.Sign(base::StringPiece(data, length),
                     reinterpret_cast<unsigned char*>(buffer_ + buffer_length_),
                     kDigestLength));
  buffer_length_ += kDigestLength;
}

void NaClValidationQuery::AddData(const unsigned char* data, size_t length) {
  AddData(reinterpret_cast<const char*>(data), length);
}

void NaClValidationQuery::AddData(const base::StringPiece& data) {
  AddData(data.data(), data.length());
}

int NaClValidationQuery::QueryKnownToValidate() {
  CHECK(state_ == READY);
  // It is suspicious if we have less than a digest's worth of data.
  CHECK(buffer_length_ >= kDigestLength);
  CHECK(buffer_length_ <= (int) sizeof(buffer_));
  state_ = GET_CALLED;
  // Ensure the buffer contains only one digest worth of data.
  CompressBuffer();
  return db_->QueryKnownToValidate(std::string(buffer_, buffer_length_));
}

void NaClValidationQuery::SetKnownToValidate() {
  CHECK(state_ == GET_CALLED);
  CHECK(buffer_length_ == kDigestLength);
  state_ = SET_CALLED;
  db_->SetKnownToValidate(std::string(buffer_, buffer_length_));
}

// Reduce the size of the data in the buffer by hashing it and writing it back
// to the buffer.
void NaClValidationQuery::CompressBuffer() {
  // Calculate the digest into a temp buffer.  It is likely safe to calculate it
  // directly back into the buffer, but this is an "accidental" semantic we're
  // avoiding depending on.
  unsigned char temp[kDigestLength];
  CHECK(hasher_.Sign(base::StringPiece(buffer_, buffer_length_), temp,
                     kDigestLength));
  memcpy(buffer_, temp, kDigestLength);
  buffer_length_ = kDigestLength;
}

// OO wrappers

static void* CreateQuery(void* handle) {
  return static_cast<NaClValidationQueryContext*>(handle)->CreateQuery();
}

static void AddData(void* query, const uint8* data, size_t length) {
  static_cast<NaClValidationQuery*>(query)->AddData(data, length);
}

static int QueryKnownToValidate(void* query) {
  return static_cast<NaClValidationQuery*>(query)->QueryKnownToValidate();
}

static void SetKnownToValidate(void* query) {
  static_cast<NaClValidationQuery*>(query)->SetKnownToValidate();
}

static void DestroyQuery(void* query) {
  delete static_cast<NaClValidationQuery*>(query);
}

struct NaClValidationCache* CreateValidationCache(
    NaClValidationDB* db, const std::string& profile_key,
    const std::string& nacl_version) {
  NaClValidationCache* cache =
      static_cast<NaClValidationCache*>(malloc(sizeof(NaClValidationCache)));
  // Make sure any fields introduced in a cross-repo change are zeroed.
  memset(cache, 0, sizeof(*cache));
  cache->handle = new NaClValidationQueryContext(db, profile_key, nacl_version);
  cache->CreateQuery = CreateQuery;
  cache->AddData = AddData;
  cache->QueryKnownToValidate = QueryKnownToValidate;
  cache->SetKnownToValidate = SetKnownToValidate;
  cache->DestroyQuery = DestroyQuery;
  return cache;
}
<|endoftext|>


<commit_before>#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/impl.h"
#include "yaml-cpp/node/convert.h"
#include "yaml-cpp/node/iterator.h"
#include "yaml-cpp/node/detail/impl.h"

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(NodeTest, SimpleScalar) {
  YAML::Node node = YAML::Node("Hello, World!");
  EXPECT_TRUE(node.IsScalar());
  EXPECT_EQ("Hello, World!", node.as<std::string>());
}

TEST(NodeTest, IntScalar) {
  YAML::Node node = YAML::Node(15);
  EXPECT_TRUE(node.IsScalar());
  EXPECT_EQ(15, node.as<int>());
}

TEST(NodeTest, SimpleAppendSequence) {
  YAML::Node node;
  node.push_back(10);
  node.push_back("foo");
  node.push_back("monkey");
  EXPECT_TRUE(node.IsSequence());
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(10, node[0].as<int>());
  EXPECT_EQ("foo", node[1].as<std::string>());
  EXPECT_EQ("monkey", node[2].as<std::string>());
  EXPECT_TRUE(node.IsSequence());
}

TEST(NodeTest, SimpleAssignSequence) {
  YAML::Node node;
  node[0] = 10;
  node[1] = "foo";
  node[2] = "monkey";
  EXPECT_TRUE(node.IsSequence());
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(10, node[0].as<int>());
  EXPECT_EQ("foo", node[1].as<std::string>());
  EXPECT_EQ("monkey", node[2].as<std::string>());
  EXPECT_TRUE(node.IsSequence());
}

TEST(NodeTest, SimpleMap) {
  YAML::Node node;
  node["key"] = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ("value", node["key"].as<std::string>());
  EXPECT_EQ(1, node.size());
}

TEST(NodeTest, MapWithUndefinedValues) {
  YAML::Node node;
  node["key"] = "value";
  node["undefined"];
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ("value", node["key"].as<std::string>());
  EXPECT_EQ(1, node.size());

  node["undefined"] = "monkey";
  EXPECT_EQ("monkey", node["undefined"].as<std::string>());
  EXPECT_EQ(2, node.size());
}

TEST(NodeTest, MapIteratorWithUndefinedValues) {
  YAML::Node node;
  node["key"] = "value";
  node["undefined"];

  std::size_t count = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it)
    count++;
  EXPECT_EQ(1, count);
}

TEST(NodeTest, SimpleSubkeys) {
  YAML::Node node;
  node["device"]["udid"] = "12345";
  node["device"]["name"] = "iPhone";
  node["device"]["os"] = "4.0";
  node["username"] = "monkey";
  EXPECT_EQ("12345", node["device"]["udid"].as<std::string>());
  EXPECT_EQ("iPhone", node["device"]["name"].as<std::string>());
  EXPECT_EQ("4.0", node["device"]["os"].as<std::string>());
  EXPECT_EQ("monkey", node["username"].as<std::string>());
}

TEST(NodeTest, StdVector) {
  std::vector<int> primes;
  primes.push_back(2);
  primes.push_back(3);
  primes.push_back(5);
  primes.push_back(7);
  primes.push_back(11);
  primes.push_back(13);

  YAML::Node node;
  node["primes"] = primes;
  EXPECT_EQ(primes, node["primes"].as<std::vector<int> >());
}

TEST(NodeTest, StdList) {
  std::list<int> primes;
  primes.push_back(2);
  primes.push_back(3);
  primes.push_back(5);
  primes.push_back(7);
  primes.push_back(11);
  primes.push_back(13);

  YAML::Node node;
  node["primes"] = primes;
  EXPECT_EQ(primes, node["primes"].as<std::list<int> >());
}

TEST(NodeTest, StdMap) {
  std::map<int, int> squares;
  squares[0] = 0;
  squares[1] = 1;
  squares[2] = 4;
  squares[3] = 9;
  squares[4] = 16;

  YAML::Node node;
  node["squares"] = squares;
  std::map<int, int> actualSquares = node["squares"].as<std::map<int, int> >();
  EXPECT_EQ(squares, actualSquares);
}

TEST(NodeTest, StdPair) {
  std::pair<int, std::string> p;
  p.first = 5;
  p.second = "five";

  YAML::Node node;
  node["pair"] = p;
  std::pair<int, std::string> actualP =
      node["pair"].as<std::pair<int, std::string> >();
  EXPECT_EQ(p, actualP);
}

TEST(NodeTest, SimpleAlias) {
  YAML::Node node;
  node["foo"] = "value";
  node["bar"] = node["foo"];
  EXPECT_EQ("value", node["foo"].as<std::string>());
  EXPECT_EQ("value", node["bar"].as<std::string>());
  EXPECT_EQ(node["bar"], node["foo"]);
  EXPECT_EQ(2, node.size());
}

TEST(NodeTest, AliasAsKey) {
  YAML::Node node;
  node["foo"] = "value";
  YAML::Node value = node["foo"];
  node[value] = "foo";
  EXPECT_EQ("value", node["foo"].as<std::string>());
  EXPECT_EQ("foo", node[value].as<std::string>());
  EXPECT_EQ("foo", node["value"].as<std::string>());
  EXPECT_EQ(2, node.size());
}

TEST(NodeTest, SelfReferenceSequence) {
  YAML::Node node;
  node[0] = node;
  EXPECT_TRUE(node.IsSequence());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ(node, node[0]);
  EXPECT_EQ(node, node[0][0]);
  EXPECT_EQ(node[0], node[0][0]);
}

TEST(NodeTest, ValueSelfReferenceMap) {
  YAML::Node node;
  node["key"] = node;
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ(node, node["key"]);
  EXPECT_EQ(node, node["key"]["key"]);
  EXPECT_EQ(node["key"], node["key"]["key"]);
}

TEST(NodeTest, KeySelfReferenceMap) {
  YAML::Node node;
  node[node] = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ("value", node[node].as<std::string>());
}

TEST(NodeTest, SelfReferenceMap) {
  YAML::Node node;
  node[node] = node;
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ(node, node[node]);
  EXPECT_EQ(node, node[node][node]);
  EXPECT_EQ(node[node], node[node][node]);
}

TEST(NodeTest, TempMapVariable) {
  YAML::Node node;
  YAML::Node tmp = node["key"];
  tmp = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ("value", node["key"].as<std::string>());
}

TEST(NodeTest, TempMapVariableAlias) {
  YAML::Node node;
  YAML::Node tmp = node["key"];
  tmp = node["other"];
  node["other"] = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(2, node.size());
  EXPECT_EQ("value", node["key"].as<std::string>());
  EXPECT_EQ("value", node["other"].as<std::string>());
  EXPECT_EQ(node["key"], node["other"]);
}

TEST(NodeTest, Bool) {
  YAML::Node node;
  node[true] = false;
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(false, node[true].as<bool>());
}

TEST(NodeTest, AutoBoolConversion) {
  YAML::Node node;
  node["foo"] = "bar";
  EXPECT_TRUE(static_cast<bool>(node["foo"]));
  EXPECT_TRUE(!node["monkey"]);
  EXPECT_TRUE(!!node["foo"]);
}

TEST(NodeTest, FloatingPrecision) {
  const double x = 0.123456789;
  YAML::Node node = YAML::Node(x);
  EXPECT_EQ(x, node.as<double>());
}

TEST(NodeTest, SpaceChar) {
  YAML::Node node = YAML::Node(' ');
  EXPECT_EQ(' ', node.as<char>());
}

TEST(NodeTest, CloneNull) {
  Node node;
  Node clone = Clone(node);
  EXPECT_EQ(NodeType::Null, clone.Type());
}
}
}
<commit_msg>Disable warning:<commit_after>#include "yaml-cpp/node/node.h"
#include "yaml-cpp/node/impl.h"
#include "yaml-cpp/node/convert.h"
#include "yaml-cpp/node/iterator.h"
#include "yaml-cpp/node/detail/impl.h"

#include "gtest/gtest.h"

namespace YAML {
namespace {
TEST(NodeTest, SimpleScalar) {
  YAML::Node node = YAML::Node("Hello, World!");
  EXPECT_TRUE(node.IsScalar());
  EXPECT_EQ("Hello, World!", node.as<std::string>());
}

TEST(NodeTest, IntScalar) {
  YAML::Node node = YAML::Node(15);
  EXPECT_TRUE(node.IsScalar());
  EXPECT_EQ(15, node.as<int>());
}

TEST(NodeTest, SimpleAppendSequence) {
  YAML::Node node;
  node.push_back(10);
  node.push_back("foo");
  node.push_back("monkey");
  EXPECT_TRUE(node.IsSequence());
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(10, node[0].as<int>());
  EXPECT_EQ("foo", node[1].as<std::string>());
  EXPECT_EQ("monkey", node[2].as<std::string>());
  EXPECT_TRUE(node.IsSequence());
}

TEST(NodeTest, SimpleAssignSequence) {
  YAML::Node node;
  node[0] = 10;
  node[1] = "foo";
  node[2] = "monkey";
  EXPECT_TRUE(node.IsSequence());
  EXPECT_EQ(3, node.size());
  EXPECT_EQ(10, node[0].as<int>());
  EXPECT_EQ("foo", node[1].as<std::string>());
  EXPECT_EQ("monkey", node[2].as<std::string>());
  EXPECT_TRUE(node.IsSequence());
}

TEST(NodeTest, SimpleMap) {
  YAML::Node node;
  node["key"] = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ("value", node["key"].as<std::string>());
  EXPECT_EQ(1, node.size());
}

TEST(NodeTest, MapWithUndefinedValues) {
  YAML::Node node;
  node["key"] = "value";
  node["undefined"];
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ("value", node["key"].as<std::string>());
  EXPECT_EQ(1, node.size());

  node["undefined"] = "monkey";
  EXPECT_EQ("monkey", node["undefined"].as<std::string>());
  EXPECT_EQ(2, node.size());
}

TEST(NodeTest, MapIteratorWithUndefinedValues) {
  YAML::Node node;
  node["key"] = "value";
  node["undefined"];

  std::size_t count = 0;
  for (const_iterator it = node.begin(); it != node.end(); ++it)
    count++;
  EXPECT_EQ(1, count);
}

TEST(NodeTest, SimpleSubkeys) {
  YAML::Node node;
  node["device"]["udid"] = "12345";
  node["device"]["name"] = "iPhone";
  node["device"]["os"] = "4.0";
  node["username"] = "monkey";
  EXPECT_EQ("12345", node["device"]["udid"].as<std::string>());
  EXPECT_EQ("iPhone", node["device"]["name"].as<std::string>());
  EXPECT_EQ("4.0", node["device"]["os"].as<std::string>());
  EXPECT_EQ("monkey", node["username"].as<std::string>());
}

TEST(NodeTest, StdVector) {
  std::vector<int> primes;
  primes.push_back(2);
  primes.push_back(3);
  primes.push_back(5);
  primes.push_back(7);
  primes.push_back(11);
  primes.push_back(13);

  YAML::Node node;
  node["primes"] = primes;
  EXPECT_EQ(primes, node["primes"].as<std::vector<int> >());
}

TEST(NodeTest, StdList) {
  std::list<int> primes;
  primes.push_back(2);
  primes.push_back(3);
  primes.push_back(5);
  primes.push_back(7);
  primes.push_back(11);
  primes.push_back(13);

  YAML::Node node;
  node["primes"] = primes;
  EXPECT_EQ(primes, node["primes"].as<std::list<int> >());
}

TEST(NodeTest, StdMap) {
  std::map<int, int> squares;
  squares[0] = 0;
  squares[1] = 1;
  squares[2] = 4;
  squares[3] = 9;
  squares[4] = 16;

  YAML::Node node;
  node["squares"] = squares;
  std::map<int, int> actualSquares = node["squares"].as<std::map<int, int> >();
  EXPECT_EQ(squares, actualSquares);
}

TEST(NodeTest, StdPair) {
  std::pair<int, std::string> p;
  p.first = 5;
  p.second = "five";

  YAML::Node node;
  node["pair"] = p;
  std::pair<int, std::string> actualP =
      node["pair"].as<std::pair<int, std::string> >();
  EXPECT_EQ(p, actualP);
}

TEST(NodeTest, SimpleAlias) {
  YAML::Node node;
  node["foo"] = "value";
  node["bar"] = node["foo"];
  EXPECT_EQ("value", node["foo"].as<std::string>());
  EXPECT_EQ("value", node["bar"].as<std::string>());
  EXPECT_EQ(node["bar"], node["foo"]);
  EXPECT_EQ(2, node.size());
}

TEST(NodeTest, AliasAsKey) {
  YAML::Node node;
  node["foo"] = "value";
  YAML::Node value = node["foo"];
  node[value] = "foo";
  EXPECT_EQ("value", node["foo"].as<std::string>());
  EXPECT_EQ("foo", node[value].as<std::string>());
  EXPECT_EQ("foo", node["value"].as<std::string>());
  EXPECT_EQ(2, node.size());
}

TEST(NodeTest, SelfReferenceSequence) {
  YAML::Node node;
  node[0] = node;
  EXPECT_TRUE(node.IsSequence());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ(node, node[0]);
  EXPECT_EQ(node, node[0][0]);
  EXPECT_EQ(node[0], node[0][0]);
}

TEST(NodeTest, ValueSelfReferenceMap) {
  YAML::Node node;
  node["key"] = node;
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ(node, node["key"]);
  EXPECT_EQ(node, node["key"]["key"]);
  EXPECT_EQ(node["key"], node["key"]["key"]);
}

TEST(NodeTest, KeySelfReferenceMap) {
  YAML::Node node;
  node[node] = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ("value", node[node].as<std::string>());
}

TEST(NodeTest, SelfReferenceMap) {
  YAML::Node node;
  node[node] = node;
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ(node, node[node]);
  EXPECT_EQ(node, node[node][node]);
  EXPECT_EQ(node[node], node[node][node]);
}

TEST(NodeTest, TempMapVariable) {
  YAML::Node node;
  YAML::Node tmp = node["key"];
  tmp = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(1, node.size());
  EXPECT_EQ("value", node["key"].as<std::string>());
}

TEST(NodeTest, TempMapVariableAlias) {
  YAML::Node node;
  YAML::Node tmp = node["key"];
  tmp = node["other"];
  node["other"] = "value";
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(2, node.size());
  EXPECT_EQ("value", node["key"].as<std::string>());
  EXPECT_EQ("value", node["other"].as<std::string>());
  EXPECT_EQ(node["key"], node["other"]);
}

TEST(NodeTest, Bool) {
  YAML::Node node;
  node[true] = false;
  EXPECT_TRUE(node.IsMap());
  EXPECT_EQ(false, node[true].as<bool>());
}

TEST(NodeTest, AutoBoolConversion) {
#pragma warning(disable:4800)
  YAML::Node node;
  node["foo"] = "bar";
  EXPECT_TRUE(static_cast<bool>(node["foo"]));
  EXPECT_TRUE(!node["monkey"]);
  EXPECT_TRUE(!!node["foo"]);
}

TEST(NodeTest, FloatingPrecision) {
  const double x = 0.123456789;
  YAML::Node node = YAML::Node(x);
  EXPECT_EQ(x, node.as<double>());
}

TEST(NodeTest, SpaceChar) {
  YAML::Node node = YAML::Node(' ');
  EXPECT_EQ(' ', node.as<char>());
}

TEST(NodeTest, CloneNull) {
  Node node;
  Node clone = Clone(node);
  EXPECT_EQ(NodeType::Null, clone.Type());
}
}
}
<|endoftext|>


<commit_before>//===- llvm/unittest/IR/AsmWriter.cpp - AsmWriter tests -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

TEST(AsmWriterTest, DebugPrintDetachedInstruction) {

  // PR24852: Ensure that an instruction can be printed even when it
  // has metadata attached but no parent.
  LLVMContext Ctx;
  auto Ty = Type::getInt32Ty(Ctx);
  auto Undef = UndefValue::get(Ty);
  std::unique_ptr<BinaryOperator> Add(BinaryOperator::CreateAdd(Undef, Undef));
  Add->setMetadata(
      "", MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(Ty, 1))}));
  std::string S;
  raw_string_ostream OS(S);
  Add->print(OS);
  std::size_t r = OS.str().find("<badref> = add i32 undef, undef, !<empty");
  EXPECT_TRUE(r != std::string::npos);
}

TEST(AsmWriterTest, DebugPrintDetachedArgument) {
  LLVMContext Ctx;
  auto Ty = Type::getInt32Ty(Ctx);
  auto Arg = new Argument(Ty);

  std::string S;
  raw_string_ostream OS(S);
  Arg->print(OS);
  EXPECT_EQ(S, "i32 <badref>");
}

TEST(AsmWriterTest, DumpDIExpression) {
  LLVMContext Ctx;
  uint64_t Ops[] = {
    dwarf::DW_OP_constu, 4,
    dwarf::DW_OP_minus,
    dwarf::DW_OP_deref,
  };
  DIExpression *Expr = DIExpression::get(Ctx, Ops);
  std::string S;
  raw_string_ostream OS(S);
  Expr->print(OS);
  EXPECT_EQ("!DIExpression(DW_OP_constu, 4, DW_OP_minus, DW_OP_deref)",
            OS.str());
}

}
<commit_msg>IR: Cleanup after test to silence ASAN builds<commit_after>//===- llvm/unittest/IR/AsmWriter.cpp - AsmWriter tests -------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

TEST(AsmWriterTest, DebugPrintDetachedInstruction) {

  // PR24852: Ensure that an instruction can be printed even when it
  // has metadata attached but no parent.
  LLVMContext Ctx;
  auto Ty = Type::getInt32Ty(Ctx);
  auto Undef = UndefValue::get(Ty);
  std::unique_ptr<BinaryOperator> Add(BinaryOperator::CreateAdd(Undef, Undef));
  Add->setMetadata(
      "", MDNode::get(Ctx, {ConstantAsMetadata::get(ConstantInt::get(Ty, 1))}));
  std::string S;
  raw_string_ostream OS(S);
  Add->print(OS);
  std::size_t r = OS.str().find("<badref> = add i32 undef, undef, !<empty");
  EXPECT_TRUE(r != std::string::npos);
}

TEST(AsmWriterTest, DebugPrintDetachedArgument) {
  LLVMContext Ctx;
  auto Ty = Type::getInt32Ty(Ctx);
  auto Arg = new Argument(Ty);

  std::string S;
  raw_string_ostream OS(S);
  Arg->print(OS);
  EXPECT_EQ(S, "i32 <badref>");
  delete Arg;
}

TEST(AsmWriterTest, DumpDIExpression) {
  LLVMContext Ctx;
  uint64_t Ops[] = {
    dwarf::DW_OP_constu, 4,
    dwarf::DW_OP_minus,
    dwarf::DW_OP_deref,
  };
  DIExpression *Expr = DIExpression::get(Ctx, Ops);
  std::string S;
  raw_string_ostream OS(S);
  Expr->print(OS);
  EXPECT_EQ("!DIExpression(DW_OP_constu, 4, DW_OP_minus, DW_OP_deref)",
            OS.str());
}

}
<|endoftext|>


<commit_before>/*
 * nRF51-DK BLEDevice service/characteristic (read/write) using mbed.org
 */

// uncomment if not interested in a console log
#define CONSOLE_LOG

#include "mbed.h"
#include "BLE.h"

//-------------------------------------------------------------------------

#ifdef CONSOLE_LOG
#define INFO(x, ...)    printf(x,        ##__VA_ARGS__);
#define INFO_NL(x, ...) printf(x "\r\n", ##__VA_ARGS__);
#else
#define INFO(x, ...)
#define INFO_NL(x, ...)
#endif

// a little routine to print a 128-bit UUID nicely
void INFO_UUID(const char *prefix, UUID uuid)
{
   uint8_t *p = (uint8_t *)uuid.getBaseUUID();
   INFO("%s: ", prefix);
   for (int i=0; i<16; i++)
   {
     INFO("%02x", p[i]);
     if ((i == 3) || (i == 5) || (i == 7) || (i == 9)) INFO("-");
   }
   INFO_NL("");
}

//-------------------------------------------------------------------------

// name of the device
const static char DEVICE_NAME[] = "nRF51-DK";

// GATT service and characteristic UUIDs
const UUID nRF51_GATT_SERVICE     = UUID((uint8_t *)"nRF51-DK        ");
const UUID nRF51_GATT_CHAR_BUTTON = UUID((uint8_t *)"nRF51-DK button ");
const UUID nRF51_GATT_CHAR_LED    = UUID((uint8_t *)"nRF51-DK led    ");

#define CHARACTERISTIC_BUTTON 0
#define CHARACTERISTIC_LED    1
#define CHARACTERISTIC_COUNT  2

// our bluetooth smart objects
BLEDevice           ble;
GattService        *gatt_service;
GattCharacteristic *gatt_characteristics[CHARACTERISTIC_COUNT];
uint8_t             gatt_char_value[CHARACTERISTIC_COUNT];

#ifdef CONSOLE_LOG
Serial pc(USBTX,USBRX);
#endif

//-------------------------------------------------------------------------
// button handling
//-------------------------------------------------------------------------

// define our digital in values we will be using for the characteristic
DigitalIn button1(P0_17);
DigitalIn button2(P0_18);
DigitalIn button3(P0_19);
DigitalIn button4(P0_20);

uint8_t button_new_value = 0;
uint8_t button_old_value = button_new_value;

void monitorButtons()
{
    // read in the buttons, mapped into nibble (0000 = all off, 1111 = all on)
    button_new_value = 0;
    button_new_value |= (button1.read() != 1); button_new_value <<= 1;
    button_new_value |= (button2.read() != 1); button_new_value <<= 1;
    button_new_value |= (button3.read() != 1); button_new_value <<= 1;
    button_new_value |= (button4.read() != 1);

    // set the updated value of the characteristic if data has changed
    if (button_new_value != button_old_value)
    {
        ble.updateCharacteristicValue(
              gatt_characteristics[CHARACTERISTIC_BUTTON] -> getValueHandle(),
              &button_new_value, sizeof(button_new_value));
        button_old_value = button_new_value;

        INFO_NL("  button state: [0x%02x]", button_new_value);
    }
}

//-------------------------------------------------------------------------
// LED handling
//-------------------------------------------------------------------------

DigitalOut led1(P0_21);
DigitalOut led2(P0_22);
DigitalOut led3(P0_23);
DigitalOut led4(P0_24);

uint8_t led_value = 0;

void onLedDataWritten(const uint8_t* value, uint8_t length)
{
    // we only care about a single byte
    led_value = value[0];

    // depending on the value coming through; set/unset LED's
    if ((led_value & 0x01) != 0) led1.write(0); else led1.write(1);
    if ((led_value & 0x02) != 0) led2.write(0); else led2.write(1);
    if ((led_value & 0x04) != 0) led3.write(0); else led3.write(1);
    if ((led_value & 0x08) != 0) led4.write(0); else led4.write(1);

    INFO_NL("     led state: [0x%02x]", led_value);
}

//-------------------------------------------------------------------------

void onConnection(const Gap::ConnectionCallbackParams_t *params)
{
  INFO_NL(">> connected");

  // set the initial values of the characteristics (for every session)
  led_value = 0;
  onLedDataWritten(&led_value, 1); // force LED's to be in off state
}

void onDataWritten(const GattWriteCallbackParams *context)
{
  // was the characteristic being written to nRF51_GATT_CHAR_LED?
  if (context -> handle ==
      gatt_characteristics[CHARACTERISTIC_LED] -> getValueHandle())
  {
    onLedDataWritten(context -> data, context -> len);
  }
}

void onDisconnection(Gap::Handle_t handle,
                     Gap::DisconnectionReason_t disconnectReason)
{
  INFO_NL(">> disconnected");
  ble.startAdvertising();
  INFO_NL(">> device advertising");
}

int main()
{
#ifdef CONSOLE_LOG
    // wait a second before trying to write something to console
    wait(1);
#endif
    INFO_NL(">> nRF51-DK start");

    // create our button characteristic (read, notify)
    gatt_characteristics[CHARACTERISTIC_BUTTON] =
      new GattCharacteristic(
            nRF51_GATT_CHAR_BUTTON,
            &gatt_char_value[CHARACTERISTIC_BUTTON], 1, 1,
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);

    // create our LED characteristic (read, write)
    gatt_characteristics[CHARACTERISTIC_LED] =
      new GattCharacteristic(
            nRF51_GATT_CHAR_LED,
            &gatt_char_value[CHARACTERISTIC_LED], 1, 1,
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);

    // create our service, with both characteristics
    gatt_service =
      new GattService(nRF51_GATT_SERVICE,
                      gatt_characteristics, CHARACTERISTIC_COUNT);

    // initialize our ble device
    ble.init();
    ble.setDeviceName((uint8_t *)DEVICE_NAME);
    INFO_NL(">> initialized device '%s'", DEVICE_NAME);

    // configure our advertising type, payload and interval
    ble.accumulateAdvertisingPayload(
          GapAdvertisingData::BREDR_NOT_SUPPORTED |
          GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.accumulateAdvertisingPayload(
          GapAdvertisingData::COMPLETE_LOCAL_NAME,
          (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.setAdvertisingInterval(160); // 100ms
    INFO_NL(">> configured advertising type, payload and interval");

    // configure our callbacks
    ble.onDisconnection(onDisconnection);
    ble.onConnection(onConnection);
    ble.onDataWritten(onDataWritten);
    INFO_NL(">> registered for callbacks");

    // add our gatt service with two characteristics
    ble.addService(*gatt_service);
    INFO_NL(">> added GATT service with two characteristics");

    // show some debugging information about service/characteristics
    INFO_UUID(" ", nRF51_GATT_SERVICE);
    INFO_UUID("  :", nRF51_GATT_CHAR_BUTTON);
    INFO_UUID("  :", nRF51_GATT_CHAR_LED);

    // start advertising
    ble.startAdvertising();
    INFO_NL(">> device advertising");

    // start monitoring the buttons and posting new values
    Ticker ticker;
    ticker.attach(monitorButtons, 0.1);  // every 10th of a second
    INFO_NL(">> monitoring button state");

    // let the device do its thing
    INFO_NL(">> waiting for events ");
    for (;;)
    {
      ble.waitForEvent();
    }
}

//-------------------------------------------------------------------------
<commit_msg>30 Sep 2015 - update to changed in mbed BLE API <commit_after>/*
 * nRF51-DK BLEDevice service/characteristic (read/write) using mbed.org
 */

// uncomment if not interested in a console log
#define CONSOLE_LOG

#include "mbed.h"
#include "BLE.h"

//-------------------------------------------------------------------------

#ifdef CONSOLE_LOG
#define INFO(x, ...)    printf(x,        ##__VA_ARGS__);
#define INFO_NL(x, ...) printf(x "\r\n", ##__VA_ARGS__);
#else
#define INFO(x, ...)
#define INFO_NL(x, ...)
#endif

// a little routine to print a 128-bit UUID nicely
void INFO_UUID(const char *prefix, UUID uuid)
{
   uint8_t *p = (uint8_t *)uuid.getBaseUUID();
   INFO("%s: ", prefix);
   for (int i=0; i<16; i++)
   {
     INFO("%02x", p[i]);
     if ((i == 3) || (i == 5) || (i == 7) || (i == 9)) INFO("-");
   }
   INFO_NL("");
}

//-------------------------------------------------------------------------

// name of the device
const static char DEVICE_NAME[] = "nRF51-DK";

// GATT service and characteristic UUIDs
const UUID nRF51_GATT_SERVICE     = UUID((uint8_t *)"nRF51-DK        ");
const UUID nRF51_GATT_CHAR_BUTTON = UUID((uint8_t *)"nRF51-DK button ");
const UUID nRF51_GATT_CHAR_LED    = UUID((uint8_t *)"nRF51-DK led    ");

#define CHARACTERISTIC_BUTTON 0
#define CHARACTERISTIC_LED    1
#define CHARACTERISTIC_COUNT  2

// our bluetooth smart objects
BLEDevice           ble;
GattService        *gatt_service;
GattCharacteristic *gatt_characteristics[CHARACTERISTIC_COUNT];
uint8_t             gatt_char_value[CHARACTERISTIC_COUNT];

#ifdef CONSOLE_LOG
Serial pc(USBTX,USBRX);
#endif

//-------------------------------------------------------------------------
// button handling
//-------------------------------------------------------------------------

// define our digital in values we will be using for the characteristic
DigitalIn button1(P0_17);
DigitalIn button2(P0_18);
DigitalIn button3(P0_19);
DigitalIn button4(P0_20);

uint8_t button_new_value = 0;
uint8_t button_old_value = button_new_value;

void monitorButtons()
{
    // read in the buttons, mapped into nibble (0000 = all off, 1111 = all on)
    button_new_value = 0;
    button_new_value |= (button1.read() != 1); button_new_value <<= 1;
    button_new_value |= (button2.read() != 1); button_new_value <<= 1;
    button_new_value |= (button3.read() != 1); button_new_value <<= 1;
    button_new_value |= (button4.read() != 1);

    // set the updated value of the characteristic if data has changed
    if (button_new_value != button_old_value)
    {
        ble.updateCharacteristicValue(
              gatt_characteristics[CHARACTERISTIC_BUTTON] -> getValueHandle(),
              &button_new_value, sizeof(button_new_value));
        button_old_value = button_new_value;

        INFO_NL("  button state: [0x%02x]", button_new_value);
    }
}

//-------------------------------------------------------------------------
// LED handling
//-------------------------------------------------------------------------

DigitalOut led1(P0_21);
DigitalOut led2(P0_22);
DigitalOut led3(P0_23);
DigitalOut led4(P0_24);

uint8_t led_value = 0;

void onLedDataWritten(const uint8_t* value, uint8_t length)
{
    // we only care about a single byte
    led_value = value[0];

    // depending on the value coming through; set/unset LED's
    if ((led_value & 0x01) != 0) led1.write(0); else led1.write(1);
    if ((led_value & 0x02) != 0) led2.write(0); else led2.write(1);
    if ((led_value & 0x04) != 0) led3.write(0); else led3.write(1);
    if ((led_value & 0x08) != 0) led4.write(0); else led4.write(1);

    INFO_NL("     led state: [0x%02x]", led_value);
}

//-------------------------------------------------------------------------

void onConnection(const Gap::ConnectionCallbackParams_t *params)
{
  INFO_NL(">> connected");

  // set the initial values of the characteristics (for every session)
  led_value = 0;
  onLedDataWritten(&led_value, 1); // force LED's to be in off state
}

void onDataWritten(const GattWriteCallbackParams *context)
{
  // was the characteristic being written to nRF51_GATT_CHAR_LED?
  if (context -> handle ==
      gatt_characteristics[CHARACTERISTIC_LED] -> getValueHandle())
  {
    onLedDataWritten(context -> data, context -> len);
  }
}

void onDisconnection(const Gap::DisconnectionCallbackParams_t *params)
{
  INFO_NL(">> disconnected");
  ble.startAdvertising();
  INFO_NL(">> device advertising");
}

int main()
{
#ifdef CONSOLE_LOG
    // wait a second before trying to write something to console
    wait(1);
#endif
    INFO_NL(">> nRF51-DK start");

    // create our button characteristic (read, notify)
    gatt_characteristics[CHARACTERISTIC_BUTTON] =
      new GattCharacteristic(
            nRF51_GATT_CHAR_BUTTON,
            &gatt_char_value[CHARACTERISTIC_BUTTON], 1, 1,
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);

    // create our LED characteristic (read, write)
    gatt_characteristics[CHARACTERISTIC_LED] =
      new GattCharacteristic(
            nRF51_GATT_CHAR_LED,
            &gatt_char_value[CHARACTERISTIC_LED], 1, 1,
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE |
            GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE);

    // create our service, with both characteristics
    gatt_service =
      new GattService(nRF51_GATT_SERVICE,
                      gatt_characteristics, CHARACTERISTIC_COUNT);

    // initialize our ble device
    ble.init();
    ble.setDeviceName((uint8_t *)DEVICE_NAME);
    INFO_NL(">> initialized device '%s'", DEVICE_NAME);

    // configure our advertising type, payload and interval
    ble.accumulateAdvertisingPayload(
          GapAdvertisingData::BREDR_NOT_SUPPORTED |
          GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.accumulateAdvertisingPayload(
          GapAdvertisingData::COMPLETE_LOCAL_NAME,
          (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.setAdvertisingInterval(160); // 100ms
    INFO_NL(">> configured advertising type, payload and interval");

    // configure our callbacks
    ble.onDisconnection(onDisconnection);
    ble.onConnection(onConnection);
    ble.onDataWritten(onDataWritten);
    INFO_NL(">> registered for callbacks");

    // add our gatt service with two characteristics
    ble.addService(*gatt_service);
    INFO_NL(">> added GATT service with two characteristics");

    // show some debugging information about service/characteristics
    INFO_UUID(" ", nRF51_GATT_SERVICE);
    INFO_UUID("  :", nRF51_GATT_CHAR_BUTTON);
    INFO_UUID("  :", nRF51_GATT_CHAR_LED);

    // start advertising
    ble.startAdvertising();
    INFO_NL(">> device advertising");

    // start monitoring the buttons and posting new values
    Ticker ticker;
    ticker.attach(monitorButtons, 0.1);  // every 10th of a second
    INFO_NL(">> monitoring button state");

    // let the device do its thing
    INFO_NL(">> waiting for events ");
    for (;;)
    {
      ble.waitForEvent();
    }
}

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


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee — CLIPP Echo Generator Implementation
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include "echo_generator.hpp"

#include <boost/make_shared.hpp>

using namespace std;

namespace IronBee {
namespace CLIPP {

struct EchoGenerator::State
{
    State() :
        produced_input(false)
    {
        // nop
    }

    bool   produced_input;
    string id;
    string request;
};

EchoGenerator::EchoGenerator()
{
    // nop
}

EchoGenerator::EchoGenerator(
    const string& request_line
) :
    m_state(boost::make_shared<State>())
{
    m_state->id = request_line;
    m_state->request = request_line + "\r\n";
}

bool EchoGenerator::operator()(Input::input_p& out_input)
{
    if (m_state->produced_input) {
        return false;
    }

    out_input->id                = m_state->id;
    out_input->connection = Input::Connection();
    out_input->connection.connection_opened(
        Input::Buffer(local_ip),  local_port,
        Input::Buffer(remote_ip), remote_port
    );
    out_input->connection.connection_closed();
    out_input->connection.add_transaction(
        Input::Buffer(m_state->request),
        Input::Buffer()
    );

    m_state->produced_input = true;

    return true;
}

const string EchoGenerator::local_ip    = "1.2.3.4";
const string EchoGenerator::remote_ip   = "5.6.7.8";
const uint16_t    EchoGenerator::local_port  = 1234;
const uint16_t    EchoGenerator::remote_port = 5678;

} // CLIPP
} // IronBee
<commit_msg>clipp: Echo generator no longer has connection data out event.<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee — CLIPP Echo Generator Implementation
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include "echo_generator.hpp"

#include <boost/make_shared.hpp>

using namespace std;

namespace IronBee {
namespace CLIPP {

struct EchoGenerator::State
{
    State() :
        produced_input(false)
    {
        // nop
    }

    bool   produced_input;
    string id;
    string request;
};

EchoGenerator::EchoGenerator()
{
    // nop
}

EchoGenerator::EchoGenerator(
    const string& request_line
) :
    m_state(boost::make_shared<State>())
{
    m_state->id = request_line;
    m_state->request = request_line + "\r\n";
}

bool EchoGenerator::operator()(Input::input_p& out_input)
{
    if (m_state->produced_input) {
        return false;
    }

    out_input->id                = m_state->id;
    out_input->connection = Input::Connection();
    out_input->connection.connection_opened(
        Input::Buffer(local_ip),  local_port,
        Input::Buffer(remote_ip), remote_port
    );
    out_input->connection.connection_closed();
    out_input->connection.add_transaction()
        .connection_data_in(Input::Buffer(m_state->request));

    m_state->produced_input = true;

    return true;
}

const string EchoGenerator::local_ip    = "1.2.3.4";
const string EchoGenerator::remote_ip   = "5.6.7.8";
const uint16_t    EchoGenerator::local_port  = 1234;
const uint16_t    EchoGenerator::remote_port = 5678;

} // CLIPP
} // IronBee
<|endoftext|>


<commit_before>#include <stan/lang/rethrow_located.hpp>
#include <gtest/gtest.h>

template <typename E, typename E2>
void test_rethrow_located_2() {
  try {
    try {
      throw E("foo");
    } catch (const std::exception& e) {
      stan::lang::rethrow_located(e, 5);
    }
  } catch (const E2& e) {
    EXPECT_TRUE(std::string(e.what()).find_first_of("5")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
                != std::string::npos);
    return;
  } catch (...) {
    FAIL();
  }
  FAIL();
}

template <typename E>
void test_rethrow_located() {
  test_rethrow_located_2<E,E>();
}

template <typename E>
void test_rethrow_located_nullary(const std::string& original_type) {
  try {
    try {
      throw E();
    } catch (const std::exception& e) {
      stan::lang::rethrow_located(e, 5);
    }
  } catch (const E& e) {
    EXPECT_TRUE(std::string(e.what()).find_first_of("5")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of(original_type)
                != std::string::npos);
    return;
  } catch (...) {
    FAIL();
  }
  FAIL();
}

struct my_test_exception : public std::exception {
  const std::string what_;
  my_test_exception(const std::string& what) throw() : what_(what) { }
  ~my_test_exception() throw() { }
  const char* what() const throw() { return what_.c_str(); }
};

TEST(langRethrowLocated, allExpected) {
  test_rethrow_located_nullary<std::bad_alloc>("bad_alloc");
  test_rethrow_located_nullary<std::bad_cast>("bad_cast");
  test_rethrow_located_nullary<std::bad_exception>("bad_exception");
  test_rethrow_located_nullary<std::bad_typeid>("bad_typeid");

  test_rethrow_located<std::domain_error>();
  test_rethrow_located<std::invalid_argument>();
  test_rethrow_located<std::length_error>();
  test_rethrow_located<std::out_of_range>();
  test_rethrow_located<std::logic_error>();
  test_rethrow_located<std::overflow_error>();
  test_rethrow_located<std::range_error>();
  test_rethrow_located<std::underflow_error>();
  test_rethrow_located<std::runtime_error>();

  test_rethrow_located_nullary<std::exception>("std::exception");

  test_rethrow_located_2<my_test_exception,std::exception>();
}
TEST(langRethrowLocated, locatedException) {
  // tests nested case
  using stan::lang::located_exception;
  try {
    try {
      throw located_exception<located_exception<std::exception> >("foo","bar");
    } catch (const std::exception& e) {
      stan::lang::rethrow_located(e, 5);
    }
  } catch (const std::exception& e) {
    EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of("bar")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of("5")
                != std::string::npos);
    return;
  } catch (...) {
    FAIL();
  }
  FAIL();
}
<commit_msg>change ref to copy in rethrow-located test; fixes #2030<commit_after>#include <stan/lang/rethrow_located.hpp>
#include <gtest/gtest.h>

template <typename E, typename E2>
void test_rethrow_located_2() {
  try {
    try {
      throw E("foo");
    } catch (const std::exception& e) {
      stan::lang::rethrow_located(e, 5);
    }
  } catch (const E2& e) {
    EXPECT_TRUE(std::string(e.what()).find_first_of("5")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
                != std::string::npos);
    return;
  } catch (...) {
    FAIL();
  }
  FAIL();
}

template <typename E>
void test_rethrow_located() {
  test_rethrow_located_2<E,E>();
}

template <typename E>
void test_rethrow_located_nullary(const std::string& original_type) {
  try {
    try {
      throw E();
    } catch (const std::exception& e) {
      stan::lang::rethrow_located(e, 5);
    }
  } catch (const E& e) {
    EXPECT_TRUE(std::string(e.what()).find_first_of("5")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of(original_type)
                != std::string::npos);
    return;
  } catch (...) {
    FAIL();
  }
  FAIL();
}

struct my_test_exception : public std::exception {
  const std::string what_;
  my_test_exception(const std::string& what) throw() : what_(what) { }
  ~my_test_exception() throw() { }
  const char* what() const throw() { return what_.c_str(); }
};

TEST(langRethrowLocated, allExpected) {
  test_rethrow_located_nullary<std::bad_alloc>("bad_alloc");
  test_rethrow_located_nullary<std::bad_cast>("bad_cast");
  test_rethrow_located_nullary<std::bad_exception>("bad_exception");
  test_rethrow_located_nullary<std::bad_typeid>("bad_typeid");

  test_rethrow_located<std::domain_error>();
  test_rethrow_located<std::invalid_argument>();
  test_rethrow_located<std::length_error>();
  test_rethrow_located<std::out_of_range>();
  test_rethrow_located<std::logic_error>();
  test_rethrow_located<std::overflow_error>();
  test_rethrow_located<std::range_error>();
  test_rethrow_located<std::underflow_error>();
  test_rethrow_located<std::runtime_error>();

  test_rethrow_located_nullary<std::exception>("std::exception");
  test_rethrow_located_2<my_test_exception,std::exception>();
}
TEST(langRethrowLocated, locatedException) {
  // tests nested case
  using stan::lang::located_exception;
  try {
    try {
      throw located_exception<located_exception<std::exception> >("foo","bar");
    } catch (const std::exception& e) {
      stan::lang::rethrow_located(e, 5);
    }
  } catch (const std::exception& e) {
    EXPECT_TRUE(std::string(e.what()).find_first_of("foo")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of("bar")
                != std::string::npos);
    EXPECT_TRUE(std::string(e.what()).find_first_of("5")
                != std::string::npos);
    return;
  } catch (...) {
    FAIL();
  }
  FAIL();
}
<|endoftext|>


<commit_before>#include "Application.h"

#include <chrono>

#include "util.h"

using namespace world;

Application::Application()
        : _running(false),
	      _mainView(std::make_unique<MainView>(*this)),
		  _newUpdatePos(0, 0, 5000),
		  _lastUpdatePos(_newUpdatePos),
		  _explorer(std::make_unique<FirstPersonExplorer>(1000)){

	_explorer->setPosition(_lastUpdatePos);
	_explorer->setFarDistance(10000);

	// Collectors
	for (int i = 0; i < 2; i++) {
		_emptyCollectors.emplace_back(std::make_unique<FlatWorldCollector>());
	}
}

void Application::run(int argc, char **argv) {
    loadWorld(argc, argv);

    _running = true;
    _mainView->show();

	bool firstExpand = true;

    while(_running) {
        if (!_mainView->running()) {
            _running = false;
        }
		else {
			// On prend les paramtres en local.
            _paramLock.lock();
			vec3d newUpdatePos = _newUpdatePos;

			if (_emptyCollectors.empty()) {
				_mainView->onWorldChange();
			}
			_paramLock.unlock();

			if (((newUpdatePos - _lastUpdatePos).norm() > 50 || firstExpand) && !_emptyCollectors.empty()) {
			    // get collector
			    _paramLock.lock();
			    std::unique_ptr<FlatWorldCollector> collector = std::move(_emptyCollectors.front());
			    _emptyCollectors.pop_front();
			    _paramLock.unlock();

                // Mise  jour du monde
				collector->reset();
				_explorer->setPosition(newUpdatePos);

				auto start = std::chrono::steady_clock::now();
                _explorer->exploreAndCollect<FlatWorld>(*_world, *collector);

				if (_dbgOn) {
					std::cout << "Temps d'exploration : " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() << " ms " << std::endl;
				}

				_paramLock.lock();
				_fullCollectors.emplace_back(std::move(collector));
				_paramLock.unlock();

				// Mise  jour de la vue
				_mainView->onWorldChange();
				_lastUpdatePos = newUpdatePos;

				firstExpand = false;
			}
		}

        sleep(20.0f);
    }

    _mainView->waitClose();
}

void Application::requestStop() {
    _running = false;
}

void Application::setUserPosition(vec3d pos) {
    std::lock_guard<std::mutex> lock(_paramLock);
	_newUpdatePos = pos;
}

vec3d Application::getUserPosition() const {
    std::lock_guard<std::mutex> lock(_paramLock);
	auto pos = _newUpdatePos;
	return pos;
}

void Application::refill(std::unique_ptr<world::FlatWorldCollector> &&toRefill) {
    std::lock_guard<std::mutex> lock(_paramLock);
	_emptyCollectors.emplace_back(std::move(toRefill));
}

std::unique_ptr<world::FlatWorldCollector> Application::popFull() {
	std::lock_guard<std::mutex> lock(_paramLock);
	if (_fullCollectors.empty())
		return nullptr;

	auto ret = std::move(_fullCollectors.front());
	_fullCollectors.pop_front();

	return std::move(ret);
}

void Application::loadWorld(int argc, char **argv) {
    _world = std::unique_ptr<FlatWorld>(FlatWorld::createDemoFlatWorld());
}<commit_msg>World3D : Frequent updates<commit_after>#include "Application.h"

#include <chrono>

#include "util.h"

using namespace world;

Application::Application()
        : _running(false),
	      _mainView(std::make_unique<MainView>(*this)),
		  _newUpdatePos(0, 0, 5000),
		  _lastUpdatePos(_newUpdatePos),
		  _explorer(std::make_unique<FirstPersonExplorer>(1000)){

	_explorer->setPosition(_lastUpdatePos);
	_explorer->setFarDistance(10000);

	// Collectors
	for (int i = 0; i < 2; i++) {
		_emptyCollectors.emplace_back(std::make_unique<FlatWorldCollector>());
	}
}

void Application::run(int argc, char **argv) {
    loadWorld(argc, argv);

    _running = true;
    _mainView->show();

    while(_running) {
        if (!_mainView->running()) {
            _running = false;
        }
		else {
			// On prend les paramtres en local.
            _paramLock.lock();
			vec3d newUpdatePos = _newUpdatePos;

			if (_emptyCollectors.empty()) {
				_mainView->onWorldChange();
			}
			_paramLock.unlock();

			if ((newUpdatePos - _lastUpdatePos).norm() > 0.01 && !_emptyCollectors.empty()) {
			    // get collector
			    _paramLock.lock();
			    std::unique_ptr<FlatWorldCollector> collector = std::move(_emptyCollectors.front());
			    _emptyCollectors.pop_front();
			    _paramLock.unlock();

                // Mise  jour du monde
				collector->reset();
				_explorer->setPosition(newUpdatePos);

				auto start = std::chrono::steady_clock::now();
                _explorer->exploreAndCollect<FlatWorld>(*_world, *collector);

				if (_dbgOn) {
					std::cout << "Temps d'exploration : " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count() << " ms " << std::endl;
				}

				_paramLock.lock();
				_fullCollectors.emplace_back(std::move(collector));
				_paramLock.unlock();

				// Mise  jour de la vue
				_mainView->onWorldChange();
				_lastUpdatePos = newUpdatePos;
			}
		}

        sleep(20.0f);
    }

    _mainView->waitClose();
}

void Application::requestStop() {
    _running = false;
}

void Application::setUserPosition(vec3d pos) {
    std::lock_guard<std::mutex> lock(_paramLock);
	_newUpdatePos = pos;
}

vec3d Application::getUserPosition() const {
    std::lock_guard<std::mutex> lock(_paramLock);
	auto pos = _newUpdatePos;
	return pos;
}

void Application::refill(std::unique_ptr<world::FlatWorldCollector> &&toRefill) {
    std::lock_guard<std::mutex> lock(_paramLock);
	_emptyCollectors.emplace_back(std::move(toRefill));
}

std::unique_ptr<world::FlatWorldCollector> Application::popFull() {
	std::lock_guard<std::mutex> lock(_paramLock);
	if (_fullCollectors.empty())
		return nullptr;

	auto ret = std::move(_fullCollectors.front());
	_fullCollectors.pop_front();

	return std::move(ret);
}

void Application::loadWorld(int argc, char **argv) {
    _world = std::unique_ptr<FlatWorld>(FlatWorld::createDemoFlatWorld());
}<|endoftext|>


<commit_before>/*
Copyright 2013 Rogier van Dalen.

This file is part of Rogier van Dalen's Rime library for C++.

This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define BOOST_TEST_MODULE test_rime_sign
#include "utility/test/boost_unit_test.hpp"

#include "rime/sign.hpp"

#include <string>
#include <type_traits>

#include <boost/mpl/assert.hpp>
#include <boost/mpl/int.hpp>

#include "rime/core.hpp"

#include "check_equal.hpp"

BOOST_AUTO_TEST_SUITE(test_rime_sign)

BOOST_AUTO_TEST_CASE (test_rime_sign_types) {
    // is_signed.
    static_assert (rime::types::is_signed <int>::value, "");
    static_assert (rime::types::is_signed <short>::value, "");
    static_assert (rime::types::is_signed <rime::int_ <-1>>::value, "");
    static_assert (rime::types::is_signed <boost::mpl::int_ <0>>::value, "");
    static_assert (rime::types::is_signed
        <std::integral_constant <int, 1>>::value, "");

    static_assert (!rime::types::is_signed <unsigned>::value, "");
    static_assert (!rime::types::is_signed <unsigned short>::value, "");
    static_assert (!rime::types::is_signed <std::size_t>::value, "");
    static_assert (!rime::types::is_signed <rime::size_t <0>>::value, "");
    static_assert (!rime::types::is_signed <rime::size_t <2>>::value, "");
    static_assert (!rime::types::is_signed <void>::value, "");
    static_assert (!rime::types::is_signed <std::string>::value, "");

    // is_unsigned.
    static_assert (rime::types::is_unsigned <unsigned>::value, "");
    static_assert (rime::types::is_unsigned <unsigned short>::value, "");
    static_assert (rime::types::is_unsigned <std::size_t>::value, "");
    static_assert (rime::types::is_unsigned <rime::size_t <0>>::value, "");
    static_assert (rime::types::is_unsigned <rime::size_t <2>>::value, "");

    static_assert (!rime::types::is_unsigned <int>::value, "");
    static_assert (!rime::types::is_unsigned <short>::value, "");
    static_assert (!rime::types::is_unsigned <rime::int_ <-1>>::value, "");
    static_assert (!rime::types::is_unsigned <boost::mpl::int_ <0>>::value, "");
    static_assert (!rime::types::is_unsigned <
        std::integral_constant <int, 1>>::value, "");

    static_assert (!rime::types::is_unsigned <void>::value, "");
    static_assert (!rime::types::is_unsigned <std::string>::value, "");

    // make_signed.
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <int>::type, int>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <unsigned>::type, int>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <short>::type, short>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <unsigned short>::type, short>));

    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_signed <rime::int_ <1>>::type, rime::int_ <1>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_signed <rime::constant <unsigned, 1>>::type,
        rime::int_ <1>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_signed <std::integral_constant <unsigned, 2>>::type,
        rime::int_ <2>>));

    // make_unsigned.
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <int>::type, unsigned>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <unsigned>::type, unsigned>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <short>::type, short unsigned>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <unsigned short>::type,
        short unsigned>));

    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_unsigned <rime::int_ <1>>::type,
        rime::constant <unsigned, 1u>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_unsigned <rime::constant <int, 1>>::type,
        rime::constant <unsigned, 1u>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_unsigned <std::integral_constant <int, 2>>::type,
        rime::constant <unsigned, 2u>>));

    // make_zero.
    RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <1>>::type(),
        rime::int_ <0>());
    RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <-5>>::type(),
        rime::int_ <0>());
    RIME_CHECK_EQUAL (
        (rime::types::make_zero <rime::constant <unsigned, 1>>::type()),
        (rime::constant <unsigned, 0>()));
}

BOOST_AUTO_TEST_CASE (test_rime_sign_convert) {
    // make_signed.
    RIME_CHECK_EQUAL (rime::make_signed (1), 1);
    RIME_CHECK_EQUAL (rime::make_signed (1u), 1);

    RIME_CHECK_EQUAL (rime::make_signed (rime::int_ <1>()), rime::int_ <1>());
    RIME_CHECK_EQUAL (
        rime::make_signed (rime::constant <unsigned, 1u>()), rime::int_ <1>());

    // make_unsigned.
    RIME_CHECK_EQUAL (rime::make_unsigned (1), 1u);
    RIME_CHECK_EQUAL (rime::make_unsigned (1u), 1u);

    RIME_CHECK_EQUAL (rime::make_unsigned (rime::int_ <3>()),
        (rime::constant <unsigned, 3u>()));
    RIME_CHECK_EQUAL (rime::make_unsigned (rime::constant <unsigned, 2u>()),
        (rime::constant <unsigned, 2u>()));

    // make_zero.
    RIME_CHECK_EQUAL (rime::make_zero (1), 0);
    RIME_CHECK_EQUAL (rime::make_zero (1u), 0u);

    RIME_CHECK_EQUAL (rime::make_zero (rime::int_ <1>()), rime::int_ <0>());
    RIME_CHECK_EQUAL (
        rime::make_zero (rime::constant <unsigned, 1u>()),
        (rime::constant <unsigned, 0u>()));

}

// Signed constants.
typedef rime::int_ <unsigned (-1)/2 + 1> very_negative_int;
very_negative_int i1;
boost::mpl::int_ <-4> i2;
std::integral_constant <int, 0> i3;
rime::int_ <30> i4;

rime::constant <unsigned, 0> u3;
rime::constant <unsigned, 30> u4;
typedef rime::constant <unsigned, unsigned (-1)> very_great_unsigned;
very_great_unsigned u5;

// Sanity check for constants.
static_assert (very_negative_int::value < 0, "Should be negative");
static_assert (int (very_great_unsigned::value) < 0,
    "Unsigned should wrongly convert to negative");

template <bool reference, class Left, class Right>
    void check_less_sign_safe (Left const & left, Right const & right)
{
    // Known at compile time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
        rime::bool_ <reference>());

    // Known only at run time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
        reference);
}

// The case where if the left operand is constant, the result is known.
// I.e. -1 < u for any unsigned u.
template <bool reference, class Left, class Right>
    void check_less_sign_safe_left_constant (
        Left const & left, Right const & right)
{
    // Known at compile time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
        rime::bool_ <reference>());
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value),
        rime::bool_ <reference>());

    // Known only at run time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
        reference);
}

// The case where if the right operand is constant, the result is known.
// I.e. u < -1 for any unsigned u.
template <bool reference, class Left, class Right>
    void check_less_sign_safe_right_constant (
        Left const & left, Right const & right)
{
    // Known at compile time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
        rime::bool_ <reference>());
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right),
        rime::bool_ <reference>());

    // Known only at run time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
        reference);
}

struct not_an_int {};

bool operator < (not_an_int, not_an_int) { return false; }

BOOST_AUTO_TEST_CASE (test_rime_less_sign_safe) {
    check_less_sign_safe <false> (i1, i1);
    check_less_sign_safe <true> (i1, i2);
    check_less_sign_safe <true> (i1, i3);
    check_less_sign_safe_left_constant <true> (i1, u3);
    check_less_sign_safe <true> (i1, i4);
    check_less_sign_safe_left_constant <true> (i1, u4);
    check_less_sign_safe_left_constant <true> (i1, u5);

    check_less_sign_safe <false> (i2, i1);
    check_less_sign_safe <false> (i2, i2);
    check_less_sign_safe <true> (i2, i3);
    check_less_sign_safe_left_constant <true> (i2, u3);
    check_less_sign_safe <true> (i2, i4);
    check_less_sign_safe_left_constant <true> (i2, u4);
    check_less_sign_safe_left_constant <true> (i2, u5);

    check_less_sign_safe <false> (i3, i1);
    check_less_sign_safe <false> (i3, i2);
    check_less_sign_safe <false> (i3, i3);
    check_less_sign_safe <false> (i3, u3);
    check_less_sign_safe <true> (i3, i4);
    check_less_sign_safe <true> (i3, u4);
    check_less_sign_safe <true> (i3, u5);

    check_less_sign_safe <false> (i4, i1);
    check_less_sign_safe <false> (i4, i2);
    check_less_sign_safe <false> (i4, i3);
    check_less_sign_safe <false> (i4, u3);
    check_less_sign_safe <false> (i4, i4);
    check_less_sign_safe <false> (i4, u4);
    check_less_sign_safe <true> (i4, u5);

    check_less_sign_safe_right_constant  <false> (u3, i1);
    check_less_sign_safe_right_constant  <false> (u3, i2);
    check_less_sign_safe <false> (u3, i3);
    check_less_sign_safe <false> (u3, u3);
    check_less_sign_safe <true> (u3, i4);
    check_less_sign_safe <true> (u3, u4);
    check_less_sign_safe <true> (u3, u5);

    check_less_sign_safe_right_constant <false> (u4, i1);
    check_less_sign_safe_right_constant <false> (u4, i2);
    check_less_sign_safe <false> (u4, i3);
    check_less_sign_safe <false> (u4, u3);
    check_less_sign_safe <false> (u4, i4);
    check_less_sign_safe <false> (u4, u4);
    check_less_sign_safe <true> (u4, u5);

    check_less_sign_safe_right_constant <false> (u5, i1);
    check_less_sign_safe_right_constant <false> (u5, i2);
    check_less_sign_safe <false> (u5, i3);
    check_less_sign_safe <false> (u5, u3);
    check_less_sign_safe <false> (u5, i4);
    check_less_sign_safe <false> (u5, u4);
    check_less_sign_safe <false> (u5, u5);

    RIME_CHECK_EQUAL (rime::less_sign_safe (not_an_int(), not_an_int()), false);
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>Fix test for sign.hpp<commit_after>/*
Copyright 2013 Rogier van Dalen.

This file is part of Rogier van Dalen's Rime library for C++.

This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#define BOOST_TEST_MODULE test_rime_sign
#include "utility/test/boost_unit_test.hpp"

#include "rime/sign.hpp"

#include <string>
#include <type_traits>

#include <boost/mpl/assert.hpp>
#include <boost/mpl/int.hpp>

#include "rime/core.hpp"

#include "check_equal.hpp"

BOOST_AUTO_TEST_SUITE(test_rime_sign)

BOOST_AUTO_TEST_CASE (test_rime_sign_types) {
    // is_signed.
    static_assert (rime::types::is_signed <int>::value, "");
    static_assert (rime::types::is_signed <short>::value, "");
    static_assert (rime::types::is_signed <rime::int_ <-1>>::value, "");
    static_assert (rime::types::is_signed <boost::mpl::int_ <0>>::value, "");
    static_assert (rime::types::is_signed
        <std::integral_constant <int, 1>>::value, "");

    static_assert (!rime::types::is_signed <unsigned>::value, "");
    static_assert (!rime::types::is_signed <unsigned short>::value, "");
    static_assert (!rime::types::is_signed <std::size_t>::value, "");
    static_assert (!rime::types::is_signed <rime::size_t <0>>::value, "");
    static_assert (!rime::types::is_signed <rime::size_t <2>>::value, "");
    static_assert (!rime::types::is_signed <void>::value, "");
    static_assert (!rime::types::is_signed <std::string>::value, "");

    // is_unsigned.
    static_assert (rime::types::is_unsigned <unsigned>::value, "");
    static_assert (rime::types::is_unsigned <unsigned short>::value, "");
    static_assert (rime::types::is_unsigned <std::size_t>::value, "");
    static_assert (rime::types::is_unsigned <rime::size_t <0>>::value, "");
    static_assert (rime::types::is_unsigned <rime::size_t <2>>::value, "");

    static_assert (!rime::types::is_unsigned <int>::value, "");
    static_assert (!rime::types::is_unsigned <short>::value, "");
    static_assert (!rime::types::is_unsigned <rime::int_ <-1>>::value, "");
    static_assert (!rime::types::is_unsigned <boost::mpl::int_ <0>>::value, "");
    static_assert (!rime::types::is_unsigned <
        std::integral_constant <int, 1>>::value, "");

    static_assert (!rime::types::is_unsigned <void>::value, "");
    static_assert (!rime::types::is_unsigned <std::string>::value, "");

    // make_signed.
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <int>::type, int>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <unsigned>::type, int>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <short>::type, short>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_signed <unsigned short>::type, short>));

    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_signed <rime::int_ <1>>::type, rime::int_ <1>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_signed <rime::constant <unsigned, 1>>::type,
        rime::int_ <1>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_signed <std::integral_constant <unsigned, 2>>::type,
        rime::int_ <2>>));

    // make_unsigned.
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <int>::type, unsigned>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <unsigned>::type, unsigned>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <short>::type, short unsigned>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename rime::types::make_unsigned <unsigned short>::type,
        short unsigned>));

    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_unsigned <rime::int_ <1>>::type,
        rime::constant <unsigned, 1u>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_unsigned <rime::constant <int, 1>>::type,
        rime::constant <unsigned, 1u>>));
    BOOST_MPL_ASSERT ((rime::same_constant <
        rime::types::make_unsigned <std::integral_constant <int, 2>>::type,
        rime::constant <unsigned, 2u>>));

    // make_zero.
    RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <1>>::type(),
        rime::int_ <0>());
    RIME_CHECK_EQUAL (rime::types::make_zero <rime::int_ <-5>>::type(),
        rime::int_ <0>());
    RIME_CHECK_EQUAL (
        (rime::types::make_zero <rime::constant <unsigned, 1>>::type()),
        (rime::constant <unsigned, 0>()));
}

BOOST_AUTO_TEST_CASE (test_rime_sign_convert) {
    // make_signed.
    RIME_CHECK_EQUAL (rime::make_signed (1), 1);
    RIME_CHECK_EQUAL (rime::make_signed (1u), 1);

    RIME_CHECK_EQUAL (rime::make_signed (rime::int_ <1>()), rime::int_ <1>());
    RIME_CHECK_EQUAL (
        rime::make_signed (rime::constant <unsigned, 1u>()), rime::int_ <1>());

    // make_unsigned.
    RIME_CHECK_EQUAL (rime::make_unsigned (1), 1u);
    RIME_CHECK_EQUAL (rime::make_unsigned (1u), 1u);

    RIME_CHECK_EQUAL (rime::make_unsigned (rime::int_ <3>()),
        (rime::constant <unsigned, 3u>()));
    RIME_CHECK_EQUAL (rime::make_unsigned (rime::constant <unsigned, 2u>()),
        (rime::constant <unsigned, 2u>()));

    // make_zero.
    RIME_CHECK_EQUAL (rime::make_zero (1), 0);
    RIME_CHECK_EQUAL (rime::make_zero (1u), 0u);

    RIME_CHECK_EQUAL (rime::make_zero (rime::int_ <1>()), rime::int_ <0>());
    RIME_CHECK_EQUAL (
        rime::make_zero (rime::constant <unsigned, 1u>()),
        (rime::constant <unsigned, 0u>()));

}

// Signed constants.
typedef rime::int_ <int (unsigned (-1)/2 + 1)> very_negative_int;
very_negative_int i1;
boost::mpl::int_ <-4> i2;
std::integral_constant <int, 0> i3;
rime::int_ <30> i4;

rime::constant <unsigned, 0> u3;
rime::constant <unsigned, 30> u4;
typedef rime::constant <unsigned, unsigned (-1)> very_great_unsigned;
very_great_unsigned u5;

// Sanity check for constants.
static_assert (very_negative_int::value < 0, "Should be negative");
static_assert (int (very_great_unsigned::value) < 0,
    "Unsigned should wrongly convert to negative");

template <bool reference, class Left, class Right>
    void check_less_sign_safe (Left const & left, Right const & right)
{
    // Known at compile time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
        rime::bool_ <reference>());

    // Known only at run time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
        reference);
}

// The case where if the left operand is constant, the result is known.
// I.e. -1 < u for any unsigned u.
template <bool reference, class Left, class Right>
    void check_less_sign_safe_left_constant (
        Left const & left, Right const & right)
{
    // Known at compile time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
        rime::bool_ <reference>());
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value),
        rime::bool_ <reference>());

    // Known only at run time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
        reference);
}

// The case where if the right operand is constant, the result is known.
// I.e. u < -1 for any unsigned u.
template <bool reference, class Left, class Right>
    void check_less_sign_safe_right_constant (
        Left const & left, Right const & right)
{
    // Known at compile time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, right),
        rime::bool_ <reference>());
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, right),
        rime::bool_ <reference>());

    // Known only at run time.
    RIME_CHECK_EQUAL (rime::less_sign_safe (left, Right::value), reference);
    RIME_CHECK_EQUAL (rime::less_sign_safe (Left::value, Right::value),
        reference);
}

struct not_an_int {};

bool operator < (not_an_int, not_an_int) { return false; }

BOOST_AUTO_TEST_CASE (test_rime_less_sign_safe) {
    check_less_sign_safe <false> (i1, i1);
    check_less_sign_safe <true> (i1, i2);
    check_less_sign_safe <true> (i1, i3);
    check_less_sign_safe_left_constant <true> (i1, u3);
    check_less_sign_safe <true> (i1, i4);
    check_less_sign_safe_left_constant <true> (i1, u4);
    check_less_sign_safe_left_constant <true> (i1, u5);

    check_less_sign_safe <false> (i2, i1);
    check_less_sign_safe <false> (i2, i2);
    check_less_sign_safe <true> (i2, i3);
    check_less_sign_safe_left_constant <true> (i2, u3);
    check_less_sign_safe <true> (i2, i4);
    check_less_sign_safe_left_constant <true> (i2, u4);
    check_less_sign_safe_left_constant <true> (i2, u5);

    check_less_sign_safe <false> (i3, i1);
    check_less_sign_safe <false> (i3, i2);
    check_less_sign_safe <false> (i3, i3);
    check_less_sign_safe <false> (i3, u3);
    check_less_sign_safe <true> (i3, i4);
    check_less_sign_safe <true> (i3, u4);
    check_less_sign_safe <true> (i3, u5);

    check_less_sign_safe <false> (i4, i1);
    check_less_sign_safe <false> (i4, i2);
    check_less_sign_safe <false> (i4, i3);
    check_less_sign_safe <false> (i4, u3);
    check_less_sign_safe <false> (i4, i4);
    check_less_sign_safe <false> (i4, u4);
    check_less_sign_safe <true> (i4, u5);

    check_less_sign_safe_right_constant  <false> (u3, i1);
    check_less_sign_safe_right_constant  <false> (u3, i2);
    check_less_sign_safe <false> (u3, i3);
    check_less_sign_safe <false> (u3, u3);
    check_less_sign_safe <true> (u3, i4);
    check_less_sign_safe <true> (u3, u4);
    check_less_sign_safe <true> (u3, u5);

    check_less_sign_safe_right_constant <false> (u4, i1);
    check_less_sign_safe_right_constant <false> (u4, i2);
    check_less_sign_safe <false> (u4, i3);
    check_less_sign_safe <false> (u4, u3);
    check_less_sign_safe <false> (u4, i4);
    check_less_sign_safe <false> (u4, u4);
    check_less_sign_safe <true> (u4, u5);

    check_less_sign_safe_right_constant <false> (u5, i1);
    check_less_sign_safe_right_constant <false> (u5, i2);
    check_less_sign_safe <false> (u5, i3);
    check_less_sign_safe <false> (u5, u3);
    check_less_sign_safe <false> (u5, i4);
    check_less_sign_safe <false> (u5, u4);
    check_less_sign_safe <false> (u5, u5);

    RIME_CHECK_EQUAL (rime::less_sign_safe (not_an_int(), not_an_int()), false);
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: HtmlReader.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:17:56 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_HTMLREADER_HXX
#define DBAUI_HTMLREADER_HXX

#ifndef DBAUI_DATABASEEXPORT_HXX
#include "DExport.hxx"
#endif
#ifndef _PARHTML_HXX //autogen
#include <svtools/parhtml.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif

namespace dbaui
{
    //===============================================================================================
    // OHTMLReader
    //===============================================================================================
    class OHTMLReader : public HTMLParser, public ODatabaseExport
    {

        sal_Int32           m_nTableCount;
        sal_Int16           m_nWidth;
        sal_Int16           m_nColumnWidth;     // max. Spaltenbreite
        sal_Bool            m_bMetaOptions;     // true when we scaned the meta information
        sal_Bool            m_bSDNum;
    protected:
        virtual void        NextToken( int nToken ); // Basisklasse
        virtual sal_Bool    CreateTable(int nToken);

        /** createPage creates the tabpage for this type
            @param  _pParent    teh parent window
        */
        virtual OWizTypeSelect* createPage(Window* _pParent);

        void                TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken);
        void                TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor);
        sal_Int16           GetWidthPixel( const HTMLOption* pOption );
        rtl_TextEncoding    GetEncodingByMIME( const String& rMime );
        void                setTextEncoding();
        ~OHTMLReader();
    public:
        OHTMLReader(SvStream& rIn,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                    const TColumnVector* rList = 0,
                    const OTypeInfoMap* _pInfoMap = 0);
        // wird f"ur auto. Typ-Erkennung gebraucht
        OHTMLReader(SvStream& rIn,
                    sal_Int32 nRows,
                    const TPositions &_rColumnPositions,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                    const TColumnVector* rList = 0,
                    const OTypeInfoMap* _pInfoMap = 0);

        virtual     SvParserState CallParser();// Basisklasse
        virtual     void          release();
        // birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde
    };

    SV_DECL_IMPL_REF( OHTMLReader );
}
#endif // DBAUI_HTMLREADER_HXX

<commit_msg>INTEGRATION: CWS dba201b (1.7.420); FILE MERGED 2005/09/21 08:58:12 oj 1.7.420.2: RESYNC: (1.7-1.8); FILE MERGED 2005/07/20 09:56:40 fs 1.7.420.1: #i51255# XConnection replaced with SharedConnection, and DataSourceHolder replaced with SharedModel<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: HtmlReader.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2005-09-23 12:33:23 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_HTMLREADER_HXX
#define DBAUI_HTMLREADER_HXX

#ifndef DBAUI_DATABASEEXPORT_HXX
#include "DExport.hxx"
#endif
#ifndef _PARHTML_HXX //autogen
#include <svtools/parhtml.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_FONTDESCRIPTOR_HPP_
#include <com/sun/star/awt/FontDescriptor.hpp>
#endif

namespace dbaui
{
    //===============================================================================================
    // OHTMLReader
    //===============================================================================================
    class OHTMLReader : public HTMLParser, public ODatabaseExport
    {

        sal_Int32           m_nTableCount;
        sal_Int16           m_nWidth;
        sal_Int16           m_nColumnWidth;     // max. Spaltenbreite
        sal_Bool            m_bMetaOptions;     // true when we scaned the meta information
        sal_Bool            m_bSDNum;
    protected:
        virtual void        NextToken( int nToken ); // Basisklasse
        virtual sal_Bool    CreateTable(int nToken);

        /** createPage creates the tabpage for this type
            @param  _pParent    teh parent window
        */
        virtual OWizTypeSelect* createPage(Window* _pParent);

        void                TableDataOn(SvxCellHorJustify& eVal,String *pValue,int nToken);
        void                TableFontOn(::com::sun::star::awt::FontDescriptor& _rFont,sal_Int32 &_rTextColor);
        sal_Int16           GetWidthPixel( const HTMLOption* pOption );
        rtl_TextEncoding    GetEncodingByMIME( const String& rMime );
        void                setTextEncoding();
        ~OHTMLReader();
    public:
        OHTMLReader(SvStream& rIn,
                    const SharedConnection& _rxConnection,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                    const TColumnVector* rList = 0,
                    const OTypeInfoMap* _pInfoMap = 0);
        // wird f"ur auto. Typ-Erkennung gebraucht
        OHTMLReader(SvStream& rIn,
                    sal_Int32 nRows,
                    const TPositions &_rColumnPositions,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >& _rxNumberF,
                    const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM,
                    const TColumnVector* rList = 0,
                    const OTypeInfoMap* _pInfoMap = 0);

        virtual     SvParserState CallParser();// Basisklasse
        virtual     void          release();
        // birgt nur korrekte Daten, wenn der 2. CTOR benutzt wurde
    };

    SV_DECL_IMPL_REF( OHTMLReader );
}
#endif // DBAUI_HTMLREADER_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: evntpost.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:26:30 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <vcl/evntpost.hxx>
#include <vcl/svapp.hxx>

namespace vcl
{

EventPoster::EventPoster( const Link& rLink )
    : m_aLink(rLink)
{
    m_nId = 0;
}

EventPoster::~EventPoster()
{
    if ( m_nId )
        GetpApp()->RemoveUserEvent( m_nId );
}

void EventPoster::Post( UserEvent* pEvent )

{
    m_nId = GetpApp()->PostUserEvent( ( LINK( this, EventPoster, DoEvent_Impl ) ), pEvent );
}

IMPL_LINK_INLINE_START( EventPoster, DoEvent_Impl, UserEvent*, pEvent )
{
    m_nId = 0;
    m_aLink.Call( pEvent );
    return 0;
}
IMPL_LINK_INLINE_END( EventPoster, DoEvent_Impl, UserEvent*, pEvent )

}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.248); FILE MERGED 2008/03/28 15:44:52 rt 1.7.248.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: evntpost.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <vcl/evntpost.hxx>
#include <vcl/svapp.hxx>

namespace vcl
{

EventPoster::EventPoster( const Link& rLink )
    : m_aLink(rLink)
{
    m_nId = 0;
}

EventPoster::~EventPoster()
{
    if ( m_nId )
        GetpApp()->RemoveUserEvent( m_nId );
}

void EventPoster::Post( UserEvent* pEvent )

{
    m_nId = GetpApp()->PostUserEvent( ( LINK( this, EventPoster, DoEvent_Impl ) ), pEvent );
}

IMPL_LINK_INLINE_START( EventPoster, DoEvent_Impl, UserEvent*, pEvent )
{
    m_nId = 0;
    m_aLink.Call( pEvent );
    return 0;
}
IMPL_LINK_INLINE_END( EventPoster, DoEvent_Impl, UserEvent*, pEvent )

}
<|endoftext|>