<commit_before>#include <string>

#include <gtest/gtest.h>

extern "C" {
#include "shoveler/resources.h"
}

static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer);
void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes);
void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData);
void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader);

class ShovelerResourcesTest : public ::testing::Test {
public:
	virtual void SetUp()
	{
		resources = shovelerResourcesCreate(requestResources, this);

		testTypeId = "test type id";
		testDefaultResourceData = "test default resource";

		testTypeLoader.typeId = testTypeId;
		testTypeLoader.defaultResourceData = (void *) testDefaultResourceData;
		testTypeLoader.data = this;
		testTypeLoader.load = loadResource;
		testTypeLoader.freeResourceData = freeResourceData;
		testTypeLoader.free = freeTypeLoader;
		bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
		ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";

		lastRequestResources = NULL;
		lastRequestTypeId = NULL;
		lastRequestResourceId = NULL;

		lastLoadBuffer = NULL;
		lastLoadBytes = 0;
		nextLoadResourceData = NULL;

		freeResourceDataArguments.clear();

		freeTypeLoaderCalled = false;
	}

	virtual void TearDown()
	{
		shovelerResourcesFree(resources);

		ASSERT_EQ(*freeResourceDataArguments.rbegin(), testTypeLoader.defaultResourceData) << "type loader's default resource data should be freed after resources was freed";
		ASSERT_TRUE(freeTypeLoaderCalled) << "type loader should be freed after resources was freed";
	}

	ShovelerResources *resources;
	const char *testTypeId;
	const char *testDefaultResourceData;
	ShovelerResourcesTypeLoader testTypeLoader;

	ShovelerResources *lastRequestResources;
	const char *lastRequestTypeId;
	const char *lastRequestResourceId;

	const unsigned char *lastLoadBuffer;
	size_t lastLoadBytes;
	void *nextLoadResourceData;

	std::vector<void *> freeResourceDataArguments;

	bool freeTypeLoaderCalled;
};

TEST_F(ShovelerResourcesTest, requestUnloaded)
{
	const char *testResourceId = "test resource id";

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
	ASSERT_EQ(lastRequestResources, resources) << "request should be called with correct resources";
	ASSERT_EQ(lastRequestTypeId, testTypeId) << "request should be called with correct type id";
	ASSERT_EQ(lastRequestResourceId, testResourceId) << "request should be called with correct resource id";

	ASSERT_EQ(resource->resources, resources) << "returned resource should have correct resources";
	ASSERT_STREQ(resource->id, testResourceId) << "returned resource should have correct resource id";
	ASSERT_STREQ(resource->typeId, testTypeId) << "returned resource should have correct type id";
	ASSERT_EQ(resource->data, testDefaultResourceData) << "returned resource should have correct default data";
}

TEST_F(ShovelerResourcesTest, requestInvalidType)
{
	const char *testInvalidTypeId = "foo/bar";
	const char *testResourceId = "test resource id";

	ShovelerResource *resource = shovelerResourcesGet(resources, testInvalidTypeId, testResourceId);
	ASSERT_TRUE(resource == NULL) << "request should have failed";
}

TEST_F(ShovelerResourcesTest, requestNull)
{
	const char *testResourceId = "test resource id";

	ShovelerResources *resources = shovelerResourcesCreate(NULL, NULL);
	bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
	ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
	ASSERT_TRUE(resource != NULL) << "returned resource must not be NULL";

	shovelerResourcesFree(resources);
}

TEST_F(ShovelerResourcesTest, loadUnrequested)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	nextLoadResourceData = (void *) testResourceData;
	bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_TRUE(loaded) << "load should have succeeded";
	ASSERT_EQ(lastLoadBuffer, &testResourceBuffer) << "load should be called with correct buffer";
	ASSERT_EQ(lastLoadBytes, testResourceBytes) << "load should be called with correct bytes";
}

TEST_F(ShovelerResourcesTest, loadInvalidType)
{
	const char *testInvalidTypeId = "foo/bar";
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;

	bool loaded = shovelerResourcesSet(resources, testInvalidTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_FALSE(loaded) << "load should have failed";
}

TEST_F(ShovelerResourcesTest, freeLoaded)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	nextLoadResourceData = (void *) testResourceData;
	shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	shovelerResourcesFree(resources);

	ASSERT_EQ(*freeResourceDataArguments.begin(), testResourceData) << "free resource data should be called with correct resource data";

	resources = NULL;
}

TEST_F(ShovelerResourcesTest, requestAndLoad)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);

	nextLoadResourceData = (void *) testResourceData;
	bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_TRUE(loaded) << "load should have succeeded";

	ASSERT_EQ(resource->data, testResourceData) << "resource data should have changed after loading";
}

TEST_F(ShovelerResourcesTest, requestAndFailToLoad)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);

	nextLoadResourceData = NULL;
	bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_FALSE(loaded) << "load should have failed";

	ASSERT_EQ(resource->data, testDefaultResourceData) << "resource data should be unchanged after failing to load";
}

TEST_F(ShovelerResourcesTest, loadAndRequest)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	nextLoadResourceData = (void *) testResourceData;
	shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);

	ASSERT_EQ(resource->data, testResourceData) << "resource data should be set to correct loaded data";
}

static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) testPointer;
	test->lastRequestResources = resources;
	test->lastRequestTypeId = typeId;
	test->lastRequestResourceId = resourceId;
}

void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
	test->lastLoadBuffer = buffer;
	test->lastLoadBytes = bytes;

	return test->nextLoadResourceData;
}

void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
	test->freeResourceDataArguments.push_back(resourceData);
}

void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
	test->freeTypeLoaderCalled = true;
}
<commit_msg>make helper methods static in resources test<commit_after>#include <string>

#include <gtest/gtest.h>

extern "C" {
#include "shoveler/resources.h"
}

static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer);
static void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes);
static void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData);
static void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader);

class ShovelerResourcesTest : public ::testing::Test {
public:
	virtual void SetUp()
	{
		resources = shovelerResourcesCreate(requestResources, this);

		testTypeId = "test type id";
		testDefaultResourceData = "test default resource";

		testTypeLoader.typeId = testTypeId;
		testTypeLoader.defaultResourceData = (void *) testDefaultResourceData;
		testTypeLoader.data = this;
		testTypeLoader.load = loadResource;
		testTypeLoader.freeResourceData = freeResourceData;
		testTypeLoader.free = freeTypeLoader;
		bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
		ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";

		lastRequestResources = NULL;
		lastRequestTypeId = NULL;
		lastRequestResourceId = NULL;

		lastLoadBuffer = NULL;
		lastLoadBytes = 0;
		nextLoadResourceData = NULL;

		freeResourceDataArguments.clear();

		freeTypeLoaderCalled = false;
	}

	virtual void TearDown()
	{
		shovelerResourcesFree(resources);

		ASSERT_EQ(*freeResourceDataArguments.rbegin(), testTypeLoader.defaultResourceData) << "type loader's default resource data should be freed after resources was freed";
		ASSERT_TRUE(freeTypeLoaderCalled) << "type loader should be freed after resources was freed";
	}

	ShovelerResources *resources;
	const char *testTypeId;
	const char *testDefaultResourceData;
	ShovelerResourcesTypeLoader testTypeLoader;

	ShovelerResources *lastRequestResources;
	const char *lastRequestTypeId;
	const char *lastRequestResourceId;

	const unsigned char *lastLoadBuffer;
	size_t lastLoadBytes;
	void *nextLoadResourceData;

	std::vector<void *> freeResourceDataArguments;

	bool freeTypeLoaderCalled;
};

TEST_F(ShovelerResourcesTest, requestUnloaded)
{
	const char *testResourceId = "test resource id";

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
	ASSERT_EQ(lastRequestResources, resources) << "request should be called with correct resources";
	ASSERT_EQ(lastRequestTypeId, testTypeId) << "request should be called with correct type id";
	ASSERT_EQ(lastRequestResourceId, testResourceId) << "request should be called with correct resource id";

	ASSERT_EQ(resource->resources, resources) << "returned resource should have correct resources";
	ASSERT_STREQ(resource->id, testResourceId) << "returned resource should have correct resource id";
	ASSERT_STREQ(resource->typeId, testTypeId) << "returned resource should have correct type id";
	ASSERT_EQ(resource->data, testDefaultResourceData) << "returned resource should have correct default data";
}

TEST_F(ShovelerResourcesTest, requestInvalidType)
{
	const char *testInvalidTypeId = "foo/bar";
	const char *testResourceId = "test resource id";

	ShovelerResource *resource = shovelerResourcesGet(resources, testInvalidTypeId, testResourceId);
	ASSERT_TRUE(resource == NULL) << "request should have failed";
}

TEST_F(ShovelerResourcesTest, requestNull)
{
	const char *testResourceId = "test resource id";

	ShovelerResources *resources = shovelerResourcesCreate(NULL, NULL);
	bool typeLoaderRegistered = shovelerResourcesRegisterTypeLoader(resources, testTypeLoader);
	ASSERT_TRUE(typeLoaderRegistered) << "test type loader should register correctly";

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);
	ASSERT_TRUE(resource != NULL) << "returned resource must not be NULL";

	shovelerResourcesFree(resources);
}

TEST_F(ShovelerResourcesTest, loadUnrequested)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	nextLoadResourceData = (void *) testResourceData;
	bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_TRUE(loaded) << "load should have succeeded";
	ASSERT_EQ(lastLoadBuffer, &testResourceBuffer) << "load should be called with correct buffer";
	ASSERT_EQ(lastLoadBytes, testResourceBytes) << "load should be called with correct bytes";
}

TEST_F(ShovelerResourcesTest, loadInvalidType)
{
	const char *testInvalidTypeId = "foo/bar";
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;

	bool loaded = shovelerResourcesSet(resources, testInvalidTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_FALSE(loaded) << "load should have failed";
}

TEST_F(ShovelerResourcesTest, freeLoaded)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	nextLoadResourceData = (void *) testResourceData;
	shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	shovelerResourcesFree(resources);

	ASSERT_EQ(*freeResourceDataArguments.begin(), testResourceData) << "free resource data should be called with correct resource data";

	resources = NULL;
}

TEST_F(ShovelerResourcesTest, requestAndLoad)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);

	nextLoadResourceData = (void *) testResourceData;
	bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_TRUE(loaded) << "load should have succeeded";

	ASSERT_EQ(resource->data, testResourceData) << "resource data should have changed after loading";
}

TEST_F(ShovelerResourcesTest, requestAndFailToLoad)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);

	nextLoadResourceData = NULL;
	bool loaded = shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);
	ASSERT_FALSE(loaded) << "load should have failed";

	ASSERT_EQ(resource->data, testDefaultResourceData) << "resource data should be unchanged after failing to load";
}

TEST_F(ShovelerResourcesTest, loadAndRequest)
{
	const char *testResourceId = "test resource id";
	unsigned char testResourceBuffer = 42;
	size_t testResourceBytes = 1337;
	const char *testResourceData = "test resource data";

	nextLoadResourceData = (void *) testResourceData;
	shovelerResourcesSet(resources, testTypeId, testResourceId, &testResourceBuffer, testResourceBytes);

	ShovelerResource *resource = shovelerResourcesGet(resources, testTypeId, testResourceId);

	ASSERT_EQ(resource->data, testResourceData) << "resource data should be set to correct loaded data";
}

static void requestResources(ShovelerResources *resources, const char *typeId, const char *resourceId, void *testPointer)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) testPointer;
	test->lastRequestResources = resources;
	test->lastRequestTypeId = typeId;
	test->lastRequestResourceId = resourceId;
}

static void *loadResource(ShovelerResourcesTypeLoader *typeLoader, const unsigned char *buffer, size_t bytes)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
	test->lastLoadBuffer = buffer;
	test->lastLoadBytes = bytes;

	return test->nextLoadResourceData;
}

static void freeResourceData(ShovelerResourcesTypeLoader *typeLoader, void *resourceData)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
	test->freeResourceDataArguments.push_back(resourceData);
}

static void freeTypeLoader(ShovelerResourcesTypeLoader *typeLoader)
{
	ShovelerResourcesTest *test = (ShovelerResourcesTest *) typeLoader->data;
	test->freeTypeLoaderCalled = true;
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
/*
  This tests the classes ImageRandomNonRepeatingIteratorWithIndex and
  ImageRandomNonRepeatingConstIteratorWithIndex.  This was contributed
  by Rupert Brooks, McGill Centre for Intelligent
  Machines, Montreal, Canada.  It is heavily based on the
  ImageRandomIterator test program.
*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include <algorithm>
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingConstIteratorWithIndex.h"
int itkImageRandomNonRepeatingIteratorWithIndexTest(int, char* [] )
{
  const unsigned int ImageDimension = 3;
  typedef itk::Index< ImageDimension >                                    PixelType;
  typedef itk::Image< PixelType, ImageDimension >                         ImageType;
  typedef itk::SizeValueType                                              PriorityPixelType;
  typedef itk::Image< PriorityPixelType, ImageDimension >                 PriorityImageType;
  typedef itk::ImageRegionIteratorWithIndex< ImageType >                  IteratorType;
  typedef itk::ImageRegionIteratorWithIndex< PriorityImageType >          PriorityIteratorType;
  typedef itk::ImageRandomNonRepeatingIteratorWithIndex< ImageType >      RandomIteratorType;
  typedef itk::ImageRandomNonRepeatingConstIteratorWithIndex< ImageType > RandomConstIteratorType;
  std::cout << "Creating images" << std::endl;

  ImageType::Pointer myImage = ImageType::New();
  ImageType::ConstPointer myConstImage = myImage.GetPointer();
  ImageType::SizeType size0;
  size0[0] = 50;
  size0[1] = 50;
  size0[2] = 50;
  unsigned long numberOfSamples = 10;
  ImageType::IndexType start0;
  start0.Fill(0);
  ImageType::RegionType region0;
  region0.SetIndex( start0 );
  region0.SetSize( size0 );
  myImage->SetLargestPossibleRegion( region0 );
  myImage->SetBufferedRegion( region0 );
  myImage->SetRequestedRegion( region0 );
  myImage->Allocate();
  // Make the priority image
  PriorityImageType::Pointer priorityImage = PriorityImageType::New();
  PriorityImageType::SizeType prioritySize;
  prioritySize[0] = 50;
  prioritySize[1] = 50;
  prioritySize[2] = 50;
  PriorityImageType::IndexType priorityStart;
  priorityStart.Fill(0);
  PriorityImageType::RegionType priorityRegion;
  priorityRegion.SetIndex( priorityStart );
  priorityRegion.SetSize( prioritySize );
  priorityImage->SetLargestPossibleRegion( priorityRegion );
  priorityImage->SetBufferedRegion( priorityRegion );
  priorityImage->SetRequestedRegion( priorityRegion );
  priorityImage->Allocate();
  // we will make most of this image ones, with a small region of
  // zeros.  Then pixels from the zero region should be selected
  // preferentially.
  std::cout << "Building Priority image" << std::endl;
  PriorityIteratorType pit( priorityImage, priorityRegion );
  pit.GoToBegin();
  while( !pit.IsAtEnd() )
  {
    pit.Set( 1 );
    ++pit;
  }
  PriorityImageType::IndexType substart;
  substart[0] = 15;
  substart[1] = 16;
  substart[2] = 17;
  PriorityImageType::SizeType subsize;
  subsize[0] = 3;
  subsize[1] = 4;
  subsize[2] = 5;
  PriorityImageType::RegionType subregion;
  subregion.SetIndex( substart );
  subregion.SetSize( subsize );
  PriorityIteratorType subit( priorityImage, subregion );
  subit.GoToBegin();
  while( !subit.IsAtEnd() )
    {
      subit.Set( 0 );
      ++subit;
    }

  //********
  std::cout << "Filling image with indices" << std::endl;

  RandomIteratorType it( myImage, region0 );
  it.SetNumberOfSamples(size0[0]*size0[1]*size0[2]);
  it.GoToBegin();
  ImageType::IndexType index0;
  // Because the random iterator does not repeat, this should
  // fill the image with indices
  while( !it.IsAtEnd() )
  {
    index0 = it.GetIndex();
    it.Set( index0 );
    ++it;
  }

  // Sample the image
  IteratorType ot( myImage, region0 );
  ot.GoToBegin();
  // if it repeated its going to have missed a few.
  std::cout << "Verifying iterators... ";
  while( !ot.IsAtEnd() )
    {
    index0 = ot.GetIndex();
    if( ot.Get() != index0 )
      {
        std::cerr << "Values don't correspond to what was stored "
          << std::endl;
        std::cerr << "Test failed at index ";
        std::cerr << index0 << std::endl;
        return EXIT_FAILURE;
      }
    //std::cout <<".";
    //std::cout << index0 << std::endl;
    ++ot;
    }
  std::cout << std::endl<<"   Done ! " << std::endl;

  // Verification
  RandomConstIteratorType cot( myConstImage, region0 );
  cot.SetNumberOfSamples( numberOfSamples );
  cot.GoToBegin();

  std::cout << "Verifying const iterator... ";
  std::cout << "Random walk of the Iterator over the image " << std::endl;
  while( !cot.IsAtEnd() )
  {
    index0 = cot.GetIndex();
    if( cot.Get() != index0 )
      {
      std::cerr << "Values don't correspond to what was stored "
        << std::endl;
      std::cerr << "Test failed at index ";
      std::cerr << index0 << " value is " << cot.Get() <<  std::endl;
      return EXIT_FAILURE;
      }
    std::cout << index0 << std::endl;
    ++cot;
  }
  std::cout << "   Done ! " << std::endl;

  // Verification
  std::cout << "Verifying iterator in reverse direction... " << std::endl;
  std::cout << "Should be a random walk too (a different one)" << std::endl;
  RandomIteratorType ior( myImage, region0 );
  ior.SetNumberOfSamples( numberOfSamples );
  ior.GoToEnd();
  --ior;

  while( !ior.IsAtBegin() )
  {
    index0 = ior.GetIndex();
    if( ior.Get() != index0 )
    {
      std::cerr << "Values don't correspond to what was stored "
        << std::endl;
      std::cerr << "Test failed at index ";
      std::cerr << index0 << " value is " << ior.Get() <<  std::endl;
      return EXIT_FAILURE;
    }
    std::cout << index0 << std::endl;
    --ior;
  }
  std::cout << index0 << std::endl; // print the value at the beginning index
  std::cout << "   Done ! " << std::endl;

  // Verification
  std::cout << "Verifying const iterator in reverse direction... ";
  RandomConstIteratorType cor( myImage, region0 );
  cor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
  cor.GoToEnd();
  --cor; // start at the end position
  while( !cor.IsAtBegin() )
    {
    index0 = cor.GetIndex();
    if( cor.Get() != index0 )
      {
      std::cerr << "Values don't correspond to what was stored "
        << std::endl;
      std::cerr << "Test failed at index ";
      std::cerr << index0 << " value is " << cor.Get() <<  std::endl;
      return EXIT_FAILURE;
      }
    std::cout << index0 << std::endl;
    --cor;
    }
  std::cout << index0 << std::endl; // print the value at the beginning index
  std::cout << "   Done ! " << std::endl;
 // Verification
  std::cout << "Verifying const iterator in both directions... ";
  RandomConstIteratorType dor( myImage, region0 );
  dor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
  dor.GoToEnd();
  --dor; // start at the last valid pixel position
  for (unsigned int counter = 0; ! dor.IsAtEnd(); ++counter)
    {
      index0 = dor.GetIndex();
      if( dor.Get() != index0 )
        {
          std::cerr << "Values don't correspond to what was stored "
                    << std::endl;
          std::cerr << "Test failed at index ";
          std::cerr << index0 << " value is " << dor.Get() <<  std::endl;
          return EXIT_FAILURE;
        }
      std::cout << index0 << std::endl;
      if (counter < 6)  { --dor; }
      else { ++dor; }
    }
  std::cout << index0 << std::endl; // print the value at the beginning index
  std::cout << "   Done ! " << std::endl;

  // Verification of the Iterator in a subregion of the image
  {
    std::cout << "Verifying Iterator in a Region smaller than the whole image... "
              << std::endl;
    ImageType::IndexType start;
    start[0] = 10;
    start[1] = 12;
    start[2] = 14;
    ImageType::SizeType size;
    size[0] = 11;
    size[1] = 12;
    size[2] = 13;
    ImageType::RegionType region;
    region.SetIndex( start );
    region.SetSize( size );
    RandomIteratorType cbot( myImage, region );
    cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
    cbot.GoToBegin();
    while( !cbot.IsAtEnd() )
      {
      ImageType::IndexType index =  cbot.GetIndex();
      ImageType::PixelType pixel =  cbot.Get();
      if( index != pixel )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << pixel << " should be" << index << std::endl;
        return EXIT_FAILURE;
        }
      if( !region.IsInside( index ) )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      }
    std::cout << "   Done ! " << std::endl;
  }

  // Verification of the Const Iterator in a subregion of the image
  {
    std::cout << "Verifying Const Iterator in a Region smaller than the whole image... "
              << std::endl;
    ImageType::IndexType start;
    start[0] = 10;
    start[1] = 12;
    start[2] = 14;
    ImageType::SizeType size;
    size[0] = 11;
    size[1] = 12;
    size[2] = 13;
    ImageType::RegionType region;
    region.SetIndex( start );
    region.SetSize( size );
    RandomConstIteratorType cbot( myImage, region );
    cbot.SetNumberOfSamples( numberOfSamples );
    cbot.GoToBegin();
    while( !cbot.IsAtEnd() )
      {
      ImageType::IndexType index =  cbot.GetIndex();
      ImageType::PixelType pixel =  cbot.Get();
      if( index != pixel )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << pixel << " should be" << index << std::endl;
        return EXIT_FAILURE;
        }
      if( !region.IsInside( index ) )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      }
    std::cout << "   Done ! " << std::endl;
  }

  // Verifying iterator works with  the priority image

  {
    std::cout << "Verifying Iterator with respect to priority image... "
              << std::endl;

    RandomIteratorType cbot( myImage, region0 );
    cbot.SetPriorityImage(priorityImage);
    cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
    cbot.GoToBegin();
    unsigned int count=0;
    while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
      {
      ImageType::IndexType index =  cbot.GetIndex();
      if( !subregion.IsInside( index ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region0 << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      ++count;
      }
    // Now we have walked through all the pixels of low priority, next
    // one should be outside the region.
      if( subregion.IsInside( index0 ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
        return EXIT_FAILURE;
        }
    std::cout << "   Done ! " << std::endl;
  }
  {
    std::cout << "Verifying const Iterator with respect to priority image... "
              << std::endl;

    RandomConstIteratorType cbot( myImage, region0 );
    cbot.SetPriorityImage(priorityImage);
    cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
    cbot.GoToBegin();
    unsigned int count=0;
    while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
      {
      ImageType::IndexType index =  cbot.GetIndex();
      if( !subregion.IsInside( index ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region0 << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      ++count;
      }
    // Now we have walked through all the pixels of low priority, next
    // one should be outside the region.
      if( subregion.IsInside( index0 ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
        return EXIT_FAILURE;
        }
    std::cout << "   Done ! " << std::endl;
  }
  {
    // Exercise assignment operator
    std::cout << "Exercising assignment operator... " << std::endl;
    RandomConstIteratorType it;
    it = RandomConstIteratorType( myImage, region0 );
    it.SetNumberOfSamples(myImage->GetLargestPossibleRegion().GetNumberOfPixels());
    it.GoToBegin();
    std::cout << "Finished exercising assignment operator... " << std::endl;
  }
  std::cout << "Test passed" << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>BUG: Fixed warning<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
/*
  This tests the classes ImageRandomNonRepeatingIteratorWithIndex and
  ImageRandomNonRepeatingConstIteratorWithIndex.  This was contributed
  by Rupert Brooks, McGill Centre for Intelligent
  Machines, Montreal, Canada.  It is heavily based on the
  ImageRandomIterator test program.
*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
#include <algorithm>
#include "itkImage.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingIteratorWithIndex.h"
#include "itkImageRandomNonRepeatingConstIteratorWithIndex.h"
int itkImageRandomNonRepeatingIteratorWithIndexTest(int, char* [] )
{
  const unsigned int ImageDimension = 3;
  typedef itk::Index< ImageDimension >                                    PixelType;
  typedef itk::Image< PixelType, ImageDimension >                         ImageType;
  typedef itk::SizeValueType                                              PriorityPixelType;
  typedef itk::Image< PriorityPixelType, ImageDimension >                 PriorityImageType;
  typedef itk::ImageRegionIteratorWithIndex< ImageType >                  IteratorType;
  typedef itk::ImageRegionIteratorWithIndex< PriorityImageType >          PriorityIteratorType;
  typedef itk::ImageRandomNonRepeatingIteratorWithIndex< ImageType >      RandomIteratorType;
  typedef itk::ImageRandomNonRepeatingConstIteratorWithIndex< ImageType > RandomConstIteratorType;
  std::cout << "Creating images" << std::endl;

  ImageType::Pointer myImage = ImageType::New();
  ImageType::ConstPointer myConstImage = myImage.GetPointer();
  ImageType::SizeType size0;
  size0[0] = 50;
  size0[1] = 50;
  size0[2] = 50;
  unsigned long numberOfSamples = 10;
  ImageType::IndexType start0;
  start0.Fill(0);
  ImageType::RegionType region0;
  region0.SetIndex( start0 );
  region0.SetSize( size0 );
  myImage->SetLargestPossibleRegion( region0 );
  myImage->SetBufferedRegion( region0 );
  myImage->SetRequestedRegion( region0 );
  myImage->Allocate();
  // Make the priority image
  PriorityImageType::Pointer priorityImage = PriorityImageType::New();
  PriorityImageType::SizeType prioritySize;
  prioritySize[0] = 50;
  prioritySize[1] = 50;
  prioritySize[2] = 50;
  PriorityImageType::IndexType priorityStart;
  priorityStart.Fill(0);
  PriorityImageType::RegionType priorityRegion;
  priorityRegion.SetIndex( priorityStart );
  priorityRegion.SetSize( prioritySize );
  priorityImage->SetLargestPossibleRegion( priorityRegion );
  priorityImage->SetBufferedRegion( priorityRegion );
  priorityImage->SetRequestedRegion( priorityRegion );
  priorityImage->Allocate();
  // we will make most of this image ones, with a small region of
  // zeros.  Then pixels from the zero region should be selected
  // preferentially.
  std::cout << "Building Priority image" << std::endl;
  PriorityIteratorType pit( priorityImage, priorityRegion );
  pit.GoToBegin();
  while( !pit.IsAtEnd() )
  {
    pit.Set( 1 );
    ++pit;
  }
  PriorityImageType::IndexType substart;
  substart[0] = 15;
  substart[1] = 16;
  substart[2] = 17;
  PriorityImageType::SizeType subsize;
  subsize[0] = 3;
  subsize[1] = 4;
  subsize[2] = 5;
  PriorityImageType::RegionType subregion;
  subregion.SetIndex( substart );
  subregion.SetSize( subsize );
  PriorityIteratorType subit( priorityImage, subregion );
  subit.GoToBegin();
  while( !subit.IsAtEnd() )
    {
      subit.Set( 0 );
      ++subit;
    }

  //********
  std::cout << "Filling image with indices" << std::endl;

  RandomIteratorType it( myImage, region0 );
  it.SetNumberOfSamples(size0[0]*size0[1]*size0[2]);
  it.GoToBegin();
  ImageType::IndexType index0;
  // Because the random iterator does not repeat, this should
  // fill the image with indices
  while( !it.IsAtEnd() )
  {
    index0 = it.GetIndex();
    it.Set( index0 );
    ++it;
  }

  // Sample the image
  IteratorType ot( myImage, region0 );
  ot.GoToBegin();
  // if it repeated its going to have missed a few.
  std::cout << "Verifying iterators... ";
  while( !ot.IsAtEnd() )
    {
    index0 = ot.GetIndex();
    if( ot.Get() != index0 )
      {
        std::cerr << "Values don't correspond to what was stored "
          << std::endl;
        std::cerr << "Test failed at index ";
        std::cerr << index0 << std::endl;
        return EXIT_FAILURE;
      }
    //std::cout <<".";
    //std::cout << index0 << std::endl;
    ++ot;
    }
  std::cout << std::endl<<"   Done ! " << std::endl;

  // Verification
  RandomConstIteratorType cot( myConstImage, region0 );
  cot.SetNumberOfSamples( numberOfSamples );
  cot.GoToBegin();

  std::cout << "Verifying const iterator... ";
  std::cout << "Random walk of the Iterator over the image " << std::endl;
  while( !cot.IsAtEnd() )
  {
    index0 = cot.GetIndex();
    if( cot.Get() != index0 )
      {
      std::cerr << "Values don't correspond to what was stored "
        << std::endl;
      std::cerr << "Test failed at index ";
      std::cerr << index0 << " value is " << cot.Get() <<  std::endl;
      return EXIT_FAILURE;
      }
    std::cout << index0 << std::endl;
    ++cot;
  }
  std::cout << "   Done ! " << std::endl;

  // Verification
  std::cout << "Verifying iterator in reverse direction... " << std::endl;
  std::cout << "Should be a random walk too (a different one)" << std::endl;
  RandomIteratorType ior( myImage, region0 );
  ior.SetNumberOfSamples( numberOfSamples );
  ior.GoToEnd();
  --ior;

  while( !ior.IsAtBegin() )
  {
    index0 = ior.GetIndex();
    if( ior.Get() != index0 )
    {
      std::cerr << "Values don't correspond to what was stored "
        << std::endl;
      std::cerr << "Test failed at index ";
      std::cerr << index0 << " value is " << ior.Get() <<  std::endl;
      return EXIT_FAILURE;
    }
    std::cout << index0 << std::endl;
    --ior;
  }
  std::cout << index0 << std::endl; // print the value at the beginning index
  std::cout << "   Done ! " << std::endl;

  // Verification
  std::cout << "Verifying const iterator in reverse direction... ";
  RandomConstIteratorType cor( myImage, region0 );
  cor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
  cor.GoToEnd();
  --cor; // start at the end position
  while( !cor.IsAtBegin() )
    {
    index0 = cor.GetIndex();
    if( cor.Get() != index0 )
      {
      std::cerr << "Values don't correspond to what was stored "
        << std::endl;
      std::cerr << "Test failed at index ";
      std::cerr << index0 << " value is " << cor.Get() <<  std::endl;
      return EXIT_FAILURE;
      }
    std::cout << index0 << std::endl;
    --cor;
    }
  std::cout << index0 << std::endl; // print the value at the beginning index
  std::cout << "   Done ! " << std::endl;
 // Verification
  std::cout << "Verifying const iterator in both directions... ";
  RandomConstIteratorType dor( myImage, region0 );
  dor.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
  dor.GoToEnd();
  --dor; // start at the last valid pixel position
  for (unsigned int counter = 0; ! dor.IsAtEnd(); ++counter)
    {
      index0 = dor.GetIndex();
      if( dor.Get() != index0 )
        {
          std::cerr << "Values don't correspond to what was stored "
                    << std::endl;
          std::cerr << "Test failed at index ";
          std::cerr << index0 << " value is " << dor.Get() <<  std::endl;
          return EXIT_FAILURE;
        }
      std::cout << index0 << std::endl;
      if (counter < 6)  { --dor; }
      else { ++dor; }
    }
  std::cout << index0 << std::endl; // print the value at the beginning index
  std::cout << "   Done ! " << std::endl;

  // Verification of the Iterator in a subregion of the image
  {
    std::cout << "Verifying Iterator in a Region smaller than the whole image... "
              << std::endl;
    ImageType::IndexType start;
    start[0] = 10;
    start[1] = 12;
    start[2] = 14;
    ImageType::SizeType size;
    size[0] = 11;
    size[1] = 12;
    size[2] = 13;
    ImageType::RegionType region;
    region.SetIndex( start );
    region.SetSize( size );
    RandomIteratorType cbot( myImage, region );
    cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
    cbot.GoToBegin();
    while( !cbot.IsAtEnd() )
      {
      ImageType::IndexType index =  cbot.GetIndex();
      ImageType::PixelType pixel =  cbot.Get();
      if( index != pixel )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << pixel << " should be" << index << std::endl;
        return EXIT_FAILURE;
        }
      if( !region.IsInside( index ) )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      }
    std::cout << "   Done ! " << std::endl;
  }

  // Verification of the Const Iterator in a subregion of the image
  {
    std::cout << "Verifying Const Iterator in a Region smaller than the whole image... "
              << std::endl;
    ImageType::IndexType start;
    start[0] = 10;
    start[1] = 12;
    start[2] = 14;
    ImageType::SizeType size;
    size[0] = 11;
    size[1] = 12;
    size[2] = 13;
    ImageType::RegionType region;
    region.SetIndex( start );
    region.SetSize( size );
    RandomConstIteratorType cbot( myImage, region );
    cbot.SetNumberOfSamples( numberOfSamples );
    cbot.GoToBegin();
    while( !cbot.IsAtEnd() )
      {
      ImageType::IndexType index =  cbot.GetIndex();
      ImageType::PixelType pixel =  cbot.Get();
      if( index != pixel )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << pixel << " should be" << index << std::endl;
        return EXIT_FAILURE;
        }
      if( !region.IsInside( index ) )
        {
        std::cerr << "Iterator in region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      }
    std::cout << "   Done ! " << std::endl;
  }

  // Verifying iterator works with  the priority image

  {
    std::cout << "Verifying Iterator with respect to priority image... "
              << std::endl;

    RandomIteratorType cbot( myImage, region0 );
    cbot.SetPriorityImage(priorityImage);
    cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
    cbot.GoToBegin();
    unsigned int count=0;
    while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
      {
      ImageType::IndexType index =  cbot.GetIndex();
      if( !subregion.IsInside( index ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region0 << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      ++count;
      }
    // Now we have walked through all the pixels of low priority, next
    // one should be outside the region.
      if( subregion.IsInside( index0 ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
        return EXIT_FAILURE;
        }
    std::cout << "   Done ! " << std::endl;
  }
  {
    std::cout << "Verifying const Iterator with respect to priority image... "
              << std::endl;

    RandomConstIteratorType cbot( myImage, region0 );
    cbot.SetPriorityImage(priorityImage);
    cbot.SetNumberOfSamples( numberOfSamples ); // 0=x, 1=y, 2=z
    cbot.GoToBegin();
    unsigned int count=0;
    while( !cbot.IsAtEnd() && count<(subsize[0]*subsize[1]*subsize[2]))
      {
      ImageType::IndexType index =  cbot.GetIndex();
      if( !subregion.IsInside( index ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index << " is outside the region " << region0 << std::endl;
        return EXIT_FAILURE;
        }
      std::cout << index << std::endl;
      ++cbot;
      ++count;
      }
    // Now we have walked through all the pixels of low priority, next
    // one should be outside the region.
      if( subregion.IsInside( index0 ) )
        {
        std::cerr << "Iterator in priority region test failed" << std::endl;
        std::cerr << index0 << " is outside the region (should be in)" << region0 << std::endl;
        return EXIT_FAILURE;
        }
    std::cout << "   Done ! " << std::endl;
  }
  {
    // Exercise assignment operator
    std::cout << "Exercising assignment operator... " << std::endl;
    RandomConstIteratorType iteratorAssignment;
    iteratorAssignment = RandomConstIteratorType( myImage, myImage->GetLargestPossibleRegion() );
    iteratorAssignment.SetNumberOfSamples(myImage->GetLargestPossibleRegion().GetNumberOfPixels());
    iteratorAssignment.GoToBegin();
    std::cout << "Finished exercising assignment operator!" << std::endl;
  }
  std::cout << "Test passed" << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sbxstr.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 21:53:04 $
 *
 *  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 _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include "sbx.hxx"
#include "sbxconv.hxx"
#include "sbxres.hxx"

// AB 29.10.99 Unicode
#ifndef _USE_NO_NAMESPACE
using namespace rtl;
#endif

// Die Konversion eines Items auf String wird ueber die Put-Methoden
// der einzelnen Datentypen abgewickelt, um doppelten Code zu vermeiden.

XubString ImpGetString( const SbxValues* p )
{
    SbxValues aTmp;
    XubString aRes;
    aTmp.eType = SbxSTRING;
    aTmp.pString = &aRes;
    switch( p->eType )
    {
        case SbxNULL:
            SbxBase::SetError( SbxERR_CONVERSION );
        case SbxEMPTY:
            break;
        case SbxCHAR:
            ImpPutChar( &aTmp, p->nChar ); break;
        case SbxBYTE:
            ImpPutByte( &aTmp, p->nByte ); break;
        case SbxINTEGER:
            ImpPutInteger( &aTmp, p->nInteger ); break;
        case SbxBOOL:
            ImpPutBool( &aTmp, p->nUShort ); break;
        case SbxUSHORT:
            ImpPutUShort( &aTmp, p->nUShort ); break;
        case SbxLONG:
            ImpPutLong( &aTmp, p->nLong ); break;
        case SbxULONG:
            ImpPutULong( &aTmp, p->nULong ); break;
        case SbxSINGLE:
            ImpPutSingle( &aTmp, p->nSingle ); break;
        case SbxDOUBLE:
            ImpPutDouble( &aTmp, p->nDouble ); break;
        case SbxCURRENCY:
            ImpPutCurrency( &aTmp, p->nLong64 ); break;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            ImpPutDecimal( &aTmp, p->pDecimal ); break;
        case SbxSALINT64:
            ImpPutInt64( &aTmp, p->nInt64 ); break;
        case SbxSALUINT64:
            ImpPutUInt64( &aTmp, p->uInt64 ); break;
        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
            if( p->pString )
                aRes = *p->pString;
            break;
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                aRes = pVal->GetString();
            else
                SbxBase::SetError( SbxERR_NO_OBJECT );
            break;
        }
        case SbxERROR:
            // Hier wird der String "Error n" erzeugt
            aRes = SbxRes( STRING_ERRORMSG );
            aRes += p->nUShort; break;
        case SbxDATE:
            ImpPutDate( &aTmp, p->nDouble ); break;

        case SbxBYREF | SbxCHAR:
            ImpPutChar( &aTmp, *p->pChar ); break;
        case SbxBYREF | SbxBYTE:
            ImpPutByte( &aTmp, *p->pByte ); break;
        case SbxBYREF | SbxINTEGER:
        case SbxBYREF | SbxBOOL:
            ImpPutInteger( &aTmp, *p->pInteger ); break;
        case SbxBYREF | SbxLONG:
            ImpPutLong( &aTmp, *p->pLong ); break;
        case SbxBYREF | SbxULONG:
            ImpPutULong( &aTmp, *p->pULong ); break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            ImpPutUShort( &aTmp, *p->pUShort ); break;
        case SbxBYREF | SbxSINGLE:
            ImpPutSingle( &aTmp, *p->pSingle ); break;
        case SbxBYREF | SbxDATE:
        case SbxBYREF | SbxDOUBLE:
            ImpPutDouble( &aTmp, *p->pDouble ); break;
        case SbxBYREF | SbxCURRENCY:
            ImpPutCurrency( &aTmp, *p->pLong64 ); break;
        case SbxBYREF | SbxSALINT64:
            ImpPutInt64( &aTmp, *p->pnInt64 ); break;
        case SbxBYREF | SbxSALUINT64:
            ImpPutUInt64( &aTmp, *p->puInt64 ); break;
        default:
            SbxBase::SetError( SbxERR_CONVERSION );
    }
    return aRes;
}

// AB 10.4.97, neue Funktion fuer SbxValue::GetCoreString()
XubString ImpGetCoreString( const SbxValues* p )
{
    // Vorerst nur fuer double
    if( ( p->eType & (~SbxBYREF) ) == SbxDOUBLE )
    {
        SbxValues aTmp;
        XubString aRes;
        aTmp.eType = SbxSTRING;
        aTmp.pString = &aRes;
        if( p->eType == SbxDOUBLE )
            ImpPutDouble( &aTmp, p->nDouble, /*bCoreString=*/TRUE );
        else
            ImpPutDouble( &aTmp, *p->pDouble, /*bCoreString=*/TRUE );
        return aRes;
    }
    else
        return ImpGetString( p );
}

void ImpPutString( SbxValues* p, const XubString* n )
{
    SbxValues aTmp;
    aTmp.eType = SbxSTRING;
    XubString* pTmp = NULL;
    // Sicherheitshalber, falls ein NULL-Ptr kommt
    if( !n )
        n = pTmp = new XubString;
    aTmp.pString = (XubString*) n;
    switch( p->eType )
    {
        case SbxCHAR:
            p->nChar = ImpGetChar( &aTmp ); break;
        case SbxBYTE:
            p->nByte = ImpGetByte( &aTmp ); break;
        case SbxINTEGER:
        case SbxBOOL:
            p->nInteger = ImpGetInteger( &aTmp ); break;
        case SbxLONG:
            p->nLong = ImpGetLong( &aTmp ); break;
        case SbxULONG:
            p->nULong = ImpGetULong( &aTmp ); break;
        case SbxERROR:
        case SbxUSHORT:
            p->nUShort = ImpGetUShort( &aTmp ); break;
        case SbxSINGLE:
            p->nSingle = ImpGetSingle( &aTmp ); break;
        case SbxDATE:
            p->nDouble = ImpGetDate( &aTmp ); break;
        case SbxDOUBLE:
            p->nDouble = ImpGetDouble( &aTmp ); break;
        case SbxULONG64:
            p->nLong64 = ImpGetCurrency( &aTmp ); break;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            releaseDecimalPtr( p->pDecimal );
            p->pDecimal = ImpGetDecimal( &aTmp ); break;
        case SbxSALINT64:
            p->nInt64 = ImpGetInt64( &aTmp ); break;
        case SbxSALUINT64:
            p->uInt64 = ImpGetUInt64( &aTmp ); break;

        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
            if( n->Len() )
            {
                if( !p->pString )
                    p->pString = new XubString;
                *p->pString = *n;
            }
            else
                delete p->pString, p->pString = NULL;
            break;
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                pVal->PutString( *n );
            else
                SbxBase::SetError( SbxERR_NO_OBJECT );
            break;
        }
        case SbxBYREF | SbxCHAR:
            *p->pChar = ImpGetChar( p ); break;
        case SbxBYREF | SbxBYTE:
            *p->pByte = ImpGetByte( p ); break;
        case SbxBYREF | SbxINTEGER:
            *p->pInteger = ImpGetInteger( p ); break;
        case SbxBYREF | SbxBOOL:
            *p->pUShort = ImpGetBool( p ); break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            *p->pUShort = ImpGetUShort( p ); break;
        case SbxBYREF | SbxLONG:
            *p->pLong = ImpGetLong( p ); break;
        case SbxBYREF | SbxULONG:
            *p->pULong = ImpGetULong( p ); break;
        case SbxBYREF | SbxSINGLE:
            *p->pSingle = ImpGetSingle( p ); break;
        case SbxBYREF | SbxDATE:
            *p->pDouble = ImpGetDate( p ); break;
        case SbxBYREF | SbxDOUBLE:
            *p->pDouble = ImpGetDouble( p ); break;
        case SbxBYREF | SbxCURRENCY:
            *p->pLong64 = ImpGetCurrency( p ); break;
        default:
            SbxBase::SetError( SbxERR_CONVERSION );
    }
    delete pTmp;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.120); FILE MERGED 2006/09/01 17:17:09 kaib 1.3.120.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sbxstr.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 10:11: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
 *
 ************************************************************************/

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

#ifndef _ERRCODE_HXX //autogen
#include <tools/errcode.hxx>
#endif
#include "sbx.hxx"
#include "sbxconv.hxx"
#include "sbxres.hxx"

// AB 29.10.99 Unicode
#ifndef _USE_NO_NAMESPACE
using namespace rtl;
#endif

// Die Konversion eines Items auf String wird ueber die Put-Methoden
// der einzelnen Datentypen abgewickelt, um doppelten Code zu vermeiden.

XubString ImpGetString( const SbxValues* p )
{
    SbxValues aTmp;
    XubString aRes;
    aTmp.eType = SbxSTRING;
    aTmp.pString = &aRes;
    switch( p->eType )
    {
        case SbxNULL:
            SbxBase::SetError( SbxERR_CONVERSION );
        case SbxEMPTY:
            break;
        case SbxCHAR:
            ImpPutChar( &aTmp, p->nChar ); break;
        case SbxBYTE:
            ImpPutByte( &aTmp, p->nByte ); break;
        case SbxINTEGER:
            ImpPutInteger( &aTmp, p->nInteger ); break;
        case SbxBOOL:
            ImpPutBool( &aTmp, p->nUShort ); break;
        case SbxUSHORT:
            ImpPutUShort( &aTmp, p->nUShort ); break;
        case SbxLONG:
            ImpPutLong( &aTmp, p->nLong ); break;
        case SbxULONG:
            ImpPutULong( &aTmp, p->nULong ); break;
        case SbxSINGLE:
            ImpPutSingle( &aTmp, p->nSingle ); break;
        case SbxDOUBLE:
            ImpPutDouble( &aTmp, p->nDouble ); break;
        case SbxCURRENCY:
            ImpPutCurrency( &aTmp, p->nLong64 ); break;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            ImpPutDecimal( &aTmp, p->pDecimal ); break;
        case SbxSALINT64:
            ImpPutInt64( &aTmp, p->nInt64 ); break;
        case SbxSALUINT64:
            ImpPutUInt64( &aTmp, p->uInt64 ); break;
        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
            if( p->pString )
                aRes = *p->pString;
            break;
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                aRes = pVal->GetString();
            else
                SbxBase::SetError( SbxERR_NO_OBJECT );
            break;
        }
        case SbxERROR:
            // Hier wird der String "Error n" erzeugt
            aRes = SbxRes( STRING_ERRORMSG );
            aRes += p->nUShort; break;
        case SbxDATE:
            ImpPutDate( &aTmp, p->nDouble ); break;

        case SbxBYREF | SbxCHAR:
            ImpPutChar( &aTmp, *p->pChar ); break;
        case SbxBYREF | SbxBYTE:
            ImpPutByte( &aTmp, *p->pByte ); break;
        case SbxBYREF | SbxINTEGER:
        case SbxBYREF | SbxBOOL:
            ImpPutInteger( &aTmp, *p->pInteger ); break;
        case SbxBYREF | SbxLONG:
            ImpPutLong( &aTmp, *p->pLong ); break;
        case SbxBYREF | SbxULONG:
            ImpPutULong( &aTmp, *p->pULong ); break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            ImpPutUShort( &aTmp, *p->pUShort ); break;
        case SbxBYREF | SbxSINGLE:
            ImpPutSingle( &aTmp, *p->pSingle ); break;
        case SbxBYREF | SbxDATE:
        case SbxBYREF | SbxDOUBLE:
            ImpPutDouble( &aTmp, *p->pDouble ); break;
        case SbxBYREF | SbxCURRENCY:
            ImpPutCurrency( &aTmp, *p->pLong64 ); break;
        case SbxBYREF | SbxSALINT64:
            ImpPutInt64( &aTmp, *p->pnInt64 ); break;
        case SbxBYREF | SbxSALUINT64:
            ImpPutUInt64( &aTmp, *p->puInt64 ); break;
        default:
            SbxBase::SetError( SbxERR_CONVERSION );
    }
    return aRes;
}

// AB 10.4.97, neue Funktion fuer SbxValue::GetCoreString()
XubString ImpGetCoreString( const SbxValues* p )
{
    // Vorerst nur fuer double
    if( ( p->eType & (~SbxBYREF) ) == SbxDOUBLE )
    {
        SbxValues aTmp;
        XubString aRes;
        aTmp.eType = SbxSTRING;
        aTmp.pString = &aRes;
        if( p->eType == SbxDOUBLE )
            ImpPutDouble( &aTmp, p->nDouble, /*bCoreString=*/TRUE );
        else
            ImpPutDouble( &aTmp, *p->pDouble, /*bCoreString=*/TRUE );
        return aRes;
    }
    else
        return ImpGetString( p );
}

void ImpPutString( SbxValues* p, const XubString* n )
{
    SbxValues aTmp;
    aTmp.eType = SbxSTRING;
    XubString* pTmp = NULL;
    // Sicherheitshalber, falls ein NULL-Ptr kommt
    if( !n )
        n = pTmp = new XubString;
    aTmp.pString = (XubString*) n;
    switch( p->eType )
    {
        case SbxCHAR:
            p->nChar = ImpGetChar( &aTmp ); break;
        case SbxBYTE:
            p->nByte = ImpGetByte( &aTmp ); break;
        case SbxINTEGER:
        case SbxBOOL:
            p->nInteger = ImpGetInteger( &aTmp ); break;
        case SbxLONG:
            p->nLong = ImpGetLong( &aTmp ); break;
        case SbxULONG:
            p->nULong = ImpGetULong( &aTmp ); break;
        case SbxERROR:
        case SbxUSHORT:
            p->nUShort = ImpGetUShort( &aTmp ); break;
        case SbxSINGLE:
            p->nSingle = ImpGetSingle( &aTmp ); break;
        case SbxDATE:
            p->nDouble = ImpGetDate( &aTmp ); break;
        case SbxDOUBLE:
            p->nDouble = ImpGetDouble( &aTmp ); break;
        case SbxULONG64:
            p->nLong64 = ImpGetCurrency( &aTmp ); break;
        case SbxDECIMAL:
        case SbxBYREF | SbxDECIMAL:
            releaseDecimalPtr( p->pDecimal );
            p->pDecimal = ImpGetDecimal( &aTmp ); break;
        case SbxSALINT64:
            p->nInt64 = ImpGetInt64( &aTmp ); break;
        case SbxSALUINT64:
            p->uInt64 = ImpGetUInt64( &aTmp ); break;

        case SbxBYREF | SbxSTRING:
        case SbxSTRING:
        case SbxLPSTR:
            if( n->Len() )
            {
                if( !p->pString )
                    p->pString = new XubString;
                *p->pString = *n;
            }
            else
                delete p->pString, p->pString = NULL;
            break;
        case SbxOBJECT:
        {
            SbxValue* pVal = PTR_CAST(SbxValue,p->pObj);
            if( pVal )
                pVal->PutString( *n );
            else
                SbxBase::SetError( SbxERR_NO_OBJECT );
            break;
        }
        case SbxBYREF | SbxCHAR:
            *p->pChar = ImpGetChar( p ); break;
        case SbxBYREF | SbxBYTE:
            *p->pByte = ImpGetByte( p ); break;
        case SbxBYREF | SbxINTEGER:
            *p->pInteger = ImpGetInteger( p ); break;
        case SbxBYREF | SbxBOOL:
            *p->pUShort = ImpGetBool( p ); break;
        case SbxBYREF | SbxERROR:
        case SbxBYREF | SbxUSHORT:
            *p->pUShort = ImpGetUShort( p ); break;
        case SbxBYREF | SbxLONG:
            *p->pLong = ImpGetLong( p ); break;
        case SbxBYREF | SbxULONG:
            *p->pULong = ImpGetULong( p ); break;
        case SbxBYREF | SbxSINGLE:
            *p->pSingle = ImpGetSingle( p ); break;
        case SbxBYREF | SbxDATE:
            *p->pDouble = ImpGetDate( p ); break;
        case SbxBYREF | SbxDOUBLE:
            *p->pDouble = ImpGetDouble( p ); break;
        case SbxBYREF | SbxCURRENCY:
            *p->pLong64 = ImpGetCurrency( p ); break;
        default:
            SbxBase::SetError( SbxERR_CONVERSION );
    }
    delete pTmp;
}

<|endoftext|>


<commit_before>#pragma once

#include "util/meta_helpers.hpp"

#include <bulk/world.hpp>
#include <memory>

/**
 * \file future.hpp
 *
 * This header defines a future object, which is used to refer to remote values
 * that are not yet known.
 */

namespace bulk {

/**
 * Represents a value that will become known in the upcoming superstep
 */
template <typename T>
class future {
    using value_type = typename bulk::meta::representation<T>::type;

  public:
    /**
     * Initialize the future.
     */
    future(bulk::world& world) : world_(world) {
        buffer_ = std::make_unique<T>();
    }

    /**
     * Deconstruct the future.
     */
    ~future() {}

    future(const future<T>& other) = delete;
    void operator=(const future<T>& other) = delete;

    future(future<T>&& other) : world_(other.world_) {
        *this = std::move(other);
    }

    /**
     * Move a future.
     */
    void operator=(future<T>&& other) { buffer_ = std::move(other.buffer_); }

    /**
     * Get a reference to the value held by the future.
     *
     * \returns a reference to the value
     */
    value_type& value() { return *buffer_.get(); }

    /**
     * Get a reference to the world of the future.
     *
     * \returns a reference to the world of the future
     */
    bulk::world& world() { return world_; }

  private:
    std::unique_ptr<value_type> buffer_;
    bulk::world& world_;
};

template <typename T>
class future<T[]> {
  public:
    /**
     * Initialize the future.
     */
    future(bulk::world& world, int size) : world_(world) {
        buffer_ = std::unique_ptr<T[]>(new T[size]);
    }

    /**
     * Deconstruct the future.
     */
    ~future() {}

    future(const future<T[]>& other) = delete;
    void operator=(const future<T[]>& other) = delete;

    future(future<T[]>&& other) : world_(other.world_) {
        *this = std::move(other);
    }

    void operator=(future<T[]>&& other) { buffer_ = std::move(other.buffer_); }

    /**
     * ...
     */
    T& operator[](int i) { return buffer_[i]; }

    /**
     * Get a reference to the world of the future.
     *
     * \returns a reference to the world of the future
     */
    bulk::world& world() { return world_; }

    T* buffer() { return buffer_.get(); }

  private:
    std::unique_ptr<T[]> buffer_;
    bulk::world& world_;
};

} // namespace bulk
<commit_msg>Add implicit cast to future<commit_after>#pragma once

#include "util/meta_helpers.hpp"

#include <bulk/world.hpp>
#include <memory>

/**
 * \file future.hpp
 *
 * This header defines a future object, which is used to refer to remote values
 * that are not yet known.
 */

namespace bulk {

/**
 * Represents a value that will become known in the upcoming superstep
 */
template <typename T>
class future {
    using value_type = typename bulk::meta::representation<T>::type;

  public:
    /**
     * Initialize the future.
     */
    future(bulk::world& world) : world_(world) {
        buffer_ = std::make_unique<T>();
    }

    /**
     * Deconstruct the future.
     */
    ~future() {}

    future(const future<T>& other) = delete;
    void operator=(const future<T>& other) = delete;

    future(future<T>&& other) : world_(other.world_) {
        *this = std::move(other);
    }

    /**
     * Move a future.
     */
    void operator=(future<T>&& other) { buffer_ = std::move(other.buffer_); }

    /**
     * Get a reference to the value held by the future.
     *
     * \returns a reference to the value
     */
    value_type& value() { return *buffer_.get(); }
    const value_type& value() const { return *buffer_.get(); }

    /**
     * Implicitly get the value held by the future
     *
     * \note This is for code like `myint = myfuture + 5;`.
     */
    operator value_type&() { return this->value(); }
    operator const value_type&() const { return this->value(); }

    /**
     * Get a reference to the world of the future.
     *
     * \returns a reference to the world of the future
     */
    bulk::world& world() { return world_; }

  private:
    std::unique_ptr<value_type> buffer_;
    bulk::world& world_;
};

template <typename T>
class future<T[]> {
  public:
    /**
     * Initialize the future.
     */
    future(bulk::world& world, int size) : world_(world) {
        buffer_ = std::unique_ptr<T[]>(new T[size]);
    }

    /**
     * Deconstruct the future.
     */
    ~future() {}

    future(const future<T[]>& other) = delete;
    void operator=(const future<T[]>& other) = delete;

    future(future<T[]>&& other) : world_(other.world_) {
        *this = std::move(other);
    }

    void operator=(future<T[]>&& other) { buffer_ = std::move(other.buffer_); }

    /**
     * ...
     */
    T& operator[](int i) { return buffer_[i]; }

    /**
     * Get a reference to the world of the future.
     *
     * \returns a reference to the world of the future
     */
    bulk::world& world() { return world_; }

    T* buffer() { return buffer_.get(); }

  private:
    std::unique_ptr<T[]> buffer_;
    bulk::world& world_;
};

} // namespace bulk
<|endoftext|>


<commit_before>/*
 * Copyright 2014-2020 CNRS INRIA
 */

#ifndef __eigenpy_fwd_hpp__
#define __eigenpy_fwd_hpp__

#include "eigenpy/config.hpp"

#include <boost/python.hpp>
#include <Eigen/Core>

#define NO_IMPORT_ARRAY
  #include "eigenpy/numpy.hpp"
#undef NO_IMPORT_ARRAY

#if EIGEN_VERSION_AT_LEAST(3,2,90)
  #define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned16
#else
  #define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned
#endif

#define EIGENPY_NO_ALIGNMENT_VALUE Eigen::Unaligned

#include "eigenpy/expose.hpp"

namespace eigenpy
{
  template<typename MatType> struct EigenToPy;
  template<typename MatType> struct EigenFromPy;
}

#endif // ifndef __eigenpy_fwd_hpp__
<commit_msg>core: add EIGENPY_UNUSED_VARIABLE macro<commit_after>/*
 * Copyright 2014-2020 CNRS INRIA
 */

#ifndef __eigenpy_fwd_hpp__
#define __eigenpy_fwd_hpp__

#include "eigenpy/config.hpp"

#include <boost/python.hpp>
#include <Eigen/Core>

#define NO_IMPORT_ARRAY
  #include "eigenpy/numpy.hpp"
#undef NO_IMPORT_ARRAY

#if EIGEN_VERSION_AT_LEAST(3,2,90)
  #define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned16
#else
  #define EIGENPY_DEFAULT_ALIGNMENT_VALUE Eigen::Aligned
#endif

#define EIGENPY_NO_ALIGNMENT_VALUE Eigen::Unaligned

#define EIGENPY_UNUSED_VARIABLE(var) (void)(var)

#include "eigenpy/expose.hpp"

namespace eigenpy
{
  template<typename MatType> struct EigenToPy;
  template<typename MatType> struct EigenFromPy;
}

#endif // ifndef __eigenpy_fwd_hpp__
<|endoftext|>


<commit_before>// Network API based on boost::asio
#ifndef LIBPORT_ASIO_HH
# define LIBPORT_ASIO_HH

# include <iostream>
# include <boost/asio.hpp>
#ifndef LIBPORT_NO_SSL
# include <boost/asio/ssl.hpp>
#endif
# include <boost/function.hpp>

# include <libport/destructible.hh>
# include <libport/finally.hh>

namespace libport
{
  class AsioDestructible: public Destructible
  {
    protected:
      virtual void doDestroy();
  };
  /** BaseSocket class.
   *
   * This class has a callback-based API: onReadFunc() and onErrorFunc().
   */
  class BaseSocket: public AsioDestructible
  {
    public:
      virtual ~BaseSocket(){}
      libport::Finally deletor;
      /// Write data asynchronously to the socket.
      virtual void write(const void* data, unsigned int length) = 0;
      /// Alias on write() for API compatibility.
      inline void send(void* addr, int len) {write((const void*)addr, len);}
      /// Alias on close() for API compatibility.
      inline void disconnect() {close();}
      /// Return if the socket is connected to a remote host.
      virtual bool isConnected() = 0;
      /// Disconnect the socket from the remote host.
      virtual void close() = 0;
      /// Callback function called each time new data is available.
      boost::function1<bool, boost::asio::streambuf&> onReadFunc;
      /// Callback function called in case of error on the socket.
      boost::function1<void, boost::system::error_code> onErrorFunc;
  };

  /** Socket class with a higher API.
   *
   */
  class Socket: public AsioDestructible
  {
    public:
      Socket(): base_(0){}
      virtual ~Socket();
      /** Set underlying BaseSocket object, setup its callbacks to call our virtual functions.
       */
      virtual void setBase(BaseSocket*);

      /** Called each time new data is received.
       *   \return the number of bytes used in buffer. The remaining data will
       *   be passed again to this function as soon as at least an extra byte
       *   is available.
       */
      virtual int onRead(const void*, int length){return length;}

      /** Called in case of error on the socket.
      */
      virtual void onError(boost::system::error_code){}

      /// Ask for the asynchronous destruction of this object.
      virtual void destroy();

      inline void write(const void* data, unsigned int length)
      { base_->write(data, length);}
      /// Alias on write() for API compatibility.
      inline void send(void* addr, int len) {write((const void*)addr, len);}
      inline void close() {if (base_) base_->close();}
      inline bool isConnected() {return base_?base_->isConnected():false;}

      boost::system::error_code connect(const std::string& host,
	  const std::string& port, bool udp=false);

      typedef void* Handle;
      typedef boost::function0<Socket*> SocketFactory;

      static Handle listen(SocketFactory f, const std::string& host,
	  const std::string& port, boost::system::error_code & erc,
          bool udp = false);
#ifndef LIBPORT_NO_SSL
      static Handle listenSSL(SocketFactory f, const std::string& host,
	  const std::string&  port,
	  boost::system::error_code& erc,
	  boost::asio::ssl::context_base::method ctx
	    = boost::asio::ssl::context::sslv23_server,
	  boost::asio::ssl::context::options options
	    = boost::asio::ssl::context::verify_none,
	  const std::string& privateKeyFile = "",
	  const std::string& certChainFile = "",
	  const std::string& tmpDHFile = "" ,
	  const std::string& cipherList = "");
#endif
    protected:
      bool onRead_(boost::asio::streambuf&);
      std::string buffer;
      BaseSocket* base_;
    private:
    template<typename Proto, typename BaseFactory> static boost::system::error_code
      listenProto(SocketFactory f, const std::string& host,
	  const std::string&port, BaseFactory bf);
    template<typename Proto, typename BaseFactory> boost::system::error_code
      connectProto(const std::string& host, const std::string& port, BaseFactory bf);
  };

}

# include "libport/asio.hxx"

#endif
<commit_msg>Add a send(std::string) to Socket.<commit_after>// Network API based on boost::asio
#ifndef LIBPORT_ASIO_HH
# define LIBPORT_ASIO_HH

# include <iostream>
# include <boost/asio.hpp>
#ifndef LIBPORT_NO_SSL
# include <boost/asio/ssl.hpp>
#endif
# include <boost/function.hpp>

# include <libport/destructible.hh>
# include <libport/finally.hh>

namespace libport
{
  class AsioDestructible: public Destructible
  {
    protected:
      virtual void doDestroy();
  };
  /** BaseSocket class.
   *
   * This class has a callback-based API: onReadFunc() and onErrorFunc().
   */
  class BaseSocket: public AsioDestructible
  {
    public:
      virtual ~BaseSocket(){}
      libport::Finally deletor;
      /// Write data asynchronously to the socket.
      virtual void write(const void* data, unsigned int length) = 0;
      /// Alias on write() for API compatibility.
      inline void send(void* addr, int len) {write((const void*)addr, len);}
      /// Alias on close() for API compatibility.
      inline void disconnect() {close();}
      /// Return if the socket is connected to a remote host.
      virtual bool isConnected() = 0;
      /// Disconnect the socket from the remote host.
      virtual void close() = 0;
      /// Callback function called each time new data is available.
      boost::function1<bool, boost::asio::streambuf&> onReadFunc;
      /// Callback function called in case of error on the socket.
      boost::function1<void, boost::system::error_code> onErrorFunc;
  };

  /** Socket class with a higher API.
   *
   */
  class Socket: public AsioDestructible
  {
    public:
      Socket(): base_(0){}
      virtual ~Socket();
      /** Set underlying BaseSocket object, setup its callbacks to call our virtual functions.
       */
      virtual void setBase(BaseSocket*);

      /** Called each time new data is received.
       *   \return the number of bytes used in buffer. The remaining data will
       *   be passed again to this function as soon as at least an extra byte
       *   is available.
       */
      virtual int onRead(const void*, int length){return length;}

      /** Called in case of error on the socket.
      */
      virtual void onError(boost::system::error_code){}

      /// Ask for the asynchronous destruction of this object.
      virtual void destroy();

      inline void write(const void* data, unsigned int length)
      { base_->write(data, length);}
      /// Alias on write() for API compatibility.
      inline void send(void* addr, int len) {write((const void*)addr, len);}
      inline void send(const std::string& s) {write(s.c_str(), s.length());}
      inline void close() {if (base_) base_->close();}
      inline bool isConnected() {return base_?base_->isConnected():false;}

      boost::system::error_code connect(const std::string& host,
	  const std::string& port, bool udp=false);

      typedef void* Handle;
      typedef boost::function0<Socket*> SocketFactory;

      static Handle listen(SocketFactory f, const std::string& host,
	  const std::string& port, boost::system::error_code & erc,
          bool udp = false);
#ifndef LIBPORT_NO_SSL
      static Handle listenSSL(SocketFactory f, const std::string& host,
	  const std::string&  port,
	  boost::system::error_code& erc,
	  boost::asio::ssl::context_base::method ctx
	    = boost::asio::ssl::context::sslv23_server,
	  boost::asio::ssl::context::options options
	    = boost::asio::ssl::context::verify_none,
	  const std::string& privateKeyFile = "",
	  const std::string& certChainFile = "",
	  const std::string& tmpDHFile = "" ,
	  const std::string& cipherList = "");
#endif
    protected:
      bool onRead_(boost::asio::streambuf&);
      std::string buffer;
      BaseSocket* base_;
    private:
    template<typename Proto, typename BaseFactory> static boost::system::error_code
      listenProto(SocketFactory f, const std::string& host,
	  const std::string&port, BaseFactory bf);
    template<typename Proto, typename BaseFactory> boost::system::error_code
      connectProto(const std::string& host, const std::string& port, BaseFactory bf);
  };

}

# include "libport/asio.hxx"

#endif
<|endoftext|>


<commit_before>/**
 * @file common.tcc
 * @author Sean Massung
 * @author Chase Geigle
 */

#include <map>
#include <sstream>
#include <sys/stat.h>
#include "util/common.h"
#include "io/mmap_file.h"

namespace meta {
namespace common {

template <class T>
std::string to_string(const T & value)
{
    std::stringstream ss;
    ss << value;
    return ss.str();
}

std::string add_commas(const std::string & number)
{
    std::string ret{""};
    size_t counter = 0;
    for(auto it = number.rbegin(); it != number.rend(); ++it, ++counter)
    {
        if(counter != 0 && counter != number.size() && counter % 3 == 0)
            ret = ',' + ret;
        ret = *it + ret;
    }

    return ret;
}

uint64_t file_size(const std::string & filename)
{
    if(!file_exists(filename))
        return 0;

    struct stat64 st;
    stat64(filename.c_str(), &st);
    return st.st_size;
}

bool file_exists(const std::string & filename)
{
    FILE* f = fopen(filename.c_str(), "r");
    if(f != nullptr)
    {
        fclose(f);
        return true;
    }
    return false;
}

uint64_t num_lines(const std::string & filename)
{
    io::mmap_file file{filename};
    return std::count(file.start(), file.start() + file.size(), '\n');
}

std::string bytes_to_units(double num_bytes)
{
    std::string units = "bytes";
    for(auto & u: {"KB", "MB", "GB", "TB"})
    {
        if(num_bytes >= 1024)
        {
            num_bytes /= 1024;
            units = u;
        }
    }

    num_bytes = static_cast<double>(static_cast<int>(num_bytes * 100)) / 100;
    return to_string(num_bytes) + " " + units;
}

template <class Duration, class Functor>
Duration time(Functor && functor)
{
    auto start = std::chrono::steady_clock::now();
    functor();
    auto end   = std::chrono::steady_clock::now();
    return std::chrono::duration_cast<Duration>(end - start);
}

void show_progress(size_t idx, size_t max, size_t freq, const std::string & prefix)
{
    if(idx % freq == 0)
    {
        std::cerr << prefix << static_cast<double>(idx) / max * 100 << "%    \r";
        std::flush(std::cerr);
    }
}

void end_progress(const std::string & prefix)
{
    std::cerr << prefix << "100%         " << std::endl;
}

template <class Key,
          class Value,
          class... Args,
          template <class, class, class...> class Map>
Value safe_at(const Map<Key, Value, Args...> & map, const Key & key)
{
    auto it = map.find(key);
    if(it == map.end())
        return Value{};
    return it->second;
}

template <class Result, class... Args>
std::function<Result(Args...)> memoize(std::function<Result(Args...)> fun)
{
    return [fun](Args... args) {
        static std::map<std::tuple<Args...>, Result> map_;
        auto it = map_.find(std::make_tuple(args...));
        if(it != map_.end())
            return it->second;
        return map_[std::make_tuple(args...)] = fun(args...);
    };
}

template <class Key, class Value>
void save_mapping(const util::invertible_map<Key, Value> & map,
                  const std::string & filename)
{
    std::ofstream outfile{filename};
    for(auto & p: map)
        outfile << p.first << " " << p.second << "\n";
}

template <class T>
void save_mapping(const std::vector<T> & vec, const std::string & filename)
{
    std::ofstream outfile{filename};
    for(auto & v: vec)
        outfile << v << "\n";
}

template <class Key, class Value>
void load_mapping(util::invertible_map<Key, Value> & map,
                  const std::string & filename)
{
    std::ifstream input{filename};
    Key k;
    Value v;
    while((input >> k) && (input >> v))
        map.insert(std::make_pair(k, v));
}

template <class T>
void load_mapping(std::vector<T> & vec, const std::string & filename)
{
    std::ifstream input{filename};
    uint64_t size = common::num_lines(filename);
    vec.reserve(size);

    T val;
    while(input >> val)
        vec.push_back(val);
}

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

}
}
<commit_msg>add progress output for line counting<commit_after>/**
 * @file common.tcc
 * @author Sean Massung
 * @author Chase Geigle
 */

#include <map>
#include <sstream>
#include <sys/stat.h>
#include "util/common.h"
#include "io/mmap_file.h"

namespace meta {
namespace common {

template <class T>
std::string to_string(const T & value)
{
    std::stringstream ss;
    ss << value;
    return ss.str();
}

std::string add_commas(const std::string & number)
{
    std::string ret{""};
    size_t counter = 0;
    for(auto it = number.rbegin(); it != number.rend(); ++it, ++counter)
    {
        if(counter != 0 && counter != number.size() && counter % 3 == 0)
            ret = ',' + ret;
        ret = *it + ret;
    }

    return ret;
}

uint64_t file_size(const std::string & filename)
{
    if(!file_exists(filename))
        return 0;

    struct stat64 st;
    stat64(filename.c_str(), &st);
    return st.st_size;
}

bool file_exists(const std::string & filename)
{
    FILE* f = fopen(filename.c_str(), "r");
    if(f != nullptr)
    {
        fclose(f);
        return true;
    }
    return false;
}

uint64_t num_lines(const std::string & filename)
{
    io::mmap_file file{filename};
    uint64_t num = 0;

    std::string progress = " Counting lines in file ";
    for(uint64_t idx = 0; idx < file.size(); ++idx)
    {
        common::show_progress(idx, file.size(), 16 * 1024 * 1024, progress);
        if(file.start()[idx] == '\n')
            ++num;
    }
    common::end_progress(progress);

    return num;
}

std::string bytes_to_units(double num_bytes)
{
    std::string units = "bytes";
    for(auto & u: {"KB", "MB", "GB", "TB"})
    {
        if(num_bytes >= 1024)
        {
            num_bytes /= 1024;
            units = u;
        }
    }

    num_bytes = static_cast<double>(static_cast<int>(num_bytes * 100)) / 100;
    return to_string(num_bytes) + " " + units;
}

template <class Duration, class Functor>
Duration time(Functor && functor)
{
    auto start = std::chrono::steady_clock::now();
    functor();
    auto end   = std::chrono::steady_clock::now();
    return std::chrono::duration_cast<Duration>(end - start);
}

void show_progress(size_t idx, size_t max, size_t freq, const std::string & prefix)
{
    if(idx % freq == 0)
    {
        std::cerr << prefix << static_cast<double>(idx) / max * 100 << "%    \r";
        std::flush(std::cerr);
    }
}

void end_progress(const std::string & prefix)
{
    std::cerr << prefix << "100%         " << std::endl;
}

template <class Key,
          class Value,
          class... Args,
          template <class, class, class...> class Map>
Value safe_at(const Map<Key, Value, Args...> & map, const Key & key)
{
    auto it = map.find(key);
    if(it == map.end())
        return Value{};
    return it->second;
}

template <class Result, class... Args>
std::function<Result(Args...)> memoize(std::function<Result(Args...)> fun)
{
    return [fun](Args... args) {
        static std::map<std::tuple<Args...>, Result> map_;
        auto it = map_.find(std::make_tuple(args...));
        if(it != map_.end())
            return it->second;
        return map_[std::make_tuple(args...)] = fun(args...);
    };
}

template <class Key, class Value>
void save_mapping(const util::invertible_map<Key, Value> & map,
                  const std::string & filename)
{
    std::ofstream outfile{filename};
    for(auto & p: map)
        outfile << p.first << " " << p.second << "\n";
}

template <class T>
void save_mapping(const std::vector<T> & vec, const std::string & filename)
{
    std::ofstream outfile{filename};
    for(auto & v: vec)
        outfile << v << "\n";
}

template <class Key, class Value>
void load_mapping(util::invertible_map<Key, Value> & map,
                  const std::string & filename)
{
    std::ifstream input{filename};
    Key k;
    Value v;
    while((input >> k) && (input >> v))
        map.insert(std::make_pair(k, v));
}

template <class T>
void load_mapping(std::vector<T> & vec, const std::string & filename)
{
    std::ifstream input{filename};
    uint64_t size = common::num_lines(filename);
    vec.reserve(size);

    T val;
    while(input >> val)
        vec.push_back(val);
}

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

}
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, 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.

// Internal Includes
#include <osvr/ClientKit/Context.h>
#include <osvr/ClientKit/Interface.h>
#include <osvr/Util/ClientReportTypesC.h>

// Library/third-party includes

// Standard includes
#include <iostream>
#include <string>

void skeletonCallback(void * /*userdata*/, const OSVR_TimeValue * /*timestamp*/,
                      const OSVR_SkeletonReport *report) {
    std::cout << "Got skeleton update callback, for sensor #" << report->sensor
              << std::endl;
}

int main() {
    osvr::clientkit::ClientContext context(
        "com.osvr.exampleclients.SkeletonCallback");

    osvr::clientkit::Interface skeleton =
        context.getInterface("/com_osvr_example_Skeleton/Skeleton/skeleton/0");
    skeleton.registerCallback(&skeletonCallback, NULL);

    // Pretend that this is your application's mainloop.
    while (1) {
        context.update();
    }

    std::cout << "Library shut down, exiting." << std::endl;
    return 0;
}
<commit_msg>remove empty example<commit_after><|endoftext|>


<commit_before>#include <iostream>

#include "initConfig.h"
#include "libconfig.h++"
#include "getopt.h"

using namespace watcher;
using namespace libconfig;
using namespace std;

bool watcher::initConfig(
            libconfig::Config &config,
            int argc,
            char **argv,
            std::string &configFilename,
            const char configFileChar,
            const char *configFileString)
{
    int c;
    // int digit_optind = 0;

    while (true)
    {
        // int this_option_optind = optind ? optind : 1;
        int option_index = 0;
        static struct option long_options[] = {
            {configFileString, required_argument, 0, configFileChar},
            {0, 0, 0, 0}
        };

        opterr=0; // Don't print message just because we see an option we don't understand.

        char args[] = { configFileChar, ':', '\n' };
        c = getopt_long(argc, argv, args, long_options, &option_index);

        if (c == -1)
            break;

        if (c==configFileChar)
        {
            try
            {
                config.readFile(optarg);
                configFilename=optarg;
                return true;
            }
            catch (ParseException &e)
            {
                // Can't use logging here - if we're reading the config file we probably have not
                // init'd the logging mechanism.
                cerr << "Error reading configuration file " << optarg << ": " << e.what() << endl;
                cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << endl;
            }
            catch (FileIOException &e)
            {
                cerr << "Unable to read file " << optarg << " given as configuration file on the command line." << endl;
            }
        }
        // else - ignore things we don't understand
    }
    return false;
}

<commit_msg>initConfig: If not passed on the command line (-c file), then look for configuration file of the name argv[0].cfg (e.g. "watcherd.cfg") when loading the config file.<commit_after>#include <iostream>

#include "initConfig.h"
#include "libconfig.h++"
#include "getopt.h"

using namespace watcher;
using namespace libconfig;
using namespace std;

static bool readConfig(libconfig::Config &config, const string &filename)
{
    try
    {
        config.readFile(filename.c_str());
        return true;
    }
    catch (ParseException &e)
    {
        // Can't use logging here - if we're reading the config file we probably have not
        // init'd the logging mechanism.
        cerr << "Error reading configuration file " << optarg << ": " << e.what() << endl;
        cerr << "Error: \"" << e.getError() << "\" on line: " << e.getLine() << endl;
    }
    catch (FileIOException &e)
    {
        cerr << "Unable to read file " << optarg << " given as configuration file on the command line." << endl;
    }
    return false;
}

bool watcher::initConfig(
            libconfig::Config &config,
            int argc,
            char **argv,
            std::string &configFilename,
            const char configFileChar,
            const char *configFileString)
{
    int c;
    // int digit_optind = 0;

    bool retVal=false;

    while (true)
    {
        // int this_option_optind = optind ? optind : 1;
        int option_index = 0;
        static struct option long_options[] = {
            {configFileString, required_argument, 0, configFileChar},
            {0, 0, 0, 0}
        };

        opterr=0; // Don't print message just because we see an option we don't understand.

        char args[] = { configFileChar, ':', '\n' };
        c = getopt_long(argc, argv, args, long_options, &option_index);

        if (c == -1)
            break;

        if (c==configFileChar)
            if(true==(retVal=readConfig(config, optarg)))
                configFilename=optarg;

        // else - ignore things we don't understand
    }

    // Last ditch: look for a file called `echo argv[0]`.cfg.
    if(retVal==false)
    {
        string fname(argv[0]);
        fname+=".cfg";

        if(true==(retVal=readConfig(config, fname)))
            configFilename=fname;
    }

    return retVal;
}

<|endoftext|>


<commit_before>/**
 * @file
 * @author  Mohammad S. Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 Mohammad S. Babaei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * The CMS start page.
 */

#ifndef SERVICE_CMS_HPP
#define SERVICE_CMS_HPP

#include "Page.hpp"

namespace Service {
class Cms;
}

class Service::Cms : public Service::Page
{
private:
    struct Impl;
    std::unique_ptr<Impl> m_pimpl;

public:
    explicit Cms();
    virtual ~Cms();

private:
    Wt::WWidget *Layout() override;
};

#endif /* SERVICE_CMS_HPP */
<commit_msg>add missing header<commit_after>/**
 * @file
 * @author  Mohammad S. Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 Mohammad S. Babaei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * The CMS start page.
 */

#ifndef SERVICE_CMS_HPP
#define SERVICE_CMS_HPP

#include <memory>
#include "Page.hpp"

namespace Service {
class Cms;
}

class Service::Cms : public Service::Page
{
private:
    struct Impl;
    std::unique_ptr<Impl> m_pimpl;

public:
    explicit Cms();
    virtual ~Cms();

private:
    Wt::WWidget *Layout() override;
};

#endif /* SERVICE_CMS_HPP */
<|endoftext|>