<commit_before>#include <algorithm>
#include <utility>
#include <cmath>

namespace maths
{
	// These are not always defined in cmath nor with 128 bit precision
	constexpr auto e       = 2.718281828459045235360287471352662498L;
	constexpr auto ln2     = 0.693147180559945309417232121458176568L;
	constexpr auto ln10    = 2.302585092994045684017991454684364208L;
	constexpr auto log2e   = 1.442695040888963407359924681001892137L;
	constexpr auto log10e  = 0.434294481903251827651128918916605082L;
	constexpr auto pi      = 3.141592653589793238462643383279502884L;
	constexpr auto pi_2    = 1.570796326794896619231321691639751442L;
	constexpr auto pi_4    = 0.785398163397448309615660845819875721L;
	constexpr auto pi2_6   = 1.644934066848226436472415166646025189L;
	constexpr auto sqrt2pi = 2.506628274631000502415765284811045253L;
	constexpr auto sqrt2   = 1.414213562373095048801688724209698079L;
	constexpr auto ngamma  = 0.577215664901532860606512090082402431L;

	/// The greatest common divisor, so that m|gcd(m, n) and n|gcd(m, n)
	template <typename int_t> int_t gcd(int_t m, int_t n)
	{
		if (n < m) std::swap(m, n);
		int_t r;
		while (m) r = n % m, n = m, m = r;
		return n;
	}

	/// The lowest common multiple, so that gcd(m, n)*lcm(m, n) = m*n
	template <typename int_t> int_t lcm(int_t m, int_t n)
	{
		return m * (n / gcd(m, n));
	}

	/// The factorial of n, n! = n(n - 1)(n - 2)...
	template <typename int_t> int_t fact(int_t n)
	{
		int_t m = 1;
		while (n) m *= n--;
		return m;
	}

	/// The primorial of n, the product of primes up to n
	template <typename int_t> int_t prim(int_t n)
	{
		int_t p = 1, q = 1;
		while (q++ < n) if (gcd(p, q) < 2) p *= q;
		return p;
	}

	/// The k permutations of n elements, n!/(n - k)!
	template <typename int_t> int_t perm(int_t n, int_t k)
	{
		k = n - k;
		int_t m = 1;
		while (k--) m *= n--;
		return m;
	}

	/// The k combinations of n elements, n!/k!(n - k)!
	template <typename int_t> int_t comb(int_t n, int_t k)
	{
		k = std::min(k, n - k);
		int_t m = 1, r = 1;
		while (k) m *= n--, r *= k--;
		return m/r;
	}

	/// Extends factorials into the real numbers, tgamma(n) = (n - 1)!
	template <typename float_t> inline float_t tgamma(float_t x)
	{
		return std::tgamma(x);
	}

	/// The natural logarithm of the gamma function
	template <typename float_t> inline float_t lgamma(float_t x)
	{
		return std::lgamma(x);
	}

	/// The lower incomplete gamma function
	template <typename float_t> float_t igamma(float_t a, float_t x)
	{
		float_t s = 0, t = std::pow(x, a)/a;
		do s += t, t *= x, t /= ++a;
		while (t);
		s /= std::exp(x);
		return s;
	}

	/// The upper incomplete gamma function (lower's complement)
	template <typename float_t> float_t igammac(float_t a, float_t x)
	{
		return std::tgamma(a) - igamma(a, x);
	}

	/// Extends combinations into the field of real numbers
	template <typename float_t> float_t beta(float_t a, float_t b)
	{
		return std::tgamma(a + b)/std::tgamma(a)/std::tgamma(b);
	}

	/// The lower incomplete beta function
	template <typename float_t> float_t ibeta(float_t a, float_t b, float_t p)
	{
		float_t t = std::pow(p, a);
		float_t s = 0, n = 1, u = 1 - b;
		do s += t/a++, t *= u++, t /= n++, t *= p;
		while (t);
		return s;
	}

	/// The upper incomplete beta function (lower's complement)
	template <typename float_t> float_t ibetac(float_t a, float_t b, float_t p)
	{
		return beta(a, b) - ibeta(a, b, p);
	}

	/// The generalized Reimann zeta function for real x > 1
	template <typename float_t> float_t zeta(float_t x, float_t eps = 1e-9)
	{
		float_t r, s = 1, t, n = 1;
		do r = std::pow(++n, x), t = 1/r, s += t;
		while (eps < t);
		return s;
	}

	/// Measures the area under the bell curve for errors of size x
	template <typename float_t> inline float_t erf(float_t x)
	{
		return std::erf(x);
	}

	/// Measures the complement of the error function
	template <typename float_t> inline float_t erfc(float_t x)
	{
		return std::erfc(x);
	}

	/// The power of x raised to the exponent p
	template <typename float_t> inline float_t pow(float_t x, float_t p)
	{
		return std::pow(x, p);
	}

	/// The square root of x
	template <typename float_t> inline float_t sqrt(float_t x)
	{
		return std::sqrt(x);
	}

	/// The cube root of x
	template <typename float_t> inline float_t cbrt(float_t x)
	{
		return std::cbrt(x);
	}

	/// The square root of the sum of the squares of x and y
	template <typename float_t> inline float_t hypot(float_t x, float_t y)
	{
		return std::hypot(x, y);
	}

	/// Equivalent to x*y + z but more precise
	template <typename float_t> inline float_t fma(float_t x, float_t y, float_t z)
	{
		return std::fma(x, y, z);
	}

	/// Euler's number raised to the exponent x
	template <typename float_t> inline float_t exp(float_t x)
	{
		return std::exp(x);
	}

	/// The number 2 raised to the exponent x
	template <typename float_t> inline float_t exp2(float_t x)
	{
		return std::exp2(x);
	}

	/// Equivalent to x*exp2(p) but more precise
	template <typename float_t> inline float_t ldexp(float_t x, int p)
	{
		return std::ldexp(x, p);
	}

	/// The natural logarithm of x, so exp(log(x)) = x
	template <typename float_t> inline float_t log(float_t x)
	{
		return std::log(x);
	}

	/// The logarithm of x expressed in base b, so pow(b, log(x, b)) = x
	template <typename float_t> inline float_t logb(float_t x, float_t b)
	{
		return std::log(x)/std::log(b);
	}

	/// The logarithm of x expressed in base 2, so log2(x) = log(x, 2)
	template <typename float_t> inline float_t log2(float_t x)
	{
		return std::log2(x);
	}

	/// The logarithm of x expressed in base 10, so log10(x) = log(x, 10)
	template <typename float_t> inline float_t log10(float_t x)
	{
		return std::log10(x);
	}

	template <typename float_t> inline float_t sin(float_t x)
	{
		return std::sin(x);
	}

	template <typename float_t> inline float_t cos(float_t x)
	{
		return std::cos(x);
	}

	template <typename float_t> inline float_t tan(float_t x)
	{
		return std::tan(x);
	}

	template <typename float_t> inline float_t asin(float_t x)
	{
		return std::asin(x);
	}

	template <typename float_t> inline float_t acos(float_t x)
	{
		return std::acos(x);
	}

	template <typename float_t> inline float_t atan(float_t x)
	{
		return std::atan(x);
	}

	template <typename float_t> inline float_t atan2(float_t y, float_t x)
	{
		return std::atan2(y, x);
	}

	template <typename float_t> inline float_t sinh(float_t x)
	{
		return std::sinh(x);
	}

	template <typename float_t> inline float_t cosh(float_t x)
	{
		return std::cosh(x);
	}

	template <typename float_t> inline float_t tanh(float_t x)
	{
		return std::tanh(x);
	}

	template <typename float_t> inline float_t asinh(float_t x)
	{
		return std::asinh(x);
	}

	template <typename float_t> inline float_t acosh(float_t x)
	{
		return std::acosh(x);
	}

	template <typename float_t> inline float_t atanh(float_t x)
	{
		return std::atanh(x);
	}

}; // namespace maths

<commit_msg>New primorial function<commit_after>#include <algorithm>
#include <utility>
#include <cmath>

namespace maths
{
	// These are not always defined in cmath nor with 128 bit precision
	constexpr auto e       = 2.718281828459045235360287471352662498L;
	constexpr auto ln2     = 0.693147180559945309417232121458176568L;
	constexpr auto ln10    = 2.302585092994045684017991454684364208L;
	constexpr auto log2e   = 1.442695040888963407359924681001892137L;
	constexpr auto log10e  = 0.434294481903251827651128918916605082L;
	constexpr auto pi      = 3.141592653589793238462643383279502884L;
	constexpr auto pi_2    = 1.570796326794896619231321691639751442L;
	constexpr auto pi_4    = 0.785398163397448309615660845819875721L;
	constexpr auto pi2_6   = 1.644934066848226436472415166646025189L;
	constexpr auto sqrt2pi = 2.506628274631000502415765284811045253L;
	constexpr auto sqrt2   = 1.414213562373095048801688724209698079L;
	constexpr auto ngamma  = 0.577215664901532860606512090082402431L;

	/// The greatest common divisor, so that m|gcd(m, n) and n|gcd(m, n)
	template <typename int_t> int_t gcd(int_t m, int_t n)
	{
		if (n < m) std::swap(m, n);
		int_t r;
		while (m) r = n % m, n = m, m = r;
		return n;
	}

	/// The lowest common multiple, so that gcd(m, n)*lcm(m, n) = m*n
	template <typename int_t> int_t lcm(int_t m, int_t n)
	{
		return m * (n / gcd(m, n));
	}

	/// The factorial of n, n! = n(n - 1)(n - 2)...
	template <typename int_t> int_t fact(int_t n)
	{
		int_t m = 1;
		while (n) m *= n--;
		return m;
	}

	/// The primorial of n, the product of primes up to n
	template <typename int_t> int_t prim(int_t n)
	{
		if (n < 2) return 1;
		int_t p = 2, q = 3;
		while (q <= n) {
		 if (gcd(p, q) < 2) p *= q;
		 q += 2;
		};
		return p;
	}

	/// The k permutations of n elements, n!/(n - k)!
	template <typename int_t> int_t perm(int_t n, int_t k)
	{
		k = n - k;
		int_t m = 1;
		while (k--) m *= n--;
		return m;
	}

	/// The k combinations of n elements, n!/k!(n - k)!
	template <typename int_t> int_t comb(int_t n, int_t k)
	{
		k = std::min(k, n - k);
		int_t m = 1, r = 1;
		while (k) m *= n--, r *= k--;
		return m/r;
	}

	/// Extends factorials into the real numbers, tgamma(n) = (n - 1)!
	template <typename float_t> inline float_t tgamma(float_t x)
	{
		return std::tgamma(x);
	}

	/// The natural logarithm of the gamma function
	template <typename float_t> inline float_t lgamma(float_t x)
	{
		return std::lgamma(x);
	}

	/// The lower incomplete gamma function
	template <typename float_t> float_t igamma(float_t a, float_t x)
	{
		float_t s = 0, t = std::pow(x, a)/a;
		do s += t, t *= x, t /= ++a;
		while (t);
		s /= std::exp(x);
		return s;
	}

	/// The upper incomplete gamma function (lower's complement)
	template <typename float_t> float_t igammac(float_t a, float_t x)
	{
		return std::tgamma(a) - igamma(a, x);
	}

	/// Extends combinations into the field of real numbers
	template <typename float_t> float_t beta(float_t a, float_t b)
	{
		return std::tgamma(a + b)/std::tgamma(a)/std::tgamma(b);
	}

	/// The lower incomplete beta function
	template <typename float_t> float_t ibeta(float_t a, float_t b, float_t p)
	{
		float_t t = std::pow(p, a);
		float_t s = 0, n = 1, u = 1 - b;
		do s += t/a++, t *= u++, t /= n++, t *= p;
		while (t);
		return s;
	}

	/// The upper incomplete beta function (lower's complement)
	template <typename float_t> float_t ibetac(float_t a, float_t b, float_t p)
	{
		return beta(a, b) - ibeta(a, b, p);
	}

	/// The generalized Reimann zeta function for real x > 1
	template <typename float_t> float_t zeta(float_t x, float_t eps = 1e-9)
	{
		float_t r, s = 1, t, n = 1;
		do r = std::pow(++n, x), t = 1/r, s += t;
		while (eps < t);
		return s;
	}

	/// Measures the area under the bell curve for errors of size x
	template <typename float_t> inline float_t erf(float_t x)
	{
		return std::erf(x);
	}

	/// Measures the complement of the error function
	template <typename float_t> inline float_t erfc(float_t x)
	{
		return std::erfc(x);
	}

	/// The power of x raised to the exponent p
	template <typename float_t> inline float_t pow(float_t x, float_t p)
	{
		return std::pow(x, p);
	}

	/// The square root of x
	template <typename float_t> inline float_t sqrt(float_t x)
	{
		return std::sqrt(x);
	}

	/// The cube root of x
	template <typename float_t> inline float_t cbrt(float_t x)
	{
		return std::cbrt(x);
	}

	/// The square root of the sum of the squares of x and y
	template <typename float_t> inline float_t hypot(float_t x, float_t y)
	{
		return std::hypot(x, y);
	}

	/// Equivalent to x*y + z but more precise
	template <typename float_t> inline float_t fma(float_t x, float_t y, float_t z)
	{
		return std::fma(x, y, z);
	}

	/// Euler's number raised to the exponent x
	template <typename float_t> inline float_t exp(float_t x)
	{
		return std::exp(x);
	}

	/// The number 2 raised to the exponent x
	template <typename float_t> inline float_t exp2(float_t x)
	{
		return std::exp2(x);
	}

	/// Equivalent to x*exp2(p) but more precise
	template <typename float_t> inline float_t ldexp(float_t x, int p)
	{
		return std::ldexp(x, p);
	}

	/// The natural logarithm of x, so exp(log(x)) = x
	template <typename float_t> inline float_t log(float_t x)
	{
		return std::log(x);
	}

	/// The logarithm of x expressed in base b, so pow(b, log(x, b)) = x
	template <typename float_t> inline float_t logb(float_t x, float_t b)
	{
		return std::log(x)/std::log(b);
	}

	/// The logarithm of x expressed in base 2, so log2(x) = log(x, 2)
	template <typename float_t> inline float_t log2(float_t x)
	{
		return std::log2(x);
	}

	/// The logarithm of x expressed in base 10, so log10(x) = log(x, 10)
	template <typename float_t> inline float_t log10(float_t x)
	{
		return std::log10(x);
	}

	template <typename float_t> inline float_t sin(float_t x)
	{
		return std::sin(x);
	}

	template <typename float_t> inline float_t cos(float_t x)
	{
		return std::cos(x);
	}

	template <typename float_t> inline float_t tan(float_t x)
	{
		return std::tan(x);
	}

	template <typename float_t> inline float_t asin(float_t x)
	{
		return std::asin(x);
	}

	template <typename float_t> inline float_t acos(float_t x)
	{
		return std::acos(x);
	}

	template <typename float_t> inline float_t atan(float_t x)
	{
		return std::atan(x);
	}

	template <typename float_t> inline float_t atan2(float_t y, float_t x)
	{
		return std::atan2(y, x);
	}

	template <typename float_t> inline float_t sinh(float_t x)
	{
		return std::sinh(x);
	}

	template <typename float_t> inline float_t cosh(float_t x)
	{
		return std::cosh(x);
	}

	template <typename float_t> inline float_t tanh(float_t x)
	{
		return std::tanh(x);
	}

	template <typename float_t> inline float_t asinh(float_t x)
	{
		return std::asinh(x);
	}

	template <typename float_t> inline float_t acosh(float_t x)
	{
		return std::acosh(x);
	}

	template <typename float_t> inline float_t atanh(float_t x)
	{
		return std::atanh(x);
	}

}; // namespace maths

<|endoftext|>


<commit_before>#include "Client.hh"

#include <string>
#include "Socket.hh"
#include "http/Response.hh"
#include "http/Request.hh"
#include "methods/Get.hh"
#include "Config.hh"

ss::Client::Client(Socket* socket) : socket(socket)
{
	auto request = get_request();
	http::Response response;
	response.headers["protocol"] = "HTTP/1.1";

	if (request.headers["method"] == "GET")
	{
		methods::Get(request, &response);
	}

	send_response(response);
}

ss::http::Request ss::Client::get_request()
{
	std::string response;

	// An endless wait may happen if the last response is the same size as buffer.
	while (true)
	{
		char buffer[1024];
		int received;
		socket->receive(&buffer, sizeof(buffer), &received);
		response.append(buffer, received);

		if (received < sizeof(buffer))
		{
			break;
		}
	}

	return http::Request(response);
}

void ss::Client::send_response(const http::Response& response)
{
	const auto response_string = response.as_string();
	socket->send(response_string.data(), response_string.size());
	socket->disconnect();
}
<commit_msg>Make while loop more compact<commit_after>#include "Client.hh"

#include <string>
#include "Socket.hh"
#include "http/Response.hh"
#include "http/Request.hh"
#include "methods/Get.hh"
#include "Config.hh"

ss::Client::Client(Socket* socket) : socket(socket)
{
	auto request = get_request();
	http::Response response;
	response.headers["protocol"] = "HTTP/1.1";

	if (request.headers["method"] == "GET")
	{
		methods::Get(request, &response);
	}

	send_response(response);
}

ss::http::Request ss::Client::get_request()
{
	std::string response;

  char buffer[1024];
	int received = sizeof(buffer);
	// An endless wait may happen if the last response is the same size as buffer.
  while (received == sizeof(buffer)) {
		socket->receive(&buffer, sizeof(buffer), &received);
		response.append(buffer, received);
	}

	return http::Request(response);
}

void ss::Client::send_response(const http::Response& response)
{
	const auto response_string = response.as_string();
	socket->send(response_string.data(), response_string.size());
	socket->disconnect();
}
<|endoftext|>


<commit_before>/*
 *  DataHandlerCallback.cpp
 *
 *    DataHandlerCallback.cpp - file I/O for libebml.
 *
 *
 *  Copyright (c) 2006  David Conrad
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation;
 *  version 2.1 of the License.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "DataHandlerCallback.h"
#include <QuickTime/QuickTime.h>

#include "ebml/Debug.h"
#include "ebml/EbmlConfig.h"
#include "ebml/StdIOCallback.h"

using namespace std;

DataHBuffer::DataHBuffer(size_t bufferSize)
{
	buffer = new uint8_t[bufferSize];
	allocatedSize = bufferSize;
	fileOffset = -1;
	dataSize = 0;
}

DataHBuffer::~DataHBuffer()
{
	if (buffer)
		delete[] buffer;
}

void DataHBuffer::Realloc(size_t bufferSize)
{
	if (buffer)
		delete[] buffer;

	buffer = new uint8_t[bufferSize];
	allocatedSize = bufferSize;
	fileOffset = -1;
	dataSize = 0;
}

bool DataHBuffer::ContainsOffset(uint64_t offset)
{
	return offset >= fileOffset && offset < fileOffset + dataSize;
}

uint8_t * DataHBuffer::GetBuffer(uint64_t offset, size_t size)
{
	if (size > allocatedSize)
		Realloc(size);

	fileOffset = offset;
	dataSize = size;
	return buffer;
}

size_t DataHBuffer::Read(uint64_t offset, size_t size, uint8_t *store)
{
	if (!ContainsOffset(offset))
		return 0;

	uint8_t *dataStart = buffer + (offset - fileOffset);
	size_t amountToRead = MIN(fileOffset + dataSize - offset, size);
	memcpy(store, dataStart, amountToRead);
	return amountToRead;
}

DataHandlerCallback::DataHandlerCallback(ComponentInstance dataHandler, const open_mode aMode)
{
	Initialize(aMode);

	switch (aMode)
	{
		case MODE_READ:
		case MODE_WRITE:
			this->dataHandler = dataHandler;
			break;

		default:
			throw 0;
			break;
	}

	// figure out if we support wide offesets
	getFileSize();
}

DataHandlerCallback::DataHandlerCallback(Handle dataRef, OSType dataRefType, const open_mode aMode)
{
    ComponentResult err = noErr;
	Component dataHComponent = NULL;

	Initialize(aMode);

	if (aMode == MODE_READ)
		dataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanRead);
	else if (aMode == MODE_WRITE)
		dataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanWrite);
	else
		throw 0;

	err = OpenAComponent(dataHComponent, &dataHandler);
	if (err) {
		throw CRTError("Error opening data handler component", err);
	}

	err = DataHSetDataRef(dataHandler, dataRef);
	if (err) {
		throw CRTError("Error setting data handler ref", err);
	}

	if (aMode == MODE_READ) {
		err = DataHOpenForRead(dataHandler);
        if (err) {
            throw CRTError("Error opening data handler for read", err);
        }
	} else if (aMode == MODE_WRITE) {
		err = DataHOpenForWrite(dataHandler);
        if (err) {
            throw CRTError("Error opening data handler for write", err);
        }
	} else {
		throw 0;
	}

	closeHandler = true;

	// figure out if we support wide offesets
	getFileSize();
}

void DataHandlerCallback::Initialize(const open_mode aMode)
{
	closeHandler = false;
	supportsWideOffsets = true;
	this->dataHandler = NULL;
	mCurrentPosition = 0;
	filesize = 0;
	this->aMode = aMode;
}

DataHandlerCallback::~DataHandlerCallback() throw()
{
	close();
}

uint32 DataHandlerCallback::read(void *buffer, size_t size)
{
	ComponentResult err = noErr;
	size_t amountRead = 0;
	uint64_t oldPos = mCurrentPosition;
	uint8_t *internalBuffer, *myBuffer = (uint8_t *)buffer;

    if (size < 1 || mCurrentPosition > filesize)
        return 0;

	if (mCurrentPosition + size > filesize)
		size = filesize - mCurrentPosition;

	while (size > 0) {
		if (dataBuffer.ContainsOffset(mCurrentPosition)) {
			amountRead = dataBuffer.Read(mCurrentPosition, size, myBuffer);
			myBuffer += amountRead;
			mCurrentPosition += amountRead;
			size -= amountRead;
		}

		if (size <= 0)
			break;

		internalBuffer = dataBuffer.GetBuffer(mCurrentPosition, READ_SIZE);

		if (supportsWideOffsets) {
			wide wideOffset = SInt64ToWide(mCurrentPosition);

			err = DataHScheduleData64(dataHandler, (Ptr)internalBuffer, &wideOffset,
									  READ_SIZE, 0, NULL, NULL);
		} else {
			err = DataHScheduleData(dataHandler, (Ptr)internalBuffer, mCurrentPosition,
									READ_SIZE, 0, NULL, NULL);
		}

		if (err) {
			throw CRTError("Error reading data", err);
		}
	}

	return mCurrentPosition - oldPos;
}

void DataHandlerCallback::setFilePointer(int64 Offset, seek_mode Mode)
{
	switch ( Mode )
	{
		case SEEK_CUR:
			mCurrentPosition += Offset;
			break;
		case SEEK_END:
			// I think this is what seeking this way does (was ftell(File))
			mCurrentPosition = getFileSize() + Offset;
			break;
		case SEEK_SET:
			mCurrentPosition = Offset;
			break;
	}
}

size_t DataHandlerCallback::write(const void *Buffer, size_t Size)
{
	ComponentResult err = noErr;

	if (supportsWideOffsets) {
		wide wideOffset = SInt64ToWide(mCurrentPosition);

		err = DataHWrite64(dataHandler, (Ptr)Buffer, &wideOffset, Size, NULL, 0);
	} else {
		err = DataHWrite(dataHandler, (Ptr)Buffer, mCurrentPosition, Size, NULL, 0);
	}

	if (err) {
		throw CRTError("Error writing data", err);
	}
	mCurrentPosition += Size;

	// does QT tell us how much it writes?
	return Size;
}

uint64 DataHandlerCallback::getFilePointer()
{
	return mCurrentPosition;
}

void DataHandlerCallback::close()
{
	if (closeHandler) {
		if (aMode == MODE_READ)
			DataHCloseForRead(dataHandler);
		else if (aMode == MODE_WRITE)
			DataHCloseForWrite(dataHandler);
		dataHandler = NULL;
	}
}

SInt64 DataHandlerCallback::getFileSize()
{
	ComponentResult err = noErr;
	wide wideFilesize;

	if (filesize > 0)
		return filesize;

	err = DataHGetFileSize64(dataHandler, &wideFilesize);
	if (err == noErr) {
		supportsWideOffsets = true;
		filesize = WideToSInt64(wideFilesize);
	} else {
		long size32;
		supportsWideOffsets = false;
		DataHGetFileSize(dataHandler, &size32);
		filesize = size32;
	}

	return filesize;
}
<commit_msg>Changed data handler to not read past the end of the file.  Also, check the file size when it may read past it.<commit_after>/*
 *  DataHandlerCallback.cpp
 *
 *    DataHandlerCallback.cpp - file I/O for libebml.
 *
 *
 *  Copyright (c) 2006  David Conrad
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation;
 *  version 2.1 of the License.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

#include "DataHandlerCallback.h"
#include <QuickTime/QuickTime.h>

#include "ebml/Debug.h"
#include "ebml/EbmlConfig.h"
#include "ebml/StdIOCallback.h"

using namespace std;

DataHBuffer::DataHBuffer(size_t bufferSize)
{
	buffer = new uint8_t[bufferSize];
	allocatedSize = bufferSize;
	fileOffset = -1;
	dataSize = 0;
}

DataHBuffer::~DataHBuffer()
{
	if (buffer)
		delete[] buffer;
}

void DataHBuffer::Realloc(size_t bufferSize)
{
	if (buffer)
		delete[] buffer;

	buffer = new uint8_t[bufferSize];
	allocatedSize = bufferSize;
	fileOffset = -1;
	dataSize = 0;
}

bool DataHBuffer::ContainsOffset(uint64_t offset)
{
	return offset >= fileOffset && offset < fileOffset + dataSize;
}

uint8_t * DataHBuffer::GetBuffer(uint64_t offset, size_t size)
{
	if (size > allocatedSize)
		Realloc(size);

	fileOffset = offset;
	dataSize = size;
	return buffer;
}

size_t DataHBuffer::Read(uint64_t offset, size_t size, uint8_t *store)
{
	if (!ContainsOffset(offset))
		return 0;

	uint8_t *dataStart = buffer + (offset - fileOffset);
	size_t amountToRead = MIN(fileOffset + dataSize - offset, size);
	memcpy(store, dataStart, amountToRead);
	return amountToRead;
}

DataHandlerCallback::DataHandlerCallback(ComponentInstance dataHandler, const open_mode aMode)
{
	Initialize(aMode);

	switch (aMode)
	{
		case MODE_READ:
		case MODE_WRITE:
			this->dataHandler = dataHandler;
			break;

		default:
			throw 0;
			break;
	}

	// figure out if we support wide offesets
	getFileSize();
}

DataHandlerCallback::DataHandlerCallback(Handle dataRef, OSType dataRefType, const open_mode aMode)
{
    ComponentResult err = noErr;
	Component dataHComponent = NULL;

	Initialize(aMode);

	if (aMode == MODE_READ)
		dataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanRead);
	else if (aMode == MODE_WRITE)
		dataHComponent = GetDataHandler(dataRef, dataRefType, kDataHCanWrite);
	else
		throw 0;

	err = OpenAComponent(dataHComponent, &dataHandler);
	if (err) {
		throw CRTError("Error opening data handler component", err);
	}

	err = DataHSetDataRef(dataHandler, dataRef);
	if (err) {
		throw CRTError("Error setting data handler ref", err);
	}

	if (aMode == MODE_READ) {
		err = DataHOpenForRead(dataHandler);
        if (err) {
            throw CRTError("Error opening data handler for read", err);
        }
	} else if (aMode == MODE_WRITE) {
		err = DataHOpenForWrite(dataHandler);
        if (err) {
            throw CRTError("Error opening data handler for write", err);
        }
	} else {
		throw 0;
	}

	closeHandler = true;

	// figure out if we support wide offesets
	getFileSize();
}

void DataHandlerCallback::Initialize(const open_mode aMode)
{
	closeHandler = false;
	supportsWideOffsets = true;
	this->dataHandler = NULL;
	mCurrentPosition = 0;
	filesize = 0;
	this->aMode = aMode;
}

DataHandlerCallback::~DataHandlerCallback() throw()
{
	close();
}

uint32 DataHandlerCallback::read(void *buffer, size_t size)
{
	ComponentResult err = noErr;
	size_t amountRead = 0;
	uint64_t oldPos = mCurrentPosition;
	uint8_t *internalBuffer, *myBuffer = (uint8_t *)buffer;

	if (mCurrentPosition + size > filesize)
		getFileSize();

    if (size < 1 || mCurrentPosition > filesize)
        return 0;

	if (mCurrentPosition + size > filesize)
		size = filesize - mCurrentPosition;

	while (size > 0) {
		if (dataBuffer.ContainsOffset(mCurrentPosition)) {
			amountRead = dataBuffer.Read(mCurrentPosition, size, myBuffer);
			myBuffer += amountRead;
			mCurrentPosition += amountRead;
			size -= amountRead;
		}

		if (size <= 0)
			break;

		size_t readSize = MIN(READ_SIZE, filesize - mCurrentPosition);

		internalBuffer = dataBuffer.GetBuffer(mCurrentPosition, readSize);

		if (supportsWideOffsets) {
			wide wideOffset = SInt64ToWide(mCurrentPosition);

			err = DataHScheduleData64(dataHandler, (Ptr)internalBuffer, &wideOffset,
									  readSize, 0, NULL, NULL);
		} else {
			err = DataHScheduleData(dataHandler, (Ptr)internalBuffer, mCurrentPosition,
									readSize, 0, NULL, NULL);
		}

		if (err) {
			throw CRTError("Error reading data", err);
		}
	}

	return mCurrentPosition - oldPos;
}

void DataHandlerCallback::setFilePointer(int64 Offset, seek_mode Mode)
{
	switch ( Mode )
	{
		case SEEK_CUR:
			mCurrentPosition += Offset;
			break;
		case SEEK_END:
			// I think this is what seeking this way does (was ftell(File))
			mCurrentPosition = getFileSize() + Offset;
			break;
		case SEEK_SET:
			mCurrentPosition = Offset;
			break;
	}
}

size_t DataHandlerCallback::write(const void *Buffer, size_t Size)
{
	ComponentResult err = noErr;

	if (supportsWideOffsets) {
		wide wideOffset = SInt64ToWide(mCurrentPosition);

		err = DataHWrite64(dataHandler, (Ptr)Buffer, &wideOffset, Size, NULL, 0);
	} else {
		err = DataHWrite(dataHandler, (Ptr)Buffer, mCurrentPosition, Size, NULL, 0);
	}

	if (err) {
		throw CRTError("Error writing data", err);
	}
	mCurrentPosition += Size;

	// does QT tell us how much it writes?
	return Size;
}

uint64 DataHandlerCallback::getFilePointer()
{
	return mCurrentPosition;
}

void DataHandlerCallback::close()
{
	if (closeHandler) {
		if (aMode == MODE_READ)
			DataHCloseForRead(dataHandler);
		else if (aMode == MODE_WRITE)
			DataHCloseForWrite(dataHandler);
		dataHandler = NULL;
	}
}

SInt64 DataHandlerCallback::getFileSize()
{
	ComponentResult err = noErr;
	wide wideFilesize;

	err = DataHGetFileSize64(dataHandler, &wideFilesize);
	if (err == noErr) {
		supportsWideOffsets = true;
		filesize = WideToSInt64(wideFilesize);
	} else {
		long size32;
		supportsWideOffsets = false;
		DataHGetFileSize(dataHandler, &size32);
		filesize = size32;
	}

	return filesize;
}
<|endoftext|>


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

// POSIX
#include <poll.h>

// STL
#include <memory>

// po6
#include <po6/time.h>

// BusyBee
#include <busybee_constants.h>
#include <busybee_single.h>

// Replicant
#include "common/bootstrap.h"
#include "common/configuration.h"
#include "common/network_msgtype.h"

using replicant::bootstrap;

bool
bootstrap :: parse_hosts(const char* conn_str,
                         std::vector<po6::net::hostname>* hosts)
{
    const size_t conn_str_sz = strlen(conn_str);
    std::vector<char> cs(conn_str, conn_str + conn_str_sz + 1);
    char* ptr = &cs[0];
    char* const end = ptr + conn_str_sz;

    while (ptr < end)
    {
        char* eoh = strchr(ptr, ',');
        eoh = eoh ? eoh : end;
        *eoh = '\0';
        char* colon = strrchr(ptr, ':');

        if (colon == NULL)
        {
            hosts->push_back(po6::net::hostname(ptr, 1982));
            ptr = eoh + 1;
            continue;
        }

        char* tmp = NULL;
        errno = 0;
        unsigned long port = strtoul(colon + 1, &tmp, 10);

        if (errno != 0)
        {
            return false;
        }

        std::string host;

        if (*ptr == '[' && colon > ptr && *(colon - 1) == ']')
        {
            host.assign(ptr + 1, colon - 1);
        }
        else
        {
            host.assign(ptr, colon);
        }

        hosts->push_back(po6::net::hostname(host.c_str(), port));
        ptr = eoh + 1;
    }

    return true;
}

std::string
bootstrap :: conn_str(const po6::net::hostname* hns, size_t hns_sz)
{
    std::ostringstream ostr;

    for (size_t i = 0; i < hns_sz; ++i)
    {
        if (i > 0)
        {
            ostr << ",";
        }

        ostr << hns[i];
    }

    return ostr.str();
}

bootstrap :: bootstrap()
    : m_hosts()
    , m_valid(true)
{
}

bootstrap :: bootstrap(const char* host, uint16_t port)
    : m_hosts()
    , m_valid(true)
{
    m_hosts.push_back(po6::net::hostname(host, port));
}

bootstrap :: bootstrap(const char* cs)
    : m_hosts()
    , m_valid(true)
{
    m_valid = parse_hosts(cs, &m_hosts);
}

bootstrap :: bootstrap(const char* host, uint16_t port, const char* cs)
    : m_hosts()
    , m_valid(true)
{
    m_valid = parse_hosts(cs, &m_hosts);
    m_hosts.push_back(po6::net::hostname(host, port));
}

bootstrap :: bootstrap(const std::vector<po6::net::hostname>& h)
    : m_hosts(h)
    , m_valid(true)
{
}

bootstrap :: bootstrap(const bootstrap& other)
    : m_hosts(other.m_hosts)
    , m_valid(other.m_valid)
{
}

bootstrap :: ~bootstrap() throw ()
{
}

bool
bootstrap :: valid() const
{
    if (!m_valid)
    {
        return false;
    }

    for (size_t i = 0; i < m_hosts.size(); ++i)
    {
        if (m_hosts[i].port <= 0 || m_hosts[i].port >= (1 << 16))
        {
            return false;
        }
    }

    return true;
}

#define MILLIS (1000ULL * 1000ULL)

replicant_returncode
bootstrap :: do_it(int timeout, configuration* config, e::error* err) const
{
    if (!m_valid)
    {
        err->set_loc(__FILE__, __LINE__);
        err->set_msg() << "invalid bootstrap connection string";
        return REPLICANT_COMM_FAILED;
    }

    if (m_hosts.empty())
    {
        err->set_loc(__FILE__, __LINE__);
        err->set_msg() << "no hosts to bootstrap from";
        return REPLICANT_COMM_FAILED;
    }

    std::vector<e::compat::shared_ptr<busybee_single> > conns;
    conns.resize(m_hosts.size());

    int64_t now = po6::monotonic_time();
    const int64_t target = now + timeout * MILLIS;
    replicant_returncode rc;

    while (timeout < 0 || now < target)
    {
        for (size_t i = 0; i < m_hosts.size(); ++i)
        {
            if (conns[i].get())
            {
                continue;
            }

            conns[i].reset(new busybee_single(m_hosts[i]));
            const size_t sz = BUSYBEE_HEADER_SIZE
                            + pack_size(REPLNET_BOOTSTRAP);
            std::auto_ptr<e::buffer> msg(e::buffer::create(sz));
            msg->pack_at(BUSYBEE_HEADER_SIZE) << REPLNET_BOOTSTRAP;

            switch (conns[i]->send(msg))
            {
                case BUSYBEE_SUCCESS:
                    break;
                case BUSYBEE_TIMEOUT:
                    err->set_loc(__FILE__, __LINE__);
                    err->set_msg() << "timed out connecting to " << m_hosts[i];
                    rc = REPLICANT_TIMEOUT;
                    conns[i].reset();
                    break;
                case BUSYBEE_SHUTDOWN:
                case BUSYBEE_POLLFAILED:
                case BUSYBEE_DISRUPTED:
                case BUSYBEE_ADDFDFAIL:
                case BUSYBEE_EXTERNAL:
                case BUSYBEE_INTERRUPTED:
                    err->set_loc(__FILE__, __LINE__);
                    err->set_msg() << "communication error with " << m_hosts[i];
                    rc = REPLICANT_COMM_FAILED;
                    conns[i].reset();
                    break;
                default:
                    abort();
            }
        }

        bool failures = false;
        std::vector<pollfd> pfds;
        pfds.resize(m_hosts.size());

        for (size_t i = 0; i < m_hosts.size(); ++i)
        {
            if (!conns[i].get())
            {
                failures = true;
                pfds[i].fd = -1;
            }
            else
            {
                pfds[i].fd = conns[i]->poll_fd();
                pfds[i].events = POLLIN|POLLOUT|POLLHUP|POLLERR;
                pfds[i].revents = 0;
            }
        }

        const int64_t remain = (target - now) / MILLIS;
        const int this_timeout = timeout < 0 ? -1 : remain;
        int ret = poll(&pfds[0], pfds.size(), failures ? std::min(this_timeout, 100) : this_timeout);
        now = po6::monotonic_time();

        if (ret < 0)
        {
            int e = errno;
            err->set_loc(__FILE__, __LINE__);
            err->set_msg() << "poll failed: " << po6::strerror(e) << " [" << po6::strerrno(e) << "]";
            errno = e;
            return REPLICANT_SEE_ERRNO;
        }
        else if (ret == 0)
        {
            continue;
        }

        assert(ret > 0);
        size_t idx = m_hosts.size();

        for (size_t i = 0; i < m_hosts.size(); ++i)
        {
            if (pfds[i].revents != 0)
            {
                idx = i;
                break;
            }
        }

        std::auto_ptr<e::buffer> msg;
        conns[idx]->set_timeout(0);

        switch (conns[idx]->recv(&msg))
        {
            case BUSYBEE_SUCCESS:
                break;
            case BUSYBEE_TIMEOUT:
                break;
            case BUSYBEE_SHUTDOWN:
            case BUSYBEE_POLLFAILED:
            case BUSYBEE_DISRUPTED:
            case BUSYBEE_ADDFDFAIL:
            case BUSYBEE_EXTERNAL:
            case BUSYBEE_INTERRUPTED:
                err->set_loc(__FILE__, __LINE__);
                err->set_msg() << "communication error with " << m_hosts[idx];
                rc = REPLICANT_COMM_FAILED;
                conns[idx].reset();
                break;
            default:
                abort();
        }

        if (!msg.get())
        {
            continue;
        }

        network_msgtype mt = REPLNET_NOP;
        e::unpacker up = msg->unpack_from(BUSYBEE_HEADER_SIZE);
        up >> mt >> *config;

        if (up.error() || mt != REPLNET_BOOTSTRAP || !config->validate())
        {
            err->set_loc(__FILE__, __LINE__);
            err->set_msg() << "received a malformed bootstrap message from " << m_hosts[idx];
            rc = REPLICANT_COMM_FAILED;
            conns[idx].reset();
            continue;
        }

        return REPLICANT_SUCCESS;
    }

    // return the error corresponding to the last failure
    return rc;
}

std::string
bootstrap :: conn_str() const
{
    return conn_str(&m_hosts[0], m_hosts.size());
}

bootstrap&
bootstrap :: operator = (const bootstrap& rhs)
{
    if (this != &rhs)
    {
        m_hosts = rhs.m_hosts;
        m_valid = rhs.m_valid;
    }

    return *this;
}

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

// POSIX
#include <poll.h>

// STL
#include <memory>

// po6
#include <po6/time.h>

// BusyBee
#include <busybee_constants.h>
#include <busybee_single.h>

// Replicant
#include "common/bootstrap.h"
#include "common/configuration.h"
#include "common/network_msgtype.h"

using replicant::bootstrap;

bool
bootstrap :: parse_hosts(const char* conn_str,
                         std::vector<po6::net::hostname>* hosts)
{
    const size_t conn_str_sz = strlen(conn_str);
    std::vector<char> cs(conn_str, conn_str + conn_str_sz + 1);
    char* ptr = &cs[0];
    char* const end = ptr + conn_str_sz;

    while (ptr < end)
    {
        char* eoh = strchr(ptr, ',');
        eoh = eoh ? eoh : end;
        *eoh = '\0';
        char* colon = strrchr(ptr, ':');

        if (colon == NULL)
        {
            hosts->push_back(po6::net::hostname(ptr, 1982));
            ptr = eoh + 1;
            continue;
        }

        char* tmp = NULL;
        errno = 0;
        unsigned long port = strtoul(colon + 1, &tmp, 10);

        if (errno != 0)
        {
            return false;
        }

        std::string host;

        if (*ptr == '[' && colon > ptr && *(colon - 1) == ']')
        {
            host.assign(ptr + 1, colon - 1);
        }
        else
        {
            host.assign(ptr, colon);
        }

        hosts->push_back(po6::net::hostname(host.c_str(), port));
        ptr = eoh + 1;
    }

    return true;
}

std::string
bootstrap :: conn_str(const po6::net::hostname* hns, size_t hns_sz)
{
    std::ostringstream ostr;

    for (size_t i = 0; i < hns_sz; ++i)
    {
        if (i > 0)
        {
            ostr << ",";
        }

        ostr << hns[i];
    }

    return ostr.str();
}

bootstrap :: bootstrap()
    : m_hosts()
    , m_valid(true)
{
}

bootstrap :: bootstrap(const char* host, uint16_t port)
    : m_hosts()
    , m_valid(true)
{
    m_hosts.push_back(po6::net::hostname(host, port));
}

bootstrap :: bootstrap(const char* cs)
    : m_hosts()
    , m_valid(true)
{
    m_valid = parse_hosts(cs, &m_hosts);
}

bootstrap :: bootstrap(const char* host, uint16_t port, const char* cs)
    : m_hosts()
    , m_valid(true)
{
    m_valid = parse_hosts(cs, &m_hosts);
    m_hosts.push_back(po6::net::hostname(host, port));
}

bootstrap :: bootstrap(const std::vector<po6::net::hostname>& h)
    : m_hosts(h)
    , m_valid(true)
{
}

bootstrap :: bootstrap(const bootstrap& other)
    : m_hosts(other.m_hosts)
    , m_valid(other.m_valid)
{
}

bootstrap :: ~bootstrap() throw ()
{
}

bool
bootstrap :: valid() const
{
    if (!m_valid)
    {
        return false;
    }

    for (size_t i = 0; i < m_hosts.size(); ++i)
    {
        if (m_hosts[i].port <= 0 || m_hosts[i].port >= (1 << 16))
        {
            return false;
        }
    }

    return true;
}

#define MILLIS (1000ULL * 1000ULL)

replicant_returncode
bootstrap :: do_it(int timeout, configuration* config, e::error* err) const
{
    if (!m_valid)
    {
        err->set_loc(__FILE__, __LINE__);
        err->set_msg() << "invalid bootstrap connection string";
        return REPLICANT_COMM_FAILED;
    }

    if (m_hosts.empty())
    {
        err->set_loc(__FILE__, __LINE__);
        err->set_msg() << "no hosts to bootstrap from";
        return REPLICANT_COMM_FAILED;
    }

    std::vector<e::compat::shared_ptr<busybee_single> > conns;
    conns.resize(m_hosts.size());

    int64_t now = po6::monotonic_time();
    const int64_t target = now + timeout * MILLIS;
    replicant_returncode rc = REPLICANT_TIMEOUT;
    err->set_loc(__FILE__, __LINE__);
    err->set_msg() << "timed out connecting to the cluster";

    while (timeout < 0 || now < target)
    {
        for (size_t i = 0; i < m_hosts.size(); ++i)
        {
            if (conns[i].get())
            {
                continue;
            }

            conns[i].reset(new busybee_single(m_hosts[i]));
            const size_t sz = BUSYBEE_HEADER_SIZE
                            + pack_size(REPLNET_BOOTSTRAP);
            std::auto_ptr<e::buffer> msg(e::buffer::create(sz));
            msg->pack_at(BUSYBEE_HEADER_SIZE) << REPLNET_BOOTSTRAP;

            switch (conns[i]->send(msg))
            {
                case BUSYBEE_SUCCESS:
                    break;
                case BUSYBEE_TIMEOUT:
                    err->set_loc(__FILE__, __LINE__);
                    err->set_msg() << "timed out connecting to " << m_hosts[i];
                    rc = REPLICANT_TIMEOUT;
                    conns[i].reset();
                    break;
                case BUSYBEE_SHUTDOWN:
                case BUSYBEE_POLLFAILED:
                case BUSYBEE_DISRUPTED:
                case BUSYBEE_ADDFDFAIL:
                case BUSYBEE_EXTERNAL:
                case BUSYBEE_INTERRUPTED:
                    err->set_loc(__FILE__, __LINE__);
                    err->set_msg() << "communication error with " << m_hosts[i];
                    rc = REPLICANT_COMM_FAILED;
                    conns[i].reset();
                    break;
                default:
                    abort();
            }
        }

        bool failures = false;
        std::vector<pollfd> pfds;
        pfds.resize(m_hosts.size());

        for (size_t i = 0; i < m_hosts.size(); ++i)
        {
            if (!conns[i].get())
            {
                failures = true;
                pfds[i].fd = -1;
            }
            else
            {
                pfds[i].fd = conns[i]->poll_fd();
                pfds[i].events = POLLIN|POLLOUT|POLLHUP|POLLERR;
                pfds[i].revents = 0;
            }
        }

        const int64_t remain = (target - now) / MILLIS;
        const int this_timeout = timeout < 0 ? -1 : remain;
        int ret = poll(&pfds[0], pfds.size(), failures ? std::min(this_timeout, 100) : this_timeout);
        now = po6::monotonic_time();

        if (ret < 0)
        {
            int e = errno;
            err->set_loc(__FILE__, __LINE__);
            err->set_msg() << "poll failed: " << po6::strerror(e) << " [" << po6::strerrno(e) << "]";
            errno = e;
            return REPLICANT_SEE_ERRNO;
        }
        else if (ret == 0)
        {
            continue;
        }

        assert(ret > 0);
        size_t idx = m_hosts.size();

        for (size_t i = 0; i < m_hosts.size(); ++i)
        {
            if (pfds[i].revents != 0)
            {
                idx = i;
                break;
            }
        }

        std::auto_ptr<e::buffer> msg;
        conns[idx]->set_timeout(0);

        switch (conns[idx]->recv(&msg))
        {
            case BUSYBEE_SUCCESS:
                break;
            case BUSYBEE_TIMEOUT:
                break;
            case BUSYBEE_SHUTDOWN:
            case BUSYBEE_POLLFAILED:
            case BUSYBEE_DISRUPTED:
            case BUSYBEE_ADDFDFAIL:
            case BUSYBEE_EXTERNAL:
            case BUSYBEE_INTERRUPTED:
                err->set_loc(__FILE__, __LINE__);
                err->set_msg() << "communication error with " << m_hosts[idx];
                rc = REPLICANT_COMM_FAILED;
                conns[idx].reset();
                break;
            default:
                abort();
        }

        if (!msg.get())
        {
            continue;
        }

        network_msgtype mt = REPLNET_NOP;
        e::unpacker up = msg->unpack_from(BUSYBEE_HEADER_SIZE);
        up >> mt >> *config;

        if (up.error() || mt != REPLNET_BOOTSTRAP || !config->validate())
        {
            err->set_loc(__FILE__, __LINE__);
            err->set_msg() << "received a malformed bootstrap message from " << m_hosts[idx];
            rc = REPLICANT_COMM_FAILED;
            conns[idx].reset();
            continue;
        }

        return REPLICANT_SUCCESS;
    }

    // return the error corresponding to the last failure
    return rc;
}

std::string
bootstrap :: conn_str() const
{
    return conn_str(&m_hosts[0], m_hosts.size());
}

bootstrap&
bootstrap :: operator = (const bootstrap& rhs)
{
    if (this != &rhs)
    {
        m_hosts = rhs.m_hosts;
        m_valid = rhs.m_valid;
    }

    return *this;
}

std::ostream&
replicant :: operator << (std::ostream& lhs, const bootstrap& rhs)
{
    return lhs << rhs.conn_str();
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------------------------------------
//* Copyright  2010-2013 Immersive and Creative Technologies Lab, Cyprus University of Technology           *
//* Link: http://ict.cut.ac.cy                                                                               *
//* Software developer(s): Kyriakos Herakleous                                                               *
//* Researcher(s): Kyriakos Herakleous, Charalambos Poullis                                                  *
//*                                                                                *
//* This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.*
//* Link: http://creativecommons.org/licenses/by-nc-sa/3.0/deed.en_US                                        *
//------------------------------------------------------------------------------------------------------------

#include "StdAfx.h"
#include "PointCloudImage.h"

PointCloudImage::PointCloudImage(int imageW,int imageH, bool colorFlag_)
{
	w=imageW;
	h=imageH;
	colorFlag = colorFlag_;

	points = cv::Mat(h,w,CV_32FC3);

	if(colorFlag==true)
	{

		color = cv::Mat(h,w,CV_32FC3,cv::Scalar(0));
	}
	else
		color = NULL;

	numOfPointsForPixel =  cv::Mat(h,w,CV_8U,cv::Scalar(0));
}

PointCloudImage::~PointCloudImage(void)
{

}

bool PointCloudImage::hasColor()
{
	return colorFlag;
}

bool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)
{
	if(i_w>w || j_h>h)
		return false;

	setPoint(i_w,j_h,point);

	Utilities::matSet3D(color,i_w,j_h,colorBGR);

	return true;
}

bool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point)
{
	if(i_w>w || j_h>h)
		return false;

	Utilities::matSet3D(points,i_w,j_h,(cv::Vec3f)point);
	Utilities::matSet2D(numOfPointsForPixel,i_w,j_h,1);

	return true;
}

bool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut, cv::Vec3f &colorOut)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num > 0)
	{

		pointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) / (float) num);

		if(!color.empty())
		{
			colorOut = (cv::Point3f) (Utilities::matGet3D(color,i_w,j_h) / (float) num);
		}
		else
		{
			return false;
		}

		return true;
	}
	else
	{
		return false;
	}

}

bool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num > 0)
	{
		pointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) / (float) num);
		return true;
	}
	else
	{
		return false;
	}

}

bool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num == 0)
		return setPoint(i_w,j_h,point,colorBGR);

	addPoint(i_w,j_h,point);

	if(!color.empty())
	{
		cv::Vec3f c = Utilities::matGet3D(color,i_w,j_h);

		Utilities::matSet3D(color,i_w,j_h,colorBGR + c);
	}
	else
	{
		return false;
	}

	return true;
}

bool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num == 0)
		return setPoint(i_w,j_h,point);

	cv::Point3f p = Utilities::matGet3D(points,i_w,j_h);
	Utilities::matSet3D(points,i_w,j_h,(cv::Vec3f)(point + p));

	numOfPointsForPixel.at<uchar>(j_h,i_w) = num + 1;

	return true;
}

void PointCloudImage::exportXYZ(char path[], bool exportOffPixels, bool colorFlag)
{

	std::ofstream out;
	out.open(path);

	int load;

	cv::Point3f p;
	cv::Vec3f c;

	std::cout<<"Export "<< path << "...";

	for(int i = 0; i<w; i++)
	{
		for(int j = 0; j<h; j++)
		{
			uchar num = numOfPointsForPixel.at<uchar>(j,i);

			if(!exportOffPixels && num == 0)
				continue;

			getPoint(i,j,p,c);

			if(exportOffPixels && num == 0)
			{
				p = cv::Point3f(0,0,0);
				c = cv::Point3f(0,0,0);
			}

			out<<p.x<<" "<<p.y<<" "<<p.z;

			if(colorFlag && !color.empty())
			{
				out<<" "<<c[2]<<" "<<c[1]<<" "<<c[0]<<"\n";
			}
			else
			{
				out<<"\n";
			}
		}
	}

	out.close();
	std::cout<<"done\n";
}

void PointCloudImage::exportNumOfPointsPerPixelImg(char path[])
{

	cv::Mat projToCamRays(cvSize(w, h), CV_8U);

	float max=0;

	int maxX,maxY;

	for(int i=0; i<w; i++)
	{
		for(int j=0; j<h; j++)
		{
			uchar num = numOfPointsForPixel.at<uchar>(j,i);

			if(num > max)
			{
				max = num;
				maxX=i;
				maxY=j;
			}
		}
	}

	for(int i=0; i<w; i++)
	{
		for(int j=0; j<h; j++)
		{

			uchar num = numOfPointsForPixel.at<uchar>(j,i);
			Utilities::matSet2D(projToCamRays,i,j, num/(float)(max*255.0));

		}
	}

	cv::imwrite("reconstruction/projToCamRays.png",projToCamRays);

	std::ofstream out1;
	std::stringstream txt;
	txt<<path<<".txt";
	out1.open(txt.str().c_str() );

	out1<< "black color = 0\nwhite color = "<< max <<"\nmax Pixel: ("<<maxX<<","<<maxY<<")";

	out1.close();

}

int PointCloudImage::getWidth()
{
	return w;
}

int PointCloudImage::getHeight()
{
	return h;
}

<commit_msg>Update PointCloudImage.cpp<commit_after>//------------------------------------------------------------------------------------------------------------
//* Copyright © 2010-2015 Immersive and Creative Technologies Lab, Cyprus University of Technology           *
//* Link: http://www.theICTlab.org                                                                           *
//* Software developer(s): Kyriakos Herakleous                                                               *
//* Researcher(s): Kyriakos Herakleous, Charalambos Poullis                                                  *
//*                                                                                *
//* License: Check the file License.md                                                                       *
//------------------------------------------------------------------------------------------------------------

#include "StdAfx.h"
#include "PointCloudImage.h"

PointCloudImage::PointCloudImage(int imageW,int imageH, bool colorFlag_)
{
	w=imageW;
	h=imageH;
	colorFlag = colorFlag_;

	points = cv::Mat(h,w,CV_32FC3);

	if(colorFlag==true)
	{

		color = cv::Mat(h,w,CV_32FC3,cv::Scalar(0));
	}
	else
		color = NULL;

	numOfPointsForPixel =  cv::Mat(h,w,CV_8U,cv::Scalar(0));
}

PointCloudImage::~PointCloudImage(void)
{

}

bool PointCloudImage::hasColor()
{
	return colorFlag;
}

bool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)
{
	if(i_w>w || j_h>h)
		return false;

	setPoint(i_w,j_h,point);

	Utilities::matSet3D(color,i_w,j_h,colorBGR);

	return true;
}

bool PointCloudImage::setPoint(int i_w, int j_h, cv::Point3f point)
{
	if(i_w>w || j_h>h)
		return false;

	Utilities::matSet3D(points,i_w,j_h,(cv::Vec3f)point);
	Utilities::matSet2D(numOfPointsForPixel,i_w,j_h,1);

	return true;
}

bool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut, cv::Vec3f &colorOut)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num > 0)
	{

		pointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) / (float) num);

		if(!color.empty())
		{
			colorOut = (cv::Point3f) (Utilities::matGet3D(color,i_w,j_h) / (float) num);
		}
		else
		{
			return false;
		}

		return true;
	}
	else
	{
		return false;
	}

}

bool PointCloudImage::getPoint(int i_w, int j_h, cv::Point3f &pointOut)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num > 0)
	{
		pointOut = (cv::Point3f) (Utilities::matGet3D(points,i_w,j_h) / (float) num);
		return true;
	}
	else
	{
		return false;
	}

}

bool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point, cv::Vec3f colorBGR)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num == 0)
		return setPoint(i_w,j_h,point,colorBGR);

	addPoint(i_w,j_h,point);

	if(!color.empty())
	{
		cv::Vec3f c = Utilities::matGet3D(color,i_w,j_h);

		Utilities::matSet3D(color,i_w,j_h,colorBGR + c);
	}
	else
	{
		return false;
	}

	return true;
}

bool PointCloudImage::addPoint(int i_w, int j_h, cv::Point3f point)
{
	if(i_w>w || j_h>h)
		return false;

	uchar num = numOfPointsForPixel.at<uchar>(j_h,i_w);

	if(num == 0)
		return setPoint(i_w,j_h,point);

	cv::Point3f p = Utilities::matGet3D(points,i_w,j_h);
	Utilities::matSet3D(points,i_w,j_h,(cv::Vec3f)(point + p));

	numOfPointsForPixel.at<uchar>(j_h,i_w) = num + 1;

	return true;
}

void PointCloudImage::exportXYZ(char path[], bool exportOffPixels, bool colorFlag)
{

	std::ofstream out;
	out.open(path);

	int load;

	cv::Point3f p;
	cv::Vec3f c;

	std::cout<<"Export "<< path << "...";

	for(int i = 0; i<w; i++)
	{
		for(int j = 0; j<h; j++)
		{
			uchar num = numOfPointsForPixel.at<uchar>(j,i);

			if(!exportOffPixels && num == 0)
				continue;

			getPoint(i,j,p,c);

			if(exportOffPixels && num == 0)
			{
				p = cv::Point3f(0,0,0);
				c = cv::Point3f(0,0,0);
			}

			out<<p.x<<" "<<p.y<<" "<<p.z;

			if(colorFlag && !color.empty())
			{
				out<<" "<<c[2]<<" "<<c[1]<<" "<<c[0]<<"\n";
			}
			else
			{
				out<<"\n";
			}
		}
	}

	out.close();
	std::cout<<"done\n";
}

void PointCloudImage::exportNumOfPointsPerPixelImg(char path[])
{

	cv::Mat projToCamRays(cvSize(w, h), CV_8U);

	float max=0;

	int maxX,maxY;

	for(int i=0; i<w; i++)
	{
		for(int j=0; j<h; j++)
		{
			uchar num = numOfPointsForPixel.at<uchar>(j,i);

			if(num > max)
			{
				max = num;
				maxX=i;
				maxY=j;
			}
		}
	}

	for(int i=0; i<w; i++)
	{
		for(int j=0; j<h; j++)
		{

			uchar num = numOfPointsForPixel.at<uchar>(j,i);
			Utilities::matSet2D(projToCamRays,i,j, num/(float)(max*255.0));

		}
	}

	cv::imwrite("reconstruction/projToCamRays.png",projToCamRays);

	std::ofstream out1;
	std::stringstream txt;
	txt<<path<<".txt";
	out1.open(txt.str().c_str() );

	out1<< "black color = 0\nwhite color = "<< max <<"\nmax Pixel: ("<<maxX<<","<<maxY<<")";

	out1.close();

}

int PointCloudImage::getWidth()
{
	return w;
}

int PointCloudImage::getHeight()
{
	return h;
}

<|endoftext|>


<commit_before>// C/C++ File
// AUTHOR:   cxd
// FILE:     genW.cpp
// ROLE:     TODO (some explanation)
// CREATED:  2014-06-30 14:05:48
// MODIFIED: 2014-06-30 14:27:15

#include <iostream>
#include <random>

using namespace std;

int main()
{
    const int MAX = 50;

    for (int i = 0; i < MAX; ++i)
    {
	cout << 25.0 << endl;
    }

    for (int i = 0; i < MAX; ++i)
    {
	cout << double(i+1) << endl;
    }

    for (int i = MAX; i >=0; --i)
    {
	cout << double(i+1) << endl;
    }

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(1, MAX);
    for (int i = 0; i < MAX; ++i)
    {
        std::cout << dis(gen) << endl;
    }

    return 0;
}

<commit_msg>Fixed cut/paste bug<commit_after>// C/C++ File
// AUTHOR:   cxd
// FILE:     genW.cpp
// ROLE:     TODO (some explanation)
// CREATED:  2014-06-30 14:05:48
// MODIFIED: 2014-07-06 14:24:39

#include <iostream>
#include <random>

using namespace std;

int main()
{
    const int MAX = 50;

    for (int i = 0; i < MAX; ++i)
    {
	cout << 25.0 << endl;
    }

    for (int i = 0; i < MAX; ++i)
    {
	cout << double(i+1) << endl;
    }

    for (int i = MAX; i > 0; --i)
    {
	cout << double(i) << endl;
    }

    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(1, MAX);
    for (int i = 0; i < MAX; ++i)
    {
        std::cout << dis(gen) << endl;
    }

    return 0;
}

<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	I/O ユーティリティー @n
			Copyright 2013 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ８ビット書き込み
		@param[in]	adr		書き込みアドレス
		@param[in]	data	書き込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void wr8_(uint32_t adr, uint8_t data) {
		*reinterpret_cast<volatile uint8_t*>(adr) = data;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ８ビット読み込み
		@param[in]	adr		読み込みアドレス
		@param[in]	data	読み込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline uint8_t rd8_(uint32_t adr) {
		return *reinterpret_cast<volatile uint8_t*>(adr);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １６ビット書き込み
		@param[in]	adr		書き込みアドレス
		@param[in]	data	書き込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void wr16_(uint32_t adr, uint16_t data) {
		*reinterpret_cast<volatile uint16_t*>(adr) = data;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １６ビット読み込み
		@param[in]	adr		読み込みアドレス
		@param[in]	data	読み込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline uint16_t rd16_(uint32_t adr) {
		return *reinterpret_cast<volatile uint16_t*>(adr);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ３２ビット書き込み
		@param[in]	adr		書き込みアドレス
		@param[in]	data	書き込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void wr32_(uint32_t adr, uint32_t data) {
		*reinterpret_cast<volatile uint32_t*>(adr) = data;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ３２ビット読み込み
		@param[in]	adr		読み込みアドレス
		@param[in]	data	読み込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline uint32_t rd32_(uint32_t adr) {
		return *reinterpret_cast<volatile uint32_t*>(adr);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  8 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t adr>
	struct io8 {
		typedef uint8_t value_type;

		static void write(uint8_t data) { wr8_(adr, data); }
		static uint8_t read() { return rd8_(adr); }

		void operator = (value_type data) const { write(data); }
		value_type operator () () const { return read(); }
		void operator |= (value_type data) const { write(read() | data); }
		void operator &= (value_type data) const { write(read() & data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  8 bits アクセス・テンプレート(RO)
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t adr>
	struct io8_ro {
		typedef uint8_t value_type;

		static uint8_t read() { return rd8_(adr); }

		value_type operator () () const { return read(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  16 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t adr>
	struct io16 {
		typedef uint16_t value_type;

		static void write(uint16_t data) { wr16_(adr, data); }
		static uint16_t read() { return rd16_(adr); }

		void operator = (value_type data) const { write(data); }
		value_type operator () () const { return read(); }
		void operator |= (value_type data) const { write(read() | data); }
		void operator &= (value_type data) const { write(read() & data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  32 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t adr>
	struct io32 {
		typedef uint32_t	value_type;

		static void write(uint32_t data) { wr32_(adr, data); }
		static uint32_t read() { return rd32_(adr); }

		void operator = (value_type data) const { write(data); }
		value_type operator () () const { return read(); }
		void operator |= (value_type data) const { write(read() | data); }
		void operator &= (value_type data) const { write(read() & data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １ビット・アクセス・テンプレート(R/W direct)
		@param[in]	T	アクセス・クラス
		@param[in]	pos	ビット位置
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, uint8_t pos>
	struct bit {
		static bool get() {
			return (T::read() & (1 << pos)) != 0;
		}
		static void set(bool v) {
			T::write(v << pos);
		}

	    typename T::value_type b(bool f = true) const {
			return f << pos;
		}

		void operator = (bool v) const { set(v); }
		bool operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １ビット・アクセス・テンプレート(R/W)
		@param[in]	T	アクセス・クラス
		@param[in]	pos	ビット位置
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, uint8_t pos>
	struct bit_t {
		static bool get() {
			return (T::read() & (1 << pos)) != 0;
		}
		static void set(bool v) {
			T::write((T::read() & ~(1 << pos)) | (v << pos));
		}

	    typename T::value_type b(bool v = true) const {
			return v << pos;
		}

		void operator = (bool v) const { set(v); }
		bool operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ビット・アクセス・テンプレート(R/W direct)
		@param[in]	T	アクセス・クラス
		@param[in]	pos	初期位置
		@param[in]	len	ビット幅
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, uint8_t pos, uint8_t len>
	struct bits {
		static typename T::value_type get() {
			return (T::read() >> pos) & ((1 << len) - 1);
		}
		static void set(typename T::value_type v) {
			T::write(v << pos);
		}

	    typename T::value_type b(typename T::value_type v) const { return v << pos; }

		void operator = (typename T::value_type v) const { set(v); }
		typename T::value_type operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ビット・アクセス・テンプレート(R/W)
		@param[in]	T	アクセス・クラス
		@param[in]	pos	初期位置
		@param[in]	len	ビット幅
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, uint8_t pos, uint8_t len>
	struct bits_t {
		static typename T::value_type get() {
			return (T::read() >> pos) & ((1 << len) - 1);
		}
		static void set(typename T::value_type v) {
			typename T::value_type m = ((1 << static_cast<typename T::value_type>(len)) - 1) << pos;
			T::write((T::read() & ~m) | (v << pos));
		}

	    typename T::value_type b(typename T::value_type v) const { return v << pos; }

		void operator = (typename T::value_type v) const { set(v); }
		typename T::value_type operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １ビット・アクセス・テンプレート(RO)
		@param[in]	T	アクセス・クラス
		@param[in]	pos	ビット位置
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, uint8_t pos>
	struct bit_ro_t {
		static bool get() {
			return T::read() & (1 << pos);
		}

		bool operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ビット・アクセス・テンプレート(RO)
		@param[in]	T	アクセス・クラス
		@param[in]	pos	初期位置
		@param[in]	len	ビット幅
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, uint8_t pos, uint8_t len>
	struct bits_ro_t {
		static typename T::value_type get() {
			return (T::read() >> pos) & ((1 << len) - 1);
		}
		typename T::value_type operator () () const { return get(); }
	};
}
<commit_msg>update I/O template<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	I/O ユーティリティー @n
			Copyright 2013,2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include <cstdint>

namespace device {

	typedef uint32_t address_type;

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ８ビット書き込み
		@param[in]	adr		書き込みアドレス
		@param[in]	data	書き込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void wr8_(address_type adr, uint8_t data) {
		*reinterpret_cast<volatile uint8_t*>(adr) = data;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ８ビット読み込み
		@param[in]	adr		読み込みアドレス
		@param[in]	data	読み込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline uint8_t rd8_(address_type adr) {
		return *reinterpret_cast<volatile uint8_t*>(adr);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １６ビット書き込み
		@param[in]	adr		書き込みアドレス
		@param[in]	data	書き込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void wr16_(address_type adr, uint16_t data) {
		*reinterpret_cast<volatile uint16_t*>(adr) = data;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  １６ビット読み込み
		@param[in]	adr		読み込みアドレス
		@param[in]	data	読み込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline uint16_t rd16_(address_type adr) {
		return *reinterpret_cast<volatile uint16_t*>(adr);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ３２ビット書き込み
		@param[in]	adr		書き込みアドレス
		@param[in]	data	書き込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline void wr32_(address_type adr, uint32_t data) {
		*reinterpret_cast<volatile uint32_t*>(adr) = data;
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ３２ビット読み込み
		@param[in]	adr		読み込みアドレス
		@param[in]	data	読み込みデータ
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	static inline uint32_t rd32_(address_type adr) {
		return *reinterpret_cast<volatile uint32_t*>(adr);
	}

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read/Write 8 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct rw8_t {
		typedef uint8_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	data	書き込み値
		*/
		//-----------------------------------------------------------------//
		static void write(value_type data) { wr8_(adr, data); }

		//-----------------------------------------------------------------//
		/*!
			@brief 読み出し
			@return 読み出し値
		*/
		//-----------------------------------------------------------------//
		static value_type read() { return rd8_(adr); }

		void operator = (value_type data) const { write(data); }
		value_type operator () () const { return read(); }
		void operator |= (value_type data) const { write(read() | data); }
		void operator &= (value_type data) const { write(read() & data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read Only 8 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct ro8_t {
		typedef uint8_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief 読み出し
			@return 読み出し値
		*/
		//-----------------------------------------------------------------//
		static value_type read() { return rd8_(adr); }

		value_type operator () () const { return read(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Write Only 8 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct wo8_t {
		typedef uint8_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	data	書き込み値
		*/
		//-----------------------------------------------------------------//
		static void write(value_type data) { wr8_(adr, data); }

		void operator = (value_type data) const { write(data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read/Write 16 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct rw16_t {
		typedef uint16_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	data	書き込み値
		*/
		//-----------------------------------------------------------------//
		static void write(value_type data) { wr16_(adr, data); }

		//-----------------------------------------------------------------//
		/*!
			@brief 読み出し
			@return 読み出し値
		*/
		//-----------------------------------------------------------------//
		static value_type read() { return rd16_(adr); }

		void operator = (value_type data) const { write(data); }
		value_type operator () () const { return read(); }
		void operator |= (value_type data) const { write(read() | data); }
		void operator &= (value_type data) const { write(read() & data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read Only 16 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct ro16_t {
		typedef uint16_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief 読み出し
			@return 読み出し値
		*/
		//-----------------------------------------------------------------//
		static value_type read() { return rd16_(adr); }

		value_type operator () () const { return read(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Write Only 16 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct wo16_t {
		typedef uint16_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	data	書き込み値
		*/
		//-----------------------------------------------------------------//
		static void write(value_type data) { wr16_(adr, data); }

		void operator = (value_type data) const { write(data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read/Write 32 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct rw32_t {
		typedef uint32_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	data	書き込み値
		*/
		//-----------------------------------------------------------------//
		static void write(value_type data) { wr32_(adr, data); }

		//-----------------------------------------------------------------//
		/*!
			@brief 読み出し
			@return 読み出し値
		*/
		//-----------------------------------------------------------------//
		static value_type read() { return rd32_(adr); }

		void operator = (value_type data) const { write(data); }
		value_type operator () () const { return read(); }
		void operator |= (value_type data) const { write(read() | data); }
		void operator &= (value_type data) const { write(read() & data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read Only 32 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct ro32_t {
		typedef uint32_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief 読み出し
			@return 読み出し値
		*/
		//-----------------------------------------------------------------//
		static value_type read() { return rd32_(adr); }

		value_type operator () () const { return read(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Write Only 32 bits アクセス・テンプレート
		@param[in]	adr	アドレス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <address_type adr>
	struct wo32_t {
		typedef uint32_t value_type;

		//-----------------------------------------------------------------//
		/*!
			@brief  書き込み
			@param[in]	data	書き込み値
		*/
		//-----------------------------------------------------------------//
		static void write(value_type data) { wr32_(adr, data); }

		void operator = (value_type data) const { write(data); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ビット位置定義
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class bitpos : uint8_t {
		B0,		///< ビット０
		B1,		///< ビット１
		B2,		///< ビット２
		B3,		///< ビット３
		B4,		///< ビット４
		B5,		///< ビット５
		B6,		///< ビット６
		B7,		///< ビット７
		B8,		///< ビット８
		B9,		///< ビット９
		B10,	///< ビット１０
		B11,	///< ビット１１
		B12,	///< ビット１２
		B13,	///< ビット１３
		B14,	///< ビット１４
		B15,	///< ビット１５
		B16,	///< ビット１６
		B17,	///< ビット１７
		B18,	///< ビット１８
		B19,	///< ビット１９
		B20,	///< ビット２０
		B21,	///< ビット２１
		B22,	///< ビット２２
		B23,	///< ビット２３
		B24,	///< ビット２４
		B25,	///< ビット２５
		B26,	///< ビット２６
		B27,	///< ビット２７
		B28,	///< ビット２８
		B29,	///< ビット２９
		B30,	///< ビット３０
		B31,	///< ビット３１
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read/Write ビット・アクセス・テンプレート
		@param[in]	T	アクセス・クラス
		@param[in]	pos	ビット位置
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, bitpos pos>
	struct bit_rw_t {
		static bool get() {
			return (T::read() >> static_cast<typename T::value_type>(pos)) & 1;
		}
		static void set(bool v) {
			if(v) {
				T::write(T::read() | (1 << static_cast<typename T::value_type>(pos)));
			} else {
				T::write(T::read() & ~(1 << static_cast<typename T::value_type>(pos)));
			}
		}

	    typename T::value_type b() const {
			return 1 << static_cast<typename T::value_type>(pos);
		}

		void operator = (bool v) { set(v); }
		bool operator () () { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read/Write ビット・アクセス・テンプレート
		@param[in]	T	アクセス・クラス
		@param[in]	pos	初期ビット位置
		@param[in]	len	ビット幅
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, bitpos pos, uint8_t len>
	struct bits_rw_t {
		static typename T::value_type get() {
			return (T::read() >> static_cast<typename T::value_type>(pos)) & ((1 << len) - 1);
		}
		static void set(typename T::value_type v) {
			auto m = static_cast<typename T::value_type>(((1 << len) - 1) << static_cast<typename T::value_type>(pos));
			T::write((T::read() & ~m) | (static_cast<typename T::value_type>(v) << static_cast<typename T::value_type>(pos)));
		}

	    typename T::value_type b(typename T::value_type v) const {
			return (((1 << len) - 1) & v) << static_cast<typename T::value_type>(pos);
		}

		void operator = (typename T::value_type v) const { set(v); }
		typename T::value_type operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  Read ビット・アクセス・テンプレート
		@param[in]	T	アクセス・クラス
		@param[in]	pos	ビット位置
		@param[in]	len	ビット幅
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T, bitpos pos>
	struct bit_ro_t {
		static bool get() {
			return (T::read() >> static_cast<typename T::value_type>(pos)) & 1;
		}

	    typename T::value_type b() const {
			return 1 << static_cast<typename T::value_type>(pos);
		}

		bool operator () () const { return get(); }
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  標準 Read/Write アクセス・テンプレート
		@param[in]	T	アクセステンプレート
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T>
	struct basic_rw_t : public T {

		using T::operator =;
		using T::operator ();
		using T::operator |=;
		using T::operator &=;

		bit_rw_t<T, bitpos::B7> B7;	///< B7 アクセス
		bit_rw_t<T, bitpos::B6> B6;	///< B6 アクセス
		bit_rw_t<T, bitpos::B5> B5;	///< B5 アクセス
		bit_rw_t<T, bitpos::B4> B4;	///< B4 アクセス
		bit_rw_t<T, bitpos::B3> B3;	///< B3 アクセス
		bit_rw_t<T, bitpos::B2> B2;	///< B2 アクセス
		bit_rw_t<T, bitpos::B1> B1;	///< B1 アクセス
		bit_rw_t<T, bitpos::B0> B0;	///< B0 アクセス
	};

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  標準 Read アクセス・テンプレート
		@param[in]	T	アクセステンプレート
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class T>
	struct basic_ro_t : public T {

		using T::operator =;
		using T::operator ();
		using T::operator |=;
		using T::operator &=;

		bit_ro_t<T, bitpos::B7> B7;	///< B7 アクセス
		bit_ro_t<T, bitpos::B6> B6;	///< B6 アクセス
		bit_ro_t<T, bitpos::B5> B5;	///< B5 アクセス
		bit_ro_t<T, bitpos::B4> B4;	///< B4 アクセス
		bit_ro_t<T, bitpos::B3> B3;	///< B3 アクセス
		bit_ro_t<T, bitpos::B2> B2;	///< B2 アクセス
		bit_ro_t<T, bitpos::B1> B1;	///< B1 アクセス
		bit_ro_t<T, bitpos::B0> B0;	///< B0 アクセス
	};
}
<|endoftext|>


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

class Ring
{
    Ring *pNext;
    Ring* pPrev;    // zur Optimierung, damit das ein/ausketten schneller geht!

protected:
    Ring()          { pNext = this; pPrev = this; }
    Ring( Ring * );
public:
    virtual ~Ring();
    void MoveTo( Ring *pDestRing );
    void MoveRingTo( Ring *pDestRing );

    Ring* GetNext() const       { return pNext; }
    Ring* GetPrev() const       { return pPrev; }
};

#endif
<commit_msg>INTEGRATION: CWS swcolsel (1.2.708); FILE MERGED 2007/04/13 13:06:03 ama 1.2.708.1: Fix #1596#: Rectangular selection<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ring.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-22 15:28:11 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _RING_HXX
#define _RING_HXX

#include <swtypes.hxx>

class Ring
{
    Ring *pNext;
    Ring* pPrev;    // zur Optimierung, damit das ein/ausketten schneller geht!

protected:
    Ring()          { pNext = this; pPrev = this; }
    Ring( Ring * );
public:
    virtual ~Ring();
    void MoveTo( Ring *pDestRing );
    void MoveRingTo( Ring *pDestRing );

    Ring* GetNext() const       { return pNext; }
    Ring* GetPrev() const       { return pPrev; }

    sal_uInt32 numberOf() const;
};

#endif
<|endoftext|>


<commit_before>//******************************************************************************************************
//  SignalIndexCache.cpp - Gbtc
//
//  Copyright  2010, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  03/09/2012 - Stephen C. Wills
//       Generated original version of source code.
//
//******************************************************************************************************

#include "SignalIndexCache.h"

namespace tsf = TimeSeriesFramework;

// Adds a measurement key to the cache.
void tsf::Transport::SignalIndexCache::AddMeasurementKey(
	uint16_t signalIndex,
	tsf::Guid signalID,
	std::string source,
	uint32_t id)
{
	std::size_t vectorIndex = m_signalIDList.size();

	m_reference[signalIndex] = vectorIndex;
	m_signalIDList.push_back(signalID);
	m_sourceList.push_back(source);
	m_idList.push_back(id);

	m_signalIDCache[signalID] = signalIndex;
}

// Empties the cache.
void tsf::Transport::SignalIndexCache::Clear()
{
	m_reference.clear();
	m_signalIDList.clear();
	m_sourceList.clear();
	m_idList.clear();

	m_signalIDCache.clear();
}

// Gets the globally unique signal ID associated with the given 16-bit runtime ID.
tsf::Guid tsf::Transport::SignalIndexCache::GetSignalID(uint16_t signalIndex) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;
	return m_signalIDList[vectorIndex];
}

// Gets the first half of the human-readable measurement
// key associated with the given 16-bit runtime ID.
std::string tsf::Transport::SignalIndexCache::GetSource(uint16_t signalIndex) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;
	return m_sourceList[vectorIndex];
}

// Gets the second half of the human-readable measurement
// key associated with the given 16-bit runtime ID.
uint32_t tsf::Transport::SignalIndexCache::GetID(uint16_t signalIndex) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;
	return m_idList[vectorIndex];
}

// Gets the globally unique signal ID as well as the human-readable
// measurement key associated with the given 16-bit runtime ID.
void tsf::Transport::SignalIndexCache::GetMeasurementKey(
	uint16_t signalIndex,
	tsf::Guid& signalID,
	std::string& source,
	uint32_t& id) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;

	signalID = m_signalIDList[vectorIndex];
	source = m_sourceList[vectorIndex];
	id = m_idList[vectorIndex];
}

// Gets the 16-bit runtime ID associated with the given globally unique signal ID.
unsigned short TimeSeriesFramework::Transport::SignalIndexCache::GetSignalIndex(tsf::Guid signalID) const
{
	std::map<tsf::Guid, uint16_t>::iterator it;
	uint16_t signalIndex = 0xFFFF;

	it = m_signalIDCache.find(signalID);

	if(it != m_signalIDCache.end())
		signalIndex = it->second;

	return signalIndex;
}<commit_msg>TSFPlatformLibrary: Modified type of iterator to const_iterator in SignalIndexCache::GetSignalIndex.<commit_after>//******************************************************************************************************
//  SignalIndexCache.cpp - Gbtc
//
//  Copyright  2010, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the Eclipse Public License -v 1.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.opensource.org/licenses/eclipse-1.0.php
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  03/09/2012 - Stephen C. Wills
//       Generated original version of source code.
//
//******************************************************************************************************

#include "SignalIndexCache.h"

namespace tsf = TimeSeriesFramework;

// Adds a measurement key to the cache.
void tsf::Transport::SignalIndexCache::AddMeasurementKey(
	uint16_t signalIndex,
	tsf::Guid signalID,
	std::string source,
	uint32_t id)
{
	std::size_t vectorIndex = m_signalIDList.size();

	m_reference[signalIndex] = vectorIndex;
	m_signalIDList.push_back(signalID);
	m_sourceList.push_back(source);
	m_idList.push_back(id);

	m_signalIDCache[signalID] = signalIndex;
}

// Empties the cache.
void tsf::Transport::SignalIndexCache::Clear()
{
	m_reference.clear();
	m_signalIDList.clear();
	m_sourceList.clear();
	m_idList.clear();

	m_signalIDCache.clear();
}

// Gets the globally unique signal ID associated with the given 16-bit runtime ID.
tsf::Guid tsf::Transport::SignalIndexCache::GetSignalID(uint16_t signalIndex) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;
	return m_signalIDList[vectorIndex];
}

// Gets the first half of the human-readable measurement
// key associated with the given 16-bit runtime ID.
std::string tsf::Transport::SignalIndexCache::GetSource(uint16_t signalIndex) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;
	return m_sourceList[vectorIndex];
}

// Gets the second half of the human-readable measurement
// key associated with the given 16-bit runtime ID.
uint32_t tsf::Transport::SignalIndexCache::GetID(uint16_t signalIndex) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;
	return m_idList[vectorIndex];
}

// Gets the globally unique signal ID as well as the human-readable
// measurement key associated with the given 16-bit runtime ID.
void tsf::Transport::SignalIndexCache::GetMeasurementKey(
	uint16_t signalIndex,
	tsf::Guid& signalID,
	std::string& source,
	uint32_t& id) const
{
	std::size_t vectorIndex = m_reference.find(signalIndex)->second;

	signalID = m_signalIDList[vectorIndex];
	source = m_sourceList[vectorIndex];
	id = m_idList[vectorIndex];
}

// Gets the 16-bit runtime ID associated with the given globally unique signal ID.
unsigned short TimeSeriesFramework::Transport::SignalIndexCache::GetSignalIndex(tsf::Guid signalID) const
{
	std::map<tsf::Guid, uint16_t>::const_iterator it;
	uint16_t signalIndex = 0xFFFF;

	it = m_signalIDCache.find(signalID);

	if(it != m_signalIDCache.end())
		signalIndex = it->second;

	return signalIndex;
}<|endoftext|>


<commit_before>#pragma once

#include <array>
#include <cstddef>
#include <cstdint>

class CallbackQueue
{
private:
    using u8 = std::uint8_t;
    using u32 = std::uint32_t;
    u32 mFlags = 0u;

public:
    bool Empty() const { return mFlags == 0u; }

    u8 Size() const { return __builtin_popcount(mFlags); }

    void Push(u8 x)
    {
        assert(x < 27u);
        mFlags |= 1u << x;
    }

    void PushFlags(u32 flags) { mFlags |= flags; }

    u8 Pop()
    {
        if (Empty())
            return u8(255);

        u8 ret = __builtin_ctz(mFlags);
        PopElement(ret);

        return ret;
    }

    void PopElement(u8 element)
    {
        mFlags &= ~(1u << element);
    }
};
<commit_msg>CallbackQueue now 128 bits instead of 32 bits in preparation for cell-based processing instead of group-based processing.<commit_after>#pragma once

#include <array>
#include <cstddef>
#include <cstdint>

class CallbackQueue
{
private:
    using u8 = std::uint8_t;
    using u64 = std::uint64_t;
    std::array<u64, 2> mFlags = {{0u, 0u}};

public:
    bool Empty() const { return mFlags[0] == 0u && mFlags[1] == 0u; }

    u8 Size() const { return __builtin_popcountll(mFlags[0]) + __builtin_popcountll(mFlags[1]); }

    void Push(u8 x)
    {
        assert(x < 81u);
        bool first = x < 64u;
        u64 bit = 1u << (x % 64u);
        mFlags[0] |= first * bit;
        mFlags[1] |= !first * bit;
    }

    void PushFlags(std::array<u64, 2> flags) { mFlags[0] |= flags[0]; mFlags[1] |= flags[1]; }
    void PushFlags(u64 flags) { mFlags[0] |= flags; } // TODO: remove

    u8 Pop()
    {
        if (mFlags[0] != 0u)
        {
            u8 ret = __builtin_ctzll(mFlags[0]);
            mFlags[0] &= ~(1u << ret);
            return u8(ret);
        }
        else if (mFlags[1] != 0u)
        {
            u8 ret = __builtin_ctzll(mFlags[1]);
            mFlags[1] &= ~(1u << ret);
            return u8(64u + ret);
        }

        return u8(255);
    }

    void PopElement(u8 element)
    {
        if (element < 64u)
        {
            mFlags[0] &= ~(1u << element);
        }
        else
        {
            element -= 64u;
            mFlags[1] &= ~(1u << element);
        }
    }
};
<|endoftext|>


<commit_before>/*
 * template.cpp
 *
 * Just some boilerplate stuff to use for each file.
 */

#include <iostream>
#include <complex>
using namespace std;

struct Vector {
    int size;
    double *elem;
};

void vector_init(Vector & v, int s)
{
    v.elem = new double[s];
    v.size = s;
}

/* Fill values in a Vector.  Assume an already initialized vector is passed in */
void read_vector(Vector & v)
{
    cout << "Please give me " << v.size << " floating point numbers.\n";

    for (auto i=0; i!=v.size; ++i)
        cin >> v.elem[i];
}

/* Sum values in a Vector. */
double sum_vector(Vector & v)
{
    double sum = 0;
    for (auto i=0; i!=v.size; ++i)
        sum += v.elem[i];

    return sum;
}

int main()
{
    int num_vals;

    cout << "How many elements in the vector? ";
    cin >> num_vals;

    Vector v;
    vector_init(v, num_vals);
    read_vector(v);

    // double sum = read_and_sum(num_vals);
    cout << "The sum is: " << sum_vector(v) << "\n";
}

// vim: set ai sw=4 et sm:
<commit_msg>Add cVector class implementation to user_types.cpp.<commit_after>/*
 * template.cpp
 *
 * Just some boilerplate stuff to use for each file.
 */

#include <iostream>
#include <complex>
using namespace std;

struct sVector {
    int size;
    double *elem;
};

void vector_init(sVector & v, int s)
{
    v.elem = new double[s];
    v.size = s;
}

/* Fill values in a sVector.  Assume an already initialized vector is passed in */
void read_vector(sVector & v)
{
    cout << "Please give me " << v.size << " floating point numbers.\n";

    for (auto i=0; i!=v.size; ++i)
        cin >> v.elem[i];
}

/* Sum values in a sVector. */
double sum_vector(sVector & v)
{
    double sum = 0;
    for (auto i=0; i!=v.size; ++i)
        sum += v.elem[i];

    return sum;
}

void svector_access(sVector v, sVector & rv, sVector *pv)
{
    int i1 = v.size;    // Access to pass-by-value vector
    int i2 = rv.size;    // Access to pass-by-reference vector
    int i3 = pv->size;   // Access by pointer to vector
}

void handle_svector()
{
    int num_vals;

    cout << "How many elements in the sVector? ";
    cin >> num_vals;

    sVector v;
    vector_init(v, num_vals);
    read_vector(v);

    // double sum = read_and_sum(num_vals);
    cout << "The sum is: " << sum_vector(v) << "\n";
}

/* Use a class instead of a struct */

class cVector {
public:
    cVector(int s): elem{new double[s]}, sz{s} {}     // construct a cVector
    double& operator[](int i) { return elem[i]; }       // [] element access: subscripting
    int size() { return sz; } // Let's see how this name overloading works!
private:
    double* elem;
    int sz;
};

double cvector_read_and_sum(int s)
{
    cVector v(s);

    cout << "Please give me " << s << " floating point numbers.\n";
    for (auto i=0; i!=v.size(); ++i)
        cin >> v[i];

    double sum = 0;
    for (auto i=0; i!=v.size(); ++i)
        sum += v[i];

    return sum;
}

void handle_cvector()
{
    int num_vals;

    cout << "How many elements in the cVector? ";
    cin >> num_vals;

    auto sum = cvector_read_and_sum(num_vals);

    // double sum = read_and_sum(num_vals);
    cout << "The sum is: " << sum << "\n";
}

int main()
{
    handle_svector();
    handle_cvector();
}

// vim: set ai sw=4 et sm:
<|endoftext|>