bricks: update and move to c++14

* Makefile.am, bricks/brick-assert,
bricks/brick-assert.h, spot/ltsmin/ltsmin.cc,
spot/mc/ec.hh: here.

* bricks/brick-bitlevel.h, bricks/brick-hash.h,
bricks/brick-hashset.h, bricks/brick-shmem.h,
bricks/brick-types.h: Rename as ...
* bricks/brick-bitlevel, bricks/brick-hash,
bricks/brick-hashset, bricks/brick-shmem,
bricks/brick-types: ... these
This commit is contained in:
Etienne Renault 2016-12-01 18:56:33 +01:00
parent 9208726d97
commit bb9fa4e910
10 changed files with 1557 additions and 1110 deletions

View file

@ -39,9 +39,9 @@ SUBDIRS = picosat buddy lib ltdl spot bin tests $(PYTHON_SUBDIR) $(DOC_SUBDIR) \
UTF8 = utf8/README.md utf8/utf8.h \ UTF8 = utf8/README.md utf8/utf8.h \
utf8/utf8/checked.h utf8/utf8/core.h utf8/utf8/unchecked.h utf8/utf8/checked.h utf8/utf8/core.h utf8/utf8/unchecked.h
nobase_include_HEADERS= bricks/brick-assert.h bricks/brick-bitlevel.h \ nobase_include_HEADERS= bricks/brick-assert bricks/brick-bitlevel \
bricks/brick-hash.h bricks/brick-hashset.h bricks/brick-shmem.h \ bricks/brick-hash bricks/brick-hashset bricks/brick-shmem \
bricks/brick-types.h bricks/brick-types
DEBIAN = \ DEBIAN = \
debian/changelog \ debian/changelog \

229
bricks/brick-assert Normal file
View file

@ -0,0 +1,229 @@
// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/*
* Various assert macros based on C++ exceptions and their support code.
*/
/*
* (c) 2006-2016 Petr Ročkai <code@fixp.eu>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <exception>
#include <string>
#include <sstream>
#ifndef TEST
#define TEST(n) void n()
#define TEST_FAILING(n) void n()
#endif
#ifndef NDEBUG
#define BRICK_SHARP_FIRST(x, ...) #x
#define ASSERT(...) ::brick::_assert::assert_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( BRICK_SHARP_FIRST( __VA_ARGS__, ignored ) ) ), __VA_ARGS__ )
#define ASSERT_PRED(p, x) ::brick::_assert::assert_pred_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( #p "( " #x " )" ) ), x, p( x ) )
#define ASSERT_EQ(x, y) ::brick::_assert::assert_eq_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( #x " == " #y ) ), x, y )
#define ASSERT_LT(x, y) ::brick::_assert::assert_lt_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( #x " < " #y ) ), x, y )
#define ASSERT_LEQ(x, y) ::brick::_assert::assert_leq_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( #x " <= " #y ) ), x, y )
#define ASSERT_NEQ(x, y) ::brick::_assert::assert_neq_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( #x " != " #y ) ), x, y )
#define ASSERT_EQ_IDX(i, x, y) ::brick::_assert::assert_eq_fn( \
BRICK_LOCWRAP( BRICK_LOCATION_I( #x " == " #y, i ) ), x, y )
#else
#define ASSERT(...) static_cast< decltype(__VA_ARGS__, void(0)) >(0)
#define ASSERT_PRED(p, x) static_cast< decltype(p, x, void(0)) >(0)
#define ASSERT_EQ(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_LEQ(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_LT(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_NEQ(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_EQ_IDX(i, x, y) static_cast< decltype(i, x, y, void(0)) >(0)
#endif
/* you must #include <brick-string.h> to use ASSERT_UNREACHABLE_F */
#define UNREACHABLE_F(...) ::brick::_assert::assert_die_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( brick::string::fmtf(__VA_ARGS__) ) ) )
#define UNREACHABLE(x) ::brick::_assert::assert_die_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( x ) ) )
#define UNREACHABLE_() ::brick::_assert::assert_die_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( "an unreachable location" ) ) )
#define NOT_IMPLEMENTED() ::brick::_assert::assert_die_fn( \
BRICK_LOCWRAP( BRICK_LOCATION( "a missing implementation" ) ) )
#ifdef _MSC_VER
#define UNUSED
#define noexcept
#else
#define UNUSED __attribute__((unused))
#endif
#ifndef BRICK_ASSERT_H
#define BRICK_ASSERT_H
namespace brick {
namespace _assert {
/* discard any number of parameters, taken as const references */
template< typename... X >
void unused( const X&... ) { }
struct Location {
int line, iteration;
std::string file, stmt;
Location( const char *f, int l, std::string st, int iter = -1 )
: line( l ), iteration( iter ), file( f ), stmt( st )
{
int slashes = 0;
for ( int i = 0; i < int( file.size() ); ++i )
if ( file[i] == '/' )
++ slashes;
while ( slashes >= 3 )
{
file = std::string( file, file.find( "/" ) + 1, std::string::npos );
-- slashes;
}
if ( f != file )
file = ".../" + file;
}
};
#define BRICK_LOCATION(stmt) ::brick::_assert::Location( __FILE__, __LINE__, stmt )
#define BRICK_LOCATION_I(stmt, i) ::brick::_assert::Location( __FILE__, __LINE__, stmt, i )
// lazy location construction in C++11
#if __cplusplus >= 201103L
#define BRICK_LOCWRAP(x) [&]{ return (x); }
#define BRICK_LOCUNWRAP(x) (x)()
#else
#define BRICK_LOCWRAP(x) (x)
#define BRICK_LOCUNWRAP(x) (x)
#endif
struct AssertFailed : std::exception
{
std::string str;
template< typename X >
friend inline AssertFailed &operator<<( AssertFailed &f, X x )
{
std::stringstream str;
str << x;
f.str += str.str();
return f;
}
AssertFailed( Location l, const char *expected = "expected" )
{
(*this) << l.file << ": " << l.line;
if ( l.iteration != -1 )
(*this) << " (iteration " << l.iteration << ")";
(*this) << ":\n " << expected << " " << l.stmt;
}
const char *what() const noexcept override { return str.c_str(); }
};
static inline void format( AssertFailed & ) {}
template< typename X, typename... Y >
void format( AssertFailed &f, X x, Y... y )
{
f << x;
format( f, y... );
}
template< typename Location, typename X, typename... Y >
void assert_fn( Location l, X x, Y... y )
{
if ( x )
return;
AssertFailed f( BRICK_LOCUNWRAP( l ) );
format( f, y... );
throw f;
}
template< typename Location >
inline void assert_die_fn( Location l ) __attribute__((noreturn));
template< typename Location >
inline void assert_die_fn( Location l )
{
throw AssertFailed( BRICK_LOCUNWRAP( l ), "encountered" );
}
#define ASSERT_FN(name, op, inv) \
template< typename Location > \
void assert_ ## name ## _fn( Location l, int64_t x, int64_t y ) \
{ \
if ( !( x op y ) ) { \
AssertFailed f( BRICK_LOCUNWRAP( l ) ); \
f << "\n but got " \
<< x << " " #inv " " << y << "\n"; \
throw f; \
} \
} \
\
template< typename Location, typename X, typename Y > \
auto assert_ ## name ## _fn( Location l, X x, Y y ) \
-> typename std::enable_if< \
!std::is_integral< X >::value || \
!std::is_integral< Y >::value >::type \
{ \
if ( !( x op y ) ) { \
AssertFailed f( BRICK_LOCUNWRAP( l ) ); \
f << "\n but got " \
<< x << " " #inv " " << y << "\n"; \
throw f; \
} \
}
ASSERT_FN(eq, ==, !=);
ASSERT_FN(leq, <=, >);
ASSERT_FN(lt, <, >=);
template< typename Location, typename X >
void assert_pred_fn( Location l, X x, bool p )
{
if ( !p ) {
AssertFailed f( BRICK_LOCUNWRAP( l ) );
f << "\n but got x = " << x << "\n";
throw f;
}
}
template< typename Location, typename X, typename Y >
void assert_neq_fn( Location l, X x, Y y )
{
if ( x != y )
return;
AssertFailed f( BRICK_LOCUNWRAP( l ) );
f << "\n but got "
<< x << " == " << y << "\n";
throw f;
}
}
}
#endif
// vim: syntax=cpp tabstop=4 shiftwidth=4 expandtab

View file

@ -1,203 +0,0 @@
// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-
/*
* Various assert macros based on C++ exceptions and their support code.
*/
/*
* (c) 2006-2014 Petr Ročkai <me@mornfall.net>
*/
/* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 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 HOLDER 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. */
#include <exception>
#include <string>
#include <sstream>
#ifdef __divine__
#include <divine.h>
#endif
#ifndef TEST
#define TEST(n) void n()
#define TEST_FAILING(n) void n()
#endif
#ifdef __divine__
#define ASSERT(x) assert( x )
#define ASSERT_PRED(p, x) assert( p( x ) )
#define ASSERT_EQ(x, y) assert( (x) == (y) )
#define ASSERT_LEQ(x, y) assert( (x) <= (y) )
#define ASSERT_NEQ(x, y) assert ( (x) != (y) )
#define ASSERT_EQ_IDX(i, x, y) assert( (x) == (y) )
#elif !defined NDEBUG
#define ASSERT(x) ::brick::_assert::assert_fn( BRICK_LOCWRAP( BRICK_LOCATION( #x ) ), x )
#define ASSERT_PRED(p, x) ::brick::_assert::assert_pred_fn( BRICK_LOCWRAP( BRICK_LOCATION( #p "( " #x " )" ) ), x, p( x ) )
#define ASSERT_EQ(x, y) ::brick::_assert::assert_eq_fn( BRICK_LOCWRAP( BRICK_LOCATION( #x " == " #y ) ), x, y )
#define ASSERT_LEQ(x, y) ::brick::_assert::assert_leq_fn( BRICK_LOCWRAP( BRICK_LOCATION( #x " <= " #y ) ), x, y )
#define ASSERT_NEQ(x, y) ::brick::_assert::assert_neq_fn( BRICK_LOCWRAP( BRICK_LOCATION( #x " != " #y ) ), x, y )
#define ASSERT_EQ_IDX(i, x, y) ::brick::_assert::assert_eq_fn( BRICK_LOCWRAP( BRICK_LOCATION_I( #x " == " #y, i ) ), x, y )
#else
#define ASSERT(x) ((void)0)
#define ASSERT_PRED(p, x) ((void)0)
#define ASSERT_EQ(x, y) ((void)0)
#define ASSERT_LEQ(x, y) ((void)0)
#define ASSERT_NEQ(x, y) ((void)0)
#define ASSERT_EQ_IDX(i, x, y) ((void)0)
#endif
/* you must #include <brick-string.h> to use ASSERT_UNREACHABLE_F */
#define ASSERT_UNREACHABLE_F(...) ::brick::_assert::assert_die_fn( BRICK_LOCATION( brick::string::fmtf(__VA_ARGS__) ) )
#define ASSERT_UNREACHABLE(x) ::brick::_assert::assert_die_fn( BRICK_LOCATION( x ) )
#define ASSERT_UNIMPLEMENTED() ::brick::_assert::assert_die_fn( BRICK_LOCATION( "not imlemented" ) )
#ifdef _MSC_VER
#define UNUSED
#define noexcept
#else
#define UNUSED __attribute__((unused))
#endif
#ifndef BRICK_ASSERT_H
#define BRICK_ASSERT_H
namespace brick {
namespace _assert {
/* discard any number of paramentets, taken as const references */
template< typename... X >
void unused( const X&... ) { }
struct Location {
const char *file;
int line, iteration;
std::string stmt;
Location( const char *f, int l, std::string st, int iter = -1 )
: file( f ), line( l ), iteration( iter ), stmt( st ) {}
};
#define BRICK_LOCATION(stmt) ::brick::_assert::Location( __FILE__, __LINE__, stmt )
#define BRICK_LOCATION_I(stmt, i) ::brick::_assert::Location( __FILE__, __LINE__, stmt, i )
// lazy location construction in C++11
#if __cplusplus >= 201103L
#define BRICK_LOCWRAP(x) [&]{ return (x); }
#define BRICK_LOCUNWRAP(x) (x)()
#else
#define BRICK_LOCWRAP(x) (x)
#define BRICK_LOCUNWRAP(x) (x)
#endif
struct AssertFailed : std::exception {
std::string str;
template< typename X >
friend inline AssertFailed &operator<<( AssertFailed &f, X x )
{
std::stringstream str;
str << x;
f.str += str.str();
return f;
}
AssertFailed( Location l )
{
(*this) << l.file << ": " << l.line;
if ( l.iteration != -1 )
(*this) << " (iteration " << l.iteration << ")";
(*this) << ": assertion `" << l.stmt << "' failed;";
}
const char *what() const noexcept override { return str.c_str(); }
};
template< typename Location, typename X >
void assert_fn( Location l, X x )
{
if ( !x ) {
throw AssertFailed( BRICK_LOCUNWRAP( l ) );
}
}
inline void assert_die_fn( Location l ) __attribute__((noreturn));
inline void assert_die_fn( Location l )
{
throw AssertFailed( l );
}
template< typename Location, typename X, typename Y >
void assert_eq_fn( Location l, X x, Y y )
{
if ( !( x == y ) ) {
AssertFailed f( BRICK_LOCUNWRAP( l ) );
f << " got ["
<< x << "] != [" << y
<< "] instead";
throw f;
}
}
template< typename Location, typename X, typename Y >
void assert_leq_fn( Location l, X x, Y y )
{
if ( !( x <= y ) ) {
AssertFailed f( BRICK_LOCUNWRAP( l ) );
f << " got ["
<< x << "] > [" << y
<< "] instead";
throw f;
}
}
template< typename Location, typename X >
void assert_pred_fn( Location l, X x, bool p )
{
if ( !p ) {
AssertFailed f( BRICK_LOCUNWRAP( l ) );
f << " for " << x;
throw f;
}
}
template< typename Location, typename X, typename Y >
void assert_neq_fn( Location l, X x, Y y )
{
if ( x != y )
return;
AssertFailed f( BRICK_LOCUNWRAP( l ) );
f << " got ["
<< x << "] == [" << y << "] instead";
throw f;
}
}
}
#endif
// vim: syntax=cpp tabstop=4 shiftwidth=4 expandtab

View file

@ -7,33 +7,25 @@
/* /*
* (c) 2013-2014 Jiří Weiser <xweiser1@fi.muni.cz> * (c) 2013-2014 Jiří Weiser <xweiser1@fi.muni.cz>
* (c) 2013 Petr Ročkai <me@mornfall.net> * (c) 2013 Petr Ročkai <me@mornfall.net>
* (c) 2015 Vladimír Štill <xstill@fi.muni.cz>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/ */
/* Redistribution and use in source and binary forms, with or without #include "brick-assert"
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 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 HOLDER 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. */
#include <bricks/brick-assert.h>
#include <type_traits> #include <type_traits>
#include <limits>
#ifdef __linux #ifdef __linux
#include <asm/byteorder.h> #include <asm/byteorder.h>
@ -43,10 +35,6 @@
#define LITTLE_ENDIAN 1234 #define LITTLE_ENDIAN 1234
#endif #endif
#ifndef bswap_64
#define bswap_64 __builtin_bswap64
#endif
#include <atomic> #include <atomic>
#include <cstring> #include <cstring>
@ -75,7 +63,7 @@ constexpr unsigned MSB( T x ) {
template< typename T > template< typename T >
constexpr T fill( T x ) { constexpr T fill( T x ) {
return x ? x | fill( x >> 1 ) : x; return x ? x | compiletime::fill( x >> 1 ) : x;
} }
template< typename T > template< typename T >
@ -83,6 +71,77 @@ constexpr size_t sizeOf() {
return std::is_empty< T >::value ? 0 : sizeof( T ); return std::is_empty< T >::value ? 0 : sizeof( T );
} }
template< typename T >
constexpr T ones( int bits )
{
return bits ? ( T(1) << ( bits - 1 ) ) | compiletime::ones< T >( bits - 1 ) : 0;
}
}
using compiletime::ones;
template< typename L, typename H >
struct bvpair
{
L low; H high;
constexpr bvpair( L l, H h = 0 ) : low( l ), high( h ) {}
constexpr bvpair() = default;
explicit constexpr operator bool() const { return low || high; }
constexpr bvpair operator<<( int s ) const
{
int rem = 8 * sizeof( low ) - s;
int unshift = std::max( rem, 0 );
int shift = rem < 0 ? -rem : 0;
H carry = ( low & ~ones< L >( unshift ) ) >> unshift;
return bvpair( low << s, ( high << s ) | ( carry << shift ) );
}
constexpr bvpair operator>>( int s ) const
{
int rem = 8 * sizeof( low ) - s;
int unshift = std::max( rem, 0 );
int shift = rem < 0 ? -rem : 0;
L carry = L( high & ones< H >( s ) ) << unshift;
return bvpair( ( low >> s ) | ( carry >> shift ), high >> s );
}
constexpr bvpair operator&( bvpair o ) const { return bvpair( o.low & low, o.high & high ); }
constexpr bvpair operator|( bvpair o ) const { return bvpair( o.low | low, o.high | high ); }
bvpair &operator|=( bvpair o ) { return *this = *this | o; }
constexpr bool operator==( bvpair o ) const { return o.low == low && o.high == high; }
constexpr bool operator!=( bvpair o ) const { return o.low != low || o.high != high; }
constexpr bvpair operator+() const { return *this; }
friend std::ostream &operator<<( std::ostream &o, bvpair p ) {
return o << p.high << "_" << p.low; }
} __attribute__((packed));
template< int i > struct _bitvec { using T = typename _bitvec< i + 1 >::T; };
template<> struct _bitvec< 8 > { using T = uint8_t; };
template<> struct _bitvec< 16 > { using T = uint16_t; };
template<> struct _bitvec< 32 > { using T = uint32_t; };
template<> struct _bitvec< 64 > { using T = uint64_t; };
template<> struct _bitvec< 80 > { using T = bvpair< uint64_t, uint16_t >; };
template<> struct _bitvec< 128 > { using T = bvpair< uint64_t, uint64_t >; };
template< int i > using bitvec = typename _bitvec< i >::T;
namespace {
uint32_t mixdown( uint64_t i ) /* due to Thomas Wang */
{
i = (~i) + (i << 18);
i = i ^ (i >> 31);
i = i * 21;
i = i ^ (i >> 11);
i = i + (i << 6);
i = i ^ (i >> 22);
return i;
}
__attribute__((unused)) uint32_t mixdown( uint32_t a, uint32_t b )
{
return mixdown( ( uint64_t( a ) << 32 ) | uint64_t( b ) );
}
} }
/* /*
@ -144,28 +203,46 @@ static inline number withoutMSB( number x ) {
return x & ~onlyMSB( x ); return x & ~onlyMSB( x );
} }
inline uint64_t bitshift( uint64_t t, int shift ) { inline constexpr uint64_t bitshift( uint64_t t, int shift ) {
#if BYTE_ORDER == LITTLE_ENDIAN
return bswap_64( shift < 0 ? bswap_64( t << -shift ) : bswap_64( t >> shift ) );
#else
return shift < 0 ? ( t << -shift ) : ( t >> shift ); return shift < 0 ? ( t << -shift ) : ( t >> shift );
#endif }
inline constexpr uint64_t mask( int first, int count ) {
return (uint64_t(-1) << first) & (uint64_t(-1) >> (64 - first - count));
} }
struct BitPointer { struct BitPointer {
using Storage = uint32_t;
static constexpr int storageBits = sizeof( Storage ) * 8;
BitPointer() : base( nullptr ), _bitoffset( 0 ) {} BitPointer() : base( nullptr ), _bitoffset( 0 ) {}
template< typename T > BitPointer( T *t, int offset = 0 ) template< typename T > BitPointer( T *t, int offset = 0 )
: base( static_cast< void * >( t ) ), _bitoffset( offset ) : base( static_cast< void * >( t ) ), _bitoffset( offset )
{ {
normalize(); normalize();
} }
uint32_t &word() { ASSERT( valid() ); return *static_cast< uint32_t * >( base ); }
uint64_t &dword() { ASSERT( valid() ); return *static_cast< uint64_t * >( base ); } template< typename T >
T &ref() { ASSERT( valid() ); return *static_cast< T * >( base ); }
uint32_t &word() { return ref< uint32_t >(); }
uint64_t &dword() { return ref< uint64_t >(); }
// unsafe version does not cross word boundary
uint32_t getUnsafe( int bits ) { return _get< uint32_t >( bits ); }
uint32_t get( int bits ) {
return bits + _bitoffset <= 32 ? _get< uint32_t >( bits ) : _get< uint64_t >( bits );
}
void setUnsafe( uint32_t val, int bits ) { return _set< uint32_t >( val, bits ); }
void set( uint32_t val, int bits ) {
return bits + _bitoffset <= 32 ? _set< uint32_t >( val, bits ) : _set< uint64_t >( val, bits );
}
void normalize() { void normalize() {
int shift = downalign( _bitoffset, 32 ); int shift = downalign( _bitoffset, storageBits );
_bitoffset -= shift; _bitoffset -= shift;
ASSERT_EQ( shift % 8, 0 ); ASSERT_EQ( shift % 8, 0 );
base = static_cast< uint32_t * >( base ) + shift / 32; base = static_cast< Storage * >( base ) + shift / storageBits;
} }
void shift( int bits ) { _bitoffset += bits; normalize(); } void shift( int bits ) { _bitoffset += bits; normalize(); }
void fromReference( BitPointer r ) { *this = r; } void fromReference( BitPointer r ) { *this = r; }
@ -174,12 +251,27 @@ struct BitPointer {
private: private:
void *base; void *base;
int _bitoffset; int _bitoffset;
};
inline uint64_t mask( int first, int count ) { template< typename T >
return bitshift(uint64_t(-1), -first) & bitshift(uint64_t(-1), (64 - first - count)); uint32_t _get( int bits ) {
static_assert( std::is_unsigned< T >::value, "T has to be unsigned numeric type" );
ASSERT( valid() );
ASSERT_LEQ( 0, bits );
ASSERT_LEQ( bits, 32 );
ASSERT_LEQ( bits + _bitoffset, int( sizeof( T ) * 8 ) );
return (ref< T >() >> _bitoffset) & mask( 0, bits );
} }
template< typename T >
void _set( uint32_t val, int bits ) {
static_assert( std::is_unsigned< T >::value, "T has to be unsigned numeric type" );
ASSERT_EQ( val & ~mask( 0, bits ), 0u );
ASSERT_LEQ( bits, 32 );
ASSERT_LEQ( bits + _bitoffset, int( sizeof( T ) * 8 ) );
ref< T >() = (ref< T >() & ~mask( _bitoffset, bits )) | (T(val) << _bitoffset);
}
};
/* /*
* NB. This function will alias whatever "to" points to with an uint64_t. With * NB. This function will alias whatever "to" points to with an uint64_t. With
* aggressive optimisations, this might break code that passes an address of a * aggressive optimisations, this might break code that passes an address of a
@ -191,26 +283,30 @@ inline uint64_t mask( int first, int count ) {
inline void bitcopy( BitPointer from, BitPointer to, int bitcount ) inline void bitcopy( BitPointer from, BitPointer to, int bitcount )
{ {
while ( bitcount ) { while ( bitcount ) {
int w = std::min( 32 - from.bitoffset(), bitcount ); if ( from.bitoffset() == 0 && to.bitoffset() == 0
uint32_t fmask = mask( from.bitoffset(), w ); && bitcount >= BitPointer::storageBits )
uint64_t tmask = mask( to.bitoffset(), w ); {
uint64_t bits = bitshift( from.word() & fmask, from.bitoffset() - to.bitoffset() ); const int cnt = bitcount / BitPointer::storageBits;
ASSERT_EQ( bits & ~tmask, 0u ); std::copy( &from.word(), &from.word() + cnt, &to.word() );
ASSERT_EQ( bits & tmask, bits ); const int bitcnt = cnt * BitPointer::storageBits;
if ( to.bitoffset() + bitcount > 32 ) from.shift( bitcnt );
to.dword() = (to.dword() & ~tmask) | bits; to.shift( bitcnt );
else bitcount -= bitcnt;
to.word() = (to.word() & ~static_cast< uint32_t >( tmask )) | static_cast< uint32_t >( bits ); } else {
int w = std::min( BitPointer::storageBits - from.bitoffset(), bitcount );
to.set( from.getUnsafe( w ), w );
from.shift( w ); to.shift( w ); bitcount -= w; // slide from.shift( w ); to.shift( w ); bitcount -= w; // slide
} }
} }
}
template< typename T, int width = sizeof( T ) * 8 > template< typename T, int width = sizeof( T ) * 8 >
struct BitField struct BitField
{ {
static const int bitwidth = width; static const int bitwidth = width;
struct Virtual : BitPointer { struct Virtual : BitPointer
void set( T t ) { bitcopy( BitPointer( &t ), *this, bitwidth ); } {
T set( T t ) { bitcopy( BitPointer( &t ), *this, bitwidth ); return t; }
Virtual operator=( T t ) { Virtual operator=( T t ) {
set( t ); set( t );
return *this; return *this;
@ -254,41 +350,24 @@ struct BitField
set( value ); set( value );
return result; return result;
} }
template< typename U >
Virtual operator+=( U value ) { #define OP(__op) \
T t( get() ); template< typename U > \
t += value; Virtual operator __op( U value ) { \
set( t ); T t( get() ); \
return *this; t __op value; \
} set( t ); \
template< typename U > return *this; \
Virtual operator-=( U value ) {
T t( get() );
t -= value;
set( t );
return *this;
}
template< typename U >
Virtual operator*=( U value ) {
T t( get() );
t *= value;
set( t );
return *this;
}
template< typename U >
Virtual operator/=( U value ) {
T t( get() );
t /= value;
set( t );
return *this;
}
template< typename U >
Virtual operator%=( U value ) {
T t( get() );
t %= value;
set( t );
return *this;
} }
OP(+=);
OP(-=);
OP(*=);
OP(/=);
OP(%=);
OP(|=);
OP(&=);
#undef OP
}; };
}; };
@ -346,6 +425,16 @@ template< typename... Args > struct BitTuple : _BitTuple< Args... >
char storage[ align( Virtual::bitwidth, 32 ) / 8 ]; char storage[ align( Virtual::bitwidth, 32 ) / 8 ];
BitTuple() { std::fill( storage, storage + sizeof( storage ), 0 ); } BitTuple() { std::fill( storage, storage + sizeof( storage ), 0 ); }
operator BitPointer() { return BitPointer( storage ); } operator BitPointer() { return BitPointer( storage ); }
bool operator<( const BitTuple &o ) const
{
return std::lexicographical_compare( storage, storage + sizeof( storage ),
o.storage, o.storage + sizeof( storage ) );
}
bool operator==( const BitTuple &o ) const
{
return std::equal( storage, storage + sizeof( storage ),
o.storage, o.storage + sizeof( storage ) );
}
}; };
template< int I, typename BT > template< int I, typename BT >
@ -357,11 +446,9 @@ typename BT::template AccessAt< I >::T::Head get( BT &bt )
return t; return t;
} }
}
} }
namespace brick_test { namespace t_bitlevel {
namespace bitlevel {
using namespace ::brick::bitlevel; using namespace ::brick::bitlevel;
@ -575,15 +662,15 @@ struct BitTupleTest {
struct OperatorTester { struct OperatorTester {
int value; int value;
int expected; int expected;
OperatorTester &operator++() { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator++() { UNREACHABLE( "fell through" ); return *this; }
OperatorTester operator++( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester operator++( int ) { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator--() { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator--() { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator--( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator--( int ) { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator+=( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator+=( int ) { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator-=( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator-=( int ) { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator*=( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator*=( int ) { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator/=( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator/=( int ) { UNREACHABLE( "fell through" ); return *this; }
OperatorTester &operator%=( int ) { ASSERT_UNREACHABLE( "fell through" ); return *this; } OperatorTester &operator%=( int ) { UNREACHABLE( "fell through" ); return *this; }
void test() { ASSERT_EQ( value, expected ); } void test() { ASSERT_EQ( value, expected ); }
void set( int v, int e ) { value = v; expected = e; } void set( int v, int e ) { value = v; expected = e; }
}; };
@ -652,6 +739,65 @@ struct BitTupleTest {
CHECK( 9, bt, 42, 9, item %= 11 ); CHECK( 9, bt, 42, 9, item %= 11 );
} }
#undef CHECK #undef CHECK
TEST(ones)
{
ASSERT_EQ( bitlevel::ones< uint32_t >( 0 ), 0 );
ASSERT_EQ( bitlevel::ones< uint32_t >( 1 ), 1 );
ASSERT_EQ( bitlevel::ones< uint32_t >( 2 ), 3 );
ASSERT_EQ( bitlevel::ones< uint32_t >( 31 ), std::numeric_limits< uint32_t >::max() >> 1 );
ASSERT_EQ( bitlevel::ones< uint32_t >( 32 ), std::numeric_limits< uint32_t >::max() );
ASSERT_EQ( bitlevel::ones< uint32_t >( 33 ), std::numeric_limits< uint32_t >::max() );
}
};
struct BitVecTest
{
TEST(bvpair_shiftl)
{
using bvp32 = bitlevel::bvpair< uint16_t, uint16_t >;
union {
bvp32 bvp;
uint32_t val;
};
bvp = bvp32( 23, 13 );
uint32_t check = ( 13u << 16 ) | 23u;
ASSERT_EQ( val, check );
bvp = bvp << 7;
check = check << 7;
ASSERT_EQ( val, check );
bvp = bvp << 18;
check = check << 18;
ASSERT_EQ( val, check );
bvp = bvp32( 0xFF, 0xFF );
check = (0xFF << 16) | 0xFF;
bvp = bvp << 20;
check = check << 20;
ASSERT_EQ( val, check );
}
TEST(bvpair_shiftr)
{
using bvp32 = bitlevel::bvpair< uint16_t, uint16_t >;
union {
bvp32 bvp;
uint32_t val;
};
bvp = bvp32( 23, 13 );
uint32_t check = ( 13u << 16 ) | 23u;
ASSERT_EQ( val, check );
bvp = bvp >> 7;
check = check >> 7;
ASSERT_EQ( val, check );
bvp = bvp >> 18;
check = check >> 18;
ASSERT_EQ( val, check );
bvp = bvp32( 0xFF, 0xFF );
check = (0xFF << 16) | 0xFF;
bvp = bvp >> 20;
check = check >> 20;
ASSERT_EQ( val, check );
}
}; };
} }

View file

@ -29,9 +29,7 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. */ * POSSIBILITY OF SUCH DAMAGE. */
#include <spot/misc/common.hh> #include "brick-assert"
#include <bricks/brick-assert.h>
#include <cstddef> #include <cstddef>
#include <utility> // pair #include <utility> // pair
@ -51,7 +49,8 @@
typedef uint16_t uint16; typedef uint16_t uint16;
typedef uint8_t uint8; typedef uint8_t uint8;
#endif #endif
#include <memory.h> #include <cstring>
#include <cinttypes>
#define ALLOW_UNALIGNED_READS 1 #define ALLOW_UNALIGNED_READS 1
@ -61,6 +60,7 @@
namespace brick { namespace brick {
namespace hash { namespace hash {
typedef uint32_t hash32_t;
typedef uint64_t hash64_t; typedef uint64_t hash64_t;
typedef std::pair< hash64_t, hash64_t > hash128_t; typedef std::pair< hash64_t, hash64_t > hash128_t;
@ -220,6 +220,9 @@ public:
// Is this message fragment too short? If it is, stuff it away. // Is this message fragment too short? If it is, stuff it away.
if (newLength < sc_bufSize) if (newLength < sc_bufSize)
{ {
#ifndef NDEBUG
if ( length > sc_bufSize ) abort();
#endif
memcpy(&reinterpret_cast< uint8 * >( m_data )[m_remainder], message, length); memcpy(&reinterpret_cast< uint8 * >( m_data )[m_remainder], message, length);
m_length = length + m_length; m_length = length + m_length;
m_remainder = uint8( newLength ); m_remainder = uint8( newLength );
@ -677,19 +680,17 @@ struct SpookyState {
namespace { namespace {
inline hash128_t spooky( const void *message, size_t length, uint64_t seed1, uint64_t seed2 ) { inline hash128_t spooky( const void *message, size_t length, uint64_t seed1 = 0, uint64_t seed2 = 0 ) {
return jenkins::SpookyHash::Hash128( message, length, seed1, seed2 ); return jenkins::SpookyHash::Hash128( message, length, seed1, seed2 );
} }
} }
}
} }
namespace brick_test { namespace t_hash {
namespace hash {
using namespace ::brick::hash; using namespace hash;
class Random class Random
{ {
@ -813,7 +814,7 @@ struct Jenkins {
saw[i] = SpookyHash::Hash32(buf, i, 0); saw[i] = SpookyHash::Hash32(buf, i, 0);
if (saw[i] != expected[i]) if (saw[i] != expected[i])
{ {
printf("%3d: saw 0x%.8x, expected 0x%.8lx\n", i, saw[i], (unsigned long) expected[i]); printf("%3d: saw 0x%.8x, expected 0x%.8" PRIx64 "\n", i, saw[i], expected[i]);
ASSERT( false ); ASSERT( false );
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -37,18 +37,18 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE. */ * POSSIBILITY OF SUCH DAMAGE. */
#include <bricks/brick-assert.h> #include "brick-assert"
#include <deque> #include <deque>
#include <iostream> #include <iostream>
#include <typeinfo> #include <typeinfo>
#if __cplusplus >= 201103L
#include <mutex> #include <mutex>
#include <atomic> #include <atomic>
#include <thread> #include <thread>
#include <stdexcept>
#include <mutex> #include <mutex>
#endif
#include <unistd.h> // alarm
#include <vector>
#ifndef BRICK_SHMEM_H #ifndef BRICK_SHMEM_H
#define BRICK_SHMEM_H #define BRICK_SHMEM_H
@ -60,108 +60,168 @@
namespace brick { namespace brick {
namespace shmem { namespace shmem {
#if __cplusplus >= 201103L template< typename T >
struct Thread : T
struct Thread { {
std::unique_ptr< std::thread > _thread; std::unique_ptr< std::thread > _thread;
std::atomic< bool > _interrupted; bool _start_on_move; // :-(
virtual void main() = 0;
virtual void exception( std::exception_ptr ep ) {
try {
std::rethrow_exception( ep );
} catch ( std::exception &ex ) {
std::cerr << "Uncaught exception"
<< " of type " << typeid( ex ).name()
<< ":" << std::endl;
std::cerr << ex.what() << std::endl;
std::terminate();
}
}
Thread() : _interrupted( false ) {} template< typename... Args >
Thread( const Thread &other ) : _interrupted( false ) { Thread( Args&&... args ) : T( std::forward< Args >( args )... ), _start_on_move( false ) {}
virtual ~Thread() { stop(); }
Thread( const Thread &other ) : T( other )
{
if ( other._thread ) if ( other._thread )
throw std::logic_error( "cannot copy running thread" ); throw std::logic_error( "cannot copy running thread" );
} }
Thread( Thread &&other ) :
Thread( Thread &&other )
: T( other._thread ? throw std::logic_error( "cannot move a running thread" ) : other ),
_thread( std::move( other._thread ) ), _thread( std::move( other._thread ) ),
_interrupted( other.interrupted() ) _start_on_move( false )
{} {
if ( other._start_on_move )
~Thread() { stop(); } start();
Thread &operator=( const Thread &other ) {
if ( _thread )
throw std::logic_error( "cannot overwrite running thread" );
if ( other._thread )
throw std::logic_error( "cannot copy running thread" );
_interrupted.store( other.interrupted(), std::memory_order_relaxed );
return *this;
} }
Thread &operator=( Thread &&other ) { virtual void start()
if ( _thread ) {
throw std::logic_error( "cannot overwrite running thread" ); _thread.reset( new std::thread( [this]() { this->main(); } ) );
_thread.swap( other._thread );
_interrupted.store( other.interrupted(), std::memory_order_relaxed );
return *this;
} }
#ifdef __divine__ virtual void stop()
void start() __attribute__((noinline)) { {
__divine_interrupt_mask();
#else
void start() {
#endif
_interrupted.store( false, std::memory_order_relaxed );
_thread.reset( new std::thread( [this]() {
try {
this->main();
} catch (...) {
this->exception( std::current_exception() );
}
} ) );
}
// stop must be idempotent
void stop() {
interrupt();
if ( _thread && _thread->joinable() ) if ( _thread && _thread->joinable() )
join(); join();
} }
void join() { void join()
if ( _thread ) { {
if ( _thread )
{
_thread->join(); _thread->join();
_thread.reset(); _thread.reset();
} }
} }
void detach() { void detach()
if ( _thread ) { {
if ( _thread )
{
_thread->detach(); _thread->detach();
_thread.reset(); _thread.reset();
} }
} }
bool interrupted() const { const Thread& operator=(const Thread& other)
{
std::cerr << "FIXME Added by us (Spot) to avoid compilation warnings\n";
std::cerr << " Should not pass here.\n";
return other;
}
};
template< typename T >
struct LoopWrapper : T
{
std::atomic< bool > _interrupted;
template< typename... Args >
LoopWrapper( Args&&... args ) : T( std::forward< Args >( args )... ), _interrupted( false ) {}
LoopWrapper( const LoopWrapper & ) = default;
LoopWrapper( LoopWrapper && ) = default;
void main()
{
while ( !_interrupted ) this->loop();
}
bool interrupted() const
{
return _interrupted.load( std::memory_order_relaxed ); return _interrupted.load( std::memory_order_relaxed );
} }
void interrupt() { void interrupt()
{
_interrupted.store( true, std::memory_order_relaxed ); _interrupted.store( true, std::memory_order_relaxed );
} }
}; };
template< typename L >
struct LambdaWrapper
{
L lambda;
LambdaWrapper( L l ) : lambda( l ) {}
void loop() { lambda(); }
void main() { lambda(); }
};
template< typename T >
struct AsyncLoop : Thread< LoopWrapper< T > >
{
using Super = Thread< LoopWrapper< T > >;
template< typename... Args >
AsyncLoop( Args&&... args ) : Super( std::forward< Args >( args )... ) {}
AsyncLoop( const AsyncLoop & ) = default;
AsyncLoop( AsyncLoop && ) = default;
virtual ~AsyncLoop()
{
stop(); /* call the correct stop(), with interrupt() */
}
void start() override
{
this->_interrupted.store( false, std::memory_order_relaxed );
Super::start();
}
void stop() override
{
this->interrupt();
Super::stop();
}
};
template< typename L >
auto async_loop( L &&l )
{
AsyncLoop< LambdaWrapper< L > > al( std::forward< L >( l ) );
al._start_on_move = true;
return std::move( al );
}
template< typename L >
auto thread( L &&l )
{
Thread< LambdaWrapper< L > > thr( std::forward< L >( l ) );
thr._start_on_move = true;
return thr;
}
template< typename T >
struct ThreadSet : std::vector< Thread< T > >
{
template< typename... Args >
ThreadSet( Args&&... args ) : std::vector< Thread< T > >( std::forward< Args >( args )... ) {}
void start() { for ( auto &t : *this ) t.start(); }
void join() { for ( auto &t : *this ) t.join(); }
};
/** /**
* A spinlock implementation. * A spinlock implementation.
* *
* One has to wonder why this is missing from the C++0x stdlib. * One has to wonder why this is missing from the C++0x stdlib.
*/ */
struct SpinLock { struct SpinLock {
std::atomic_flag b = ATOMIC_FLAG_INIT;; std::atomic_flag b;
SpinLock() {} SpinLock() : b( 0 ) {}
void lock() { void lock() {
while( b.test_and_set() ); while( b.test_and_set() );
@ -198,53 +258,49 @@ struct ApproximateCounter {
Shared( const Shared& ) = delete; Shared( const Shared& ) = delete;
}; };
Shared &shared; std::shared_ptr< Shared > _s;
intptr_t local; intptr_t _l;
ApproximateCounter( Shared &s ) : shared( s ), local( 0 ) {} ApproximateCounter() : _s( new Shared ), _l( 0 ) {}
ApproximateCounter( const ApproximateCounter &other ) : _s( other._s ), _l( 0 ) {}
ApproximateCounter operator=( const ApproximateCounter & ) = delete;
~ApproximateCounter() { sync(); } ~ApproximateCounter() { sync(); }
void sync() { void sync() {
intptr_t value = shared.counter; intptr_t value = _s->counter;
while ( local > 0 ) { while ( _l > 0 ) {
if ( value >= local ) { if ( value >= _l ) {
if ( shared.counter.compare_exchange_weak( value, value - local ) ) if ( _s->counter.compare_exchange_weak( value, value - _l ) )
local = 0; _l = 0;
} else { } else {
if ( shared.counter.compare_exchange_weak( value, 0 ) ) if ( _s->counter.compare_exchange_weak( value, 0 ) )
local = 0; _l = 0;
} }
} }
} }
ApproximateCounter& operator++() { ApproximateCounter& operator++() {
if ( local == 0 ) { if ( _l == 0 ) {
shared.counter += step; _s->counter += step;
local = step; _l = step;
} }
--local; -- _l;
return *this; return *this;
} }
ApproximateCounter &operator--() { ApproximateCounter &operator--() {
++local; ++ _l;
return *this; return *this;
} }
// NB. sync() must be called manually as this method is called too often // NB. may return false spuriously; call sync() to ensure a correct result
bool isZero() { operator bool() { return _s->counter; }
return shared.counter == 0; bool operator!() { return _s->counter == 0; }
}
void reset() { shared.counter = 0; } void reset() { _s->counter = 0; } /* fixme misleading? */
ApproximateCounter( const ApproximateCounter &a )
: shared( a.shared ), local( a.local )
{}
ApproximateCounter operator=( const ApproximateCounter & ) = delete;
}; };
struct StartDetector { struct StartDetector {
@ -264,22 +320,21 @@ struct StartDetector {
Shared( Shared & ) = delete; Shared( Shared & ) = delete;
}; };
Shared &shared; std::shared_ptr< Shared > _s;
StartDetector( Shared &s ) : shared( s ) {} StartDetector() : _s( new Shared() ) {}
StartDetector( const StartDetector &s ) : shared( s.shared ) {}
void waitForAll( unsigned short peers ) { void waitForAll( unsigned short peers )
{
while ( _s->leaveGuard );
while ( shared.leaveGuard ); if ( ++ _s->counter == peers ) {
_s->leaveGuard = peers;
if ( ++shared.counter == peers ) { _s->counter = 0;
shared.leaveGuard = peers;
shared.counter = 0;
} }
while ( shared.counter ); while ( _s->counter );
--shared.leaveGuard; -- _s->leaveGuard;
} }
}; };
@ -333,8 +388,6 @@ struct WeakAtomic : std::conditional< std::is_integral< T >::value && !std::is_s
friend struct _impl::WeakAtomicIntegral< WeakAtomic< T >, T >; friend struct _impl::WeakAtomicIntegral< WeakAtomic< T >, T >;
}; };
#endif
#ifndef __divine__ #ifndef __divine__
template< typename T > template< typename T >
constexpr int defaultNodeSize() { constexpr int defaultNodeSize() {
@ -530,28 +583,106 @@ struct LockedQueue {
LockedQueue &operator=( const LockedQueue & ) = delete; LockedQueue &operator=( const LockedQueue & ) = delete;
}; };
template< template< typename > class Q, typename T >
struct Chunked
{
using Chunk = std::deque< T >;
using ChQ = Q< Chunk >;
std::shared_ptr< ChQ > q;
unsigned chunkSize;
Chunk outgoing;
Chunk incoming;
void push( T t ) {
outgoing.push_back( t );
if ( outgoing.size() >= chunkSize )
flush();
}
T pop() {
if ( incoming.empty() )
incoming = q->pop();
if ( incoming.empty() )
UNREACHABLE( "attempted to pop an empty queue" );
auto x = incoming.front();
incoming.pop_front();
return x;
}
void flush() {
if ( !outgoing.empty() ) {
Chunk tmp;
std::swap( outgoing, tmp );
q->push( std::move( tmp ) );
/* A quickstart trick -- make first few chunks smaller. */
if ( chunkSize < 64 )
chunkSize = std::min( 2 * chunkSize, 64u );
} }
} }
#if __cplusplus >= 201103L bool empty() {
if ( incoming.empty() ) /* try to get a fresh one */
incoming = q->pop();
return incoming.empty();
}
#include <unistd.h> // alarm Chunked() : q( new ChQ() ), chunkSize( 2 ) {}
#include <vector> };
namespace brick_test { template< typename T >
namespace shmem { using SharedQueue = Chunked< LockedQueue, T >;
}
namespace t_shmem {
using namespace ::brick::shmem; using namespace ::brick::shmem;
#ifdef __divine__
static constexpr int size = 16;
static void timeout() {}
#else
static constexpr int size = 128 * 1024;
#endif
#if defined( __unix ) || defined( POSIX )
static void timeout() { alarm( 5 ); }
#else
static void timeout() { }
#endif
struct ThreadTest
{
TEST(async_loop)
{
timeout();
std::atomic< int > x( 0 );
auto t = shmem::async_loop( [&]() { x = 1; } );
while ( !x );
t.stop();
}
TEST(thread)
{
timeout();
std::atomic< int > x( 0 );
auto t = shmem::thread( [&]() { x = 1; } );
while ( !x );
t.join();
}
};
struct FifoTest { struct FifoTest {
template< typename T > template< typename T >
struct Checker : Thread struct Checker
{ {
Fifo< T > fifo; Fifo< T > fifo;
int terminate; int terminate;
int n; int n;
void main() override void main()
{ {
std::vector< int > x; std::vector< int > x;
x.resize( n ); x.resize( n );
@ -572,17 +703,17 @@ struct FifoTest {
} }
terminate = 0; terminate = 0;
for ( int i = 0; i < n; ++i ) for ( int i = 0; i < n; ++i )
ASSERT_EQ( x[ i ], 128*1024 ); ASSERT_EQ( x[ i ], size );
} }
Checker( int _n = 1 ) : terminate( 0 ), n( _n ) {} Checker( int _n = 1 ) : terminate( 0 ), n( _n ) {}
}; };
TEST(stress) { TEST(stress) {
Checker< int > c; Thread< Checker< int > > c;
for ( int j = 0; j < 5; ++j ) { for ( int j = 0; j < 5; ++j ) {
c.start(); c.start();
for( int i = 0; i < 128 * 1024; ++i ) for( int i = 0; i < size; ++i )
c.fifo.push( i ); c.fifo.push( i );
c.terminate = true; c.terminate = true;
c.join(); c.join();
@ -590,39 +721,38 @@ struct FifoTest {
} }
}; };
namespace { const int peers = 12; }
struct Utils { struct Utils {
static const int peers = 12;
struct DetectorWorker : Thread {
struct DetectorWorker
{
StartDetector detector; StartDetector detector;
int rep; int rep;
DetectorWorker( StartDetector::Shared &sh, int repeat ) : DetectorWorker( StartDetector sh, int repeat ) :
detector( sh ), detector( sh ),
rep( repeat ) rep( repeat )
{} {}
void main() override { void main() {
for ( int i = 0; i < rep; ++i ) for ( int i = 0; i < rep; ++i )
detector.waitForAll( peers ); detector.waitForAll( peers );
} }
}; };
void processDetector( int repeat ) { void processDetector( int repeat )
StartDetector::Shared sh; {
std::vector< DetectorWorker > threads{ peers, DetectorWorker{ sh, repeat } }; StartDetector sh;
ThreadSet< DetectorWorker > threads( peers, DetectorWorker{ sh, repeat } );
#if (defined( __unix ) || defined( POSIX )) && !defined( __divine__ ) // hm timeout();
alarm( 5 );
#endif
for ( int i = 0; i != 4; ++i ) { for ( int i = 0; i != 4; ++i )
for ( auto &w : threads ) {
w.start(); threads.start();
for ( auto &w : threads ) threads.join();
w.join(); ASSERT_EQ( sh._s->counter.load(), 0 );
ASSERT_EQ( sh.counter.load(), 0 );
} }
} }
@ -634,21 +764,21 @@ struct Utils {
processDetector( 4 ); processDetector( 4 );
} }
struct CounterWorker : Thread { struct CounterWorker
{
StartDetector detector; StartDetector detector;
ApproximateCounter counter; ApproximateCounter counter;
int produce; int produce;
int consume; int consume;
template< typename D, typename C > CounterWorker( StartDetector det, ApproximateCounter ctr ) :
CounterWorker( D &d, C &c ) : detector( det ),
detector( d ), counter( ctr ),
counter( c ),
produce( 0 ), produce( 0 ),
consume( 0 ) consume( 0 )
{} {}
void main() override { void main() {
detector.waitForAll( peers ); detector.waitForAll( peers );
while ( produce-- ) while ( produce-- )
@ -664,15 +794,14 @@ struct Utils {
} }
}; };
void processCounter() { TEST(approximateCounter)
StartDetector::Shared detectorShared; {
ApproximateCounter::Shared counterShared; StartDetector det;
std::vector< CounterWorker > threads{ peers, ApproximateCounter ctr;
CounterWorker{ detectorShared, counterShared } };
#if (defined( __unix ) || defined( POSIX )) && !defined( __divine__ ) // hm ThreadSet< CounterWorker > threads( peers, CounterWorker{ det, ctr } );
alarm( 5 );
#endif timeout();
// set consume and produce limits to each worker // set consume and produce limits to each worker
int i = 1; int i = 1;
@ -685,20 +814,15 @@ struct Utils {
++i; ++i;
} }
for ( auto &w : threads ) threads.start();
w.start(); threads.join();
ASSERT_EQ( ctr._s->counter.load(), 0 );
for ( auto &w : threads )
w.join();
ASSERT_EQ( counterShared.counter.load(), 0 );
} }
TEST(approximateCounter) {
processCounter();
};
}; };
} }
} }
#ifdef BRICK_BENCHMARK_REG #ifdef BRICK_BENCHMARK_REG
@ -708,7 +832,7 @@ struct Utils {
#endif #endif
#include <random> #include <random>
#include <brick-benchmark.h> #include <brick-benchmark>
namespace brick_test { namespace brick_test {
namespace shmem { namespace shmem {
@ -841,7 +965,7 @@ struct Linked {
Linked() { Linked() {
reader = writer = new Node(); reader = writer = new Node();
reader->next = 0; reader->next = nullptr;
} }
}; };
@ -882,59 +1006,6 @@ struct Shared {
Shared() : q( new Q() ) {} Shared() : q( new Q() ) {}
}; };
template< template< typename > class Q, typename T >
struct Chunked {
using Chunk = std::deque< T >;
using ChQ = Q< Chunk >;
std::shared_ptr< ChQ > q;
unsigned chunkSize;
Chunk outgoing;
Chunk incoming;
void push( T t ) {
outgoing.push_back( t );
// std::cerr << "pushed " << outgoing.back() << std::endl;
if ( outgoing.size() >= chunkSize )
flush();
}
T pop() {
// std::cerr << "pop: empty = " << incoming.empty() << std::endl;
if ( incoming.empty() )
incoming = q->pop();
if ( incoming.empty() )
return T();
// std::cerr << "pop: found " << incoming.front() << std::endl;
auto x = incoming.front();
incoming.pop_front();
return x;
}
void flush() {
if ( !outgoing.empty() ) {
// std::cerr << "flushing " << outgoing.size() << " items" << std::endl;
Chunk tmp;
std::swap( outgoing, tmp );
q->push( std::move( tmp ) );
/* A quickstart trick -- make first few chunks smaller. */
if ( chunkSize < 64 )
chunkSize = std::min( 2 * chunkSize, 64u );
}
}
bool empty() {
if ( incoming.empty() ) { /* try to get a fresh one */
incoming = q->pop();
// std::cerr << "pulled in " << incoming.size() << " items" << std::endl;
}
return incoming.empty();
}
Chunked() : q( new ChQ() ), chunkSize( 2 ) {}
};
template< typename Q > template< typename Q >
struct InsertThread : Thread { struct InsertThread : Thread {
Q *q; Q *q;
@ -952,7 +1023,7 @@ struct InsertThread : Thread {
}; };
template< typename Q > template< typename Q >
struct WorkThread : Thread { struct WorkThread {
Q q; Q q;
std::atomic< bool > *stop; std::atomic< bool > *stop;
int items; int items;
@ -1027,7 +1098,7 @@ struct ShQueue : BenchmarkGroup
template< typename Q > template< typename Q >
void scale() { void scale() {
Q fifo; Q fifo;
auto *t = new WorkThread< Q >[ p ]; auto *t = new Thread< WorkThread< Q > >[ p ];
std::atomic< bool > stop( false ); std::atomic< bool > stop( false );
for ( int i = 0; i < p; ++i ) { for ( int i = 0; i < p; ++i ) {
@ -1135,7 +1206,6 @@ struct FIFO : BenchmarkGroup
} }
} }
#endif
#endif #endif
#endif #endif

View file

@ -10,32 +10,22 @@
/* /*
* (c) 2006, 2014 Petr Ročkai <me@mornfall.net> * (c) 2006, 2014 Petr Ročkai <me@mornfall.net>
* (c) 2013-2014 Vladimír Štill <xstill@fi.muni.cz> * (c) 2013-2015 Vladimír Štill <xstill@fi.muni.cz>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/ */
/* Redistribution and use in source and binary forms, with or without #include "brick-assert"
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 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 HOLDER 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. */
#include <bricks/brick-assert.h>
#include <memory> #include <memory>
#include <cstring> #include <cstring>
@ -51,7 +41,7 @@
#define CONSTEXPR #define CONSTEXPR
#endif #endif
#if __cplusplus > 201103L #if __cplusplus > 201103L && __GNUC__ != 4 && __GNUC_MINOR__ != 9
#define CPP1Y_CONSTEXPR constexpr // C++1y #define CPP1Y_CONSTEXPR constexpr // C++1y
#else #else
#define CPP1Y_CONSTEXPR // C++11 #define CPP1Y_CONSTEXPR // C++11
@ -68,34 +58,30 @@ struct Unit {
struct Preferred { CONSTEXPR Preferred() { } }; struct Preferred { CONSTEXPR Preferred() { } };
struct NotPreferred { CONSTEXPR NotPreferred( Preferred ) {} }; struct NotPreferred { CONSTEXPR NotPreferred( Preferred ) {} };
struct Comparable { template< typename _T >
typedef bool IsComparable; struct Witness { using T = _T; };
};
struct Eq { typedef bool IsEq; };
template< typename T > template< typename T >
typename T::IsComparable operator!=( const T &a, const T &b ) { typename T::IsEq operator!=( const T &a, const T &b ) { return !(a == b); }
return not( a == b );
} struct Ord : Eq { typedef bool IsOrd; };
template< typename T > template< typename T >
typename T::IsComparable operator==( const T &a, const T &b ) { typename T::IsOrd operator<( const T &a, const T &b ) { return !(b <= a); }
template< typename T >
typename T::IsOrd operator>( const T &a, const T &b ) { return !(a <= b); }
template< typename T >
typename T::IsOrd operator>=( const T &a, const T &b ) { return b <= a; }
template< typename T >
typename T::IsOrd operator==( const T &a, const T &b ) {
return a <= b && b <= a; return a <= b && b <= a;
} }
using Comparable = Ord;
template< typename T >
typename T::IsComparable operator<( const T &a, const T &b ) {
return a <= b && a != b;
}
template< typename T >
typename T::IsComparable operator>( const T &a, const T &b ) {
return b <= a && a != b;
}
template< typename T >
typename T::IsComparable operator>=( const T &a, const T &b ) {
return b <= a;
}
struct Defer { struct Defer {
template< typename F > template< typename F >
@ -234,7 +220,7 @@ struct Maybe : Comparable
T fromMaybe( T x ) const { return isJust() ? value() : x; } T fromMaybe( T x ) const { return isJust() ? value() : x; }
explicit operator bool() const { return isJust(); } explicit operator bool() const { return isJust() && bool( value() ); }
static Maybe Just( const T &t ) { return Maybe( t ); } static Maybe Just( const T &t ) { return Maybe( t ); }
static Maybe Nothing() { return Maybe(); } static Maybe Nothing() { return Maybe(); }
@ -365,21 +351,6 @@ struct StrongEnumFlags {
UnderlyingType store; UnderlyingType store;
}; };
// don't catch integral types and classical enum!
template< typename Self, typename = typename
std::enable_if< is_enum_class< Self >::value >::type >
constexpr StrongEnumFlags< Self > operator|( Self a, Self b ) noexcept {
using Ret = StrongEnumFlags< Self >;
return Ret( a ) | Ret( b );
}
template< typename Self, typename = typename
std::enable_if< is_enum_class< Self >::value >::type >
constexpr StrongEnumFlags< Self > operator&( Self a, Self b ) noexcept {
using Ret = StrongEnumFlags< Self >;
return Ret( a ) & Ret( b );
}
/* implementation of Union */ /* implementation of Union */
namespace _impl { namespace _impl {
@ -411,9 +382,6 @@ namespace _impl {
std::is_same< Needle, T >::value || In< Needle, Ts... >::value > std::is_same< Needle, T >::value || In< Needle, Ts... >::value >
{ }; { };
template< typename _T >
struct Witness { using T = _T; };
template< typename, typename... > template< typename, typename... >
struct _OneConversion { }; struct _OneConversion { };
@ -454,10 +422,10 @@ template< typename F, typename T, typename Fallback, typename Check = bool >
struct _ApplyResult : Fallback {}; struct _ApplyResult : Fallback {};
template< typename F, typename T, typename Fallback > template< typename F, typename T, typename Fallback >
struct _ApplyResult< F, T, Fallback, decltype( std::declval< F >()( std::declval< T >() ), true ) > struct _ApplyResult< F, T, Fallback, decltype( std::declval< F >()( std::declval< T& >() ), true ) >
{ {
using Parameter = T; using Parameter = T;
using Result = decltype( std::declval< F >()( std::declval< T >() ) ); using Result = decltype( std::declval< F >()( std::declval< T& >() ) );
}; };
template< typename F, typename... Ts > struct ApplyResult; template< typename F, typename... Ts > struct ApplyResult;
@ -524,6 +492,11 @@ struct Union : Comparable {
return *this; return *this;
} }
~Union() {
if ( _discriminator )
_destruct< 1, Types... >( _discriminator );
}
template< typename T > template< typename T >
auto operator=( const T &other ) -> typename auto operator=( const T &other ) -> typename
std::enable_if< std::is_lvalue_reference< T & >::value, Union & >::type std::enable_if< std::is_lvalue_reference< T & >::value, Union & >::type
@ -546,26 +519,26 @@ struct Union : Comparable {
return *this; return *this;
} }
void swap( Union other ) { void swap( Union &other ) {
typename std::aligned_storage< size, algignment >::type tmpStor; if ( _discriminator == 0 && other._discriminator == 0 )
unsigned char tmpDis; return;
std::memcpy( &tmpStor, &other.storage, size ); if ( _discriminator == other._discriminator )
tmpDis = other._discriminator; _swapSame< 1, Types... >( other );
other._discriminator = 0; else
std::memcpy( &other.storage, &storage, size ); _swapDifferent< 0, void, Types... >( other );
other._discriminator = _discriminator;
_discriminator = 0;
std::memcpy( &storage, &tmpStor, size );
_discriminator = tmpDis;
} }
bool empty() { bool empty() const {
return _discriminator == 0; return _discriminator == 0;
} }
explicit operator bool() { explicit operator bool() const
return !empty(); {
auto rv = const_cast< Union* >( this )->apply( []( const auto & x ) -> bool { return !!x; } );
if ( rv.isNothing() )
return false;
return true;
} }
template< typename T > template< typename T >
@ -595,6 +568,12 @@ struct Union : Comparable {
return unsafeGet< T >(); return unsafeGet< T >();
} }
template< typename T >
T *asptr() { return is< T >() ? &get< T >() : nullptr; }
template< typename T >
const T *asptr() const { return is< T >() ? &get< T >() : nullptr; }
template< typename T > template< typename T >
const T &getOr( const T &val ) const { const T &getOr( const T &val ) const {
if ( is< T >() ) if ( is< T >() )
@ -642,7 +621,7 @@ struct Union : Comparable {
// invoke the first function that can handle the currently stored value // invoke the first function that can handle the currently stored value
// (type-based pattern matching) // (type-based pattern matching)
template< typename R, typename F, typename... Args > template< typename R, typename F, typename... Args >
R _match( F f, Args... args ) { R _match( F f, Args&&... args ) {
auto x = apply( f ); auto x = apply( f );
if ( x.isNothing() ) if ( x.isNothing() )
return _match< R >( args... ); return _match< R >( args... );
@ -650,25 +629,24 @@ struct Union : Comparable {
return x; return x;
} }
// invoke the first function that can handle the currently stored value
// (type-based pattern matching)
// * return value can be extracted from resuling Maybe value
// * auto lambdas are supported an can be called on any value!
template< typename F, typename... Args > template< typename F, typename... Args >
Applied< F > match( F f, Args... args ) { Applied< F > match( F f, Args&&... args ) {
return _match< Applied< F > >( f, args... ); return _match< Applied< F > >( f, args... );
} }
bool operator==( const Union &other ) const { bool operator==( const Union &other ) const {
return _discriminator == other._discriminator return _discriminator == other._discriminator
&& _compare< std::equal_to >( other ); && (_discriminator == 0 || _compare< std::equal_to >( other ));
}
bool operator!=( const Union &other ) const {
return _discriminator != other._discriminator
|| _compare< std::not_equal_to >( other );
} }
bool operator<( const Union &other ) const { bool operator<( const Union &other ) const {
return _discriminator < other._discriminator return _discriminator < other._discriminator
|| (_discriminator == other._discriminator || (_discriminator == other._discriminator
&& _compare< std::less >( other ) ); && (_discriminator == 0 || _compare< std::less >( other )) );
} }
unsigned char discriminator() const { return _discriminator; } unsigned char discriminator() const { return _discriminator; }
@ -682,11 +660,10 @@ struct Union : Comparable {
private: private:
static constexpr size_t size = _impl::MaxSizeof< 1, Types... >::value; static constexpr size_t size = _impl::MaxSizeof< 1, Types... >::value;
static constexpr size_t algignment = _impl::MaxAlign< 1, Types... >::value; static constexpr size_t alignment = _impl::MaxAlign< 1, Types... >::value;
typename std::aligned_storage< size, algignment >::type storage; typename std::aligned_storage< size, alignment >::type storage;
unsigned char _discriminator; unsigned char _discriminator;
template< unsigned char i, typename Needle, typename T, typename... Ts > template< unsigned char i, typename Needle, typename T, typename... Ts >
constexpr unsigned char _discriminatorF() const { constexpr unsigned char _discriminatorF() const {
return std::is_same< Needle, T >::value return std::is_same< Needle, T >::value
@ -706,7 +683,7 @@ struct Union : Comparable {
template< unsigned char > template< unsigned char >
unsigned char _copyConstruct( unsigned char, const Union & ) unsigned char _copyConstruct( unsigned char, const Union & )
{ ASSERT_UNREACHABLE( "invalid _copyConstruct" ); } { UNREACHABLE( "invalid _copyConstruct" ); return 0; }
template< unsigned char i, typename T, typename... Ts > template< unsigned char i, typename T, typename... Ts >
void _moveConstruct( unsigned char d, Union &&other ) { void _moveConstruct( unsigned char d, Union &&other ) {
@ -718,7 +695,7 @@ struct Union : Comparable {
template< unsigned char > template< unsigned char >
unsigned char _moveConstruct( unsigned char, Union && ) unsigned char _moveConstruct( unsigned char, Union && )
{ ASSERT_UNREACHABLE( "invalid _moveConstruct" ); } { UNREACHABLE( "invalid _moveConstruct" ); return 0; }
void _copyAssignDifferent( const Union &other ) { void _copyAssignDifferent( const Union &other ) {
auto tmp = _discriminator; auto tmp = _discriminator;
@ -746,7 +723,7 @@ struct Union : Comparable {
} }
template< unsigned char > template< unsigned char >
void _copyAssignSame( const Union & ) { ASSERT_UNREACHABLE( "invalid _copyAssignSame" ); } void _copyAssignSame( const Union & ) { UNREACHABLE( "invalid _copyAssignSame" ); }
template< unsigned char i, typename T, typename... Ts > template< unsigned char i, typename T, typename... Ts >
void _destruct( unsigned char d ) { void _destruct( unsigned char d ) {
@ -757,7 +734,7 @@ struct Union : Comparable {
} }
template< unsigned char > template< unsigned char >
void _destruct( unsigned char ) { ASSERT_UNREACHABLE( "invalid _destruct" ); } void _destruct( unsigned char ) { UNREACHABLE( "invalid _destruct" ); }
void _moveAssignSame( Union &&other ) { void _moveAssignSame( Union &&other ) {
ASSERT_EQ( _discriminator, other._discriminator ); ASSERT_EQ( _discriminator, other._discriminator );
@ -775,7 +752,7 @@ struct Union : Comparable {
} }
template< unsigned char > template< unsigned char >
void _moveAssignSame( Union && ) { ASSERT_UNREACHABLE( "invalid _moveAssignSame" ); } void _moveAssignSame( Union && ) { UNREACHABLE( "invalid _moveAssignSame" ); }
void _moveAssignDifferent( Union &&other ) { void _moveAssignDifferent( Union &&other ) {
auto tmp = _discriminator; auto tmp = _discriminator;
@ -821,7 +798,7 @@ struct Union : Comparable {
} }
template< template< typename > class Compare, int d > template< template< typename > class Compare, int d >
bool _compare2( const Union & ) const { ASSERT_UNREACHABLE( "invalid discriminator" ); } bool _compare2( const Union & ) const { UNREACHABLE( "invalid discriminator" ); return false;}
template< template< typename > class Compare, int d, typename T, typename... Ts > template< template< typename > class Compare, int d, typename T, typename... Ts >
bool _compare2( const Union &other ) const { bool _compare2( const Union &other ) const {
@ -838,7 +815,7 @@ struct Union : Comparable {
template< typename Target, bool anyCastPossible, int > template< typename Target, bool anyCastPossible, int >
Target _convert2( Preferred ) const { Target _convert2( Preferred ) const {
static_assert( anyCastPossible, "Cast of Union can never succeed" ); static_assert( anyCastPossible, "Cast of Union can never succeed" );
ASSERT_UNREACHABLE( "wrong _convert2 in Union" ); UNREACHABLE( "wrong _convert2 in Union" );
} }
template< typename Target, bool any, int d, typename, typename... Ts > template< typename Target, bool any, int d, typename, typename... Ts >
@ -859,8 +836,155 @@ struct Union : Comparable {
return _convert2< Target, false, 1, Types... >( Preferred() ); return _convert2< Target, false, 1, Types... >( Preferred() );
} }
template< unsigned char i, typename T, typename... Ts >
void _swapSame( Union &other ) {
if ( _discriminator == i )
_doSwap< T >( unsafeGet< T >(), other.unsafeGet< T >(), Preferred() );
else
_swapSame< i + 1, Ts... >( other );
}
template< unsigned char i >
void _swapSame( Union & ) { UNREACHABLE( "Invalid _swapSame" ); }
template< typename T >
auto _doSwap( T &a, T &b, Preferred ) -> decltype( a.swap( b ) ) {
a.swap( b );
}
template< typename T >
auto _doSwap( T &a, T &b, NotPreferred ) -> decltype( std::swap( a, b ) ) {
std::swap( a, b );
}
template< unsigned char i, typename T, typename... Ts >
void _swapDifferent( Union &other ) {
if ( i == _discriminator )
_swapDifferent2< i, T, 0, void, Types... >( other );
else
_swapDifferent< i + 1, Ts... >( other );
}
template< unsigned char i >
void _swapDifferent( Union & ) { UNREACHABLE( "Invalid _swapDifferent" ); }
template< unsigned char local, typename Local, unsigned char i, typename T, typename... Ts >
void _swapDifferent2( Union &other ) {
if ( i == other._discriminator )
_doSwapDifferent< local, i, Local, T >( other );
else
_swapDifferent2< local, Local, i + 1, Ts... >( other );
}
template< unsigned char local, typename Local, unsigned char i >
void _swapDifferent2( Union & ) { UNREACHABLE( "Invalid _swapDifferent2" ); }
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union &other ) -> typename std::enable_if< l != 0 && r != 0 >::type {
L lval( unsafeMoveOut< L >() );
unsafeGet< L >().~L();
new ( &unsafeGet< R >() ) R( other.unsafeMoveOut< R >() );
other.unsafeGet< R >().~R();
new ( &other.unsafeGet< L >() ) L( std::move( lval ) );
std::swap( _discriminator, other._discriminator );
}
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union &other ) -> typename std::enable_if< l == 0 && r != 0 >::type {
new ( &unsafeGet< R >() ) R( other.unsafeMoveOut< R >() );
other.unsafeGet< R >().~R();
std::swap( _discriminator, other._discriminator );
}
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union &other ) -> typename std::enable_if< l != 0 && r == 0 >::type {
new ( &other.unsafeGet< L >() ) L( unsafeMoveOut< L >() );
unsafeGet< L >().~L();
std::swap( _discriminator, other._discriminator );
}
template< unsigned char l, unsigned char r, typename L, typename R >
auto _doSwapDifferent( Union & ) -> typename std::enable_if< l == 0 && r == 0 >::type {
UNREACHABLE( "Invalid _doSwapDifferent" );
}
}; };
template< typename Left, typename Right >
struct Either : Union< Left, Right > {
using Union< Left, Right >::Union;
bool isLeft() const { return this->template is< Left >(); }
bool isRight() const { return this->template is< Right >(); }
Left &left() { return this->template get< Left >(); }
Right &right() { return this->template get< Right >(); }
const Left &left() const { return this->template get< Left >(); }
const Right &right() const { return this->template get< Right >(); }
};
// a pointer-like structure which can, however store values a value or a
// referrence to type T
template< typename T >
struct RefOrVal {
static_assert( !std::is_reference< T >::value, "T must not be a reference type" );
RefOrVal() : _store( InPlace< T >() ) { }
RefOrVal( T &&val ) : _store( std::forward< T >( val ) ) { }
RefOrVal( T *ref ) : _store( ref ) { }
RefOrVal( T &ref ) : _store( &ref ) { }
RefOrVal &operator=( const RefOrVal & ) = default;
RefOrVal &operator=( RefOrVal && ) = default;
RefOrVal &operator=( T &v ) { _store = v; return *this; }
RefOrVal &operator=( T &&v ) { _store = std::move( v ); return *this; }
RefOrVal &operator=( T *ptr ) { _store = ptr; return *this; }
T *ptr() {
ASSERT( !_store.empty() );
auto *val = _store.template asptr< T >();
return val ? val : _store.template get< T * >();
}
const T *ptr() const {
ASSERT( !_store.empty() );
const auto *val = _store.template asptr< T >();
return val ? val : _store.template get< T * >();
}
T *operator->() { return ptr(); }
T &operator*() { return *ptr(); }
const T *operator->() const { return ptr(); }
const T &operator*() const { return *ptr(); }
private:
Union< T, T * > _store;
};
template< typename Fn, typename R = typename std::result_of< Fn() >::type >
struct Lazy {
Lazy( Fn &&fn ) : _fn( std::forward< Fn >( fn ) ), _val() { }
R &get() {
if ( _val.empty() )
_val = _fn();
return _val.template get< R >();
}
R &operator*() { return get(); }
R *operator->() { return &get(); }
private:
Fn _fn;
Union< R > _val;
};
template< typename Fn, typename R = typename std::result_of< Fn() >::type >
Lazy< Fn, R > lazy( Fn &&fn ) { return Lazy< Fn, R >( std::forward< Fn >( fn ) ); }
template< template< typename > class C, typename T, typename F > template< template< typename > class C, typename T, typename F >
using FMap = C< typename std::result_of< F( T ) >::type >; using FMap = C< typename std::result_of< F( T ) >::type >;
@ -955,10 +1079,25 @@ auto operator>=( const A &a, const B &b ) -> typename _OneUnion< A, B >::type
} }
} }
namespace brick_test { // don't catch integral types and classical enum!
namespace types { template< typename Self, typename = typename
std::enable_if< brick::types::is_enum_class< Self >::value >::type >
constexpr brick::types::StrongEnumFlags< Self > operator|( Self a, Self b ) noexcept {
using Ret = brick::types::StrongEnumFlags< Self >;
return Ret( a ) | Ret( b );
}
using namespace ::brick::types; template< typename Self, typename = typename
std::enable_if< brick::types::is_enum_class< Self >::value >::type >
constexpr brick::types::StrongEnumFlags< Self > operator&( Self a, Self b ) noexcept {
using Ret = brick::types::StrongEnumFlags< Self >;
return Ret( a ) & Ret( b );
}
namespace brick {
namespace t_types {
using namespace types;
struct Integer : Comparable struct Integer : Comparable
{ {
@ -968,23 +1107,53 @@ public:
bool operator<=( const Integer& o ) const { return val <= o.val; } bool operator<=( const Integer& o ) const { return val <= o.val; }
}; };
struct IntegerEq : Eq {
int val;
public:
IntegerEq(int val) : val(val) {}
bool operator==( const IntegerEq& o ) const { return val == o.val; }
};
struct IntegerEqOrd : Ord {
int val;
public:
IntegerEqOrd(int val) : val(val) {}
bool operator==( const IntegerEqOrd& o ) const { return val == o.val; }
bool operator<=( const IntegerEqOrd& o ) const { return val <= o.val; }
};
struct IntegerOrd : Ord {
int val;
public:
IntegerOrd(int val) : val(val) {}
bool operator<=( const IntegerOrd& o ) const { return val <= o.val; }
};
struct Mixins { struct Mixins {
TEST(comparable) { template< typename T >
Integer i10(10); void eq() {
Integer i10a(10); T i10(10);
Integer i20(20); T i10a(10);
T i20(20);
ASSERT(i10 <= i10a);
ASSERT(i10a <= i10);
ASSERT(i10 <= i20);
ASSERT(! (i20 <= i10));
ASSERT(i10 != i20); ASSERT(i10 != i20);
ASSERT(!(i10 != i10a)); ASSERT(!(i10 != i10a));
ASSERT(i10 == i10a); ASSERT(i10 == i10a);
ASSERT(!(i10 == i20)); ASSERT(!(i10 == i20));
}
template< typename T >
void ord() {
T i10(10);
T i10a(10);
T i20(20);
ASSERT(i10 <= i10a);
ASSERT(i10a <= i10);
ASSERT(i10 <= i20);
ASSERT(! (i20 <= i10));
ASSERT(i10 < i20); ASSERT(i10 < i20);
ASSERT(!(i20 < i10)); ASSERT(!(i20 < i10));
@ -1000,6 +1169,25 @@ struct Mixins {
ASSERT(! (i10 >= i20)); ASSERT(! (i10 >= i20));
} }
TEST(comparable) {
eq< Integer >();
ord< Integer >();
}
TEST(eq) {
eq< IntegerEq >();
}
TEST(ord) {
eq< IntegerOrd >();
ord< IntegerOrd >();
}
TEST(eqord) {
eq< IntegerEqOrd >();
ord< IntegerEqOrd >();
}
}; };
#if __cplusplus >= 201103L #if __cplusplus >= 201103L
@ -1024,25 +1212,24 @@ struct UnionInstances {
struct UnionTest { struct UnionTest {
TEST(basic) { TEST(basic) {
Union< int > u( 1 ); Union< int > u( 1 );
ASSERT( !!u );
ASSERT( !u.empty() ); ASSERT( !u.empty() );
ASSERT( u.is< int >() ); ASSERT( u.is< int >() );
ASSERT_EQ( u.get< int >(), 1 ); ASSERT_EQ( u.get< int >(), 1 );
u = 2; // move u = 2; // move
ASSERT( !!u ); ASSERT( !u.empty() );
ASSERT_EQ( u.get< int >(), 2 ); ASSERT_EQ( u.get< int >(), 2 );
int i = 3; int i = 3;
u = i; // copy u = i; // copy
ASSERT( !!u ); ASSERT( !u.empty() );
ASSERT_EQ( u.get< int >(), 3 ); ASSERT_EQ( u.get< int >(), 3 );
u = types::Union< int >( 4 ); u = types::Union< int >( 4 );
ASSERT( u.is< int >() ); ASSERT( u.is< int >() );
ASSERT_EQ( u.get< int >(), 4 ); ASSERT_EQ( u.get< int >(), 4 );
u = types::Union< int >(); u = types::Union< int >();
ASSERT( !u ); ASSERT( u.empty() );
ASSERT( !u.is< int >() ); ASSERT( !u.is< int >() );
u = 5; u = 5;
ASSERT( u ); ASSERT( !u.empty() );
ASSERT( u.is< int >() ); ASSERT( u.is< int >() );
ASSERT_EQ( u.get< int >(), 5 ); ASSERT_EQ( u.get< int >(), 5 );
} }
@ -1061,12 +1248,12 @@ struct UnionTest {
ASSERT( wierd.empty() ); ASSERT( wierd.empty() );
wierd = 2L; wierd = 2L;
ASSERT( !!wierd ); ASSERT( !wierd.empty() );
ASSERT( wierd.is< long >() ); ASSERT( wierd.is< long >() );
ASSERT_EQ( wierd.get< long >(), 2L ); ASSERT_EQ( wierd.get< long >(), 2L );
wierd = Move(); wierd = Move();
ASSERT( !!wierd ); ASSERT( !wierd.empty() );
ASSERT( wierd.is< Move >() ); ASSERT( wierd.is< Move >() );
} }
@ -1086,8 +1273,9 @@ struct UnionTest {
ASSERT( ( Union< B, std::string >{ 1 }.is< B >() ) ); ASSERT( ( Union< B, std::string >{ 1 }.is< B >() ) );
} }
static C idC( C c ) { return c; }; static C idC( C c ) { return c; }
static C constC( B ) { return C( 32 ); }; static C constC( B ) { return C( 32 ); }
static C refC( C &c ) { return c; }
TEST(apply) { TEST(apply) {
Union< B, C > u; Union< B, C > u;
@ -1104,6 +1292,9 @@ struct UnionTest {
result = u.match( constC ); result = u.match( constC );
ASSERT( result.isNothing() ); ASSERT( result.isNothing() );
result = u.match( refC );
ASSERT_EQ( result.value().x, 12 );
} }
TEST(eq) { TEST(eq) {
@ -1153,6 +1344,31 @@ struct UnionTest {
ASSERT( v < 2l ); ASSERT( v < 2l );
ASSERT( w <= 2l ); ASSERT( w <= 2l );
} }
struct TrackDtor {
TrackDtor( int *cnt ) : cnt( cnt ) { }
~TrackDtor() { ++*cnt; }
int *cnt;
};
TEST(dtor) {
int cnt = 0;
{
Union< int, TrackDtor > u;
u = TrackDtor( &cnt );
cnt = 0;
}
ASSERT_EQ( cnt, 1 );
}
TEST(assing_dtor) {
int cnt = 0;
Union< int, TrackDtor > u;
u = TrackDtor( &cnt );
cnt = 0;
u = 1;
ASSERT_EQ( cnt, 1 );
}
}; };
enum class FA : unsigned char { X = 1, Y = 2, Z = 4 }; enum class FA : unsigned char { X = 1, Y = 2, Z = 4 };
@ -1202,5 +1418,6 @@ struct StrongEnumFlagsTest {
} }
} }
#endif #endif
// vim: syntax=cpp tabstop=4 shiftwidth=4 expandtab // vim: syntax=cpp tabstop=4 shiftwidth=4 expandtab

View file

@ -43,8 +43,8 @@
#include <spot/twacube/cube.hh> #include <spot/twacube/cube.hh>
#include <spot/mc/utils.hh> #include <spot/mc/utils.hh>
#include <spot/mc/ec.hh> #include <spot/mc/ec.hh>
#include <bricks/brick-hashset.h> #include <bricks/brick-hashset>
#include <bricks/brick-hash.h> #include <bricks/brick-hash>
#include <spot/twaalgos/dot.hh> #include <spot/twaalgos/dot.hh>
#include <spot/twa/twaproduct.hh> #include <spot/twa/twaproduct.hh>
#include <spot/twaalgos/emptiness.hh> #include <spot/twaalgos/emptiness.hh>
@ -1285,7 +1285,7 @@ namespace spot
cspins_state s = cspins_state s =
inner->manager->alloc_setup(dst, inner->compressed_, inner->manager->alloc_setup(dst, inner->compressed_,
inner->manager->size() * 2); inner->manager->size() * 2);
auto it = inner->map->insert({s}); auto it = inner->map->insert(s);
inner->succ->push_back(*it); inner->succ->push_back(*it);
if (!it.isnew()) if (!it.isnew())
inner->manager->dealloc(s); inner->manager->dealloc(s);
@ -1335,7 +1335,7 @@ namespace spot
cspins_state s = cspins_state s =
inner->manager->alloc_setup(dst, inner->compressed_, inner->manager->alloc_setup(dst, inner->compressed_,
inner->manager->size() * 2); inner->manager->size() * 2);
auto it = inner->map->insert({s}); auto it = inner->map->insert(s);
inner->succ->push_back(*it); inner->succ->push_back(*it);
if (!it.isnew()) if (!it.isnew())
inner->manager->dealloc(s); inner->manager->dealloc(s);
@ -1421,7 +1421,7 @@ namespace spot
compress_(compress), cubeset_(visible_aps.size()), compress_(compress), cubeset_(visible_aps.size()),
selfloopize_(selfloopize), aps_(visible_aps), nb_threads_(nb_threads) selfloopize_(selfloopize), aps_(visible_aps), nb_threads_(nb_threads)
{ {
map_.setSize(2000000); map_.initialSize(2000000);
manager_ = static_cast<cspins_state_manager*> manager_ = static_cast<cspins_state_manager*>
(::operator new(sizeof(cspins_state_manager) * nb_threads)); (::operator new(sizeof(cspins_state_manager) * nb_threads));
inner_ = new inner_callback_parameters[nb_threads_]; inner_ = new inner_callback_parameters[nb_threads_];

View file

@ -185,7 +185,7 @@ namespace spot
// -example and flush the bfs queue. // -example and flush the bfs queue.
auto mark = this->twa_->trans_data(front->it_prop, auto mark = this->twa_->trans_data(front->it_prop,
this->tid_).acc_; this->tid_).acc_;
if (!acc.has(mark)) if (!acc.has(mark.id))
{ {
ctrx_element* current = front; ctrx_element* current = front;
while (current != nullptr) while (current != nullptr)