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

// Base include file.  Must be first.
#include <new>

#include <xalanc/Include/PlatformDefinitions.hpp>

#include <xercesc/framework/MemoryManager.hpp>

#if defined(XALAN_WINDOWS)
#include <windows.h>
#include <stdexcept>
#include <stdlib.h>

class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType
{
public:

    XalanMemoryManagerImpl( DWORD defSize = 0 ) :
	    m_heapHandle(NULL)
	{
		m_heapHandle = HeapCreate(	HEAP_NO_SERIALIZE,
		                            0, // dwInitialSize
		                            defSize);

        if( m_heapHandle == NULL )
		{
            XALAN_USING_STD(runtime_error)

            char buffer[20];
            buffer[0] = 0;

            _ultoa( GetLastError(), buffer, 10);

            throw runtime_error(buffer);
		}
	}

	virtual void*
	allocate( size_t size )
    {
        LPVOID ptr = HeapAlloc(
                        m_heapHandle,   //HANDLE hHeap
                        0,              //DWORD dwFlags
                        size            //SIZE_T dwBytes
                        );

        if( ptr == 0)
        {
            XALAN_USING_STD(bad_alloc)

            throw bad_alloc();
        }

        return ptr;
    }

	virtual void
	deallocate(  void* 	pDataPointer  )
	{
        if ( 0 == HeapFree(
                        m_heapHandle,   //HANDLE hHeap,
                        0,              //DWORD dwFlags,
                        pDataPointer ) )//*LPVOID lpMem
        {
            XALAN_USING_STD(bad_alloc)

            throw bad_alloc();
        }
    }

    MemoryManager*
    getExceptionMemoryManager()
    {
        return this;
    }

    virtual
	~XalanMemoryManagerImpl()
	{
       if( 0 == HeapDestroy(m_heapHandle) )
       {
            XALAN_USING_STD(runtime_error)

            char buffer[20];
            buffer[0] = 0;

            _ultoa( GetLastError(), buffer, 10);

            throw runtime_error(buffer);
       }
	}

private:

    // Not implemented
	XalanMemoryManagerImpl&
	operator=(const XalanMemoryManagerImpl&);

	XalanMemoryManagerImpl(const XalanMemoryManagerImpl&);

	//Data
	HANDLE  m_heapHandle;
};

#else

class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType
{
public:

    virtual
	~XalanMemoryManagerImpl()
	{
	}

	virtual void*
	allocate( size_t 	size )
	{
	    void* memptr = ::operator new(size);

	    if (memptr != NULL)
	    {
	        return memptr;
	    }

		XALAN_USING_STD(bad_alloc)

		throw bad_alloc();
	}
	virtual void
	deallocate(  void* 		pDataPointer  )
	{
		operator delete(pDataPointer);
	}
};

#endif

#endif  // MEMORYMANAGERIMPL_HEADER_GUARD_1357924680
<commit_msg>Changes for compatibility with the updated Xerces-C MemoryManager class.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(MEMORYMANAGERIMPL_HEADER_GUARD_1357924680)
#define MEMORYMANAGERIMPL_HEADER_GUARD_1357924680

// Base include file.  Must be first.
#include <new>

#include <xalanc/Include/PlatformDefinitions.hpp>

#include <xercesc/framework/MemoryManager.hpp>

#if defined(XALAN_WINDOWS)
#include <windows.h>
#include <stdexcept>
#include <stdlib.h>

class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType
{
public:

    XalanMemoryManagerImpl( DWORD defSize = 0 ) :
	    m_heapHandle(NULL)
	{
		m_heapHandle = HeapCreate(	HEAP_NO_SERIALIZE,
		                            0, // dwInitialSize
		                            defSize);

        if( m_heapHandle == NULL )
		{
            XALAN_USING_STD(runtime_error)

            char buffer[20];
            buffer[0] = 0;

            _ultoa( GetLastError(), buffer, 10);

            throw runtime_error(buffer);
		}
	}

	virtual void*
	allocate( size_t size )
    {
        LPVOID ptr = HeapAlloc(
                        m_heapHandle,   //HANDLE hHeap
                        0,              //DWORD dwFlags
                        size            //SIZE_T dwBytes
                        );

        if( ptr == 0)
        {
            XALAN_USING_STD(bad_alloc)

            throw bad_alloc();
        }

        return ptr;
    }

	virtual void
	deallocate(  void* 	pDataPointer  )
	{
        if ( 0 == HeapFree(
                        m_heapHandle,   //HANDLE hHeap,
                        0,              //DWORD dwFlags,
                        pDataPointer ) )//*LPVOID lpMem
        {
            XALAN_USING_STD(bad_alloc)

            throw bad_alloc();
        }
    }

    MemoryManager*
    getExceptionMemoryManager()
    {
        return this;
    }

    virtual
	~XalanMemoryManagerImpl()
	{
       if( 0 == HeapDestroy(m_heapHandle) )
       {
            XALAN_USING_STD(runtime_error)

            char buffer[20];
            buffer[0] = 0;

            _ultoa( GetLastError(), buffer, 10);

            throw runtime_error(buffer);
       }
	}

private:

    // Not implemented
	XalanMemoryManagerImpl&
	operator=(const XalanMemoryManagerImpl&);

	XalanMemoryManagerImpl(const XalanMemoryManagerImpl&);

	//Data
	HANDLE  m_heapHandle;
};

#else

class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType
{
public:

    virtual
	~XalanMemoryManagerImpl()
	{
	}

	virtual void*
	allocate( size_t 	size )
	{
	    void* memptr = ::operator new(size);

	    if (memptr != NULL)
	    {
	        return memptr;
	    }

		XALAN_USING_STD(bad_alloc)

		throw bad_alloc();
	}
	virtual void
	deallocate(  void* 		pDataPointer  )
	{
		operator delete(pDataPointer);
	}

    MemoryManager*
    getExceptionMemoryManager()
    {
        return this;
    }
};

#endif

#endif  // MEMORYMANAGERIMPL_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/**
	This software was developed by the University of Tennessee as part of the
	Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
	project funded by the US National Science Foundation.

	If you use DANSE applications to do scientific research that leads to
	publication, we ask that you acknowledge the use of the software with the
	following sentence:

	"This work benefited from DANSE software developed under NSF award DMR-0520547."

	copyright 2008, University of Tennessee
 */
#include "parameters.hh"
#include <stdio.h>
#include <math.h>
using namespace std;

/**
 * TODO: normalize all dispersion weight lists
 */

/**
 * Weight points
 */
WeightPoint :: WeightPoint() {
	value = 0.0;
	weight = 0.0;
}

WeightPoint :: WeightPoint(double v, double w) {
	value = v;
	weight = w;
}

/**
 * Dispersion models
 */
DispersionModel :: DispersionModel() {
	npts  = 1;
	width = 0.0;
};

void DispersionModel :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) {
	visitor->dispersion_to_dict(from, to);
}
void DispersionModel :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) {
	visitor->dispersion_from_dict(from, to);
}
void DispersionModel :: operator() (void *param, vector<WeightPoint> &weights){
	// Check against zero width
	if (width<=0) {
		width = 0.0;
		npts  = 1;
	}

	Parameter* par = (Parameter*)param;
	double value = (*par)();

	if (npts<2) {
		weights.insert(weights.end(), WeightPoint(value, 1.0));
	} else {
		for(int i=0; i<npts; i++) {
			double val = value + width * (1.0*i/float(npts-1) - 0.5);

			if ( ((*par).has_min==false || val>(*par).min)
			  && ((*par).has_max==false || val<(*par).max)  )
				weights.insert(weights.end(), WeightPoint(val, 1.0));
		}
	}
}

/**
 * Method to set the weights
 * Not implemented for this class
 */
void DispersionModel :: set_weights(int npoints, double* values, double* weights){}

/**
 * Gaussian dispersion
 */

GaussianDispersion :: GaussianDispersion() {
	npts  = 1;
	width = 0.0;
	nsigmas = 2;
};

void GaussianDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) {
	visitor->gaussian_to_dict(from, to);
}
void GaussianDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) {
	visitor->gaussian_from_dict(from, to);
}

double gaussian_weight(double mean, double sigma, double x) {
	double vary, expo_value;
    vary = x-mean;
    expo_value = -vary*vary/(2*sigma*sigma);
    //return 1.0;
    return exp(expo_value);
}

/**
 * Gaussian dispersion
 * @param mean: mean value of the Gaussian
 * @param sigma: standard deviation of the Gaussian
 * @param x: value at which the Gaussian is evaluated
 * @return: value of the Gaussian
 */
void GaussianDispersion :: operator() (void *param, vector<WeightPoint> &weights){
	// Check against zero width
	if (width<=0) {
		width = 0.0;
		npts  = 1;
		nsigmas = 3;
	}

	Parameter* par = (Parameter*)param;
	double value = (*par)();

	if (npts<2) {
		weights.insert(weights.end(), WeightPoint(value, 1.0));
	} else {
		for(int i=0; i<npts; i++) {
			// We cover n(nsigmas) times sigmas on each side of the mean
			double val = value + width * (2.0*nsigmas*i/float(npts-1) - nsigmas);

			if ( ((*par).has_min==false || val>(*par).min)
			  && ((*par).has_max==false || val<(*par).max)  ) {
				double _w = gaussian_weight(value, width, val);
				weights.insert(weights.end(), WeightPoint(val, _w));
			}
		}
	}
}

/**
 * Array dispersion based on input arrays
 */

void ArrayDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) {
	visitor->array_to_dict(from, to);
}
void ArrayDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) {
	visitor->array_from_dict(from, to);
}

/**
 * Method to get the weights
 */
void ArrayDispersion :: operator() (void *param, vector<WeightPoint> &weights) {
	Parameter* par = (Parameter*)param;
	double value = (*par)();

		for(int i=0; i<npts; i++) {
			double val = value + _values[i];
			if ( ((*par).has_min==false || val>(*par).min)
			  && ((*par).has_max==false || val<(*par).max)  )
				weights.insert(weights.end(), WeightPoint(val, _weights[i]));
		}

}

/**
 * Method to set the weights
 */
void ArrayDispersion :: set_weights(int npoints, double* values, double* weights){
	npts = npoints;
	_values = values;
	_weights = weights;
}

/**
 * Parameters
 */
Parameter :: Parameter() {
	value = 0;
	min   = 0.0;
	max   = 0.0;
	has_min = false;
	has_max = false;
	has_dispersion = false;
	dispersion = new GaussianDispersion();
}

Parameter :: Parameter(double _value) {
	value = _value;
	min   = 0.0;
	max   = 0.0;
	has_min = false;
	has_max = false;
	has_dispersion = false;
	dispersion = new GaussianDispersion();
}

Parameter :: Parameter(double _value, bool disp) {
	value = _value;
	min   = 0.0;
	max   = 0.0;
	has_min = false;
	has_max = false;
	has_dispersion = disp;
	dispersion = new GaussianDispersion();
}

void Parameter :: get_weights(vector<WeightPoint> &weights) {
	(*dispersion)((void*)this, weights);
}

void Parameter :: set_min(double value) {
	has_min = true;
	min = value;
}

void Parameter :: set_max(double value) {
	has_max = true;
	max = value;
}

double Parameter :: operator()() {
	return value;
}

double Parameter :: operator=(double _value){
	value = _value;
}
<commit_msg>revert code<commit_after>/**
	This software was developed by the University of Tennessee as part of the
	Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
	project funded by the US National Science Foundation.

	If you use DANSE applications to do scientific research that leads to
	publication, we ask that you acknowledge the use of the software with the
	following sentence:

	"This work benefited from DANSE software developed under NSF award DMR-0520547."

	copyright 2008, University of Tennessee
 */
#include "parameters.hh"
#include <stdio.h>
#include <math.h>
using namespace std;

/**
 * TODO: normalize all dispersion weight lists
 */

/**
 * Weight points
 */
WeightPoint :: WeightPoint() {
	value = 0.0;
	weight = 0.0;
}

WeightPoint :: WeightPoint(double v, double w) {
	value = v;
	weight = w;
}

/**
 * Dispersion models
 */
DispersionModel :: DispersionModel() {
	npts  = 1;
	width = 0.0;
};

void DispersionModel :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) {
	visitor->dispersion_to_dict(from, to);
}
void DispersionModel :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) {
	visitor->dispersion_from_dict(from, to);
}
void DispersionModel :: operator() (void *param, vector<WeightPoint> &weights){
	// Check against zero width
	if (width<=0) {
		width = 0.0;
		npts  = 1;
	}

	Parameter* par = (Parameter*)param;
	double value = (*par)();

	if (npts<2) {
		weights.insert(weights.end(), WeightPoint(value, 1.0));
	} else {
		for(int i=0; i<npts; i++) {
			double val = value + width * (1.0*i/float(npts-1) - 0.5);

			if ( ((*par).has_min==false || val>(*par).min)
			  && ((*par).has_max==false || val<(*par).max)  )
				weights.insert(weights.end(), WeightPoint(val, 1.0));
		}
	}
}

/**
 * Method to set the weights
 * Not implemented for this class
 */
void DispersionModel :: set_weights(int npoints, double* values, double* weights){}

/**
 * Gaussian dispersion
 */

GaussianDispersion :: GaussianDispersion() {
	npts  = 1;
	width = 0.0;
	nsigmas = 2;
};

void GaussianDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) {
	visitor->gaussian_to_dict(from, to);
}
void GaussianDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) {
	visitor->gaussian_from_dict(from, to);
}

double gaussian_weight(double mean, double sigma, double x) {
	double vary, expo_value;
    vary = x-mean;
    expo_value = -vary*vary/(2*sigma*sigma);
    //return 1.0;
    return exp(expo_value);
}

/**
 * Gaussian dispersion
 * @param mean: mean value of the Gaussian
 * @param sigma: standard deviation of the Gaussian
 * @param x: value at which the Gaussian is evaluated
 * @return: value of the Gaussian
 */
void GaussianDispersion :: operator() (void *param, vector<WeightPoint> &weights){
	// Check against zero width
	if (width<=0) {
		width = 0.0;
		npts  = 1;
		nsigmas = 3;
	}

	Parameter* par = (Parameter*)param;
	double value = (*par)();

	if (npts<2) {
		weights.insert(weights.end(), WeightPoint(value, 1.0));
	} else {
		for(int i=0; i<npts; i++) {
			// We cover n(nsigmas) times sigmas on each side of the mean
			double val = value + width * (2.0*nsigmas*i/float(npts-1) - nsigmas);

			if ( ((*par).has_min==false || val>(*par).min)
			  && ((*par).has_max==false || val<(*par).max)  ) {
				double _w = gaussian_weight(value, width, val);
				weights.insert(weights.end(), WeightPoint(val, _w));
			}
		}
	}
}

/**
 * Array dispersion based on input arrays
 */

void ArrayDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) {
	visitor->array_to_dict(from, to);
}
void ArrayDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) {
	visitor->array_from_dict(from, to);
}

/**
 * Method to get the weights
 */
void ArrayDispersion :: operator() (void *param, vector<WeightPoint> &weights) {
	Parameter* par = (Parameter*)param;
	double value = (*par)();

	if (npts<2) {
		weights.insert(weights.end(), WeightPoint(value, 1.0));
	} else {
		for(int i=0; i<npts; i++) {
			if ( ((*par).has_min==false || _values[i]>(*par).min)
			  && ((*par).has_max==false || _values[i]<(*par).max)  )
				weights.insert(weights.end(), WeightPoint(_values[i], _weights[i]));
		}
	}
}
/**
 * Method to set the weights
 */
void ArrayDispersion :: set_weights(int npoints, double* values, double* weights){
	npts = npoints;
	_values = values;
	_weights = weights;
}

/**
 * Parameters
 */
Parameter :: Parameter() {
	value = 0;
	min   = 0.0;
	max   = 0.0;
	has_min = false;
	has_max = false;
	has_dispersion = false;
	dispersion = new GaussianDispersion();
}

Parameter :: Parameter(double _value) {
	value = _value;
	min   = 0.0;
	max   = 0.0;
	has_min = false;
	has_max = false;
	has_dispersion = false;
	dispersion = new GaussianDispersion();
}

Parameter :: Parameter(double _value, bool disp) {
	value = _value;
	min   = 0.0;
	max   = 0.0;
	has_min = false;
	has_max = false;
	has_dispersion = disp;
	dispersion = new GaussianDispersion();
}

void Parameter :: get_weights(vector<WeightPoint> &weights) {
	(*dispersion)((void*)this, weights);
}

void Parameter :: set_min(double value) {
	has_min = true;
	min = value;
}

void Parameter :: set_max(double value) {
	has_max = true;
	max = value;
}

double Parameter :: operator()() {
	return value;
}

double Parameter :: operator=(double _value){
	value = _value;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>

#include <osquery/core.h>
#include <osquery/tables.h>
#include <osquery/filesystem.h>

#include "osquery/core/conversions.h"

namespace osquery {
namespace tables {

std::string getUSBProperty(const CFMutableDictionaryRef& details,
                           const std::string& key) {
  // Get a property from the device.
  auto cfkey = CFStringCreateWithCString(kCFAllocatorDefault, key.c_str(),
    kCFStringEncodingUTF8);
  auto property = CFDictionaryGetValue(details, cfkey);
  CFRelease(cfkey);
  if (property) {
    if (CFGetTypeID(property) == CFNumberGetTypeID()) {
      return stringFromCFNumber((CFDataRef)property);
    } else if (CFGetTypeID(property) == CFStringGetTypeID()) {
      return stringFromCFString((CFStringRef)property);
    }
  }
  return "";
}

void genUSBDevice(const io_service_t& device, QueryData& results) {
  Row r;

  // Get the device details
  CFMutableDictionaryRef details;
  IORegistryEntryCreateCFProperties(
      device, &details, kCFAllocatorDefault, kNilOptions);

  r["usb_address"] = getUSBProperty(details, "USB Address");
  r["usb_port"] = getUSBProperty(details, "PortNum");

  r["model"] = getUSBProperty(details, "USB Product Name");
  r["model_id"] = getUSBProperty(details, "idProduct");
  r["vendor"] = getUSBProperty(details, "USB Vendor Name");
  r["vendor_id"] = getUSBProperty(details, "idVendor");
  r["serial"] = getUSBProperty(details, "iSerialNumber");

  auto non_removable = getUSBProperty(details, "non-removable");
  r["removable"] = (non_removable == "yes") ? "0" : "1";

  results.push_back(r);
  CFRelease(details);
}

QueryData genUSBDevices(QueryContext& context) {
  QueryData results;

  auto matching = IOServiceMatching(kIOUSBDeviceClassName);
  if (matching == nullptr) {
    // No devices matched USB, very odd.
    return results;
  }

  io_iterator_t it;
  auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &it);
  if (kr != KERN_SUCCESS) {
    return results;
  }

  io_service_t device;
  while ((device = IOIteratorNext(it))) {
    genUSBDevice(device, results);
    IOObjectRelease(device);
  }

  IOObjectRelease(it);
  return results;
}
}
}
<commit_msg>[Fix #1432] Improve OS X USB device reporting<commit_after>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <iomanip>
#include <sstream>

#include <IOKit/IOKitLib.h>
#include <IOKit/usb/IOUSBLib.h>

#include <osquery/core.h>
#include <osquery/tables.h>
#include <osquery/filesystem.h>

#include "osquery/core/conversions.h"

namespace osquery {
namespace tables {

std::string getUSBProperty(const CFMutableDictionaryRef& details,
                           const std::string& key) {
  // Get a property from the device.
  auto cfkey = CFStringCreateWithCString(kCFAllocatorDefault, key.c_str(),
    kCFStringEncodingUTF8);
  auto property = CFDictionaryGetValue(details, cfkey);
  CFRelease(cfkey);
  if (property) {
    if (CFGetTypeID(property) == CFNumberGetTypeID()) {
      return stringFromCFNumber((CFDataRef)property);
    } else if (CFGetTypeID(property) == CFStringGetTypeID()) {
      return stringFromCFString((CFStringRef)property);
    }
  }
  return "";
}

inline void idToHex(std::string& id) {
  int base = AS_LITERAL(int, id);
  std::stringstream hex_id;
  hex_id << std::hex << std::setw(4) << std::setfill('0') << (base & 0xFFFF);
  id = hex_id.str();
}

void genUSBDevice(const io_service_t& device, QueryData& results) {
  Row r;

  // Get the device details
  CFMutableDictionaryRef details;
  IORegistryEntryCreateCFProperties(
      device, &details, kCFAllocatorDefault, kNilOptions);

  r["usb_address"] = getUSBProperty(details, "USB Address");
  r["usb_port"] = getUSBProperty(details, "PortNum");

  r["model"] = getUSBProperty(details, "USB Product Name");
  if (r.at("model").size() == 0) {
    // Could not find the model name from IOKit, use the label.
    io_name_t name;
    if (IORegistryEntryGetName(device, name) == KERN_SUCCESS) {
      r["model"] = std::string(name);
    }
  }

  r["model_id"] = getUSBProperty(details, "idProduct");
  r["vendor"] = getUSBProperty(details, "USB Vendor Name");
  r["vendor_id"] = getUSBProperty(details, "idVendor");

  r["serial"] = getUSBProperty(details, "USB Serial Number");
  if (r.at("serial").size() == 0) {
    r["serial"] = getUSBProperty(details, "iSerialNumber");
  }

  auto non_removable = getUSBProperty(details, "non-removable");
  r["removable"] = (non_removable == "yes") ? "0" : "1";

  if (r.at("vendor_id").size() > 0 && r.at("model_id").size() > 0) {
    // Only add the USB device on OS X if it contains a Vendor and Model ID.
    // On OS X 10.11 the simulation hubs are PCI devices within IOKit and
    // lack the useful USB metadata.
    idToHex(r["vendor_id"]);
    idToHex(r["model_id"]);
    results.push_back(r);
  }
  CFRelease(details);
}

QueryData genUSBDevices(QueryContext& context) {
  QueryData results;

  auto matching = IOServiceMatching(kIOUSBDeviceClassName);
  if (matching == nullptr) {
    // No devices matched USB, very odd.
    return results;
  }

  io_iterator_t it;
  auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &it);
  if (kr != KERN_SUCCESS) {
    return results;
  }

  io_service_t device;
  while ((device = IOIteratorNext(it))) {
    genUSBDevice(device, results);
    IOObjectRelease(device);
  }

  IOObjectRelease(it);
  return results;
}
}
}
<|endoftext|>


<commit_before>#ifndef _SNARKFRONT_AES_INV_CIPHER_HPP_
#define _SNARKFRONT_AES_INV_CIPHER_HPP_

#include <array>
#include <cstdint>
#include "AES_InvSBox.hpp"
#include "AES_KeyExpansion.hpp"

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// 5.3 Inverse Cipher
//

template <typename VAR, typename T, typename U, typename BITWISE>
class AES_InvCipher
{
public:
    typedef VAR VarType;
    typedef std::array<VAR, 16> BlockType;
    typedef AES_KeyExpansion<VAR, T, U, BITWISE> KeyExpansion;

    AES_InvCipher() = default;

    // AES-128
    void operator() (const std::array<VAR, 16>& in,
                     std::array<VAR, 16>& out,
                     const std::array<VAR, 176>& w) const {
        decrypt(in, out, w);
    }

    // AES-192
    void operator() (const std::array<VAR, 16>& in,
                     std::array<VAR, 16>& out,
                     const std::array<VAR, 208>& w) const {
        decrypt(in, out, w);
    }

    // AES-256
    void operator() (const std::array<VAR, 16>& in,
                     std::array<VAR, 16>& out,
                     const std::array<VAR, 240>& w) const {
        decrypt(in, out, w);
    }

private:
    // AES-128 key schedule size 176 (Nr = 10)
    // AES-192 key schedule size 208 (Nr = 12)
    // AES-256 key schedule size 240 (Nr = 14)
    template <std::size_t WSZ>
    void decrypt(const std::array<VAR, 16>& in,
                 std::array<VAR, 16>& out,
                 const std::array<VAR, WSZ>& w) const // 16 * (Nr + 1) octets
    {
        const auto Nr = w.size() / 16 - 1;

        auto state = in;

        AddRoundKey(state, w, 16*Nr);

        for (std::size_t round = Nr - 1; round > 0; --round) {
            InvShiftRows(state);
            InvSubBytes(state);
            AddRoundKey(state, w, 16*round);
            InvMixColumns(state);
        }

        InvShiftRows(state);
        InvSubBytes(state);
        AddRoundKey(state, w, 0);

        out = state;
    }

    // 5.3.1 InvShiftRows() Transformation
    void InvShiftRows(std::array<VAR, 16>& state) const {
        VAR tmp;

        // second row rotate right by one element
        tmp = state[13];
        state[13] = state[9];
        state[9] = state[5];
        state[5] = state[1];
        state[1] = tmp;

        // third row rotate right by two elements
        tmp = state[14];
        state[14] = state[6];
        state[6] = tmp;
        tmp = state[10];
        state[10] = state[2];
        state[2] = tmp;

        // fourth row rotate right by three elements
        tmp = state[15];
        state[15] = state[3];
        state[3] = state[7];
        state[7] = state[11];
        state[11] = tmp;
    }

    // 5.3.2 InvSubBytes() Transformation
    void InvSubBytes(std::array<VAR, 16>& state) const {
        for (auto& a : state)
            a = m_inv_sbox(a);
    }

    // 5.3.3 InvMixColumns() Transformation
    void InvMixColumns(std::array<VAR, 16>& state) const {
        // irreducible polynomial for AES
        const auto modpoly = BITWISE::constant(0x1b);

        for (std::size_t i = 0; i < 16; i += 4) {
            const VAR
                xs0 = BITWISE::xtime(state[i], modpoly), // {02} * s0
                xxs0 = BITWISE::xtime(xs0, modpoly),     // {04} * s0
                xxxs0 = BITWISE::xtime(xxs0, modpoly);   // {08} * s0

            const VAR
                xs1 = BITWISE::xtime(state[i + 1], modpoly), // {02} * s1
                xxs1 = BITWISE::xtime(xs1, modpoly),         // {04} * s1
                xxxs1 = BITWISE::xtime(xxs1, modpoly);       // {08} * s1

            const VAR
                xs2 = BITWISE::xtime(state[i + 2], modpoly), // {02} * s2
                xxs2 = BITWISE::xtime(xs2, modpoly),         // {04} * s2
                xxxs2 = BITWISE::xtime(xxs2, modpoly);       // {08} * s2

            const VAR
                xs3 = BITWISE::xtime(state[i + 3], modpoly), // {02} * s3
                xxs3 = BITWISE::xtime(xs3, modpoly),         // {04} * s3
                xxxs3 = BITWISE::xtime(xxs3, modpoly);       // {08} * s3

            // sp0 = ({0e} * s0) XOR ({0b} * s1) XOR ({0d} * s2) XOR ({09} * s3)
            const VAR sp0 =
                BITWISE::XOR(
                    BITWISE::XOR(xs0, BITWISE::XOR(xxs0, xxxs0)),
                    BITWISE::XOR(
                        BITWISE::XOR(state[i + 1], BITWISE::XOR(xs1, xxxs1)),
                        BITWISE::XOR(
                            BITWISE::XOR(state[i + 2], BITWISE::XOR(xxs2, xxxs2)),
                            BITWISE::XOR(state[i + 3], xxxs3))));

            // sp1 = ({09} * s0) XOR ({0e} * s1) XOR ({0b} * s2) XOR ({0d} * s3)
            const VAR sp1 =
                BITWISE::XOR(
                    BITWISE::XOR(state[i], xxxs0),
                    BITWISE::XOR(
                        BITWISE::XOR(xs1, BITWISE::XOR(xxs1, xxxs1)),
                        BITWISE::XOR(
                            BITWISE::XOR(state[i + 2], BITWISE::XOR(xs2, xxxs2)),
                            BITWISE::XOR(state[i + 3], BITWISE::XOR(xxs3, xxxs3)))));

            // sp2 = ({0d} * s0) XOR ({09} * s1) XOR ({0e} * s2) XOR ({0b} * s3)
            const VAR sp2 =
                BITWISE::XOR(
                    BITWISE::XOR(state[i], BITWISE::XOR(xxs0, xxxs0)),
                    BITWISE::XOR(
                        BITWISE::XOR(state[i + 1], xxxs1),
                        BITWISE::XOR(
                            BITWISE::XOR(xs2, BITWISE::XOR(xxs2, xxxs2)),
                            BITWISE::XOR(state[i + 3], BITWISE::XOR(xs3, xxxs3)))));

            // sp3 = ({0b} * s0) XOR ({0d} * s1) XOR ({09} * s2) XOR ({0e} * s3)
            const VAR sp3 =
                BITWISE::XOR(
                    BITWISE::XOR(state[i], BITWISE::XOR(xs0, xxxs0)),
                    BITWISE::XOR(
                        BITWISE::XOR(state[i + 1], BITWISE::XOR(xxs1, xxxs1)),
                        BITWISE::XOR(
                            BITWISE::XOR(state[i + 2], xxxs2),
                            BITWISE::XOR(xs3, BITWISE::XOR(xxs3, xxxs3)))));

            state[i] = sp0;
            state[i + 1] = sp1;
            state[i + 2] = sp2;
            state[i + 3] = sp3;
        }
    }

    // 5.3.4 AddRoundKey() Transformation
    template <std::size_t N>
    void AddRoundKey(std::array<VAR, 16>& state,
                     const std::array<VAR, N>& w,
                     const std::size_t offset) const {
        for (std::size_t i = 0; i < 16; ++i)
            state[i] = BITWISE::XOR(state[i], w[i + offset]);
    }

    const AES_InvSBox<T, U, BITWISE> m_inv_sbox;
};

////////////////////////////////////////////////////////////////////////////////
// typedefs
//

namespace zk {
    template <typename FR> using
    AES_Decrypt = AES_InvCipher<AST_Var<Alg_uint8<FR>>,
                                AST_Node<Alg_uint8<FR>>,
                                AST_Op<Alg_uint8<FR>>,
                                BitwiseAST<Alg_uint8<FR>>>;
} // namespace zk

namespace eval {
    typedef AES_InvCipher<std::uint8_t,
                          std::uint8_t,
                          std::uint8_t,
                          BitwiseINT<std::uint8_t>>
        AES_Decrypt;
} // namespace eval

} // namespace snarkfront

#endif
<commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_AES_INV_CIPHER_HPP_
#define _SNARKFRONT_AES_INV_CIPHER_HPP_

#include <array>
#include <cstdint>

#include <snarkfront/AES_InvSBox.hpp>
#include <snarkfront/AES_KeyExpansion.hpp>

namespace snarkfront {

////////////////////////////////////////////////////////////////////////////////
// FIPS PUB 197, NIST November 2001
//
// Algorithm     Key Length    Block Size   Number of Rounds
//               (Nk words)    (Nb words)   (Nr)
//
// AES-128       4             4            10
// AES-192       6             4            12
// AES-256       8             4            14
//

////////////////////////////////////////////////////////////////////////////////
// 5.3 Inverse Cipher
//

template <typename VAR, typename T, typename U, typename BITWISE>
class AES_InvCipher
{
public:
    typedef VAR VarType;
    typedef std::array<VAR, 16> BlockType;
    typedef AES_KeyExpansion<VAR, T, U, BITWISE> KeyExpansion;

    AES_InvCipher() = default;

    // AES-128
    void operator() (const std::array<VAR, 16>& in,
                     std::array<VAR, 16>& out,
                     const std::array<VAR, 176>& w) const {
        decrypt(in, out, w);
    }

    // AES-192
    void operator() (const std::array<VAR, 16>& in,
                     std::array<VAR, 16>& out,
                     const std::array<VAR, 208>& w) const {
        decrypt(in, out, w);
    }

    // AES-256
    void operator() (const std::array<VAR, 16>& in,
                     std::array<VAR, 16>& out,
                     const std::array<VAR, 240>& w) const {
        decrypt(in, out, w);
    }

private:
    // AES-128 key schedule size 176 (Nr = 10)
    // AES-192 key schedule size 208 (Nr = 12)
    // AES-256 key schedule size 240 (Nr = 14)
    template <std::size_t WSZ>
    void decrypt(const std::array<VAR, 16>& in,
                 std::array<VAR, 16>& out,
                 const std::array<VAR, WSZ>& w) const // 16 * (Nr + 1) octets
    {
        const auto Nr = w.size() / 16 - 1;

        auto state = in;

        AddRoundKey(state, w, 16*Nr);

        for (std::size_t round = Nr - 1; round > 0; --round) {
            InvShiftRows(state);
            InvSubBytes(state);
            AddRoundKey(state, w, 16*round);
            InvMixColumns(state);
        }

        InvShiftRows(state);
        InvSubBytes(state);
        AddRoundKey(state, w, 0);

        out = state;
    }

    // 5.3.1 InvShiftRows() Transformation
    void InvShiftRows(std::array<VAR, 16>& state) const {
        VAR tmp;

        // second row rotate right by one element
        tmp = state[13];
        state[13] = state[9];
        state[9] = state[5];
        state[5] = state[1];
        state[1] = tmp;

        // third row rotate right by two elements
        tmp = state[14];
        state[14] = state[6];
        state[6] = tmp;
        tmp = state[10];
        state[10] = state[2];
        state[2] = tmp;

        // fourth row rotate right by three elements
        tmp = state[15];
        state[15] = state[3];
        state[3] = state[7];
        state[7] = state[11];
        state[11] = tmp;
    }

    // 5.3.2 InvSubBytes() Transformation
    void InvSubBytes(std::array<VAR, 16>& state) const {
        for (auto& a : state)
            a = m_inv_sbox(a);
    }

    // 5.3.3 InvMixColumns() Transformation
    void InvMixColumns(std::array<VAR, 16>& state) const {
        // irreducible polynomial for AES
        const auto modpoly = BITWISE::constant(0x1b);

        for (std::size_t i = 0; i < 16; i += 4) {
            const VAR
                xs0 = BITWISE::xtime(state[i], modpoly), // {02} * s0
                xxs0 = BITWISE::xtime(xs0, modpoly),     // {04} * s0
                xxxs0 = BITWISE::xtime(xxs0, modpoly);   // {08} * s0

            const VAR
                xs1 = BITWISE::xtime(state[i + 1], modpoly), // {02} * s1
                xxs1 = BITWISE::xtime(xs1, modpoly),         // {04} * s1
                xxxs1 = BITWISE::xtime(xxs1, modpoly);       // {08} * s1

            const VAR
                xs2 = BITWISE::xtime(state[i + 2], modpoly), // {02} * s2
                xxs2 = BITWISE::xtime(xs2, modpoly),         // {04} * s2
                xxxs2 = BITWISE::xtime(xxs2, modpoly);       // {08} * s2

            const VAR
                xs3 = BITWISE::xtime(state[i + 3], modpoly), // {02} * s3
                xxs3 = BITWISE::xtime(xs3, modpoly),         // {04} * s3
                xxxs3 = BITWISE::xtime(xxs3, modpoly);       // {08} * s3

            // sp0 = ({0e} * s0) XOR ({0b} * s1) XOR ({0d} * s2) XOR ({09} * s3)
            const VAR sp0 =
                BITWISE::XOR(
                    BITWISE::XOR(xs0, BITWISE::XOR(xxs0, xxxs0)),
                    BITWISE::XOR(
                        BITWISE::XOR(state[i + 1], BITWISE::XOR(xs1, xxxs1)),
                        BITWISE::XOR(
                            BITWISE::XOR(state[i + 2], BITWISE::XOR(xxs2, xxxs2)),
                            BITWISE::XOR(state[i + 3], xxxs3))));

            // sp1 = ({09} * s0) XOR ({0e} * s1) XOR ({0b} * s2) XOR ({0d} * s3)
            const VAR sp1 =
                BITWISE::XOR(
                    BITWISE::XOR(state[i], xxxs0),
                    BITWISE::XOR(
                        BITWISE::XOR(xs1, BITWISE::XOR(xxs1, xxxs1)),
                        BITWISE::XOR(
                            BITWISE::XOR(state[i + 2], BITWISE::XOR(xs2, xxxs2)),
                            BITWISE::XOR(state[i + 3], BITWISE::XOR(xxs3, xxxs3)))));

            // sp2 = ({0d} * s0) XOR ({09} * s1) XOR ({0e} * s2) XOR ({0b} * s3)
            const VAR sp2 =
                BITWISE::XOR(
                    BITWISE::XOR(state[i], BITWISE::XOR(xxs0, xxxs0)),
                    BITWISE::XOR(
                        BITWISE::XOR(state[i + 1], xxxs1),
                        BITWISE::XOR(
                            BITWISE::XOR(xs2, BITWISE::XOR(xxs2, xxxs2)),
                            BITWISE::XOR(state[i + 3], BITWISE::XOR(xs3, xxxs3)))));

            // sp3 = ({0b} * s0) XOR ({0d} * s1) XOR ({09} * s2) XOR ({0e} * s3)
            const VAR sp3 =
                BITWISE::XOR(
                    BITWISE::XOR(state[i], BITWISE::XOR(xs0, xxxs0)),
                    BITWISE::XOR(
                        BITWISE::XOR(state[i + 1], BITWISE::XOR(xxs1, xxxs1)),
                        BITWISE::XOR(
                            BITWISE::XOR(state[i + 2], xxxs2),
                            BITWISE::XOR(xs3, BITWISE::XOR(xxs3, xxxs3)))));

            state[i] = sp0;
            state[i + 1] = sp1;
            state[i + 2] = sp2;
            state[i + 3] = sp3;
        }
    }

    // 5.3.4 AddRoundKey() Transformation
    template <std::size_t N>
    void AddRoundKey(std::array<VAR, 16>& state,
                     const std::array<VAR, N>& w,
                     const std::size_t offset) const {
        for (std::size_t i = 0; i < 16; ++i)
            state[i] = BITWISE::XOR(state[i], w[i + offset]);
    }

    const AES_InvSBox<T, U, BITWISE> m_inv_sbox;
};

////////////////////////////////////////////////////////////////////////////////
// typedefs
//

namespace zk {
    template <typename FR> using
    AES_Decrypt = AES_InvCipher<AST_Var<Alg_uint8<FR>>,
                                AST_Node<Alg_uint8<FR>>,
                                AST_Op<Alg_uint8<FR>>,
                                BitwiseAST<Alg_uint8<FR>>>;
} // namespace zk

namespace eval {
    typedef AES_InvCipher<std::uint8_t,
                          std::uint8_t,
                          std::uint8_t,
                          BitwiseINT<std::uint8_t>>
        AES_Decrypt;
} // namespace eval

} // namespace snarkfront

#endif
<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// 	Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev
//
// 	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.

#include "Tests.h"
#include <UnitTest++.h>
#include <MTScheduler.h>

SUITE(StackSizeTests)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct StandartStackSizeTask
{
	MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::Color::Blue);

	void Do(MT::FiberContext&)
	{
		byte stackData[28000];
		memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData));
	}
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct ExtendedStackSizeTask
{
	MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::Color::Red);

	void Do(MT::FiberContext&)
	{
		byte stackData[262144];
		memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData));
	}

};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunStandartTasks)
{
	MT::TaskScheduler scheduler;

	StandartStackSizeTask tasks[100];
	scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks));
	CHECK(scheduler.WaitAll(1000));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunExtendedTasks)
{
	MT::TaskScheduler scheduler;

	ExtendedStackSizeTask tasks[100];
	scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks));
	CHECK(scheduler.WaitAll(1000));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunMixedTasks)
{
	MT::TaskScheduler scheduler;

	MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool;
	MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool;

	MT::TaskHandle taskHandles[100];
	for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i)
	{
		MT::TaskHandle handle;

		if (i & 1)
		{
			handle = extendedTaskPool.Alloc(ExtendedStackSizeTask());
		} else
		{
			handle = standardTaskPool.Alloc(StandartStackSizeTask());
		}
		taskHandles[i] = handle;
	}

	scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles));
	CHECK(scheduler.WaitAll(1000));
}

}
<commit_msg>Fix OSX test<commit_after>// The MIT License (MIT)
//
// 	Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev
//
// 	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.

#include "Tests.h"
#include <UnitTest++.h>
#include <MTScheduler.h>

SUITE(StackSizeTests)
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct StandartStackSizeTask
{
	MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::Color::Blue);

	void Do(MT::FiberContext&)
	{
		byte stackData[26000];
		memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData));
	}
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct ExtendedStackSizeTask
{
	MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::Color::Red);

	void Do(MT::FiberContext&)
	{
		byte stackData[262144];
		memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData));
	}

};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunStandartTasks)
{
	MT::TaskScheduler scheduler;

	StandartStackSizeTask tasks[100];
	scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks));
	CHECK(scheduler.WaitAll(1000));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunExtendedTasks)
{
	MT::TaskScheduler scheduler;

	ExtendedStackSizeTask tasks[100];
	scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks));
	CHECK(scheduler.WaitAll(1000));
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TEST(RunMixedTasks)
{
	MT::TaskScheduler scheduler;

	MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool;
	MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool;

	MT::TaskHandle taskHandles[100];
	for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i)
	{
		MT::TaskHandle handle;

		if (i & 1)
		{
			handle = extendedTaskPool.Alloc(ExtendedStackSizeTask());
		} else
		{
			handle = standardTaskPool.Alloc(StandartStackSizeTask());
		}
		taskHandles[i] = handle;
	}

	scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles));
	CHECK(scheduler.WaitAll(1000));
}

}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2014 by Marcin Ziemiński <zieminn@gmail.com>            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2.1 of the License, or   *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "proxy-service-adaptee.h"
#include "proxy-service.h"
#include "otr-constants.h"

#include <TelepathyQt/DBusObject>

ProxyServiceAdaptee::ProxyServiceAdaptee(ProxyService *ps, const QDBusConnection &dbusConnection)
    : adaptor(new Tp::Service::ProxyServiceAdaptor(dbusConnection, this, ps->dbusObject())),
    ps(ps)
{
    connect(ps, SIGNAL(keyGenerationStarted(const QString&)), SLOT(onKeyGenerationStarted(const QString&)));
    connect(ps, SIGNAL(keyGenerationFinished(const QString&, bool)), SLOT(onKeyGenerationFinished(const QString&, bool)));
}

ProxyServiceAdaptee::~ProxyServiceAdaptee() { }

uint ProxyServiceAdaptee::policy() const
{
    switch(ps->getPolicy()) {
        case OTRL_POLICY_ALWAYS:
            return 0;
        case OTRL_POLICY_OPPORTUNISTIC:
            return 1;
        case OTRL_POLICY_MANUAL:
            return 2;
        case OTRL_POLICY_NEVER:
        default:
            return 3;
    }
}

void ProxyServiceAdaptee::setPolicy(uint otrPolicy)
{
    switch(otrPolicy) {
        case 0:
            ps->setPolicy(OTRL_POLICY_ALWAYS);
        case 1:
            ps->setPolicy(OTRL_POLICY_OPPORTUNISTIC);
        case 2:
            ps->setPolicy(OTRL_POLICY_MANUAL);
        case 3:
            ps->setPolicy(OTRL_POLICY_NEVER);
        default:
            // nos uch policy
            return;
    }
}

void ProxyServiceAdaptee::onProxyConnected(const QDBusObjectPath &proxyPath)
{
    Q_EMIT proxyConnected(proxyPath);
}
void ProxyServiceAdaptee::onProxyDisconnected(const QDBusObjectPath &proxyPath)
{
    Q_EMIT proxyDisconnected(proxyPath);
}

void ProxyServiceAdaptee::onKeyGenerationStarted(const QString &accountId)
{
    Q_EMIT(keyGenerationStarted(OTR::utils::objectPathFor(accountId)));
}

void ProxyServiceAdaptee::onKeyGenerationFinished(const QString &accountId, bool error)
{
    Q_EMIT(keyGenerationFinished(OTR::utils::objectPathFor(accountId), error));
}

void ProxyServiceAdaptee::generatePrivateKey(const QDBusObjectPath &accountPath,
        const Tp::Service::ProxyServiceAdaptor::GeneratePrivateKeyContextPtr &context)
{
    Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path());
    if(ac && ac->isValidAccount() &&
            ps->createNewPrivateKey(OTR::utils::accountIdFor(accountPath), ac->normalizedName())) {
        context->setFinished();
    } else {
        // TODO better errors
        context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT,
                QLatin1String("Could not generate private key for given account"));
    }
}

void ProxyServiceAdaptee::getFingerprintForAccount(QDBusObjectPath accountPath,
        const Tp::Service::ProxyServiceAdaptor::GetFingerprintForAccountContextPtr &context)
{
    Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path());
    if(ac && ac->isValidAccount()) {
        context->setFinished(ps->getFingerprintFor(OTR::utils::accountIdFor(accountPath), ac->normalizedName()));
    } else {
        context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT, QLatin1String("No such valid account"));
    }
}
<commit_msg>Fixed policy settings bug.<commit_after>/***************************************************************************
 *   Copyright (C) 2014 by Marcin Ziemiński <zieminn@gmail.com>            *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2.1 of the License, or   *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "proxy-service-adaptee.h"
#include "proxy-service.h"
#include "otr-constants.h"

#include <TelepathyQt/DBusObject>

ProxyServiceAdaptee::ProxyServiceAdaptee(ProxyService *ps, const QDBusConnection &dbusConnection)
    : adaptor(new Tp::Service::ProxyServiceAdaptor(dbusConnection, this, ps->dbusObject())),
    ps(ps)
{
    connect(ps, SIGNAL(keyGenerationStarted(const QString&)), SLOT(onKeyGenerationStarted(const QString&)));
    connect(ps, SIGNAL(keyGenerationFinished(const QString&, bool)), SLOT(onKeyGenerationFinished(const QString&, bool)));
}

ProxyServiceAdaptee::~ProxyServiceAdaptee() { }

uint ProxyServiceAdaptee::policy() const
{
    switch(ps->getPolicy()) {
        case OTRL_POLICY_ALWAYS:
            return 0;
        case OTRL_POLICY_OPPORTUNISTIC:
            return 1;
        case OTRL_POLICY_MANUAL:
            return 2;
        case OTRL_POLICY_NEVER:
        default:
            return 3;
    }
}

void ProxyServiceAdaptee::setPolicy(uint otrPolicy)
{
    switch(otrPolicy) {
        case 0:
            ps->setPolicy(OTRL_POLICY_ALWAYS);
            return;
        case 1:
            ps->setPolicy(OTRL_POLICY_OPPORTUNISTIC);
            return;
        case 2:
            ps->setPolicy(OTRL_POLICY_MANUAL);
            return;
        case 3:
            ps->setPolicy(OTRL_POLICY_NEVER);
            return;
        default:
            // nos uch policy
            return;
    }
}

void ProxyServiceAdaptee::onProxyConnected(const QDBusObjectPath &proxyPath)
{
    Q_EMIT proxyConnected(proxyPath);
}
void ProxyServiceAdaptee::onProxyDisconnected(const QDBusObjectPath &proxyPath)
{
    Q_EMIT proxyDisconnected(proxyPath);
}

void ProxyServiceAdaptee::onKeyGenerationStarted(const QString &accountId)
{
    Q_EMIT(keyGenerationStarted(OTR::utils::objectPathFor(accountId)));
}

void ProxyServiceAdaptee::onKeyGenerationFinished(const QString &accountId, bool error)
{
    Q_EMIT(keyGenerationFinished(OTR::utils::objectPathFor(accountId), error));
}

void ProxyServiceAdaptee::generatePrivateKey(const QDBusObjectPath &accountPath,
        const Tp::Service::ProxyServiceAdaptor::GeneratePrivateKeyContextPtr &context)
{
    Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path());
    if(ac && ac->isValidAccount() &&
            ps->createNewPrivateKey(OTR::utils::accountIdFor(accountPath), ac->normalizedName())) {
        context->setFinished();
    } else {
        // TODO better errors
        context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT,
                QLatin1String("Could not generate private key for given account"));
    }
}

void ProxyServiceAdaptee::getFingerprintForAccount(QDBusObjectPath accountPath,
        const Tp::Service::ProxyServiceAdaptor::GetFingerprintForAccountContextPtr &context)
{
    Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path());
    if(ac && ac->isValidAccount()) {
        context->setFinished(ps->getFingerprintFor(OTR::utils::accountIdFor(accountPath), ac->normalizedName()));
    } else {
        context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT, QLatin1String("No such valid account"));
    }
}
<|endoftext|>


<commit_before><commit_msg>fix of parsing<commit_after><|endoftext|>


<commit_before><commit_msg>Set VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT on secondary begin<commit_after><|endoftext|>


<commit_before>
#include "../../Flare.h"
#include "FlareMainMenu.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareSaveGame.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"

#define LOCTEXT_NAMESPACE "FlareMainMenu"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareMainMenu::Construct(const FArguments& InArgs)
{
	// Data
	MenuManager = InArgs._MenuManager;
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	AFlarePlayerController* PC = MenuManager->GetPC();
	SaveSlotCount = 3;
	Initialized = false;

	// Build structure
	ChildSlot
	.HAlign(HAlign_Fill)
	.VAlign(VAlign_Fill)
	[
		SNew(SVerticalBox)

		+ SVerticalBox::Slot()
		.AutoHeight()
		.HAlign(HAlign_Fill)
		.VAlign(VAlign_Center)
		.Padding(Theme.ContentPadding)
		[
			SNew(SHorizontalBox)

			// Icon
			+ SHorizontalBox::Slot()
			.AutoWidth()
			[
				SNew(SImage)
				.Image(FFlareStyleSet::GetIcon("HeliumRain"))
			]

			// Title
			+ SHorizontalBox::Slot()
			.VAlign(VAlign_Center)
			.Padding(Theme.ContentPadding)
			[
				SNew(STextBlock)
				.TextStyle(&Theme.TitleFont)
				.Text(LOCTEXT("MainMenu", "HELIUM RAIN"))
			]

			// Settings
			+ SHorizontalBox::Slot()
			.HAlign(HAlign_Right)
			.VAlign(VAlign_Bottom)
			.Padding(Theme.TitleButtonPadding)
			.AutoWidth()
			[
				SNew(SFlareRoundButton)
				.Text(LOCTEXT("Settings", "Settings"))
				.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Settings, true))
				.OnClicked(this, &SFlareMainMenu::OnOpenSettings)
			]

			// Quit
			+ SHorizontalBox::Slot()
			.HAlign(HAlign_Right)
			.VAlign(VAlign_Bottom)
			.Padding(Theme.TitleButtonPadding)
			.AutoWidth()
			[
				SNew(SFlareRoundButton)
				.Text(LOCTEXT("Quit", "Quit game"))
				.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Quit, true))
				.OnClicked(this, &SFlareMainMenu::OnQuitGame)
			]
		]

		// Separator
		+ SVerticalBox::Slot()
		.AutoHeight()
		.Padding(FMargin(200, 40))
		[
			SNew(SImage).Image(&Theme.SeparatorBrush)
		]

		// Save slots
		+ SVerticalBox::Slot()
		[
			SAssignNew(SaveBox, SHorizontalBox)
		]
	];

	// Add save slots
	for (int32 Index = 1; Index <= SaveSlotCount; Index++)
	{
		TSharedPtr<int32> IndexPtr(new int32(Index));

		SaveBox->AddSlot()
		.HAlign(HAlign_Center)
		.VAlign(VAlign_Top)
		[
			SNew(SVerticalBox)

			// Slot N
			+ SVerticalBox::Slot()
			.AutoHeight()
			.Padding(Theme.TitlePadding)
			[
				SNew(STextBlock)
				.TextStyle(&Theme.TitleFont)
				.Text(FText::FromString(FString::FromInt(Index) + "/"))
			]

			// Company emblem
			+ SVerticalBox::Slot()
			.AutoHeight()
			.Padding(Theme.ContentPadding)
			[
				SNew(SHorizontalBox)
				+ SHorizontalBox::Slot()
				.HAlign(HAlign_Center)
				[
					SNew(SImage)
					.Image(this, &SFlareMainMenu::GetSaveIcon, Index)
				]
			]

			// Description
			+ SVerticalBox::Slot()
			.AutoHeight()
			[
				SNew(STextBlock)
				.TextStyle(&Theme.TextFont)
				.Text(this, &SFlareMainMenu::GetText, Index)
			]

			// Launch
			+ SVerticalBox::Slot()
			.HAlign(HAlign_Left)
			.VAlign(VAlign_Center)
			.AutoHeight()
			.Padding(Theme.SmallContentPadding)
			[
				SNew(SFlareButton)
				.Text(this, &SFlareMainMenu::GetButtonText, Index)
				.Icon(this, &SFlareMainMenu::GetButtonIcon, Index)
				.OnClicked(this, &SFlareMainMenu::OnOpenSlot, IndexPtr)
				.Width(5)
				.Height(1)
			]

			// Delete
			+ SVerticalBox::Slot()
			.HAlign(HAlign_Left)
			.VAlign(VAlign_Center)
			.AutoHeight()
			.Padding(Theme.SmallContentPadding)
			[
				SNew(SFlareButton)
				.Text(LOCTEXT("Delete", "Delete game"))
				.Icon(FFlareStyleSet::GetIcon("Delete"))
				.OnClicked(this, &SFlareMainMenu::OnDeleteSlot, IndexPtr)
				.Width(5)
				.Height(1)
				.Visibility(this, &SFlareMainMenu::GetDeleteButtonVisibility, Index)
			]
		];
	}
}

/*----------------------------------------------------
	Interaction
----------------------------------------------------*/

void SFlareMainMenu::Setup()
{
	SetEnabled(false);
	SetVisibility(EVisibility::Hidden);
}

void SFlareMainMenu::Enter()
{
	FLOG("SFlareMainMenu::Enter");
	UpdateSaveSlots();
	SetEnabled(true);
	SetVisibility(EVisibility::Visible);
}

void SFlareMainMenu::Exit()
{
	SetEnabled(false);
	Initialized = false;

	SaveSlots.Empty();

	SetVisibility(EVisibility::Hidden);
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

FText SFlareMainMenu::GetText(int32 Index) const
{
	if (IsExistingGame(Index - 1))
	{
		const FFlareSaveSlotInfo& SaveSlotInfo = SaveSlots[Index - 1];

		FString CompanyString = SaveSlotInfo.CompanyName.ToString();
		FString ShipString = FString::FromInt(SaveSlotInfo.CompanyShipCount) + " " + LOCTEXT("Ships", "ships").ToString();
		FString MoneyString = FString::FromInt(SaveSlotInfo.CompanyMoney) + " " + LOCTEXT("Credits", "credits").ToString();

		return FText::FromString(CompanyString + "\n" + ShipString + "\n" + MoneyString + "\n");
	}
	else
	{
		return FText::FromString("\n\n\n");
	}
}

const FSlateBrush* SFlareMainMenu::GetSaveIcon(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? &SaveSlots[Index - 1].EmblemBrush : FFlareStyleSet::GetIcon("HeliumRain"));
}

EVisibility SFlareMainMenu::GetDeleteButtonVisibility(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? EVisibility::Visible : EVisibility::Collapsed);
}

FText SFlareMainMenu::GetButtonText(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? LOCTEXT("Load", "Load game") : LOCTEXT("Create", "New game"));
}

const FSlateBrush* SFlareMainMenu::GetButtonIcon(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? FFlareStyleSet::GetIcon("Load") : FFlareStyleSet::GetIcon("New"));
}

void SFlareMainMenu::OnOpenSlot(TSharedPtr<int32> Index)
{
	AFlarePlayerController* PC = MenuManager->GetPC();
	AFlareGame* Game = MenuManager->GetGame();

	if (PC && Game)
	{
		// Load the world
		bool WorldLoaded = Game->LoadWorld(PC, *Index);
		if (!WorldLoaded)
		{
			Game->CreateWorld(PC);
		}

		// Go to the ship
		MenuManager->OpenMenu(EFlareMenu::MENU_FlyShip, PC->GetShipPawn());
	}
}

void SFlareMainMenu::OnDeleteSlot(TSharedPtr<int32> Index)
{
	AFlareGame::DeleteSaveFile(*Index);
	UpdateSaveSlots();
}

void SFlareMainMenu::OnOpenSettings()
{
	MenuManager->OpenMenu(EFlareMenu::MENU_Settings);
}

void SFlareMainMenu::OnQuitGame()
{
	MenuManager->OpenMenu(EFlareMenu::MENU_Quit);
}

/*----------------------------------------------------
	Helpers
----------------------------------------------------*/

void SFlareMainMenu::UpdateSaveSlots()
{
	// Setup
	SaveSlots.Empty();
	FVector2D EmblemSize = 128 * FVector2D::UnitVector;
	UMaterial* BaseEmblemMaterial = Cast<UMaterial>(FFlareStyleSet::GetIcon("CompanyEmblem")->GetResourceObject());

	// Get all saves
	for (int32 Index = 1; Index <= SaveSlotCount; Index++)
	{
		FFlareSaveSlotInfo SaveSlotInfo;
		SaveSlotInfo.EmblemBrush.ImageSize = EmblemSize;
		UFlareSaveGame* Save = AFlareGame::LoadSaveFile(Index);
		SaveSlotInfo.Save = Save;

		if (Save)
		{
			// Basic setup
			AFlareGame* Game = MenuManager->GetPC()->GetGame();
			FFlareCompanySave& Company = Save->CompanyData[0];
			UFlareCustomizationCatalog* Catalog = Game->GetCustomizationCatalog();
			SaveSlotInfo.CompanyName = LOCTEXT("Company", "Mining Syndicate");
			FLOGV("SFlareMainMenu::UpdateSaveSlots : found valid save data in slot %d", Index);

			// Count player ships
			SaveSlotInfo.CompanyShipCount = 0;
			for (int32 Index = 0; Index < Save->ShipData.Num(); Index++)
			{
				const FFlareSpacecraftSave& Spacecraft = Save->ShipData[Index];

				if (Spacecraft.CompanyIdentifier == Save->PlayerData.CompanyIdentifier)
				{
					SaveSlotInfo.CompanyShipCount++;
				}
			}

			// Money
			SaveSlotInfo.CompanyMoney = 50000;

			// Emblem material
			SaveSlotInfo.Emblem = UMaterialInstanceDynamic::Create(BaseEmblemMaterial, Game->GetWorld());
			SaveSlotInfo.Emblem->SetVectorParameterValue("BasePaintColor", Catalog->GetColor(Company.CustomizationBasePaintColorIndex));
			SaveSlotInfo.Emblem->SetVectorParameterValue("PaintColor", Catalog->GetColor(Company.CustomizationPaintColorIndex));
			SaveSlotInfo.Emblem->SetVectorParameterValue("OverlayColor", Catalog->GetColor(Company.CustomizationOverlayColorIndex));
			SaveSlotInfo.Emblem->SetVectorParameterValue("GlowColor", Catalog->GetColor(Company.CustomizationLightColorIndex));

			// Create the brush dynamically
			SaveSlotInfo.EmblemBrush.SetResourceObject(SaveSlotInfo.Emblem);
		}
		else
		{
			SaveSlotInfo.Save = NULL;
			SaveSlotInfo.Emblem = NULL;
			SaveSlotInfo.EmblemBrush = FSlateNoResource();
			SaveSlotInfo.CompanyShipCount = 0;
			SaveSlotInfo.CompanyMoney = 0;
			SaveSlotInfo.CompanyName = FText::FromString("");
		}

		SaveSlots.Add(SaveSlotInfo);
	}

	FLOG("SFlareMainMenu::UpdateSaveSlots : all slots found");
	Initialized = true;
}

bool SFlareMainMenu::IsExistingGame(int32 Index) const
{
	return Initialized && Index < SaveSlots.Num() && SaveSlots[Index].Save;
}

#undef LOCTEXT_NAMESPACE

<commit_msg>Fix shadow variable build error on Linux<commit_after>
#include "../../Flare.h"
#include "FlareMainMenu.h"
#include "../../Game/FlareGame.h"
#include "../../Game/FlareSaveGame.h"
#include "../../Player/FlareMenuPawn.h"
#include "../../Player/FlareMenuManager.h"
#include "../../Player/FlarePlayerController.h"

#define LOCTEXT_NAMESPACE "FlareMainMenu"

/*----------------------------------------------------
	Construct
----------------------------------------------------*/

void SFlareMainMenu::Construct(const FArguments& InArgs)
{
	// Data
	MenuManager = InArgs._MenuManager;
	const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
	AFlarePlayerController* PC = MenuManager->GetPC();
	SaveSlotCount = 3;
	Initialized = false;

	// Build structure
	ChildSlot
	.HAlign(HAlign_Fill)
	.VAlign(VAlign_Fill)
	[
		SNew(SVerticalBox)

		+ SVerticalBox::Slot()
		.AutoHeight()
		.HAlign(HAlign_Fill)
		.VAlign(VAlign_Center)
		.Padding(Theme.ContentPadding)
		[
			SNew(SHorizontalBox)

			// Icon
			+ SHorizontalBox::Slot()
			.AutoWidth()
			[
				SNew(SImage)
				.Image(FFlareStyleSet::GetIcon("HeliumRain"))
			]

			// Title
			+ SHorizontalBox::Slot()
			.VAlign(VAlign_Center)
			.Padding(Theme.ContentPadding)
			[
				SNew(STextBlock)
				.TextStyle(&Theme.TitleFont)
				.Text(LOCTEXT("MainMenu", "HELIUM RAIN"))
			]

			// Settings
			+ SHorizontalBox::Slot()
			.HAlign(HAlign_Right)
			.VAlign(VAlign_Bottom)
			.Padding(Theme.TitleButtonPadding)
			.AutoWidth()
			[
				SNew(SFlareRoundButton)
				.Text(LOCTEXT("Settings", "Settings"))
				.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Settings, true))
				.OnClicked(this, &SFlareMainMenu::OnOpenSettings)
			]

			// Quit
			+ SHorizontalBox::Slot()
			.HAlign(HAlign_Right)
			.VAlign(VAlign_Bottom)
			.Padding(Theme.TitleButtonPadding)
			.AutoWidth()
			[
				SNew(SFlareRoundButton)
				.Text(LOCTEXT("Quit", "Quit game"))
				.Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Quit, true))
				.OnClicked(this, &SFlareMainMenu::OnQuitGame)
			]
		]

		// Separator
		+ SVerticalBox::Slot()
		.AutoHeight()
		.Padding(FMargin(200, 40))
		[
			SNew(SImage).Image(&Theme.SeparatorBrush)
		]

		// Save slots
		+ SVerticalBox::Slot()
		[
			SAssignNew(SaveBox, SHorizontalBox)
		]
	];

	// Add save slots
	for (int32 Index = 1; Index <= SaveSlotCount; Index++)
	{
		TSharedPtr<int32> IndexPtr(new int32(Index));

		SaveBox->AddSlot()
		.HAlign(HAlign_Center)
		.VAlign(VAlign_Top)
		[
			SNew(SVerticalBox)

			// Slot N°
			+ SVerticalBox::Slot()
			.AutoHeight()
			.Padding(Theme.TitlePadding)
			[
				SNew(STextBlock)
				.TextStyle(&Theme.TitleFont)
				.Text(FText::FromString(FString::FromInt(Index) + "/"))
			]

			// Company emblem
			+ SVerticalBox::Slot()
			.AutoHeight()
			.Padding(Theme.ContentPadding)
			[
				SNew(SHorizontalBox)
				+ SHorizontalBox::Slot()
				.HAlign(HAlign_Center)
				[
					SNew(SImage)
					.Image(this, &SFlareMainMenu::GetSaveIcon, Index)
				]
			]

			// Description
			+ SVerticalBox::Slot()
			.AutoHeight()
			[
				SNew(STextBlock)
				.TextStyle(&Theme.TextFont)
				.Text(this, &SFlareMainMenu::GetText, Index)
			]

			// Launch
			+ SVerticalBox::Slot()
			.HAlign(HAlign_Left)
			.VAlign(VAlign_Center)
			.AutoHeight()
			.Padding(Theme.SmallContentPadding)
			[
				SNew(SFlareButton)
				.Text(this, &SFlareMainMenu::GetButtonText, Index)
				.Icon(this, &SFlareMainMenu::GetButtonIcon, Index)
				.OnClicked(this, &SFlareMainMenu::OnOpenSlot, IndexPtr)
				.Width(5)
				.Height(1)
			]

			// Delete
			+ SVerticalBox::Slot()
			.HAlign(HAlign_Left)
			.VAlign(VAlign_Center)
			.AutoHeight()
			.Padding(Theme.SmallContentPadding)
			[
				SNew(SFlareButton)
				.Text(LOCTEXT("Delete", "Delete game"))
				.Icon(FFlareStyleSet::GetIcon("Delete"))
				.OnClicked(this, &SFlareMainMenu::OnDeleteSlot, IndexPtr)
				.Width(5)
				.Height(1)
				.Visibility(this, &SFlareMainMenu::GetDeleteButtonVisibility, Index)
			]
		];
	}
}

/*----------------------------------------------------
	Interaction
----------------------------------------------------*/

void SFlareMainMenu::Setup()
{
	SetEnabled(false);
	SetVisibility(EVisibility::Hidden);
}

void SFlareMainMenu::Enter()
{
	FLOG("SFlareMainMenu::Enter");
	UpdateSaveSlots();
	SetEnabled(true);
	SetVisibility(EVisibility::Visible);
}

void SFlareMainMenu::Exit()
{
	SetEnabled(false);
	Initialized = false;

	SaveSlots.Empty();

	SetVisibility(EVisibility::Hidden);
}

/*----------------------------------------------------
	Callbacks
----------------------------------------------------*/

FText SFlareMainMenu::GetText(int32 Index) const
{
	if (IsExistingGame(Index - 1))
	{
		const FFlareSaveSlotInfo& SaveSlotInfo = SaveSlots[Index - 1];

		FString CompanyString = SaveSlotInfo.CompanyName.ToString();
		FString ShipString = FString::FromInt(SaveSlotInfo.CompanyShipCount) + " " + LOCTEXT("Ships", "ships").ToString();
		FString MoneyString = FString::FromInt(SaveSlotInfo.CompanyMoney) + " " + LOCTEXT("Credits", "credits").ToString();

		return FText::FromString(CompanyString + "\n" + ShipString + "\n" + MoneyString + "\n");
	}
	else
	{
		return FText::FromString("\n\n\n");
	}
}

const FSlateBrush* SFlareMainMenu::GetSaveIcon(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? &SaveSlots[Index - 1].EmblemBrush : FFlareStyleSet::GetIcon("HeliumRain"));
}

EVisibility SFlareMainMenu::GetDeleteButtonVisibility(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? EVisibility::Visible : EVisibility::Collapsed);
}

FText SFlareMainMenu::GetButtonText(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? LOCTEXT("Load", "Load game") : LOCTEXT("Create", "New game"));
}

const FSlateBrush* SFlareMainMenu::GetButtonIcon(int32 Index) const
{
	return (IsExistingGame(Index - 1) ? FFlareStyleSet::GetIcon("Load") : FFlareStyleSet::GetIcon("New"));
}

void SFlareMainMenu::OnOpenSlot(TSharedPtr<int32> Index)
{
	AFlarePlayerController* PC = MenuManager->GetPC();
	AFlareGame* Game = MenuManager->GetGame();

	if (PC && Game)
	{
		// Load the world
		bool WorldLoaded = Game->LoadWorld(PC, *Index);
		if (!WorldLoaded)
		{
			Game->CreateWorld(PC);
		}

		// Go to the ship
		MenuManager->OpenMenu(EFlareMenu::MENU_FlyShip, PC->GetShipPawn());
	}
}

void SFlareMainMenu::OnDeleteSlot(TSharedPtr<int32> Index)
{
	AFlareGame::DeleteSaveFile(*Index);
	UpdateSaveSlots();
}

void SFlareMainMenu::OnOpenSettings()
{
	MenuManager->OpenMenu(EFlareMenu::MENU_Settings);
}

void SFlareMainMenu::OnQuitGame()
{
	MenuManager->OpenMenu(EFlareMenu::MENU_Quit);
}

/*----------------------------------------------------
	Helpers
----------------------------------------------------*/

void SFlareMainMenu::UpdateSaveSlots()
{
	// Setup
	SaveSlots.Empty();
	FVector2D EmblemSize = 128 * FVector2D::UnitVector;
	UMaterial* BaseEmblemMaterial = Cast<UMaterial>(FFlareStyleSet::GetIcon("CompanyEmblem")->GetResourceObject());

	// Get all saves
	for (int32 Index = 1; Index <= SaveSlotCount; Index++)
	{
		FFlareSaveSlotInfo SaveSlotInfo;
		SaveSlotInfo.EmblemBrush.ImageSize = EmblemSize;
		UFlareSaveGame* Save = AFlareGame::LoadSaveFile(Index);
		SaveSlotInfo.Save = Save;

		if (Save)
		{
			// Basic setup
			AFlareGame* Game = MenuManager->GetPC()->GetGame();
			FFlareCompanySave& Company = Save->CompanyData[0];
			UFlareCustomizationCatalog* Catalog = Game->GetCustomizationCatalog();
			SaveSlotInfo.CompanyName = LOCTEXT("Company", "Mining Syndicate");
			FLOGV("SFlareMainMenu::UpdateSaveSlots : found valid save data in slot %d", Index);

			// Count player ships
			SaveSlotInfo.CompanyShipCount = 0;
			for (int32 ShipIndex = 0; ShipIndex < Save->ShipData.Num(); ShipIndex++)
			{
				const FFlareSpacecraftSave& Spacecraft = Save->ShipData[ShipIndex];

				if (Spacecraft.CompanyIdentifier == Save->PlayerData.CompanyIdentifier)
				{
					SaveSlotInfo.CompanyShipCount++;
				}
			}

			// Money
			SaveSlotInfo.CompanyMoney = 50000;

			// Emblem material
			SaveSlotInfo.Emblem = UMaterialInstanceDynamic::Create(BaseEmblemMaterial, Game->GetWorld());
			SaveSlotInfo.Emblem->SetVectorParameterValue("BasePaintColor", Catalog->GetColor(Company.CustomizationBasePaintColorIndex));
			SaveSlotInfo.Emblem->SetVectorParameterValue("PaintColor", Catalog->GetColor(Company.CustomizationPaintColorIndex));
			SaveSlotInfo.Emblem->SetVectorParameterValue("OverlayColor", Catalog->GetColor(Company.CustomizationOverlayColorIndex));
			SaveSlotInfo.Emblem->SetVectorParameterValue("GlowColor", Catalog->GetColor(Company.CustomizationLightColorIndex));

			// Create the brush dynamically
			SaveSlotInfo.EmblemBrush.SetResourceObject(SaveSlotInfo.Emblem);
		}
		else
		{
			SaveSlotInfo.Save = NULL;
			SaveSlotInfo.Emblem = NULL;
			SaveSlotInfo.EmblemBrush = FSlateNoResource();
			SaveSlotInfo.CompanyShipCount = 0;
			SaveSlotInfo.CompanyMoney = 0;
			SaveSlotInfo.CompanyName = FText::FromString("");
		}

		SaveSlots.Add(SaveSlotInfo);
	}

	FLOG("SFlareMainMenu::UpdateSaveSlots : all slots found");
	Initialized = true;
}

bool SFlareMainMenu::IsExistingGame(int32 Index) const
{
	return Initialized && Index < SaveSlots.Num() && SaveSlots[Index].Save;
}

#undef LOCTEXT_NAMESPACE

<|endoftext|>


<commit_before>//===- llvm/unittest/ADT/SmallVectorMap.cpp ---------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// SmallVector unit tests.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/ADT/SmallVector.h"
#include <stdarg.h>

using namespace llvm;

namespace {

/// A helper class that counts the total number of constructor and
/// destructor calls.
class Constructable {
private:
  static int numConstructorCalls;
  static int numDestructorCalls;
  static int numAssignmentCalls;

  int value;

public:
  Constructable() : value(0) {
    ++numConstructorCalls;
  }

  Constructable(int val) : value(val) {
    ++numConstructorCalls;
  }

  Constructable(const Constructable & src) {
    value = src.value;
    ++numConstructorCalls;
  }

  ~Constructable() {
    ++numDestructorCalls;
  }

  Constructable & operator=(const Constructable & src) {
    value = src.value;
    ++numAssignmentCalls;
    return *this;
  }

  int getValue() const {
    return abs(value);
  }

  static void reset() {
    numConstructorCalls = 0;
    numDestructorCalls = 0;
    numAssignmentCalls = 0;
  }

  static int getNumConstructorCalls() {
    return numConstructorCalls;
  }

  static int getNumDestructorCalls() {
    return numDestructorCalls;
  }

  friend bool operator==(const Constructable & c0, const Constructable & c1) {
    return c0.getValue() == c1.getValue();
  }

  friend bool operator!=(const Constructable & c0, const Constructable & c1) {
    return c0.getValue() != c1.getValue();
  }
};

int Constructable::numConstructorCalls;
int Constructable::numDestructorCalls;
int Constructable::numAssignmentCalls;

// Test fixture class
class SmallVectorTest : public testing::Test {
protected:
  typedef SmallVector<Constructable, 4> VectorType;

  VectorType theVector;
  VectorType otherVector;

  void SetUp() {
    Constructable::reset();
  }

  void assertEmpty(VectorType & v) {
    // Size tests
    EXPECT_EQ(0u, v.size());
    EXPECT_TRUE(v.empty());

    // Iterator tests
    EXPECT_TRUE(v.begin() == v.end());
  }

  // Assert that theVector contains the specified values, in order.
  void assertValuesInOrder(VectorType & v, size_t size, ...) {
    EXPECT_EQ(size, v.size());

    va_list ap;
    va_start(ap, size);
    for (size_t i = 0; i < size; ++i) {
      int value = va_arg(ap, int);
      EXPECT_EQ(value, v[i].getValue());
    }

    va_end(ap);
  }

  // Generate a sequence of values to initialize the vector.
  void makeSequence(VectorType & v, int start, int end) {
    for (int i = start; i <= end; ++i) {
      v.push_back(Constructable(i));
    }
  }
};

// New vector test.
TEST_F(SmallVectorTest, EmptyVectorTest) {
  SCOPED_TRACE("EmptyVectorTest");
  assertEmpty(theVector);
  EXPECT_TRUE(theVector.rbegin() == theVector.rend());
  EXPECT_EQ(0, Constructable::getNumConstructorCalls());
  EXPECT_EQ(0, Constructable::getNumDestructorCalls());
}

// Simple insertions and deletions.
TEST_F(SmallVectorTest, PushPopTest) {
  SCOPED_TRACE("PushPopTest");

  // Push an element
  theVector.push_back(Constructable(1));

  // Size tests
  assertValuesInOrder(theVector, 1u, 1);
  EXPECT_FALSE(theVector.begin() == theVector.end());
  EXPECT_FALSE(theVector.empty());

  // Push another element
  theVector.push_back(Constructable(2));
  assertValuesInOrder(theVector, 2u, 1, 2);

  // Pop one element
  theVector.pop_back();
  assertValuesInOrder(theVector, 1u, 1);

  // Pop another element
  theVector.pop_back();
  assertEmpty(theVector);

  // Check number of constructor calls. Should be 2 for each list element,
  // one for the argument to push_back, and one for the list element itself.
  EXPECT_EQ(4, Constructable::getNumConstructorCalls());
  EXPECT_EQ(4, Constructable::getNumDestructorCalls());
}

// Clear test.
TEST_F(SmallVectorTest, ClearTest) {
  SCOPED_TRACE("ClearTest");

  makeSequence(theVector, 1, 2);
  theVector.clear();

  assertEmpty(theVector);
  EXPECT_EQ(4, Constructable::getNumConstructorCalls());
  EXPECT_EQ(4, Constructable::getNumDestructorCalls());
}

// Resize smaller test.
TEST_F(SmallVectorTest, ResizeShrinkTest) {
  SCOPED_TRACE("ResizeShrinkTest");

  makeSequence(theVector, 1, 3);
  theVector.resize(1);

  assertValuesInOrder(theVector, 1u, 1);
  EXPECT_EQ(6, Constructable::getNumConstructorCalls());
  EXPECT_EQ(5, Constructable::getNumDestructorCalls());
}

// Resize bigger test.
TEST_F(SmallVectorTest, ResizeGrowTest) {
  SCOPED_TRACE("ResizeGrowTest");

  theVector.resize(2);

  // XXX: I don't know where the extra construct/destruct is coming from.
  EXPECT_EQ(3, Constructable::getNumConstructorCalls());
  EXPECT_EQ(1, Constructable::getNumDestructorCalls());
  EXPECT_EQ(2u, theVector.size());
}

// Resize with fill value.
TEST_F(SmallVectorTest, ResizeFillTest) {
  SCOPED_TRACE("ResizeFillTest");

  theVector.resize(3, Constructable(77));
  assertValuesInOrder(theVector, 3u, 77, 77, 77);
}

// Overflow past fixed size.
TEST_F(SmallVectorTest, OverflowTest) {
  SCOPED_TRACE("OverflowTest");

  // Push more elements than the fixed size
  makeSequence(theVector, 1, 10);

  // test size and values
  EXPECT_EQ(10u, theVector.size());
  for (int i = 0; i < 10; ++i) {
    EXPECT_EQ(i+1, theVector[i].getValue());
  }

  // Now resize back to fixed size
  theVector.resize(1);

  assertValuesInOrder(theVector, 1u, 1);
}

// Iteration tests.
TEST_F(SmallVectorTest, IterationTest) {
  makeSequence(theVector, 1, 2);

  // Forward Iteration
  VectorType::iterator it = theVector.begin();
  EXPECT_TRUE(*it == theVector.front());
  EXPECT_TRUE(*it == theVector[0]);
  EXPECT_EQ(1, it->getValue());
  ++it;
  EXPECT_TRUE(*it == theVector[1]);
  EXPECT_TRUE(*it == theVector.back());
  EXPECT_EQ(2, it->getValue());
  ++it;
  EXPECT_TRUE(it == theVector.end());
  --it;
  EXPECT_TRUE(*it == theVector[1]);
  EXPECT_EQ(2, it->getValue());
  --it;
  EXPECT_TRUE(*it == theVector[0]);
  EXPECT_EQ(1, it->getValue());

  // Reverse Iteration
  VectorType::reverse_iterator rit = theVector.rbegin();
  EXPECT_TRUE(*rit == theVector[1]);
  EXPECT_EQ(2, rit->getValue());
  ++rit;
  EXPECT_TRUE(*rit == theVector[0]);
  EXPECT_EQ(1, rit->getValue());
  ++rit;
  EXPECT_TRUE(rit == theVector.rend());
  --rit;
  EXPECT_TRUE(*rit == theVector[0]);
  EXPECT_EQ(1, rit->getValue());
  --rit;
  EXPECT_TRUE(*rit == theVector[1]);
  EXPECT_EQ(2, rit->getValue());
}

// Swap test.
TEST_F(SmallVectorTest, SwapTest) {
  SCOPED_TRACE("SwapTest");

  makeSequence(theVector, 1, 2);
  std::swap(theVector, otherVector);

  assertEmpty(theVector);
  assertValuesInOrder(otherVector, 2u, 1, 2);
}

// Append test
TEST_F(SmallVectorTest, AppendTest) {
  SCOPED_TRACE("AppendTest");

  makeSequence(otherVector, 2, 3);

  theVector.push_back(Constructable(1));
  theVector.append(otherVector.begin(), otherVector.end());

  assertValuesInOrder(theVector, 3u, 1, 2, 3);
}

// Append repeated test
TEST_F(SmallVectorTest, AppendRepeatedTest) {
  SCOPED_TRACE("AppendRepeatedTest");

  theVector.push_back(Constructable(1));
  theVector.append(2, Constructable(77));
  assertValuesInOrder(theVector, 3u, 1, 77, 77);
}

// Assign test
TEST_F(SmallVectorTest, AssignTest) {
  SCOPED_TRACE("AssignTest");

  theVector.push_back(Constructable(1));
  theVector.assign(2, Constructable(77));
  assertValuesInOrder(theVector, 2u, 77, 77);
}

// Erase a single element
TEST_F(SmallVectorTest, EraseTest) {
  SCOPED_TRACE("EraseTest");

  makeSequence(theVector, 1, 3);
  theVector.erase(theVector.begin());
  assertValuesInOrder(theVector, 2u, 2, 3);
}

// Erase a range of elements
TEST_F(SmallVectorTest, EraseRangeTest) {
  SCOPED_TRACE("EraseRangeTest");

  makeSequence(theVector, 1, 3);
  theVector.erase(theVector.begin(), theVector.begin() + 2);
  assertValuesInOrder(theVector, 1u, 3);
}

// Insert a single element.
TEST_F(SmallVectorTest, InsertTest) {
  SCOPED_TRACE("InsertTest");

  makeSequence(theVector, 1, 3);
  theVector.insert(theVector.begin() + 1, Constructable(77));
  assertValuesInOrder(theVector, 4u, 1, 77, 2, 3);
}

// Insert repeated elements.
TEST_F(SmallVectorTest, InsertRepeatedTest) {
  SCOPED_TRACE("InsertRepeatedTest");

  makeSequence(theVector, 1, 3);
  theVector.insert(theVector.begin() + 1, 3, Constructable(77));
  assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3);
}

// Insert range.
TEST_F(SmallVectorTest, InsertRangeTest) {
  SCOPED_TRACE("InsertRepeatedTest");

  makeSequence(theVector, 1, 3);
  theVector.insert(theVector.begin() + 1, 3, Constructable(77));
  assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3);
}

// Comparison tests.
TEST_F(SmallVectorTest, ComparisonTest) {
  SCOPED_TRACE("ComparisonTest");

  makeSequence(theVector, 1, 3);
  makeSequence(otherVector, 1, 3);

  EXPECT_TRUE(theVector == otherVector);
  EXPECT_FALSE(theVector != otherVector);

  otherVector.clear();
  makeSequence(otherVector, 2, 4);

  EXPECT_FALSE(theVector == otherVector);
  EXPECT_TRUE(theVector != otherVector);
}

// Constant vector tests.
TEST_F(SmallVectorTest, ConstVectorTest) {
  const VectorType constVector;

  EXPECT_EQ(0u, constVector.size());
  EXPECT_TRUE(constVector.empty());
  EXPECT_TRUE(constVector.begin() == constVector.end());
}

}
<commit_msg>Fix naming of file.<commit_after>//===- llvm/unittest/ADT/SmallVectorTest.cpp ------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// SmallVector unit tests.
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "llvm/ADT/SmallVector.h"
#include <stdarg.h>

using namespace llvm;

namespace {

/// A helper class that counts the total number of constructor and
/// destructor calls.
class Constructable {
private:
  static int numConstructorCalls;
  static int numDestructorCalls;
  static int numAssignmentCalls;

  int value;

public:
  Constructable() : value(0) {
    ++numConstructorCalls;
  }

  Constructable(int val) : value(val) {
    ++numConstructorCalls;
  }

  Constructable(const Constructable & src) {
    value = src.value;
    ++numConstructorCalls;
  }

  ~Constructable() {
    ++numDestructorCalls;
  }

  Constructable & operator=(const Constructable & src) {
    value = src.value;
    ++numAssignmentCalls;
    return *this;
  }

  int getValue() const {
    return abs(value);
  }

  static void reset() {
    numConstructorCalls = 0;
    numDestructorCalls = 0;
    numAssignmentCalls = 0;
  }

  static int getNumConstructorCalls() {
    return numConstructorCalls;
  }

  static int getNumDestructorCalls() {
    return numDestructorCalls;
  }

  friend bool operator==(const Constructable & c0, const Constructable & c1) {
    return c0.getValue() == c1.getValue();
  }

  friend bool operator!=(const Constructable & c0, const Constructable & c1) {
    return c0.getValue() != c1.getValue();
  }
};

int Constructable::numConstructorCalls;
int Constructable::numDestructorCalls;
int Constructable::numAssignmentCalls;

// Test fixture class
class SmallVectorTest : public testing::Test {
protected:
  typedef SmallVector<Constructable, 4> VectorType;

  VectorType theVector;
  VectorType otherVector;

  void SetUp() {
    Constructable::reset();
  }

  void assertEmpty(VectorType & v) {
    // Size tests
    EXPECT_EQ(0u, v.size());
    EXPECT_TRUE(v.empty());

    // Iterator tests
    EXPECT_TRUE(v.begin() == v.end());
  }

  // Assert that theVector contains the specified values, in order.
  void assertValuesInOrder(VectorType & v, size_t size, ...) {
    EXPECT_EQ(size, v.size());

    va_list ap;
    va_start(ap, size);
    for (size_t i = 0; i < size; ++i) {
      int value = va_arg(ap, int);
      EXPECT_EQ(value, v[i].getValue());
    }

    va_end(ap);
  }

  // Generate a sequence of values to initialize the vector.
  void makeSequence(VectorType & v, int start, int end) {
    for (int i = start; i <= end; ++i) {
      v.push_back(Constructable(i));
    }
  }
};

// New vector test.
TEST_F(SmallVectorTest, EmptyVectorTest) {
  SCOPED_TRACE("EmptyVectorTest");
  assertEmpty(theVector);
  EXPECT_TRUE(theVector.rbegin() == theVector.rend());
  EXPECT_EQ(0, Constructable::getNumConstructorCalls());
  EXPECT_EQ(0, Constructable::getNumDestructorCalls());
}

// Simple insertions and deletions.
TEST_F(SmallVectorTest, PushPopTest) {
  SCOPED_TRACE("PushPopTest");

  // Push an element
  theVector.push_back(Constructable(1));

  // Size tests
  assertValuesInOrder(theVector, 1u, 1);
  EXPECT_FALSE(theVector.begin() == theVector.end());
  EXPECT_FALSE(theVector.empty());

  // Push another element
  theVector.push_back(Constructable(2));
  assertValuesInOrder(theVector, 2u, 1, 2);

  // Pop one element
  theVector.pop_back();
  assertValuesInOrder(theVector, 1u, 1);

  // Pop another element
  theVector.pop_back();
  assertEmpty(theVector);

  // Check number of constructor calls. Should be 2 for each list element,
  // one for the argument to push_back, and one for the list element itself.
  EXPECT_EQ(4, Constructable::getNumConstructorCalls());
  EXPECT_EQ(4, Constructable::getNumDestructorCalls());
}

// Clear test.
TEST_F(SmallVectorTest, ClearTest) {
  SCOPED_TRACE("ClearTest");

  makeSequence(theVector, 1, 2);
  theVector.clear();

  assertEmpty(theVector);
  EXPECT_EQ(4, Constructable::getNumConstructorCalls());
  EXPECT_EQ(4, Constructable::getNumDestructorCalls());
}

// Resize smaller test.
TEST_F(SmallVectorTest, ResizeShrinkTest) {
  SCOPED_TRACE("ResizeShrinkTest");

  makeSequence(theVector, 1, 3);
  theVector.resize(1);

  assertValuesInOrder(theVector, 1u, 1);
  EXPECT_EQ(6, Constructable::getNumConstructorCalls());
  EXPECT_EQ(5, Constructable::getNumDestructorCalls());
}

// Resize bigger test.
TEST_F(SmallVectorTest, ResizeGrowTest) {
  SCOPED_TRACE("ResizeGrowTest");

  theVector.resize(2);

  // XXX: I don't know where the extra construct/destruct is coming from.
  EXPECT_EQ(3, Constructable::getNumConstructorCalls());
  EXPECT_EQ(1, Constructable::getNumDestructorCalls());
  EXPECT_EQ(2u, theVector.size());
}

// Resize with fill value.
TEST_F(SmallVectorTest, ResizeFillTest) {
  SCOPED_TRACE("ResizeFillTest");

  theVector.resize(3, Constructable(77));
  assertValuesInOrder(theVector, 3u, 77, 77, 77);
}

// Overflow past fixed size.
TEST_F(SmallVectorTest, OverflowTest) {
  SCOPED_TRACE("OverflowTest");

  // Push more elements than the fixed size
  makeSequence(theVector, 1, 10);

  // test size and values
  EXPECT_EQ(10u, theVector.size());
  for (int i = 0; i < 10; ++i) {
    EXPECT_EQ(i+1, theVector[i].getValue());
  }

  // Now resize back to fixed size
  theVector.resize(1);

  assertValuesInOrder(theVector, 1u, 1);
}

// Iteration tests.
TEST_F(SmallVectorTest, IterationTest) {
  makeSequence(theVector, 1, 2);

  // Forward Iteration
  VectorType::iterator it = theVector.begin();
  EXPECT_TRUE(*it == theVector.front());
  EXPECT_TRUE(*it == theVector[0]);
  EXPECT_EQ(1, it->getValue());
  ++it;
  EXPECT_TRUE(*it == theVector[1]);
  EXPECT_TRUE(*it == theVector.back());
  EXPECT_EQ(2, it->getValue());
  ++it;
  EXPECT_TRUE(it == theVector.end());
  --it;
  EXPECT_TRUE(*it == theVector[1]);
  EXPECT_EQ(2, it->getValue());
  --it;
  EXPECT_TRUE(*it == theVector[0]);
  EXPECT_EQ(1, it->getValue());

  // Reverse Iteration
  VectorType::reverse_iterator rit = theVector.rbegin();
  EXPECT_TRUE(*rit == theVector[1]);
  EXPECT_EQ(2, rit->getValue());
  ++rit;
  EXPECT_TRUE(*rit == theVector[0]);
  EXPECT_EQ(1, rit->getValue());
  ++rit;
  EXPECT_TRUE(rit == theVector.rend());
  --rit;
  EXPECT_TRUE(*rit == theVector[0]);
  EXPECT_EQ(1, rit->getValue());
  --rit;
  EXPECT_TRUE(*rit == theVector[1]);
  EXPECT_EQ(2, rit->getValue());
}

// Swap test.
TEST_F(SmallVectorTest, SwapTest) {
  SCOPED_TRACE("SwapTest");

  makeSequence(theVector, 1, 2);
  std::swap(theVector, otherVector);

  assertEmpty(theVector);
  assertValuesInOrder(otherVector, 2u, 1, 2);
}

// Append test
TEST_F(SmallVectorTest, AppendTest) {
  SCOPED_TRACE("AppendTest");

  makeSequence(otherVector, 2, 3);

  theVector.push_back(Constructable(1));
  theVector.append(otherVector.begin(), otherVector.end());

  assertValuesInOrder(theVector, 3u, 1, 2, 3);
}

// Append repeated test
TEST_F(SmallVectorTest, AppendRepeatedTest) {
  SCOPED_TRACE("AppendRepeatedTest");

  theVector.push_back(Constructable(1));
  theVector.append(2, Constructable(77));
  assertValuesInOrder(theVector, 3u, 1, 77, 77);
}

// Assign test
TEST_F(SmallVectorTest, AssignTest) {
  SCOPED_TRACE("AssignTest");

  theVector.push_back(Constructable(1));
  theVector.assign(2, Constructable(77));
  assertValuesInOrder(theVector, 2u, 77, 77);
}

// Erase a single element
TEST_F(SmallVectorTest, EraseTest) {
  SCOPED_TRACE("EraseTest");

  makeSequence(theVector, 1, 3);
  theVector.erase(theVector.begin());
  assertValuesInOrder(theVector, 2u, 2, 3);
}

// Erase a range of elements
TEST_F(SmallVectorTest, EraseRangeTest) {
  SCOPED_TRACE("EraseRangeTest");

  makeSequence(theVector, 1, 3);
  theVector.erase(theVector.begin(), theVector.begin() + 2);
  assertValuesInOrder(theVector, 1u, 3);
}

// Insert a single element.
TEST_F(SmallVectorTest, InsertTest) {
  SCOPED_TRACE("InsertTest");

  makeSequence(theVector, 1, 3);
  theVector.insert(theVector.begin() + 1, Constructable(77));
  assertValuesInOrder(theVector, 4u, 1, 77, 2, 3);
}

// Insert repeated elements.
TEST_F(SmallVectorTest, InsertRepeatedTest) {
  SCOPED_TRACE("InsertRepeatedTest");

  makeSequence(theVector, 1, 3);
  theVector.insert(theVector.begin() + 1, 3, Constructable(77));
  assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3);
}

// Insert range.
TEST_F(SmallVectorTest, InsertRangeTest) {
  SCOPED_TRACE("InsertRepeatedTest");

  makeSequence(theVector, 1, 3);
  theVector.insert(theVector.begin() + 1, 3, Constructable(77));
  assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3);
}

// Comparison tests.
TEST_F(SmallVectorTest, ComparisonTest) {
  SCOPED_TRACE("ComparisonTest");

  makeSequence(theVector, 1, 3);
  makeSequence(otherVector, 1, 3);

  EXPECT_TRUE(theVector == otherVector);
  EXPECT_FALSE(theVector != otherVector);

  otherVector.clear();
  makeSequence(otherVector, 2, 4);

  EXPECT_FALSE(theVector == otherVector);
  EXPECT_TRUE(theVector != otherVector);
}

// Constant vector tests.
TEST_F(SmallVectorTest, ConstVectorTest) {
  const VectorType constVector;

  EXPECT_EQ(0u, constVector.size());
  EXPECT_TRUE(constVector.empty());
  EXPECT_TRUE(constVector.begin() == constVector.end());
}

}
<|endoftext|>