<commit_before>/*
    Copyright 2005 - 2006 Roman Plasil
	http://foo-title.sourceforge.net
    This file is part of foo_title.

    foo_title is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    foo_title 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 foo_title; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "stdafx.h"
#include <vcclr.h>

using namespace fooManagedWrapper;
using namespace std;
using namespace System::Collections::Generic;

namespace fooManagedWrapper {

	CManagedMainMenuCommands::CManagedMainMenuCommands(List<CCommand ^> ^_cmds) {
		commonInit();
		cmds = _cmds;
	};

	CManagedMainMenuCommands::CManagedMainMenuCommands() {
		commonInit();
	}

	void CManagedMainMenuCommands::commonInit() {
		cmds = gcnew List<CCommand ^>();
		CManagedWrapper::getInstance()->AddService(this);

		wrapper = new CMainMenuCommandsFactoryWrapper();
		wrapper->mainMenuCommands.get_static_instance().SetImplementation(this);
	}

	CManagedMainMenuCommands::!CManagedMainMenuCommands() {
		this->~CManagedMainMenuCommands();
	}

	CManagedMainMenuCommands::~CManagedMainMenuCommands() {
		delete wrapper;
	}

	unsigned int CManagedMainMenuCommands::GetCommandsCount() {
		return cmds->Count;
	}

	Guid CManagedMainMenuCommands::GetGuid(unsigned int index) {
		return cmds[index]->GetGuid();
	}

	String ^CManagedMainMenuCommands::GetName(unsigned int index) {
		return cmds[index]->GetName();
	}

	bool CManagedMainMenuCommands::GetDescription(unsigned int index, String ^ %desc) {
		return cmds[index]->GetDescription(desc);
	}

	void CManagedMainMenuCommands::Execute(unsigned int index) {
		return cmds[index]->Execute();
	}

	bool CManagedMainMenuCommands::GetDisplay(unsigned int index, String ^ %text, unsigned int %flags) {
		return cmds[index]->GetDisplay(text, flags);
	}

	void CCustomMainMenuCommands::SetImplementation(gcroot<CManagedMainMenuCommands ^> impl) {
		managedMainMenuCommands = impl;
	}

	t_uint32 CCustomMainMenuCommands::get_command_count() {
		return managedMainMenuCommands->GetCommandsCount();
	}

	GUID CCustomMainMenuCommands::get_command(t_uint32 p_index) {
		return CManagedWrapper::ToGUID(managedMainMenuCommands->GetGuid(p_index));
	}

	void CCustomMainMenuCommands::get_name(t_uint32 p_index, pfc::string_base & p_out) {
		const char *c_str = CManagedWrapper::ToCString(managedMainMenuCommands->GetName(p_index));
		p_out = c_str;
		CManagedWrapper::FreeCString(c_str);
	}

	bool CCustomMainMenuCommands::get_description(t_uint32 p_index, pfc::string_base &p_out) {
		String ^str2 = gcnew String("");
		bool res;
		res = managedMainMenuCommands->GetDescription(p_index, (String ^)str2);
		const char *c_str = CManagedWrapper::ToCString(str2);
		p_out = c_str;
		CManagedWrapper::FreeCString(c_str);
		return res;
	}

	GUID CCustomMainMenuCommands::get_parent() {
		return CManagedWrapper::ToGUID(managedMainMenuCommands->GetCommandsParent());
	}

	void CCustomMainMenuCommands::execute(t_uint32 p_index, service_ptr_t<service_base> p_callback) {
		managedMainMenuCommands->Execute(p_index);
	}

	unsigned int CCustomMainMenuCommands::get_sort_priority() {
		return managedMainMenuCommands->GetCommandsSortPriority();
	}

	bool CCustomMainMenuCommands::get_display(t_uint32 p_index,pfc::string_base & p_text,t_uint32 & p_flags) {
		String ^str = gcnew String("");
		bool res = managedMainMenuCommands->GetDisplay(p_index, str, p_flags);
		const char *c_str = CManagedWrapper::ToCString(str);
		p_text = c_str;
		CManagedWrapper::FreeCString(c_str);
		return res;
	}

};<commit_msg>fixed unicode characters<commit_after>/*
    Copyright 2005 - 2006 Roman Plasil
	http://foo-title.sourceforge.net
    This file is part of foo_title.

    foo_title is free software; you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation; either version 2.1 of the License, or
    (at your option) any later version.

    foo_title 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 foo_title; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "stdafx.h"
#include <vcclr.h>

using namespace fooManagedWrapper;
using namespace std;
using namespace System::Collections::Generic;
using namespace System::Text;

namespace fooManagedWrapper {

	CManagedMainMenuCommands::CManagedMainMenuCommands(List<CCommand ^> ^_cmds) {
		commonInit();
		cmds = _cmds;
	};

	CManagedMainMenuCommands::CManagedMainMenuCommands() {
		commonInit();
	}

	void CManagedMainMenuCommands::commonInit() {
		cmds = gcnew List<CCommand ^>();
		CManagedWrapper::getInstance()->AddService(this);

		wrapper = new CMainMenuCommandsFactoryWrapper();
		wrapper->mainMenuCommands.get_static_instance().SetImplementation(this);
	}

	CManagedMainMenuCommands::!CManagedMainMenuCommands() {
		this->~CManagedMainMenuCommands();
	}

	CManagedMainMenuCommands::~CManagedMainMenuCommands() {
		delete wrapper;
	}

	unsigned int CManagedMainMenuCommands::GetCommandsCount() {
		return cmds->Count;
	}

	Guid CManagedMainMenuCommands::GetGuid(unsigned int index) {
		return cmds[index]->GetGuid();
	}

	String ^CManagedMainMenuCommands::GetName(unsigned int index) {
		return cmds[index]->GetName();
	}

	bool CManagedMainMenuCommands::GetDescription(unsigned int index, String ^ %desc) {
		return cmds[index]->GetDescription(desc);
	}

	void CManagedMainMenuCommands::Execute(unsigned int index) {
		return cmds[index]->Execute();
	}

	bool CManagedMainMenuCommands::GetDisplay(unsigned int index, String ^ %text, unsigned int %flags) {
		return cmds[index]->GetDisplay(text, flags);
	}

	void CCustomMainMenuCommands::SetImplementation(gcroot<CManagedMainMenuCommands ^> impl) {
		managedMainMenuCommands = impl;
	}

	t_uint32 CCustomMainMenuCommands::get_command_count() {
		return managedMainMenuCommands->GetCommandsCount();
	}

	GUID CCustomMainMenuCommands::get_command(t_uint32 p_index) {
		return CManagedWrapper::ToGUID(managedMainMenuCommands->GetGuid(p_index));
	}

	void CCustomMainMenuCommands::get_name(t_uint32 p_index, pfc::string_base & p_out) {
		p_out = CManagedWrapper::StringToPfcString(managedMainMenuCommands->GetName(p_index));
	}

	bool CCustomMainMenuCommands::get_description(t_uint32 p_index, pfc::string_base &p_out) {
		String ^str;
		bool res = managedMainMenuCommands->GetDescription(p_index, str);
		p_out = CManagedWrapper::StringToPfcString(str);
		return res;
	}

	GUID CCustomMainMenuCommands::get_parent() {
		return CManagedWrapper::ToGUID(managedMainMenuCommands->GetCommandsParent());
	}

	void CCustomMainMenuCommands::execute(t_uint32 p_index, service_ptr_t<service_base> p_callback) {
		managedMainMenuCommands->Execute(p_index);
	}

	unsigned int CCustomMainMenuCommands::get_sort_priority() {
		return managedMainMenuCommands->GetCommandsSortPriority();
	}

	bool CCustomMainMenuCommands::get_display(t_uint32 p_index,pfc::string_base & p_text,t_uint32 & p_flags) {
		String ^str;
		bool res = managedMainMenuCommands->GetDisplay(p_index, str, p_flags);
		p_text = CManagedWrapper::StringToPfcString(str);
		return res;
	}

};<|endoftext|>


<commit_before><commit_msg>fix ambiguity in argument<commit_after><|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "TagTestProblem.h"
#include "NonlinearSystem.h"

template <>
InputParameters
validParams<TagTestProblem>()
{
  InputParameters params = validParams<FEProblem>();

  MultiMooseEnum test_tagvs(" ", " ", true);
  MultiMooseEnum test_tagms(" ", " ", true);

  params.addParam<MultiMooseEnum>(
      "test_tag_vectors", test_tagvs, "Vector tags we are going to test against ");

  params.addParam<MultiMooseEnum>(
      "test_tag_matrices", test_tagms, "Matrix tags we are going to test against");

  return params;
}

TagTestProblem::TagTestProblem(const InputParameters & params) : FEProblem(params)
{
  auto & vectortags = params.get<MultiMooseEnum>("test_tag_vectors");

  vtags.clear();
  for (auto & vtag : vectortags)
    vtags.insert(vtag);

  auto & matrixtags = params.get<MultiMooseEnum>("test_tag_matrices");

  mtags.clear();
  for (auto & mtag : matrixtags)
    mtags.insert(mtag);
}

void
TagTestProblem::computeResidual(const NumericVector<Number> & soln,
                                NumericVector<Number> & residual)
{
  _fe_vector_tags.clear();

  for (auto & vtag : vtags)
    if (vectorTagExists(vtag))
    {
      auto tag = getVectorTagID(vtag);
      _fe_vector_tags.insert(tag);
    }
    else
      mooseError("Tag ", vtag, " does not exist");

  _nl->setSolution(soln);

  if (_fe_vector_tags.find(_nl->residualVectorTag()) != _fe_vector_tags.end())
    _nl->associateVectorToTag(residual, _nl->residualVectorTag());

  computeResidualTags(_fe_vector_tags);

  if (_fe_vector_tags.find(_nl->residualVectorTag()) != _fe_vector_tags.end())
    _nl->disassociateVectorFromTag(residual, _nl->residualVectorTag());
}

void
TagTestProblem::computeJacobian(const NumericVector<Number> & soln, SparseMatrix<Number> & jacobian)
{
  _fe_matrix_tags.clear();

  for (auto & mtag : mtags)
    if (matrixTagExists(mtag))
    {
      auto tag = getMatrixTagID(mtag);
      _fe_matrix_tags.insert(tag);
    }
    else
      mooseError("Tag ", mtag, " does not exist");

  _nl->setSolution(soln);

  if (_fe_matrix_tags.size() > 0)
    _nl->associateMatrixToTag(jacobian, *_fe_matrix_tags.begin());

  computeJacobianTags(_fe_matrix_tags);

  if (_fe_matrix_tags.size() > 0)
    _nl->disassociateMatrixFromTag(jacobian, *_fe_matrix_tags.begin());
}
<commit_msg>Register TagTestProblem using the new way<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "TagTestProblem.h"
#include "NonlinearSystem.h"

registerMooseObject("MooseTestApp", TagTestProblem);

template <>
InputParameters
validParams<TagTestProblem>()
{
  InputParameters params = validParams<FEProblem>();

  MultiMooseEnum test_tagvs(" ", " ", true);
  MultiMooseEnum test_tagms(" ", " ", true);

  params.addParam<MultiMooseEnum>(
      "test_tag_vectors", test_tagvs, "Vector tags we are going to test against ");

  params.addParam<MultiMooseEnum>(
      "test_tag_matrices", test_tagms, "Matrix tags we are going to test against");

  return params;
}

TagTestProblem::TagTestProblem(const InputParameters & params) : FEProblem(params)
{
  auto & vectortags = params.get<MultiMooseEnum>("test_tag_vectors");

  vtags.clear();
  for (auto & vtag : vectortags)
    vtags.insert(vtag);

  auto & matrixtags = params.get<MultiMooseEnum>("test_tag_matrices");

  mtags.clear();
  for (auto & mtag : matrixtags)
    mtags.insert(mtag);
}

void
TagTestProblem::computeResidual(const NumericVector<Number> & soln,
                                NumericVector<Number> & residual)
{
  _fe_vector_tags.clear();

  for (auto & vtag : vtags)
    if (vectorTagExists(vtag))
    {
      auto tag = getVectorTagID(vtag);
      _fe_vector_tags.insert(tag);
    }
    else
      mooseError("Tag ", vtag, " does not exist");

  _nl->setSolution(soln);

  if (_fe_vector_tags.find(_nl->residualVectorTag()) != _fe_vector_tags.end())
    _nl->associateVectorToTag(residual, _nl->residualVectorTag());

  computeResidualTags(_fe_vector_tags);

  if (_fe_vector_tags.find(_nl->residualVectorTag()) != _fe_vector_tags.end())
    _nl->disassociateVectorFromTag(residual, _nl->residualVectorTag());
}

void
TagTestProblem::computeJacobian(const NumericVector<Number> & soln, SparseMatrix<Number> & jacobian)
{
  _fe_matrix_tags.clear();

  for (auto & mtag : mtags)
    if (matrixTagExists(mtag))
    {
      auto tag = getMatrixTagID(mtag);
      _fe_matrix_tags.insert(tag);
    }
    else
      mooseError("Tag ", mtag, " does not exist");

  _nl->setSolution(soln);

  if (_fe_matrix_tags.size() > 0)
    _nl->associateMatrixToTag(jacobian, *_fe_matrix_tags.begin());

  computeJacobianTags(_fe_matrix_tags);

  if (_fe_matrix_tags.size() > 0)
    _nl->disassociateMatrixFromTag(jacobian, *_fe_matrix_tags.begin());
}
<|endoftext|>


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

#include <signal.h>
#include <stddef.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "gtest/gtest.h"
#include "test/util/signal_util.h"
#include "test/util/test_util.h"

namespace gvisor {
namespace testing {

namespace {

// Signals numbers used for testing.
static constexpr int kTestSignal1 = SIGUSR1;
static constexpr int kTestSignal2 = SIGUSR2;

static int raw_sigprocmask(int how, const sigset_t* set, sigset_t* oldset) {
  return syscall(SYS_rt_sigprocmask, how, set, oldset, _NSIG / 8);
}

// count of the number of signals received
int signal_count[kMaxSignal + 1];

// signal handler increments the signal counter
void SigHandler(int sig, siginfo_t* info, void* context) {
  TEST_CHECK(sig > 0 && sig <= kMaxSignal);
  signal_count[sig] += 1;
}

// The test fixture saves and restores the signal mask and
// sets up handlers for kTestSignal1 and kTestSignal2.
class SigProcMaskTest : public ::testing::Test {
 protected:
  void SetUp() override {
    // Save the current signal mask.
    EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &mask_),
                SyscallSucceeds());

    // Setup signal handlers for kTestSignal1 and kTestSignal2.
    struct sigaction sa;
    sa.sa_sigaction = SigHandler;
    sigfillset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO;
    EXPECT_THAT(sigaction(kTestSignal1, &sa, &sa_test_sig_1_),
                SyscallSucceeds());
    EXPECT_THAT(sigaction(kTestSignal2, &sa, &sa_test_sig_2_),
                SyscallSucceeds());

    // Clear the signal counters.
    memset(signal_count, 0, sizeof(signal_count));
  }

  void TearDown() override {
    // Restore the signal mask.
    EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &mask_, nullptr),
                SyscallSucceeds());

    // Restore the signal handlers for kTestSignal1 and kTestSignal2.
    EXPECT_THAT(sigaction(kTestSignal1, &sa_test_sig_1_, nullptr),
                SyscallSucceeds());
    EXPECT_THAT(sigaction(kTestSignal2, &sa_test_sig_2_, nullptr),
                SyscallSucceeds());
  }

 private:
  sigset_t mask_;
  struct sigaction sa_test_sig_1_;
  struct sigaction sa_test_sig_2_;
};

// Both sigsets nullptr should succeed and do nothing.
TEST_F(SigProcMaskTest, NullAddress) {
  EXPECT_THAT(raw_sigprocmask(SIG_BLOCK, nullptr, NULL), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, nullptr, NULL), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, NULL), SyscallSucceeds());
}

// Bad address for either sigset should fail with EFAULT.
TEST_F(SigProcMaskTest, BadAddress) {
  sigset_t* bad_addr = reinterpret_cast<sigset_t*>(-1);

  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, bad_addr, nullptr),
              SyscallFailsWithErrno(EFAULT));

  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, bad_addr),
              SyscallFailsWithErrno(EFAULT));
}

// Bad value of the "how" parameter should fail with EINVAL.
TEST_F(SigProcMaskTest, BadParameter) {
  int bad_param_1 = -1;
  int bad_param_2 = 42;

  sigset_t set1;
  sigemptyset(&set1);

  EXPECT_THAT(raw_sigprocmask(bad_param_1, &set1, nullptr),
              SyscallFailsWithErrno(EINVAL));

  EXPECT_THAT(raw_sigprocmask(bad_param_2, &set1, nullptr),
              SyscallFailsWithErrno(EINVAL));
}

// Check that we can get the current signal mask.
TEST_F(SigProcMaskTest, GetMask) {
  sigset_t set1;
  sigset_t set2;

  sigemptyset(&set1);
  sigfillset(&set2);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &set1), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &set2), SyscallSucceeds());
  EXPECT_THAT(set1, EqualsSigset(set2));
}

// Check that we can set the signal mask.
TEST_F(SigProcMaskTest, SetMask) {
  sigset_t actual;
  sigset_t expected;

  // Try to mask all signals
  sigfillset(&expected);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  // sigprocmask() should have silently ignored SIGKILL and SIGSTOP.
  sigdelset(&expected, SIGSTOP);
  sigdelset(&expected, SIGKILL);
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to clear the signal mask
  sigemptyset(&expected);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to set a mask with one signal.
  sigemptyset(&expected);
  sigaddset(&expected, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  EXPECT_THAT(actual, EqualsSigset(expected));
}

// Check that we can add and remove signals.
TEST_F(SigProcMaskTest, BlockUnblock) {
  sigset_t actual;
  sigset_t expected;

  // Try to set a mask with one signal.
  sigemptyset(&expected);
  sigaddset(&expected, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to add another signal.
  sigset_t block;
  sigemptyset(&block);
  sigaddset(&block, kTestSignal2);
  EXPECT_THAT(raw_sigprocmask(SIG_BLOCK, &block, nullptr), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  sigaddset(&expected, kTestSignal2);
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to remove a signal.
  sigset_t unblock;
  sigemptyset(&unblock);
  sigaddset(&unblock, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, &unblock, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  sigdelset(&expected, kTestSignal1);
  EXPECT_THAT(actual, EqualsSigset(expected));
}

// Test that the signal mask actually blocks signals.
TEST_F(SigProcMaskTest, SignalHandler) {
  sigset_t mask;

  // clear the signal mask
  sigemptyset(&mask);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &mask, nullptr), SyscallSucceeds());

  // Check the initial signal counts.
  EXPECT_EQ(0, signal_count[kTestSignal1]);
  EXPECT_EQ(0, signal_count[kTestSignal2]);

  // Check that both kTestSignal1 and kTestSignal2 are not blocked.
  raise(kTestSignal1);
  raise(kTestSignal2);
  EXPECT_EQ(1, signal_count[kTestSignal1]);
  EXPECT_EQ(1, signal_count[kTestSignal2]);

  // Block kTestSignal1.
  sigaddset(&mask, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_BLOCK, &mask, nullptr), SyscallSucceeds());

  // Check that kTestSignal1 is blocked.
  raise(kTestSignal1);
  raise(kTestSignal2);
  EXPECT_EQ(1, signal_count[kTestSignal1]);
  EXPECT_EQ(2, signal_count[kTestSignal2]);

  // Unblock kTestSignal1.
  sigaddset(&mask, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, &mask, nullptr), SyscallSucceeds());

  // Check that the unblocked kTestSignal1 has been delivered.
  // TODO: gvisor currently drops masked signals on the floor.
  if (!IsRunningOnGvisor()) {
    EXPECT_EQ(2, signal_count[kTestSignal1]);
  }
  EXPECT_EQ(2, signal_count[kTestSignal2]);
}

// Check that sigprocmask correctly handles aliasing of the set and oldset
// pointers.
TEST_F(SigProcMaskTest, AliasedSets) {
  sigset_t mask;

  // Set a mask in which only kTestSignal1 is blocked.
  sigset_t mask1;
  sigemptyset(&mask1);
  sigaddset(&mask1, kTestSignal1);
  mask = mask1;
  ASSERT_THAT(raw_sigprocmask(SIG_SETMASK, &mask, nullptr), SyscallSucceeds());

  // Exchange it with a mask in which only kTestSignal2 is blocked.
  sigset_t mask2;
  sigemptyset(&mask2);
  sigaddset(&mask2, kTestSignal2);
  mask = mask2;
  ASSERT_THAT(raw_sigprocmask(SIG_SETMASK, &mask, &mask), SyscallSucceeds());

  // Check that the exchange succeeeded:
  // mask should now contain the previously-set mask blocking only kTestSignal1.
  EXPECT_THAT(mask, EqualsSigset(mask1));
  // The current mask should block only kTestSignal2.
  ASSERT_THAT(raw_sigprocmask(0, nullptr, &mask), SyscallSucceeds());
  EXPECT_THAT(mask, EqualsSigset(mask2));
}

}  // namespace

}  // namespace testing
}  // namespace gvisor
<commit_msg>Convert outdated TODO to NOTE.<commit_after>// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <signal.h>
#include <stddef.h>
#include <sys/syscall.h>
#include <unistd.h>

#include "gtest/gtest.h"
#include "test/util/signal_util.h"
#include "test/util/test_util.h"

namespace gvisor {
namespace testing {

namespace {

// Signals numbers used for testing.
static constexpr int kTestSignal1 = SIGUSR1;
static constexpr int kTestSignal2 = SIGUSR2;

static int raw_sigprocmask(int how, const sigset_t* set, sigset_t* oldset) {
  return syscall(SYS_rt_sigprocmask, how, set, oldset, _NSIG / 8);
}

// count of the number of signals received
int signal_count[kMaxSignal + 1];

// signal handler increments the signal counter
void SigHandler(int sig, siginfo_t* info, void* context) {
  TEST_CHECK(sig > 0 && sig <= kMaxSignal);
  signal_count[sig] += 1;
}

// The test fixture saves and restores the signal mask and
// sets up handlers for kTestSignal1 and kTestSignal2.
class SigProcMaskTest : public ::testing::Test {
 protected:
  void SetUp() override {
    // Save the current signal mask.
    EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &mask_),
                SyscallSucceeds());

    // Setup signal handlers for kTestSignal1 and kTestSignal2.
    struct sigaction sa;
    sa.sa_sigaction = SigHandler;
    sigfillset(&sa.sa_mask);
    sa.sa_flags = SA_SIGINFO;
    EXPECT_THAT(sigaction(kTestSignal1, &sa, &sa_test_sig_1_),
                SyscallSucceeds());
    EXPECT_THAT(sigaction(kTestSignal2, &sa, &sa_test_sig_2_),
                SyscallSucceeds());

    // Clear the signal counters.
    memset(signal_count, 0, sizeof(signal_count));
  }

  void TearDown() override {
    // Restore the signal mask.
    EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &mask_, nullptr),
                SyscallSucceeds());

    // Restore the signal handlers for kTestSignal1 and kTestSignal2.
    EXPECT_THAT(sigaction(kTestSignal1, &sa_test_sig_1_, nullptr),
                SyscallSucceeds());
    EXPECT_THAT(sigaction(kTestSignal2, &sa_test_sig_2_, nullptr),
                SyscallSucceeds());
  }

 private:
  sigset_t mask_;
  struct sigaction sa_test_sig_1_;
  struct sigaction sa_test_sig_2_;
};

// Both sigsets nullptr should succeed and do nothing.
TEST_F(SigProcMaskTest, NullAddress) {
  EXPECT_THAT(raw_sigprocmask(SIG_BLOCK, nullptr, NULL), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, nullptr, NULL), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, NULL), SyscallSucceeds());
}

// Bad address for either sigset should fail with EFAULT.
TEST_F(SigProcMaskTest, BadAddress) {
  sigset_t* bad_addr = reinterpret_cast<sigset_t*>(-1);

  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, bad_addr, nullptr),
              SyscallFailsWithErrno(EFAULT));

  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, bad_addr),
              SyscallFailsWithErrno(EFAULT));
}

// Bad value of the "how" parameter should fail with EINVAL.
TEST_F(SigProcMaskTest, BadParameter) {
  int bad_param_1 = -1;
  int bad_param_2 = 42;

  sigset_t set1;
  sigemptyset(&set1);

  EXPECT_THAT(raw_sigprocmask(bad_param_1, &set1, nullptr),
              SyscallFailsWithErrno(EINVAL));

  EXPECT_THAT(raw_sigprocmask(bad_param_2, &set1, nullptr),
              SyscallFailsWithErrno(EINVAL));
}

// Check that we can get the current signal mask.
TEST_F(SigProcMaskTest, GetMask) {
  sigset_t set1;
  sigset_t set2;

  sigemptyset(&set1);
  sigfillset(&set2);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &set1), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &set2), SyscallSucceeds());
  EXPECT_THAT(set1, EqualsSigset(set2));
}

// Check that we can set the signal mask.
TEST_F(SigProcMaskTest, SetMask) {
  sigset_t actual;
  sigset_t expected;

  // Try to mask all signals
  sigfillset(&expected);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  // sigprocmask() should have silently ignored SIGKILL and SIGSTOP.
  sigdelset(&expected, SIGSTOP);
  sigdelset(&expected, SIGKILL);
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to clear the signal mask
  sigemptyset(&expected);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to set a mask with one signal.
  sigemptyset(&expected);
  sigaddset(&expected, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  EXPECT_THAT(actual, EqualsSigset(expected));
}

// Check that we can add and remove signals.
TEST_F(SigProcMaskTest, BlockUnblock) {
  sigset_t actual;
  sigset_t expected;

  // Try to set a mask with one signal.
  sigemptyset(&expected);
  sigaddset(&expected, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &expected, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to add another signal.
  sigset_t block;
  sigemptyset(&block);
  sigaddset(&block, kTestSignal2);
  EXPECT_THAT(raw_sigprocmask(SIG_BLOCK, &block, nullptr), SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  sigaddset(&expected, kTestSignal2);
  EXPECT_THAT(actual, EqualsSigset(expected));

  // Try to remove a signal.
  sigset_t unblock;
  sigemptyset(&unblock);
  sigaddset(&unblock, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, &unblock, nullptr),
              SyscallSucceeds());
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, nullptr, &actual),
              SyscallSucceeds());
  sigdelset(&expected, kTestSignal1);
  EXPECT_THAT(actual, EqualsSigset(expected));
}

// Test that the signal mask actually blocks signals.
TEST_F(SigProcMaskTest, SignalHandler) {
  sigset_t mask;

  // clear the signal mask
  sigemptyset(&mask);
  EXPECT_THAT(raw_sigprocmask(SIG_SETMASK, &mask, nullptr), SyscallSucceeds());

  // Check the initial signal counts.
  EXPECT_EQ(0, signal_count[kTestSignal1]);
  EXPECT_EQ(0, signal_count[kTestSignal2]);

  // Check that both kTestSignal1 and kTestSignal2 are not blocked.
  raise(kTestSignal1);
  raise(kTestSignal2);
  EXPECT_EQ(1, signal_count[kTestSignal1]);
  EXPECT_EQ(1, signal_count[kTestSignal2]);

  // Block kTestSignal1.
  sigaddset(&mask, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_BLOCK, &mask, nullptr), SyscallSucceeds());

  // Check that kTestSignal1 is blocked.
  raise(kTestSignal1);
  raise(kTestSignal2);
  EXPECT_EQ(1, signal_count[kTestSignal1]);
  EXPECT_EQ(2, signal_count[kTestSignal2]);

  // Unblock kTestSignal1.
  sigaddset(&mask, kTestSignal1);
  EXPECT_THAT(raw_sigprocmask(SIG_UNBLOCK, &mask, nullptr), SyscallSucceeds());

  // Check that the unblocked kTestSignal1 has been delivered.
  // Note: gvisor currently drops masked signals on the floor.
  if (!IsRunningOnGvisor()) {
    EXPECT_EQ(2, signal_count[kTestSignal1]);
  }
  EXPECT_EQ(2, signal_count[kTestSignal2]);
}

// Check that sigprocmask correctly handles aliasing of the set and oldset
// pointers.
TEST_F(SigProcMaskTest, AliasedSets) {
  sigset_t mask;

  // Set a mask in which only kTestSignal1 is blocked.
  sigset_t mask1;
  sigemptyset(&mask1);
  sigaddset(&mask1, kTestSignal1);
  mask = mask1;
  ASSERT_THAT(raw_sigprocmask(SIG_SETMASK, &mask, nullptr), SyscallSucceeds());

  // Exchange it with a mask in which only kTestSignal2 is blocked.
  sigset_t mask2;
  sigemptyset(&mask2);
  sigaddset(&mask2, kTestSignal2);
  mask = mask2;
  ASSERT_THAT(raw_sigprocmask(SIG_SETMASK, &mask, &mask), SyscallSucceeds());

  // Check that the exchange succeeeded:
  // mask should now contain the previously-set mask blocking only kTestSignal1.
  EXPECT_THAT(mask, EqualsSigset(mask1));
  // The current mask should block only kTestSignal2.
  ASSERT_THAT(raw_sigprocmask(0, nullptr, &mask), SyscallSucceeds());
  EXPECT_THAT(mask, EqualsSigset(mask2));
}

}  // namespace

}  // namespace testing
}  // namespace gvisor
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2012 The QXmpp developers
 *
 * Author:
 *  Manjeet Dahiya
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppDiscoveryManager.h"

#include <QDomElement>
#include <QCoreApplication>

#include "QXmppClient.h"
#include "QXmppConstants.h"
#include "QXmppDataForm.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppStream.h"
#include "QXmppGlobal.h"

class QXmppDiscoveryManagerPrivate
{
public:
    QString clientCapabilitiesNode;
    QString clientCategory;
    QString clientType;
    QString clientName;
    QXmppDataForm clientInfoForm;
};

QXmppDiscoveryManager::QXmppDiscoveryManager()
    : d(new QXmppDiscoveryManagerPrivate)
{
    d->clientCapabilitiesNode = "http://code.google.com/p/qxmpp";
    d->clientCategory = "client";
    d->clientType = "pc";
    if (qApp->applicationName().isEmpty() && qApp->applicationVersion().isEmpty())
        d->clientName = QString("%1 %2").arg("Based on QXmpp", QXmppVersion());
    else
        d->clientName = QString("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion());
}

QXmppDiscoveryManager::~QXmppDiscoveryManager()
{
    delete d;
}

/// Requests information from the specified XMPP entity.
///
/// \param jid  The target entity's JID.
/// \param node The target node (optional).

QString QXmppDiscoveryManager::requestInfo(const QString& jid, const QString& node)
{
    QXmppDiscoveryIq request;
    request.setType(QXmppIq::Get);
    request.setQueryType(QXmppDiscoveryIq::InfoQuery);
    request.setTo(jid);
    if(!node.isEmpty())
        request.setQueryNode(node);
    if(client()->sendPacket(request))
        return request.id();
    else
        return QString();
}

/// Requests items from the specified XMPP entity.
///
/// \param jid  The target entity's JID.
/// \param node The target node (optional).

QString QXmppDiscoveryManager::requestItems(const QString& jid, const QString& node)
{
    QXmppDiscoveryIq request;
    request.setType(QXmppIq::Get);
    request.setQueryType(QXmppDiscoveryIq::ItemsQuery);
    request.setTo(jid);
    if(!node.isEmpty())
        request.setQueryNode(node);
    if(client()->sendPacket(request))
        return request.id();
    else
        return QString();
}

/// Returns the client's full capabilities.

QXmppDiscoveryIq QXmppDiscoveryManager::capabilities()
{
    QXmppDiscoveryIq iq;
    iq.setType(QXmppIq::Result);
    iq.setQueryType(QXmppDiscoveryIq::InfoQuery);

    // features
    QStringList features;
    features
        << ns_data              // XEP-0004: Data Forms
        << ns_rsm               // XEP-0059: Result Set Management
        << ns_xhtml_im          // XEP-0071: XHTML-IM
        << ns_chat_states       // XEP-0085: Chat State Notifications
        << ns_capabilities      // XEP-0115: Entity Capabilities
        << ns_ping              // XEP-0199: XMPP Ping
        << ns_attention;        // XEP-0224: Attention

    foreach(QXmppClientExtension* extension, client()->extensions())
    {
        if(extension)
            features << extension->discoveryFeatures();
    }

    iq.setFeatures(features);

    // identities
    QList<QXmppDiscoveryIq::Identity> identities;

    QXmppDiscoveryIq::Identity identity;
    identity.setCategory(clientCategory());
    identity.setType(clientType());
    identity.setName(clientName());
    identities << identity;

    foreach(QXmppClientExtension* extension, client()->extensions())
    {
        if(extension)
            identities << extension->discoveryIdentities();
    }

    iq.setIdentities(identities);

    // extended information
    if (!d->clientInfoForm.isNull())
        iq.setForm(d->clientInfoForm);

    return iq;
}

/// Sets the capabilities node of the local XMPP client.
///
/// \param node

void QXmppDiscoveryManager::setClientCapabilitiesNode(const QString &node)
{
    d->clientCapabilitiesNode = node;
}

/// Sets the category of the local XMPP client.
///
/// You can find a list of valid categories at:
/// http://xmpp.org/registrar/disco-categories.html
///
/// \param category

void QXmppDiscoveryManager::setClientCategory(const QString& category)
{
    d->clientCategory = category;
}

/// Sets the type of the local XMPP client.
///
/// You can find a list of valid types at:
/// http://xmpp.org/registrar/disco-categories.html
///
/// \param type

void QXmppDiscoveryManager::setClientType(const QString& type)
{
    d->clientType = type;
}

/// Sets the name of the local XMPP client.
///
/// \param name

void QXmppDiscoveryManager::setClientName(const QString& name)
{
    d->clientName = name;
}

/// Returns the capabilities node of the local XMPP client.
///
/// By default this is "http://code.google.com/p/qxmpp".

QString QXmppDiscoveryManager::clientCapabilitiesNode() const
{
    return d->clientCapabilitiesNode;
}

/// Returns the category of the local XMPP client.
///
/// By default this is "client".

QString QXmppDiscoveryManager::clientCategory() const
{
    return d->clientCategory;
}

/// Returns the type of the local XMPP client.
///
/// By default this is "pc".

QString QXmppDiscoveryManager::clientType() const
{
    return d->clientType;
}

/// Returns the name of the local XMPP client.
///
/// By default this is "Based on QXmpp x.y.z".

QString QXmppDiscoveryManager::clientName() const
{
    return d->clientName;
}

/// Returns the client's extended information form, as defined
/// by XEP-0128 Service Discovery Extensions.

QXmppDataForm QXmppDiscoveryManager::clientInfoForm() const
{
    return d->clientInfoForm;
}

/// Sets the client's extended information form, as defined
/// by XEP-0128 Service Discovery Extensions.

void QXmppDiscoveryManager::setClientInfoForm(const QXmppDataForm &form)
{
    d->clientInfoForm = form;
}

/// \cond
QStringList QXmppDiscoveryManager::discoveryFeatures() const
{
    return QStringList() << ns_disco_info;
}

bool QXmppDiscoveryManager::handleStanza(const QDomElement &element)
{
    if (element.tagName() == "iq" && QXmppDiscoveryIq::isDiscoveryIq(element))
    {
        QXmppDiscoveryIq receivedIq;
        receivedIq.parse(element);

        if(receivedIq.type() == QXmppIq::Get &&
           receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery &&
           (receivedIq.queryNode().isEmpty() ||
            receivedIq.queryNode().startsWith(d->clientCapabilitiesNode))) {
            // respond to query
            QXmppDiscoveryIq qxmppFeatures = capabilities();
            qxmppFeatures.setId(receivedIq.id());
            qxmppFeatures.setTo(receivedIq.from());
            qxmppFeatures.setQueryNode(receivedIq.queryNode());
            client()->sendPacket(qxmppFeatures);
        } else if(receivedIq.type() == QXmppIq::Result &&
                  receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery) {
            // info result
            emit infoReceived(receivedIq);
        } else if(receivedIq.type() == QXmppIq::Result &&
                  receivedIq.queryType() == QXmppDiscoveryIq::ItemsQuery) {
            // items result
            emit itemsReceived(receivedIq);
        }

        return true;
    }
    return false;
}
/// \endcond
<commit_msg>Handle Error disco replies in DiscoveryManager as well.<commit_after>/*
 * Copyright (C) 2008-2012 The QXmpp developers
 *
 * Author:
 *  Manjeet Dahiya
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include "QXmppDiscoveryManager.h"

#include <QDomElement>
#include <QCoreApplication>

#include "QXmppClient.h"
#include "QXmppConstants.h"
#include "QXmppDataForm.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppStream.h"
#include "QXmppGlobal.h"

class QXmppDiscoveryManagerPrivate
{
public:
    QString clientCapabilitiesNode;
    QString clientCategory;
    QString clientType;
    QString clientName;
    QXmppDataForm clientInfoForm;
};

QXmppDiscoveryManager::QXmppDiscoveryManager()
    : d(new QXmppDiscoveryManagerPrivate)
{
    d->clientCapabilitiesNode = "http://code.google.com/p/qxmpp";
    d->clientCategory = "client";
    d->clientType = "pc";
    if (qApp->applicationName().isEmpty() && qApp->applicationVersion().isEmpty())
        d->clientName = QString("%1 %2").arg("Based on QXmpp", QXmppVersion());
    else
        d->clientName = QString("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion());
}

QXmppDiscoveryManager::~QXmppDiscoveryManager()
{
    delete d;
}

/// Requests information from the specified XMPP entity.
///
/// \param jid  The target entity's JID.
/// \param node The target node (optional).

QString QXmppDiscoveryManager::requestInfo(const QString& jid, const QString& node)
{
    QXmppDiscoveryIq request;
    request.setType(QXmppIq::Get);
    request.setQueryType(QXmppDiscoveryIq::InfoQuery);
    request.setTo(jid);
    if(!node.isEmpty())
        request.setQueryNode(node);
    if(client()->sendPacket(request))
        return request.id();
    else
        return QString();
}

/// Requests items from the specified XMPP entity.
///
/// \param jid  The target entity's JID.
/// \param node The target node (optional).

QString QXmppDiscoveryManager::requestItems(const QString& jid, const QString& node)
{
    QXmppDiscoveryIq request;
    request.setType(QXmppIq::Get);
    request.setQueryType(QXmppDiscoveryIq::ItemsQuery);
    request.setTo(jid);
    if(!node.isEmpty())
        request.setQueryNode(node);
    if(client()->sendPacket(request))
        return request.id();
    else
        return QString();
}

/// Returns the client's full capabilities.

QXmppDiscoveryIq QXmppDiscoveryManager::capabilities()
{
    QXmppDiscoveryIq iq;
    iq.setType(QXmppIq::Result);
    iq.setQueryType(QXmppDiscoveryIq::InfoQuery);

    // features
    QStringList features;
    features
        << ns_data              // XEP-0004: Data Forms
        << ns_rsm               // XEP-0059: Result Set Management
        << ns_xhtml_im          // XEP-0071: XHTML-IM
        << ns_chat_states       // XEP-0085: Chat State Notifications
        << ns_capabilities      // XEP-0115: Entity Capabilities
        << ns_ping              // XEP-0199: XMPP Ping
        << ns_attention;        // XEP-0224: Attention

    foreach(QXmppClientExtension* extension, client()->extensions())
    {
        if(extension)
            features << extension->discoveryFeatures();
    }

    iq.setFeatures(features);

    // identities
    QList<QXmppDiscoveryIq::Identity> identities;

    QXmppDiscoveryIq::Identity identity;
    identity.setCategory(clientCategory());
    identity.setType(clientType());
    identity.setName(clientName());
    identities << identity;

    foreach(QXmppClientExtension* extension, client()->extensions())
    {
        if(extension)
            identities << extension->discoveryIdentities();
    }

    iq.setIdentities(identities);

    // extended information
    if (!d->clientInfoForm.isNull())
        iq.setForm(d->clientInfoForm);

    return iq;
}

/// Sets the capabilities node of the local XMPP client.
///
/// \param node

void QXmppDiscoveryManager::setClientCapabilitiesNode(const QString &node)
{
    d->clientCapabilitiesNode = node;
}

/// Sets the category of the local XMPP client.
///
/// You can find a list of valid categories at:
/// http://xmpp.org/registrar/disco-categories.html
///
/// \param category

void QXmppDiscoveryManager::setClientCategory(const QString& category)
{
    d->clientCategory = category;
}

/// Sets the type of the local XMPP client.
///
/// You can find a list of valid types at:
/// http://xmpp.org/registrar/disco-categories.html
///
/// \param type

void QXmppDiscoveryManager::setClientType(const QString& type)
{
    d->clientType = type;
}

/// Sets the name of the local XMPP client.
///
/// \param name

void QXmppDiscoveryManager::setClientName(const QString& name)
{
    d->clientName = name;
}

/// Returns the capabilities node of the local XMPP client.
///
/// By default this is "http://code.google.com/p/qxmpp".

QString QXmppDiscoveryManager::clientCapabilitiesNode() const
{
    return d->clientCapabilitiesNode;
}

/// Returns the category of the local XMPP client.
///
/// By default this is "client".

QString QXmppDiscoveryManager::clientCategory() const
{
    return d->clientCategory;
}

/// Returns the type of the local XMPP client.
///
/// By default this is "pc".

QString QXmppDiscoveryManager::clientType() const
{
    return d->clientType;
}

/// Returns the name of the local XMPP client.
///
/// By default this is "Based on QXmpp x.y.z".

QString QXmppDiscoveryManager::clientName() const
{
    return d->clientName;
}

/// Returns the client's extended information form, as defined
/// by XEP-0128 Service Discovery Extensions.

QXmppDataForm QXmppDiscoveryManager::clientInfoForm() const
{
    return d->clientInfoForm;
}

/// Sets the client's extended information form, as defined
/// by XEP-0128 Service Discovery Extensions.

void QXmppDiscoveryManager::setClientInfoForm(const QXmppDataForm &form)
{
    d->clientInfoForm = form;
}

/// \cond
QStringList QXmppDiscoveryManager::discoveryFeatures() const
{
    return QStringList() << ns_disco_info;
}

bool QXmppDiscoveryManager::handleStanza(const QDomElement &element)
{
    if (element.tagName() == "iq" && QXmppDiscoveryIq::isDiscoveryIq(element))
    {
        QXmppDiscoveryIq receivedIq;
        receivedIq.parse(element);

        const bool isReplyType = receivedIq.type() == QXmppIq::Result ||
                receivedIq.type() == QXmppIq::Error;

        if(receivedIq.type() == QXmppIq::Get &&
           receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery &&
           (receivedIq.queryNode().isEmpty() ||
            receivedIq.queryNode().startsWith(d->clientCapabilitiesNode))) {
            // respond to query
            QXmppDiscoveryIq qxmppFeatures = capabilities();
            qxmppFeatures.setId(receivedIq.id());
            qxmppFeatures.setTo(receivedIq.from());
            qxmppFeatures.setQueryNode(receivedIq.queryNode());
            client()->sendPacket(qxmppFeatures);
        } else if(isReplyType &&
                  receivedIq.queryType() == QXmppDiscoveryIq::InfoQuery) {
            // info result
            emit infoReceived(receivedIq);
        } else if(isReplyType &&
                  receivedIq.queryType() == QXmppDiscoveryIq::ItemsQuery) {
            // items result
            emit itemsReceived(receivedIq);
        }

        return true;
    }
    return false;
}
/// \endcond
<|endoftext|>


<commit_before>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{
    void set_hash(create_torrent& c, int p, char const* hash)
    {
        c.set_hash(p, sha1_hash(hash));
    }

    void call_python_object(boost::python::object const& obj, int i)
    {
       obj(i);
    }

#ifndef BOOST_NO_EXCEPTIONS
    void set_piece_hashes_callback(create_torrent& c, std::string const& p
        , boost::python::object cb)
    {
        set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1));
    }
#else
    void set_piece_hashes_callback(create_torrent& c, std::string const& p
        , boost::python::object cb)
    {
        error_code ec;
        set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1), ec);
    }

    void set_piece_hashes0(create_torrent& c, std::string const & s)
    {
        error_code ec;
        set_piece_hashes(c, s, ec);
    }
#endif

    void add_node(create_torrent& ct, std::string const& addr, int port)
    {
        ct.add_node(std::make_pair(addr, port));
    }

    void add_file(file_storage& ct, file_entry const& fe)
    {
       ct.add_file(fe);
    }
}

void bind_create_torrent()
{
    void (file_storage::*add_file0)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#if TORRENT_USE_WSTRING
    void (file_storage::*add_file1)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#endif

    void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
#if TORRENT_USE_WSTRING
    void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name;
#endif

#ifndef BOOST_NO_EXCEPTIONS
    void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
#endif
    void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files;

    file_entry (file_storage::*at)(int) const = &file_storage::at;

    class_<file_storage>("file_storage")
        .def("is_valid", &file_storage::is_valid)
        .def("add_file", add_file, arg("entry"))
        .def("add_file", add_file0, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#if TORRENT_USE_WSTRING
        .def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#endif
        .def("num_files", &file_storage::num_files)
        .def("at", at)
//        .def("hash", &file_storage::hash)
//        .def("symlink", &file_storage::symlink, return_internal_reference<>())
//        .def("file_index", &file_storage::file_index)
//        .def("file_base", &file_storage::file_base)
//        .def("set_file_base", &file_storage::set_file_base)
//        .def("file_path", &file_storage::file_path)
        .def("total_size", &file_storage::total_size)
        .def("set_num_pieces", &file_storage::set_num_pieces)
        .def("num_pieces", &file_storage::num_pieces)
        .def("set_piece_length", &file_storage::set_piece_length)
        .def("piece_length", &file_storage::piece_length)
        .def("piece_size", &file_storage::piece_size)
        .def("set_name", set_name0)
#if TORRENT_USE_WSTRING
        .def("set_name", set_name1)
#endif
        .def("name", &file_storage::name, return_internal_reference<>())
        ;

    class_<create_torrent>("create_torrent", no_init)
        .def(init<file_storage&>())
        .def(init<file_storage&, int, int, int>((arg("storage"), arg("piece_size") = 0
            , arg("pad_file_limit") = -1, arg("flags") = int(libtorrent::create_torrent::optimize))))

        .def("generate", &create_torrent::generate)

        .def("files", &create_torrent::files, return_internal_reference<>())
        .def("set_comment", &create_torrent::set_comment)
        .def("set_creator", &create_torrent::set_creator)
        .def("set_hash", &set_hash)
        .def("add_url_seed", &create_torrent::add_url_seed)
        .def("add_node", &add_node)
        .def("add_tracker", &create_torrent::add_tracker, (arg("announce_url"), arg("tier") = 0))
        .def("set_priv", &create_torrent::set_priv)
        .def("num_pieces", &create_torrent::num_pieces)
        .def("piece_length", &create_torrent::piece_length)
        .def("piece_size", &create_torrent::piece_size)
        .def("priv", &create_torrent::priv)
        ;

    enum_<create_torrent::flags_t>("create_torrent_flags_t")
        .value("optimize", create_torrent::optimize)
        .value("merkle", create_torrent::merkle)
        .value("modification_time", create_torrent::modification_time)
        .value("symlinks", create_torrent::symlinks)
    ;

    def("add_files", add_files0, (arg("fs"), arg("path"), arg("flags") = 0));
    def("set_piece_hashes", set_piece_hashes0);
    def("set_piece_hashes", set_piece_hashes_callback);

}
<commit_msg>expose create_torrent constructor to python binding<commit_after>// Copyright Daniel Wallin & Arvid Norberg 2009. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/python.hpp>
#include <libtorrent/create_torrent.hpp>
#include <libtorrent/file_storage.hpp>
#include "libtorrent/intrusive_ptr_base.hpp"

using namespace boost::python;
using namespace libtorrent;

namespace
{
    void set_hash(create_torrent& c, int p, char const* hash)
    {
        c.set_hash(p, sha1_hash(hash));
    }

    void call_python_object(boost::python::object const& obj, int i)
    {
       obj(i);
    }

#ifndef BOOST_NO_EXCEPTIONS
    void set_piece_hashes_callback(create_torrent& c, std::string const& p
        , boost::python::object cb)
    {
        set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1));
    }
#else
    void set_piece_hashes_callback(create_torrent& c, std::string const& p
        , boost::python::object cb)
    {
        error_code ec;
        set_piece_hashes(c, p, boost::bind(call_python_object, cb, _1), ec);
    }

    void set_piece_hashes0(create_torrent& c, std::string const & s)
    {
        error_code ec;
        set_piece_hashes(c, s, ec);
    }
#endif

    void add_node(create_torrent& ct, std::string const& addr, int port)
    {
        ct.add_node(std::make_pair(addr, port));
    }

    void add_file(file_storage& ct, file_entry const& fe)
    {
       ct.add_file(fe);
    }
}

void bind_create_torrent()
{
    void (file_storage::*add_file0)(std::string const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#if TORRENT_USE_WSTRING
    void (file_storage::*add_file1)(std::wstring const&, size_type, int, std::time_t, std::string const&) = &file_storage::add_file;
#endif

    void (file_storage::*set_name0)(std::string const&) = &file_storage::set_name;
#if TORRENT_USE_WSTRING
    void (file_storage::*set_name1)(std::wstring const&) = &file_storage::set_name;
#endif

#ifndef BOOST_NO_EXCEPTIONS
    void (*set_piece_hashes0)(create_torrent&, std::string const&) = &set_piece_hashes;
#endif
    void (*add_files0)(file_storage&, std::string const&, boost::uint32_t) = add_files;

    file_entry (file_storage::*at)(int) const = &file_storage::at;

    class_<file_storage>("file_storage")
        .def("is_valid", &file_storage::is_valid)
        .def("add_file", add_file, arg("entry"))
        .def("add_file", add_file0, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#if TORRENT_USE_WSTRING
        .def("add_file", add_file1, (arg("path"), arg("size"), arg("flags") = 0, arg("mtime") = 0, arg("linkpath") = ""))
#endif
        .def("num_files", &file_storage::num_files)
        .def("at", at)
//        .def("hash", &file_storage::hash)
//        .def("symlink", &file_storage::symlink, return_internal_reference<>())
//        .def("file_index", &file_storage::file_index)
//        .def("file_base", &file_storage::file_base)
//        .def("set_file_base", &file_storage::set_file_base)
//        .def("file_path", &file_storage::file_path)
        .def("total_size", &file_storage::total_size)
        .def("set_num_pieces", &file_storage::set_num_pieces)
        .def("num_pieces", &file_storage::num_pieces)
        .def("set_piece_length", &file_storage::set_piece_length)
        .def("piece_length", &file_storage::piece_length)
        .def("piece_size", &file_storage::piece_size)
        .def("set_name", set_name0)
#if TORRENT_USE_WSTRING
        .def("set_name", set_name1)
#endif
        .def("name", &file_storage::name, return_internal_reference<>())
        ;

    class_<create_torrent>("create_torrent", no_init)
        .def(init<file_storage&>())
        .def(init<file_storage&, torrent_info const&>(arg("ti")))
        .def(init<file_storage&, int, int, int>((arg("storage"), arg("piece_size") = 0
            , arg("pad_file_limit") = -1, arg("flags") = int(libtorrent::create_torrent::optimize))))

        .def("generate", &create_torrent::generate)

        .def("files", &create_torrent::files, return_internal_reference<>())
        .def("set_comment", &create_torrent::set_comment)
        .def("set_creator", &create_torrent::set_creator)
        .def("set_hash", &set_hash)
        .def("add_url_seed", &create_torrent::add_url_seed)
        .def("add_node", &add_node)
        .def("add_tracker", &create_torrent::add_tracker, (arg("announce_url"), arg("tier") = 0))
        .def("set_priv", &create_torrent::set_priv)
        .def("num_pieces", &create_torrent::num_pieces)
        .def("piece_length", &create_torrent::piece_length)
        .def("piece_size", &create_torrent::piece_size)
        .def("priv", &create_torrent::priv)
        ;

    enum_<create_torrent::flags_t>("create_torrent_flags_t")
        .value("optimize", create_torrent::optimize)
        .value("merkle", create_torrent::merkle)
        .value("modification_time", create_torrent::modification_time)
        .value("symlinks", create_torrent::symlinks)
    ;

    def("add_files", add_files0, (arg("fs"), arg("path"), arg("flags") = 0));
    def("set_piece_hashes", set_piece_hashes0);
    def("set_piece_hashes", set_piece_hashes_callback);

}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -std=c++11 -emit-pch -o %t.a %s
// RUN: %clang_cc1 -std=c++11 -include-pch %t.a %s -ast-print -o - | FileCheck %s

#ifndef HEADER
#define HEADER

inline void test(int i) {
  switch (i) {
    case 1:
      // Notice that the NullStmt has two attributes.
      [[clang::fallthrough]][[clang::fallthrough]];
    case 2:
      break;
  }
}

#else

void foo(void) {
  test(1);
}

#endif
<commit_msg>Updated the test case to show that no diagnostics are expected, and not require emitting the AST until after the AST printing for statement attributes is updated.<commit_after>// RUN: %clang_cc1 -std=c++11 -emit-pch -o %t.a %s
// RUN: %clang_cc1 -std=c++11 -fsyntax-only -include-pch %t.a %s
// expected-no-diagnostics

#ifndef HEADER
#define HEADER

inline void test(int i) {
  switch (i) {
    case 1:
      // Notice that the NullStmt has two attributes.
      [[clang::fallthrough]][[clang::fallthrough]];
    case 2:
      break;
  }
}

#else

void foo(void) {
  test(1);
}

#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtCore/QScopedPointer>

/*!
 \class tst_QScopedPointer
 \internal
 \since 4.6
 \brief Tests class QScopedPointer.

 */
class tst_QScopedPointer : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void defaultConstructor();
    void dataOnDefaultConstructed();
    void useSubClassInConstructor();
    void dataOnValue();
    void dataSignature();
    void reset();
    void dereferenceOperator();
    void dereferenceOperatorSignature();
    void pointerOperator();
    void pointerOperatorSignature();
    void negationOperator();
    void negationOperatorSignature();
    void operatorBool();
    void operatorBoolSignature();
    void isNull();
    void isNullSignature();
    void objectSize();
    void comparison();
    // TODO instanciate on const object
};

void tst_QScopedPointer::defaultConstructor()
{
    /* Check that the members, one, is correctly initialized. */
    QScopedPointer<int> p;
    QCOMPARE(p.data(), static_cast<int *>(0));
}

void tst_QScopedPointer::dataOnDefaultConstructed()
{
    QScopedPointer<int> p;

    QCOMPARE(p.data(), static_cast<int *>(0));
}

class MyClass
{
};

class MySubClass : public MyClass
{
};

void tst_QScopedPointer::useSubClassInConstructor()
{
    /* Use a syntax which users typically would do. */
    QScopedPointer<MyClass> p(new MyClass());
}

void tst_QScopedPointer::dataOnValue()
{
    int *const rawPointer = new int(5);
    QScopedPointer<int> p(rawPointer);

    QCOMPARE(p.data(), rawPointer);
}

void tst_QScopedPointer::dataSignature()
{
    const QScopedPointer<int> p;
    /* data() should be const. */
    p.data();
}

void tst_QScopedPointer::reset()
{
    /* Call reset() on a default constructed value. */
    {
        QScopedPointer<int> p;
        p.reset();
        QCOMPARE(p.data(), static_cast<int *>(0));
    }

    /* Call reset() on an active value. */
    {
        QScopedPointer<int> p(new int(3));
        p.reset();
        QCOMPARE(p.data(), static_cast<int *>(0));
    }

    /* Call reset() with a value, on an active value. */
    {
        QScopedPointer<int> p(new int(3));

        int *const value = new int(9);
        p.reset(value);
        QCOMPARE(*p.data(), 9);
    }

    /* Call reset() with a value, on default constructed value. */
    {
        QScopedPointer<int> p;

        int *const value = new int(9);
        p.reset(value);
        QCOMPARE(*p.data(), 9);
    }
}

class AbstractClass
{
public:
    virtual ~AbstractClass()
    {
    }

    virtual int member() const = 0;
};

class SubClass : public AbstractClass
{
public:
    virtual int member() const
    {
        return 5;
    }
};

void tst_QScopedPointer::dereferenceOperator()
{
    /* Dereference a basic value. */
    {
        QScopedPointer<int> p(new int(5));

        const int value2 = *p;
        QCOMPARE(value2, 5);
    }

    /* Dereference a pointer to an abstract class. This verifies
     * that the operator returns a reference, when compiling
     * with MSVC 2005. */
    {
        QScopedPointer<AbstractClass> p(new SubClass());

        QCOMPARE((*p).member(), 5);
    }
}

void tst_QScopedPointer::dereferenceOperatorSignature()
{
    /* The operator should be const. */
    {
        const QScopedPointer<int> p(new int(5));
        *p;
    }

    /* A reference should be returned, not a value. */
    {
        const QScopedPointer<int> p(new int(5));
        Q_UNUSED(static_cast<int &>(*p));
    }

    /* Instantiated on a const object, the returned object is a const reference. */
    {
        const QScopedPointer<const int> p(new int(5));
        Q_UNUSED(static_cast<const int &>(*p));
    }
}

class AnyForm
{
public:
    int value;
};

void tst_QScopedPointer::pointerOperator()
{
    QScopedPointer<AnyForm> p(new AnyForm());
    p->value = 5;

    QCOMPARE(p->value, 5);
}

void tst_QScopedPointer::pointerOperatorSignature()
{
    /* The operator should be const. */
    const QScopedPointer<AnyForm> p(new AnyForm);
    p->value = 5;

    QVERIFY(p->value);
}

void tst_QScopedPointer::negationOperator()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QVERIFY(!p);
    }

    /* Invoke on a value. */
    {
        QScopedPointer<int> p(new int(2));
        QCOMPARE(!p, false);
    }
}

void tst_QScopedPointer::negationOperatorSignature()
{
    /* The signature should be const. */
    const QScopedPointer<int> p;
    !p;

    /* The return value should be bool. */
    static_cast<bool>(!p);
}

void tst_QScopedPointer::operatorBool()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QCOMPARE(bool(p), false);
    }

    /* Invoke on active value. */
    {
        QScopedPointer<int> p(new int(3));
        QVERIFY(p);
    }
}

void tst_QScopedPointer::operatorBoolSignature()
{
    /* The signature should be const and return bool. */
    const QScopedPointer<int> p;

    (void)static_cast<bool>(p);
}

void tst_QScopedPointer::isNull()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QVERIFY(p.isNull());
    }

    /* Invoke on a set value. */
    {
        QScopedPointer<int> p(new int(69));
        QVERIFY(!p.isNull());
    }
}

void tst_QScopedPointer::isNullSignature()
{
    const QScopedPointer<int> p(new int(69));

    /* The signature should be const and return bool. */
    static_cast<bool>(p.isNull());
}

void tst_QScopedPointer::objectSize()
{
    /* The size of QScopedPointer should be the same as one pointer. */
    QCOMPARE(sizeof(QScopedPointer<int>), sizeof(void *));
}

struct RefCounted
{
    RefCounted()
        : ref(0)
    {
        instanceCount.ref();
    }

    RefCounted(RefCounted const &other)
        : ref(0)
    {
        instanceCount.ref();
    }

    ~RefCounted()
    {
        QVERIFY( ref == 0 );
        instanceCount.deref();
    }

    RefCounted &operator=(RefCounted const &)
    {
    }

    QAtomicInt ref;

    static QAtomicInt instanceCount;
};

QAtomicInt RefCounted::instanceCount = 0;

template <class A1, class A2, class B>
void scopedPointerComparisonTest(const A1 &a1, const A2 &a2, const B &b)
{
    // test equality on equal pointers
    QVERIFY(a1 == a2);
    QVERIFY(a2 == a1);

    // test inequality on equal pointers
    QVERIFY(!(a1 != a2));
    QVERIFY(!(a2 != a1));

    // test equality on unequal pointers
    QVERIFY(!(a1 == b));
    QVERIFY(!(a2 == b));
    QVERIFY(!(b == a1));
    QVERIFY(!(b == a2));

    // test inequality on unequal pointers
    QVERIFY(b != a1);
    QVERIFY(b != a2);
    QVERIFY(a1 != b);
    QVERIFY(a2 != b);
}

void tst_QScopedPointer::comparison()
{
    QCOMPARE( int(RefCounted::instanceCount), 0 );

    {
        RefCounted *a = new RefCounted;
        RefCounted *b = new RefCounted;

        QCOMPARE( int(RefCounted::instanceCount), 2 );

        QScopedPointer<RefCounted> pa1(a);
        QScopedPointer<RefCounted> pa2(a);
        QScopedPointer<RefCounted> pb(b);

        scopedPointerComparisonTest(pa1, pa1, pb);
        scopedPointerComparisonTest(pa2, pa2, pb);
        scopedPointerComparisonTest(pa1, pa2, pb);

        pa2.take();

        QCOMPARE( int(RefCounted::instanceCount), 2 );
    }

    QCOMPARE( int(RefCounted::instanceCount), 0 );

    {
        RefCounted *a = new RefCounted[42];
        RefCounted *b = new RefCounted[43];

        QCOMPARE( int(RefCounted::instanceCount), 85 );

        QScopedArrayPointer<RefCounted> pa1(a);
        QScopedArrayPointer<RefCounted> pa2(a);
        QScopedArrayPointer<RefCounted> pb(b);

        scopedPointerComparisonTest(pa1, pa2, pb);

        pa2.take();

        QCOMPARE( int(RefCounted::instanceCount), 85 );
    }

    QCOMPARE( int(RefCounted::instanceCount), 0 );

    {
        // QScopedSharedPointer is an internal helper class -- it is unsupported!

        RefCounted *a = new RefCounted;
        RefCounted *b = new RefCounted;

        QCOMPARE( int(RefCounted::instanceCount), 2 );

        QSharedDataPointer<RefCounted> pa1(a);
        QSharedDataPointer<RefCounted> pa2(a);
        QSharedDataPointer<RefCounted> pb(b);

        QCOMPARE( int(a->ref), 2 );
        QCOMPARE( int(b->ref), 1 );
        QCOMPARE( int(RefCounted::instanceCount), 2 );

        scopedPointerComparisonTest(pa1, pa2, pb);

        QCOMPARE( int(RefCounted::instanceCount), 2 );
    }

    QCOMPARE( int(RefCounted::instanceCount), 0 );
}

QTEST_MAIN(tst_QScopedPointer)
#include "tst_qscopedpointer.moc"
<commit_msg>Fixing warnings in QScopedPointer test case<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtCore/QScopedPointer>

/*!
 \class tst_QScopedPointer
 \internal
 \since 4.6
 \brief Tests class QScopedPointer.

 */
class tst_QScopedPointer : public QObject
{
    Q_OBJECT

private Q_SLOTS:
    void defaultConstructor();
    void dataOnDefaultConstructed();
    void useSubClassInConstructor();
    void dataOnValue();
    void dataSignature();
    void reset();
    void dereferenceOperator();
    void dereferenceOperatorSignature();
    void pointerOperator();
    void pointerOperatorSignature();
    void negationOperator();
    void negationOperatorSignature();
    void operatorBool();
    void operatorBoolSignature();
    void isNull();
    void isNullSignature();
    void objectSize();
    void comparison();
    // TODO instanciate on const object
};

void tst_QScopedPointer::defaultConstructor()
{
    /* Check that the members, one, is correctly initialized. */
    QScopedPointer<int> p;
    QCOMPARE(p.data(), static_cast<int *>(0));
}

void tst_QScopedPointer::dataOnDefaultConstructed()
{
    QScopedPointer<int> p;

    QCOMPARE(p.data(), static_cast<int *>(0));
}

class MyClass
{
};

class MySubClass : public MyClass
{
};

void tst_QScopedPointer::useSubClassInConstructor()
{
    /* Use a syntax which users typically would do. */
    QScopedPointer<MyClass> p(new MyClass());
}

void tst_QScopedPointer::dataOnValue()
{
    int *const rawPointer = new int(5);
    QScopedPointer<int> p(rawPointer);

    QCOMPARE(p.data(), rawPointer);
}

void tst_QScopedPointer::dataSignature()
{
    const QScopedPointer<int> p;
    /* data() should be const. */
    p.data();
}

void tst_QScopedPointer::reset()
{
    /* Call reset() on a default constructed value. */
    {
        QScopedPointer<int> p;
        p.reset();
        QCOMPARE(p.data(), static_cast<int *>(0));
    }

    /* Call reset() on an active value. */
    {
        QScopedPointer<int> p(new int(3));
        p.reset();
        QCOMPARE(p.data(), static_cast<int *>(0));
    }

    /* Call reset() with a value, on an active value. */
    {
        QScopedPointer<int> p(new int(3));

        int *const value = new int(9);
        p.reset(value);
        QCOMPARE(*p.data(), 9);
    }

    /* Call reset() with a value, on default constructed value. */
    {
        QScopedPointer<int> p;

        int *const value = new int(9);
        p.reset(value);
        QCOMPARE(*p.data(), 9);
    }
}

class AbstractClass
{
public:
    virtual ~AbstractClass()
    {
    }

    virtual int member() const = 0;
};

class SubClass : public AbstractClass
{
public:
    virtual int member() const
    {
        return 5;
    }
};

void tst_QScopedPointer::dereferenceOperator()
{
    /* Dereference a basic value. */
    {
        QScopedPointer<int> p(new int(5));

        const int value2 = *p;
        QCOMPARE(value2, 5);
    }

    /* Dereference a pointer to an abstract class. This verifies
     * that the operator returns a reference, when compiling
     * with MSVC 2005. */
    {
        QScopedPointer<AbstractClass> p(new SubClass());

        QCOMPARE((*p).member(), 5);
    }
}

void tst_QScopedPointer::dereferenceOperatorSignature()
{
    /* The operator should be const. */
    {
        const QScopedPointer<int> p(new int(5));
        *p;
    }

    /* A reference should be returned, not a value. */
    {
        const QScopedPointer<int> p(new int(5));
        Q_UNUSED(static_cast<int &>(*p));
    }

    /* Instantiated on a const object, the returned object is a const reference. */
    {
        const QScopedPointer<const int> p(new int(5));
        Q_UNUSED(static_cast<const int &>(*p));
    }
}

class AnyForm
{
public:
    int value;
};

void tst_QScopedPointer::pointerOperator()
{
    QScopedPointer<AnyForm> p(new AnyForm());
    p->value = 5;

    QCOMPARE(p->value, 5);
}

void tst_QScopedPointer::pointerOperatorSignature()
{
    /* The operator should be const. */
    const QScopedPointer<AnyForm> p(new AnyForm);
    p->value = 5;

    QVERIFY(p->value);
}

void tst_QScopedPointer::negationOperator()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QVERIFY(!p);
    }

    /* Invoke on a value. */
    {
        QScopedPointer<int> p(new int(2));
        QCOMPARE(!p, false);
    }
}

void tst_QScopedPointer::negationOperatorSignature()
{
    /* The signature should be const. */
    const QScopedPointer<int> p;
    !p;

    /* The return value should be bool. */
    static_cast<bool>(!p);
}

void tst_QScopedPointer::operatorBool()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QCOMPARE(bool(p), false);
    }

    /* Invoke on active value. */
    {
        QScopedPointer<int> p(new int(3));
        QVERIFY(p);
    }
}

void tst_QScopedPointer::operatorBoolSignature()
{
    /* The signature should be const and return bool. */
    const QScopedPointer<int> p;

    (void)static_cast<bool>(p);
}

void tst_QScopedPointer::isNull()
{
    /* Invoke on default constructed value. */
    {
        QScopedPointer<int> p;
        QVERIFY(p.isNull());
    }

    /* Invoke on a set value. */
    {
        QScopedPointer<int> p(new int(69));
        QVERIFY(!p.isNull());
    }
}

void tst_QScopedPointer::isNullSignature()
{
    const QScopedPointer<int> p(new int(69));

    /* The signature should be const and return bool. */
    static_cast<bool>(p.isNull());
}

void tst_QScopedPointer::objectSize()
{
    /* The size of QScopedPointer should be the same as one pointer. */
    QCOMPARE(sizeof(QScopedPointer<int>), sizeof(void *));
}

struct RefCounted
{
    RefCounted()
        : ref(0)
    {
        instanceCount.ref();
    }

    RefCounted(RefCounted const &)
        : ref(0)
    {
        instanceCount.ref();
    }

    ~RefCounted()
    {
        QVERIFY( ref == 0 );
        instanceCount.deref();
    }

    RefCounted &operator=(RefCounted const &)
    {
        return *this;
    }

    QAtomicInt ref;

    static QAtomicInt instanceCount;
};

QAtomicInt RefCounted::instanceCount = 0;

template <class A1, class A2, class B>
void scopedPointerComparisonTest(const A1 &a1, const A2 &a2, const B &b)
{
    // test equality on equal pointers
    QVERIFY(a1 == a2);
    QVERIFY(a2 == a1);

    // test inequality on equal pointers
    QVERIFY(!(a1 != a2));
    QVERIFY(!(a2 != a1));

    // test equality on unequal pointers
    QVERIFY(!(a1 == b));
    QVERIFY(!(a2 == b));
    QVERIFY(!(b == a1));
    QVERIFY(!(b == a2));

    // test inequality on unequal pointers
    QVERIFY(b != a1);
    QVERIFY(b != a2);
    QVERIFY(a1 != b);
    QVERIFY(a2 != b);
}

void tst_QScopedPointer::comparison()
{
    QCOMPARE( int(RefCounted::instanceCount), 0 );

    {
        RefCounted *a = new RefCounted;
        RefCounted *b = new RefCounted;

        QCOMPARE( int(RefCounted::instanceCount), 2 );

        QScopedPointer<RefCounted> pa1(a);
        QScopedPointer<RefCounted> pa2(a);
        QScopedPointer<RefCounted> pb(b);

        scopedPointerComparisonTest(pa1, pa1, pb);
        scopedPointerComparisonTest(pa2, pa2, pb);
        scopedPointerComparisonTest(pa1, pa2, pb);

        pa2.take();

        QCOMPARE( int(RefCounted::instanceCount), 2 );
    }

    QCOMPARE( int(RefCounted::instanceCount), 0 );

    {
        RefCounted *a = new RefCounted[42];
        RefCounted *b = new RefCounted[43];

        QCOMPARE( int(RefCounted::instanceCount), 85 );

        QScopedArrayPointer<RefCounted> pa1(a);
        QScopedArrayPointer<RefCounted> pa2(a);
        QScopedArrayPointer<RefCounted> pb(b);

        scopedPointerComparisonTest(pa1, pa2, pb);

        pa2.take();

        QCOMPARE( int(RefCounted::instanceCount), 85 );
    }

    QCOMPARE( int(RefCounted::instanceCount), 0 );

    {
        // QScopedSharedPointer is an internal helper class -- it is unsupported!

        RefCounted *a = new RefCounted;
        RefCounted *b = new RefCounted;

        QCOMPARE( int(RefCounted::instanceCount), 2 );

        QSharedDataPointer<RefCounted> pa1(a);
        QSharedDataPointer<RefCounted> pa2(a);
        QSharedDataPointer<RefCounted> pb(b);

        QCOMPARE( int(a->ref), 2 );
        QCOMPARE( int(b->ref), 1 );
        QCOMPARE( int(RefCounted::instanceCount), 2 );

        scopedPointerComparisonTest(pa1, pa2, pb);

        QCOMPARE( int(RefCounted::instanceCount), 2 );
    }

    QCOMPARE( int(RefCounted::instanceCount), 0 );
}

QTEST_MAIN(tst_QScopedPointer)
#include "tst_qscopedpointer.moc"
<|endoftext|>


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

#include <realm/util/circular_buffer.hpp>
#include "test.hpp"

using namespace realm;
using namespace realm::util;

// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.

TEST(Utils_CircularBuffer_Basics)
{
    CircularBuffer<int> buffer(10);
    std::vector<int> vec;

    for (int i = 0; i < 5; i++) {
        buffer.insert(i);
    }
    CHECK_EQUAL(buffer.size(), 5);

    for (int i = 5; i < 10; i++) {
        buffer.insert(i);
    }
    CHECK_EQUAL(buffer.size(), 10);
    for (int i = 0; i < 10; i++) {
        CHECK_EQUAL(buffer[i], i);
    }

    buffer.insert(10);
    CHECK_EQUAL(buffer.size(), 10);
    for (int i = 0; i < 10; i++) {
        CHECK_EQUAL(buffer[i], i + 1);
    }

    for (int i = 0; i < 8; i++) {
        buffer.insert(i + 11);
    }
    for (int i = 0; i < 10; i++) {
        CHECK_EQUAL(buffer[i], i + 9);
    }
    int val = 9;
    for (auto i : buffer) {
        CHECK_EQUAL(i, val++);
    }

    bool ok = false;
    try {
        CircularBuffer<std::string> str_buf(0);
    }
    catch (const std::exception& e) {
        ok = true;
    }
    CHECK(ok);

    CircularBuffer<std::string> str_buf(1);
    str_buf.insert("Foo");
    str_buf.insert("Bar");
    CHECK_EQUAL(str_buf[0], "Bar");
}
#endif
<commit_msg>fix unused var warning<commit_after>/*************************************************************************
 *
 * Copyright 2016 Realm Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************/
#include "testsettings.hpp"
#ifdef TEST_UTIL_CIRCULAR_BUFFER

#include <realm/util/circular_buffer.hpp>
#include "test.hpp"

using namespace realm;
using namespace realm::util;

// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.

TEST(Utils_CircularBuffer_Basics)
{
    CircularBuffer<int> buffer(10);
    std::vector<int> vec;

    for (int i = 0; i < 5; i++) {
        buffer.insert(i);
    }
    CHECK_EQUAL(buffer.size(), 5);

    for (int i = 5; i < 10; i++) {
        buffer.insert(i);
    }
    CHECK_EQUAL(buffer.size(), 10);
    for (int i = 0; i < 10; i++) {
        CHECK_EQUAL(buffer[i], i);
    }

    buffer.insert(10);
    CHECK_EQUAL(buffer.size(), 10);
    for (int i = 0; i < 10; i++) {
        CHECK_EQUAL(buffer[i], i + 1);
    }

    for (int i = 0; i < 8; i++) {
        buffer.insert(i + 11);
    }
    for (int i = 0; i < 10; i++) {
        CHECK_EQUAL(buffer[i], i + 9);
    }
    int val = 9;
    for (auto i : buffer) {
        CHECK_EQUAL(i, val++);
    }

    bool ok = false;
    try {
        CircularBuffer<std::string> str_buf(0);
    }
    catch (const std::exception&) {
        ok = true;
    }
    CHECK(ok);

    CircularBuffer<std::string> str_buf(1);
    str_buf.insert("Foo");
    str_buf.insert("Bar");
    CHECK_EQUAL(str_buf[0], "Bar");
}
#endif
<|endoftext|>