diff --git a/bench/Jamfile.v2 b/bench/Jamfile.v2 index cc1e715..cc068ee 100644 --- a/bench/Jamfile.v2 +++ b/bench/Jamfile.v2 @@ -21,7 +21,7 @@ rule test_all for local fileb in [ glob *.cpp ] { - all_rules += [ run $(fileb) /boost/timer//boost_timer + all_rules += [ run $(fileb) /boost/timer//boost_timer /boost/container//boost_container : # additional args : # test-files : # requirements @@ -31,4 +31,4 @@ rule test_all return $(all_rules) ; } -test-suite container_test : [ test_all r ] ; +test-suite container_bench : [ test_all r ] ; diff --git a/bench/bench_adaptive_node_pool.cpp b/bench/bench_adaptive_node_pool.cpp new file mode 100644 index 0000000..5c0eb93 --- /dev/null +++ b/bench/bench_adaptive_node_pool.cpp @@ -0,0 +1,327 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef _MSC_VER +#pragma warning (disable : 4512) +#pragma warning (disable : 4127) +#pragma warning (disable : 4244) +#pragma warning (disable : 4267) +#endif + +#include +#include +#include +#include +#include //std::allocator +#include //std::cout, std::endl +#include //std::vector +#include //std::size_t +#include +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; + +namespace bc = boost::container; + +typedef std::allocator StdAllocator; +typedef bc::allocator AllocatorPlusV2; +typedef bc::allocator AllocatorPlusV1; +typedef bc::adaptive_pool + < int + , bc::ADP_nodes_per_block + , bc::ADP_max_free_blocks + , bc::ADP_only_alignment + , 1> AdPoolAlignOnlyV1; +typedef bc::adaptive_pool + < int + , bc::ADP_nodes_per_block + , bc::ADP_max_free_blocks + , bc::ADP_only_alignment + , 2> AdPoolAlignOnlyV2; +typedef bc::adaptive_pool + < int + , bc::ADP_nodes_per_block + , bc::ADP_max_free_blocks + , 2 + , 1> AdPool2PercentV1; +typedef bc::adaptive_pool + < int + , bc::ADP_nodes_per_block + , bc::ADP_max_free_blocks + , 2 + , 2> AdPool2PercentV2; +typedef bc::node_allocator + < int + , bc::NodeAlloc_nodes_per_block + , 1> SimpleSegregatedStorageV1; +typedef bc::node_allocator + < int + , bc::NodeAlloc_nodes_per_block + , 2> SimpleSegregatedStorageV2; + +//Explicit instantiation +template class bc::adaptive_pool + < int + , bc::ADP_nodes_per_block + , bc::ADP_max_free_blocks + , bc::ADP_only_alignment + , 2>; + +template class bc::node_allocator + < int + , bc::NodeAlloc_nodes_per_block + , 2>; + +template struct get_allocator_name; + +template<> struct get_allocator_name +{ static const char *get() { return "StdAllocator"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV1"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AdPoolAlignOnlyV1"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AdPoolAlignOnlyV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AdPool2PercentV1"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AdPool2PercentV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "SimpleSegregatedStorageV1"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "SimpleSegregatedStorageV2"; } }; + +class MyInt +{ + std::size_t int_; + + public: + explicit MyInt(std::size_t i = 0) : int_(i){} + MyInt(const MyInt &other) + : int_(other.int_) + {} + MyInt & operator=(const MyInt &other) + { + int_ = other.int_; + return *this; + } +}; + +template +void list_test_template(std::size_t num_iterations, std::size_t num_elements, bool csv_output) +{ + typedef typename Allocator::template rebind::other IntAllocator; + nanosecond_type tinsert, terase; + boost_cont_malloc_stats_t insert_stats, erase_stats; + std::size_t insert_inuse, erase_inuse; + const size_t sizeof_node = 2*sizeof(void*)+sizeof(int); + + typedef bc::list list_t; + typedef typename list_t::iterator iterator_t; + { + cpu_timer timer; + timer.resume(); + list_t l; + for(std::size_t r = 0; r != num_iterations; ++r){ + l.insert(l.end(), num_elements, MyInt(r)); + } + timer.stop(); + tinsert = timer.elapsed().wall; + + insert_inuse = boost_cont_in_use_memory(); + insert_stats = boost_cont_malloc_stats(); +/* + iterator_t it(l.begin()); + iterator_t last(--l.end()); + for(std::size_t n_elem = 0, n_max = l.size()/2-1; n_elem != n_max; ++n_elem) + { + l.splice(it++, l, last--); + } +*/ + //l.reverse(); + + //Now preprocess erase ranges + std::vector ranges_to_erase; + ranges_to_erase.push_back(l.begin()); + for(std::size_t r = 0; r != num_iterations; ++r){ + iterator_t next_pos(ranges_to_erase[r]); + std::size_t n = num_elements; + while(n--){ ++next_pos; } + ranges_to_erase.push_back(next_pos); + } + + //Measure range erasure function + timer.start(); + for(std::size_t r = 0; r != num_iterations; ++r){ + assert((r+1) < ranges_to_erase.size()); + l.erase(ranges_to_erase[r], ranges_to_erase[r+1]); + } + timer.stop(); + terase = timer.elapsed().wall; + erase_inuse = boost_cont_in_use_memory(); + erase_stats = boost_cont_malloc_stats(); + } + + + if(csv_output){ + std::cout << get_allocator_name::get() + << ";" + << num_iterations + << ";" + << num_elements + << ";" + << float(tinsert)/(num_iterations*num_elements) + << ";" + << (unsigned int)insert_stats.system_bytes + << ";" + << float(insert_stats.system_bytes)/(num_iterations*num_elements*sizeof_node)*100.0-100.0 + << ";" + << (unsigned int)insert_inuse + << ";" + << (float(insert_inuse)/(num_iterations*num_elements*sizeof_node)*100.0)-100.0 + << ";"; + std::cout << float(terase)/(num_iterations*num_elements) + << ";" + << (unsigned int)erase_stats.system_bytes + << ";" + << (unsigned int)erase_inuse + << std::endl; + } + else{ + std::cout << std::endl + << "Allocator: " << get_allocator_name::get() + << std::endl + << " allocation/deallocation(ns): " << float(tinsert)/(num_iterations*num_elements) << '\t' << float(terase)/(num_iterations*num_elements) + << std::endl + << " Sys MB(overh.)/Inuse MB(overh.): " << (float)insert_stats.system_bytes/(1024*1024) << "(" << float(insert_stats.system_bytes)/(num_iterations*num_elements*sizeof_node)*100.0-100.0 << "%)" + << " / " + << (float)insert_inuse/(1024*1024) << "(" << (float(insert_inuse)/(num_iterations*num_elements*sizeof_node)*100.0)-100.0 << "%)" + << std::endl + << " system MB/inuse bytes after: " << (float)erase_stats.system_bytes/(1024*1024) << '\t' << boost_cont_in_use_memory() + << std::endl << std::endl; + } + + //Release node_allocator cache + typedef boost::container::container_detail::shared_node_pool + < (2*sizeof(void*)+sizeof(int)) + , AdPoolAlignOnlyV2::nodes_per_block> shared_node_pool_t; + boost::container::container_detail::singleton_default + ::instance().purge_blocks(); + + //Release adaptive_pool cache + typedef boost::container::container_detail::shared_adaptive_node_pool + < (2*sizeof(void*)+sizeof(int)) + , AdPool2PercentV2::nodes_per_block + , AdPool2PercentV2::max_free_blocks + , AdPool2PercentV2::overhead_percent> shared_adaptive_pool_plus_t; + boost::container::container_detail::singleton_default + ::instance().deallocate_free_blocks(); + + //Release adaptive_pool cache + typedef boost::container::container_detail::shared_adaptive_node_pool + < (2*sizeof(void*)+sizeof(int)) + , AdPool2PercentV2::nodes_per_block + , AdPool2PercentV2::max_free_blocks + , 0u> shared_adaptive_pool_plus_align_only_t; + boost::container::container_detail::singleton_default + ::instance().deallocate_free_blocks(); + //Release dlmalloc memory + boost_cont_trim(0); +} + +void print_header() +{ + std::cout << "Allocator" << ";" << "Iterations" << ";" << "Size" << ";" + << "Insertion time(ns)" << ";" + << "System bytes" << ";" + << "System overhead(%)" << ";" + << "In use bytes" << ";" + << "In use overhead(%)" << ";" + << "Erasure time (ns)" << ";" + << "System bytes after" << ";" + << "In use bytes after" + << std::endl; +} + +int main(int argc, const char *argv[]) +{ + #define SINGLE_TEST + #ifndef SINGLE_TEST + #ifdef NDEBUG + std::size_t numrep [] = { 3000, 30000, 300000, 3000000, 6000000, 15000000, 30000000 }; + #else + std::size_t numrep [] = { 20, 200, 2000, 20000, 40000, 100000, 200000 }; + #endif + std::size_t numele [] = { 10000, 1000, 100, 10, 5, 2, 1 }; + #else + #ifdef NDEBUG + std::size_t numrep [] = { 1500000 }; + #else + std::size_t numrep [] = { 10000 }; + #endif + std::size_t numele [] = { 10 }; + #endif + + bool csv_output = argc == 2 && (strcmp(argv[1], "--csv-output") == 0); + + if(csv_output){/* + print_header(); + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + } + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + list_test_template(numrep[i], numele[i], csv_output); + }*/ + } + else{ + for(std::size_t i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + std::cout << "\n ----------------------------------- \n" + << " Iterations/Elements: " << numrep[i] << "/" << numele[i] + << "\n ----------------------------------- \n"; + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + list_test_template(numrep[i], numele[i], csv_output); + } + } + return 0; +} diff --git a/bench/bench_alloc.cpp b/bench/bench_alloc.cpp new file mode 100644 index 0000000..689d75f --- /dev/null +++ b/bench/bench_alloc.cpp @@ -0,0 +1,181 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef _MSC_VER +#pragma warning (disable : 4512) +#endif + +#include + +#define BOOST_INTERPROCESS_VECTOR_ALLOC_STATS + +#include //std::cout, std::endl +#include //typeid + +#include +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; + +template +void allocation_timing_test(unsigned int num_iterations, unsigned int num_elements) +{ + size_t capacity = 0; + unsigned int numalloc = 0, numexpand = 0; + + std::cout + << " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n" + << " Iterations/Elements: " << num_iterations << "/" << num_elements << '\n' + << " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ \n" + << std::endl; + + + allocation_type malloc_types[] = { BOOST_CONTAINER_EXPAND_BWD, BOOST_CONTAINER_EXPAND_FWD, BOOST_CONTAINER_ALLOCATE_NEW }; + const char * malloc_names[] = { "Backwards expansion", "Forward expansion", "New allocation" }; + for(size_t i = 0; i < sizeof(malloc_types)/sizeof(allocation_type); ++i){ + numalloc = 0; numexpand = 0; + const allocation_type m_mode = malloc_types[i]; + const char *malloc_name = malloc_names[i]; + + cpu_timer timer; + timer.resume(); + + for(unsigned int r = 0; r != num_iterations; ++r){ + void *first_mem = 0; + if(m_mode != BOOST_CONTAINER_EXPAND_FWD) + first_mem = boost_cont_malloc(sizeof(POD)*num_elements*3/2); + void *addr = boost_cont_malloc(1*sizeof(POD)); + if(m_mode == BOOST_CONTAINER_EXPAND_FWD) + first_mem = boost_cont_malloc(sizeof(POD)*num_elements*3/2); + capacity = boost_cont_size(addr)/sizeof(POD); + boost_cont_free(first_mem); + ++numalloc; + + try{ + boost_cont_command_ret_t ret; + for(size_t e = capacity + 1; e < num_elements; ++e){ + size_t received_size; + size_t min = (capacity+1)*sizeof(POD); + size_t max = (capacity*3/2)*sizeof(POD); + if(min > max) + max = min; + ret = boost_cont_allocation_command + ( m_mode, sizeof(POD) + , min, max, &received_size, addr); + if(!ret.first){ + std::cout << "(!ret.first)!" << std::endl; + throw int(0); + } + if(!ret.second){ + assert(m_mode == BOOST_CONTAINER_ALLOCATE_NEW); + if(m_mode != BOOST_CONTAINER_ALLOCATE_NEW){ + std::cout << "m_mode != BOOST_CONTAINER_ALLOCATE_NEW!" << std::endl; + return; + } + boost_cont_free(addr); + addr = ret.first; + ++numalloc; + } + else{ + assert(m_mode != BOOST_CONTAINER_ALLOCATE_NEW); + if(m_mode == BOOST_CONTAINER_ALLOCATE_NEW){ + std::cout << "m_mode == BOOST_CONTAINER_ALLOCATE_NEW!" << std::endl; + return; + } + ++numexpand; + } + capacity = received_size/sizeof(POD); + addr = ret.first; + e = capacity + 1; + } + boost_cont_free(addr); + } + catch(...){ + boost_cont_free(addr); + throw; + } + } + + assert( boost_cont_allocated_memory() == 0); + if(boost_cont_allocated_memory()!= 0){ + std::cout << "Memory leak!" << std::endl; + return; + } + + timer.stop(); + nanosecond_type nseconds = timer.elapsed().wall; + + std::cout << " Malloc type: " << malloc_name + << std::endl + << " allocation ns: " + << float(nseconds)/(num_iterations*num_elements) + << std::endl + << " capacity - alloc calls (new/expand): " + << (unsigned int)capacity << " - " + << (float(numalloc) + float(numexpand))/num_iterations + << "(" << float(numalloc)/num_iterations << "/" << float(numexpand)/num_iterations << ")" + << std::endl << std::endl; + boost_cont_trim(0); + } +} + +template +struct char_holder +{ + char ints_[N]; +}; + +template +int allocation_loop() +{ + std::cout << std::endl + << "-------------------------------------------\n" + << "-------------------------------------------\n" + << " Type(sizeof): " << typeid(POD).name() << " (" << sizeof(POD) << ")\n" + << "-------------------------------------------\n" + << "-------------------------------------------\n" + << std::endl; + + #define SINGLE_TEST + #ifndef SINGLE_TEST + #ifdef NDEBUG + unsigned int numrep [] = { /*10000, */100000, 1000000, 10000000 }; + #else + unsigned int numrep [] = { /*10000, */10000, 100000, 1000000 }; + #endif + unsigned int numele [] = { /*10000, */1000, 100, 10 }; + #else + #ifdef NDEBUG + unsigned int numrep [] = { 500000 }; + #else + unsigned int numrep [] = { 50000 }; + #endif + unsigned int numele [] = { 100 }; + #endif + + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + allocation_timing_test(numrep[i], numele[i]); + } + + return 0; +} + +int main() +{ + boost_cont_mallopt( (-3)//M_MMAP_THRESHOLD + , 100*10000000); + //allocation_loop >(); + //allocation_loop >(); + allocation_loop >(); + allocation_loop >(); + //allocation_loop >(); + allocation_loop >(); + return 0; +} diff --git a/bench/bench_alloc_expand_bwd.cpp b/bench/bench_alloc_expand_bwd.cpp new file mode 100644 index 0000000..c2ba54e --- /dev/null +++ b/bench/bench_alloc_expand_bwd.cpp @@ -0,0 +1,216 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef _MSC_VER +#pragma warning (disable : 4512) +#endif + +#include + +#define BOOST_CONTAINER_VECTOR_ALLOC_STATS + +#include +#include //std::allocator +#include //std::cout, std::endl + +#include +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; + +namespace bc = boost::container; + +typedef std::allocator StdAllocator; +typedef bc::allocator AllocatorPlusV2Mask; +typedef bc::allocator AllocatorPlusV2; +typedef bc::allocator AllocatorPlusV1; + +template struct get_allocator_name; + +template<> struct get_allocator_name +{ static const char *get() { return "StdAllocator"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2Mask"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV1"; } }; + +//typedef int MyInt; + +class MyInt +{ + int int_; + + public: + MyInt(int i = 0) + : int_(i) + {} + + MyInt(const MyInt &other) + : int_(other.int_) + {} + + MyInt & operator=(const MyInt &other) + { + int_ = other.int_; + return *this; + } + + ~MyInt() + { + int_ = 0; + } +}; +namespace boost{ + +template<> +struct has_trivial_destructor_after_move +{ + static const bool value = true; + //static const bool value = false; +}; + +} //namespace boost{ + + +void print_header() +{ + std::cout << "Allocator" << ";" << "Iterations" << ";" << "Size" << ";" + << "Capacity" << ";" << "push_back(ns)" << ";" << "Allocator calls" << ";" + << "New allocations" << ";" << "Bwd expansions" << std::endl; +} + +template +void vector_test_template(unsigned int num_iterations, unsigned int num_elements, bool csv_output) +{ + typedef typename Allocator::template rebind::other IntAllocator; + unsigned int numalloc = 0, numexpand = 0; + + cpu_timer timer; + timer.resume(); + + unsigned int capacity = 0; + for(unsigned int r = 0; r != num_iterations; ++r){ + bc::vector v; + v.reset_alloc_stats(); + void *first_mem = 0; + try{ + first_mem = boost_cont_malloc(sizeof(MyInt)*num_elements*3/2); + v.push_back(MyInt(0)); + boost_cont_free(first_mem); + + for(unsigned int e = 0; e != num_elements; ++e){ + v.push_back(MyInt(e)); + } + numalloc += v.num_alloc; + numexpand += v.num_expand_bwd; + capacity = static_cast(v.capacity()); + } + catch(...){ + boost_cont_free(first_mem); + throw; + } + } + + assert(boost_cont_allocated_memory() == 0); + + timer.stop(); + nanosecond_type nseconds = timer.elapsed().wall; + + if(csv_output){ + std::cout << get_allocator_name::get() + << ";" + << num_iterations + << ";" + << num_elements + << ";" + << capacity + << ";" + << float(nseconds)/(num_iterations*num_elements) + << ";" + << (float(numalloc) + float(numexpand))/num_iterations + << ";" + << float(numalloc)/num_iterations + << ";" + << float(numexpand)/num_iterations + << std::endl; + } + else{ + std::cout << std::endl + << "Allocator: " << get_allocator_name::get() + << std::endl + << " push_back ns: " + << float(nseconds)/(num_iterations*num_elements) + << std::endl + << " capacity - alloc calls (new/expand): " + << (unsigned int)capacity << " - " + << (float(numalloc) + float(numexpand))/num_iterations + << "(" << float(numalloc)/num_iterations << "/" << float(numexpand)/num_iterations << ")" + << std::endl; + std::cout << '\n' + << " ----------------------------------- " + << std::endl; + } + boost_cont_trim(0); +} + +int main(int argc, const char *argv[]) +{ + #define SINGLE_TEST + #ifndef SINGLE_TEST + #ifdef NDEBUG + unsigned int numit [] = { 20000, 200000, 2000000, 20000000 }; + #else + unsigned int numit [] = { 100, 1000, 10000, 100000 }; + #endif + unsigned int numele [] = { 10000, 1000, 100, 10 }; + #else + #ifdef NDEBUG + unsigned int numit [] = { 20000 }; + #else + unsigned int numit [] = { 100 }; + #endif + unsigned int numele [] = { 10000 }; + #endif + + bool csv_output = argc == 2 && (strcmp(argv[1], "--csv-output") == 0); + + if(csv_output){ + print_header(); + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + } + else{ + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + std::cout << "\n ----------------------------------- \n" + << " Iterations/Elements: " << numit[i] << "/" << numele[i] + << "\n ----------------------------------- \n"; + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + } + } + return 0; +} diff --git a/bench/bench_alloc_expand_fwd.cpp b/bench/bench_alloc_expand_fwd.cpp new file mode 100644 index 0000000..f0bf179 --- /dev/null +++ b/bench/bench_alloc_expand_fwd.cpp @@ -0,0 +1,285 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef _MSC_VER +#pragma warning (disable : 4512) +#pragma warning (disable : 4267) +#pragma warning (disable : 4244) +#endif + +#define BOOST_CONTAINER_VECTOR_ALLOC_STATS + +#include +#include +#include + +#include //std::allocator +#include //std::cout, std::endl +#include //std::strcmp +#include +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; + +namespace bc = boost::container; + +typedef std::allocator StdAllocator; +typedef bc::allocator AllocatorPlusV2Mask; +typedef bc::allocator AllocatorPlusV2; +typedef bc::allocator AllocatorPlusV1; + +template struct get_allocator_name; + +template<> struct get_allocator_name +{ static const char *get() { return "StdAllocator"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2Mask"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV1"; } }; + +#if defined(BOOST_CONTAINER_VECTOR_ALLOC_STATS) +// +// stats_traits; +// + +template class Vector> +struct stats_traits; + +template<> +struct stats_traits +{ + template + static void reset_alloc_stats(std::vector &) + {} + + template + static std::size_t get_num_alloc(std::vector &) + { return 0; } + + template + static std::size_t get_num_expand(std::vector &) + { return 0; } +}; + +template<> +struct stats_traits +{ + template + static void reset_alloc_stats(bc::vector &v) + { v.reset_alloc_stats(); } + + template + static std::size_t get_num_alloc(bc::vector &v) + { return v.num_alloc; } + + template + static std::size_t get_num_expand(bc::vector &v) + { return v.num_expand_fwd; } +}; + +#endif //BOOST_CONTAINER_VECTOR_ALLOC_STATS + +template class Vector> struct get_container_name; + +template<> struct get_container_name +{ static const char *get() { return "StdVector"; } }; + +template<> struct get_container_name +{ static const char *get() { return "BoostContainerVector"; } }; + +class MyInt +{ + int int_; + + public: + explicit MyInt(int i = 0) + : int_(i) + {} + + MyInt(const MyInt &other) + : int_(other.int_) + {} + + MyInt & operator=(const MyInt &other) + { + int_ = other.int_; + return *this; + } + + ~MyInt() + { + int_ = 0; + } +}; + +template class Vector> +void vector_test_template(unsigned int num_iterations, unsigned int num_elements, bool csv_output) +{ + typedef typename Allocator::template rebind::other IntAllocator; + unsigned int numalloc = 0, numexpand = 0; + + #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS + typedef stats_traits stats_traits_t; + #endif + + cpu_timer timer; + timer.resume(); + + unsigned int capacity = 0; + for(unsigned int r = 0; r != num_iterations; ++r){ + Vector v; + #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS + stats_traits_t::reset_alloc_stats(v); + #endif + //v.reserve(num_elements); + //MyInt a[3]; +/* + for(unsigned int e = 0; e != num_elements/3; ++e){ + v.insert(v.end(), &a[0], &a[0]+3); + }*/ +/* + for(unsigned int e = 0; e != num_elements/3; ++e){ + v.insert(v.end(), 3, MyInt(e)); + }*/ +/* + for(unsigned int e = 0; e != num_elements/3; ++e){ + v.insert(v.empty() ? v.end() : --v.end(), &a[0], &a[0]+3); + }*/ +/* + for(unsigned int e = 0; e != num_elements/3; ++e){ + v.insert(v.empty() ? v.end() : --v.end(), 3, MyInt(e)); + }*/ +/* + for(unsigned int e = 0; e != num_elements/3; ++e){ + v.insert(v.size() >= 3 ? v.end()-3 : v.begin(), &a[0], &a[0]+3); + }*/ +/* + for(unsigned int e = 0; e != num_elements/3; ++e){ + v.insert(v.size() >= 3 ? v.end()-3 : v.begin(), 3, MyInt(e)); + }*/ +/* + for(unsigned int e = 0; e != num_elements; ++e){ + v.insert(v.end(), MyInt(e)); + }*/ +/* + for(unsigned int e = 0; e != num_elements; ++e){ + v.insert(v.empty() ? v.end() : --v.end(), MyInt(e)); + }*/ + + for(unsigned int e = 0; e != num_elements; ++e){ + v.push_back(MyInt(e)); + } + + #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS + numalloc += stats_traits_t::get_num_alloc(v); + numexpand += stats_traits_t::get_num_expand(v); + #endif + capacity = static_cast(v.capacity()); + } + + timer.stop(); + nanosecond_type nseconds = timer.elapsed().wall; + + if(csv_output){ + std::cout << get_allocator_name::get() + << ";" + << num_iterations + << ";" + << num_elements + << ";" + << capacity + << ";" + << float(nseconds)/(num_iterations*num_elements) + << ";" + << (float(numalloc) + float(numexpand))/num_iterations + << ";" + << float(numalloc)/num_iterations + << ";" + << float(numexpand)/num_iterations + << std::endl; + } + else{ + std::cout << std::endl + << "Allocator: " << get_allocator_name::get() + << std::endl + << " push_back ns: " + << float(nseconds)/(num_iterations*num_elements) + << std::endl + << " capacity - alloc calls (new/expand): " + << (unsigned int)capacity << " - " + << (float(numalloc) + float(numexpand))/num_iterations + << "(" << float(numalloc)/num_iterations << "/" << float(numexpand)/num_iterations << ")" + << std::endl << std::endl; + } + boost_cont_trim(0); +} + +void print_header() +{ + std::cout << "Allocator" << ";" << "Iterations" << ";" << "Size" << ";" + << "Capacity" << ";" << "push_back(ns)" << ";" << "Allocator calls" << ";" + << "New allocations" << ";" << "Fwd expansions" << std::endl; +} + +int main(int argc, const char *argv[]) +{ + #define SINGLE_TEST + #ifndef SINGLE_TEST + #ifdef NDEBUG + unsigned int numit [] = { 10000, 100000, 1000000, 10000000 }; + #else + unsigned int numit [] = { 100, 1000, 10000, 100000 }; + #endif + unsigned int numele [] = { 10000, 1000, 100, 10 }; + #else + #ifdef NDEBUG + std::size_t numit [] = { 10000 }; + #else + std::size_t numit [] = { 100 }; + #endif + std::size_t numele [] = { 10000 }; + #endif + + bool csv_output = argc == 2 && (strcmp(argv[1], "--csv-output") == 0); + + if(csv_output){ + print_header(); + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + } + else{ + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + std::cout << "\n ----------------------------------- \n" + << " Iterations/Elements: " << numit[i] << "/" << numele[i] + << "\n ----------------------------------- \n"; + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + } + } + return 0; +} diff --git a/bench/bench_alloc_shrink_to_fit.cpp b/bench/bench_alloc_shrink_to_fit.cpp new file mode 100644 index 0000000..33bde3e --- /dev/null +++ b/bench/bench_alloc_shrink_to_fit.cpp @@ -0,0 +1,168 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef _MSC_VER +#pragma warning (disable : 4512) +#endif + +#include + +#define BOOST_CONTAINER_VECTOR_ALLOC_STATS + +#include + +#undef BOOST_CONTAINER_VECTOR_ALLOC_STATS + +#include //std::allocator +#include //std::cout, std::endl + +#include +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; + +namespace bc = boost::container; + +typedef std::allocator StdAllocator; +typedef bc::allocator AllocatorPlusV2; +typedef bc::allocator AllocatorPlusV1; + +template struct get_allocator_name; + +template<> struct get_allocator_name +{ static const char *get() { return "StdAllocator"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV1"; } }; + +class MyInt +{ + int int_; + + public: + MyInt(int i = 0) : int_(i){} + + MyInt(const MyInt &other) + : int_(other.int_) + {} + + MyInt & operator=(const MyInt &other) + { + int_ = other.int_; + return *this; + } +}; + +void print_header() +{ + std::cout << "Allocator" << ";" << "Iterations" << ";" << "Size" << ";" + << "num_shrink" << ";" << "shrink_to_fit(ns)" << std::endl; +} + +template +void vector_test_template(unsigned int num_iterations, unsigned int num_elements, bool csv_output) +{ + typedef typename Allocator::template rebind::other IntAllocator; + + unsigned int capacity = 0; + const std::size_t Step = 5; + unsigned int num_shrink = 0; + (void)capacity; + + cpu_timer timer; + timer.resume(); + + #ifndef NDEBUG + typedef bc::container_detail::integral_constant + ::value> alloc_version; + #endif + + for(unsigned int r = 0; r != num_iterations; ++r){ + bc::vector v(num_elements); + v.reset_alloc_stats(); + num_shrink = 0; + for(unsigned int e = num_elements; e != 0; e -= Step){ + v.erase(v.end() - Step, v.end()); + v.shrink_to_fit(); + assert( (alloc_version::value != 2) || (e == Step) || (v.num_shrink > num_shrink) ); + num_shrink = v.num_shrink; + } + assert(v.empty()); + assert(0 == v.capacity()); + } + + timer.stop(); + nanosecond_type nseconds = timer.elapsed().wall; + + if(csv_output){ + std::cout << get_allocator_name::get() + << ";" + << num_iterations + << ";" + << num_elements + << ";" + << num_shrink + << ";" + << float(nseconds)/(num_iterations*num_elements) + << std::endl; + } + else{ + std::cout << std::endl + << "Allocator: " << get_allocator_name::get() + << std::endl + << " num_shrink: " << num_shrink + << std::endl + << " shrink_to_fit ns: " + << float(nseconds)/(num_iterations*num_elements) + << std::endl << std::endl; + } + boost_cont_trim(0); +} + +int main(int argc, const char *argv[]) +{ + #define SINGLE_TEST + #ifndef SINGLE_TEST + unsigned int numit [] = { 100, 1000, 10000 }; + unsigned int numele [] = { 10000, 2000, 500 }; + #else + unsigned int numit [] = { 500 }; + unsigned int numele [] = { 2000 }; + #endif + + bool csv_output = argc == 2 && (strcmp(argv[1], "--csv-output") == 0); + + if(csv_output){ + print_header(); + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + vector_test_template(numit[i], numele[i], csv_output); + } + } + else{ + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + std::cout << "\n ----------------------------------- \n" + << " Iterations/Elements: " << numit[i] << "/" << numele[i] + << "\n ----------------------------------- \n"; + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + vector_test_template(numit[i], numele[i], csv_output); + } + } + return 0; +} diff --git a/bench/bench_alloc_stable_vector_burst_allocation.cpp b/bench/bench_alloc_stable_vector_burst_allocation.cpp new file mode 100644 index 0000000..03feb2b --- /dev/null +++ b/bench/bench_alloc_stable_vector_burst_allocation.cpp @@ -0,0 +1,287 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifdef _MSC_VER +#pragma warning (disable : 4512) +#pragma warning (disable : 4541) +#pragma warning (disable : 4673) +#pragma warning (disable : 4671) +#pragma warning (disable : 4244) +#endif + +#include //std::allocator +#include //std::cout, std::endl +#include //std::vector +#include //std::size_t +#include +#include +#include +#include +#include +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; + +namespace bc = boost::container; + +typedef std::allocator StdAllocator; +typedef bc::allocator AllocatorPlusV1; +typedef bc::allocator AllocatorPlusV2; +typedef bc::adaptive_pool + < int + , bc::ADP_nodes_per_block + , 0//bc::ADP_max_free_blocks + , 2 + , 2> AdPool2PercentV2; + +template struct get_allocator_name; + +template<> struct get_allocator_name +{ static const char *get() { return "StdAllocator"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV1"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AllocatorPlusV2"; } }; + +template<> struct get_allocator_name +{ static const char *get() { return "AdPool2PercentV2"; } }; + +class MyInt +{ + int int_; + + public: + MyInt(int i = 0) : int_(i){} + MyInt(const MyInt &other) + : int_(other.int_) + {} + MyInt & operator=(const MyInt &other) + { + int_ = other.int_; + return *this; + } +}; + +template +struct get_vector +{ + typedef bc::vector + ::other> type; + static const char *vector_name() + { + return "vector"; + } +}; + +template +struct get_stable_vector +{ + typedef bc::stable_vector + ::other> type; + static const char *vector_name() + { + return "stable_vector"; + } +}; + +template class GetContainer, class Allocator> +void stable_vector_test_template(unsigned int num_iterations, unsigned int num_elements, bool csv_output) +{ + typedef typename GetContainer::type vector_type; + //std::size_t top_capacity = 0; + nanosecond_type nseconds; + { + { + vector_type l; + cpu_timer timer; + timer.resume(); + + for(unsigned int r = 0; r != num_iterations; ++r){ + l.insert(l.end(), num_elements, MyInt(r)); + } + + timer.stop(); + nseconds = timer.elapsed().wall; + + if(csv_output){ + std::cout << get_allocator_name::get() + << ";" + << GetContainer::vector_name() + << ";" + << num_iterations + << ";" + << num_elements + << ";" + << float(nseconds)/(num_iterations*num_elements) + << ";"; + } + else{ + std::cout << "Allocator: " << get_allocator_name::get() + << '\t' + << GetContainer::vector_name() + << std::endl + << " allocation ns: " + << float(nseconds)/(num_iterations*num_elements); + } +// top_capacity = l.capacity(); + //Now preprocess ranges to erase + std::vector ranges_to_erase; + ranges_to_erase.push_back(l.begin()); + for(unsigned int r = 0; r != num_iterations; ++r){ + typename vector_type::iterator next_pos(ranges_to_erase[r]); + std::size_t n = num_elements; + while(n--){ ++next_pos; } + ranges_to_erase.push_back(next_pos); + } + + //Measure range erasure function + timer.stop(); + timer.start(); + + for(unsigned int r = 0; r != num_iterations; ++r){ + std::size_t init_pos = (num_iterations-1)-r; + l.erase(ranges_to_erase[init_pos], l.end()); + } + timer.stop(); + nseconds = timer.elapsed().wall; + assert(l.empty()); + } + } + + if(csv_output){ + std::cout << float(nseconds)/(num_iterations*num_elements) + << std::endl; + } + else{ + std::cout << '\t' + << " deallocation ns: " + << float(nseconds)/(num_iterations*num_elements)/* + << std::endl + << " max capacity: " + << static_cast(top_capacity) + << std::endl + << " remaining cap. " + << static_cast(top_capacity - num_iterations*num_elements) + << " (" << (float(top_capacity)/float(num_iterations*num_elements) - 1)*100 << " %)"*/ + << std::endl << std::endl; + } + assert(boost_cont_all_deallocated()); + boost_cont_trim(0); +} + +void print_header() +{ + std::cout << "Allocator" << ";" << "Iterations" << ";" << "Size" << ";" + << "Insertion time(ns)" << ";" << "Erasure time(ns)" << ";" + << std::endl; +} + +void stable_vector_operations() +{ + { + bc::stable_vector a(bc::stable_vector::size_type(5), 4); + bc::stable_vector b(a); + bc::stable_vector c(a.cbegin(), a.cend()); + b.insert(b.cend(), 0); + c.pop_back(); + a.assign(b.cbegin(), b.cend()); + a.assign(c.cbegin(), c.cend()); + a.assign(1, 2); + } + { + typedef bc::stable_vector > stable_vector_t; + stable_vector_t a(bc::stable_vector::size_type(5), 4); + stable_vector_t b(a); + stable_vector_t c(a.cbegin(), a.cend()); + b.insert(b.cend(), 0); + c.pop_back(); + assert(static_cast(a.end() - a.begin()) == a.size()); + a.assign(b.cbegin(), b.cend()); + assert(static_cast(a.end() - a.begin()) == a.size()); + a.assign(c.cbegin(), c.cend()); + assert(static_cast(a.end() - a.begin()) == a.size()); + a.assign(1, 2); + assert(static_cast(a.end() - a.begin()) == a.size()); + a.reserve(100); + assert(static_cast(a.end() - a.begin()) == a.size()); + } +} + +int main(int argc, const char *argv[]) +{ + #define SINGLE_TEST + #ifndef SINGLE_TEST + #ifdef NDEBUG + unsigned int numit [] = { 400, 4000, 40000, 400000 }; + #else + unsigned int numit [] = { 4, 40, 400, 4000 }; + #endif + unsigned int numele [] = { 10000, 1000, 100, 10 }; + #else + #ifdef NDEBUG + unsigned int numit [] = { 400 }; + #else + unsigned int numit [] = { 4 }; + #endif + unsigned int numele [] = { 10000 }; + #endif + + //Warning: range erasure is buggy. Vector iterators are not stable, so it is not + //possible to cache iterators, but indexes!!! + + bool csv_output = argc == 2 && (strcmp(argv[1], "--csv-output") == 0); + + if(csv_output){ + print_header(); + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + stable_vector_test_template(numit[i], numele[i], csv_output); + } + } + else{ + for(unsigned int i = 0; i < sizeof(numele)/sizeof(numele[0]); ++i){ + std::cout << "\n ----------------------------------- \n" + << " Iterations/Elements: " << numit[i] << "/" << numele[i] + << "\n ----------------------------------- \n"; + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + stable_vector_test_template(numit[i], numele[i], csv_output); + } + } + + return 0; +} diff --git a/bench/bench_flat_multiset.cpp b/bench/bench_flat_multiset.cpp new file mode 100644 index 0000000..6ee7cca --- /dev/null +++ b/bench/bench_flat_multiset.cpp @@ -0,0 +1,29 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include "boost/container/flat_set.hpp" +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //flat_set vs set + launch_tests< flat_multiset , multiset > + ("flat_multiset", "multiset"); + launch_tests< flat_multiset , multiset > + ("flat_multiset", "multiset"); + + return 0; +} diff --git a/bench/bench_flat_set.cpp b/bench/bench_flat_set.cpp new file mode 100644 index 0000000..8f86ba4 --- /dev/null +++ b/bench/bench_flat_set.cpp @@ -0,0 +1,29 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include "boost/container/flat_set.hpp" +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //flat_set vs set + launch_tests< flat_set , set > + ("flat_set", "set"); + launch_tests< flat_set , set > + ("flat_set", "set"); + + return 0; +} diff --git a/bench/bench_set.cpp b/bench/bench_set.cpp index 662d11b..890fd35 100644 --- a/bench/bench_set.cpp +++ b/bench/bench_set.cpp @@ -9,340 +9,27 @@ ////////////////////////////////////////////////////////////////////////////// #include "boost/container/set.hpp" -#include "boost/container/flat_set.hpp" #include -#include -#include -#include -#include -#include - -using boost::timer::cpu_timer; -using boost::timer::cpu_times; -using boost::timer::nanosecond_type; - -#ifdef NDEBUG -static const std::size_t N = 5000; -#else -static const std::size_t N = 500; -#endif - -void compare_times(cpu_times time_numerator, cpu_times time_denominator){ - std::cout << "----------------------------------------------" << '\n'; - std::cout << " wall = " << ((double)time_numerator.wall/(double)time_denominator.wall) << std::endl; - std::cout << "----------------------------------------------" << '\n' << std::endl; -} - -std::vector sorted_unique_range; -std::vector sorted_range; -std::vector random_unique_range; -std::vector random_range; - -void fill_ranges() -{ - sorted_unique_range.resize(N); - sorted_range.resize(N); - random_unique_range.resize(N); - random_range.resize(N); - std::srand (0); - //random_range - std::generate(random_unique_range.begin(), random_unique_range.end(), std::rand); - random_unique_range.erase(std::unique(random_unique_range.begin(), random_unique_range.end()), random_unique_range.end()); - //random_range - random_range = random_unique_range; - random_range.insert(random_range.end(), random_unique_range.begin(), random_unique_range.end()); - //sorted_unique_range - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - sorted_unique_range[i] = static_cast(i); - } - //sorted_range - sorted_range = sorted_unique_range; - sorted_range.insert(sorted_range.end(), sorted_unique_range.begin(), sorted_unique_range.end()); - std::sort(sorted_range.begin(), sorted_range.end()); -} - -template -cpu_times construct_time() -{ - cpu_timer sur_timer, sr_timer, rur_timer, rr_timer, copy_timer, assign_timer, destroy_timer; - //sur_timer.stop();sr_timer.stop();rur_timer.stop();rr_timer.stop();destroy_timer.stop(); - - cpu_timer total_time; - total_time.resume(); - - for(std::size_t i = 0; i != N; ++i){ - { - sur_timer.resume(); - T t(sorted_unique_range.begin(), sorted_unique_range.end()); - sur_timer.stop(); - } - { - sr_timer.resume(); - T t(sorted_range.begin(), sorted_range.end()); - sr_timer.stop(); - copy_timer.resume(); - T taux(t); - copy_timer.stop(); - assign_timer.resume(); - t = taux;; - assign_timer.stop(); - } - { - rur_timer.resume(); - T t(random_unique_range.begin(), random_unique_range.end()); - rur_timer.stop(); - } - { - rr_timer.resume(); - T t(random_range.begin(), random_range.end()); - rr_timer.stop(); - destroy_timer.resume(); - } - destroy_timer.stop(); - } - total_time.stop(); - - std::cout << " Construct sorted_unique_range " << boost::timer::format(sur_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Construct sorted_range " << boost::timer::format(sr_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Copy sorted range " << boost::timer::format(copy_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Assign sorted range " << boost::timer::format(assign_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Construct random_unique_range " << boost::timer::format(rur_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Construct random_range " << boost::timer::format(rr_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Destroy " << boost::timer::format(destroy_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws wall\n") << std::endl; - return total_time.elapsed(); -} - -template -cpu_times insert_time() -{ - cpu_timer sur_timer,sr_timer,rur_timer,rr_timer,destroy_timer; - sur_timer.stop();sr_timer.stop();rur_timer.stop();rr_timer.stop(); - - cpu_timer total_time; - total_time.resume(); - - for(std::size_t i = 0; i != N; ++i){ - { - sur_timer.resume(); - T t; - t.insert(sorted_unique_range.begin(), sorted_unique_range.end()); - sur_timer.stop(); - } - { - sr_timer.resume(); - T t; - t.insert(sorted_range.begin(), sorted_range.end()); - sr_timer.stop(); - } - { - rur_timer.resume(); - T t; - t.insert(random_unique_range.begin(), random_unique_range.end()); - rur_timer.stop(); - } - { - rr_timer.resume(); - T t; - t.insert(random_range.begin(), random_range.end()); - rr_timer.stop(); - } - } - total_time.stop(); - - std::cout << " Insert sorted_unique_range " << boost::timer::format(sur_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Insert sorted_range " << boost::timer::format(sr_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Insert random_unique_range " << boost::timer::format(rur_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Insert random_range " << boost::timer::format(rr_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws wall\n") << std::endl; - return total_time.elapsed(); -} - -template -cpu_times search_time() -{ - cpu_timer find_timer, lower_timer, upper_timer, equal_range_timer, count_timer; - - T t(sorted_unique_range.begin(), sorted_unique_range.end()); - - cpu_timer total_time; - total_time.resume(); - - for(std::size_t i = 0; i != N; ++i){ - //Find - { - std::size_t found = 0; - find_timer.resume(); - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.end() != t.find(sorted_unique_range[i])); - } - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.end() != t.find(sorted_unique_range[i])); - } - find_timer.stop(); - if(found/2 != t.size()){ - std::cout << "ERROR! all elements not found" << std::endl; - } - } - //Lower - { - std::size_t found = 0; - lower_timer.resume(); - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.end() != t.lower_bound(sorted_unique_range[i])); - } - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.end() != t.lower_bound(sorted_unique_range[i])); - } - lower_timer.stop(); - if(found/2 != t.size()){ - std::cout << "ERROR! all elements not found" << std::endl; - } - } - //Upper - { - std::size_t found = 0; - upper_timer.resume(); - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.end() != t.upper_bound(sorted_unique_range[i])); - } - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.end() != t.upper_bound(sorted_unique_range[i])); - } - upper_timer.stop(); - if(found/2 != (t.size()-1)){ - std::cout << "ERROR! all elements not found" << std::endl; - } - } - //Equal - { - std::size_t found = 0; - std::pair ret; - equal_range_timer.resume(); - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - ret = t.equal_range(sorted_unique_range[i]); - found += static_cast(ret.first != ret.second); - } - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - ret = t.equal_range(sorted_unique_range[i]); - found += static_cast(ret.first != ret.second); - } - equal_range_timer.stop(); - if(found/2 != t.size()){ - std::cout << "ERROR! all elements not found" << std::endl; - } - } - //Count - { - std::size_t found = 0; - std::pair ret; - count_timer.resume(); - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.count(sorted_unique_range[i])); - } - for(std::size_t i = 0, max = sorted_unique_range.size(); i != max; ++i){ - found += static_cast(t.count(sorted_unique_range[i])); - } - count_timer.stop(); - if(found/2 != t.size()){ - std::cout << "ERROR! all elements not found" << std::endl; - } - } - } - total_time.stop(); - - std::cout << " Find " << boost::timer::format(find_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Lower Bound " << boost::timer::format(lower_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Upper Bound " << boost::timer::format(upper_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Equal Range " << boost::timer::format(equal_range_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Count " << boost::timer::format(count_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws wall\n") << std::endl; - return total_time.elapsed(); -} - -template -void extensions_time() -{ - cpu_timer sur_timer,sur_opt_timer; - sur_timer.stop();sur_opt_timer.stop(); - - for(std::size_t i = 0; i != N; ++i){ - { - sur_timer.resume(); - T t(sorted_unique_range.begin(), sorted_unique_range.end()); - sur_timer.stop(); - } - { - sur_opt_timer.resume(); - T t(boost::container::ordered_unique_range, sorted_unique_range.begin(), sorted_unique_range.end()); - sur_opt_timer.stop(); - } - - } - std::cout << " Construct sorted_unique_range " << boost::timer::format(sur_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << " Construct sorted_unique_range (extension) " << boost::timer::format(sur_opt_timer.elapsed(), boost::timer::default_places, "%ws wall\n"); - std::cout << "Total time (Extension/Standard):\n"; - compare_times(sur_opt_timer.elapsed(), sur_timer.elapsed()); -} - -template -void launch_tests(const char *BoostContName, const char *StdContName) -{ - try { - fill_ranges(); - { - std::cout << "Construct benchmark:" << BoostContName << std::endl; - cpu_times boost_set_time = construct_time< BoostClass >(); - - std::cout << "Construct benchmark:" << StdContName << std::endl; - cpu_times std_set_time = construct_time< StdClass >(); - - std::cout << "Total time (" << BoostContName << "/" << StdContName << "):\n"; - compare_times(boost_set_time, std_set_time); - } - { - std::cout << "Insert benchmark:" << BoostContName << std::endl; - cpu_times boost_set_time = insert_time< BoostClass >(); - - std::cout << "Insert benchmark:" << StdContName << std::endl; - cpu_times std_set_time = insert_time< StdClass >(); - - std::cout << "Total time (" << BoostContName << "/" << StdContName << "):\n"; - compare_times(boost_set_time, std_set_time); - } - { - std::cout << "Search benchmark:" << BoostContName << std::endl; - cpu_times boost_set_time = search_time< BoostClass >(); - - std::cout << "Search benchmark:" << StdContName << std::endl; - cpu_times std_set_time = search_time< StdClass >(); - - std::cout << "Total time (" << BoostContName << "/" << StdContName << "):\n"; - compare_times(boost_set_time, std_set_time); - } - { - std::cout << "Extensions benchmark:" << BoostContName << std::endl; - extensions_time< BoostClass >(); - } - - }catch(std::exception e){ - std::cout << e.what(); - } -} +#include "bench_set.hpp" int main() { + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + //set vs std::set - launch_tests< boost::container::set , std::set > - ("boost::container::set", "std::set");/* - //multiset vs std::set - launch_tests< boost::container::multiset , std::multiset > - ("boost::container::multiset", "std::multiset");*/ - //flat_set vs set - //launch_tests< boost::container::flat_set , boost::container::set > - //("boost::container::flat_set", "boost::container::set"); - //flat_multiset vs multiset - //launch_tests< boost::container::flat_multiset , boost::container::multiset > - //("boost::container::flat_multiset", "boost::container::multiset"); - return 1; + launch_tests< set , std::set > + ("set", "std::set"); + launch_tests< set , std::set > + ("set", "std::set"); + + //set(sizeopt) vs set(!sizeopt) + launch_tests< set, set, std::allocator, tree_assoc_options< optimize_size >::type > > + ("set(sizeopt=true)", "set(sizeopt=false)"); + launch_tests< set, set, std::allocator, tree_assoc_options< optimize_size >::type > > + ("set(sizeopt=true)", "set(sizeopt=false)"); + + return 0; } diff --git a/bench/bench_set.hpp b/bench/bench_set.hpp new file mode 100644 index 0000000..f606b38 --- /dev/null +++ b/bench/bench_set.hpp @@ -0,0 +1,462 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2014. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_BENCH_BENCH_SET_HPP +#define BOOST_CONTAINER_BENCH_BENCH_SET_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +using boost::timer::cpu_timer; +using boost::timer::cpu_times; +using boost::timer::nanosecond_type; +using namespace boost::container; + +#ifdef NDEBUG +static const std::size_t NElements = 1000; +#else +static const std::size_t NElements = 100; +#endif + +#ifdef NDEBUG +static const std::size_t NIter = 500; +#else +static const std::size_t NIter = 50; +#endif + +void compare_times(cpu_times time_numerator, cpu_times time_denominator){ + std::cout << ((double)time_numerator.wall/(double)time_denominator.wall) << std::endl; + std::cout << "----------------------------------------------" << '\n' << std::endl; +} + +vector sorted_unique_range_int; +vector sorted_range_int; +vector random_unique_range_int; +vector random_range_int; + +void fill_range_ints() +{ + //sorted_unique_range_int + sorted_unique_range_int.resize(NElements); + for(std::size_t i = 0, max = sorted_unique_range_int.size(); i != max; ++i){ + sorted_unique_range_int[i] = static_cast(i); + } + //sorted_range_int + sorted_range_int = sorted_unique_range_int; + sorted_range_int.insert(sorted_range_int.end(), sorted_unique_range_int.begin(), sorted_unique_range_int.end()); + std::sort(sorted_range_int.begin(), sorted_range_int.end()); + + //random_range_int + std::srand(0); + random_range_int.assign(sorted_range_int.begin(), sorted_range_int.end()); + std::random_shuffle(random_range_int.begin(), random_range_int.end()); + //random_unique_range_int + std::srand(0); + random_unique_range_int.assign(sorted_unique_range_int.begin(), sorted_unique_range_int.end()); + std::random_shuffle(random_unique_range_int.begin(), random_unique_range_int.end()); +} + +vector sorted_unique_range_string; +vector sorted_range_string; +vector random_unique_range_string; +vector random_range_string; + +void fill_range_strings() +{ + //sorted_unique_range_int + sorted_unique_range_string.resize(NElements); + for(std::size_t i = 0, max = sorted_unique_range_string.size(); i != max; ++i){ + std::stringstream sstr; + sstr << std::setfill('0') << std::setw(10) << i; + sorted_unique_range_string[i] = "really_long_long_prefix_to_ssb_and_increase_comparison_costs_"; + const std::string &s = sstr.str(); + sorted_unique_range_string[i].append(s.begin(), s.end()); + } + //sorted_range_string + sorted_range_string = sorted_unique_range_string; + sorted_range_string.insert(sorted_range_string.end(), sorted_unique_range_string.begin(), sorted_unique_range_string.end()); + std::sort(sorted_range_string.begin(), sorted_range_string.end()); + + //random_range_string + std::srand(0); + random_range_string.assign(sorted_range_string.begin(), sorted_range_string.end()); + std::random_shuffle(random_range_string.begin(), random_range_string.end()); + //random_unique_range_string + std::srand(0); + random_unique_range_string.assign(sorted_unique_range_string.begin(), sorted_unique_range_string.end()); + std::random_shuffle(random_unique_range_string.begin(), random_unique_range_string.end()); +} + +template +struct range_provider; + +template<> +struct range_provider +{ + typedef vector type; + + static type &sorted_unique() + { return sorted_unique_range_int; } + + static type &sorted() + { return sorted_range_int; } + + static type &random_unique() + { return random_unique_range_int; } + + static type &random() + { return random_range_int; } +}; + +template<> +struct range_provider +{ + typedef vector type; + + static type &sorted_unique() + { return sorted_unique_range_string; } + + static type &sorted() + { return sorted_range_string; } + + static type &random_unique() + { return random_unique_range_string; } + + static type &random() + { return random_range_string; } +}; + +template +cpu_times copy_destroy_time(vector &unique_range) +{ + cpu_timer copy_timer, assign_timer, destroy_timer; + + cpu_timer total_time; + + for(std::size_t i = 0; i != NIter; ++i){ + { + C c(unique_range.begin(), unique_range.end()); + total_time.resume(); + copy_timer.resume(); + C caux(c); + copy_timer.stop(); + assign_timer.resume(); + c = caux; + assign_timer.stop(); + destroy_timer.resume(); + } + destroy_timer.stop(); + total_time.stop(); + } + total_time.stop(); + + std::cout << " Copy sorted range " << boost::timer::format(copy_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Assign sorted range " << boost::timer::format(assign_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Destroy " << boost::timer::format(destroy_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws\n") << std::endl; + return total_time.elapsed(); +} + +template +cpu_times construct_time(vector &unique_range, vector &range, const char *RangeType) +{ + cpu_timer sur_timer, sr_timer; + + cpu_timer total_time; + + for(std::size_t i = 0; i != NIter; ++i){ + { + sur_timer.resume(); + total_time.resume(); + C c(unique_range.begin(), unique_range.end()); + sur_timer.stop(); + total_time.stop(); + } + { + total_time.resume(); + sr_timer.resume(); + C c(range.begin(), range.end()); + sr_timer.stop(); + total_time.stop(); + } + } + + std::cout << " Construct " << RangeType << " unique_range " << boost::timer::format(sur_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Construct " << RangeType << " range " << boost::timer::format(sr_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws\n") << std::endl; + return total_time.elapsed(); +} + +template +cpu_times insert_time(vector &unique_range, vector &range, const char *RangeType) +{ + cpu_timer ur_timer,r_timer; + ur_timer.stop();r_timer.stop(); + + cpu_timer total_time; + total_time.resume(); + + for(std::size_t i = 0; i != NIter; ++i){ + { + total_time.resume(); + ur_timer.resume(); + C c; + c.insert(unique_range.begin(), unique_range.end()); + ur_timer.stop(); + total_time.stop(); + } + { + total_time.resume(); + r_timer.resume(); + C c; + c.insert(range.begin(), range.end()); + r_timer.stop(); + total_time.stop(); + } + } + + std::cout << " Insert " << RangeType << " unique_range " << boost::timer::format(ur_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Insert " << RangeType << " range " << boost::timer::format(r_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws\n") << std::endl; + return total_time.elapsed(); +} + +template +bool check_not_end(vector &iterators, Iterator itend, std::size_t number_of_ends = 0) +{ + std::size_t end_count = 0; + for(std::size_t i = 0, max = iterators.size(); i != max; ++i){ + if(iterators[i] == itend && (++end_count > number_of_ends) ) + return false; + } + return true; +} + +template +bool check_all_not_empty(vector< std::pair > &iterator_pairs) +{ + for(std::size_t i = 0, max = iterator_pairs.size(); i != max; ++i){ + if(iterator_pairs[i].first == iterator_pairs[i].second) + return false; + } + return true; +} + +template +cpu_times search_time(vector &unique_range, const char *RangeType) +{ + cpu_timer find_timer, lower_timer, upper_timer, equal_range_timer, count_timer; + + C c(unique_range.begin(), unique_range.end()); + + cpu_timer total_time; + total_time.resume(); + + vector v_it(NElements); + vector< std::pair > v_itp(NElements); + + for(std::size_t i = 0; i != NIter; ++i){ + //Find + { + find_timer.resume(); + for(std::size_t rep = 0; rep != 2; ++rep) + for(std::size_t i = 0, max = unique_range.size(); i != max; ++i){ + v_it[i] = c.find(unique_range[i]); + } + find_timer.stop(); + if(!check_not_end(v_it, c.end())){ + std::cout << "ERROR! find all elements not found" << std::endl; + } + } + //Lower + { + lower_timer.resume(); + for(std::size_t rep = 0; rep != 2; ++rep) + for(std::size_t i = 0, max = unique_range.size(); i != max; ++i){ + v_it[i] = c.lower_bound(unique_range[i]); + } + lower_timer.stop(); + if(!check_not_end(v_it, c.end())){ + std::cout << "ERROR! lower_bound all elements not found" << std::endl; + } + } + //Upper + { + upper_timer.resume(); + for(std::size_t rep = 0; rep != 2; ++rep) + for(std::size_t i = 0, max = unique_range.size(); i != max; ++i){ + v_it[i] = c.upper_bound(unique_range[i]); + } + upper_timer.stop(); + if(!check_not_end(v_it, c.end(), 1u)){ + std::cout << "ERROR! upper_bound all elements not found" << std::endl; + } + } + //Equal + { + equal_range_timer.resume(); + for(std::size_t rep = 0; rep != 2; ++rep) + for(std::size_t i = 0, max = unique_range.size(); i != max; ++i){ + v_itp[i] = c.equal_range(unique_range[i]); + } + equal_range_timer.stop(); + if(!check_all_not_empty(v_itp)){ + std::cout << "ERROR! equal_range all elements not found" << std::endl; + } + } + //Count + { + std::size_t count = 0; + count_timer.resume(); + for(std::size_t rep = 0; rep != 2; ++rep) + for(std::size_t i = 0, max = unique_range.size(); i != max; ++i){ + count += c.count(unique_range[i]); + } + count_timer.stop(); + if(count/2 != c.size()){ + std::cout << "ERROR! count all elements not found" << std::endl; + } + } + } + total_time.stop(); + + std::cout << " Find " << RangeType << " " << boost::timer::format(find_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Lower Bound " << RangeType << " " << boost::timer::format(lower_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Upper Bound " << RangeType << " " << boost::timer::format(upper_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Equal Range " << RangeType << " " << boost::timer::format(equal_range_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Count " << RangeType << " " << boost::timer::format(count_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Total time = " << boost::timer::format(total_time.elapsed(), boost::timer::default_places, "%ws\n") << std::endl; + return total_time.elapsed(); +} + +template +void extensions_time(vector &sorted_unique_range) +{ + cpu_timer sur_timer,sur_opt_timer; + sur_timer.stop();sur_opt_timer.stop(); + + for(std::size_t i = 0; i != NIter; ++i){ + { + sur_timer.resume(); + C c(sorted_unique_range.begin(), sorted_unique_range.end()); + sur_timer.stop(); + } + { + sur_opt_timer.resume(); + C c(boost::container::ordered_unique_range, sorted_unique_range.begin(), sorted_unique_range.end()); + sur_opt_timer.stop(); + } + + } + std::cout << " Construct sorted_unique_range " << boost::timer::format(sur_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << " Construct sorted_unique_range (extension) " << boost::timer::format(sur_opt_timer.elapsed(), boost::timer::default_places, "%ws\n"); + std::cout << "Extension/Standard: "; + compare_times(sur_opt_timer.elapsed(), sur_timer.elapsed()); +} + +template +void launch_tests(const char *BoostContName, const char *StdContName) +{ + typedef range_provider get_range_t; + try { + std::cout << "**********************************************" << '\n'; + std::cout << "**********************************************" << '\n'; + std::cout << '\n'; + std::cout << BoostContName << " .VS " << StdContName << '\n'; + std::cout << '\n'; + std::cout << "**********************************************" << '\n'; + std::cout << "**********************************************" << '\n' << std::endl; + { + std::cout << "Copy/Assign/Destroy benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = copy_destroy_time< BoostClass >(get_range_t::sorted_unique()); + + std::cout << "Copy/Assign/Destroy benchmark:" << StdContName << std::endl; + cpu_times std_set_time = copy_destroy_time< StdClass >(get_range_t::sorted_unique()); + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Ordered construct benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = construct_time< BoostClass >(get_range_t::sorted_unique(), get_range_t::sorted(), "(ord)"); + + std::cout << "Ordered construct benchmark:" << StdContName << std::endl; + cpu_times std_set_time = construct_time< StdClass >(get_range_t::sorted_unique(), get_range_t::sorted(), "(ord)");; + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Random construct benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = construct_time< BoostClass >(get_range_t::random_unique(), get_range_t::random(), "(rnd)"); + + std::cout << "Random construct benchmark:" << StdContName << std::endl; + cpu_times std_set_time = construct_time< StdClass >(get_range_t::random_unique(), get_range_t::random(), "(rnd)");; + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Ordered Insert benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = insert_time< BoostClass >(get_range_t::sorted_unique(), get_range_t::sorted(), "(ord)"); + + std::cout << "Ordered Insert benchmark:" << StdContName << std::endl; + cpu_times std_set_time = insert_time< StdClass >(get_range_t::sorted_unique(), get_range_t::sorted(), "(ord)"); + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Random Insert benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = insert_time< BoostClass >(get_range_t::random_unique(), get_range_t::random(), "(rnd)"); + + std::cout << "Random Insert benchmark:" << StdContName << std::endl; + cpu_times std_set_time = insert_time< StdClass >(get_range_t::random_unique(), get_range_t::random(), "(rnd)"); + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Ordered Search benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = search_time< BoostClass >(get_range_t::sorted_unique(), "(ord)"); + + std::cout << "Ordered Search benchmark:" << StdContName << std::endl; + cpu_times std_set_time = search_time< StdClass >(get_range_t::sorted_unique(), "(ord)"); + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Random Search benchmark:" << BoostContName << std::endl; + cpu_times boost_set_time = search_time< BoostClass >(get_range_t::random_unique(), "(rnd)"); + + std::cout << "Random Search benchmark:" << StdContName << std::endl; + cpu_times std_set_time = search_time< StdClass >(get_range_t::random_unique(), "(rnd)"); + + std::cout << BoostContName << "/" << StdContName << ": "; + compare_times(boost_set_time, std_set_time); + } + { + std::cout << "Extensions benchmark:" << BoostContName << std::endl; + extensions_time< BoostClass >(get_range_t::sorted_unique()); + } + + }catch(std::exception e){ + std::cout << e.what(); + } +} + +#endif //#ifndef BOOST_CONTAINER_BENCH_BENCH_SET_HPP diff --git a/bench/bench_set_alloc_v2.cpp b/bench/bench_set_alloc_v2.cpp new file mode 100644 index 0000000..b927590 --- /dev/null +++ b/bench/bench_set_alloc_v2.cpp @@ -0,0 +1,29 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include "boost/container/allocator.hpp" +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //set<..., allocator_v2> vs. set + launch_tests< set, allocator >, set > + ("set", "set"); + launch_tests< set, allocator >, set > + ("set", "set"); + + return 0; +} diff --git a/bench/bench_set_avl.cpp b/bench/bench_set_avl.cpp new file mode 100644 index 0000000..6d0d77d --- /dev/null +++ b/bench/bench_set_avl.cpp @@ -0,0 +1,38 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include + +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //set(AVL) vs set(RB) + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type >, set > + ("set(AVL)", "set(RB)"); + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type >, set > + ("set(AVL)", "set(RB)"); + + //set(AVL,sizeopt) vs set(AVL,!sizeopt) + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type > + , set, std::allocator, tree_assoc_options< tree_type, optimize_size >::type > > + ("set(AVL,sizeopt=true)", "set(AVL,sizeopt=false)"); + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type > + , set, std::allocator, tree_assoc_options< tree_type, optimize_size >::type > > + ("set(AVL,sizeopt=true)", "set(AVL,sizeopt=false)"); + + return 0; +} diff --git a/bench/bench_set_multi.cpp b/bench/bench_set_multi.cpp new file mode 100644 index 0000000..a01dbc9 --- /dev/null +++ b/bench/bench_set_multi.cpp @@ -0,0 +1,30 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include + +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //multiset vs std::multiset + launch_tests< multiset , std::multiset > + ("multiset", "std::multiset"); + launch_tests< multiset , std::multiset > + ("multiset", "std::multiset"); + + return 0; +} diff --git a/bench/bench_set_sg.cpp b/bench/bench_set_sg.cpp new file mode 100644 index 0000000..c988438 --- /dev/null +++ b/bench/bench_set_sg.cpp @@ -0,0 +1,28 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //set(RB) vs set(SG) + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type >, set > + ("set(SG)", "set(RB)"); + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type >, set > + ("set(SG)", "set(RB)"); + + return 0; +} diff --git a/bench/bench_set_sp.cpp b/bench/bench_set_sp.cpp new file mode 100644 index 0000000..0f86ed4 --- /dev/null +++ b/bench/bench_set_sp.cpp @@ -0,0 +1,28 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include "boost/container/set.hpp" +#include "bench_set.hpp" + +int main() +{ + using namespace boost::container; + + fill_range_ints(); + fill_range_strings(); + + //set(RB) vs set(SP) + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type >, set > + ("set(SP)", "set(RB)"); + launch_tests< set, std::allocator, tree_assoc_options< tree_type >::type >, set > + ("set(SP)", "set(RB)"); + + return 0; +} diff --git a/bench/bench_static_vector.cpp b/bench/bench_static_vector.cpp index 71e48a9..a331eb9 100644 --- a/bench/bench_static_vector.cpp +++ b/bench/bench_static_vector.cpp @@ -4,8 +4,8 @@ // @date Aug 14, 2011 // @author Andrew Hundt // -// (C) 2011-2012 Andrew Hundt -// (C) 2013 Ion Gaztanaga +// (C) 2011-2013 Andrew Hundt +// (C) 2013-2013 Ion Gaztanaga // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at @@ -28,7 +28,7 @@ using boost::timer::cpu_times; using boost::timer::nanosecond_type; #ifdef NDEBUG -static const std::size_t N = 1000; +static const std::size_t N = 300; #else static const std::size_t N = 100; #endif @@ -141,5 +141,5 @@ int main() }catch(std::exception e){ std::cout << e.what(); } - return 1; + return 0; } diff --git a/bench/detail/varray.hpp b/bench/detail/varray.hpp index 874daae..eb63470 100644 --- a/bench/detail/varray.hpp +++ b/bench/detail/varray.hpp @@ -10,7 +10,7 @@ #ifndef BOOST_CONTAINER_DETAIL_VARRAY_HPP #define BOOST_CONTAINER_DETAIL_VARRAY_HPP -#if (defined _MSC_VER) +#if defined(_MSC_VER) # pragma once #endif @@ -19,8 +19,8 @@ #include #include "varray_util.hpp" -#include "varray_concept.hpp" -#include +//#include "varray_concept.hpp" +//#include #ifndef BOOST_NO_EXCEPTIONS #include @@ -229,7 +229,7 @@ class varray (varray) ); - BOOST_CONCEPT_ASSERT((concept::VArrayStrategy)); + //BOOST_CONCEPT_ASSERT((concept::VArrayStrategy)); typedef boost::aligned_storage< sizeof(Value[Capacity]), @@ -353,7 +353,7 @@ public: varray(Iterator first, Iterator last) : m_size(0) { - BOOST_CONCEPT_ASSERT((boost_concepts::ForwardTraversal)); // Make sure you passed a ForwardIterator + //BOOST_CONCEPT_ASSERT((boost_concepts::ForwardTraversal)); // Make sure you passed a ForwardIterator this->assign(first, last); // may throw } @@ -890,7 +890,7 @@ public: template iterator insert(iterator position, Iterator first, Iterator last) { - BOOST_CONCEPT_ASSERT((boost_concepts::ForwardTraversal)); // Make sure you passed a ForwardIterator + //BOOST_CONCEPT_ASSERT((boost_concepts::ForwardTraversal)); // Make sure you passed a ForwardIterator typedef typename boost::iterator_traversal::type traversal; this->insert_dispatch(position, first, last, traversal()); @@ -975,7 +975,7 @@ public: template void assign(Iterator first, Iterator last) { - BOOST_CONCEPT_ASSERT((boost_concepts::ForwardTraversal)); // Make sure you passed a ForwardIterator + //BOOST_CONCEPT_ASSERT((boost_concepts::ForwardTraversal)); // Make sure you passed a ForwardIterator typedef typename boost::iterator_traversal::type traversal; this->assign_dispatch(first, last, traversal()); // may throw @@ -1728,7 +1728,7 @@ private: template void insert_dispatch(iterator position, Iterator first, Iterator last, boost::random_access_traversal_tag const&) { - BOOST_CONCEPT_ASSERT((boost_concepts::RandomAccessTraversal)); // Make sure you passed a RandomAccessIterator + //BOOST_CONCEPT_ASSERT((boost_concepts::RandomAccessTraversal)); // Make sure you passed a RandomAccessIterator errh::check_iterator_end_eq(*this, position); @@ -2015,7 +2015,7 @@ public: void insert(iterator, Iterator first, Iterator last) { // TODO - add MPL_ASSERT, check if Iterator is really an iterator - typedef typename boost::iterator_traversal::type traversal; + //typedef typename boost::iterator_traversal::type traversal; errh::check_capacity(*this, std::distance(first, last)); // may throw } @@ -2039,7 +2039,7 @@ public: void assign(Iterator first, Iterator last) { // TODO - add MPL_ASSERT, check if Iterator is really an iterator - typedef typename boost::iterator_traversal::type traversal; + //typedef typename boost::iterator_traversal::type traversal; errh::check_capacity(*this, std::distance(first, last)); // may throw } diff --git a/bench/detail/varray_util.hpp b/bench/detail/varray_util.hpp index 23f0d24..01b533b 100644 --- a/bench/detail/varray_util.hpp +++ b/bench/detail/varray_util.hpp @@ -566,13 +566,6 @@ template inline void construct(DisableTrivialInit const&, I pos, BOOST_RV_REF(P) p) { - typedef typename - ::boost::mpl::and_< - is_corresponding_value, - ::boost::has_trivial_copy

- >::type - use_memcpy; - typedef typename boost::iterator_value::type V; new (static_cast(boost::addressof(*pos))) V(::boost::move(p)); // may throw } diff --git a/bench/varray.hpp b/bench/varray.hpp index 8dcb5de..8022b9a 100644 --- a/bench/varray.hpp +++ b/bench/varray.hpp @@ -10,13 +10,14 @@ #ifndef BOOST_CONTAINER_VARRAY_HPP #define BOOST_CONTAINER_VARRAY_HPP -#if (defined _MSC_VER) +#if defined(_MSC_VER) # pragma once #endif #include #include "detail/varray.hpp" +#include namespace boost { namespace container { diff --git a/build/Jamfile.v2 b/build/Jamfile.v2 new file mode 100644 index 0000000..a371c4a --- /dev/null +++ b/build/Jamfile.v2 @@ -0,0 +1,23 @@ +# (C) Copyright Vladimir Prus, David Abrahams, Michael Stevens, Hartmut Kaiser, +# Ion Gaztanaga 2007-2008 +# Use, modification and distribution are subject to the +# Boost Software License, Version 1.0. (See accompanying file +# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +project boost/container + : source-location ../src + : usage-requirements # pass these requirement to dependents (i.e. users) + shared:BOOST_CONTAINER_DYN_LINK=1 + static:BOOST_CONTAINER_STATIC_LINK=1 + ; + +# Base names of the source files for libboost_container +CPP_SOURCES = alloc_lib ; + +lib boost_container + : $(CPP_SOURCES).c + : shared:BOOST_CONTAINER_DYN_LINK=1 + static:BOOST_CONTAINER_STATIC_LINK=1 + ; + +boost-install boost_container ; \ No newline at end of file diff --git a/doc/Jamfile.v2 b/doc/Jamfile.v2 index fe7f054..90d6feb 100644 --- a/doc/Jamfile.v2 +++ b/doc/Jamfile.v2 @@ -1,6 +1,6 @@ # Boost.Container library documentation Jamfile --------------------------------- # -# Copyright Ion Gaztanaga 2009-2012. Use, modification and +# Copyright Ion Gaztanaga 2009-2013. Use, modification and # distribution is subject to the Boost Software License, Version # 1.0. (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) @@ -35,7 +35,9 @@ doxygen autodoc \"BOOST_RV_REF_BEG=\" \\ \"BOOST_RV_REF_END=&&\" \\ \"BOOST_COPY_ASSIGN_REF(T)=const T &\" \\ - \"BOOST_FWD_REF(a)=a &&\"" + \"BOOST_FWD_REF(a)=a &&\" \\ + \"BOOST_INTRUSIVE_OPTION_CONSTANT(OPTION_NAME, TYPE, VALUE, CONSTANT_NAME) = template struct OPTION_NAME{};\" \\ + \"BOOST_INTRUSIVE_OPTION_TYPE(OPTION_NAME, TYPE, TYPEDEF_EXPR, TYPEDEF_NAME) = template struct OPTION_NAME{};\" " "boost.doxygen.reftitle=Boost.Container Header Reference" ; diff --git a/doc/container.qbk b/doc/container.qbk index 0c88b82..302773f 100644 --- a/doc/container.qbk +++ b/doc/container.qbk @@ -49,9 +49,13 @@ In short, what does [*Boost.Container] offer? [section:introduction_building_container Building Boost.Container] -There is no need to compile [*Boost.Container], since it's -a header only library. Just include your Boost header directory in your -compiler include path. +There is no need to compile [*Boost.Container] if you don't use [link container.extended_functionality.extended_allocators Extended Allocators] +since in that case it's a header-only library. Just include your Boost header directory in your compiler include path. + +[link container.extended_functionality.extended_allocators Extended Allocators] are +implemented as a separately compiled library, so you must install binaries in a location that can be found by your linker +when using these classes. If you followed the [@http://www.boost.org/doc/libs/release/more/getting_started/index.html Boost Getting Started] instructions, +that's already been done for you. [endsect] @@ -148,12 +152,19 @@ today, in fact, implementors would have to go out of their way to prohibit it!]] C++11 standard is also cautious about incomplete types and STL: ["['17.6.4.8 Other functions (...) 2. the effects are undefined in the following cases: (...) In particular - if an incomplete type (3.9) is used as a template argument when instantiating a template component, -unless specifically allowed for that component]]. Fortunately [*Boost.Container] containers are designed -to support type erasure and recursive types, so let's see some examples: +unless specifically allowed for that component]]. + +Fortunately all [*Boost.Container] containers except +[classref boost::container::static_vector static_vector] and +[classref boost::container::basic_string basic_string] are designed to support incomplete types. +[classref boost::container::static_vector static_vector] is special because +it statically allocates memory for `value_type` and this requires complete types and +[classref boost::container::basic_string basic_string] implements Small String Optimization which +also requires complete types. [section:recursive_containers Recursive containers] -All containers offered by [*Boost.Container] can be used to define recursive containers: +Most [*Boost.Container] containers can be used to define recursive containers: [import ../example/doc_recursive_containers.cpp] [doc_recursive_containers] @@ -261,8 +272,8 @@ When dealing with user-defined classes, (e.g. when constructing user-defined cla propagate error situations internally as no error will be propagated through [*Boost.Container]. * If `BOOST_NO_EXCEPTIONS` is *not* defined, the library propagates exceptions offering the exception guarantees detailed in the documentation. -When the library needs to throw an exception (such as `out_of_range` when an incorrect index is used in `vector::at`)], the library calls -a throw callback declared in ``: +When the library needs to throw an exception (such as `out_of_range` when an incorrect index is used in `vector::at`), the library calls +a throw-callback declared in [headerref boost/container/throw_exception.hpp]: * If `BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS` is defined, then the programmer must provide its own definition for all `throw_xxx` functions. Those functions can't return, they must throw an exception or call `std::exit` or `std::abort`. @@ -522,6 +533,168 @@ using [@http://en.cppreference.com/w/cpp/language/default_initialization default [endsect] +[section:ordered_range_insertion Ordered range insertion for associative containers (['ordered_unique_range], ['ordered_range]) ] + +When filling associative containers big performance gains can be achieved if the input range to be inserted +is guaranteed by the user to be ordered according to the predicate. This can happen when inserting values from a `set` to +a `multiset` or between different associative container families (`[multi]set/map` vs. `flat_[multi]set/map`). + +[*Boost.Container] has some overloads for constructors and insertions taking an `ordered_unique_range_t` or +an `ordered_range_t` tag parameters as the first argument. When an `ordered_unique_range_t` overload is used, the +user notifies the container that the input range is ordered according to the container predicate and has no +duplicates. When an `ordered_range_t` overload is used, the +user notifies the container that the input range is ordered according to the container predicate but it might +have duplicates. With this information, the container can avoid multiple predicate calls and improve insertion +times. + +[endsect] + +[section:configurable_tree_based_associative_containers Configurable tree-based associative ordered containers] + +[classref boost::container::set set], [classref boost::container::multiset multiset], +[classref boost::container::map map] and [classref boost::container::multimap multimap] associative containers +are implemented as binary search trees which offer the needed complexity and stability guarantees required by the +C++ standard for associative containers. + +[*Boost.Container] offers the possibility to configure at compile time some parameters of the binary search tree +implementation. This configuration is passed as the last template parameter and defined using the utility class +[classref boost::container::tree_assoc_options tree_assoc_options]. + +The following parameters can be configured: + +* The underlying [*tree implementation] type ([classref boost::container::tree_type tree_type]). + By default these containers use a red-black tree but the user can use other tree types: + * [@http://en.wikipedia.org/wiki/Red%E2%80%93black_tree Red-Black Tree] + * [@http://en.wikipedia.org/wiki/Avl_trees AVL tree] + * [@http://en.wikipedia.org/wiki/Scapegoat_tree Scapegoat tree]. In this case Insertion and Deletion + are amortized O(log n) instead of O(log n). + * [@http://en.wikipedia.org/wiki/Splay_tree Splay tree]. In this case Searches, Insertions and Deletions + are amortized O(log n) instead of O(log n). + +* Whether the [*size saving] mechanisms are used to implement the tree nodes + ([classref boost::container::optimize_size optimize_size]). By default this option is activated and is only + meaningful to red-black and avl trees (in other cases, this option will be ignored). + This option will try to put rebalancing metadata inside the "parent" pointer of the node if the pointer + type has enough alignment. Usually, due to alignment issues, the metadata uses the size of a pointer yielding + to four pointer size overhead per node, whereas activating this option usually leads to 3 pointer size overhead. + Although some mask operations must be performed to extract + data from this special "parent" pointer, in several systems this option also improves performance due to the + improved cache usage produced by the node size reduction. + +See the following example to see how [classref boost::container::tree_assoc_options tree_assoc_options] can be +used to customize these containers: + +[import ../example/doc_custom_tree.cpp] +[doc_custom_tree] + +[endsect] + +[section:constant_time_range_splice Constant-time range splice for `(s)list`] + +In the first C++ standard `list::size()` was not required to be constant-time, +and that caused some controversy in the C++ community. Quoting Howard Hinnant's +[@http://home.roadrunner.com/~hinnant/On_list_size.html ['On List Size]] paper: + +[: ['There is a considerable debate on whether `std::list::size()` should be O(1) or O(N). +The usual argument notes that it is a tradeoff with:] + +`splice(iterator position, list& x, iterator first, iterator last);` + +['If size() is O(1) and this != &x, then this method must perform a linear operation so that it +can adjust the size member in each list]] + +C++11 definitely required `size()` to be O(1), so range splice became O(N). However, +Howard Hinnant's paper proposed a new `splice` overload so that even O(1) `list:size()` +implementations could achieve O(1) range splice when the range size was known to the caller: + +[: `void splice(iterator position, list& x, iterator first, iterator last, size_type n);` + + [*Effects]: Inserts elements in the range [first, last) before position and removes the elements from x. + + [*Requires]: [first, last) is a valid range in x. The result is undefined if position is an iterator in the range [first, last). Invalidates only the iterators and references to the spliced elements. n == distance(first, last). + + [*Throws]: Nothing. + + [*Complexity]: Constant time. +] + +This new splice signature allows the client to pass the distance of the input range in. +This information is often available at the call site. If it is passed in, +then the operation is constant time, even with an O(1) size. + +[*Boost.Container] implements this overload for `list` and a modified version of it for `slist` +(as `slist::size()` is also `O(1)`). + +[endsect] + +[section:extended_allocators Extended allocators] + +Many C++ programmers have ever wondered where does good old realloc fit in C++. And that's a good question. +Could we improve [classref boost::container::vector vector] performance using memory expansion mechanisms +to avoid too many copies? But [classref boost::container::vector vector] is not the only container that +could benefit from an improved allocator interface: we could take advantage of the insertion of multiple +elements in [classref boost::container::list list] using a burst allocation mechanism that could amortize +costs (mutex locks, free memory searches...) that can't be amortized when using single node allocation +strategies. + +These improvements require extending the STL allocator interface and use make use of a new +general purpose allocator since new and delete don't offer expansion and burst capabilities. + +* [*Boost.Container] containers support an extended allocator interface based on an evolution of proposals +[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1953.html N1953: Upgrading the Interface of Allocators using API Versioning], +[@http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2045.html N2045: Improving STL allocators] +and the article +[@http://www.drivehq.com/web/igaztanaga/allocplus/ Applying classic memory allocation strategies to C++ containers]. +The extended allocator interface is implemented by [classref boost::container::allocator allocator], +[classref boost::container::adaptive_pool adaptive_pool] and [classref boost::container::node_allocator node_allocator] +classes. + +* Extended allocators use a modified [@http://g.oswego.edu/dl/html/malloc.html Doug Lea Malloc (DLMalloc)] low-level +allocator and offers an C API to implement memory expansion and burst allocations. DLmalloc is known to be very size +and speed efficient, and this allocator is used as the basis of many malloc implementations, including multithreaded +allocators built above DLmalloc (See [@http://www.malloc.de/en/ ptmalloc2, ptmalloc3] or +[@http://www.nedprod.com/programs/portable/nedmalloc/ nedmalloc]). This low-level allocator is implemented as +a separately compiled library whereas [classref boost::container::allocator allocator], +[classref boost::container::adaptive_pool adaptive_pool] and [classref boost::container::node_allocator node_allocator] +are header-only classes. + +The following extended allocators are provided: + +* [classref boost::container::allocator allocator]: This extended allocator offers expansion, shrink-in place + and burst allocation capabilities implemented as a thin wrapper around the modified DLMalloc. + It can be used with all containers and it should be the default choice when the programmer wants to use + extended allocator capabilities. + +* [classref boost::container::node_allocator node_allocator]: It's a + [@http://www.boost.org/doc/libs/1_55_0/libs/pool/doc/html/boost_pool/pool/pooling.html#boost_pool.pool.pooling.simple Simple Segregated Storage] + allocator, similar to [*Boost.Pool] that takes advantage of the modified DLMalloc burst interface. It does not return + memory to the DLMalloc allocator (and thus, to the system), unless explicitly requested. It does offer a very small + memory overhead so it's suitable for node containers ([boost::container::list list], [boost::container::slist slist] + [boost::container::set set]...) that allocate very small `value_type`s and it offers improved node allocation times + for single node allocations with respecto to [classref boost::container::allocator allocator]. + +* [classref boost::container::adaptive_pool adaptive_pool]: It's a low-overhead node allocator that can return memory + to the system. The overhead can be very low (< 5% for small nodes) and it's nearly as fast as [classref boost::container::node_allocator node_allocator]. + It's also suitable for node containers. + +Use them simply specifying the new allocator in the corresponding template argument of your favourite container: + +[import ../example/doc_extended_allocators.cpp] +[doc_extended_allocators] + +[endsect] + +[/ +/a__section:previous_element_slist Previous element for slist__a +/ +/The C++11 `std::forward_list` class implement a singly linked list, similar to `slist`, and these +/containers only offer forward iterators and implement insertions and splice operations that operate with ranges +/to be inserted ['after] that position. In those cases, sometimes it's interesting to obtain an iterator pointing +/to the previous element of another element. This operation can be implemented +/ +/a__endsect__a +] + [/ /a__section:get_stored_allocator Obtain stored allocator__a / @@ -532,18 +705,6 @@ using [@http://en.cppreference.com/w/cpp/language/default_initialization default /http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html / /a__endsect__a -/ -/a__section:ordered_range_insertion Ordered range insertion (a__'ordered_unique_range__a, a__'ordered_range__a) __a -/ -/a__endsect__a -/ -/a__section:constant_time_range_splice Constant-time range splice__a -/ -/a__endsect__a -/ -/a__section:previous_element_slist Slist previous element__a -/ -/a__endsect__a /] [endsect] @@ -709,9 +870,10 @@ use [*Boost.Container]? There are several reasons for that: * Default constructors don't allocate memory at all, which improves performance and usually implies a no-throw guarantee (if predicate's or allocator's default constructor doesn't throw). * Small string optimization for [classref boost::container::basic_string basic_string]. -* New extensions beyond the standard based on user feedback to improve code performance. +* [link container.extended_functionality Extended functionality] beyond the standard based + on user feedback to improve code performance. * You need a portable implementation that works when compiling without exceptions support or - you need to customize the error handling when a container needs to signall an exceptional error. + you need to customize the error handling when a container needs to signal an exceptional error. [endsect] @@ -759,6 +921,21 @@ use [*Boost.Container]? There are several reasons for that: [section:release_notes Release Notes] +[section:release_notes_boost_1_56_00 Boost 1.56 Release] + +* Added DlMalloc-based [link container.extended_functionality.extended_allocators Extended Allocators]. + +* [link container.extended_functionality.configurable_tree_based_associative_containers Improved configurability] + of tree-based ordered associative containers. AVL, Scapegoat and Splay trees are now available + to implement [classref boost::container::set set], [classref boost::container::multiset multiset], + [classref boost::container::map map] and [classref boost::container::multimap multimap]. + +* Fixed bugs: + * [@https://svn.boost.org/trac/boost/ticket/9338 #9338: ['"VS2005 compiler errors in swap() definition after including container/memory_util.hpp"]]. + * [@https://svn.boost.org/trac/boost/ticket/9648 #9648: ['"string construction optimization - char_traits::copy could be used ..."]]. + +[endsect] + [section:release_notes_boost_1_55_00 Boost 1.55 Release] * Implemented [link container.main_features.scary_iterators SCARY iterators]. @@ -769,7 +946,8 @@ use [*Boost.Container]? There are several reasons for that: [@https://svn.boost.org/trac/boost/ticket/9009 #9009], [@https://svn.boost.org/trac/boost/ticket/9064 #9064], [@https://svn.boost.org/trac/boost/ticket/9092 #9092], - [@https://svn.boost.org/trac/boost/ticket/9108 #9108]. + [@https://svn.boost.org/trac/boost/ticket/9108 #9108], + [@https://svn.boost.org/trac/boost/ticket/9166 #9166], [endsect] diff --git a/example/Jamfile.v2 b/example/Jamfile.v2 index 2371b80..58ebcdd 100644 --- a/example/Jamfile.v2 +++ b/example/Jamfile.v2 @@ -21,7 +21,7 @@ rule test_all for local fileb in [ glob doc_*.cpp ] { - all_rules += [ run $(fileb) + all_rules += [ run $(fileb) /boost/container//boost_container /boost/timer//boost_timer : # additional args : # test-files : # requirements diff --git a/example/doc_custom_tree.cpp b/example/doc_custom_tree.cpp new file mode 100644 index 0000000..651dd22 --- /dev/null +++ b/example/doc_custom_tree.cpp @@ -0,0 +1,64 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#include +#include +//[doc_custom_tree +#include +#include + +int main () +{ + using namespace boost::container; + + //First define several options + // + + //This option specifies an AVL tree based associative container + typedef tree_assoc_options< tree_type >::type AVLTree; + + //This option specifies an AVL tree based associative container + //disabling node size optimization. + typedef tree_assoc_options< tree_type + , optimize_size >::type AVLTreeNoSizeOpt; + + //This option specifies an Splay tree based associative container + typedef tree_assoc_options< tree_type >::type SplayTree; + + //Now define new tree-based associative containers + // + + //AVLTree based set container + typedef set, std::allocator, AVLTree> AvlSet; + + //AVLTree based set container without size optimization + typedef set, std::allocator, AVLTreeNoSizeOpt> AvlSetNoSizeOpt; + + //Splay tree based multiset container + typedef multiset, std::allocator, SplayTree> SplayMultiset; + + //Use them + // + AvlSet avl_set; + avl_set.insert(0); + assert(avl_set.find(0) != avl_set.end()); + + AvlSetNoSizeOpt avl_set_no_szopt; + avl_set_no_szopt.insert(1); + avl_set_no_szopt.insert(1); + assert(avl_set_no_szopt.count(1) == 1); + + SplayMultiset splay_mset; + splay_mset.insert(2); + splay_mset.insert(2); + assert(splay_mset.count(2) == 2); + return 0; +} +//] +#include diff --git a/example/doc_emplace.cpp b/example/doc_emplace.cpp index d494061..76b5939 100644 --- a/example/doc_emplace.cpp +++ b/example/doc_emplace.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/example/doc_extended_allocators.cpp b/example/doc_extended_allocators.cpp new file mode 100644 index 0000000..0eceba4 --- /dev/null +++ b/example/doc_extended_allocators.cpp @@ -0,0 +1,54 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#include +#include +//[doc_extended_allocators +#include +#include +#include +#include + +//"allocator" is a general purpose allocator that can reallocate +//memory, something useful for vector and flat associative containers +#include + +//"adaptive_pool" is a node allocator, specially suited for +//node-based containers +#include + +int main () +{ + using namespace boost::container; + + //A vector that can reallocate memory to implement faster insertions + vector > extended_alloc_vector; + + //A flat set that can reallocate memory to implement faster insertions + flat_set, allocator > extended_alloc_flat_set; + + //A list that can manages nodes to implement faster + //range insertions and deletions + list > extended_alloc_list; + + //A set that can recycle nodes to implement faster + //range insertions and deletions + set, adaptive_pool > extended_alloc_set; + + //Now user them as always + extended_alloc_vector.push_back(0); + extended_alloc_flat_set.insert(0); + extended_alloc_list.push_back(0); + extended_alloc_set.insert(0); + + //... + return 0; +} +//] +#include diff --git a/example/doc_move_containers.cpp b/example/doc_move_containers.cpp index 867db0b..ffb09de 100644 --- a/example/doc_move_containers.cpp +++ b/example/doc_move_containers.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/example/doc_recursive_containers.cpp b/example/doc_recursive_containers.cpp index e486209..8e6c33f 100644 --- a/example/doc_recursive_containers.cpp +++ b/example/doc_recursive_containers.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,9 +11,10 @@ #include //[doc_recursive_containers #include +#include +#include #include #include -#include #include using namespace boost::container; @@ -23,6 +24,10 @@ struct data int i_; //A vector holding still undefined class 'data' vector v_; + //A stable_vector holding still undefined class 'data' + stable_vector sv_; + //A stable_vector holding still undefined class 'data' + deque d_; //A list holding still undefined 'data' list l_; //A map holding still undefined 'data' diff --git a/example/doc_type_erasure.cpp b/example/doc_type_erasure.cpp index 1c56f7f..e776062 100644 --- a/example/doc_type_erasure.cpp +++ b/example/doc_type_erasure.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2009-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/include/boost/container/adaptive_pool.hpp b/include/boost/container/adaptive_pool.hpp new file mode 100644 index 0000000..c176547 --- /dev/null +++ b/include/boost/container/adaptive_pool.hpp @@ -0,0 +1,390 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_ADAPTIVE_POOL_HPP +#define BOOST_CONTAINER_ADAPTIVE_POOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace container { + +//!An STL node allocator that uses a modified DLMalloc as memory +//!source. +//! +//!This node allocator shares a segregated storage between all instances +//!of adaptive_pool with equal sizeof(T). +//! +//!NodesPerBlock is the number of nodes allocated at once when the allocator +//!needs runs out of nodes. MaxFreeBlocks is the maximum number of totally free blocks +//!that the adaptive node pool will hold. The rest of the totally free blocks will be +//!deallocated to the memory manager. +//! +//!OverheadPercent is the (approximated) maximum size overhead (1-20%) of the allocator: +//!(memory usable for nodes / total memory allocated from the memory allocator) +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +template < class T + , std::size_t NodesPerBlock = ADP_nodes_per_block + , std::size_t MaxFreeBlocks = ADP_max_free_blocks + , std::size_t OverheadPercent = ADP_overhead_percent + > +#else +template < class T + , std::size_t NodesPerBlock + , std::size_t MaxFreeBlocks + , std::size_t OverheadPercent + , unsigned Version + > +#endif +class adaptive_pool +{ + //!If Version is 1, the allocator is a STL conforming allocator. If Version is 2, + //!the allocator offers advanced expand in place and burst allocation capabilities. + public: + typedef unsigned int allocation_type; + typedef adaptive_pool + self_t; + + static const std::size_t nodes_per_block = NodesPerBlock; + static const std::size_t max_free_blocks = MaxFreeBlocks; + static const std::size_t overhead_percent = OverheadPercent; + static const std::size_t real_nodes_per_block = NodesPerBlock; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + BOOST_STATIC_ASSERT((Version <=2)); + #endif + + public: + //------- + typedef T value_type; + typedef T * pointer; + typedef const T * const_pointer; + typedef typename ::boost::container:: + container_detail::unvoid::type & reference; + typedef const typename ::boost::container:: + container_detail::unvoid::type & const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + typedef boost::container::container_detail:: + version_type version; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + typedef boost::container::container_detail:: + basic_multiallocation_chain multiallocation_chain_void; + typedef boost::container::container_detail:: + transform_multiallocation_chain + multiallocation_chain; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + //!Obtains adaptive_pool from + //!adaptive_pool + template + struct rebind + { + typedef adaptive_pool + < T2 + , NodesPerBlock + , MaxFreeBlocks + , OverheadPercent + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + , Version + #endif + > other; + }; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + private: + //!Not assignable from related adaptive_pool + template + adaptive_pool& operator= + (const adaptive_pool&); + + //!Not assignable from other adaptive_pool + adaptive_pool& operator=(const adaptive_pool&); + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + public: + //!Default constructor + adaptive_pool() BOOST_CONTAINER_NOEXCEPT + {} + + //!Copy constructor from other adaptive_pool. + adaptive_pool(const adaptive_pool &) BOOST_CONTAINER_NOEXCEPT + {} + + //!Copy constructor from related adaptive_pool. + template + adaptive_pool + (const adaptive_pool &) BOOST_CONTAINER_NOEXCEPT + {} + + //!Destructor + ~adaptive_pool() BOOST_CONTAINER_NOEXCEPT + {} + + //!Returns the number of elements that could be allocated. + //!Never throws + size_type max_size() const BOOST_CONTAINER_NOEXCEPT + { return size_type(-1)/sizeof(T); } + + //!Allocate memory for an array of count elements. + //!Throws std::bad_alloc if there is no enough memory + pointer allocate(size_type count, const void * = 0) + { + if(count > this->max_size()) + boost::container::throw_bad_alloc(); + + if(Version == 1 && count == 1){ + typedef typename container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + return pointer(static_cast(singleton_t::instance().allocate_node())); + } + else{ + return static_cast(boost_cont_malloc(count*sizeof(T))); + } + } + + //!Deallocate allocated memory. + //!Never throws + void deallocate(const pointer &ptr, size_type count) BOOST_CONTAINER_NOEXCEPT + { + (void)count; + if(Version == 1 && count == 1){ + typedef container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().deallocate_node(ptr); + } + else{ + boost_cont_free(ptr); + } + } + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, pointer reuse = pointer()) + { + std::pair ret = + this->priv_allocation_command(command, limit_size, preferred_size, received_size, reuse); + if(!ret.first && !(command & BOOST_CONTAINER_NOTHROW_ALLOCATION)) + boost::container::throw_bad_alloc(); + return ret; + } + + //!Returns maximum the number of objects the previously allocated memory + //!pointed by p can hold. + size_type size(pointer p) const BOOST_CONTAINER_NOEXCEPT + { return boost_cont_size(p); } + + //!Allocates just one object. Memory allocated with this function + //!must be deallocated only with deallocate_one(). + //!Throws bad_alloc if there is no enough memory + pointer allocate_one() + { + typedef container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + return (pointer)singleton_t::instance().allocate_node(); + } + + //!Allocates many elements of size == 1. + //!Elements must be individually deallocated with deallocate_one() + void allocate_individual(std::size_t num_elements, multiallocation_chain &chain) + { + typedef container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().allocate_nodes(num_elements, static_cast(chain)); + //typename shared_pool_t::multiallocation_chain ch; + //singleton_t::instance().allocate_nodes(num_elements, ch); + //chain.incorporate_after + //(chain.before_begin(), (T*)&*ch.begin(), (T*)&*ch.last(), ch.size()); + } + + //!Deallocates memory previously allocated with allocate_one(). + //!You should never use deallocate_one to deallocate memory allocated + //!with other functions different from allocate_one(). Never throws + void deallocate_one(pointer p) BOOST_CONTAINER_NOEXCEPT + { + typedef container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().deallocate_node(p); + } + + void deallocate_individual(multiallocation_chain &chain) BOOST_CONTAINER_NOEXCEPT + { + typedef container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + //typename shared_pool_t::multiallocation_chain ch(&*chain.begin(), &*chain.last(), chain.size()); + //singleton_t::instance().deallocate_nodes(ch); + singleton_t::instance().deallocate_nodes(chain); + } + + //!Allocates many elements of size elem_size. + //!Elements must be individually deallocated with deallocate() + void allocate_many(size_type elem_size, std::size_t n_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 ));/* + boost_cont_memchain ch; + BOOST_CONTAINER_MEMCHAIN_INIT(&ch); + if(!boost_cont_multialloc_nodes(n_elements, elem_size*sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &ch)){ + boost::container::throw_bad_alloc(); + } + chain.incorporate_after(chain.before_begin() + ,(T*)BOOST_CONTAINER_MEMCHAIN_FIRSTMEM(&ch) + ,(T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + ,BOOST_CONTAINER_MEMCHAIN_SIZE(&ch) );*/ + if(!boost_cont_multialloc_nodes(n_elements, elem_size*sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, reinterpret_cast(&chain))){ + boost::container::throw_bad_alloc(); + } + } + + //!Allocates n_elements elements, each one of size elem_sizes[i] + //!Elements must be individually deallocated with deallocate() + void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 ));/* + boost_cont_memchain ch; + BOOST_CONTAINER_MEMCHAIN_INIT(&ch); + if(!boost_cont_multialloc_arrays(n_elements, elem_sizes, sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &ch)){ + boost::container::throw_bad_alloc(); + } + chain.incorporate_after(chain.before_begin() + ,(T*)BOOST_CONTAINER_MEMCHAIN_FIRSTMEM(&ch) + ,(T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + ,BOOST_CONTAINER_MEMCHAIN_SIZE(&ch) );*/ + if(!boost_cont_multialloc_arrays(n_elements, elem_sizes, sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, reinterpret_cast(&chain))){ + boost::container::throw_bad_alloc(); + } + } + + void deallocate_many(multiallocation_chain &chain) BOOST_CONTAINER_NOEXCEPT + {/* + boost_cont_memchain ch; + void *beg(&*chain.begin()), *last(&*chain.last()); + size_t size(chain.size()); + BOOST_CONTAINER_MEMCHAIN_INIT_FROM(&ch, beg, last, size); + boost_cont_multidealloc(&ch);*/ + boost_cont_multidealloc(reinterpret_cast(&chain)); + } + + //!Deallocates all free blocks of the pool + static void deallocate_free_blocks() BOOST_CONTAINER_NOEXCEPT + { + typedef container_detail::shared_adaptive_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().deallocate_free_blocks(); + } + + //!Swaps allocators. Does not throw. If each allocator is placed in a + //!different memory segment, the result is undefined. + friend void swap(adaptive_pool &, adaptive_pool &) BOOST_CONTAINER_NOEXCEPT + {} + + //!An allocator always compares to true, as memory allocated with one + //!instance can be deallocated by another instance + friend bool operator==(const adaptive_pool &, const adaptive_pool &) BOOST_CONTAINER_NOEXCEPT + { return true; } + + //!An allocator always compares to false, as memory allocated with one + //!instance can be deallocated by another instance + friend bool operator!=(const adaptive_pool &, const adaptive_pool &) BOOST_CONTAINER_NOEXCEPT + { return false; } +/* + //!Returns address of mutable object. + //!Never throws + pointer address(reference value) const + { return pointer(boost::addressof(value)); } + + //!Returns address of non mutable object. + //!Never throws + const_pointer address(const_reference value) const + { return const_pointer(boost::addressof(value)); } + + //!Default construct an object. + //!Throws if T's default constructor throws + void construct(const pointer &ptr) + { new(ptr) value_type; } + + //!Construct a copy of the passed object. + //!Throws if T's copy constructor throws + void construct(pointer ptr, const_reference t) + { new(ptr) value_type(t); } + + //!Destroys object. Throws if object's + //!destructor throws + void destroy(const pointer &ptr) + { (void)ptr; BOOST_ASSERT(ptr); (*ptr).~value_type(); } +*/ + private: + std::pair priv_allocation_command + (allocation_type command, std::size_t limit_size + ,std::size_t preferred_size,std::size_t &received_size, void *reuse_ptr) + { + boost_cont_command_ret_t ret = {0 , 0}; + if(limit_size > this->max_size() || preferred_size > this->max_size()){ +// ret.first = 0; + return std::pair(pointer(), false); + } + std::size_t l_size = limit_size*sizeof(T); + std::size_t p_size = preferred_size*sizeof(T); + std::size_t r_size; + { + ret = boost_cont_allocation_command(command, sizeof(T), l_size, p_size, &r_size, reuse_ptr); + } + received_size = r_size/sizeof(T); + return std::pair(static_cast(ret.first), !!ret.second); + } +}; + +} //namespace container { +} //namespace boost { + +#include + +#endif //#ifndef BOOST_CONTAINER_ADAPTIVE_POOL_HPP diff --git a/include/boost/container/allocator.hpp b/include/boost/container/allocator.hpp new file mode 100644 index 0000000..af46532 --- /dev/null +++ b/include/boost/container/allocator.hpp @@ -0,0 +1,368 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_ALLOCATOR_HPP +#define BOOST_CONTAINER_ALLOCATOR_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace container { + +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + +template +class allocator +{ + typedef allocator self_t; + public: + typedef void value_type; + typedef void * pointer; + typedef const void* const_pointer; + typedef int & reference; + typedef const int & const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + typedef boost::container::container_detail:: + version_type version; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + typedef boost::container::container_detail:: + basic_multiallocation_chain multiallocation_chain; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + //!Obtains an allocator that allocates + //!objects of type T2 + template + struct rebind + { + typedef allocator< T2 + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + , Version, AllocationDisableMask + #endif + > other; + }; + + //!Default constructor + //!Never throws + allocator() + {} + + //!Constructor from other allocator. + //!Never throws + allocator(const allocator &) + {} + + //!Constructor from related allocator. + //!Never throws + template + allocator(const allocator &) + {} +}; + +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + +//!\file +//! This class is an extended STL-compatible that offers advanced allocation mechanism +//!(in-place expansion, shrinking, burst-allocation...) +//! +//! This allocator is a wrapper around a modified DLmalloc. +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +template +#else +//! If Version is 1, the allocator is a STL conforming allocator. If Version is 2, +//! the allocator offers advanced expand in place and burst allocation capabilities. +// +//! AllocationDisableMask works only if Version is 2 and it can be an inclusive OR +//! of allocation types the user wants to disable. +template +#endif //#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +class allocator +{ + typedef unsigned int allocation_type; + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + private: + + //Self type + typedef allocator self_t; + + //Not assignable from related allocator + template + allocator& operator=(const allocator&); + + //Not assignable from other allocator + allocator& operator=(const allocator&); + + static const unsigned int ForbiddenMask = + BOOST_CONTAINER_ALLOCATE_NEW | BOOST_CONTAINER_EXPAND_BWD | BOOST_CONTAINER_EXPAND_FWD ; + + //The mask can't disable all the allocation types + BOOST_STATIC_ASSERT(( (AllocationDisableMask & ForbiddenMask) != ForbiddenMask )); + + //The mask is only valid for version 2 allocators + BOOST_STATIC_ASSERT(( Version != 1 || (AllocationDisableMask == 0) )); + + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + public: + typedef T value_type; + typedef T * pointer; + typedef const T * const_pointer; + typedef T & reference; + typedef const T & const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + typedef boost::container::container_detail:: + version_type version; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + typedef boost::container::container_detail:: + basic_multiallocation_chain void_multiallocation_chain; + + typedef boost::container::container_detail:: + transform_multiallocation_chain + multiallocation_chain; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + //!Obtains an allocator that allocates + //!objects of type T2 + template + struct rebind + { + typedef allocator other; + }; + + //!Default constructor + //!Never throws + allocator() BOOST_CONTAINER_NOEXCEPT + {} + + //!Constructor from other allocator. + //!Never throws + allocator(const allocator &) BOOST_CONTAINER_NOEXCEPT + {} + + //!Constructor from related allocator. + //!Never throws + template + allocator(const allocator &) BOOST_CONTAINER_NOEXCEPT + {} + + //!Allocates memory for an array of count elements. + //!Throws std::bad_alloc if there is no enough memory + //!If Version is 2, this allocated memory can only be deallocated + //!with deallocate() or (for Version == 2) deallocate_many() + pointer allocate(size_type count, const void * hint= 0) + { + (void)hint; + if(count > this->max_size()) + boost::container::throw_bad_alloc(); + void *ret = boost_cont_malloc(count*sizeof(T)); + if(!ret) + boost::container::throw_bad_alloc(); + return static_cast(ret); + } + + //!Deallocates previously allocated memory. + //!Never throws + void deallocate(pointer ptr, size_type) BOOST_CONTAINER_NOEXCEPT + { boost_cont_free(ptr); } + + //!Returns the maximum number of elements that could be allocated. + //!Never throws + size_type max_size() const BOOST_CONTAINER_NOEXCEPT + { return size_type(-1)/sizeof(T); } + + //!Swaps two allocators, does nothing + //!because this allocator is stateless + friend void swap(self_t &, self_t &) BOOST_CONTAINER_NOEXCEPT + {} + + //!An allocator always compares to true, as memory allocated with one + //!instance can be deallocated by another instance + friend bool operator==(const allocator &, const allocator &) BOOST_CONTAINER_NOEXCEPT + { return true; } + + //!An allocator always compares to false, as memory allocated with one + //!instance can be deallocated by another instance + friend bool operator!=(const allocator &, const allocator &) BOOST_CONTAINER_NOEXCEPT + { return false; } + + //!An advanced function that offers in-place expansion shrink to fit and new allocation + //!capabilities. Memory allocated with this function can only be deallocated with deallocate() + //!or deallocate_many(). + //!This function is available only with Version == 2 + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, pointer reuse = pointer()) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + const allocation_type mask(AllocationDisableMask); + command &= ~mask; + std::pair ret = + priv_allocation_command(command, limit_size, preferred_size, received_size, reuse); + if(!ret.first && !(command & BOOST_CONTAINER_NOTHROW_ALLOCATION)) + boost::container::throw_bad_alloc(); + return ret; + } + + //!Returns maximum the number of objects the previously allocated memory + //!pointed by p can hold. + //!Memory must not have been allocated with + //!allocate_one or allocate_individual. + //!This function is available only with Version == 2 + size_type size(pointer p) const BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + return boost_cont_size(p); + } + + //!Allocates just one object. Memory allocated with this function + //!must be deallocated only with deallocate_one(). + //!Throws bad_alloc if there is no enough memory + //!This function is available only with Version == 2 + pointer allocate_one() + { + BOOST_STATIC_ASSERT(( Version > 1 )); + return this->allocate(1); + } + + //!Allocates many elements of size == 1. + //!Elements must be individually deallocated with deallocate_one() + //!This function is available only with Version == 2 + void allocate_individual(std::size_t num_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + this->allocate_many(1, num_elements, chain); + } + + //!Deallocates memory previously allocated with allocate_one(). + //!You should never use deallocate_one to deallocate memory allocated + //!with other functions different from allocate_one() or allocate_individual. + //Never throws + void deallocate_one(pointer p) BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + return this->deallocate(p, 1); + } + + //!Deallocates memory allocated with allocate_one() or allocate_individual(). + //!This function is available only with Version == 2 + void deallocate_individual(multiallocation_chain &chain) BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + return this->deallocate_many(chain); + } + + //!Allocates many elements of size elem_size. + //!Elements must be individually deallocated with deallocate() + //!This function is available only with Version == 2 + void allocate_many(size_type elem_size, std::size_t n_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 ));/* + boost_cont_memchain ch; + BOOST_CONTAINER_MEMCHAIN_INIT(&ch); + if(!boost_cont_multialloc_nodes(n_elements, elem_size*sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &ch)){ + boost::container::throw_bad_alloc(); + } + chain.incorporate_after(chain.before_begin() + ,(T*)BOOST_CONTAINER_MEMCHAIN_FIRSTMEM(&ch) + ,(T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + ,BOOST_CONTAINER_MEMCHAIN_SIZE(&ch) );*/ + if(!boost_cont_multialloc_nodes(n_elements, elem_size*sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, reinterpret_cast(&chain))){ + boost::container::throw_bad_alloc(); + } + } + + //!Allocates n_elements elements, each one of size elem_sizes[i] + //!Elements must be individually deallocated with deallocate() + //!This function is available only with Version == 2 + void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + boost_cont_memchain ch; + BOOST_CONTAINER_MEMCHAIN_INIT(&ch); + if(!boost_cont_multialloc_arrays(n_elements, elem_sizes, sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &ch)){ + boost::container::throw_bad_alloc(); + } + chain.incorporate_after(chain.before_begin() + ,(T*)BOOST_CONTAINER_MEMCHAIN_FIRSTMEM(&ch) + ,(T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + ,BOOST_CONTAINER_MEMCHAIN_SIZE(&ch) ); + /* + if(!boost_cont_multialloc_arrays(n_elements, elem_sizes, sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, reinterpret_cast(&chain))){ + boost::container::throw_bad_alloc(); + }*/ + } + + //!Deallocates several elements allocated by + //!allocate_many(), allocate(), or allocation_command(). + //!This function is available only with Version == 2 + void deallocate_many(multiallocation_chain &chain) BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + boost_cont_memchain ch; + void *beg(&*chain.begin()), *last(&*chain.last()); + size_t size(chain.size()); + BOOST_CONTAINER_MEMCHAIN_INIT_FROM(&ch, beg, last, size); + boost_cont_multidealloc(&ch); + //boost_cont_multidealloc(reinterpret_cast(&chain)); + } + + private: + + std::pair priv_allocation_command + (allocation_type command, std::size_t limit_size + ,std::size_t preferred_size,std::size_t &received_size, void *reuse_ptr) + { + boost_cont_command_ret_t ret = {0 , 0}; + if((limit_size > this->max_size()) | (preferred_size > this->max_size())){ + return std::pair(pointer(), false); + } + std::size_t l_size = limit_size*sizeof(T); + std::size_t p_size = preferred_size*sizeof(T); + std::size_t r_size; + { + ret = boost_cont_allocation_command(command, sizeof(T), l_size, p_size, &r_size, reuse_ptr); + } + received_size = r_size/sizeof(T); + return std::pair(static_cast(ret.first), !!ret.second); + } +}; + +} //namespace container { +} //namespace boost { + +#include + +#endif //BOOST_CONTAINER_ALLOCATOR_HPP + diff --git a/include/boost/container/allocator_traits.hpp b/include/boost/container/allocator_traits.hpp index aa8194a..613d116 100644 --- a/include/boost/container/allocator_traits.hpp +++ b/include/boost/container/allocator_traits.hpp @@ -6,7 +6,7 @@ // ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -38,7 +38,7 @@ #include #endif -///@cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { namespace container { @@ -56,7 +56,7 @@ struct is_std_allocator< std::allocator > } //namespace container_detail { -///@endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! The class template allocator_traits supplies a uniform interface to all allocator types. //! This class is a C++03-compatible implementation of std::allocator_traits @@ -94,29 +94,29 @@ struct allocator_traits //! typedef see_documentation size_type; //! Alloc::propagate_on_container_copy_assignment if such a type exists, otherwise an integral_constant - //! type with internal constant static member `value` == false. + //! type with internal constant static member value == false. typedef see_documentation propagate_on_container_copy_assignment; //! Alloc::propagate_on_container_move_assignment if such a type exists, otherwise an integral_constant - //! type with internal constant static member `value` == false. + //! type with internal constant static member value == false. typedef see_documentation propagate_on_container_move_assignment; //! Alloc::propagate_on_container_swap if such a type exists, otherwise an integral_constant - //! type with internal constant static member `value` == false. + //! type with internal constant static member value == false. typedef see_documentation propagate_on_container_swap; //! Defines an allocator: Alloc::rebind::other if such a type exists; otherwise, Alloc //! if Alloc is a class template instantiation of the form Alloc, where Args is zero or //! more type arguments ; otherwise, the instantiation of rebind_alloc is ill-formed. //! - //! In C++03 compilers `rebind_alloc` is a struct derived from an allocator + //! In C++03 compilers rebind_alloc is a struct derived from an allocator //! deduced by previously detailed rules. template using rebind_alloc = see_documentation; - //! In C++03 compilers `rebind_traits` is a struct derived from - //! `allocator_traits`, where `OtherAlloc` is - //! the allocator deduced by rules explained in `rebind_alloc`. + //! In C++03 compilers rebind_traits is a struct derived from + //! allocator_traits, where OtherAlloc is + //! the allocator deduced by rules explained in rebind_alloc. template using rebind_traits = allocator_traits >; //! Non-standard extension: Portable allocator rebind for C++03 and C++11 compilers. - //! `type` is an allocator related to Alloc deduced deduced by rules explained in `rebind_alloc`. + //! type is an allocator related to Alloc deduced deduced by rules explained in rebind_alloc. template struct portable_rebind_alloc { typedef see_documentation type; }; @@ -206,19 +206,19 @@ struct allocator_traits { typedef typename boost::intrusive::detail::type_rebinder::type type; }; #endif //BOOST_CONTAINER_DOXYGEN_INVOKED - //! Returns: `a.allocate(n)` + //! Returns: a.allocate(n) //! static pointer allocate(Alloc &a, size_type n) { return a.allocate(n); } - //! Returns: `a.deallocate(p, n)` + //! Returns: a.deallocate(p, n) //! //! Throws: Nothing static void deallocate(Alloc &a, pointer p, size_type n) { a.deallocate(p, n); } - //! Effects: calls `a.allocate(n, p)` if that call is well-formed; - //! otherwise, invokes `a.allocate(n)` + //! Effects: calls a.allocate(n, p) if that call is well-formed; + //! otherwise, invokes a.allocate(n) static pointer allocate(Alloc &a, size_type n, const_void_pointer p) { const bool value = boost::container::container_detail:: @@ -228,10 +228,10 @@ struct allocator_traits return allocator_traits::priv_allocate(flag, a, n, p); } - //! Effects: calls `a.destroy(p)` if that call is well-formed; - //! otherwise, invokes `p->~T()`. + //! Effects: calls a.destroy(p) if that call is well-formed; + //! otherwise, invokes p->~T(). template - static void destroy(Alloc &a, T*p) + static void destroy(Alloc &a, T*p) BOOST_CONTAINER_NOEXCEPT { typedef T* destroy_pointer; const bool value = boost::container::container_detail:: @@ -241,9 +241,9 @@ struct allocator_traits allocator_traits::priv_destroy(flag, a, p); } - //! Returns: `a.max_size()` if that expression is well-formed; otherwise, - //! `numeric_limits::max()`. - static size_type max_size(const Alloc &a) + //! Returns: a.max_size() if that expression is well-formed; otherwise, + //! numeric_limits::max(). + static size_type max_size(const Alloc &a) BOOST_CONTAINER_NOEXCEPT { const bool value = boost::container::container_detail:: has_member_function_callable_with_max_size @@ -252,7 +252,7 @@ struct allocator_traits return allocator_traits::priv_max_size(flag, a); } - //! Returns: `a.select_on_container_copy_construction()` if that expression is well-formed; + //! Returns: a.select_on_container_copy_construction() if that expression is well-formed; //! otherwise, a. static #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) @@ -276,8 +276,8 @@ struct allocator_traits } #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: calls `a.construct(p, std::forward(args)...)` if that call is well-formed; - //! otherwise, invokes `::new (static_cast(p)) T(std::forward(args)...)` + //! Effects: calls a.construct(p, std::forward(args)...) if that call is well-formed; + //! otherwise, invokes ::new (static_cast(p)) T(std::forward(args)...) template static void construct(Alloc & a, T* p, BOOST_FWD_REF(Args)... args) { @@ -285,7 +285,7 @@ struct allocator_traits allocator_traits::priv_construct(flag, a, p, ::boost::forward(args)...); } #endif - ///@cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) private: static pointer priv_allocate(boost::true_type, Alloc &a, size_type n, const_void_pointer p) @@ -295,23 +295,23 @@ struct allocator_traits { return allocator_traits::allocate(a, n); } template - static void priv_destroy(boost::true_type, Alloc &a, T* p) + static void priv_destroy(boost::true_type, Alloc &a, T* p) BOOST_CONTAINER_NOEXCEPT { a.destroy(p); } template - static void priv_destroy(boost::false_type, Alloc &, T* p) + static void priv_destroy(boost::false_type, Alloc &, T* p) BOOST_CONTAINER_NOEXCEPT { p->~T(); (void)p; } - static size_type priv_max_size(boost::true_type, const Alloc &a) + static size_type priv_max_size(boost::true_type, const Alloc &a) BOOST_CONTAINER_NOEXCEPT { return a.max_size(); } - static size_type priv_max_size(boost::false_type, const Alloc &) + static size_type priv_max_size(boost::false_type, const Alloc &) BOOST_CONTAINER_NOEXCEPT { return (std::numeric_limits::max)(); } static Alloc priv_select_on_container_copy_construction(boost::true_type, const Alloc &a) { return a.select_on_container_copy_construction(); } - static const Alloc &priv_select_on_container_copy_construction(boost::false_type, const Alloc &a) + static const Alloc &priv_select_on_container_copy_construction(boost::false_type, const Alloc &a) BOOST_CONTAINER_NOEXCEPT { return a; } #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) @@ -394,7 +394,7 @@ struct allocator_traits { ::new((void*)p) T; } #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - ///@endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; } //namespace container { diff --git a/include/boost/container/container_fwd.hpp b/include/boost/container/container_fwd.hpp index 271cc8b..415de0f 100644 --- a/include/boost/container/container_fwd.hpp +++ b/include/boost/container/container_fwd.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,11 +15,37 @@ # pragma once #endif +//! \file +//! This header file forward declares the following containers: +//! - boost::container::vector +//! - boost::container::stable_vector +//! - boost::container::static_vector +//! - boost::container::slist +//! - boost::container::list +//! - boost::container::set +//! - boost::container::multiset +//! - boost::container::map +//! - boost::container::multimap +//! - boost::container::flat_set +//! - boost::container::flat_multiset +//! - boost::container::flat_map +//! - boost::container::flat_multimap +//! - boost::container::basic_string +//! - boost::container::string +//! - boost::container::wstring +//! +//! It forward declares the following allocators: +//! - boost::container::allocator +//! - boost::container::node_allocator +//! - boost::container::adaptive_pool +//! +//! And finally it defines the following types + ////////////////////////////////////////////////////////////////////////////// // Standard predeclarations ////////////////////////////////////////////////////////////////////////////// -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost{ namespace intrusive{ @@ -32,13 +58,14 @@ namespace bi = boost::intrusive; }}} +#include #include #include #include #include #include -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED ////////////////////////////////////////////////////////////////////////////// // Containers @@ -47,89 +74,146 @@ namespace bi = boost::intrusive; namespace boost { namespace container { -//vector class +//! Enumeration used to configure ordered associative containers +//! with a concrete tree implementation. +enum tree_type_enum +{ + red_black_tree, + avl_tree, + scapegoat_tree, + splay_tree +}; + +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + template > class vector; -//vector class template > class stable_vector; -//vector class +template +class static_vector; + template > class deque; -//list class template > class list; -//slist class template > class slist; -//set class +template +struct tree_opt; + +typedef tree_opt tree_assoc_defaults; + template - ,class Allocator = std::allocator > + ,class Allocator = std::allocator + ,class Options = tree_assoc_defaults > class set; -//multiset class template - ,class Allocator = std::allocator > + ,class Allocator = std::allocator + ,class Options = tree_assoc_defaults > class multiset; -//map class template - ,class Allocator = std::allocator > > + ,class Allocator = std::allocator > + ,class Options = tree_assoc_defaults > class map; -//multimap class template - ,class Allocator = std::allocator > > + ,class Allocator = std::allocator > + ,class Options = tree_assoc_defaults > class multimap; -//flat_set class template ,class Allocator = std::allocator > class flat_set; -//flat_multiset class template ,class Allocator = std::allocator > class flat_multiset; -//flat_map class template ,class Allocator = std::allocator > > class flat_map; -//flat_multimap class template ,class Allocator = std::allocator > > class flat_multimap; -//basic_string class template ,class Allocator = std::allocator > class basic_string; +typedef basic_string + + ,std::allocator > +string; + +typedef basic_string + + ,std::allocator > +wstring; + +static const std::size_t ADP_nodes_per_block = 256u; +static const std::size_t ADP_max_free_blocks = 2u; +static const std::size_t ADP_overhead_percent = 1u; +static const std::size_t ADP_only_alignment = 0u; + +template < class T + , std::size_t NodesPerBlock = ADP_nodes_per_block + , std::size_t MaxFreeBlocks = ADP_max_free_blocks + , std::size_t OverheadPercent = ADP_overhead_percent + , unsigned Version = 2 + > +class adaptive_pool; + +template < class T + , unsigned Version = 2 + , unsigned int AllocationDisableMask = 0> +class allocator; + +static const std::size_t NodeAlloc_nodes_per_block = 256u; + +template + < class T + , std::size_t NodesPerBlock = NodeAlloc_nodes_per_block + , std::size_t Version = 2> +class node_allocator; + +#else + +//! Default options for tree-based associative containers +//! - tree_type +//! - optimize_size +typedef implementation_defined tree_assoc_defaults; + +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + //! Type used to tag that the input range is //! guaranteed to be ordered struct ordered_range_t @@ -149,17 +233,26 @@ struct ordered_unique_range_t //! guaranteed to be ordered and unique static const ordered_unique_range_t ordered_unique_range = ordered_unique_range_t(); -//! Type used to tag that the input range is -//! guaranteed to be ordered and unique +//! Type used to tag that the inserted values +//! should be default initialized struct default_init_t {}; -//! Value used to tag that the input range is -//! guaranteed to be ordered and unique +//! Value used to tag that the inserted values +//! should be default initialized static const default_init_t default_init = default_init_t(); -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED -namespace detail_really_deep_namespace { +//! Type used to tag that the inserted values +//! should be value initialized +struct value_init_t +{}; + +//! Value used to tag that the inserted values +//! should be value initialized +static const value_init_t value_init = value_init_t(); + +namespace container_detail_really_deep_namespace { //Otherwise, gcc issues a warning of previously defined //anonymous_instance and unique_instance @@ -175,7 +268,7 @@ struct dummy } //detail_really_deep_namespace { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }} //namespace boost { namespace container { diff --git a/include/boost/container/deque.hpp b/include/boost/container/deque.hpp index 136b4f6..4fd2e7c 100644 --- a/include/boost/container/deque.hpp +++ b/include/boost/container/deque.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -45,12 +45,8 @@ namespace boost { namespace container { -/// @cond -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template > -#else +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED template -#endif class deque; template @@ -465,21 +461,24 @@ class deque_base const allocator_type &alloc() const BOOST_CONTAINER_NOEXCEPT { return members_; } }; -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED -//! Deque class -//! #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +//! A double-ended queue is a sequence that supports random access to elements, constant time insertion +//! and removal of elements at the end of the sequence, and linear time insertion and removal of elements in the middle. +//! +//! \tparam T The type of object that is stored in the deque +//! \tparam Allocator The allocator used for all internal memory management template > #else template #endif class deque : protected deque_base { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: typedef deque_base Base; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: @@ -503,7 +502,7 @@ class deque : protected deque_base typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: // Internal typedefs BOOST_COPYABLE_AND_MOVABLE(deque) @@ -512,7 +511,7 @@ class deque : protected deque_base { return Base::s_buffer_size(); } typedef allocator_traits allocator_traits_type; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -549,8 +548,8 @@ class deque : protected deque_base explicit deque(size_type n) : Base(n, allocator_type()) { - container_detail::insert_value_initialized_n_proxy proxy(this->alloc()); - proxy.uninitialized_copy_n_and_update(this->begin(), n); + container_detail::insert_value_initialized_n_proxy proxy; + proxy.uninitialized_copy_n_and_update(this->alloc(), this->begin(), n); //deque_base will deallocate in case of exception... } @@ -566,8 +565,8 @@ class deque : protected deque_base deque(size_type n, default_init_t) : Base(n, allocator_type()) { - container_detail::insert_default_initialized_n_proxy proxy(this->alloc()); - proxy.uninitialized_copy_n_and_update(this->begin(), n); + container_detail::insert_default_initialized_n_proxy proxy; + proxy.uninitialized_copy_n_and_update(this->alloc(), this->begin(), n); //deque_base will deallocate in case of exception... } @@ -978,7 +977,7 @@ class deque : protected deque_base this->priv_erase_last_n(len - new_size); else{ const size_type n = new_size - this->size(); - container_detail::insert_value_initialized_n_proxy proxy(this->alloc()); + container_detail::insert_value_initialized_n_proxy proxy; priv_insert_back_aux_impl(n, proxy); } } @@ -998,7 +997,7 @@ class deque : protected deque_base this->priv_erase_last_n(len - new_size); else{ const size_type n = new_size - this->size(); - container_detail::insert_default_initialized_n_proxy proxy(this->alloc()); + container_detail::insert_default_initialized_n_proxy proxy; priv_insert_back_aux_impl(n, proxy); } } @@ -1155,7 +1154,7 @@ class deque : protected deque_base } else{ typedef container_detail::insert_non_movable_emplace_proxy type; - this->priv_insert_front_aux_impl(1, type(this->alloc(), boost::forward(args)...)); + this->priv_insert_front_aux_impl(1, type(boost::forward(args)...)); } } @@ -1177,7 +1176,7 @@ class deque : protected deque_base } else{ typedef container_detail::insert_non_movable_emplace_proxy type; - this->priv_insert_back_aux_impl(1, type(this->alloc(), boost::forward(args)...)); + this->priv_insert_back_aux_impl(1, type(boost::forward(args)...)); } } @@ -1203,7 +1202,7 @@ class deque : protected deque_base } else{ typedef container_detail::insert_emplace_proxy type; - return this->priv_insert_aux_impl(p, 1, type(this->alloc(), boost::forward(args)...)); + return this->priv_insert_aux_impl(p, 1, type(boost::forward(args)...)); } } @@ -1222,10 +1221,10 @@ class deque : protected deque_base priv_push_front_simple_commit(); \ } \ else{ \ - container_detail::BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, n) \ - proxy \ - (this->alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - priv_insert_front_aux_impl(1, proxy); \ + typedef container_detail::BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, n) \ + type; \ + priv_insert_front_aux_impl \ + (1, type(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ } \ } \ \ @@ -1240,10 +1239,10 @@ class deque : protected deque_base priv_push_back_simple_commit(); \ } \ else{ \ - container_detail::BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, n) \ - proxy \ - (this->alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - priv_insert_back_aux_impl(1, proxy); \ + typedef container_detail::BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, n) \ + type; \ + priv_insert_back_aux_impl \ + (1, type(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ } \ } \ \ @@ -1260,10 +1259,10 @@ class deque : protected deque_base return (this->end()-1); \ } \ else{ \ - container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ - proxy \ - (this->alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ - return this->priv_insert_aux_impl(p, 1, proxy); \ + typedef container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ + type; \ + return this->priv_insert_aux_impl \ + (p, 1, type(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _))); \ } \ } \ //! @@ -1397,7 +1396,7 @@ class deque : protected deque_base #endif ) { - container_detail::insert_range_proxy proxy(this->alloc(), first); + container_detail::insert_range_proxy proxy(first); return priv_insert_aux_impl(p, (size_type)std::distance(first, last), proxy); } #endif @@ -1537,7 +1536,49 @@ class deque : protected deque_base this->members_.m_finish = this->members_.m_start; } - /// @cond + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const deque& x, const deque& y) + { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const deque& x, const deque& y) + { return !(x == y); } + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const deque& x, const deque& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const deque& x, const deque& y) + { return y < x; } + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const deque& x, const deque& y) + { return !(y < x); } + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const deque& x, const deque& y) + { return !(x < y); } + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(deque& x, deque& y) + { x.swap(y); } + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: void priv_erase_last_n(size_type n) @@ -1570,7 +1611,8 @@ class deque : protected deque_base } else { return priv_insert_aux_impl - (position, (size_type)1, container_detail::get_insert_value_proxy(this->alloc(), ::boost::forward(x))); + ( position, (size_type)1 + , container_detail::get_insert_value_proxy(::boost::forward(x))); } } @@ -1584,7 +1626,8 @@ class deque : protected deque_base } else{ priv_insert_aux_impl - (this->cbegin(), (size_type)1, container_detail::get_insert_value_proxy(this->alloc(), ::boost::forward(x))); + ( this->cbegin(), (size_type)1 + , container_detail::get_insert_value_proxy(::boost::forward(x))); } } @@ -1598,8 +1641,8 @@ class deque : protected deque_base } else{ priv_insert_aux_impl - (this->cend(), (size_type)1, container_detail::get_insert_value_proxy(this->alloc(), ::boost::forward(x))); - container_detail::insert_copy_proxy proxy(this->alloc(), x); + ( this->cend(), (size_type)1 + , container_detail::get_insert_value_proxy(::boost::forward(x))); } } @@ -1652,7 +1695,7 @@ class deque : protected deque_base } template - iterator priv_insert_aux_impl(const_iterator p, size_type n, InsertProxy interf) + iterator priv_insert_aux_impl(const_iterator p, size_type n, InsertProxy proxy) { iterator pos(p.unconst()); const size_type pos_n = p - this->cbegin(); @@ -1667,7 +1710,7 @@ class deque : protected deque_base const iterator new_start = this->priv_reserve_elements_at_front(n); const iterator old_start = this->members_.m_start; if(!elemsbefore){ - interf.uninitialized_copy_n_and_update(new_start, n); + proxy.uninitialized_copy_n_and_update(this->alloc(), new_start, n); this->members_.m_start = new_start; } else{ @@ -1678,17 +1721,17 @@ class deque : protected deque_base (this->alloc(), this->members_.m_start, start_n, new_start); this->members_.m_start = new_start; boost::move(start_n, pos, old_start); - interf.copy_n_and_update(pos - n, n); + proxy.copy_n_and_update(this->alloc(), pos - n, n); } else { const size_type mid_count = n - elemsbefore; const iterator mid_start = old_start - mid_count; - interf.uninitialized_copy_n_and_update(mid_start, mid_count); + proxy.uninitialized_copy_n_and_update(this->alloc(), mid_start, mid_count); this->members_.m_start = mid_start; ::boost::container::uninitialized_move_alloc (this->alloc(), old_start, pos, new_start); this->members_.m_start = new_start; - interf.copy_n_and_update(old_start, elemsbefore); + proxy.copy_n_and_update(this->alloc(), old_start, elemsbefore); } } } @@ -1697,7 +1740,7 @@ class deque : protected deque_base const iterator old_finish = this->members_.m_finish; const size_type elemsafter = length - elemsbefore; if(!elemsafter){ - interf.uninitialized_copy_n_and_update(old_finish, n); + proxy.uninitialized_copy_n_and_update(this->alloc(), old_finish, n); this->members_.m_finish = new_finish; } else{ @@ -1708,15 +1751,15 @@ class deque : protected deque_base (this->alloc(), finish_n, old_finish, old_finish); this->members_.m_finish = new_finish; boost::move_backward(pos, finish_n, old_finish); - interf.copy_n_and_update(pos, n); + proxy.copy_n_and_update(this->alloc(), pos, n); } else { const size_type raw_gap = n - elemsafter; ::boost::container::uninitialized_move_alloc (this->alloc(), pos, old_finish, old_finish + raw_gap); BOOST_TRY{ - interf.copy_n_and_update(pos, elemsafter); - interf.uninitialized_copy_n_and_update(old_finish, raw_gap); + proxy.copy_n_and_update(this->alloc(), pos, elemsafter); + proxy.uninitialized_copy_n_and_update(this->alloc(), old_finish, raw_gap); } BOOST_CATCH(...){ this->priv_destroy_range(old_finish, old_finish + elemsafter); @@ -1731,7 +1774,7 @@ class deque : protected deque_base } template - iterator priv_insert_back_aux_impl(size_type n, InsertProxy interf) + iterator priv_insert_back_aux_impl(size_type n, InsertProxy proxy) { if(!this->members_.m_map){ this->priv_initialize_map(0); @@ -1739,20 +1782,20 @@ class deque : protected deque_base iterator new_finish = this->priv_reserve_elements_at_back(n); iterator old_finish = this->members_.m_finish; - interf.uninitialized_copy_n_and_update(old_finish, n); + proxy.uninitialized_copy_n_and_update(this->alloc(), old_finish, n); this->members_.m_finish = new_finish; return iterator(this->members_.m_finish - n); } template - iterator priv_insert_front_aux_impl(size_type n, InsertProxy interf) + iterator priv_insert_front_aux_impl(size_type n, InsertProxy proxy) { if(!this->members_.m_map){ this->priv_initialize_map(0); } iterator new_start = this->priv_reserve_elements_at_front(n); - interf.uninitialized_copy_n_and_update(new_start, n); + proxy.uninitialized_copy_n_and_update(this->alloc(), new_start, n); this->members_.m_start = new_start; return new_start; } @@ -1934,45 +1977,12 @@ class deque : protected deque_base this->members_.m_start.priv_set_node(new_nstart); this->members_.m_finish.priv_set_node(new_nstart + old_num_nodes - 1); } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -// Nonmember functions. -template -inline bool operator==(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT -{ - return x.size() == y.size() && equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool operator<(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT -{ - return lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); -} - -template -inline bool operator!=(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return !(x == y); } - -template -inline bool operator>(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return y < x; } - -template -inline bool operator>=(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return !(x < y); } - -template -inline bool operator<=(const deque& x, const deque& y) BOOST_CONTAINER_NOEXCEPT - { return !(y < x); } - -template -inline void swap(deque& x, deque& y) -{ x.swap(y); } - }} -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { @@ -1985,7 +1995,7 @@ struct has_trivial_destructor_after_move > } -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #include diff --git a/include/boost/container/detail/adaptive_node_pool.hpp b/include/boost/container/detail/adaptive_node_pool.hpp new file mode 100644 index 0000000..8914d4a --- /dev/null +++ b/include/boost/container/detail/adaptive_node_pool.hpp @@ -0,0 +1,162 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_HPP +#define BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace container { +namespace container_detail { + +template +struct select_private_adaptive_node_pool_impl +{ + typedef boost::container::container_detail:: + private_adaptive_node_pool_impl + < fake_segment_manager + , unsigned(AlignOnly)*::boost::container::adaptive_pool_flag::align_only + | ::boost::container::adaptive_pool_flag::size_ordered | ::boost::container::adaptive_pool_flag::address_ordered + > type; +}; + +//!Pooled memory allocator using an smart adaptive pool. Includes +//!a reference count but the class does not delete itself, this is +//!responsibility of user classes. Node size (NodeSize) and the number of +//!nodes allocated per block (NodesPerBlock) are known at compile time. +template< std::size_t NodeSize + , std::size_t NodesPerBlock + , std::size_t MaxFreeBlocks + , std::size_t OverheadPercent + > +class private_adaptive_node_pool + : public select_private_adaptive_node_pool_impl<(OverheadPercent == 0)>::type +{ + typedef typename select_private_adaptive_node_pool_impl::type base_t; + //Non-copyable + private_adaptive_node_pool(const private_adaptive_node_pool &); + private_adaptive_node_pool &operator=(const private_adaptive_node_pool &); + + public: + typedef typename base_t::multiallocation_chain multiallocation_chain; + static const std::size_t nodes_per_block = NodesPerBlock; + + //!Constructor. Never throws + private_adaptive_node_pool() + : base_t(0 + , NodeSize + , NodesPerBlock + , MaxFreeBlocks + , (unsigned char)OverheadPercent) + {} +}; + +//!Pooled memory allocator using adaptive pool. Includes +//!a reference count but the class does not delete itself, this is +//!responsibility of user classes. Node size (NodeSize) and the number of +//!nodes allocated per block (NodesPerBlock) are known at compile time +template< std::size_t NodeSize + , std::size_t NodesPerBlock + , std::size_t MaxFreeBlocks + , std::size_t OverheadPercent + > +class shared_adaptive_node_pool + : public private_adaptive_node_pool + +{ + private: + typedef private_adaptive_node_pool + private_node_allocator_t; + public: + typedef typename private_node_allocator_t::multiallocation_chain multiallocation_chain; + + //!Constructor. Never throws + shared_adaptive_node_pool() + : private_node_allocator_t(){} + + //!Destructor. Deallocates all allocated blocks. Never throws + ~shared_adaptive_node_pool() + {} + + //!Allocates array of count elements. Can throw std::bad_alloc + void *allocate_node() + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + return private_node_allocator_t::allocate_node(); + } + + //!Deallocates an array pointed by ptr. Never throws + void deallocate_node(void *ptr) + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::deallocate_node(ptr); + } + + //!Allocates a singly linked list of n nodes ending in null pointer. + //!can throw std::bad_alloc + void allocate_nodes(const std::size_t n, multiallocation_chain &chain) + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + return private_node_allocator_t::allocate_nodes(n, chain); + } + + void deallocate_nodes(multiallocation_chain &chain) + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::deallocate_nodes(chain); + } + + //!Deallocates all the free blocks of memory. Never throws + void deallocate_free_blocks() + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::deallocate_free_blocks(); + } + + private: + default_mutex mutex_; +}; + +} //namespace container_detail { +} //namespace container { +} //namespace boost { + +#include + +#endif //#ifndef BOOST_CONTAINER_DETAIL_ADAPTIVE_NODE_POOL_HPP diff --git a/include/boost/container/detail/adaptive_node_pool_impl.hpp b/include/boost/container/detail/adaptive_node_pool_impl.hpp index 4578ea8..13f9723 100644 --- a/include/boost/container/detail/adaptive_node_pool_impl.hpp +++ b/include/boost/container/detail/adaptive_node_pool_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,9 +15,10 @@ # pragma once #endif -#include "config_begin.hpp" -#include +#include #include + +#include #include #include #include diff --git a/include/boost/container/detail/advanced_insert_int.hpp b/include/boost/container/detail/advanced_insert_int.hpp index e42bcb3..a3bbc23 100644 --- a/include/boost/container/detail/advanced_insert_int.hpp +++ b/include/boost/container/detail/advanced_insert_int.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,8 +15,373 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include + +#include +#include +#include +#include +#include //std::iterator_traits +#include +#include + +namespace boost { namespace container { namespace container_detail { + +template +struct move_insert_range_proxy +{ + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::value_type value_type; + + explicit move_insert_range_proxy(FwdIt first) + : first_(first) + {} + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) + { + this->first_ = ::boost::container::uninitialized_move_alloc_n_source + (a, this->first_, n, p); + } + + void copy_n_and_update(A &, Iterator p, size_type n) + { + this->first_ = ::boost::container::move_n_source(this->first_, n, p); + } + + FwdIt first_; +}; + + +template +struct insert_range_proxy +{ + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::value_type value_type; + + explicit insert_range_proxy(FwdIt first) + : first_(first) + {} + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) + { + this->first_ = ::boost::container::uninitialized_copy_alloc_n_source(a, this->first_, n, p); + } + + void copy_n_and_update(A &, Iterator p, size_type n) + { + this->first_ = ::boost::container::copy_n_source(this->first_, n, p); + } + + FwdIt first_; +}; + + +template +struct insert_n_copies_proxy +{ + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::value_type value_type; + + explicit insert_n_copies_proxy(const value_type &v) + : v_(v) + {} + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) const + { boost::container::uninitialized_fill_alloc_n(a, v_, n, p); } + + void copy_n_and_update(A &, Iterator p, size_type n) const + { std::fill_n(p, n, v_); } + + const value_type &v_; +}; + +template +struct insert_value_initialized_n_proxy +{ + typedef ::boost::container::allocator_traits alloc_traits; + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::value_type value_type; + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) const + { boost::container::uninitialized_value_init_alloc_n(a, n, p); } + + void copy_n_and_update(A &, Iterator, size_type) const + { BOOST_ASSERT(false); } +}; + +template +struct insert_default_initialized_n_proxy +{ + typedef ::boost::container::allocator_traits alloc_traits; + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::value_type value_type; + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) const + { boost::container::uninitialized_default_init_alloc_n(a, n, p); } + + void copy_n_and_update(A &, Iterator, size_type) const + { BOOST_ASSERT(false); } +}; + +template +struct insert_copy_proxy +{ + typedef boost::container::allocator_traits alloc_traits; + typedef typename alloc_traits::size_type size_type; + typedef typename alloc_traits::value_type value_type; + + explicit insert_copy_proxy(const value_type &v) + : v_(v) + {} + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) const + { + BOOST_ASSERT(n == 1); (void)n; + alloc_traits::construct( a, container_detail::to_raw_pointer(&*p), v_); + } + + void copy_n_and_update(A &, Iterator p, size_type n) const + { + BOOST_ASSERT(n == 1); (void)n; + *p =v_; + } + + const value_type &v_; +}; + + +template +struct insert_move_proxy +{ + typedef boost::container::allocator_traits alloc_traits; + typedef typename alloc_traits::size_type size_type; + typedef typename alloc_traits::value_type value_type; + + explicit insert_move_proxy(value_type &v) + : v_(v) + {} + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) const + { + BOOST_ASSERT(n == 1); (void)n; + alloc_traits::construct( a + , container_detail::to_raw_pointer(&*p) + , ::boost::move(v_) + ); + } + + void copy_n_and_update(A &, Iterator p, size_type n) const + { + BOOST_ASSERT(n == 1); (void)n; + *p = ::boost::move(v_); + } + + value_type &v_; +}; + +template +insert_move_proxy get_insert_value_proxy(BOOST_RV_REF(typename std::iterator_traits::value_type) v) +{ + return insert_move_proxy(v); +} + +template +insert_copy_proxy get_insert_value_proxy(const typename std::iterator_traits::value_type &v) +{ + return insert_copy_proxy(v); +} + +}}} //namespace boost { namespace container { namespace container_detail { + +#ifdef BOOST_CONTAINER_PERFECT_FORWARDING + +#include +#include +#include +//#include //For debugging purposes + +namespace boost { +namespace container { +namespace container_detail { + +template +struct insert_non_movable_emplace_proxy +{ + typedef boost::container::allocator_traits alloc_traits; + typedef typename alloc_traits::size_type size_type; + typedef typename alloc_traits::value_type value_type; + + typedef typename build_number_seq::type index_tuple_t; + + explicit insert_non_movable_emplace_proxy(Args&&... args) + : args_(args...) + {} + + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) + { this->priv_uninitialized_copy_some_and_update(a, index_tuple_t(), p, n); } + + private: + template + void priv_uninitialized_copy_some_and_update(A &a, const index_tuple&, Iterator p, size_type n) + { + BOOST_ASSERT(n == 1); (void)n; + alloc_traits::construct( a + , container_detail::to_raw_pointer(&*p) + , ::boost::forward(get(this->args_))... + ); + } + + protected: + tuple args_; +}; + +template +struct insert_emplace_proxy + : public insert_non_movable_emplace_proxy +{ + typedef insert_non_movable_emplace_proxy base_t; + typedef boost::container::allocator_traits alloc_traits; + typedef typename base_t::value_type value_type; + typedef typename base_t::size_type size_type; + typedef typename base_t::index_tuple_t index_tuple_t; + + explicit insert_emplace_proxy(Args&&... args) + : base_t(::boost::forward(args)...) + {} + + void copy_n_and_update(A &a, Iterator p, size_type n) + { this->priv_copy_some_and_update(a, index_tuple_t(), p, n); } + + private: + + template + void priv_copy_some_and_update(A &a, const index_tuple&, Iterator p, size_type n) + { + BOOST_ASSERT(n ==1); (void)n; + aligned_storage::value> v; + value_type *vp = static_cast(static_cast(&v)); + alloc_traits::construct(a, vp, + ::boost::forward(get(this->args_))...); + BOOST_TRY{ + *p = ::boost::move(*vp); + } + BOOST_CATCH(...){ + alloc_traits::destroy(a, vp); + BOOST_RETHROW + } + BOOST_CATCH_END + alloc_traits::destroy(a, vp); + } +}; + +}}} //namespace boost { namespace container { namespace container_detail { + +#else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING + +#include +#include + +namespace boost { +namespace container { +namespace container_detail { + +#define BOOST_PP_LOCAL_MACRO(N) \ +template \ +struct BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ +{ \ + typedef boost::container::allocator_traits alloc_traits; \ + typedef typename alloc_traits::size_type size_type; \ + typedef typename alloc_traits::value_type value_type; \ + \ + explicit BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ + ( BOOST_PP_ENUM(N, BOOST_CONTAINER_PP_PARAM_LIST, _) ) \ + BOOST_PP_EXPR_IF(N, :) BOOST_PP_ENUM(N, BOOST_CONTAINER_PP_PARAM_INIT, _) \ + {} \ + \ + void uninitialized_copy_n_and_update(A &a, Iterator p, size_type n) \ + { \ + BOOST_ASSERT(n == 1); (void)n; \ + alloc_traits::construct \ + ( a \ + , container_detail::to_raw_pointer(&*p) \ + BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_MEMBER_FORWARD, _) \ + ); \ + } \ + \ + void copy_n_and_update(A &, Iterator, size_type) \ + { BOOST_ASSERT(false); } \ + \ + protected: \ + BOOST_PP_REPEAT(N, BOOST_CONTAINER_PP_PARAM_DEFINE, _) \ +}; \ + \ +template \ +struct BOOST_PP_CAT(insert_emplace_proxy_arg, N) \ + : BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ + < A, Iterator BOOST_PP_ENUM_TRAILING_PARAMS(N, P) > \ +{ \ + typedef BOOST_PP_CAT(insert_non_movable_emplace_proxy_arg, N) \ + base_t; \ + typedef typename base_t::value_type value_type; \ + typedef typename base_t::size_type size_type; \ + typedef boost::container::allocator_traits alloc_traits; \ + \ + explicit BOOST_PP_CAT(insert_emplace_proxy_arg, N) \ + ( BOOST_PP_ENUM(N, BOOST_CONTAINER_PP_PARAM_LIST, _) ) \ + : base_t(BOOST_PP_ENUM(N, BOOST_CONTAINER_PP_PARAM_FORWARD, _) ) \ + {} \ + \ + void copy_n_and_update(A &a, Iterator p, size_type n) \ + { \ + BOOST_ASSERT(n == 1); (void)n; \ + aligned_storage::value> v; \ + value_type *vp = static_cast(static_cast(&v)); \ + alloc_traits::construct(a, vp \ + BOOST_PP_ENUM_TRAILING(N, BOOST_CONTAINER_PP_MEMBER_FORWARD, _)); \ + BOOST_TRY{ \ + *p = ::boost::move(*vp); \ + } \ + BOOST_CATCH(...){ \ + alloc_traits::destroy(a, vp); \ + BOOST_RETHROW \ + } \ + BOOST_CATCH_END \ + alloc_traits::destroy(a, vp); \ + } \ +}; \ +//! +#define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) +#include BOOST_PP_LOCAL_ITERATE() + +}}} //namespace boost { namespace container { namespace container_detail { + +#endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING + +#include + +#endif //#ifndef BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP +/* +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2008-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP +#define BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP + +#if defined(_MSC_VER) +# pragma once +#endif + +#include +#include + #include #include #include @@ -391,3 +756,4 @@ struct BOOST_PP_CAT(insert_emplace_proxy_arg, N) #include #endif //#ifndef BOOST_CONTAINER_ADVANCED_INSERT_INT_HPP +*/ \ No newline at end of file diff --git a/include/boost/container/detail/algorithms.hpp b/include/boost/container/detail/algorithms.hpp index 7a4a868..9358995 100644 --- a/include/boost/container/detail/algorithms.hpp +++ b/include/boost/container/detail/algorithms.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -17,7 +17,7 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include #include diff --git a/include/boost/container/detail/alloc_lib.h b/include/boost/container/detail/alloc_lib.h new file mode 100644 index 0000000..279dffe --- /dev/null +++ b/include/boost/container/detail/alloc_lib.h @@ -0,0 +1,326 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#ifndef BOOST_CONTAINER_ALLOC_LIB_EXT_H +#define BOOST_CONTAINER_ALLOC_LIB_EXT_H + +#include + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable : 4127) + +/* + we need to import/export our code only if the user has specifically + asked for it by defining either BOOST_ALL_DYN_LINK if they want all boost + libraries to be dynamically linked, or BOOST_CONTAINER_DYN_LINK + if they want just this one to be dynamically liked: +*/ +#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_CONTAINER_DYN_LINK) + +/* export if this is our own source, otherwise import: */ +#ifdef BOOST_CONTAINER_SOURCE +# define BOOST_CONTAINER_DECL __declspec(dllexport) +#else +# define BOOST_CONTAINER_DECL __declspec(dllimport) +#endif /* BOOST_CONTAINER_SOURCE */ +#endif /* DYN_LINK */ +#endif /* _MSC_VER */ + +/* if BOOST_CONTAINER_DECL isn't defined yet define it now: */ +#ifndef BOOST_CONTAINER_DECL +#define BOOST_CONTAINER_DECL +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*!An forward iterator to traverse the elements of a memory chain container.*/ +typedef struct multialloc_node_impl +{ + struct multialloc_node_impl *next_node_ptr; +} boost_cont_memchain_node; + + +/*!An forward iterator to traverse the elements of a memory chain container.*/ +typedef struct multialloc_it_impl +{ + boost_cont_memchain_node *node_ptr; +} boost_cont_memchain_it; + +/*!Memory chain: A container holding memory portions allocated by boost_cont_multialloc_nodes + and boost_cont_multialloc_arrays functions.*/ +typedef struct boost_cont_memchain_impl +{ + size_t num_mem; + boost_cont_memchain_node root_node; + boost_cont_memchain_node *last_node_ptr; +} boost_cont_memchain; + +/*!Advances the iterator one position so that it points to the next element in the memory chain*/ +#define BOOST_CONTAINER_MEMIT_NEXT(IT) (IT.node_ptr = IT.node_ptr->next_node_ptr) + +/*!Returns the address of the memory chain currently pointed by the iterator*/ +#define BOOST_CONTAINER_MEMIT_ADDR(IT) ((void*)IT.node_ptr) + +/*!Initializer for an iterator pointing to the position before the first element*/ +#define BOOST_CONTAINER_MEMCHAIN_BEFORE_BEGIN_IT(PMEMCHAIN) { &((PMEMCHAIN)->root_node) } + +/*!Initializer for an iterator pointing to the first element*/ +#define BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(PMEMCHAIN) {(PMEMCHAIN)->root_node.next_node_ptr } + +/*!Initializer for an iterator pointing to the last element*/ +#define BOOST_CONTAINER_MEMCHAIN_LAST_IT(PMEMCHAIN) {(PMEMCHAIN)->last_node_ptr } + +/*!Initializer for an iterator pointing to one past the last element (end iterator)*/ +#define BOOST_CONTAINER_MEMCHAIN_END_IT(PMEMCHAIN) {(boost_cont_memchain_node *)0 } + +/*!True if IT is the end iterator, false otherwise*/ +#define BOOST_CONTAINER_MEMCHAIN_IS_END_IT(PMEMCHAIN, IT) (!(IT).node_ptr) + +/*!The address of the first memory portion hold by the memory chain*/ +#define BOOST_CONTAINER_MEMCHAIN_FIRSTMEM(PMEMCHAIN)((void*)((PMEMCHAIN)->root_node.next_node_ptr)) + +/*!The address of the last memory portion hold by the memory chain*/ +#define BOOST_CONTAINER_MEMCHAIN_LASTMEM(PMEMCHAIN) ((void*)((PMEMCHAIN)->last_node_ptr)) + +/*!The number of memory portions hold by the memory chain*/ +#define BOOST_CONTAINER_MEMCHAIN_SIZE(PMEMCHAIN) ((PMEMCHAIN)->num_mem) + +/*!Initializes the memory chain from the first memory portion, the last memory + portion and number of portions obtained from another memory chain*/ +#define BOOST_CONTAINER_MEMCHAIN_INIT_FROM(PMEMCHAIN, FIRST, LAST, NUM)\ + (PMEMCHAIN)->last_node_ptr = (boost_cont_memchain_node *)(LAST), \ + (PMEMCHAIN)->root_node.next_node_ptr = (boost_cont_memchain_node *)(FIRST), \ + (PMEMCHAIN)->num_mem = (NUM);\ +/**/ + +/*!Default initializes a memory chain. Postconditions: begin iterator is end iterator, + the number of portions is zero.*/ +#define BOOST_CONTAINER_MEMCHAIN_INIT(PMEMCHAIN)\ + ((PMEMCHAIN)->root_node.next_node_ptr = 0, (PMEMCHAIN)->last_node_ptr = &((PMEMCHAIN)->root_node), (PMEMCHAIN)->num_mem = 0)\ +/**/ + +/*!True if the memory chain is empty (holds no memory portions*/ +#define BOOST_CONTAINER_MEMCHAIN_EMPTY(PMEMCHAIN)\ + ((PMEMCHAIN)->num_mem == 0)\ +/**/ + +/*!Inserts a new memory portions in the front of the chain*/ +#define BOOST_CONTAINER_MEMCHAIN_PUSH_BACK(PMEMCHAIN, MEM)\ + do{\ + boost_cont_memchain *____chain____ = (PMEMCHAIN);\ + boost_cont_memchain_node *____tmp_mem____ = (boost_cont_memchain_node *)(MEM);\ + ____chain____->last_node_ptr->next_node_ptr = ____tmp_mem____;\ + ____tmp_mem____->next_node_ptr = 0;\ + ____chain____->last_node_ptr = ____tmp_mem____;\ + ++____chain____->num_mem;\ + }while(0)\ +/**/ + +/*!Inserts a new memory portions in the back of the chain*/ +#define BOOST_CONTAINER_MEMCHAIN_PUSH_FRONT(PMEMCHAIN, MEM)\ + do{\ + boost_cont_memchain *____chain____ = (PMEMCHAIN);\ + boost_cont_memchain_node *____tmp_mem____ = (boost_cont_memchain_node *)(MEM);\ + boost_cont_memchain *____root____ = &((PMEMCHAIN)->root_node);\ + if(!____chain____->root_node.next_node_ptr){\ + ____chain____->last_node_ptr = ____tmp_mem____;\ + }\ + boost_cont_memchain_node *____old_first____ = ____root____->next_node_ptr;\ + ____tmp_mem____->next_node_ptr = ____old_first____;\ + ____root____->next_node_ptr = ____tmp_mem____;\ + ++____chain____->num_mem;\ + }while(0)\ +/**/ + +/*!Erases the memory portion after the portion pointed by BEFORE_IT from the memory chain*/ +/*!Precondition: BEFORE_IT must be a valid iterator of the memory chain and it can't be the end iterator*/ +#define BOOST_CONTAINER_MEMCHAIN_ERASE_AFTER(PMEMCHAIN, BEFORE_IT)\ + do{\ + boost_cont_memchain *____chain____ = (PMEMCHAIN);\ + boost_cont_memchain_node *____prev_node____ = (BEFORE_IT).node_ptr;\ + boost_cont_memchain_node *____erase_node____ = ____prev_node____->next_node_ptr;\ + if(____chain____->last_node_ptr == ____erase_node____){\ + ____chain____->last_node_ptr = &____chain____->root_node;\ + }\ + ____prev_node____->next_node_ptr = ____erase_node____->next_node_ptr;\ + --____chain____->num_mem;\ + }while(0)\ +/**/ + +/*!Erases the first portion from the memory chain. + Precondition: the memory chain must not be empty*/ +#define BOOST_CONTAINER_MEMCHAIN_POP_FRONT(PMEMCHAIN)\ + do{\ + boost_cont_memchain *____chain____ = (PMEMCHAIN);\ + boost_cont_memchain_node *____prev_node____ = &____chain____->root_node;\ + boost_cont_memchain_node *____erase_node____ = ____prev_node____->next_node_ptr;\ + if(____chain____->last_node_ptr == ____erase_node____){\ + ____chain____->last_node_ptr = &____chain____->root_node;\ + }\ + ____prev_node____->next_node_ptr = ____erase_node____->next_node_ptr;\ + --____chain____->num_mem;\ + }while(0)\ +/**/ + +/*!Joins two memory chains inserting the portions of the second chain at the back of the first chain*/ +/* +#define BOOST_CONTAINER_MEMCHAIN_SPLICE_BACK(PMEMCHAIN, PMEMCHAIN2)\ + do{\ + boost_cont_memchain *____chain____ = (PMEMCHAIN);\ + boost_cont_memchain *____chain2____ = (PMEMCHAIN2);\ + if(!____chain2____->root_node.next_node_ptr){\ + break;\ + }\ + else if(!____chain____->first_mem){\ + ____chain____->first_mem = ____chain2____->first_mem;\ + ____chain____->last_node_ptr = ____chain2____->last_node_ptr;\ + ____chain____->num_mem = ____chain2____->num_mem;\ + BOOST_CONTAINER_MEMCHAIN_INIT(*____chain2____);\ + }\ + else{\ + ____chain____->last_node_ptr->next_node_ptr = ____chain2____->first_mem;\ + ____chain____->last_node_ptr = ____chain2____->last_node_ptr;\ + ____chain____->num_mem += ____chain2____->num_mem;\ + }\ + }while(0)\*/ +/**/ + +/*!Joins two memory chains inserting the portions of the second chain at the back of the first chain*/ +#define BOOST_CONTAINER_MEMCHAIN_INCORPORATE_AFTER(PMEMCHAIN, BEFORE_IT, FIRST, BEFORELAST, NUM)\ + do{\ + boost_cont_memchain *____chain____ = (PMEMCHAIN);\ + boost_cont_memchain_node *____pnode____ = (BEFORE_IT).node_ptr;\ + boost_cont_memchain_node *____next____ = ____pnode____->next_node_ptr;\ + boost_cont_memchain_node *____first____ = (boost_cont_memchain_node *)(FIRST);\ + boost_cont_memchain_node *____blast____ = (boost_cont_memchain_node *)(BEFORELAST);\ + size_t ____num____ = (NUM);\ + if(!____num____){\ + break;\ + }\ + if(____pnode____ == ____chain____->last_node_ptr){\ + ____chain____->last_node_ptr = ____blast____;\ + }\ + ____pnode____->next_node_ptr = ____first____;\ + ____blast____->next_node_ptr = ____next____;\ + ____chain____->num_mem += ____num____;\ + }while(0)\ +/**/ + +BOOST_CONTAINER_DECL size_t boost_cont_size(const void *p); + +BOOST_CONTAINER_DECL void* boost_cont_malloc(size_t bytes); + +BOOST_CONTAINER_DECL void boost_cont_free(void* mem); + +BOOST_CONTAINER_DECL void* boost_cont_memalign(size_t bytes, size_t alignment); + +/*!Indicates the all elements allocated by boost_cont_multialloc_nodes or boost_cont_multialloc_arrays + must be contiguous.*/ +#define DL_MULTIALLOC_ALL_CONTIGUOUS ((size_t)(-1)) + +/*!Indicates the number of contiguous elements allocated by boost_cont_multialloc_nodes or boost_cont_multialloc_arrays + should be selected by those functions.*/ +#define DL_MULTIALLOC_DEFAULT_CONTIGUOUS ((size_t)(0)) + +BOOST_CONTAINER_DECL int boost_cont_multialloc_nodes + (size_t n_elements, size_t elem_size, size_t contiguous_elements, boost_cont_memchain *pchain); + +BOOST_CONTAINER_DECL int boost_cont_multialloc_arrays + (size_t n_elements, const size_t *sizes, size_t sizeof_element, size_t contiguous_elements, boost_cont_memchain *pchain); + +BOOST_CONTAINER_DECL void boost_cont_multidealloc(boost_cont_memchain *pchain); + +BOOST_CONTAINER_DECL size_t boost_cont_footprint(); + +BOOST_CONTAINER_DECL size_t boost_cont_allocated_memory(); + +BOOST_CONTAINER_DECL size_t boost_cont_chunksize(const void *p); + +BOOST_CONTAINER_DECL int boost_cont_all_deallocated(); + +typedef struct boost_cont_malloc_stats_impl +{ + size_t max_system_bytes; + size_t system_bytes; + size_t in_use_bytes; +} boost_cont_malloc_stats_t; + +BOOST_CONTAINER_DECL boost_cont_malloc_stats_t boost_cont_malloc_stats(); + +BOOST_CONTAINER_DECL size_t boost_cont_in_use_memory(); + +BOOST_CONTAINER_DECL int boost_cont_trim(size_t pad); + +BOOST_CONTAINER_DECL int boost_cont_mallopt + (int parameter_number, int parameter_value); + +BOOST_CONTAINER_DECL int boost_cont_grow + (void* oldmem, size_t minbytes, size_t maxbytes, size_t *received); + +BOOST_CONTAINER_DECL int boost_cont_shrink + (void* oldmem, size_t minbytes, size_t maxbytes, size_t *received, int do_commit); + +BOOST_CONTAINER_DECL void* boost_cont_alloc + (size_t minbytes, size_t preferred_bytes, size_t *received_bytes); + +BOOST_CONTAINER_DECL int boost_cont_malloc_check(); + +typedef unsigned int allocation_type; + +enum +{ + // constants for allocation commands + BOOST_CONTAINER_ALLOCATE_NEW = 0X01, + BOOST_CONTAINER_EXPAND_FWD = 0X02, + BOOST_CONTAINER_EXPAND_BWD = 0X04, + BOOST_CONTAINER_SHRINK_IN_PLACE = 0X08, + BOOST_CONTAINER_NOTHROW_ALLOCATION = 0X10, +// BOOST_CONTAINER_ZERO_MEMORY = 0X20, + BOOST_CONTAINER_TRY_SHRINK_IN_PLACE = 0X40, + BOOST_CONTAINER_EXPAND_BOTH = BOOST_CONTAINER_EXPAND_FWD | BOOST_CONTAINER_EXPAND_BWD, + BOOST_CONTAINER_EXPAND_OR_NEW = BOOST_CONTAINER_ALLOCATE_NEW | BOOST_CONTAINER_EXPAND_BOTH +}; + +//#define BOOST_CONTAINERDLMALLOC__FOOTERS +#ifndef BOOST_CONTAINERDLMALLOC__FOOTERS +enum { BOOST_CONTAINER_ALLOCATION_PAYLOAD = sizeof(size_t) }; +#else +enum { BOOST_CONTAINER_ALLOCATION_PAYLOAD = sizeof(size_t)*2 }; +#endif + +typedef struct boost_cont_command_ret_impl +{ + void *first; + int second; +}boost_cont_command_ret_t; + +BOOST_CONTAINER_DECL boost_cont_command_ret_t boost_cont_allocation_command + ( allocation_type command + , size_t sizeof_object + , size_t limit_objects + , size_t preferred_objects + , size_t *received_objects + , void *reuse_ptr + ); + +BOOST_CONTAINER_DECL int boost_cont_mallopt(int param_number, int value); + +#ifdef __cplusplus +} //extern "C" { +#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + + +#endif //#define BOOST_CONTAINERDLMALLOC__EXT_H diff --git a/include/boost/container/detail/alloc_lib_auto_link.hpp b/include/boost/container/detail/alloc_lib_auto_link.hpp new file mode 100644 index 0000000..e424890 --- /dev/null +++ b/include/boost/container/detail/alloc_lib_auto_link.hpp @@ -0,0 +1,16 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#ifndef BOOST_CONTAINER_DETAIL_BOOST_CONT_EXT_AUTO_LINK_HPP +#define BOOST_CONTAINER_DETAIL_BOOST_CONT_EXT_AUTO_LINK_HPP + +#include +#include + +#endif //#ifndef BOOST_CONTAINER_DETAIL_BOOST_CONT_EXT_AUTO_LINK_HPP diff --git a/include/boost/container/detail/allocation_type.hpp b/include/boost/container/detail/allocation_type.hpp index 59ae922..6aa04ac 100644 --- a/include/boost/container/detail/allocation_type.hpp +++ b/include/boost/container/detail/allocation_type.hpp @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,13 +15,13 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include namespace boost { namespace container { -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED enum allocation_type_v { // constants for allocation commands @@ -37,7 +37,7 @@ enum allocation_type_v }; typedef int allocation_type; -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED static const allocation_type allocate_new = (allocation_type)allocate_new_v; static const allocation_type expand_fwd = (allocation_type)expand_fwd_v; static const allocation_type expand_bwd = (allocation_type)expand_bwd_v; diff --git a/include/boost/container/detail/allocator_version_traits.hpp b/include/boost/container/detail/allocator_version_traits.hpp index 6df79da..d4567da 100644 --- a/include/boost/container/detail/allocator_version_traits.hpp +++ b/include/boost/container/detail/allocator_version_traits.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2012-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,6 +17,7 @@ #include #include + #include //allocator_traits #include #include //multiallocation_chain diff --git a/include/boost/container/detail/auto_link.hpp b/include/boost/container/detail/auto_link.hpp new file mode 100644 index 0000000..dbc8b29 --- /dev/null +++ b/include/boost/container/detail/auto_link.hpp @@ -0,0 +1,38 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#ifndef BOOST_CONTAINER_DETAIL_AUTO_LINK_HPP_INCLUDED +#define BOOST_CONTAINER_DETAIL_AUTO_LINK_HPP_INCLUDED + +#if defined(_MSC_VER) +# pragma once +#endif + +// +// Automatically link to the correct build variant where possible. +// +#if !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_CONTAINER_NO_LIB) && !defined(BOOST_CONTAINER_SOURCE) +// +// Set the name of our library, this will get undef'ed by auto_link.hpp +// once it's done with it: +// +#define BOOST_LIB_NAME boost_container +// +// If we're importing code from a dll, then tell auto_link.hpp about it: +// +#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_CONTAINER_DYN_LINK) +# define BOOST_DYN_LINK +#endif +// +// And include the header that does the work: +// +#include +#endif // auto-linking disabled + +#endif //#ifndef BOOST_CONTAINER_DETAIL_AUTO_LINK_HPP_INCLUDED diff --git a/include/boost/container/detail/config_begin.hpp b/include/boost/container/detail/config_begin.hpp index 664f092..6c54bef 100644 --- a/include/boost/container/detail/config_begin.hpp +++ b/include/boost/container/detail/config_begin.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -18,6 +18,10 @@ #define BOOST_CONTAINER_DETAIL_CRT_SECURE_NO_DEPRECATE #define _CRT_SECURE_NO_DEPRECATE #endif + #ifndef _SCL_SECURE_NO_WARNINGS + #define BOOST_CONTAINER_DETAIL_SCL_SECURE_NO_WARNINGS + #define _SCL_SECURE_NO_WARNINGS + #endif #pragma warning (push) #pragma warning (disable : 4702) // unreachable code #pragma warning (disable : 4706) // assignment within conditional expression diff --git a/include/boost/container/detail/config_end.hpp b/include/boost/container/detail/config_end.hpp index 3451371..7217019 100644 --- a/include/boost/container/detail/config_end.hpp +++ b/include/boost/container/detail/config_end.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -13,5 +13,9 @@ #undef BOOST_CONTAINER_DETAIL_CRT_SECURE_NO_DEPRECATE #undef _CRT_SECURE_NO_DEPRECATE #endif + #ifdef BOOST_CONTAINER_DETAIL_SCL_SECURE_NO_WARNINGS + #undef BOOST_CONTAINER_DETAIL_SCL_SECURE_NO_WARNINGS + #undef _SCL_SECURE_NO_WARNINGS + #endif #endif diff --git a/include/boost/container/detail/destroyers.hpp b/include/boost/container/detail/destroyers.hpp index fef8aa0..329a6ef 100644 --- a/include/boost/container/detail/destroyers.hpp +++ b/include/boost/container/detail/destroyers.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -17,8 +17,9 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include + #include #include #include @@ -231,6 +232,9 @@ struct null_scoped_destructor_n void increment_size_backwards(size_type) {} + void shrink_forward(size_type) + {} + void release() {} }; diff --git a/include/boost/container/detail/flat_tree.hpp b/include/boost/container/detail/flat_tree.hpp index f214d19..d3f9ee6 100644 --- a/include/boost/container/detail/flat_tree.hpp +++ b/include/boost/container/detail/flat_tree.hpp @@ -1,6 +1,6 @@ //////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,7 +15,7 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include #include @@ -270,6 +270,9 @@ class flat_tree Compare key_comp() const { return this->m_data.get_comp(); } + value_compare value_comp() const + { return this->m_data; } + allocator_type get_allocator() const { return this->m_data.m_vect.get_allocator(); } @@ -526,7 +529,7 @@ class flat_tree this->reserve(this->size()+len); const const_iterator b(this->cbegin()); const_iterator pos(b); - const value_compare &value_comp = this->m_data; + const value_compare &val_cmp = this->m_data; skips[0u] = 0u; //Loop in burst sizes while(len){ @@ -539,7 +542,7 @@ class flat_tree --len; pos = const_cast(*this).priv_lower_bound(pos, ce, KeyOfValue()(val)); //Check if already present - if(pos != ce && !value_comp(val, *pos)){ + if(pos != ce && !val_cmp(val, *pos)){ if(unique_burst > 0){ ++skips[unique_burst-1]; } @@ -714,6 +717,7 @@ class flat_tree return i; } + // set operations: size_type count(const key_type& k) const { std::pair p = this->equal_range(k); @@ -739,12 +743,44 @@ class flat_tree std::pair equal_range(const key_type& k) const { return this->priv_equal_range(this->cbegin(), this->cend(), k); } + std::pair lower_bound_range(const key_type& k) + { return this->priv_lower_bound_range(this->begin(), this->end(), k); } + + std::pair lower_bound_range(const key_type& k) const + { return this->priv_lower_bound_range(this->cbegin(), this->cend(), k); } + size_type capacity() const { return this->m_data.m_vect.capacity(); } void reserve(size_type cnt) { this->m_data.m_vect.reserve(cnt); } + friend bool operator==(const flat_tree& x, const flat_tree& y) + { + return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); + } + + friend bool operator<(const flat_tree& x, const flat_tree& y) + { + return std::lexicographical_compare(x.begin(), x.end(), + y.begin(), y.end()); + } + + friend bool operator!=(const flat_tree& x, const flat_tree& y) + { return !(x == y); } + + friend bool operator>(const flat_tree& x, const flat_tree& y) + { return y < x; } + + friend bool operator<=(const flat_tree& x, const flat_tree& y) + { return !(y < x); } + + friend bool operator>=(const flat_tree& x, const flat_tree& y) + { return !(x < y); } + + friend void swap(flat_tree& x, flat_tree& y) + { x.swap(y); } + private: struct insert_commit_data { @@ -764,10 +800,10 @@ class flat_tree // insert val before upper_bound(val) // else // insert val before lower_bound(val) - const value_compare &value_comp = this->m_data; + const value_compare &val_cmp = this->m_data; - if(pos == this->cend() || !value_comp(*pos, val)){ - if (pos == this->cbegin() || !value_comp(val, pos[-1])){ + if(pos == this->cend() || !val_cmp(*pos, val)){ + if (pos == this->cbegin() || !val_cmp(val, pos[-1])){ data.position = pos; } else{ @@ -784,9 +820,9 @@ class flat_tree bool priv_insert_unique_prepare (const_iterator b, const_iterator e, const value_type& val, insert_commit_data &commit_data) { - const value_compare &value_comp = this->m_data; + const value_compare &val_cmp = this->m_data; commit_data.position = this->priv_lower_bound(b, e, KeyOfValue()(val)); - return commit_data.position == e || value_comp(val, *commit_data.position); + return commit_data.position == e || val_cmp(val, *commit_data.position); } bool priv_insert_unique_prepare @@ -807,9 +843,9 @@ class flat_tree // insert val after pos //else // insert val before lower_bound(val) - const value_compare &value_comp = this->m_data; + const value_compare &val_cmp = this->m_data; const const_iterator cend_it = this->cend(); - if(pos == cend_it || value_comp(val, *pos)){ //Check if val should go before end + if(pos == cend_it || val_cmp(val, *pos)){ //Check if val should go before end const const_iterator cbeg = this->cbegin(); commit_data.position = pos; if(pos == cbeg){ //If container is empty then insert it in the beginning @@ -817,10 +853,10 @@ class flat_tree } const_iterator prev(pos); --prev; - if(value_comp(*prev, val)){ //If previous element was less, then it should go between prev and pos + if(val_cmp(*prev, val)){ //If previous element was less, then it should go between prev and pos return true; } - else if(!value_comp(val, *prev)){ //If previous was equal then insertion should fail + else if(!val_cmp(val, *prev)){ //If previous was equal then insertion should fail commit_data.position = prev; return false; } @@ -846,7 +882,7 @@ class flat_tree } template - RanIt priv_lower_bound(RanIt first, RanIt last, + RanIt priv_lower_bound(RanIt first, const RanIt last, const key_type & key) const { const Compare &key_cmp = this->m_data.get_comp(); @@ -855,24 +891,23 @@ class flat_tree RanIt middle; while (len) { - size_type half = len >> 1; + size_type step = len >> 1; middle = first; - middle += half; + middle += step; if (key_cmp(key_extract(*middle), key)) { - ++middle; - first = middle; - len = len - half - 1; + first = ++middle; + len -= step + 1; + } + else{ + len = step; } - else - len = half; } return first; } - template - RanIt priv_upper_bound(RanIt first, RanIt last, + RanIt priv_upper_bound(RanIt first, const RanIt last, const key_type & key) const { const Compare &key_cmp = this->m_data.get_comp(); @@ -881,16 +916,16 @@ class flat_tree RanIt middle; while (len) { - size_type half = len >> 1; + size_type step = len >> 1; middle = first; - middle += half; + middle += step; if (key_cmp(key, key_extract(*middle))) { - len = half; + len = step; } else{ first = ++middle; - len = len - half - 1; + len -= step + 1; } } return first; @@ -906,29 +941,41 @@ class flat_tree RanIt middle; while (len) { - size_type half = len >> 1; + size_type step = len >> 1; middle = first; - middle += half; + middle += step; if (key_cmp(key_extract(*middle), key)){ - first = middle; - ++first; - len = len - half - 1; + first = ++middle; + len -= step + 1; } else if (key_cmp(key, key_extract(*middle))){ - len = half; + len = step; } else { //Middle is equal to key last = first; last += len; - first = this->priv_lower_bound(first, middle, key); - return std::pair (first, this->priv_upper_bound(++middle, last, key)); + return std::pair + ( this->priv_lower_bound(first, middle, key) + , this->priv_upper_bound(++middle, last, key)); } } return std::pair(first, first); } + template + std::pair priv_lower_bound_range(RanIt first, RanIt last, const key_type& k) const + { + const Compare &key_cmp = this->m_data.get_comp(); + KeyOfValue key_extract; + RanIt lb(this->priv_lower_bound(first, last, k)), ub(lb); + if(lb != last && static_cast(!key_cmp(k, key_extract(*lb)))){ + ++ub; + } + return std::pair(lb, ub); + } + template void priv_insert_equal_loop(InIt first, InIt last) { @@ -950,62 +997,6 @@ class flat_tree } }; -template -inline bool -operator==(const flat_tree& x, - const flat_tree& y) -{ - return x.size() == y.size() && - std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator<(const flat_tree& x, - const flat_tree& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), - y.begin(), y.end()); -} - -template -inline bool -operator!=(const flat_tree& x, - const flat_tree& y) - { return !(x == y); } - -template -inline bool -operator>(const flat_tree& x, - const flat_tree& y) - { return y < x; } - -template -inline bool -operator<=(const flat_tree& x, - const flat_tree& y) - { return !(y < x); } - -template -inline bool -operator>=(const flat_tree& x, - const flat_tree& y) - { return !(x < y); } - - -template -inline void -swap(flat_tree& x, - flat_tree& y) - { x.swap(y); } - } //namespace container_detail { } //namespace container { diff --git a/include/boost/container/detail/function_detector.hpp b/include/boost/container/detail/function_detector.hpp index 5a5f6fd..1fe6731 100644 --- a/include/boost/container/detail/function_detector.hpp +++ b/include/boost/container/detail/function_detector.hpp @@ -1,6 +1,6 @@ ///////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2009-2012. +// (C) Copyright Ion Gaztanaga 2009-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at diff --git a/include/boost/container/detail/hash_table.hpp b/include/boost/container/detail/hash_table.hpp new file mode 100644 index 0000000..da7bb53 --- /dev/null +++ b/include/boost/container/detail/hash_table.hpp @@ -0,0 +1,383 @@ +/* +template , class Pred = equal_to, + class Alloc = allocator > +class hash_set +{ +public: + // types + typedef Value key_type; + typedef key_type value_type; + typedef Hash hasher; + typedef Pred key_equal; + typedef Alloc allocator_type; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef typename allocator_traits::pointer pointer; + typedef typename allocator_traits::const_pointer const_pointer; + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::difference_type difference_type; + + typedef /unspecified/ iterator; + typedef /unspecified/ const_iterator; + typedef /unspecified/ local_iterator; + typedef /unspecified/ const_local_iterator; + + hash_set() + noexcept( + is_nothrow_default_constructible::value && + is_nothrow_default_constructible::value && + is_nothrow_default_constructible::value); + explicit hash_set(size_type n, const hasher& hf = hasher(), + const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + template + hash_set(InputIterator f, InputIterator l, + size_type n = 0, const hasher& hf = hasher(), + const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + explicit hash_set(const allocator_type&); + hash_set(const hash_set&); + hash_set(const hash_set&, const Allocator&); + hash_set(hash_set&&) + noexcept( + is_nothrow_move_constructible::value && + is_nothrow_move_constructible::value && + is_nothrow_move_constructible::value); + hash_set(hash_set&&, const Allocator&); + hash_set(initializer_list, size_type n = 0, + const hasher& hf = hasher(), const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + ~hash_set(); + hash_set& operator=(const hash_set&); + hash_set& operator=(hash_set&&) + noexcept( + allocator_type::propagate_on_container_move_assignment::value && + is_nothrow_move_assignable::value && + is_nothrow_move_assignable::value && + is_nothrow_move_assignable::value); + hash_set& operator=(initializer_list); + + allocator_type get_allocator() const noexcept; + + bool empty() const noexcept; + size_type size() const noexcept; + size_type max_size() const noexcept; + + iterator begin() noexcept; + iterator end() noexcept; + const_iterator begin() const noexcept; + const_iterator end() const noexcept; + const_iterator cbegin() const noexcept; + const_iterator cend() const noexcept; + + template + pair emplace(Args&&... args); + template + iterator emplace_hint(const_iterator position, Args&&... args); + pair insert(const value_type& obj); + pair insert(value_type&& obj); + iterator insert(const_iterator hint, const value_type& obj); + iterator insert(const_iterator hint, value_type&& obj); + template + void insert(InputIterator first, InputIterator last); + void insert(initializer_list); + + iterator erase(const_iterator position); + size_type erase(const key_type& k); + iterator erase(const_iterator first, const_iterator last); + void clear() noexcept; + + void swap(hash_set&) + noexcept( + (!allocator_type::propagate_on_container_swap::value || + __is_nothrow_swappable::value) && + __is_nothrow_swappable::value && + __is_nothrow_swappable::value); + + hasher hash_function() const; + key_equal key_eq() const; + + iterator find(const key_type& k); + const_iterator find(const key_type& k) const; + size_type count(const key_type& k) const; + pair equal_range(const key_type& k); + pair equal_range(const key_type& k) const; + + size_type bucket_count() const noexcept; + size_type max_bucket_count() const noexcept; + + size_type bucket_size(size_type n) const; + size_type bucket(const key_type& k) const; + + local_iterator begin(size_type n); + local_iterator end(size_type n); + const_local_iterator begin(size_type n) const; + const_local_iterator end(size_type n) const; + const_local_iterator cbegin(size_type n) const; + const_local_iterator cend(size_type n) const; + + float load_factor() const noexcept; + float max_load_factor() const noexcept; + void max_load_factor(float z); + void rehash(size_type n); + void reserve(size_type n); +}; + +template , class Pred = equal_to, + class Alloc = allocator > > +class hash_map +{ +public: + // types + typedef Key key_type; + typedef T mapped_type; + typedef Hash hasher; + typedef Pred key_equal; + typedef Alloc allocator_type; + typedef pair value_type; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef typename allocator_traits::pointer pointer; + typedef typename allocator_traits::const_pointer const_pointer; + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::difference_type difference_type; + + typedef /unspecified/ iterator; + typedef /unspecified/ const_iterator; + typedef /unspecified/ local_iterator; + typedef /unspecified/ const_local_iterator; + + hash_map() + noexcept( + is_nothrow_default_constructible::value && + is_nothrow_default_constructible::value && + is_nothrow_default_constructible::value); + explicit hash_map(size_type n, const hasher& hf = hasher(), + const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + template + hash_map(InputIterator f, InputIterator l, + size_type n = 0, const hasher& hf = hasher(), + const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + explicit hash_map(const allocator_type&); + hash_map(const hash_map&); + hash_map(const hash_map&, const Allocator&); + hash_map(hash_map&&) + noexcept( + is_nothrow_move_constructible::value && + is_nothrow_move_constructible::value && + is_nothrow_move_constructible::value); + hash_map(hash_map&&, const Allocator&); + hash_map(initializer_list, size_type n = 0, + const hasher& hf = hasher(), const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + ~hash_map(); + hash_map& operator=(const hash_map&); + hash_map& operator=(hash_map&&) + noexcept( + allocator_type::propagate_on_container_move_assignment::value && + is_nothrow_move_assignable::value && + is_nothrow_move_assignable::value && + is_nothrow_move_assignable::value); + hash_map& operator=(initializer_list); + + allocator_type get_allocator() const noexcept; + + bool empty() const noexcept; + size_type size() const noexcept; + size_type max_size() const noexcept; + + iterator begin() noexcept; + iterator end() noexcept; + const_iterator begin() const noexcept; + const_iterator end() const noexcept; + const_iterator cbegin() const noexcept; + const_iterator cend() const noexcept; + + template + pair emplace(Args&&... args); + template + iterator emplace_hint(const_iterator position, Args&&... args); + pair insert(const value_type& obj); + template + pair insert(P&& obj); + iterator insert(const_iterator hint, const value_type& obj); + template + iterator insert(const_iterator hint, P&& obj); + template + void insert(InputIterator first, InputIterator last); + void insert(initializer_list); + + iterator erase(const_iterator position); + size_type erase(const key_type& k); + iterator erase(const_iterator first, const_iterator last); + void clear() noexcept; + + void swap(hash_map&) + noexcept( + (!allocator_type::propagate_on_container_swap::value || + __is_nothrow_swappable::value) && + __is_nothrow_swappable::value && + __is_nothrow_swappable::value); + + hasher hash_function() const; + key_equal key_eq() const; + + iterator find(const key_type& k); + const_iterator find(const key_type& k) const; + size_type count(const key_type& k) const; + pair equal_range(const key_type& k); + pair equal_range(const key_type& k) const; + + mapped_type& operator[](const key_type& k); + mapped_type& operator[](key_type&& k); + + mapped_type& at(const key_type& k); + const mapped_type& at(const key_type& k) const; + + size_type bucket_count() const noexcept; + size_type max_bucket_count() const noexcept; + + size_type bucket_size(size_type n) const; + size_type bucket(const key_type& k) const; + + local_iterator begin(size_type n); + local_iterator end(size_type n); + const_local_iterator begin(size_type n) const; + const_local_iterator end(size_type n) const; + const_local_iterator cbegin(size_type n) const; + const_local_iterator cend(size_type n) const; + + float load_factor() const noexcept; + float max_load_factor() const noexcept; + void max_load_factor(float z); + void rehash(size_type n); + void reserve(size_type n); +}; + +*/ + +template , class Pred = equal_to, + class Alloc = allocator > +class hash_table +{ +public: + // types + typedef Value key_type; + typedef key_type value_type; + typedef Hash hasher; + typedef Pred key_equal; + typedef Alloc allocator_type; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef typename allocator_traits::pointer pointer; + typedef typename allocator_traits::const_pointer const_pointer; + typedef typename allocator_traits::size_type size_type; + typedef typename allocator_traits::difference_type difference_type; + + typedef /unspecified/ iterator; + typedef /unspecified/ const_iterator; + typedef /unspecified/ local_iterator; + typedef /unspecified/ const_local_iterator; + + hash_set() + noexcept( + is_nothrow_default_constructible::value && + is_nothrow_default_constructible::value && + is_nothrow_default_constructible::value); + explicit hash_set(size_type n, const hasher& hf = hasher(), + const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + template + hash_set(InputIterator f, InputIterator l, + size_type n = 0, const hasher& hf = hasher(), + const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + explicit hash_set(const allocator_type&); + hash_set(const hash_set&); + hash_set(const hash_set&, const Allocator&); + hash_set(hash_set&&) + noexcept( + is_nothrow_move_constructible::value && + is_nothrow_move_constructible::value && + is_nothrow_move_constructible::value); + hash_set(hash_set&&, const Allocator&); + hash_set(initializer_list, size_type n = 0, + const hasher& hf = hasher(), const key_equal& eql = key_equal(), + const allocator_type& a = allocator_type()); + ~hash_set(); + hash_set& operator=(const hash_set&); + hash_set& operator=(hash_set&&) + noexcept( + allocator_type::propagate_on_container_move_assignment::value && + is_nothrow_move_assignable::value && + is_nothrow_move_assignable::value && + is_nothrow_move_assignable::value); + hash_set& operator=(initializer_list); + + allocator_type get_allocator() const noexcept; + + bool empty() const noexcept; + size_type size() const noexcept; + size_type max_size() const noexcept; + + iterator begin() noexcept; + iterator end() noexcept; + const_iterator begin() const noexcept; + const_iterator end() const noexcept; + const_iterator cbegin() const noexcept; + const_iterator cend() const noexcept; + + template + pair emplace(Args&&... args); + template + iterator emplace_hint(const_iterator position, Args&&... args); + pair insert(const value_type& obj); + pair insert(value_type&& obj); + iterator insert(const_iterator hint, const value_type& obj); + iterator insert(const_iterator hint, value_type&& obj); + template + void insert(InputIterator first, InputIterator last); + void insert(initializer_list); + + iterator erase(const_iterator position); + size_type erase(const key_type& k); + iterator erase(const_iterator first, const_iterator last); + void clear() noexcept; + + void swap(hash_set&) + noexcept( + (!allocator_type::propagate_on_container_swap::value || + __is_nothrow_swappable::value) && + __is_nothrow_swappable::value && + __is_nothrow_swappable::value); + + hasher hash_function() const; + key_equal key_eq() const; + + iterator find(const key_type& k); + const_iterator find(const key_type& k) const; + size_type count(const key_type& k) const; + pair equal_range(const key_type& k); + pair equal_range(const key_type& k) const; + + size_type bucket_count() const noexcept; + size_type max_bucket_count() const noexcept; + + size_type bucket_size(size_type n) const; + size_type bucket(const key_type& k) const; + + local_iterator begin(size_type n); + local_iterator end(size_type n); + const_local_iterator begin(size_type n) const; + const_local_iterator end(size_type n) const; + const_local_iterator cbegin(size_type n) const; + const_local_iterator cend(size_type n) const; + + float load_factor() const noexcept; + float max_load_factor() const noexcept; + void max_load_factor(float z); + void rehash(size_type n); + void reserve(size_type n); +}; diff --git a/include/boost/container/detail/iterators.hpp b/include/boost/container/detail/iterators.hpp index 5766a7c..be3c157 100644 --- a/include/boost/container/detail/iterators.hpp +++ b/include/boost/container/detail/iterators.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // (C) Copyright Gennaro Prota 2003 - 2004. // // Distributed under the Boost Software License, Version 1.0. @@ -18,7 +18,7 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include #include #include diff --git a/include/boost/container/detail/math_functions.hpp b/include/boost/container/detail/math_functions.hpp index fe8386b..3eff6b1 100644 --- a/include/boost/container/detail/math_functions.hpp +++ b/include/boost/container/detail/math_functions.hpp @@ -1,7 +1,7 @@ ////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Stephen Cleary 2000. -// (C) Copyright Ion Gaztanaga 2007-2012. +// (C) Copyright Ion Gaztanaga 2007-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -16,7 +16,9 @@ #ifndef BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP #define BOOST_CONTAINER_DETAIL_MATH_FUNCTIONS_HPP -#include "config_begin.hpp" +#include +#include + #include #include diff --git a/include/boost/container/detail/memory_util.hpp b/include/boost/container/detail/memory_util.hpp index ed89954..572d30a 100644 --- a/include/boost/container/detail/memory_util.hpp +++ b/include/boost/container/detail/memory_util.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,20 +17,22 @@ #include #include + #include +#include #include #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME allocate #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 2, )) +#define BOOST_PP_ITERATION_PARAMS_1 (3, (2, 2, )) #include BOOST_PP_ITERATE() #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME destroy #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 3, )) +#define BOOST_PP_ITERATION_PARAMS_1 (3, (1, 1, )) #include BOOST_PP_ITERATE() #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME max_size @@ -48,20 +50,19 @@ #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME construct #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS+1, )) +#define BOOST_PP_ITERATION_PARAMS_1 (3, (1, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS+1, )) #include BOOST_PP_ITERATE() #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME swap #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace container_detail { #define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} -#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 1, )) +#define BOOST_PP_ITERATION_PARAMS_1 (3, (1, 1, )) #include BOOST_PP_ITERATE() namespace boost { namespace container { namespace container_detail { - BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(pointer) BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(const_pointer) BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(reference) @@ -73,6 +74,8 @@ BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_copy_assig BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_move_assignment) BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(propagate_on_container_swap) BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(difference_type) +BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(value_compare) +BOOST_INTRUSIVE_INSTANTIATE_DEFAULT_TYPE_TMPLT(wrapped_value_compare) } //namespace container_detail { } //namespace container { diff --git a/include/boost/container/detail/mpl.hpp b/include/boost/container/detail/mpl.hpp index 08f3eae..941e5ee 100644 --- a/include/boost/container/detail/mpl.hpp +++ b/include/boost/container/detail/mpl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -17,6 +17,9 @@ # pragma once #endif +#include +#include + #include namespace boost { @@ -110,8 +113,10 @@ struct if_ template struct select1st -// : public std::unary_function { + typedef Pair argument_type; + typedef typename Pair::first_type result_type; + template const typename Pair::first_type& operator()(const OtherPair& x) const { return x.first; } @@ -123,8 +128,10 @@ struct select1st // identity is an extension: it is not part of the standard. template struct identity -// : public std::unary_function { + typedef T argument_type; + typedef T result_type; + typedef T type; const T& operator()(const T& x) const { return x; } @@ -156,5 +163,7 @@ template <> struct unvoid { struct type { }; }; } //namespace container { } //namespace boost { +#include + #endif //#ifndef BOOST_CONTAINER_CONTAINER_DETAIL_MPL_HPP diff --git a/include/boost/container/detail/multiallocation_chain.hpp b/include/boost/container/detail/multiallocation_chain.hpp index bc9945a..38c331c 100644 --- a/include/boost/container/detail/multiallocation_chain.hpp +++ b/include/boost/container/detail/multiallocation_chain.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,7 +11,9 @@ #ifndef BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP #define BOOST_CONTAINER_DETAIL_MULTIALLOCATION_CHAIN_HPP -#include "config_begin.hpp" +#include +#include + #include #include #include diff --git a/include/boost/container/detail/mutex.hpp b/include/boost/container/detail/mutex.hpp new file mode 100644 index 0000000..89b041c --- /dev/null +++ b/include/boost/container/detail/mutex.hpp @@ -0,0 +1,278 @@ +// Copyright (C) 2000 Stephen Cleary +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org for updates, documentation, and revision history. + +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_MUTEX_HPP +#define BOOST_CONTAINER_MUTEX_HPP + +//#define BOOST_CONTAINER_NO_MT +//#define BOOST_CONTAINER_NO_SPINLOCKS + +#include +#include + +// Extremely Light-Weight wrapper classes for OS thread synchronization + +#define BOOST_MUTEX_HELPER_NONE 0 +#define BOOST_MUTEX_HELPER_WIN32 1 +#define BOOST_MUTEX_HELPER_PTHREAD 2 +#define BOOST_MUTEX_HELPER_SPINLOCKS 3 + +#if !defined(BOOST_HAS_THREADS) && !defined(BOOST_NO_MT) +# define BOOST_NO_MT +#endif + +#if defined(BOOST_NO_MT) || defined(BOOST_CONTAINER_NO_MT) + // No multithreading -> make locks into no-ops + #define BOOST_MUTEX_HELPER BOOST_MUTEX_HELPER_NONE +#else + //Taken from dlmalloc + #if !defined(BOOST_CONTAINER_NO_SPINLOCKS) && \ + ((defined(__GNUC__) && \ + ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \ + defined(__i386__) || defined(__x86_64__))) || \ + (defined(_MSC_VER) && _MSC_VER>=1310)) + #define BOOST_MUTEX_HELPER BOOST_MUTEX_HELPER_SPINLOCKS + #endif + + #if defined(BOOST_WINDOWS) + #include + #ifndef BOOST_MUTEX_HELPER + #define BOOST_MUTEX_HELPER BOOST_MUTEX_HELPER_WIN32 + #endif + #elif defined(BOOST_HAS_UNISTD_H) + #include + #if !defined(BOOST_MUTEX_HELPER) && (defined(_POSIX_THREADS) || defined(BOOST_HAS_PTHREADS)) + #define BOOST_MUTEX_HELPER BOOST_MUTEX_HELPER_PTHREAD + #endif + #endif +#endif + +#ifndef BOOST_MUTEX_HELPER + #error Unable to determine platform mutex type; #define BOOST_NO_MT to assume single-threaded +#endif + +#if BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_NONE + //... +#elif BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_SPINLOCKS + #if defined(_MSC_VER) + #ifndef _M_AMD64 + /* These are already defined on AMD64 builds */ + #ifdef __cplusplus + extern "C" { + #endif /* __cplusplus */ + long __cdecl _InterlockedCompareExchange(long volatile *Dest, long Exchange, long Comp); + long __cdecl _InterlockedExchange(long volatile *Target, long Value); + #ifdef __cplusplus + } + #endif /* __cplusplus */ + #endif /* _M_AMD64 */ + #pragma intrinsic (_InterlockedCompareExchange) + #pragma intrinsic (_InterlockedExchange) + #define interlockedcompareexchange _InterlockedCompareExchange + #define interlockedexchange _InterlockedExchange + #elif defined(WIN32) && defined(__GNUC__) + #define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b) + #define interlockedexchange __sync_lock_test_and_set + #endif /* Win32 */ + + /* First, define CAS_LOCK and CLEAR_LOCK on ints */ + /* Note CAS_LOCK defined to return 0 on success */ + + #if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) + #define BOOST_CONTAINER_CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1) + #define BOOST_CONTAINER_CLEAR_LOCK(sl) __sync_lock_release(sl) + + #elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) + /* Custom spin locks for older gcc on x86 */ + static FORCEINLINE int boost_container_x86_cas_lock(int *sl) { + int ret; + int val = 1; + int cmp = 0; + __asm__ __volatile__ ("lock; cmpxchgl %1, %2" + : "=a" (ret) + : "r" (val), "m" (*(sl)), "0"(cmp) + : "memory", "cc"); + return ret; + } + + static FORCEINLINE void boost_container_x86_clear_lock(int* sl) { + assert(*sl != 0); + int prev = 0; + int ret; + __asm__ __volatile__ ("lock; xchgl %0, %1" + : "=r" (ret) + : "m" (*(sl)), "0"(prev) + : "memory"); + } + + #define BOOST_CONTAINER_CAS_LOCK(sl) boost_container_x86_cas_lock(sl) + #define BOOST_CONTAINER_CLEAR_LOCK(sl) boost_container_x86_clear_lock(sl) + + #else /* Win32 MSC */ + #define BOOST_CONTAINER_CAS_LOCK(sl) interlockedexchange((long volatile*)sl, (long)1) + #define BOOST_CONTAINER_CLEAR_LOCK(sl) interlockedexchange((long volatile*)sl, (long)0) + #endif + + /* How to yield for a spin lock */ + #define SPINS_PER_YIELD 63 + #if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) + #define SLEEP_EX_DURATION 50 /* delay for yield/sleep */ + #define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE) + #elif defined (__SVR4) && defined (__sun) /* solaris */ + #define SPIN_LOCK_YIELD thr_yield(); + #elif !defined(LACKS_SCHED_H) + #define SPIN_LOCK_YIELD sched_yield(); + #else + #define SPIN_LOCK_YIELD + #endif /* ... yield ... */ + + #define BOOST_CONTAINER_SPINS_PER_YIELD 63 + inline int boost_interprocess_spin_acquire_lock(int *sl) { + int spins = 0; + while (*(volatile int *)sl != 0 || + BOOST_CONTAINER_CAS_LOCK(sl)) { + if ((++spins & BOOST_CONTAINER_SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } + return 0; + } + #define BOOST_CONTAINER_MLOCK_T int + #define BOOST_CONTAINER_TRY_LOCK(sl) !BOOST_CONTAINER_CAS_LOCK(sl) + #define BOOST_CONTAINER_RELEASE_LOCK(sl) BOOST_CONTAINER_CLEAR_LOCK(sl) + #define BOOST_CONTAINER_ACQUIRE_LOCK(sl) (BOOST_CONTAINER_CAS_LOCK(sl)? boost_interprocess_spin_acquire_lock(sl) : 0) + #define BOOST_CONTAINER_INITIAL_LOCK(sl) (*sl = 0) + #define BOOST_CONTAINER_DESTROY_LOCK(sl) (0) +#elif BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_WIN32 + // +#elif BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_PTHREAD + #include +#endif + +namespace boost { +namespace container { +namespace container_detail { + +#if BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_NONE + class null_mutex + { + private: + null_mutex(const null_mutex &); + void operator=(const null_mutex &); + + public: + null_mutex() { } + + static void lock() { } + static void unlock() { } + }; + + typedef null_mutex default_mutex; +#elif BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_SPINLOCKS + + class spin_mutex + { + private: + BOOST_CONTAINER_MLOCK_T sl; + spin_mutex(const spin_mutex &); + void operator=(const spin_mutex &); + + public: + spin_mutex() { BOOST_CONTAINER_INITIAL_LOCK(&sl); } + + void lock() { BOOST_CONTAINER_ACQUIRE_LOCK(&sl); } + void unlock() { BOOST_CONTAINER_RELEASE_LOCK(&sl); } + }; + typedef spin_mutex default_mutex; +#elif BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_WIN32 + class mutex + { + private: + CRITICAL_SECTION mtx; + + mutex(const mutex &); + void operator=(const mutex &); + + public: + mutex() + { InitializeCriticalSection(&mtx); } + + ~mutex() + { DeleteCriticalSection(&mtx); } + + void lock() + { EnterCriticalSection(&mtx); } + + void unlock() + { LeaveCriticalSection(&mtx); } + }; + + typedef mutex default_mutex; +#elif BOOST_MUTEX_HELPER == BOOST_MUTEX_HELPER_PTHREAD + class mutex + { + private: + pthread_mutex_t mtx; + + mutex(const mutex &); + void operator=(const mutex &); + + public: + mutex() + { pthread_mutex_init(&mtx, 0); } + + ~mutex() + { pthread_mutex_destroy(&mtx); } + + void lock() + { pthread_mutex_lock(&mtx); } + + void unlock() + { pthread_mutex_unlock(&mtx); } + }; + + typedef mutex default_mutex; +#endif + +template +class scoped_lock +{ + public: + scoped_lock(Mutex &m) + : m_(m) + { m_.lock(); } + ~scoped_lock() + { m_.unlock(); } + + private: + Mutex &m_; +}; + +} // namespace container_detail +} // namespace container +} // namespace boost + +#undef BOOST_MUTEX_HELPER_WIN32 +#undef BOOST_MUTEX_HELPER_PTHREAD +#undef BOOST_MUTEX_HELPER_NONE +#undef BOOST_MUTEX_HELPER +#undef BOOST_MUTEX_HELPER_SPINLOCKS + +#include + +#endif diff --git a/include/boost/container/detail/node_alloc_holder.hpp b/include/boost/container/detail/node_alloc_holder.hpp index d94c2e9..3c1b4f6 100644 --- a/include/boost/container/detail/node_alloc_holder.hpp +++ b/include/boost/container/detail/node_alloc_holder.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,7 +15,7 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include #include @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -50,33 +51,44 @@ template struct node_compare : private ValueCompare { - typedef typename ValueCompare::key_type key_type; - typedef typename ValueCompare::value_type value_type; - typedef typename ValueCompare::key_of_value key_of_value; + typedef ValueCompare wrapped_value_compare; + typedef typename wrapped_value_compare::key_type key_type; + typedef typename wrapped_value_compare::value_type value_type; + typedef typename wrapped_value_compare::key_of_value key_of_value; - explicit node_compare(const ValueCompare &pred) - : ValueCompare(pred) + explicit node_compare(const wrapped_value_compare &pred) + : wrapped_value_compare(pred) {} node_compare() - : ValueCompare() + : wrapped_value_compare() {} - ValueCompare &value_comp() - { return static_cast(*this); } + wrapped_value_compare &value_comp() + { return static_cast(*this); } - ValueCompare &value_comp() const - { return static_cast(*this); } + wrapped_value_compare &value_comp() const + { return static_cast(*this); } bool operator()(const Node &a, const Node &b) const - { return ValueCompare::operator()(a.get_data(), b.get_data()); } + { return wrapped_value_compare::operator()(a.get_data(), b.get_data()); } }; -template +template struct node_alloc_holder { + //If the intrusive container is an associative container, obtain the predicate, which will + //be of type node_compare<>. If not an associative container value_compare will be a "nat" type. + typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, ICont, + value_compare, container_detail::nat) intrusive_value_compare; + //In that case obtain the value predicate from the node predicate via wrapped_value_compare + //if intrusive_value_compare is node_compare<>, nat otherwise + typedef BOOST_INTRUSIVE_OBTAIN_TYPE_WITH_DEFAULT(boost::container::container_detail::, ICont, + wrapped_value_compare, container_detail::nat) value_compare; + typedef allocator_traits allocator_traits_type; typedef typename allocator_traits_type::value_type value_type; + typedef ICont intrusive_container; typedef typename ICont::value_type Node; typedef typename allocator_traits_type::template portable_rebind_alloc::type NodeAlloc; @@ -121,20 +133,20 @@ struct node_alloc_holder { this->icont().swap(x.icont()); } //Constructors for associative containers - explicit node_alloc_holder(const ValAlloc &a, const ValPred &c) + explicit node_alloc_holder(const ValAlloc &a, const value_compare &c) : members_(a, c) {} - explicit node_alloc_holder(const node_alloc_holder &x, const ValPred &c) + explicit node_alloc_holder(const node_alloc_holder &x, const value_compare &c) : members_(NodeAllocTraits::select_on_container_copy_construction(x.node_alloc()), c) {} - explicit node_alloc_holder(const ValPred &c) + explicit node_alloc_holder(const value_compare &c) : members_(c) {} //helpers for move assignments - explicit node_alloc_holder(BOOST_RV_REF(node_alloc_holder) x, const ValPred &c) + explicit node_alloc_holder(BOOST_RV_REF(node_alloc_holder) x, const value_compare &c) : members_(boost::move(x.node_alloc()), c) { this->icont().swap(x.icont()); } @@ -346,12 +358,12 @@ struct node_alloc_holder {} template - members_holder(BOOST_FWD_REF(ConvertibleToAlloc) c2alloc, const ValPred &c) + members_holder(BOOST_FWD_REF(ConvertibleToAlloc) c2alloc, const value_compare &c) : NodeAlloc(boost::forward(c2alloc)) , m_icont(typename ICont::value_compare(c)) {} - explicit members_holder(const ValPred &c) + explicit members_holder(const value_compare &c) : NodeAlloc() , m_icont(typename ICont::value_compare(c)) {} diff --git a/include/boost/container/detail/node_pool.hpp b/include/boost/container/detail/node_pool.hpp new file mode 100644 index 0000000..323935e --- /dev/null +++ b/include/boost/container/detail/node_pool.hpp @@ -0,0 +1,157 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_HPP +#define BOOST_CONTAINER_DETAIL_NODE_POOL_HPP + +#if defined(_MSC_VER) && (_MSC_VER >= 1200) +# pragma once +#endif + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include //std::unary_function +#include //std::swap +#include + +namespace boost { +namespace container { +namespace container_detail { + +//!Pooled memory allocator using single segregated storage. Includes +//!a reference count but the class does not delete itself, this is +//!responsibility of user classes. Node size (NodeSize) and the number of +//!nodes allocated per block (NodesPerBlock) are known at compile time +template< std::size_t NodeSize, std::size_t NodesPerBlock > +class private_node_pool + //Inherit from the implementation to avoid template bloat + : public boost::container::container_detail:: + private_node_pool_impl +{ + typedef boost::container::container_detail:: + private_node_pool_impl base_t; + //Non-copyable + private_node_pool(const private_node_pool &); + private_node_pool &operator=(const private_node_pool &); + + public: + typedef typename base_t::multiallocation_chain multiallocation_chain; + static const std::size_t nodes_per_block = NodesPerBlock; + + //!Constructor from a segment manager. Never throws + private_node_pool() + : base_t(0, NodeSize, NodesPerBlock) + {} + +}; + +template< std::size_t NodeSize + , std::size_t NodesPerBlock + > +class shared_node_pool + : public private_node_pool +{ + private: + typedef private_node_pool private_node_allocator_t; + + public: + typedef typename private_node_allocator_t::free_nodes_t free_nodes_t; + typedef typename private_node_allocator_t::multiallocation_chain multiallocation_chain; + + //!Constructor from a segment manager. Never throws + shared_node_pool() + : private_node_allocator_t(){} + + //!Destructor. Deallocates all allocated blocks. Never throws + ~shared_node_pool() + {} + + //!Allocates array of count elements. Can throw std::bad_alloc + void *allocate_node() + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + return private_node_allocator_t::allocate_node(); + } + + //!Deallocates an array pointed by ptr. Never throws + void deallocate_node(void *ptr) + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::deallocate_node(ptr); + } + + //!Allocates a singly linked list of n nodes ending in null pointer. + //!can throw std::bad_alloc + void allocate_nodes(const std::size_t n, multiallocation_chain &chain) + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + return private_node_allocator_t::allocate_nodes(n, chain); + } + + void deallocate_nodes(multiallocation_chain &chain) + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::deallocate_nodes(chain); + } + + //!Deallocates all the free blocks of memory. Never throws + void deallocate_free_blocks() + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::deallocate_free_blocks(); + } + + //!Deallocates all blocks. Never throws + void purge_blocks() + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + private_node_allocator_t::purge_blocks(); + } + + std::size_t num_free_nodes() + { + //----------------------- + scoped_lock guard(mutex_); + //----------------------- + return private_node_allocator_t::num_free_nodes(); + } + + private: + default_mutex mutex_; +}; + +} //namespace container_detail { +} //namespace container { +} //namespace boost { + +#include + +#endif //#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_HPP diff --git a/include/boost/container/detail/node_pool_impl.hpp b/include/boost/container/detail/node_pool_impl.hpp index 0c5c744..b7f5996 100644 --- a/include/boost/container/detail/node_pool_impl.hpp +++ b/include/boost/container/detail/node_pool_impl.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,9 +15,10 @@ # pragma once #endif -#include "config_begin.hpp" -#include +#include #include + +#include #include #include #include @@ -29,8 +30,6 @@ #include #include #include -#include //std::unary_function - namespace boost { namespace container { @@ -251,8 +250,10 @@ class private_node_pool_impl }; struct is_between - : std::unary_function { + typedef typename free_nodes_t::value_type argument_type; + typedef bool result_type; + is_between(const void *addr, std::size_t size) : beg_(static_cast(addr)), end_(beg_+size) {} diff --git a/include/boost/container/detail/pair.hpp b/include/boost/container/detail/pair.hpp index bfe7978..0d7e0a9 100644 --- a/include/boost/container/detail/pair.hpp +++ b/include/boost/container/detail/pair.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -17,7 +17,7 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include #include diff --git a/include/boost/container/detail/pool_common.hpp b/include/boost/container/detail/pool_common.hpp index 6ab2d43..53a7427 100644 --- a/include/boost/container/detail/pool_common.hpp +++ b/include/boost/container/detail/pool_common.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -8,14 +8,16 @@ // ////////////////////////////////////////////////////////////////////////////// -#ifndef BOOST_CONTAINER_DETAIL_NODE_POOL_COMMON_HPP -#define BOOST_CONTAINER_DETAIL_NODE_POOL_COMMON_HPP +#ifndef BOOST_CONTAINER_DETAIL_POOL_COMMON_HPP +#define BOOST_CONTAINER_DETAIL_POOL_COMMON_HPP #if defined(_MSC_VER) # pragma once #endif -#include "config_begin.hpp" +#include +#include + #include #include diff --git a/include/boost/container/detail/pool_common_alloc.hpp b/include/boost/container/detail/pool_common_alloc.hpp new file mode 100644 index 0000000..37186a6 --- /dev/null +++ b/include/boost/container/detail/pool_common_alloc.hpp @@ -0,0 +1,94 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_DETAIL_POOL_COMMON_ALLOC_HPP +#define BOOST_CONTAINER_DETAIL_POOL_COMMON_ALLOC_HPP + +#include +#include +#include + +#include +#include +#include +#include + +namespace boost{ +namespace container{ +namespace container_detail{ + +struct node_slist_helper + : public boost::container::container_detail::node_slist +{}; + +struct fake_segment_manager +{ + typedef void * void_pointer; + static const std::size_t PayloadPerAllocation = BOOST_CONTAINER_ALLOCATION_PAYLOAD; + + typedef boost::container::container_detail:: + basic_multiallocation_chain multiallocation_chain; + static void deallocate(void_pointer p) + { boost_cont_free(p); } + + static void deallocate_many(multiallocation_chain &chain) + { + std::size_t size = chain.size(); + std::pair ptrs = chain.extract_data(); + boost_cont_memchain dlchain; + BOOST_CONTAINER_MEMCHAIN_INIT_FROM(&dlchain, ptrs.first, ptrs.second, size); + boost_cont_multidealloc(&dlchain); + } + + typedef std::ptrdiff_t difference_type; + typedef std::size_t size_type; + + static void *allocate_aligned(std::size_t nbytes, std::size_t alignment) + { + void *ret = boost_cont_memalign(nbytes, alignment); + if(!ret) + boost::container::throw_bad_alloc(); + return ret; + } + + static void *allocate(std::size_t nbytes) + { + void *ret = boost_cont_malloc(nbytes); + if(!ret) + boost::container::throw_bad_alloc(); + return ret; + } +}; + +} //namespace boost{ +} //namespace container{ +} //namespace container_detail{ + +namespace boost { +namespace container { +namespace container_detail { + +template +struct is_stateless_segment_manager; + +template<> +struct is_stateless_segment_manager + +{ + static const bool value = true; +}; + +} //namespace container_detail { +} //namespace container { +} //namespace boost { + +#include + +#endif //BOOST_CONTAINER_DETAIL_POOL_COMMON_ALLOC_HPP diff --git a/include/boost/container/detail/preprocessor.hpp b/include/boost/container/detail/preprocessor.hpp index 41d1f55..7e4f5eb 100644 --- a/include/boost/container/detail/preprocessor.hpp +++ b/include/boost/container/detail/preprocessor.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/include/boost/container/detail/singleton.hpp b/include/boost/container/detail/singleton.hpp new file mode 100644 index 0000000..0843319 --- /dev/null +++ b/include/boost/container/detail/singleton.hpp @@ -0,0 +1,113 @@ +// Copyright (C) 2000 Stephen Cleary +// Copyright (C) 2008 Ion Gaztanaga +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org for updates, documentation, and revision history. +// +// This file is a modified file from Boost.Pool + +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_DETAIL_SINGLETON_DETAIL_HPP +#define BOOST_CONTAINER_DETAIL_SINGLETON_DETAIL_HPP + +#include +#include + +// +// The following helper classes are placeholders for a generic "singleton" +// class. The classes below support usage of singletons, including use in +// program startup/shutdown code, AS LONG AS there is only one thread +// running before main() begins, and only one thread running after main() +// exits. +// +// This class is also limited in that it can only provide singleton usage for +// classes with default constructors. +// + +// The design of this class is somewhat twisted, but can be followed by the +// calling inheritance. Let us assume that there is some user code that +// calls "singleton_default::instance()". The following (convoluted) +// sequence ensures that the same function will be called before main(): +// instance() contains a call to create_object.do_nothing() +// Thus, object_creator is implicitly instantiated, and create_object +// must exist. +// Since create_object is a static member, its constructor must be +// called before main(). +// The constructor contains a call to instance(), thus ensuring that +// instance() will be called before main(). +// The first time instance() is called (i.e., before main()) is the +// latest point in program execution where the object of type T +// can be created. +// Thus, any call to instance() will auto-magically result in a call to +// instance() before main(), unless already present. +// Furthermore, since the instance() function contains the object, instead +// of the singleton_default class containing a static instance of the +// object, that object is guaranteed to be constructed (at the latest) in +// the first call to instance(). This permits calls to instance() from +// static code, even if that code is called before the file-scope objects +// in this file have been initialized. + +namespace boost { +namespace container { +namespace container_detail { + +// T must be: no-throw default constructible and no-throw destructible +template +struct singleton_default +{ + private: + struct object_creator + { + // This constructor does nothing more than ensure that instance() + // is called before main() begins, thus creating the static + // T object before multithreading race issues can come up. + object_creator() { singleton_default::instance(); } + inline void do_nothing() const { } + }; + static object_creator create_object; + + singleton_default(); + + public: + typedef T object_type; + + // If, at any point (in user code), singleton_default::instance() + // is called, then the following function is instantiated. + static object_type & instance() + { + // This is the object that we return a reference to. + // It is guaranteed to be created before main() begins because of + // the next line. + static object_type obj; + + // The following line does nothing else than force the instantiation + // of singleton_default::create_object, whose constructor is + // called before main() begins. + create_object.do_nothing(); + + return obj; + } +}; +template +typename singleton_default::object_creator +singleton_default::create_object; + +} // namespace container_detail +} // namespace container +} // namespace boost + +#include + +#endif //BOOST_CONTAINER_DETAIL_SINGLETON_DETAIL_HPP diff --git a/include/boost/container/detail/transform_iterator.hpp b/include/boost/container/detail/transform_iterator.hpp index c40ecc6..f10f3fe 100644 --- a/include/boost/container/detail/transform_iterator.hpp +++ b/include/boost/container/detail/transform_iterator.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // (C) Copyright Gennaro Prota 2003 - 2004. // // Distributed under the Boost Software License, Version 1.0. @@ -18,8 +18,9 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include + #include #include diff --git a/include/boost/container/detail/tree.hpp b/include/boost/container/detail/tree.hpp index 7400a1a..16db841 100644 --- a/include/boost/container/detail/tree.hpp +++ b/include/boost/container/detail/tree.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,15 +11,10 @@ #ifndef BOOST_CONTAINER_TREE_HPP #define BOOST_CONTAINER_TREE_HPP -#include "config_begin.hpp" +#include #include #include -#include -#include -#include -#include -#include #include #include #include @@ -28,7 +23,19 @@ #include #include #include +#include + +// +#include +#include +#include +#include +#include +// +#include +#include #include +// #ifndef BOOST_CONTAINER_PERFECT_FORWARDING #include #endif @@ -85,47 +92,78 @@ struct tree_value_compare { return key_compare::operator()(this->key_forward(key1), this->key_forward(key2)); } }; -template -struct rbtree_hook +template +struct intrusive_tree_hook; + +template +struct intrusive_tree_hook { typedef typename container_detail::bi::make_set_base_hook < container_detail::bi::void_pointer , container_detail::bi::link_mode - , container_detail::bi::optimize_size + , container_detail::bi::optimize_size + >::type type; +}; + +template +struct intrusive_tree_hook +{ + typedef typename container_detail::bi::make_avl_set_base_hook + < container_detail::bi::void_pointer + , container_detail::bi::link_mode + , container_detail::bi::optimize_size + >::type type; +}; + +template +struct intrusive_tree_hook +{ + typedef typename container_detail::bi::make_bs_set_base_hook + < container_detail::bi::void_pointer + , container_detail::bi::link_mode + >::type type; +}; + +template +struct intrusive_tree_hook +{ + typedef typename container_detail::bi::make_bs_set_base_hook + < container_detail::bi::void_pointer + , container_detail::bi::link_mode >::type type; }; //This trait is used to type-pun std::pair because in C++03 //compilers std::pair is useless for C++11 features template -struct rbtree_internal_data_type +struct tree_internal_data_type { typedef T type; }; template -struct rbtree_internal_data_type< std::pair > +struct tree_internal_data_type< std::pair > { typedef pair type; }; - //The node to be store in the tree -template -struct rbtree_node - : public rbtree_hook::type +template +struct tree_node + : public intrusive_tree_hook::type { private: - //BOOST_COPYABLE_AND_MOVABLE(rbtree_node) - rbtree_node(); + //BOOST_COPYABLE_AND_MOVABLE(tree_node) + tree_node(); public: - typedef typename rbtree_hook::type hook_type; - + typedef typename intrusive_tree_hook + ::type hook_type; typedef T value_type; - typedef typename rbtree_internal_data_type::type internal_type; + typedef typename tree_internal_data_type::type internal_type; - typedef rbtree_node node_type; + typedef tree_node< T, VoidPointer + , tree_type_value, OptimizeSize> node_type; T &get_data() { @@ -210,52 +248,224 @@ class push_back_functor namespace container_detail { -template -struct intrusive_rbtree_type +template< class NodeType, class NodeCompareType + , class SizeType, class HookType + , boost::container::tree_type_enum tree_type_value> +struct intrusive_tree_dispatch; + +template +struct intrusive_tree_dispatch + { + typedef typename container_detail::bi::make_rbtree + + ,container_detail::bi::base_hook + ,container_detail::bi::constant_time_size + ,container_detail::bi::size_type + >::type type; +}; + +template +struct intrusive_tree_dispatch + +{ + typedef typename container_detail::bi::make_avltree + + ,container_detail::bi::base_hook + ,container_detail::bi::constant_time_size + ,container_detail::bi::size_type + >::type type; +}; + +template +struct intrusive_tree_dispatch + +{ + typedef typename container_detail::bi::make_sgtree + + ,container_detail::bi::base_hook + ,container_detail::bi::floating_point + ,container_detail::bi::size_type + >::type type; +}; + +template +struct intrusive_tree_dispatch + +{ + typedef typename container_detail::bi::make_splaytree + + ,container_detail::bi::base_hook + ,container_detail::bi::constant_time_size + ,container_detail::bi::size_type + >::type type; +}; + +template +struct intrusive_tree_type +{ + private: typedef typename boost::container:: allocator_traits::value_type value_type; typedef typename boost::container:: allocator_traits::void_pointer void_pointer; typedef typename boost::container:: allocator_traits::size_type size_type; - typedef typename container_detail::rbtree_node - node_type; + typedef typename container_detail::tree_node + < value_type, void_pointer + , tree_type_value, OptimizeSize> node_type; typedef node_compare node_compare_type; - typedef typename container_detail::bi::make_rbtree - - ,container_detail::bi::base_hook::type> - ,container_detail::bi::constant_time_size - ,container_detail::bi::size_type - >::type container_type; - typedef container_type type ; + //Deducing the hook type from node_type (e.g. node_type::hook_type) would + //provoke an early instantiation of node_type that could ruin recursive + //tree definitions, so retype the complete type to avoid any problem. + typedef typename intrusive_tree_hook + ::type hook_type; + public: + typedef typename intrusive_tree_dispatch + < node_type, node_compare_type + , size_type, hook_type + , tree_type_value>::type type; +}; + +//Trait to detect manually rebalanceable tree types +template +struct is_manually_balanceable +{ static const bool value = true; }; + +template<> struct is_manually_balanceable +{ static const bool value = false; }; + +template<> struct is_manually_balanceable +{ static const bool value = false; }; + +//Proxy traits to implement different operations depending on the +//is_manually_balanceable<>::value +template< boost::container::tree_type_enum tree_type_value + , bool IsManuallyRebalanceable = is_manually_balanceable::value> +struct intrusive_tree_proxy +{ + template + static void rebalance(Icont &) {} +}; + +template +struct intrusive_tree_proxy +{ + template + static void rebalance(Icont &c) + { c.rebalance(); } }; } //namespace container_detail { namespace container_detail { +//This functor will be used with Intrusive clone functions to obtain +//already allocated nodes from a intrusive container instead of +//allocating new ones. When the intrusive container runs out of nodes +//the node holder is used instead. +template +class RecyclingCloner +{ + typedef typename AllocHolder::intrusive_container intrusive_container; + typedef typename AllocHolder::Node node_type; + typedef typename AllocHolder::NodePtr node_ptr_type; + + public: + RecyclingCloner(AllocHolder &holder, intrusive_container &itree) + : m_holder(holder), m_icont(itree) + {} + + static void do_assign(node_ptr_type &p, const node_type &other, bool_) + { p->do_assign(other.m_data); } + + static void do_assign(node_ptr_type &p, const node_type &other, bool_) + { p->do_move_assign(const_cast(other).m_data); } + + node_ptr_type operator()(const node_type &other) const + { + if(node_ptr_type p = m_icont.unlink_leftmost_without_rebalance()){ + //First recycle a node (this can't throw) + BOOST_TRY{ + //This can throw + this->do_assign(p, other, bool_()); + return p; + } + BOOST_CATCH(...){ + //If there is an exception destroy the whole source + m_holder.destroy_node(p); + while((p = m_icont.unlink_leftmost_without_rebalance())){ + m_holder.destroy_node(p); + } + BOOST_RETHROW + } + BOOST_CATCH_END + } + else{ + return m_holder.create_node(other.m_data); + } + } + + AllocHolder &m_holder; + intrusive_container &m_icont; +}; + +template +//where KeyValueCompare is tree_value_compare +struct key_node_compare + : private KeyValueCompare +{ + explicit key_node_compare(const KeyValueCompare &comp) + : KeyValueCompare(comp) + {} + + template + struct is_node + { + static const bool value = is_same::value; + }; + + template + typename enable_if_c::value, const typename KeyValueCompare::value_type &>::type + key_forward(const T &node) const + { return node.get_data(); } + + template + typename enable_if_c::value, const T &>::type + key_forward(const T &key) const + { return key; } + + template + bool operator()(const KeyType &key1, const KeyType2 &key2) const + { return KeyValueCompare::operator()(this->key_forward(key1), this->key_forward(key2)); } +}; + template -class rbtree + class KeyCompare, class A, + class Options = tree_assoc_defaults> +class tree : protected container_detail::node_alloc_holder < A - , typename container_detail::intrusive_rbtree_type - - >::type - , tree_value_compare + , typename container_detail::intrusive_tree_type + < A, tree_value_compare //ValComp + , Options::tree_type, Options::optimize_size>::type > { typedef tree_value_compare ValComp; - typedef typename container_detail::intrusive_rbtree_type - < A, ValComp>::type Icont; + typedef typename container_detail::intrusive_tree_type + < A, ValComp, Options::tree_type + , Options::optimize_size>::type Icont; typedef container_detail::node_alloc_holder - AllocHolder; + AllocHolder; typedef typename AllocHolder::NodePtr NodePtr; - typedef rbtree < Key, Value, KeyOfValue - , KeyCompare, A> ThisType; + typedef tree < Key, Value, KeyOfValue + , KeyCompare, A, Options> ThisType; typedef typename AllocHolder::NodeAlloc NodeAlloc; typedef typename AllocHolder::ValAlloc ValAlloc; typedef typename AllocHolder::Node Node; @@ -265,84 +475,9 @@ class rbtree typedef typename AllocHolder::allocator_v1 allocator_v1; typedef typename AllocHolder::allocator_v2 allocator_v2; typedef typename AllocHolder::alloc_version alloc_version; + typedef intrusive_tree_proxy intrusive_tree_proxy_t; - class RecyclingCloner; - friend class RecyclingCloner; - - class RecyclingCloner - { - public: - RecyclingCloner(AllocHolder &holder, Icont &irbtree) - : m_holder(holder), m_icont(irbtree) - {} - - NodePtr operator()(const Node &other) const - { - if(NodePtr p = m_icont.unlink_leftmost_without_rebalance()){ - //First recycle a node (this can't throw) - BOOST_TRY{ - //This can throw - p->do_assign(other.m_data); - return p; - } - BOOST_CATCH(...){ - //If there is an exception destroy the whole source - m_holder.destroy_node(p); - while((p = m_icont.unlink_leftmost_without_rebalance())){ - m_holder.destroy_node(p); - } - BOOST_RETHROW - } - BOOST_CATCH_END - } - else{ - return m_holder.create_node(other.m_data); - } - } - - AllocHolder &m_holder; - Icont &m_icont; - }; - - class RecyclingMoveCloner; - friend class RecyclingMoveCloner; - - class RecyclingMoveCloner - { - public: - RecyclingMoveCloner(AllocHolder &holder, Icont &irbtree) - : m_holder(holder), m_icont(irbtree) - {} - - NodePtr operator()(const Node &other) const - { - if(NodePtr p = m_icont.unlink_leftmost_without_rebalance()){ - //First recycle a node (this can't throw) - BOOST_TRY{ - //This can throw - p->do_move_assign(const_cast(other).m_data); - return p; - } - BOOST_CATCH(...){ - //If there is an exception destroy the whole source - m_holder.destroy_node(p); - while((p = m_icont.unlink_leftmost_without_rebalance())){ - m_holder.destroy_node(p); - } - BOOST_RETHROW - } - BOOST_CATCH_END - } - else{ - return m_holder.create_node(other.m_data); - } - } - - AllocHolder &m_holder; - Icont &m_icont; - }; - - BOOST_COPYABLE_AND_MOVABLE(rbtree) + BOOST_COPYABLE_AND_MOVABLE(tree) public: @@ -363,45 +498,16 @@ class rbtree allocator_traits::size_type size_type; typedef typename boost::container:: allocator_traits::difference_type difference_type; - typedef difference_type rbtree_difference_type; - typedef pointer rbtree_pointer; - typedef const_pointer rbtree_const_pointer; - typedef reference rbtree_reference; - typedef const_reference rbtree_const_reference; + typedef difference_type tree_difference_type; + typedef pointer tree_pointer; + typedef const_pointer tree_const_pointer; + typedef reference tree_reference; + typedef const_reference tree_const_reference; typedef NodeAlloc stored_allocator_type; private: - template - struct key_node_compare - : private KeyValueCompare - { - key_node_compare(const KeyValueCompare &comp) - : KeyValueCompare(comp) - {} - - template - struct is_node - { - static const bool value = is_same::value; - }; - - template - typename enable_if_c::value, const value_type &>::type - key_forward(const T &node) const - { return node.get_data(); } - - template - typename enable_if_c::value, const T &>::type - key_forward(const T &key) const - { return key; } - - template - bool operator()(const KeyType &key1, const KeyType2 &key2) const - { return KeyValueCompare::operator()(this->key_forward(key1), this->key_forward(key2)); } - }; - - typedef key_node_compare KeyNodeCompare; + typedef key_node_compare KeyNodeCompare; public: typedef container_detail::iterator iterator; @@ -409,20 +515,20 @@ class rbtree typedef std::reverse_iterator reverse_iterator; typedef std::reverse_iterator const_reverse_iterator; - rbtree() + tree() : AllocHolder(ValComp(key_compare())) {} - explicit rbtree(const key_compare& comp, const allocator_type& a = allocator_type()) + explicit tree(const key_compare& comp, const allocator_type& a = allocator_type()) : AllocHolder(a, ValComp(comp)) {} - explicit rbtree(const allocator_type& a) + explicit tree(const allocator_type& a) : AllocHolder(a) {} template - rbtree(bool unique_insertion, InputIterator first, InputIterator last, const key_compare& comp, + tree(bool unique_insertion, InputIterator first, InputIterator last, const key_compare& comp, const allocator_type& a #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) , typename container_detail::enable_if_c @@ -450,7 +556,7 @@ class rbtree } template - rbtree(bool unique_insertion, InputIterator first, InputIterator last, const key_compare& comp, + tree(bool unique_insertion, InputIterator first, InputIterator last, const key_compare& comp, const allocator_type& a #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) , typename container_detail::enable_if_c @@ -479,7 +585,7 @@ class rbtree } template - rbtree( ordered_range_t, InputIterator first, InputIterator last + tree( ordered_range_t, InputIterator first, InputIterator last , const key_compare& comp = key_compare(), const allocator_type& a = allocator_type() #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) , typename container_detail::enable_if_c @@ -496,7 +602,7 @@ class rbtree } template - rbtree( ordered_range_t, InputIterator first, InputIterator last + tree( ordered_range_t, InputIterator first, InputIterator last , const key_compare& comp = key_compare(), const allocator_type& a = allocator_type() #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) , typename container_detail::enable_if_c @@ -513,25 +619,25 @@ class rbtree , container_detail::push_back_functor(this->icont())); } - rbtree(const rbtree& x) + tree(const tree& x) : AllocHolder(x, x.value_comp()) { this->icont().clone_from (x.icont(), typename AllocHolder::cloner(*this), Destroyer(this->node_alloc())); } - rbtree(BOOST_RV_REF(rbtree) x) + tree(BOOST_RV_REF(tree) x) : AllocHolder(::boost::move(static_cast(x)), x.value_comp()) {} - rbtree(const rbtree& x, const allocator_type &a) + tree(const tree& x, const allocator_type &a) : AllocHolder(a, x.value_comp()) { this->icont().clone_from (x.icont(), typename AllocHolder::cloner(*this), Destroyer(this->node_alloc())); } - rbtree(BOOST_RV_REF(rbtree) x, const allocator_type &a) + tree(BOOST_RV_REF(tree) x, const allocator_type &a) : AllocHolder(a, x.value_comp()) { if(this->node_alloc() == x.node_alloc()){ @@ -543,10 +649,10 @@ class rbtree } } - ~rbtree() + ~tree() {} //AllocHolder clears the tree - rbtree& operator=(BOOST_COPY_ASSIGN_REF(rbtree) x) + tree& operator=(BOOST_COPY_ASSIGN_REF(tree) x) { if (&x != this){ NodeAlloc &this_alloc = this->get_stored_allocator(); @@ -565,7 +671,7 @@ class rbtree //Now recreate the source tree reusing nodes stored by other_tree this->icont().clone_from (x.icont() - , RecyclingCloner(*this, other_tree) + , RecyclingCloner(*this, other_tree) , Destroyer(this->node_alloc())); //If there are remaining nodes, destroy them @@ -577,7 +683,7 @@ class rbtree return *this; } - rbtree& operator=(BOOST_RV_REF(rbtree) x) + tree& operator=(BOOST_RV_REF(tree) x) { if (&x != this){ NodeAlloc &this_alloc = this->get_stored_allocator(); @@ -600,7 +706,7 @@ class rbtree //Now recreate the source tree reusing nodes stored by other_tree this->icont().clone_from (x.icont() - , RecyclingMoveCloner(*this, other_tree) + , RecyclingCloner(*this, other_tree) , Destroyer(this->node_alloc())); //If there are remaining nodes, destroy them @@ -965,7 +1071,8 @@ class rbtree void clear() { AllocHolder::clear(alloc_version()); } - // set operations: + // search operations. Const and non-const overloads even if no iterator is returned + // so splay implementations can to their rebalancing when searching in non-const versions iterator find(const key_type& k) { return iterator(this->icont().find(k, KeyNodeCompare(value_comp()))); } @@ -1001,70 +1108,47 @@ class rbtree return std::pair (const_iterator(ret.first), const_iterator(ret.second)); } + + std::pair lower_bound_range(const key_type& k) + { + std::pair ret = + this->icont().lower_bound_range(k, KeyNodeCompare(value_comp())); + return std::pair(iterator(ret.first), iterator(ret.second)); + } + + std::pair lower_bound_range(const key_type& k) const + { + std::pair ret = + this->non_const_icont().lower_bound_range(k, KeyNodeCompare(value_comp())); + return std::pair + (const_iterator(ret.first), const_iterator(ret.second)); + } + + void rebalance() + { intrusive_tree_proxy_t::rebalance(this->icont()); } + + friend bool operator==(const tree& x, const tree& y) + { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } + + friend bool operator<(const tree& x, const tree& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + friend bool operator!=(const tree& x, const tree& y) + { return !(x == y); } + + friend bool operator>(const tree& x, const tree& y) + { return y < x; } + + friend bool operator<=(const tree& x, const tree& y) + { return !(y < x); } + + friend bool operator>=(const tree& x, const tree& y) + { return !(x < y); } + + friend void swap(tree& x, tree& y) + { x.swap(y); } }; -template -inline bool -operator==(const rbtree& x, - const rbtree& y) -{ - return x.size() == y.size() && - std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator<(const rbtree& x, - const rbtree& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), - y.begin(), y.end()); -} - -template -inline bool -operator!=(const rbtree& x, - const rbtree& y) { - return !(x == y); -} - -template -inline bool -operator>(const rbtree& x, - const rbtree& y) { - return y < x; -} - -template -inline bool -operator<=(const rbtree& x, - const rbtree& y) { - return !(y < x); -} - -template -inline bool -operator>=(const rbtree& x, - const rbtree& y) { - return !(x < y); -} - - -template -inline void -swap(rbtree& x, - rbtree& y) -{ - x.swap(y); -} - } //namespace container_detail { } //namespace container { /* @@ -1073,7 +1157,7 @@ swap(rbtree& x, template struct has_trivial_destructor_after_move - > + > { static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; }; diff --git a/include/boost/container/detail/type_traits.hpp b/include/boost/container/detail/type_traits.hpp index 8dbd182..6f20bd5 100644 --- a/include/boost/container/detail/type_traits.hpp +++ b/include/boost/container/detail/type_traits.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // (C) Copyright John Maddock 2000. -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -19,7 +19,8 @@ # pragma once #endif -#include "config_begin.hpp" +#include +#include #include diff --git a/include/boost/container/detail/utilities.hpp b/include/boost/container/detail/utilities.hpp index c42087c..9298988 100644 --- a/include/boost/container/detail/utilities.hpp +++ b/include/boost/container/detail/utilities.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,8 +11,9 @@ #ifndef BOOST_CONTAINER_DETAIL_UTILITIES_HPP #define BOOST_CONTAINER_DETAIL_UTILITIES_HPP -#include "config_begin.hpp" -#include "workaround.hpp" +#include +#include + #include #include //for ::memcpy #include @@ -24,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -109,25 +111,47 @@ template const T &min_value(const T &a, const T &b) { return a < b ? a : b; } -template -SizeType - get_next_capacity(const SizeType max_size - ,const SizeType capacity - ,const SizeType n) +enum NextCapacityOption { NextCapacityDouble, NextCapacity60Percent }; + +template +struct next_capacity_calculator; + +template +struct next_capacity_calculator { -// if (n > max_size - capacity) -// throw std::length_error("get_next_capacity"); + static SizeType get(const SizeType max_size + ,const SizeType capacity + ,const SizeType n) + { + const SizeType remaining = max_size - capacity; + if ( remaining < n ) + boost::container::throw_length_error("get_next_capacity, allocator's max_size reached"); + const SizeType additional = max_value(n, capacity); + return ( remaining < additional ) ? max_size : ( capacity + additional ); + } +}; - const SizeType m3 = max_size/3; - if (capacity < m3) - return capacity + max_value(3*(capacity+1)/5, n); +template +struct next_capacity_calculator +{ + static SizeType get(const SizeType max_size + ,const SizeType capacity + ,const SizeType n) + { + const SizeType remaining = max_size - capacity; + if ( remaining < n ) + boost::container::throw_length_error("get_next_capacity, allocator's max_size reached"); + const SizeType m3 = max_size/3; - if (capacity < m3*2) - return capacity + max_value((capacity+1)/2, n); + if (capacity < m3) + return capacity + max_value(3*(capacity+1)/5, n); - return max_size; -} + if (capacity < m3*2) + return capacity + max_value((capacity+1)/2, n); + return max_size; + } +}; template inline T* to_raw_pointer(T* p) diff --git a/include/boost/container/detail/value_init.hpp b/include/boost/container/detail/value_init.hpp index afe5b15..68f9678 100644 --- a/include/boost/container/detail/value_init.hpp +++ b/include/boost/container/detail/value_init.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. +// (C) Copyright Ion Gaztanaga 2005-2013. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at @@ -17,7 +17,7 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include namespace boost { diff --git a/include/boost/container/detail/variadic_templates_tools.hpp b/include/boost/container/detail/variadic_templates_tools.hpp index cce7fed..b07fe30 100644 --- a/include/boost/container/detail/variadic_templates_tools.hpp +++ b/include/boost/container/detail/variadic_templates_tools.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,8 +15,9 @@ # pragma once #endif -#include "config_begin.hpp" +#include #include + #include #include //std::size_t diff --git a/include/boost/container/detail/version_type.hpp b/include/boost/container/detail/version_type.hpp index e47ba26..66cafc9 100644 --- a/include/boost/container/detail/version_type.hpp +++ b/include/boost/container/detail/version_type.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,7 +16,8 @@ #ifndef BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP #define BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP -#include "config_begin.hpp" +#include +#include #include #include @@ -87,6 +88,6 @@ struct version } //namespace container { } //namespace boost{ -#include "config_end.hpp" +#include #endif //#define BOOST_CONTAINER_DETAIL_VERSION_TYPE_HPP diff --git a/include/boost/container/detail/workaround.hpp b/include/boost/container/detail/workaround.hpp index 49fe284..f919aa5 100644 --- a/include/boost/container/detail/workaround.hpp +++ b/include/boost/container/detail/workaround.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/include/boost/container/flat_map.hpp b/include/boost/container/flat_map.hpp index 8778de5..0f70e0f 100644 --- a/include/boost/container/flat_map.hpp +++ b/include/boost/container/flat_map.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -34,18 +34,7 @@ namespace boost { namespace container { -/// @cond -// Forward declarations of operators == and <, needed for friend declarations. -template -class flat_map; - -template -inline bool operator==(const flat_map& x, - const flat_map& y); - -template -inline bool operator<(const flat_map& x, - const flat_map& y); +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace container_detail{ @@ -62,8 +51,7 @@ static D force_copy(S s) } //namespace container_detail{ - -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! A flat_map is a kind of associative container that supports unique keys (contains at //! most one of each key value) and provides for fast retrieval of values of another @@ -88,6 +76,12 @@ static D force_copy(S s) //! pointing to elements that come after (their keys are bigger) the erased element. //! //! This container provides random-access iterators. +//! +//! \tparam Key is the key_type of the map +//! \tparam Value is the mapped_type +//! \tparam Compare is the ordering function for Keys (e.g. std::less). +//! \tparam Allocator is the allocator to allocate the value_types +//! (e.g. allocator< std::pair > ). #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template , class Allocator = std::allocator< std::pair< Key, T> > > #else @@ -95,7 +89,7 @@ template #endif class flat_map { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(flat_map) //This is the tree that we should store if pair was movable @@ -129,7 +123,7 @@ class flat_map ::pointer>::reverse_iterator reverse_iterator_impl; typedef typename container_detail::get_flat_tree_iterators ::pointer>::const_reverse_iterator const_reverse_iterator_impl; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: @@ -168,7 +162,11 @@ class flat_map //! //! Complexity: Constant. flat_map() - : m_flat_tree() {} + : m_flat_tree() + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_map using the specified //! comparison object and allocator. @@ -176,14 +174,20 @@ class flat_map //! Complexity: Constant. explicit flat_map(const Compare& comp, const allocator_type& a = allocator_type()) : m_flat_tree(comp, container_detail::force(a)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_map using the specified allocator. //! //! Complexity: Constant. explicit flat_map(const allocator_type& a) : m_flat_tree(container_detail::force(a)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_map using the specified comparison object and //! allocator, and inserts elements from the range [first ,last ). @@ -194,7 +198,10 @@ class flat_map flat_map(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(true, first, last, comp, container_detail::force(a)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_map using the specified comparison object and //! allocator, and inserts elements from the ordered unique range [first ,last). This function @@ -210,13 +217,20 @@ class flat_map flat_map( ordered_unique_range_t, InputIterator first, InputIterator last , const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(ordered_range, first, last, comp, a) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Copy constructs a flat_map. //! //! Complexity: Linear in x.size(). flat_map(const flat_map& x) - : m_flat_tree(x.m_flat_tree) {} + : m_flat_tree(x.m_flat_tree) + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Move constructs a flat_map. //! Constructs *this using x's resources. @@ -226,14 +240,20 @@ class flat_map //! Postcondition: x is emptied. flat_map(BOOST_RV_REF(flat_map) x) : m_flat_tree(boost::move(x.m_flat_tree)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Copy constructs a flat_map using the specified allocator. //! //! Complexity: Linear in x.size(). flat_map(const flat_map& x, const allocator_type &a) : m_flat_tree(x.m_flat_tree, a) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Move constructs a flat_map using the specified allocator. //! Constructs *this using x's resources. @@ -241,7 +261,10 @@ class flat_map //! Complexity: Constant if x.get_allocator() == a, linear otherwise. flat_map(BOOST_RV_REF(flat_map) x, const allocator_type &a) : m_flat_tree(boost::move(x.m_flat_tree), a) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Makes *this a copy of x. //! @@ -834,22 +857,57 @@ class flat_map //! //! Complexity: Logarithmic std::pair equal_range(const key_type& x) - { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } + { return container_detail::force_copy >(m_flat_tree.lower_bound_range(x)); } //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic std::pair equal_range(const key_type& x) const - { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } + { return container_detail::force_copy >(m_flat_tree.lower_bound_range(x)); } - /// @cond - template - friend bool operator== (const flat_map&, - const flat_map&); - template - friend bool operator< (const flat_map&, - const flat_map&); + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const flat_map& x, const flat_map& y) + { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const flat_map& x, const flat_map& y) + { return !(x == y); } + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const flat_map& x, const flat_map& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const flat_map& x, const flat_map& y) + { return y < x; } + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const flat_map& x, const flat_map& y) + { return !(y < x); } + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const flat_map& x, const flat_map& y) + { return !(x < y); } + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(flat_map& x, flat_map& y) + { x.swap(y); } + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: mapped_type &priv_subscript(const key_type& k) { @@ -872,45 +930,10 @@ class flat_map } return (*i).second; } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const flat_map& x, - const flat_map& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_map& x, - const flat_map& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_map& x, - const flat_map& y) - { return !(x == y); } - -template -inline bool operator>(const flat_map& x, - const flat_map& y) - { return y < x; } - -template -inline bool operator<=(const flat_map& x, - const flat_map& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_map& x, - const flat_map& y) - { return !(x < y); } - -template -inline void swap(flat_map& x, - flat_map& y) - { x.swap(y); } - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { @@ -924,18 +947,7 @@ struct has_trivial_destructor_after_move -class flat_multimap; - -template -inline bool operator==(const flat_multimap& x, - const flat_multimap& y); - -template -inline bool operator<(const flat_multimap& x, - const flat_multimap& y); -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! A flat_multimap is a kind of associative container that supports equivalent keys //! (possibly containing multiple copies of the same key value) and provides for @@ -960,6 +972,12 @@ inline bool operator<(const flat_multimap& x, //! pointing to elements that come after (their keys are bigger) the erased element. //! //! This container provides random-access iterators. +//! +//! \tparam Key is the key_type of the map +//! \tparam Value is the mapped_type +//! \tparam Compare is the ordering function for Keys (e.g. std::less). +//! \tparam Allocator is the allocator to allocate the value_types +//! (e.g. allocator< std::pair > ). #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template , class Allocator = std::allocator< std::pair< Key, T> > > #else @@ -967,7 +985,7 @@ template #endif class flat_multimap { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(flat_multimap) typedef container_detail::flat_tree::pointer>::reverse_iterator reverse_iterator_impl; typedef typename container_detail::get_flat_tree_iterators ::pointer>::const_reverse_iterator const_reverse_iterator_impl; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: @@ -1037,7 +1055,11 @@ class flat_multimap //! //! Complexity: Constant. flat_multimap() - : m_flat_tree() {} + : m_flat_tree() + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_multimap using the specified comparison //! object and allocator. @@ -1046,14 +1068,20 @@ class flat_multimap explicit flat_multimap(const Compare& comp, const allocator_type& a = allocator_type()) : m_flat_tree(comp, container_detail::force(a)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_multimap using the specified allocator. //! //! Complexity: Constant. explicit flat_multimap(const allocator_type& a) : m_flat_tree(container_detail::force(a)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_multimap using the specified comparison object //! and allocator, and inserts elements from the range [first ,last ). @@ -1065,7 +1093,10 @@ class flat_multimap const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(false, first, last, comp, container_detail::force(a)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Constructs an empty flat_multimap using the specified comparison object and //! allocator, and inserts elements from the ordered range [first ,last). This function @@ -1081,13 +1112,20 @@ class flat_multimap const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(ordered_range, first, last, comp, a) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Copy constructs a flat_multimap. //! //! Complexity: Linear in x.size(). flat_multimap(const flat_multimap& x) - : m_flat_tree(x.m_flat_tree) { } + : m_flat_tree(x.m_flat_tree) + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Move constructs a flat_multimap. Constructs *this using x's resources. //! @@ -1096,14 +1134,20 @@ class flat_multimap //! Postcondition: x is emptied. flat_multimap(BOOST_RV_REF(flat_multimap) x) : m_flat_tree(boost::move(x.m_flat_tree)) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Copy constructs a flat_multimap using the specified allocator. //! //! Complexity: Linear in x.size(). flat_multimap(const flat_multimap& x, const allocator_type &a) : m_flat_tree(x.m_flat_tree, a) - {} + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Move constructs a flat_multimap using the specified allocator. //! Constructs *this using x's resources. @@ -1111,7 +1155,10 @@ class flat_multimap //! Complexity: Constant if a == x.get_allocator(), linear otherwise. flat_multimap(BOOST_RV_REF(flat_multimap) x, const allocator_type &a) : m_flat_tree(boost::move(x.m_flat_tree), a) - { } + { + //Allocator type must be std::pair + BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); + } //! Effects: Makes *this a copy of x. //! @@ -1637,54 +1684,52 @@ class flat_multimap std::pair equal_range(const key_type& x) const { return container_detail::force_copy >(m_flat_tree.equal_range(x)); } - /// @cond - template - friend bool operator== (const flat_multimap& x, - const flat_multimap& y); + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const flat_multimap& x, const flat_multimap& y) + { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } - template - friend bool operator< (const flat_multimap& x, - const flat_multimap& y); - /// @endcond -}; + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const flat_multimap& x, const flat_multimap& y) + { return !(x == y); } -template -inline bool operator==(const flat_multimap& x, - const flat_multimap& y) - { return x.m_flat_tree == y.m_flat_tree; } + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const flat_multimap& x, const flat_multimap& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } -template -inline bool operator<(const flat_multimap& x, - const flat_multimap& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_multimap& x, - const flat_multimap& y) - { return !(x == y); } - -template -inline bool operator>(const flat_multimap& x, - const flat_multimap& y) + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const flat_multimap& x, const flat_multimap& y) { return y < x; } -template -inline bool operator<=(const flat_multimap& x, - const flat_multimap& y) + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const flat_multimap& x, const flat_multimap& y) { return !(y < x); } -template -inline bool operator>=(const flat_multimap& x, - const flat_multimap& y) + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const flat_multimap& x, const flat_multimap& y) { return !(x < y); } -template -inline void swap(flat_multimap& x, flat_multimap& y) + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(flat_multimap& x, flat_multimap& y) { x.swap(y); } +}; }} -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { @@ -1698,7 +1743,7 @@ struct has_trivial_destructor_after_move< boost::container::flat_multimap diff --git a/include/boost/container/flat_set.hpp b/include/boost/container/flat_set.hpp index eda8fbd..0a1ece6 100644 --- a/include/boost/container/flat_set.hpp +++ b/include/boost/container/flat_set.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -31,25 +31,6 @@ namespace boost { namespace container { -/// @cond -// Forward declarations of operators < and ==, needed for friend declaration. - -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > -#else -template -#endif -class flat_set; - -template -inline bool operator==(const flat_set& x, - const flat_set& y); - -template -inline bool operator<(const flat_set& x, - const flat_set& y); -/// @endcond - //! flat_set is a Sorted Associative Container that stores objects of type Key. //! It is also a Unique Associative Container, meaning that no two elements are the same. //! @@ -61,19 +42,25 @@ inline bool operator<(const flat_set& x, //! pointing to elements that come after (their keys are bigger) the erased element. //! //! This container provides random-access iterators. +//! +//! \tparam Key is the type to be inserted in the set, which is also the key_type +//! \tparam Compare is the comparison functor used to order keys +//! \tparam Allocator is the allocator to be used to allocate memory for this container #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template , class Allocator = std::allocator > #else template #endif class flat_set + ///@cond + : public container_detail::flat_tree, Compare, Allocator> + ///@endcond { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(flat_set) - typedef container_detail::flat_tree, Compare, Allocator> tree_t; - tree_t m_flat_tree; // flat tree representing flat_set - /// @endcond + typedef container_detail::flat_tree, Compare, Allocator> base_t; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -92,11 +79,11 @@ class flat_set typedef typename ::boost::container::allocator_traits::size_type size_type; typedef typename ::boost::container::allocator_traits::difference_type difference_type; typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::stored_allocator_type) stored_allocator_type; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::iterator) iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_iterator) const_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::reverse_iterator) reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_reverse_iterator) const_reverse_iterator; public: ////////////////////////////////////////////// @@ -105,30 +92,30 @@ class flat_set // ////////////////////////////////////////////// - //! Effects: Default constructs an empty flat_set. + //! Effects: Default constructs an empty container. //! //! Complexity: Constant. explicit flat_set() - : m_flat_tree() + : base_t() {} - //! Effects: Constructs an empty flat_set using the specified + //! Effects: Constructs an empty container using the specified //! comparison object and allocator. //! //! Complexity: Constant. explicit flat_set(const Compare& comp, const allocator_type& a = allocator_type()) - : m_flat_tree(comp, a) + : base_t(comp, a) {} - //! Effects: Constructs an empty flat_set using the specified allocator. + //! Effects: Constructs an empty container using the specified allocator. //! //! Complexity: Constant. explicit flat_set(const allocator_type& a) - : m_flat_tree(a) + : base_t(a) {} - //! Effects: Constructs an empty set using the specified comparison object and + //! Effects: Constructs an empty container using the specified comparison object and //! allocator, and inserts elements from the range [first ,last ). //! //! Complexity: Linear in N if the range [first ,last ) is already sorted using @@ -137,10 +124,10 @@ class flat_set flat_set(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_flat_tree(true, first, last, comp, a) + : base_t(true, first, last, comp, a) {} - //! Effects: Constructs an empty flat_set using the specified comparison object and + //! Effects: Constructs an empty container using the specified comparison object and //! allocator, and inserts elements from the ordered unique range [first ,last). This function //! is more efficient than the normal range creation for ordered ranges. //! @@ -154,58 +141,58 @@ class flat_set flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_flat_tree(ordered_range, first, last, comp, a) + : base_t(ordered_range, first, last, comp, a) {} - //! Effects: Copy constructs a set. + //! Effects: Copy constructs the container. //! //! Complexity: Linear in x.size(). flat_set(const flat_set& x) - : m_flat_tree(x.m_flat_tree) + : base_t(static_cast(x)) {} - //! Effects: Move constructs a set. Constructs *this using x's resources. + //! Effects: Move constructs thecontainer. Constructs *this using mx's resources. //! //! Complexity: Constant. //! - //! Postcondition: x is emptied. + //! Postcondition: mx is emptied. flat_set(BOOST_RV_REF(flat_set) mx) - : m_flat_tree(boost::move(mx.m_flat_tree)) + : base_t(boost::move(static_cast(mx))) {} - //! Effects: Copy constructs a set using the specified allocator. + //! Effects: Copy constructs a container using the specified allocator. //! //! Complexity: Linear in x.size(). flat_set(const flat_set& x, const allocator_type &a) - : m_flat_tree(x.m_flat_tree, a) + : base_t(static_cast(x), a) {} - //! Effects: Move constructs a set using the specified allocator. - //! Constructs *this using x's resources. + //! Effects: Move constructs a container using the specified allocator. + //! Constructs *this using mx's resources. //! //! Complexity: Constant if a == mx.get_allocator(), linear otherwise flat_set(BOOST_RV_REF(flat_set) mx, const allocator_type &a) - : m_flat_tree(boost::move(mx.m_flat_tree), a) + : base_t(boost::move(static_cast(mx)), a) {} //! Effects: Makes *this a copy of x. //! //! Complexity: Linear in x.size(). flat_set& operator=(BOOST_COPY_ASSIGN_REF(flat_set) x) - { m_flat_tree = x.m_flat_tree; return *this; } + { return static_cast(this->base_t::operator=(static_cast(x))); } - //! Effects: Makes *this a copy of the previous value of xx. + //! Effects: Makes *this a copy of the previous value of mx. //! //! Complexity: Linear in x.size(). flat_set& operator=(BOOST_RV_REF(flat_set) mx) - { m_flat_tree = boost::move(mx.m_flat_tree); return *this; } + { return static_cast(this->base_t::operator=(boost::move(static_cast(mx)))); } + #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED //! Effects: Returns a copy of the Allocator that //! was passed to the object's constructor. //! //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_allocator(); } + allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reference to the internal allocator. //! @@ -214,8 +201,7 @@ class flat_set //! Complexity: Constant. //! //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } + stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reference to the internal allocator. //! @@ -224,46 +210,35 @@ class flat_set //! Complexity: Constant. //! //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// + const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns an iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.begin(); } + iterator begin() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.begin(); } + const_iterator begin() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns an iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } + iterator end() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } + const_iterator end() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reverse_iterator pointing to the beginning //! of the reversed container. @@ -271,8 +246,7 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } + reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. @@ -280,8 +254,7 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } + const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reverse_iterator pointing to the end //! of the reversed container. @@ -289,8 +262,7 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } + reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed container. @@ -298,24 +270,21 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } + const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cbegin(); } + const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cend(); } + const_iterator cend() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. @@ -323,8 +292,7 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crbegin(); } + const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed container. @@ -332,39 +300,28 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crend(); } - - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns true if the container contains no elements. //! //! Throws: Nothing. //! //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.empty(); } + bool empty() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns the number of the elements contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.size(); } + size_type size() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns the largest possible size of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.max_size(); } + size_type max_size() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Number of elements for which memory has been allocated. //! capacity() is always greater than or equal to size(). @@ -372,8 +329,7 @@ class flat_set //! Throws: Nothing. //! //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.capacity(); } + size_type capacity() const BOOST_CONTAINER_NOEXCEPT; //! Effects: If n is less than or equal to capacity(), this call has no //! effect. Otherwise, it is a request for allocation of additional memory. @@ -384,8 +340,7 @@ class flat_set //! //! Note: If capacity() is less than "cnt", iterators and references to //! to values might be invalidated. - void reserve(size_type cnt) - { m_flat_tree.reserve(cnt); } + void reserve(size_type cnt); //! Effects: Tries to deallocate the excess of memory created // with previous allocations. The size of the vector is unchanged @@ -393,8 +348,9 @@ class flat_set //! Throws: If memory allocation throws, or Key's copy constructor throws. //! //! Complexity: Linear to size(). - void shrink_to_fit() - { m_flat_tree.shrink_to_fit(); } + void shrink_to_fit(); + + #endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) ////////////////////////////////////////////// // @@ -418,7 +374,7 @@ class flat_set //! Note: If an element is inserted it might invalidate elements. template std::pair emplace(Args&&... args) - { return m_flat_tree.emplace_unique(boost::forward(args)...); } + { return this->base_t::emplace_unique(boost::forward(args)...); } //! Effects: Inserts an object of type Key constructed with //! std::forward(args)... in the container if and only if there is @@ -434,19 +390,19 @@ class flat_set //! Note: If an element is inserted it might invalidate elements. template iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_flat_tree.emplace_hint_unique(hint, boost::forward(args)...); } + { return this->base_t::emplace_hint_unique(hint, boost::forward(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ + { return this->base_t::emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); }\ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_hint_unique \ + { return this->base_t::emplace_hint_unique \ (hint BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -526,7 +482,7 @@ class flat_set //! Note: If an element is inserted it might invalidate elements. template void insert(InputIterator first, InputIterator last) - { m_flat_tree.insert_unique(first, last); } + { this->base_t::insert_unique(first, last); } //! Requires: first, last are not iterators into *this and //! must be ordered according to the predicate and must be @@ -541,7 +497,9 @@ class flat_set //! Note: Non-standard extension. If an element is inserted it might invalidate elements. template void insert(ordered_unique_range_t, InputIterator first, InputIterator last) - { m_flat_tree.insert_unique(ordered_unique_range, first, last); } + { this->base_t::insert_unique(ordered_unique_range, first, last); } + + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Erases the element pointed to by position. //! @@ -553,8 +511,7 @@ class flat_set //! //! Note: Invalidates elements with keys //! not less than the erased element. - iterator erase(const_iterator position) - { return m_flat_tree.erase(position); } + iterator erase(const_iterator position); //! Effects: Erases all elements in the container with key equivalent to x. //! @@ -562,8 +519,7 @@ class flat_set //! //! Complexity: Logarithmic search time plus erasure time //! linear to the elements with bigger keys. - size_type erase(const key_type& x) - { return m_flat_tree.erase(x); } + size_type erase(const key_type& x); //! Effects: Erases all the elements in the range [first, last). //! @@ -573,164 +529,145 @@ class flat_set //! //! Complexity: Logarithmic search time plus erasure time //! linear to the elements with bigger keys. - iterator erase(const_iterator first, const_iterator last) - { return m_flat_tree.erase(first, last); } + iterator erase(const_iterator first, const_iterator last); //! Effects: Swaps the contents of *this and x. //! //! Throws: Nothing. //! //! Complexity: Constant. - void swap(flat_set& x) - { m_flat_tree.swap(x.m_flat_tree); } + void swap(flat_set& x); //! Effects: erase(a.begin(),a.end()). //! //! Postcondition: size() == 0. //! //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_flat_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// + void clear() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns the comparison object out //! of which a was constructed. //! //! Complexity: Constant. - key_compare key_comp() const - { return m_flat_tree.key_comp(); } + key_compare key_comp() const; //! Effects: Returns an object of value_compare constructed out //! of the comparison object. //! //! Complexity: Constant. - value_compare value_comp() const - { return m_flat_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// + value_compare value_comp() const; //! Returns: An iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_flat_tree.find(x); } + iterator find(const key_type& x); //! Returns: Allocator const_iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! - //! Complexity: Logarithmic.s - const_iterator find(const key_type& x) const - { return m_flat_tree.find(x); } + //! Complexity: Logarithmic. + const_iterator find(const key_type& x) const; + + #endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Returns: The number of elements with key equivalent to x. //! //! Complexity: log(size())+count(k) size_type count(const key_type& x) const - { return static_cast(m_flat_tree.find(x) != m_flat_tree.end()); } + { return static_cast(this->base_t::find(x) != this->base_t::cend()); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Returns: An iterator pointing to the first element with key not less //! than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_flat_tree.lower_bound(x); } + iterator lower_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_flat_tree.lower_bound(x); } + const_iterator lower_bound(const key_type& x) const; //! Returns: An iterator pointing to the first element with key not less //! than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_flat_tree.upper_bound(x); } + iterator upper_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_flat_tree.upper_bound(x); } + const_iterator upper_bound(const key_type& x) const; + + #endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic std::pair equal_range(const key_type& x) const - { return m_flat_tree.equal_range(x); } + { return this->base_t::lower_bound_range(x); } //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic std::pair equal_range(const key_type& x) - { return m_flat_tree.equal_range(x); } + { return this->base_t::lower_bound_range(x); } - /// @cond - template - friend bool operator== (const flat_set&, const flat_set&); + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - friend bool operator< (const flat_set&, const flat_set&); + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const flat_set& x, const flat_set& y); + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const flat_set& x, const flat_set& y); + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const flat_set& x, const flat_set& y); + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const flat_set& x, const flat_set& y); + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const flat_set& x, const flat_set& y); + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const flat_set& x, const flat_set& y); + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(flat_set& x, flat_set& y); + + #endif //#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: template std::pair priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_unique(::boost::forward(x)); } + { return this->base_t::insert_unique(::boost::forward(x)); } template iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_unique(p, ::boost::forward(x)); } - /// @endcond + { return this->base_t::insert_unique(p, ::boost::forward(x)); } + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const flat_set& x, - const flat_set& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_set& x, - const flat_set& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_set& x, - const flat_set& y) - { return !(x == y); } - -template -inline bool operator>(const flat_set& x, - const flat_set& y) - { return y < x; } - -template -inline bool operator<=(const flat_set& x, - const flat_set& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_set& x, - const flat_set& y) - { return !(x < y); } - -template -inline void swap(flat_set& x, flat_set& y) - { x.swap(y); } - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { @@ -744,23 +681,7 @@ struct has_trivial_destructor_after_move, class Allocator = std::allocator > -#else -template -#endif -class flat_multiset; - -template -inline bool operator==(const flat_multiset& x, - const flat_multiset& y); - -template -inline bool operator<(const flat_multiset& x, - const flat_multiset& y); -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! flat_multiset is a Sorted Associative Container that stores objects of type Key. //! @@ -774,19 +695,25 @@ inline bool operator<(const flat_multiset& x, //! pointing to elements that come after (their keys are bigger) the erased element. //! //! This container provides random-access iterators. +//! +//! \tparam Key is the type to be inserted in the multiset, which is also the key_type +//! \tparam Compare is the comparison functor used to order keys +//! \tparam Allocator is the allocator to be used to allocate memory for this container #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template , class Allocator = std::allocator > #else template #endif class flat_multiset + ///@cond + : public container_detail::flat_tree, Compare, Allocator> + ///@endcond { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(flat_multiset) - typedef container_detail::flat_tree, Compare, Allocator> tree_t; - tree_t m_flat_tree; // flat tree representing flat_multiset - /// @endcond + typedef container_detail::flat_tree, Compare, Allocator> base_t; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -805,40 +732,34 @@ class flat_multiset typedef typename ::boost::container::allocator_traits::size_type size_type; typedef typename ::boost::container::allocator_traits::difference_type difference_type; typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::stored_allocator_type) stored_allocator_type; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::iterator) iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_iterator) const_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::reverse_iterator) reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_reverse_iterator) const_reverse_iterator; - //! Effects: Default constructs an empty flat_multiset. - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::flat_set::flat_set() explicit flat_multiset() - : m_flat_tree() + : base_t() {} - //! Effects: Constructs an empty flat_multiset using the specified - //! comparison object and allocator. - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::flat_set::flat_set(const Compare&, const allocator_type&) explicit flat_multiset(const Compare& comp, const allocator_type& a = allocator_type()) - : m_flat_tree(comp, a) + : base_t(comp, a) {} - //! Effects: Constructs an empty flat_multiset using the specified allocator. - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::flat_set::flat_set(const allocator_type&) explicit flat_multiset(const allocator_type& a) - : m_flat_tree(a) + : base_t(a) {} + //! @copydoc ::boost::container::flat_set::flat_set(InputIterator, InputIterator, const Compare& comp, const allocator_type&) template flat_multiset(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_flat_tree(false, first, last, comp, a) + : base_t(false, first, last, comp, a) {} //! Effects: Constructs an empty flat_multiset using the specified comparison object and @@ -854,240 +775,103 @@ class flat_multiset flat_multiset(ordered_range_t, InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_flat_tree(ordered_range, first, last, comp, a) + : base_t(ordered_range, first, last, comp, a) {} - //! Effects: Copy constructs a flat_multiset. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::flat_set::flat_set(const flat_set &) flat_multiset(const flat_multiset& x) - : m_flat_tree(x.m_flat_tree) + : base_t(static_cast(x)) {} - //! Effects: Move constructs a flat_multiset. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. + //! @copydoc ::boost::container::flat_set(flat_set &&) flat_multiset(BOOST_RV_REF(flat_multiset) mx) - : m_flat_tree(boost::move(mx.m_flat_tree)) + : base_t(boost::move(static_cast(mx))) {} - //! Effects: Copy constructs a flat_multiset using the specified allocator. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::flat_set(const flat_set &, const allocator_type &) flat_multiset(const flat_multiset& x, const allocator_type &a) - : m_flat_tree(x.m_flat_tree, a) + : base_t(static_cast(x), a) {} - //! Effects: Move constructs a flat_multiset using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == mx.get_allocator(), linear otherwise + //! @copydoc ::boost::container::flat_set(flat_set &&, const allocator_type &) flat_multiset(BOOST_RV_REF(flat_multiset) mx, const allocator_type &a) - : m_flat_tree(boost::move(mx.m_flat_tree), a) + : base_t(boost::move(static_cast(mx)), a) {} - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::flat_set::operator=(const flat_set &) flat_multiset& operator=(BOOST_COPY_ASSIGN_REF(flat_multiset) x) - { m_flat_tree = x.m_flat_tree; return *this; } + { return static_cast(this->base_t::operator=(static_cast(x))); } - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::flat_set::operator=(flat_set &&) flat_multiset& operator=(BOOST_RV_REF(flat_multiset) mx) - { m_flat_tree = boost::move(mx.m_flat_tree); return *this; } + { return static_cast(this->base_t::operator=(boost::move(static_cast(mx)))); } - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_allocator(); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } + //! @copydoc ::boost::container::flat_set::get_allocator() + allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.get_stored_allocator(); } + //! @copydoc ::boost::container::flat_set::get_stored_allocator() + stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.begin(); } + //! @copydoc ::boost::container::flat_set::get_stored_allocator() const + const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const - { return m_flat_tree.begin(); } + //! @copydoc ::boost::container::flat_set::begin() + iterator begin() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cbegin(); } + //! @copydoc ::boost::container::flat_set::begin() const + const_iterator begin() const; - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } + //! @copydoc ::boost::container::flat_set::cbegin() const + const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.end(); } + //! @copydoc ::boost::container::flat_set::end() + iterator end() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.cend(); } + //! @copydoc ::boost::container::flat_set::end() const + const_iterator end() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } + //! @copydoc ::boost::container::flat_set::cend() const + const_iterator cend() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rbegin(); } + //! @copydoc ::boost::container::flat_set::rbegin() + reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crbegin(); } + //! @copydoc ::boost::container::flat_set::rbegin() const + const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } + //! @copydoc ::boost::container::flat_set::crbegin() const + const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.rend(); } + //! @copydoc ::boost::container::flat_set::rend() + reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.crend(); } + //! @copydoc ::boost::container::flat_set::rend() const + const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT; - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::flat_set::crend() const + const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.empty(); } + //! @copydoc ::boost::container::flat_set::empty() const + bool empty() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.size(); } + //! @copydoc ::boost::container::flat_set::size() const + size_type size() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.max_size(); } + //! @copydoc ::boost::container::flat_set::max_size() const + size_type max_size() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Number of elements for which memory has been allocated. - //! capacity() is always greater than or equal to size(). - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type capacity() const BOOST_CONTAINER_NOEXCEPT - { return m_flat_tree.capacity(); } + //! @copydoc ::boost::container::flat_set::capacity() const + size_type capacity() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: If n is less than or equal to capacity(), this call has no - //! effect. Otherwise, it is a request for allocation of additional memory. - //! If the request is successful, then capacity() is greater than or equal to - //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. - //! - //! Throws: If memory allocation allocation throws or Key's copy constructor throws. - //! - //! Note: If capacity() is less than "cnt", iterators and references to - //! to values might be invalidated. - void reserve(size_type cnt) - { m_flat_tree.reserve(cnt); } + //! @copydoc ::boost::container::flat_set::reserve(size_type) + void reserve(size_type cnt); - //! Effects: Tries to deallocate the excess of memory created - // with previous allocations. The size of the vector is unchanged - //! - //! Throws: If memory allocation throws, or Key's copy constructor throws. - //! - //! Complexity: Linear to size(). - void shrink_to_fit() - { m_flat_tree.shrink_to_fit(); } + //! @copydoc ::boost::container::flat_set::shrink_to_fit() + void shrink_to_fit(); + + #endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) ////////////////////////////////////////////// // @@ -1107,7 +891,7 @@ class flat_multiset //! Note: If an element is inserted it might invalidate elements. template iterator emplace(Args&&... args) - { return m_flat_tree.emplace_equal(boost::forward(args)...); } + { return this->base_t::emplace_equal(boost::forward(args)...); } //! Effects: Inserts an object of type Key constructed with //! std::forward(args)... in the container. @@ -1122,19 +906,19 @@ class flat_multiset //! Note: If an element is inserted it might invalidate elements. template iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_flat_tree.emplace_hint_equal(hint, boost::forward(args)...); } + { return this->base_t::emplace_hint_equal(hint, boost::forward(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ + { return this->base_t::emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_flat_tree.emplace_hint_equal \ + { return this->base_t::emplace_hint_equal \ (hint BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -1202,7 +986,7 @@ class flat_multiset //! Note: If an element is inserted it might invalidate elements. template void insert(InputIterator first, InputIterator last) - { m_flat_tree.insert_equal(first, last); } + { this->base_t::insert_equal(first, last); } //! Requires: first, last are not iterators into *this and //! must be ordered according to the predicate. @@ -1216,196 +1000,108 @@ class flat_multiset //! Note: Non-standard extension. If an element is inserted it might invalidate elements. template void insert(ordered_range_t, InputIterator first, InputIterator last) - { m_flat_tree.insert_equal(ordered_range, first, last); } + { this->base_t::insert_equal(ordered_range, first, last); } - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Linear to the elements with keys bigger than position - //! - //! Note: Invalidates elements with keys - //! not less than the erased element. - iterator erase(const_iterator position) - { return m_flat_tree.erase(position); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - size_type erase(const key_type& x) - { return m_flat_tree.erase(x); } + //! @copydoc ::boost::container::flat_set::erase(const_iterator) + iterator erase(const_iterator position); - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: size()*N where N is the distance from first to last. - //! - //! Complexity: Logarithmic search time plus erasure time - //! linear to the elements with bigger keys. - iterator erase(const_iterator first, const_iterator last) - { return m_flat_tree.erase(first, last); } + //! @copydoc ::boost::container::flat_set::erase(const key_type&) + size_type erase(const key_type& x); - //! Effects: Swaps the contents of *this and x. + //! @copydoc ::boost::container::flat_set::erase(const_iterator,const_iterator) + iterator erase(const_iterator first, const_iterator last); + + //! @copydoc ::boost::container::flat_set::swap + void swap(flat_multiset& x); + + //! @copydoc ::boost::container::flat_set::clear + void clear() BOOST_CONTAINER_NOEXCEPT; + + //! @copydoc ::boost::container::flat_set::key_comp + key_compare key_comp() const; + + //! @copydoc ::boost::container::flat_set::value_comp + value_compare value_comp() const; + + //! @copydoc ::boost::container::flat_set::find(const key_type& ) + iterator find(const key_type& x); + + //! @copydoc ::boost::container::flat_set::find(const key_type& ) const + const_iterator find(const key_type& x) const; + + //! @copydoc ::boost::container::flat_set::count(const key_type& ) const + size_type count(const key_type& x) const; + + //! @copydoc ::boost::container::flat_set::lower_bound(const key_type& ) + iterator lower_bound(const key_type& x); + + //! @copydoc ::boost::container::flat_set::lower_bound(const key_type& ) const + const_iterator lower_bound(const key_type& x) const; + + //! @copydoc ::boost::container::flat_set::upper_bound(const key_type& ) + iterator upper_bound(const key_type& x); + + //! @copydoc ::boost::container::flat_set::upper_bound(const key_type& ) const + const_iterator upper_bound(const key_type& x) const; + + //! @copydoc ::boost::container::flat_set::equal_range(const key_type& ) const + std::pair equal_range(const key_type& x) const; + + //! @copydoc ::boost::container::flat_set::equal_range(const key_type& ) + std::pair equal_range(const key_type& x); + + //! Effects: Returns true if x and y are equal //! - //! Throws: Nothing. + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const flat_multiset& x, const flat_multiset& y); + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const flat_multiset& x, const flat_multiset& y); + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const flat_multiset& x, const flat_multiset& y); + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const flat_multiset& x, const flat_multiset& y); + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const flat_multiset& x, const flat_multiset& y); + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const flat_multiset& x, const flat_multiset& y); + + //! Effects: x.swap(y) //! //! Complexity: Constant. - void swap(flat_multiset& x) - { m_flat_tree.swap(x.m_flat_tree); } + friend void swap(flat_multiset& x, flat_multiset& y); - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_flat_tree.clear(); } + #endif //#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_flat_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return m_flat_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_flat_tree.find(x); } - - //! Returns: Allocator const_iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic.s - const_iterator find(const key_type& x) const - { return m_flat_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_flat_tree.count(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_flat_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_flat_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_flat_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_flat_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_flat_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_flat_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const flat_multiset&, - const flat_multiset&); - template - friend bool operator< (const flat_multiset&, - const flat_multiset&); + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: template iterator priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_equal(::boost::forward(x)); } + { return this->base_t::insert_equal(::boost::forward(x)); } template iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_flat_tree.insert_equal(p, ::boost::forward(x)); } - /// @endcond + { return this->base_t::insert_equal(p, ::boost::forward(x)); } + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const flat_multiset& x, - const flat_multiset& y) - { return x.m_flat_tree == y.m_flat_tree; } - -template -inline bool operator<(const flat_multiset& x, - const flat_multiset& y) - { return x.m_flat_tree < y.m_flat_tree; } - -template -inline bool operator!=(const flat_multiset& x, - const flat_multiset& y) - { return !(x == y); } - -template -inline bool operator>(const flat_multiset& x, - const flat_multiset& y) - { return y < x; } - -template -inline bool operator<=(const flat_multiset& x, - const flat_multiset& y) - { return !(y < x); } - -template -inline bool operator>=(const flat_multiset& x, - const flat_multiset& y) -{ return !(x < y); } - -template -inline void swap(flat_multiset& x, flat_multiset& y) - { x.swap(y); } - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { @@ -1419,7 +1115,7 @@ struct has_trivial_destructor_after_move @@ -99,7 +99,7 @@ struct intrusive_list_type }; } //namespace container_detail { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! A list is a doubly linked list. That is, it is a Sequence that supports both //! forward and backward traversal, and (amortized) constant time insertion and @@ -111,6 +111,9 @@ struct intrusive_list_type //! after a list operation than it did before), but the iterators themselves will //! not be invalidated or made to point to different elements unless that invalidation //! or mutation is explicit. +//! +//! \tparam T The type of object that is stored in the list +//! \tparam Allocator The allocator used for all internal memory management #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template > #else @@ -120,7 +123,7 @@ class list : protected container_detail::node_alloc_holder ::type> { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED typedef typename container_detail::intrusive_list_type::type Icont; typedef container_detail::node_alloc_holder AllocHolder; @@ -167,7 +170,7 @@ class list typedef container_detail::iterator iterator_impl; typedef container_detail::iterator const_iterator_impl; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -1214,9 +1217,65 @@ class list //! //! Note: Iterators and references are not invalidated void reverse() BOOST_CONTAINER_NOEXCEPT - { this->icont().reverse(); } + { this->icont().reverse(); } - /// @cond + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const list& x, const list& y) + { + if(x.size() != y.size()){ + return false; + } + typedef typename list::const_iterator const_iterator; + const_iterator end1 = x.end(); + + const_iterator i1 = x.begin(); + const_iterator i2 = y.begin(); + while (i1 != end1 && *i1 == *i2) { + ++i1; + ++i2; + } + return i1 == end1; + } + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const list& x, const list& y) + { return !(x == y); } + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const list& x, const list& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const list& x, const list& y) + { return y < x; } + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const list& x, const list& y) + { return !(y < x); } + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const list& x, const list& y) + { return !(x < y); } + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(list& x, list& y) + { x.swap(y); } + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: bool priv_try_shrink(size_type new_size) @@ -1303,66 +1362,11 @@ class list bool operator()(const value_type &a, const value_type &b) const { return a == b; } }; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const list& x, const list& y) -{ - if(x.size() != y.size()){ - return false; - } - typedef typename list::const_iterator const_iterator; - const_iterator end1 = x.end(); - - const_iterator i1 = x.begin(); - const_iterator i2 = y.begin(); - while (i1 != end1 && *i1 == *i2) { - ++i1; - ++i2; - } - return i1 == end1; -} - -template -inline bool operator<(const list& x, - const list& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); -} - -template -inline bool operator!=(const list& x, const list& y) -{ - return !(x == y); -} - -template -inline bool operator>(const list& x, const list& y) -{ - return y < x; -} - -template -inline bool operator<=(const list& x, const list& y) -{ - return !(y < x); -} - -template -inline bool operator>=(const list& x, const list& y) -{ - return !(x < y); -} - -template -inline void swap(list& x, list& y) -{ - x.swap(y); -} - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { @@ -1375,7 +1379,7 @@ struct has_trivial_destructor_after_move > namespace container { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }} diff --git a/include/boost/container/map.hpp b/include/boost/container/map.hpp index f4776e8..49a6cec 100644 --- a/include/boost/container/map.hpp +++ b/include/boost/container/map.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -39,49 +39,47 @@ namespace boost { namespace container { -/// @cond -// Forward declarations of operators == and <, needed for friend declarations. -template -inline bool operator==(const map& x, - const map& y); - -template -inline bool operator<(const map& x, - const map& y); -/// @endcond +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED //! A map is a kind of associative container that supports unique keys (contains at //! most one of each key value) and provides for fast retrieval of values of another //! type T based on the keys. The map class supports bidirectional iterators. //! //! A map satisfies all of the requirements of a container and of a reversible -//! container and of an associative container. For a -//! map the key_type is Key and the value_type is std::pair. +//! container and of an associative container. The value_type stored +//! by this container is the value_type is std::pair. //! -//! Compare is the ordering function for Keys (e.g. std::less). -//! -//! Allocator is the allocator to allocate the value_types -//! (e.g. allocator< std::pair > ). -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator< std::pair< const Key, T> > > +//! \tparam Key is the key_type of the map +//! \tparam Value is the mapped_type +//! \tparam Compare is the ordering function for Keys (e.g. std::less). +//! \tparam Allocator is the allocator to allocate the value_types +//! (e.g. allocator< std::pair > ). +//! \tparam MapOptions is an packed option type generated using using boost::container::tree_assoc_options. +template < class Key, class T, class Compare = std::less + , class Allocator = std::allocator< std::pair< const Key, T> >, class MapOptions = tree_assoc_defaults > #else -template +template #endif class map + ///@cond + : public container_detail::tree + < Key, std::pair + , container_detail::select1st< std::pair > + , Compare, Allocator, MapOptions> + ///@endcond { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(map) typedef std::pair value_type_impl; - typedef container_detail::rbtree - , Compare, Allocator> tree_t; + typedef container_detail::tree + , Compare, Allocator, MapOptions> base_t; typedef container_detail::pair movable_value_type_impl; typedef container_detail::tree_value_compare < Key, value_type_impl, Compare, container_detail::select1st > value_compare_impl; - tree_t m_tree; // red-black tree representing map - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -100,13 +98,13 @@ class map typedef typename boost::container::allocator_traits::size_type size_type; typedef typename boost::container::allocator_traits::difference_type difference_type; typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::stored_allocator_type) stored_allocator_type; typedef BOOST_CONTAINER_IMPDEF(value_compare_impl) value_compare; typedef Compare key_compare; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::iterator) iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_iterator) const_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::reverse_iterator) reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_reverse_iterator) const_reverse_iterator; typedef std::pair nonconst_value_type; typedef BOOST_CONTAINER_IMPDEF(movable_value_type_impl) movable_value_type; @@ -120,7 +118,7 @@ class map //! //! Complexity: Constant. map() - : m_tree() + : base_t() { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -132,7 +130,7 @@ class map //! Complexity: Constant. explicit map(const Compare& comp, const allocator_type& a = allocator_type()) - : m_tree(comp, a) + : base_t(comp, a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -142,7 +140,7 @@ class map //! //! Complexity: Constant. explicit map(const allocator_type& a) - : m_tree(a) + : base_t(a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -156,7 +154,7 @@ class map template map(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(true, first, last, comp, a) + : base_t(true, first, last, comp, a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -175,7 +173,7 @@ class map template map( ordered_unique_range_t, InputIterator first, InputIterator last , const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) + : base_t(ordered_range, first, last, comp, a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -185,7 +183,7 @@ class map //! //! Complexity: Linear in x.size(). map(const map& x) - : m_tree(x.m_tree) + : base_t(static_cast(x)) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -197,7 +195,7 @@ class map //! //! Postcondition: x is emptied. map(BOOST_RV_REF(map) x) - : m_tree(boost::move(x.m_tree)) + : base_t(boost::move(static_cast(x))) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -207,7 +205,7 @@ class map //! //! Complexity: Linear in x.size(). map(const map& x, const allocator_type &a) - : m_tree(x.m_tree, a) + : base_t(static_cast(x), a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -220,7 +218,7 @@ class map //! //! Postcondition: x is emptied. map(BOOST_RV_REF(map) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) + : base_t(boost::move(static_cast(x)), a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -230,20 +228,21 @@ class map //! //! Complexity: Linear in x.size(). map& operator=(BOOST_COPY_ASSIGN_REF(map) x) - { m_tree = x.m_tree; return *this; } + { return static_cast(this->base_t::operator=(static_cast(x))); } //! Effects: this->swap(x.get()). //! //! Complexity: Constant. map& operator=(BOOST_RV_REF(map) x) - { m_tree = boost::move(x.m_tree); return *this; } + { return static_cast(this->base_t::operator=(boost::move(static_cast(x)))); } + + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Returns a copy of the Allocator that //! was passed to the object's constructor. //! //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_allocator(); } + allocator_type get_allocator() const; //! Effects: Returns a reference to the internal allocator. //! @@ -252,8 +251,7 @@ class map //! Complexity: Constant. //! //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } + stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reference to the internal allocator. //! @@ -262,46 +260,49 @@ class map //! Complexity: Constant. //! //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// + const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns an iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } + iterator begin() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbegin(); } + const_iterator begin() const BOOST_CONTAINER_NOEXCEPT; + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns an iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } + iterator end() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } + const_iterator end() const BOOST_CONTAINER_NOEXCEPT; + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reverse_iterator pointing to the beginning //! of the reversed container. @@ -309,8 +310,7 @@ class map //! Throws: Nothing. //! //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } + reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. @@ -318,8 +318,15 @@ class map //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } + const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT; + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a reverse_iterator pointing to the end //! of the reversed container. @@ -327,8 +334,7 @@ class map //! Throws: Nothing. //! //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } + reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed container. @@ -336,33 +342,7 @@ class map //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } + const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed container. @@ -370,44 +350,30 @@ class map //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns true if the container contains no elements. //! //! Throws: Nothing. //! //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.empty(); } + bool empty() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns the number of the elements contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.size(); } + size_type size() const BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns the largest possible size of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.max_size(); } + size_type max_size() const BOOST_CONTAINER_NOEXCEPT; - ////////////////////////////////////////////// - // - // element access - // - ////////////////////////////////////////////// + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: If there is no key equivalent to x in the map, inserts @@ -468,7 +434,7 @@ class map //! //! Complexity: Logarithmic. std::pair insert(const value_type& x) - { return m_tree.insert_unique(x); } + { return this->base_t::insert_unique(x); } //! Effects: Inserts a new value_type created from the pair if and only if //! there is no element in the container with key equivalent to the key of x. @@ -479,7 +445,7 @@ class map //! //! Complexity: Logarithmic. std::pair insert(const nonconst_value_type& x) - { return m_tree.insert_unique(x); } + { return this->base_t::insert_unique(x); } //! Effects: Inserts a new value_type move constructed from the pair if and //! only if there is no element in the container with key equivalent to the key of x. @@ -490,7 +456,7 @@ class map //! //! Complexity: Logarithmic. std::pair insert(BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_unique(boost::move(x)); } + { return this->base_t::insert_unique(boost::move(x)); } //! Effects: Inserts a new value_type move constructed from the pair if and //! only if there is no element in the container with key equivalent to the key of x. @@ -501,7 +467,7 @@ class map //! //! Complexity: Logarithmic. std::pair insert(BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_unique(boost::move(x)); } + { return this->base_t::insert_unique(boost::move(x)); } //! Effects: Move constructs a new value from x if and only if there is //! no element in the container with key equivalent to the key of x. @@ -512,7 +478,7 @@ class map //! //! Complexity: Logarithmic. std::pair insert(BOOST_RV_REF(value_type) x) - { return m_tree.insert_unique(boost::move(x)); } + { return this->base_t::insert_unique(boost::move(x)); } //! Effects: Inserts a copy of x in the container if and only if there is //! no element in the container with key equivalent to the key of x. @@ -524,7 +490,7 @@ class map //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, const value_type& x) - { return m_tree.insert_unique(position, x); } + { return this->base_t::insert_unique(position, x); } //! Effects: Move constructs a new value from x if and only if there is //! no element in the container with key equivalent to the key of x. @@ -536,7 +502,7 @@ class map //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_unique(position, boost::move(x)); } + { return this->base_t::insert_unique(position, boost::move(x)); } //! Effects: Move constructs a new value from x if and only if there is //! no element in the container with key equivalent to the key of x. @@ -548,7 +514,7 @@ class map //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_unique(position, boost::move(x)); } + { return this->base_t::insert_unique(position, boost::move(x)); } //! Effects: Inserts a copy of x in the container. //! p is a hint pointing to where the insert should start to search. @@ -557,7 +523,7 @@ class map //! //! Complexity: Logarithmic. iterator insert(const_iterator position, const nonconst_value_type& x) - { return m_tree.insert_unique(position, x); } + { return this->base_t::insert_unique(position, x); } //! Effects: Inserts an element move constructed from x in the container. //! p is a hint pointing to where the insert should start to search. @@ -566,7 +532,7 @@ class map //! //! Complexity: Logarithmic. iterator insert(const_iterator position, BOOST_RV_REF(value_type) x) - { return m_tree.insert_unique(position, boost::move(x)); } + { return this->base_t::insert_unique(position, boost::move(x)); } //! Requires: first, last are not iterators into *this. //! @@ -576,7 +542,7 @@ class map //! Complexity: At most N log(size()+N) (N is the distance from first to last) template void insert(InputIterator first, InputIterator last) - { m_tree.insert_unique(first, last); } + { this->base_t::insert_unique(first, last); } #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) @@ -593,7 +559,7 @@ class map //! is inserted right before p. template std::pair emplace(Args&&... args) - { return m_tree.emplace_unique(boost::forward(args)...); } + { return this->base_t::emplace_unique(boost::forward(args)...); } //! Effects: Inserts an object of type T constructed with //! std::forward(args)... in the container if and only if there is @@ -607,19 +573,19 @@ class map //! is inserted right before p. template iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_unique(hint, boost::forward(args)...); } + { return this->base_t::emplace_hint_unique(hint, boost::forward(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ + { return this->base_t::emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); }\ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_unique(hint \ + { return this->base_t::emplace_hint_unique(hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -627,6 +593,8 @@ class map #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + //! Effects: Erases the element pointed to by position. //! //! Returns: Returns an iterator pointing to the element immediately @@ -634,141 +602,154 @@ class map //! returns end(). //! //! Complexity: Amortized constant time - iterator erase(const_iterator position) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(position); } + iterator erase(const_iterator position) BOOST_CONTAINER_NOEXCEPT; //! Effects: Erases all elements in the container with key equivalent to x. //! //! Returns: Returns the number of erased elements. //! //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(x); } + size_type erase(const key_type& x) BOOST_CONTAINER_NOEXCEPT; //! Effects: Erases all the elements in the range [first, last). //! //! Returns: Returns last. //! //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(first, last); } + iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT; //! Effects: Swaps the contents of *this and x. //! //! Throws: Nothing. //! //! Complexity: Constant. - void swap(map& x) - { m_tree.swap(x.m_tree); } + void swap(map& x); //! Effects: erase(a.begin(),a.end()). //! //! Postcondition: size() == 0. //! //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// + void clear() BOOST_CONTAINER_NOEXCEPT; //! Effects: Returns the comparison object out //! of which a was constructed. //! //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } + key_compare key_comp() const; //! Effects: Returns an object of value_compare constructed out //! of the comparison object. //! //! Complexity: Constant. - value_compare value_comp() const - { return value_compare(m_tree.key_comp()); } - - ////////////////////////////////////////////// - // - // map operations - // - ////////////////////////////////////////////// + value_compare value_comp() const; //! Returns: An iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } + iterator find(const key_type& x); //! Returns: Allocator const_iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } + const_iterator find(const key_type& x) const; + + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Returns: The number of elements with key equivalent to x. //! //! Complexity: log(size())+count(k) size_type count(const key_type& x) const - { return static_cast(m_tree.find(x) != m_tree.end()); } + { return static_cast(this->find(x) != this->cend()); } + + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Returns: An iterator pointing to the first element with key not less //! than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_tree.lower_bound(x); } + iterator lower_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } + const_iterator lower_bound(const key_type& x) const; //! Returns: An iterator pointing to the first element with key not less //! than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } + iterator upper_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } + const_iterator upper_bound(const key_type& x) const; //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } + std::pair equal_range(const key_type& x); //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } + std::pair equal_range(const key_type& x) const; - /// @cond - template - friend bool operator== (const map&, - const map&); - template - friend bool operator< (const map&, - const map&); + //! Effects: Rebalances the tree. It's a no-op for Red-Black and AVL trees. + //! + //! Complexity: Linear + void rebalance(); + + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const map& x, const map& y); + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const map& x, const map& y); + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const map& x, const map& y); + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const map& x, const map& y); + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const map& x, const map& y); + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const map& x, const map& y); + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(map& x, map& y); + + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: mapped_type& priv_subscript(const key_type &k) { //we can optimize this - iterator i = lower_bound(k); + iterator i = this->lower_bound(k); // i->first is greater than or equivalent to k. - if (i == end() || key_comp()(k, (*i).first)){ + if (i == this->end() || this->key_comp()(k, (*i).first)){ container_detail::value_init m; movable_value_type val(k, boost::move(m.m_t)); i = insert(i, boost::move(val)); @@ -780,9 +761,9 @@ class map { key_type &k = mk; //we can optimize this - iterator i = lower_bound(k); + iterator i = this->lower_bound(k); // i->first is greater than or equivalent to k. - if (i == end() || key_comp()(k, (*i).first)){ + if (i == this->end() || this->key_comp()(k, (*i).first)){ container_detail::value_init m; movable_value_type val(boost::move(k), boost::move(m.m_t)); i = insert(i, boost::move(val)); @@ -790,54 +771,11 @@ class map return (*i).second; } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const map& x, - const map& y) - { return x.m_tree == y.m_tree; } -template -inline bool operator<(const map& x, - const map& y) - { return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const map& x, - const map& y) - { return !(x == y); } - -template -inline bool operator>(const map& x, - const map& y) - { return y < x; } - -template -inline bool operator<=(const map& x, - const map& y) - { return !(y < x); } - -template -inline bool operator>=(const map& x, - const map& y) - { return !(x < y); } - -template -inline void swap(map& x, map& y) - { x.swap(y); } - -/// @cond - -// Forward declaration of operators < and ==, needed for friend declaration. - -template -inline bool operator==(const multimap& x, - const multimap& y); - -template -inline bool operator<(const multimap& x, - const multimap& y); +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { @@ -851,7 +789,9 @@ struct has_trivial_destructor_after_move the key_type is Key and the value_type is std::pair. +//! container and of an associative container. The value_type stored +//! by this container is the value_type is std::pair. //! -//! Compare is the ordering function for Keys (e.g. std::less). -//! -//! Allocator is the allocator to allocate the value_types -//!(e.g. allocator< std::pair<const Key, T> >). -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator< std::pair< const Key, T> > > +//! \tparam Key is the key_type of the map +//! \tparam Value is the mapped_type +//! \tparam Compare is the ordering function for Keys (e.g. std::less). +//! \tparam Allocator is the allocator to allocate the value_types +//! (e.g. allocator< std::pair > ). +//! \tparam MultiMapOptions is an packed option type generated using using boost::container::tree_assoc_options. +template < class Key, class T, class Compare = std::less + , class Allocator = std::allocator< std::pair< const Key, T> >, class MultiMapOptions = tree_assoc_defaults> #else -template +template #endif class multimap + ///@cond + : public container_detail::tree + < Key, std::pair + , container_detail::select1st< std::pair > + , Compare, Allocator, MultiMapOptions> + ///@endcond { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(multimap) typedef std::pair value_type_impl; - typedef container_detail::rbtree - , Compare, Allocator> tree_t; + typedef container_detail::tree + , Compare, Allocator, MultiMapOptions> base_t; typedef container_detail::pair movable_value_type_impl; typedef container_detail::tree_value_compare < Key, value_type_impl, Compare, container_detail::select1st > value_compare_impl; - tree_t m_tree; // red-black tree representing map - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -904,13 +851,13 @@ class multimap typedef typename boost::container::allocator_traits::size_type size_type; typedef typename boost::container::allocator_traits::difference_type difference_type; typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::stored_allocator_type) stored_allocator_type; typedef BOOST_CONTAINER_IMPDEF(value_compare_impl) value_compare; typedef Compare key_compare; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::iterator) iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_iterator) const_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::reverse_iterator) reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_reverse_iterator) const_reverse_iterator; typedef std::pair nonconst_value_type; typedef BOOST_CONTAINER_IMPDEF(movable_value_type_impl) movable_value_type; @@ -924,7 +871,7 @@ class multimap //! //! Complexity: Constant. multimap() - : m_tree() + : base_t() { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -934,7 +881,7 @@ class multimap //! //! Complexity: Constant. explicit multimap(const Compare& comp, const allocator_type& a = allocator_type()) - : m_tree(comp, a) + : base_t(comp, a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -945,7 +892,7 @@ class multimap //! //! Complexity: Constant. explicit multimap(const allocator_type& a) - : m_tree(a) + : base_t(a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -960,7 +907,7 @@ class multimap multimap(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(false, first, last, comp, a) + : base_t(false, first, last, comp, a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -978,14 +925,14 @@ class multimap template multimap(ordered_range_t, InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) + : base_t(ordered_range, first, last, comp, a) {} //! Effects: Copy constructs a multimap. //! //! Complexity: Linear in x.size(). multimap(const multimap& x) - : m_tree(x.m_tree) + : base_t(static_cast(x)) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -997,7 +944,7 @@ class multimap //! //! Postcondition: x is emptied. multimap(BOOST_RV_REF(multimap) x) - : m_tree(boost::move(x.m_tree)) + : base_t(boost::move(static_cast(x))) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -1007,7 +954,7 @@ class multimap //! //! Complexity: Linear in x.size(). multimap(const multimap& x, const allocator_type &a) - : m_tree(x.m_tree, a) + : base_t(static_cast(x), a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -1019,7 +966,7 @@ class multimap //! //! Postcondition: x is emptied. multimap(BOOST_RV_REF(multimap) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) + : base_t(boost::move(static_cast(x)), a) { //Allocator type must be std::pair BOOST_STATIC_ASSERT((container_detail::is_same, typename Allocator::value_type>::value)); @@ -1029,184 +976,71 @@ class multimap //! //! Complexity: Linear in x.size(). multimap& operator=(BOOST_COPY_ASSIGN_REF(multimap) x) - { m_tree = x.m_tree; return *this; } + { return static_cast(this->base_t::operator=(static_cast(x))); } //! Effects: this->swap(x.get()). //! //! Complexity: Constant. multimap& operator=(BOOST_RV_REF(multimap) x) - { m_tree = boost::move(x.m_tree); return *this; } + { return static_cast(this->base_t::operator=(boost::move(static_cast(x)))); } - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_allocator(); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } + //! @copydoc ::boost::container::set::get_allocator() + allocator_type get_allocator() const; - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.get_stored_allocator(); } + //! @copydoc ::boost::container::set::get_stored_allocator() + stored_allocator_type &get_stored_allocator(); - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::set::get_stored_allocator() const + const stored_allocator_type &get_stored_allocator() const; - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } + //! @copydoc ::boost::container::set::begin() + iterator begin(); - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const BOOST_CONTAINER_NOEXCEPT - { return this->cbegin(); } + //! @copydoc ::boost::container::set::begin() const + const_iterator begin() const; - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } + //! @copydoc ::boost::container::set::cbegin() const + const_iterator cbegin() const; - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const BOOST_CONTAINER_NOEXCEPT - { return this->cend(); } + //! @copydoc ::boost::container::set::end() + iterator end() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } + //! @copydoc ::boost::container::set::end() const + const_iterator end() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT - { return this->crbegin(); } + //! @copydoc ::boost::container::set::cend() const + const_iterator cend() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } + //! @copydoc ::boost::container::set::rbegin() + reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT - { return this->crend(); } + //! @copydoc ::boost::container::set::rbegin() const + const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.begin(); } + //! @copydoc ::boost::container::set::crbegin() const + const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.end(); } + //! @copydoc ::boost::container::set::rend() + reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rbegin(); } + //! @copydoc ::boost::container::set::rend() const + const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.rend(); } + //! @copydoc ::boost::container::set::crend() const + const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT; - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::set::empty() const + bool empty() const; - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.empty(); } + //! @copydoc ::boost::container::set::size() const + size_type size() const; - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.size(); } + //! @copydoc ::boost::container::set::max_size() const + size_type max_size() const; - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const BOOST_CONTAINER_NOEXCEPT - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) @@ -1221,7 +1055,7 @@ class multimap //! is inserted right before p. template iterator emplace(Args&&... args) - { return m_tree.emplace_equal(boost::forward(args)...); } + { return this->base_t::emplace_equal(boost::forward(args)...); } //! Effects: Inserts an object of type T constructed with //! std::forward(args)... in the container. @@ -1234,19 +1068,19 @@ class multimap //! is inserted right before p. template iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_equal(hint, boost::forward(args)...); } + { return this->base_t::emplace_hint_equal(hint, boost::forward(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ + { return this->base_t::emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_equal(hint \ + { return this->base_t::emplace_hint_equal(hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -1259,28 +1093,28 @@ class multimap //! //! Complexity: Logarithmic. iterator insert(const value_type& x) - { return m_tree.insert_equal(x); } + { return this->base_t::insert_equal(x); } //! Effects: Inserts a new value constructed from x and returns //! the iterator pointing to the newly inserted element. //! //! Complexity: Logarithmic. iterator insert(const nonconst_value_type& x) - { return m_tree.insert_equal(x); } + { return this->base_t::insert_equal(x); } //! Effects: Inserts a new value move-constructed from x and returns //! the iterator pointing to the newly inserted element. //! //! Complexity: Logarithmic. iterator insert(BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_equal(boost::move(x)); } + { return this->base_t::insert_equal(boost::move(x)); } //! Effects: Inserts a new value move-constructed from x and returns //! the iterator pointing to the newly inserted element. //! //! Complexity: Logarithmic. iterator insert(BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_equal(boost::move(x)); } + { return this->base_t::insert_equal(boost::move(x)); } //! Effects: Inserts a copy of x in the container. //! p is a hint pointing to where the insert should start to search. @@ -1291,7 +1125,7 @@ class multimap //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, const value_type& x) - { return m_tree.insert_equal(position, x); } + { return this->base_t::insert_equal(position, x); } //! Effects: Inserts a new value constructed from x in the container. //! p is a hint pointing to where the insert should start to search. @@ -1302,7 +1136,7 @@ class multimap //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, const nonconst_value_type& x) - { return m_tree.insert_equal(position, x); } + { return this->base_t::insert_equal(position, x); } //! Effects: Inserts a new value move constructed from x in the container. //! p is a hint pointing to where the insert should start to search. @@ -1313,7 +1147,7 @@ class multimap //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, BOOST_RV_REF(nonconst_value_type) x) - { return m_tree.insert_equal(position, boost::move(x)); } + { return this->base_t::insert_equal(position, boost::move(x)); } //! Effects: Inserts a new value move constructed from x in the container. //! p is a hint pointing to where the insert should start to search. @@ -1324,7 +1158,7 @@ class multimap //! Complexity: Logarithmic in general, but amortized constant if t //! is inserted right before p. iterator insert(const_iterator position, BOOST_RV_REF(movable_value_type) x) - { return m_tree.insert_equal(position, boost::move(x)); } + { return this->base_t::insert_equal(position, boost::move(x)); } //! Requires: first, last are not iterators into *this. //! @@ -1333,182 +1167,126 @@ class multimap //! Complexity: At most N log(size()+N) (N is the distance from first to last) template void insert(InputIterator first, InputIterator last) - { m_tree.insert_equal(first, last); } + { this->base_t::insert_equal(first, last); } - //! Effects: Erases the element pointed to by position. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Amortized constant time - iterator erase(const_iterator position) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(position); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(x); } + //! @copydoc ::boost::container::set::erase(const_iterator) + iterator erase(const_iterator p); - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT - { return m_tree.erase(first, last); } + //! @copydoc ::boost::container::set::erase(const key_type&) + size_type erase(const key_type& x); - //! Effects: Swaps the contents of *this and x. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - void swap(multimap& x) - { m_tree.swap(x.m_tree); } + //! @copydoc ::boost::container::set::erase(const_iterator,const_iterator) + iterator erase(const_iterator first, const_iterator last); - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() BOOST_CONTAINER_NOEXCEPT - { m_tree.clear(); } + //! @copydoc ::boost::container::set::swap + void swap(flat_multiset& x); - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::set::clear + void clear() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } + //! @copydoc ::boost::container::set::key_comp + key_compare key_comp() const; - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return value_compare(m_tree.key_comp()); } - - ////////////////////////////////////////////// - // - // map operations - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::set::value_comp + value_compare value_comp() const; //! Returns: An iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } + iterator find(const key_type& x); //! Returns: Allocator const iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } + const_iterator find(const key_type& x) const; //! Returns: The number of elements with key equivalent to x. //! //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_tree.count(x); } + size_type count(const key_type& x) const; //! Returns: An iterator pointing to the first element with key not less //! than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - {return m_tree.lower_bound(x); } + iterator lower_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } + const_iterator lower_bound(const key_type& x) const; //! Returns: An iterator pointing to the first element with key not less //! than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } + iterator upper_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } + const_iterator upper_bound(const key_type& x) const; //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } + std::pair equal_range(const key_type& x); //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } + std::pair equal_range(const key_type& x) const; - /// @cond - template - friend bool operator== (const multimap& x, - const multimap& y); + //! Effects: Rebalances the tree. It's a no-op for Red-Black and AVL trees. + //! + //! Complexity: Linear + void rebalance(); - template - friend bool operator< (const multimap& x, - const multimap& y); - /// @endcond + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const multimap& x, const multimap& y); + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const multimap& x, const multimap& y); + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const multimap& x, const multimap& y); + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const multimap& x, const multimap& y); + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const multimap& x, const multimap& y); + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const multimap& x, const multimap& y); + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(multimap& x, multimap& y); + + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) }; -template -inline bool operator==(const multimap& x, - const multimap& y) -{ return x.m_tree == y.m_tree; } - -template -inline bool operator<(const multimap& x, - const multimap& y) -{ return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const multimap& x, - const multimap& y) -{ return !(x == y); } - -template -inline bool operator>(const multimap& x, - const multimap& y) -{ return y < x; } - -template -inline bool operator<=(const multimap& x, - const multimap& y) -{ return !(y < x); } - -template -inline bool operator>=(const multimap& x, - const multimap& y) -{ return !(x < y); } - -template -inline void swap(multimap& x, multimap& y) -{ x.swap(y); } - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { @@ -1522,7 +1300,7 @@ struct has_trivial_destructor_after_move= 1200) +# pragma once +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace container { + +//!An STL node allocator that uses a modified DlMalloc as memory +//!source. +//! +//!This node allocator shares a segregated storage between all instances +//!of node_allocator with equal sizeof(T). +//! +//!NodesPerBlock is the number of nodes allocated at once when the allocator +//!runs out of nodes +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED +template + < class T + , std::size_t NodesPerBlock = NodeAlloc_nodes_per_block> +#else +template + < class T + , std::size_t NodesPerBlock + , std::size_t Version> +#endif +class node_allocator +{ + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + //! If Version is 1, the allocator is a STL conforming allocator. If Version is 2, + //! the allocator offers advanced expand in place and burst allocation capabilities. + public: + typedef unsigned int allocation_type; + typedef node_allocator self_t; + + static const std::size_t nodes_per_block = NodesPerBlock; + + BOOST_STATIC_ASSERT((Version <=2)); + #endif + + public: + //------- + typedef T value_type; + typedef T * pointer; + typedef const T * const_pointer; + typedef typename ::boost::container:: + container_detail::unvoid::type & reference; + typedef const typename ::boost::container:: + container_detail::unvoid::type & const_reference; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; + + typedef boost::container::container_detail:: + version_type version; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + typedef boost::container::container_detail:: + basic_multiallocation_chain multiallocation_chain_void; + typedef boost::container::container_detail:: + transform_multiallocation_chain + multiallocation_chain; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + //!Obtains node_allocator from + //!node_allocator + template + struct rebind + { + typedef node_allocator< T2, NodesPerBlock + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + , Version + #endif + > other; + }; + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + private: + //!Not assignable from related node_allocator + template + node_allocator& operator= + (const node_allocator&); + + //!Not assignable from other node_allocator + node_allocator& operator=(const node_allocator&); + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + + public: + + //!Default constructor + node_allocator() BOOST_CONTAINER_NOEXCEPT + {} + + //!Copy constructor from other node_allocator. + node_allocator(const node_allocator &) BOOST_CONTAINER_NOEXCEPT + {} + + //!Copy constructor from related node_allocator. + template + node_allocator + (const node_allocator &) BOOST_CONTAINER_NOEXCEPT + {} + + //!Destructor + ~node_allocator() BOOST_CONTAINER_NOEXCEPT + {} + + //!Returns the number of elements that could be allocated. + //!Never throws + size_type max_size() const + { return size_type(-1)/sizeof(T); } + + //!Allocate memory for an array of count elements. + //!Throws std::bad_alloc if there is no enough memory + pointer allocate(size_type count, const void * = 0) + { + if(count > this->max_size()) + boost::container::throw_bad_alloc(); + + if(Version == 1 && count == 1){ + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + return pointer(static_cast(singleton_t::instance().allocate_node())); + } + else{ + void *ret = boost_cont_malloc(count*sizeof(T)); + if(!ret) + boost::container::throw_bad_alloc(); + return static_cast(ret); + } + } + + //!Deallocate allocated memory. + //!Never throws + void deallocate(const pointer &ptr, size_type count) BOOST_CONTAINER_NOEXCEPT + { + (void)count; + if(Version == 1 && count == 1){ + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().deallocate_node(ptr); + } + else{ + boost_cont_free(ptr); + } + } + + //!Deallocates all free blocks of the pool + static void deallocate_free_blocks() BOOST_CONTAINER_NOEXCEPT + { + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().deallocate_free_blocks(); + } + + std::pair + allocation_command(allocation_type command, + size_type limit_size, + size_type preferred_size, + size_type &received_size, pointer reuse = pointer()) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + std::pair ret = + priv_allocation_command(command, limit_size, preferred_size, received_size, reuse); + if(!ret.first && !(command & BOOST_CONTAINER_NOTHROW_ALLOCATION)) + boost::container::throw_bad_alloc(); + return ret; + } + + //!Returns maximum the number of objects the previously allocated memory + //!pointed by p can hold. + size_type size(pointer p) const BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + return boost_cont_size(p); + } + + //!Allocates just one object. Memory allocated with this function + //!must be deallocated only with deallocate_one(). + //!Throws bad_alloc if there is no enough memory + pointer allocate_one() + { + BOOST_STATIC_ASSERT(( Version > 1 )); + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + return (pointer)singleton_t::instance().allocate_node(); + } + + //!Allocates many elements of size == 1. + //!Elements must be individually deallocated with deallocate_one() + void allocate_individual(std::size_t num_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + typename shared_pool_t::multiallocation_chain ch; + singleton_t::instance().allocate_nodes(num_elements, ch); + chain.incorporate_after(chain.before_begin(), (T*)&*ch.begin(), (T*)&*ch.last(), ch.size()); + } + + //!Deallocates memory previously allocated with allocate_one(). + //!You should never use deallocate_one to deallocate memory allocated + //!with other functions different from allocate_one(). Never throws + void deallocate_one(pointer p) BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + singleton_t::instance().deallocate_node(p); + } + + void deallocate_individual(multiallocation_chain &chain) BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + typedef container_detail::shared_node_pool + shared_pool_t; + typedef container_detail::singleton_default singleton_t; + typename shared_pool_t::multiallocation_chain ch(&*chain.begin(), &*chain.last(), chain.size()); + singleton_t::instance().deallocate_nodes(ch); + } + + //!Allocates many elements of size elem_size. + //!Elements must be individually deallocated with deallocate() + void allocate_many(size_type elem_size, std::size_t n_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + boost_cont_memchain ch; + BOOST_CONTAINER_MEMCHAIN_INIT(&ch); + if(!boost_cont_multialloc_nodes(n_elements, elem_size*sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &ch)){ + boost::container::throw_bad_alloc(); + } + chain.incorporate_after( chain.before_begin() + , (T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + , (T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + , BOOST_CONTAINER_MEMCHAIN_SIZE(&ch)); + } + + //!Allocates n_elements elements, each one of size elem_sizes[i] + //!Elements must be individually deallocated with deallocate() + void allocate_many(const size_type *elem_sizes, size_type n_elements, multiallocation_chain &chain) + { + BOOST_STATIC_ASSERT(( Version > 1 )); + boost_cont_memchain ch; + boost_cont_multialloc_arrays(n_elements, elem_sizes, sizeof(T), DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &ch); + if(BOOST_CONTAINER_MEMCHAIN_EMPTY(&ch)){ + boost::container::throw_bad_alloc(); + } + chain.incorporate_after( chain.before_begin() + , (T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + , (T*)BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ch) + , BOOST_CONTAINER_MEMCHAIN_SIZE(&ch)); + } + + void deallocate_many(multiallocation_chain &chain) BOOST_CONTAINER_NOEXCEPT + { + BOOST_STATIC_ASSERT(( Version > 1 )); + void *first = &*chain.begin(); + void *last = &*chain.last(); + size_t num = chain.size(); + boost_cont_memchain ch; + BOOST_CONTAINER_MEMCHAIN_INIT_FROM(&ch, first, last, num); + boost_cont_multidealloc(&ch); + } + + //!Swaps allocators. Does not throw. If each allocator is placed in a + //!different memory segment, the result is undefined. + friend void swap(self_t &, self_t &) BOOST_CONTAINER_NOEXCEPT + {} + + //!An allocator always compares to true, as memory allocated with one + //!instance can be deallocated by another instance + friend bool operator==(const node_allocator &, const node_allocator &) BOOST_CONTAINER_NOEXCEPT + { return true; } + + //!An allocator always compares to false, as memory allocated with one + //!instance can be deallocated by another instance + friend bool operator!=(const node_allocator &, const node_allocator &) BOOST_CONTAINER_NOEXCEPT + { return false; } + + private: + std::pair priv_allocation_command + (allocation_type command, std::size_t limit_size + ,std::size_t preferred_size,std::size_t &received_size, void *reuse_ptr) + { + boost_cont_command_ret_t ret = {0 , 0}; + if(limit_size > this->max_size() || preferred_size > this->max_size()){ + //ret.first = 0; + return std::pair(pointer(), false); + } + std::size_t l_size = limit_size*sizeof(T); + std::size_t p_size = preferred_size*sizeof(T); + std::size_t r_size; + { + ret = boost_cont_allocation_command(command, sizeof(T), l_size, p_size, &r_size, reuse_ptr); + } + received_size = r_size/sizeof(T); + return std::pair(static_cast(ret.first), !!ret.second); + } +}; + +} //namespace container { +} //namespace boost { + +#include + +#endif //#ifndef BOOST_CONTAINER_POOLED_NODE_ALLOCATOR_HPP diff --git a/include/boost/container/options.hpp b/include/boost/container/options.hpp new file mode 100644 index 0000000..11bf9de --- /dev/null +++ b/include/boost/container/options.hpp @@ -0,0 +1,72 @@ +///////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013 +// +// Distributed under the Boost Software License, Version 1.0. +// (See accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +///////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_OPTIONS_HPP +#define BOOST_CONTAINER_OPTIONS_HPP + +#include +#include +#include + +namespace boost { +namespace container { + +#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + +template +struct tree_opt +{ + static const boost::container::tree_type_enum tree_type = TreeType; + static const bool optimize_size = OptimizeSize; +}; + +#endif //!defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + +//!This option setter specifies the underlying tree type +//!(red-black, AVL, Scapegoat or Splay) for ordered associative containers +BOOST_INTRUSIVE_OPTION_CONSTANT(tree_type, tree_type_enum, TreeType, tree_type) + +//!This option setter specifies if node size is optimized +//!storing rebalancing data masked into pointers for ordered associative containers +BOOST_INTRUSIVE_OPTION_CONSTANT(optimize_size, bool, Enabled, optimize_size) + +//! Helper metafunction to combine options into a single type to be used +//! by \c boost::container::set, \c boost::container::multiset +//! \c boost::container::map and \c boost::container::multimap. +//! Supported options are: \c boost::container::optimize_size and \c boost::container::tree_type +#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) || defined(BOOST_CONTAINER_VARIADIC_TEMPLATES) +template +#else +template +#endif +struct tree_assoc_options +{ + /// @cond + typedef typename ::boost::intrusive::pack_options + < tree_assoc_defaults, + #if !defined(BOOST_CONTAINER_VARIADIC_TEMPLATES) + O1, O2, O3, O4 + #else + Options... + #endif + >::type packed_options; + typedef tree_opt implementation_defined; + /// @endcond + typedef implementation_defined type; +}; + +} //namespace container { +} //namespace boost { + +#include + +#endif //#ifndef BOOST_CONTAINER_OPTIONS_HPP diff --git a/include/boost/container/scoped_allocator.hpp b/include/boost/container/scoped_allocator.hpp index d16ac37..fac90f5 100644 --- a/include/boost/container/scoped_allocator.hpp +++ b/include/boost/container/scoped_allocator.hpp @@ -6,7 +6,7 @@ // ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -46,7 +46,7 @@ namespace boost { namespace container { //! and if T is used in a context where a container must call such a constructor, then the program is //! ill-formed. //! -//! [Example: +//! //! template > //! class Z { //! public: @@ -64,7 +64,7 @@ namespace boost { namespace container { //! template > //! struct constructible_with_allocator_suffix > //! : ::boost::true_type { }; -//! -- end example] +//! //! //! Note: This trait is a workaround inspired by "N2554: The Scoped Allocator Model (Rev 2)" //! (Pablo Halpern, 2008-02-29) to backport the scoped allocator model to C++03, as @@ -90,7 +90,7 @@ struct constructible_with_allocator_suffix //! called with these initial arguments, and if T is used in a context where a container must call such //! a constructor, then the program is ill-formed. //! -//! [Example: +//! //! template > //! class Y { //! public: @@ -115,7 +115,7 @@ struct constructible_with_allocator_suffix //! struct constructible_with_allocator_prefix > //! : ::boost::true_type { }; //! -//! -- end example] +//! //! //! Note: This trait is a workaround inspired by "N2554: The Scoped Allocator Model (Rev 2)" //! (Pablo Halpern, 2008-02-29) to backport the scoped allocator model to C++03, as @@ -130,7 +130,7 @@ struct constructible_with_allocator_prefix : ::boost::false_type {}; -///@cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace container_detail { @@ -159,7 +159,7 @@ struct uses_allocator_imp } //namespace container_detail { -///@endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! Remark: Automatically detects if T has a nested allocator_type that is convertible from //! Alloc. Meets the BinaryTypeTrait requirements ([meta.rqmts] 20.4.1). A program may @@ -173,7 +173,7 @@ struct uses_allocator : boost::integral_constant::value> {}; -///@cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace container_detail { @@ -675,16 +675,16 @@ class scoped_allocator_adaptor_base friend void swap(scoped_allocator_adaptor_base &l, scoped_allocator_adaptor_base &r) { l.swap(r); } - inner_allocator_type& inner_allocator() + inner_allocator_type& inner_allocator() BOOST_CONTAINER_NOEXCEPT { return m_inner; } - inner_allocator_type const& inner_allocator() const + inner_allocator_type const& inner_allocator() const BOOST_CONTAINER_NOEXCEPT { return m_inner; } - outer_allocator_type & outer_allocator() + outer_allocator_type & outer_allocator() BOOST_CONTAINER_NOEXCEPT { return static_cast(*this); } - const outer_allocator_type &outer_allocator() const + const outer_allocator_type &outer_allocator() const BOOST_CONTAINER_NOEXCEPT { return static_cast(*this); } scoped_allocator_type select_on_container_copy_construction() const @@ -1008,7 +1008,7 @@ class scoped_allocator_adaptor_base } //namespace container_detail { -///@endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //Scoped allocator #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) @@ -1038,14 +1038,14 @@ class scoped_allocator_adaptor_base //! scoped_allocator_adaptor is derived from the outer allocator type so it can be //! substituted for the outer allocator type in most expressions. -end note] //! - //! In the construct member functions, `OUTERMOST(x)` is x if x does not have - //! an `outer_allocator()` member function and - //! `OUTERMOST(x.outer_allocator())` otherwise; `OUTERMOST_ALLOC_TRAITS(x)` is - //! `allocator_traits`. + //! In the construct member functions, OUTERMOST(x) is x if x does not have + //! an outer_allocator() member function and + //! OUTERMOST(x.outer_allocator()) otherwise; OUTERMOST_ALLOC_TRAITS(x) is + //! allocator_traits. //! - //! [Note: `OUTERMOST(x)` and - //! `OUTERMOST_ALLOC_TRAITS(x)` are recursive operations. It is incumbent upon - //! the definition of `outer_allocator()` to ensure that the recursion terminates. + //! [Note: OUTERMOST(x) and + //! OUTERMOST_ALLOC_TRAITS(x) are recursive operations. It is incumbent upon + //! the definition of outer_allocator() to ensure that the recursion terminates. //! It will terminate for all instantiations of scoped_allocator_adaptor. -end note] template class scoped_allocator_adaptor @@ -1076,7 +1076,7 @@ class scoped_allocator_adaptor BOOST_COPYABLE_AND_MOVABLE(scoped_allocator_adaptor) public: - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED typedef container_detail::scoped_allocator_adaptor_base base_type; typedef typename base_type::internal_type_t internal_type_t; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED typedef OuterAlloc outer_allocator_type; //! Type: For exposition only //! typedef allocator_traits outer_traits_type; - //! Type: `scoped_allocator_adaptor` if `sizeof...(InnerAllocs)` is zero; otherwise, - //! `scoped_allocator_adaptor`. + //! Type: scoped_allocator_adaptor if sizeof...(InnerAllocs) is zero; otherwise, + //! scoped_allocator_adaptor. typedef typename base_type::inner_allocator_type inner_allocator_type; typedef allocator_traits inner_traits_type; typedef typename outer_traits_type::value_type value_type; @@ -1102,23 +1102,23 @@ class scoped_allocator_adaptor typedef typename outer_traits_type::const_pointer const_pointer; typedef typename outer_traits_type::void_pointer void_pointer; typedef typename outer_traits_type::const_void_pointer const_void_pointer; - //! Type: `true_type` if `allocator_traits::propagate_on_container_copy_assignment::value` is - //! true for any `Allocator` in the set of `OuterAlloc` and `InnerAllocs...`; otherwise, false_type. + //! Type: true_type if allocator_traits::propagate_on_container_copy_assignment::value is + //! true for any Allocator in the set of OuterAlloc and InnerAllocs...; otherwise, false_type. typedef typename base_type:: propagate_on_container_copy_assignment propagate_on_container_copy_assignment; - //! Type: `true_type` if `allocator_traits::propagate_on_container_move_assignment::value` is - //! true for any `Allocator` in the set of `OuterAlloc` and `InnerAllocs...`; otherwise, false_type. + //! Type: true_type if allocator_traits::propagate_on_container_move_assignment::value is + //! true for any Allocator in the set of OuterAlloc and InnerAllocs...; otherwise, false_type. typedef typename base_type:: propagate_on_container_move_assignment propagate_on_container_move_assignment; - //! Type: `true_type` if `allocator_traits::propagate_on_container_swap::value` is true for any - //! `Allocator` in the set of `OuterAlloc` and `InnerAllocs...`; otherwise, false_type. + //! Type: true_type if allocator_traits::propagate_on_container_swap::value is true for any + //! Allocator in the set of OuterAlloc and InnerAllocs...; otherwise, false_type. typedef typename base_type:: propagate_on_container_swap propagate_on_container_swap; //! Type: Rebinds scoped allocator to - //! `typedef scoped_allocator_adaptor + //! typedef scoped_allocator_adaptor //! < typename outer_traits_type::template portable_rebind_alloc::type - //! , InnerAllocs... >` + //! , InnerAllocs... > template struct rebind { @@ -1224,55 +1224,55 @@ class scoped_allocator_adaptor friend void swap(scoped_allocator_adaptor &l, scoped_allocator_adaptor &r); //! Returns: - //! `static_cast(*this)`. - outer_allocator_type & outer_allocator(); + //! static_cast(*this). + outer_allocator_type & outer_allocator() BOOST_CONTAINER_NOEXCEPT; //! Returns: - //! `static_cast(*this)`. - const outer_allocator_type &outer_allocator() const; + //! static_cast(*this). + const outer_allocator_type &outer_allocator() const BOOST_CONTAINER_NOEXCEPT; //! Returns: - //! *this if `sizeof...(InnerAllocs)` is zero; otherwise, inner. - inner_allocator_type& inner_allocator(); + //! *this if sizeof...(InnerAllocs) is zero; otherwise, inner. + inner_allocator_type& inner_allocator() BOOST_CONTAINER_NOEXCEPT; //! Returns: - //! *this if `sizeof...(InnerAllocs)` is zero; otherwise, inner. - inner_allocator_type const& inner_allocator() const; + //! *this if sizeof...(InnerAllocs) is zero; otherwise, inner. + inner_allocator_type const& inner_allocator() const BOOST_CONTAINER_NOEXCEPT; #endif //BOOST_CONTAINER_DOXYGEN_INVOKED //! Returns: - //! `allocator_traits::max_size(outer_allocator())`. - size_type max_size() const + //! allocator_traits::max_size(outer_allocator()). + size_type max_size() const BOOST_CONTAINER_NOEXCEPT { return outer_traits_type::max_size(this->outer_allocator()); } //! Effects: - //! calls `OUTERMOST_ALLOC_TRAITS(*this)::destroy(OUTERMOST(*this), p)`. + //! calls OUTERMOST_ALLOC_TRAITS(*this)::destroy(OUTERMOST(*this), p). template - void destroy(T* p) + void destroy(T* p) BOOST_CONTAINER_NOEXCEPT { allocator_traits::type> ::destroy(get_outermost_allocator(this->outer_allocator()), p); } //! Returns: - //! `allocator_traits::allocate(outer_allocator(), n)`. + //! allocator_traits::allocate(outer_allocator(), n). pointer allocate(size_type n) { return outer_traits_type::allocate(this->outer_allocator(), n); } //! Returns: - //! `allocator_traits::allocate(outer_allocator(), n, hint)`. + //! allocator_traits::allocate(outer_allocator(), n, hint). pointer allocate(size_type n, const_void_pointer hint) { return outer_traits_type::allocate(this->outer_allocator(), n, hint); } //! Effects: - //! `allocator_traits::deallocate(outer_allocator(), p, n)`. + //! allocator_traits::deallocate(outer_allocator(), p, n). void deallocate(pointer p, size_type n) { outer_traits_type::deallocate(this->outer_allocator(), p, n); @@ -1281,45 +1281,45 @@ class scoped_allocator_adaptor #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED //! Returns: Allocator new scoped_allocator_adaptor object where each allocator //! A in the adaptor is initialized from the result of calling - //! `allocator_traits::select_on_container_copy_construction()` on + //! allocator_traits::select_on_container_copy_construction() on //! the corresponding allocator in *this. scoped_allocator_adaptor select_on_container_copy_construction() const; #endif //BOOST_CONTAINER_DOXYGEN_INVOKED - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED base_type &base() { return *this; } const base_type &base() const { return *this; } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: - //! 1) If `uses_allocator::value` is false calls - //! `OUTERMOST_ALLOC_TRAITS(*this)::construct - //! (OUTERMOST(*this), p, std::forward(args)...)`. + //! 1) If uses_allocator::value is false calls + //! OUTERMOST_ALLOC_TRAITS(*this)::construct + //! (OUTERMOST(*this), p, std::forward(args)...). //! - //! 2) Otherwise, if `uses_allocator::value` is true and - //! `is_constructible::value` is true, calls - //! `OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST(*this), p, allocator_arg, - //! inner_allocator(), std::forward(args)...)`. + //! 2) Otherwise, if uses_allocator::value is true and + //! is_constructible::value is true, calls + //! OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST(*this), p, allocator_arg, + //! inner_allocator(), std::forward(args)...). //! - //! [Note: In compilers without advanced decltype SFINAE support, `is_constructible` can't + //! [Note: In compilers without advanced decltype SFINAE support, is_constructible can't //! be implemented so that condition will be replaced by //! constructible_with_allocator_prefix::value. -end note] //! //! 3) Otherwise, if uses_allocator::value is true and - //! `is_constructible::value` is true, calls - //! `OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST(*this), p, - //! std::forward(args)..., inner_allocator())`. + //! is_constructible::value is true, calls + //! OUTERMOST_ALLOC_TRAITS(*this)::construct(OUTERMOST(*this), p, + //! std::forward(args)..., inner_allocator()). //! - //! [Note: In compilers without advanced decltype SFINAE support, `is_constructible` can't be + //! [Note: In compilers without advanced decltype SFINAE support, is_constructible can't be //! implemented so that condition will be replaced by - //! `constructible_with_allocator_suffix::value`. -end note] + //! constructible_with_allocator_suffix::value. -end note] //! //! 4) Otherwise, the program is ill-formed. //! - //! [Note: An error will result if `uses_allocator` evaluates + //! [Note: An error will result if uses_allocator evaluates //! to true but the specific constructor does not take an allocator. This definition prevents a silent //! failure to pass an inner allocator to a contained element. -end note] template < typename T, class ...Args> @@ -1395,7 +1395,7 @@ class scoped_allocator_adaptor , BOOST_RV_REF_BEG container_detail::pair BOOST_RV_REF_END x) { this->construct_pair(p, x); } - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: template void construct_pair(Pair* p) @@ -1463,7 +1463,7 @@ class scoped_allocator_adaptor : base_type(internal_type_t(), ::boost::forward(outer), inner) {} - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; template -inline bool operator==(const set& x, - const set& y); - -template -inline bool operator<(const set& x, - const set& y); -/// @endcond +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED //! A set is a kind of associative container that supports unique keys (contains at //! most one of each key value) and provides for fast retrieval of the keys themselves. @@ -53,20 +44,27 @@ inline bool operator<(const set& x, //! A set satisfies all of the requirements of a container and of a reversible container //! , and of an associative container. A set also provides most operations described in //! for unique keys. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > +//! +//! \tparam Key is the type to be inserted in the set, which is also the key_type +//! \tparam Compare is the comparison functor used to order keys +//! \tparam Allocator is the allocator to be used to allocate memory for this container +//! \tparam SetOptions is an packed option type generated using using boost::container::tree_assoc_options. +template , class Allocator = std::allocator, class SetOptions = tree_assoc_defaults > #else -template +template #endif class set + ///@cond + : public container_detail::tree + < Key, Key, container_detail::identity, Compare, Allocator, SetOptions> + ///@endcond { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(set) - typedef container_detail::rbtree, Compare, Allocator> tree_t; - tree_t m_tree; // red-black tree representing set - /// @endcond + typedef container_detail::tree + < Key, Key, container_detail::identity, Compare, Allocator, SetOptions> base_t; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -85,11 +83,11 @@ class set typedef typename ::boost::container::allocator_traits::size_type size_type; typedef typename ::boost::container::allocator_traits::difference_type difference_type; typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::stored_allocator_type) stored_allocator_type; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::iterator) iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_iterator) const_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::reverse_iterator) reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_reverse_iterator) const_reverse_iterator; ////////////////////////////////////////////// // @@ -101,7 +99,7 @@ class set //! //! Complexity: Constant. set() - : m_tree() + : base_t() {} //! Effects: Constructs an empty set using the specified comparison object @@ -110,14 +108,14 @@ class set //! Complexity: Constant. explicit set(const Compare& comp, const allocator_type& a = allocator_type()) - : m_tree(comp, a) + : base_t(comp, a) {} //! Effects: Constructs an empty set using the specified allocator object. //! //! Complexity: Constant. explicit set(const allocator_type& a) - : m_tree(a) + : base_t(a) {} //! Effects: Constructs an empty set using the specified comparison object and @@ -128,7 +126,7 @@ class set template set(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(true, first, last, comp, a) + : base_t(true, first, last, comp, a) {} //! Effects: Constructs an empty set using the specified comparison object and @@ -144,14 +142,14 @@ class set template set( ordered_unique_range_t, InputIterator first, InputIterator last , const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) + : base_t(ordered_range, first, last, comp, a) {} //! Effects: Copy constructs a set. //! //! Complexity: Linear in x.size(). set(const set& x) - : m_tree(x.m_tree) + : base_t(static_cast(x)) {} //! Effects: Move constructs a set. Constructs *this using x's resources. @@ -160,14 +158,14 @@ class set //! //! Postcondition: x is emptied. set(BOOST_RV_REF(set) x) - : m_tree(boost::move(x.m_tree)) + : base_t(boost::move(static_cast(x))) {} //! Effects: Copy constructs a set using the specified allocator. //! //! Complexity: Linear in x.size(). set(const set& x, const allocator_type &a) - : m_tree(x.m_tree, a) + : base_t(static_cast(x), a) {} //! Effects: Move constructs a set using the specified allocator. @@ -175,27 +173,28 @@ class set //! //! Complexity: Constant if a == x.get_allocator(), linear otherwise. set(BOOST_RV_REF(set) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) + : base_t(boost::move(static_cast(x)), a) {} //! Effects: Makes *this a copy of x. //! //! Complexity: Linear in x.size(). set& operator=(BOOST_COPY_ASSIGN_REF(set) x) - { m_tree = x.m_tree; return *this; } + { return static_cast(this->base_t::operator=(static_cast(x))); } //! Effects: this->swap(x.get()). //! //! Complexity: Constant. set& operator=(BOOST_RV_REF(set) x) - { m_tree = boost::move(x.m_tree); return *this; } + { return static_cast(this->base_t::operator=(boost::move(static_cast(x)))); } + + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Returns a copy of the Allocator that //! was passed to the object's constructor. //! //! Complexity: Constant. - allocator_type get_allocator() const - { return m_tree.get_allocator(); } + allocator_type get_allocator() const; //! Effects: Returns a reference to the internal allocator. //! @@ -204,8 +203,7 @@ class set //! Complexity: Constant. //! //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const - { return m_tree.get_stored_allocator(); } + stored_allocator_type &get_stored_allocator(); //! Effects: Returns a reference to the internal allocator. //! @@ -214,46 +212,49 @@ class set //! Complexity: Constant. //! //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() - { return m_tree.get_stored_allocator(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + const stored_allocator_type &get_stored_allocator() const; //! Effects: Returns an iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant - iterator begin() - { return m_tree.begin(); } + iterator begin(); //! Effects: Returns a const_iterator to the first element contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator begin() const - { return m_tree.begin(); } + const_iterator begin() const; + + //! Effects: Returns a const_iterator to the first element contained in the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cbegin() const; //! Effects: Returns an iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - iterator end() - { return m_tree.end(); } + iterator end(); //! Effects: Returns a const_iterator to the end of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - const_iterator end() const - { return m_tree.end(); } + const_iterator end() const; + + //! Effects: Returns a const_iterator to the end of the container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_iterator cend() const; //! Effects: Returns a reverse_iterator pointing to the beginning //! of the reversed container. @@ -261,8 +262,7 @@ class set //! Throws: Nothing. //! //! Complexity: Constant. - reverse_iterator rbegin() - { return m_tree.rbegin(); } + reverse_iterator rbegin(); //! Effects: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. @@ -270,8 +270,15 @@ class set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator rbegin() const - { return m_tree.rbegin(); } + const_reverse_iterator rbegin() const; + + //! Effects: Returns a const_reverse_iterator pointing to the beginning + //! of the reversed container. + //! + //! Throws: Nothing. + //! + //! Complexity: Constant. + const_reverse_iterator crbegin() const; //! Effects: Returns a reverse_iterator pointing to the end //! of the reversed container. @@ -279,8 +286,7 @@ class set //! Throws: Nothing. //! //! Complexity: Constant. - reverse_iterator rend() - { return m_tree.rend(); } + reverse_iterator rend(); //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed container. @@ -288,33 +294,7 @@ class set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator rend() const - { return m_tree.rend(); } - - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const - { return m_tree.cbegin(); } - - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const - { return m_tree.cend(); } - - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const - { return m_tree.crbegin(); } + const_reverse_iterator rend() const; //! Effects: Returns a const_reverse_iterator pointing to the end //! of the reversed container. @@ -322,44 +302,29 @@ class set //! Throws: Nothing. //! //! Complexity: Constant. - const_reverse_iterator crend() const - { return m_tree.crend(); } - - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + const_reverse_iterator crend() const; //! Effects: Returns true if the container contains no elements. //! //! Throws: Nothing. //! //! Complexity: Constant. - bool empty() const - { return m_tree.empty(); } + bool empty() const; //! Effects: Returns the number of the elements contained in the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - size_type size() const - { return m_tree.size(); } + size_type size() const; //! Effects: Returns the largest possible size of the container. //! //! Throws: Nothing. //! //! Complexity: Constant. - size_type max_size() const - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// + size_type max_size() const; + #endif // #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) @@ -379,7 +344,7 @@ class set //! Complexity: Logarithmic. template std::pair emplace(Args&&... args) - { return m_tree.emplace_unique(boost::forward(args)...); } + { return this->base_t::emplace_unique(boost::forward(args)...); } //! Effects: Inserts an object of type Key constructed with //! std::forward(args)... if and only if there is @@ -392,19 +357,19 @@ class set //! Complexity: Logarithmic. template iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_unique(hint, boost::forward(args)...); } + { return this->base_t::emplace_hint_unique(hint, boost::forward(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ std::pair emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ + { return this->base_t::emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); }\ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_unique(hint \ + { return this->base_t::emplace_hint_unique(hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -470,7 +435,9 @@ class set //! Complexity: At most N log(size()+N) (N is the distance from first to last) template void insert(InputIterator first, InputIterator last) - { m_tree.insert_unique(first, last); } + { this->base_t::insert_unique(first, last); } + + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Erases the element pointed to by p. //! @@ -479,203 +446,197 @@ class set //! returns end(). //! //! Complexity: Amortized constant time - iterator erase(const_iterator p) - { return m_tree.erase(p); } + iterator erase(const_iterator p); //! Effects: Erases all elements in the container with key equivalent to x. //! //! Returns: Returns the number of erased elements. //! //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) - { return m_tree.erase(x); } + size_type erase(const key_type& x); //! Effects: Erases all the elements in the range [first, last). //! //! Returns: Returns last. //! //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) - { return m_tree.erase(first, last); } + iterator erase(const_iterator first, const_iterator last); //! Effects: Swaps the contents of *this and x. //! //! Throws: Nothing. //! //! Complexity: Constant. - void swap(set& x) - { m_tree.swap(x.m_tree); } + void swap(set& x); //! Effects: erase(a.begin(),a.end()). //! //! Postcondition: size() == 0. //! //! Complexity: linear in size(). - void clear() - { m_tree.clear(); } - - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// + void clear(); //! Effects: Returns the comparison object out //! of which a was constructed. //! //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } + key_compare key_comp() const; //! Effects: Returns an object of value_compare constructed out //! of the comparison object. //! //! Complexity: Constant. - value_compare value_comp() const - { return m_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// + value_compare value_comp() const; //! Returns: An iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } + iterator find(const key_type& x); //! Returns: Allocator const_iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } + const_iterator find(const key_type& x) const; + + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Returns: The number of elements with key equivalent to x. //! //! Complexity: log(size())+count(k) size_type count(const key_type& x) const - { return static_cast(m_tree.find(x) != m_tree.end()); } + { return static_cast(this->base_t::find(x) != this->base_t::cend()); } + + //! Returns: The number of elements with key equivalent to x. + //! + //! Complexity: log(size())+count(k) + size_type count(const key_type& x) + { return static_cast(this->base_t::find(x) != this->base_t::end()); } + + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Returns: An iterator pointing to the first element with key not less //! than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_tree.lower_bound(x); } + iterator lower_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than k, or a.end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } + const_iterator lower_bound(const key_type& x) const; //! Returns: An iterator pointing to the first element with key not less //! than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } + iterator upper_bound(const key_type& x); //! Returns: Allocator const iterator pointing to the first element with key not //! less than x, or end() if such an element is not found. //! //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } + const_iterator upper_bound(const key_type& x) const; + + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } + { return this->base_t::lower_bound_range(x); } //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! Complexity: Logarithmic std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } + { return this->base_t::lower_bound_range(x); } - /// @cond - template - friend bool operator== (const set&, const set&); + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - template - friend bool operator< (const set&, const set&); + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x); + //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). + //! + //! Complexity: Logarithmic + std::pair equal_range(const key_type& x) const; + + //! Effects: Rebalances the tree. It's a no-op for Red-Black and AVL trees. + //! + //! Complexity: Linear + void rebalance(); + + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const set& x, const set& y); + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const set& x, const set& y); + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const set& x, const set& y); + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const set& x, const set& y); + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const set& x, const set& y); + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const set& x, const set& y); + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(set& x, set& y); + + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: template std::pair priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_unique(::boost::forward(x)); } + { return this->base_t::insert_unique(::boost::forward(x)); } template iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_unique(p, ::boost::forward(x)); } - /// @endcond + { return this->base_t::insert_unique(p, ::boost::forward(x)); } + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const set& x, - const set& y) -{ return x.m_tree == y.m_tree; } - -template -inline bool operator<(const set& x, - const set& y) -{ return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const set& x, - const set& y) -{ return !(x == y); } - -template -inline bool operator>(const set& x, - const set& y) -{ return y < x; } - -template -inline bool operator<=(const set& x, - const set& y) -{ return !(y < x); } - -template -inline bool operator>=(const set& x, - const set& y) -{ return !(x < y); } - -template -inline void swap(set& x, set& y) -{ x.swap(y); } - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { //!has_trivial_destructor_after_move<> == true_type //!specialization for optimizations -template -struct has_trivial_destructor_after_move > +template +struct has_trivial_destructor_after_move > { static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; }; namespace container { -// Forward declaration of operators < and ==, needed for friend declaration. +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED -template -inline bool operator==(const multiset& x, - const multiset& y); - -template -inline bool operator<(const multiset& x, - const multiset& y); -/// @endcond +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED //! A multiset is a kind of associative container that supports equivalent keys //! (possibly contains multiple copies of the same key value) and provides for @@ -684,20 +645,27 @@ inline bool operator<(const multiset& x, //! A multiset satisfies all of the requirements of a container and of a reversible //! container, and of an associative container). multiset also provides most operations //! described for duplicate keys. -#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED -template , class Allocator = std::allocator > +//! +//! \tparam Key is the type to be inserted in the set, which is also the key_type +//! \tparam Compare is the comparison functor used to order keys +//! \tparam Allocator is the allocator to be used to allocate memory for this container +//! \tparam MultiSetOptions is an packed option type generated using using boost::container::tree_assoc_options. +template , class Allocator = std::allocator, class MultiSetOptions = tree_assoc_defaults > #else -template +template #endif class multiset -{ /// @cond + : public container_detail::tree + , Compare, Allocator, MultiSetOptions> + /// @endcond +{ + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(multiset) - typedef container_detail::rbtree, Compare, Allocator> tree_t; - tree_t m_tree; // red-black tree representing multiset - /// @endcond + typedef container_detail::tree + , Compare, Allocator, MultiSetOptions> base_t; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: @@ -717,11 +685,11 @@ class multiset typedef typename ::boost::container::allocator_traits::size_type size_type; typedef typename ::boost::container::allocator_traits::difference_type difference_type; typedef Allocator allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; - typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::stored_allocator_type) stored_allocator_type; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::iterator) iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_iterator) const_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::reverse_iterator) reverse_iterator; + typedef typename BOOST_CONTAINER_IMPDEF(base_t::const_reverse_iterator) const_reverse_iterator; ////////////////////////////////////////////// // @@ -729,40 +697,28 @@ class multiset // ////////////////////////////////////////////// - //! Effects: Constructs an empty multiset using the specified comparison - //! object and allocator. - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::set::set() multiset() - : m_tree() + : base_t() {} - //! Effects: Constructs an empty multiset using the specified comparison - //! object and allocator. - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::set::set(const Compare&, const allocator_type&) explicit multiset(const Compare& comp, const allocator_type& a = allocator_type()) - : m_tree(comp, a) + : base_t(comp, a) {} - //! Effects: Constructs an empty multiset using the specified allocator. - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::set::set(const allocator_type&) explicit multiset(const allocator_type& a) - : m_tree(a) + : base_t(a) {} - //! Effects: Constructs an empty multiset using the specified comparison object - //! and allocator, and inserts elements from the range [first ,last ). - //! - //! Complexity: Linear in N if the range [first ,last ) is already sorted using - //! comp and otherwise N logN, where N is last - first. + //! @copydoc ::boost::container::set::set(InputIterator, InputIterator, const Compare& comp, const allocator_type&) template multiset(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) - : m_tree(false, first, last, comp, a) + : base_t(false, first, last, comp, a) {} //! Effects: Constructs an empty multiset using the specified comparison object and @@ -778,224 +734,94 @@ class multiset multiset( ordered_range_t, InputIterator first, InputIterator last , const Compare& comp = Compare() , const allocator_type& a = allocator_type()) - : m_tree(ordered_range, first, last, comp, a) + : base_t(ordered_range, first, last, comp, a) {} - //! Effects: Copy constructs a multiset. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::set::set(const set &) multiset(const multiset& x) - : m_tree(x.m_tree) + : base_t(static_cast(x)) {} - //! Effects: Move constructs a multiset. Constructs *this using x's resources. - //! - //! Complexity: Constant. - //! - //! Postcondition: x is emptied. + //! @copydoc ::boost::container::set(set &&) multiset(BOOST_RV_REF(multiset) x) - : m_tree(boost::move(x.m_tree)) + : base_t(boost::move(static_cast(x))) {} - //! Effects: Copy constructs a multiset using the specified allocator. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::set(const set &, const allocator_type &) multiset(const multiset& x, const allocator_type &a) - : m_tree(x.m_tree, a) + : base_t(static_cast(x), a) {} - //! Effects: Move constructs a multiset using the specified allocator. - //! Constructs *this using x's resources. - //! - //! Complexity: Constant if a == x.get_allocator(), linear otherwise. - //! - //! Postcondition: x is emptied. + //! @copydoc ::boost::container::set(set &&, const allocator_type &) multiset(BOOST_RV_REF(multiset) x, const allocator_type &a) - : m_tree(boost::move(x.m_tree), a) + : base_t(boost::move(static_cast(x)), a) {} - //! Effects: Makes *this a copy of x. - //! - //! Complexity: Linear in x.size(). + //! @copydoc ::boost::container::set::operator=(const set &) multiset& operator=(BOOST_COPY_ASSIGN_REF(multiset) x) - { m_tree = x.m_tree; return *this; } + { return static_cast(this->base_t::operator=(static_cast(x))); } - //! Effects: this->swap(x.get()). - //! - //! Complexity: Constant. + //! @copydoc ::boost::container::set::operator=(set &&) multiset& operator=(BOOST_RV_REF(multiset) x) - { m_tree = boost::move(x.m_tree); return *this; } + { return static_cast(this->base_t::operator=(boost::move(static_cast(x)))); } - //! Effects: Returns a copy of the Allocator that - //! was passed to the object's constructor. - //! - //! Complexity: Constant. - allocator_type get_allocator() const - { return m_tree.get_allocator(); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - stored_allocator_type &get_stored_allocator() - { return m_tree.get_stored_allocator(); } + //! @copydoc ::boost::container::set::get_allocator() + allocator_type get_allocator() const; - //! Effects: Returns a reference to the internal allocator. - //! - //! Throws: Nothing - //! - //! Complexity: Constant. - //! - //! Note: Non-standard extension. - const stored_allocator_type &get_stored_allocator() const - { return m_tree.get_stored_allocator(); } + //! @copydoc ::boost::container::set::get_stored_allocator() + stored_allocator_type &get_stored_allocator(); - ////////////////////////////////////////////// - // - // iterators - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::set::get_stored_allocator() const + const stored_allocator_type &get_stored_allocator() const; - //! Effects: Returns an iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator begin() - { return m_tree.begin(); } + //! @copydoc ::boost::container::set::begin() + iterator begin(); - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator begin() const - { return m_tree.begin(); } + //! @copydoc ::boost::container::set::begin() const + const_iterator begin() const; - //! Effects: Returns an iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - iterator end() - { return m_tree.end(); } + //! @copydoc ::boost::container::set::cbegin() const + const_iterator cbegin() const; - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator end() const - { return m_tree.end(); } + //! @copydoc ::boost::container::set::end() + iterator end() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rbegin() - { return m_tree.rbegin(); } + //! @copydoc ::boost::container::set::end() const + const_iterator end() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rbegin() const - { return m_tree.rbegin(); } + //! @copydoc ::boost::container::set::cend() const + const_iterator cend() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - reverse_iterator rend() - { return m_tree.rend(); } + //! @copydoc ::boost::container::set::rbegin() + reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator rend() const - { return m_tree.rend(); } + //! @copydoc ::boost::container::set::rbegin() const + const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the first element contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cbegin() const - { return m_tree.cbegin(); } + //! @copydoc ::boost::container::set::crbegin() const + const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_iterator to the end of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_iterator cend() const - { return m_tree.cend(); } + //! @copydoc ::boost::container::set::rend() + reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the beginning - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crbegin() const - { return m_tree.crbegin(); } + //! @copydoc ::boost::container::set::rend() const + const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT; - //! Effects: Returns a const_reverse_iterator pointing to the end - //! of the reversed container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - const_reverse_iterator crend() const - { return m_tree.crend(); } + //! @copydoc ::boost::container::set::crend() const + const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT; - ////////////////////////////////////////////// - // - // capacity - // - ////////////////////////////////////////////// + //! @copydoc ::boost::container::set::empty() const + bool empty() const; - //! Effects: Returns true if the container contains no elements. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - bool empty() const - { return m_tree.empty(); } + //! @copydoc ::boost::container::set::size() const + size_type size() const; - //! Effects: Returns the number of the elements contained in the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type size() const - { return m_tree.size(); } + //! @copydoc ::boost::container::set::max_size() const + size_type max_size() const; - //! Effects: Returns the largest possible size of the container. - //! - //! Throws: Nothing. - //! - //! Complexity: Constant. - size_type max_size() const - { return m_tree.max_size(); } - - ////////////////////////////////////////////// - // - // modifiers - // - ////////////////////////////////////////////// + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) @@ -1006,7 +832,7 @@ class multiset //! Complexity: Logarithmic. template iterator emplace(Args&&... args) - { return m_tree.emplace_equal(boost::forward(args)...); } + { return this->base_t::emplace_equal(boost::forward(args)...); } //! Effects: Inserts an object of type Key constructed with //! std::forward(args)... @@ -1018,19 +844,19 @@ class multiset //! is inserted right before p. template iterator emplace_hint(const_iterator hint, Args&&... args) - { return m_tree.emplace_hint_equal(hint, boost::forward(args)...); } + { return this->base_t::emplace_hint_equal(hint, boost::forward(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ + { return this->base_t::emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ - { return m_tree.emplace_hint_equal(hint \ + { return this->base_t::emplace_hint_equal(hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _));} \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -1038,9 +864,6 @@ class multiset #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING - - - #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! Effects: Inserts x and returns the iterator pointing to the //! newly inserted element. @@ -1091,204 +914,126 @@ class multiset //! Complexity: At most N log(size()+N) (N is the distance from first to last) template void insert(InputIterator first, InputIterator last) - { m_tree.insert_equal(first, last); } + { this->base_t::insert_equal(first, last); } - //! Effects: Erases the element pointed to by p. - //! - //! Returns: Returns an iterator pointing to the element immediately - //! following q prior to the element being erased. If no such element exists, - //! returns end(). - //! - //! Complexity: Amortized constant time - iterator erase(const_iterator p) - { return m_tree.erase(p); } + #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - //! Effects: Erases all elements in the container with key equivalent to x. - //! - //! Returns: Returns the number of erased elements. - //! - //! Complexity: log(size()) + count(k) - size_type erase(const key_type& x) - { return m_tree.erase(x); } + //! @copydoc ::boost::container::set::erase(const_iterator) + iterator erase(const_iterator p); - //! Effects: Erases all the elements in the range [first, last). - //! - //! Returns: Returns last. - //! - //! Complexity: log(size())+N where N is the distance from first to last. - iterator erase(const_iterator first, const_iterator last) - { return m_tree.erase(first, last); } + //! @copydoc ::boost::container::set::erase(const key_type&) + size_type erase(const key_type& x); - //! Effects: Swaps the contents of *this and x. + //! @copydoc ::boost::container::set::erase(const_iterator,const_iterator) + iterator erase(const_iterator first, const_iterator last); + + //! @copydoc ::boost::container::set::swap + void swap(flat_multiset& x); + + //! @copydoc ::boost::container::set::clear + void clear() BOOST_CONTAINER_NOEXCEPT; + + //! @copydoc ::boost::container::set::key_comp + key_compare key_comp() const; + + //! @copydoc ::boost::container::set::value_comp + value_compare value_comp() const; + + //! @copydoc ::boost::container::set::find(const key_type& ) + iterator find(const key_type& x); + + //! @copydoc ::boost::container::set::find(const key_type& ) const + const_iterator find(const key_type& x) const; + + //! @copydoc ::boost::container::set::count(const key_type& ) const + size_type count(const key_type& x) const; + + //! @copydoc ::boost::container::set::lower_bound(const key_type& ) + iterator lower_bound(const key_type& x); + + //! @copydoc ::boost::container::set::lower_bound(const key_type& ) const + const_iterator lower_bound(const key_type& x) const; + + //! @copydoc ::boost::container::set::upper_bound(const key_type& ) + iterator upper_bound(const key_type& x); + + //! @copydoc ::boost::container::set::upper_bound(const key_type& ) const + const_iterator upper_bound(const key_type& x) const; + + //! @copydoc ::boost::container::set::equal_range(const key_type& ) const + std::pair equal_range(const key_type& x) const; + + //! @copydoc ::boost::container::set::equal_range(const key_type& ) + std::pair equal_range(const key_type& x); + + //! @copydoc ::boost::container::set::rebalance() + void rebalance(); + + //! Effects: Returns true if x and y are equal //! - //! Throws: Nothing. + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const multiset& x, const multiset& y); + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const multiset& x, const multiset& y); + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const multiset& x, const multiset& y); + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const multiset& x, const multiset& y); + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const multiset& x, const multiset& y); + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const multiset& x, const multiset& y); + + //! Effects: x.swap(y) //! //! Complexity: Constant. - void swap(multiset& x) - { m_tree.swap(x.m_tree); } + friend void swap(multiset& x, multiset& y); - //! Effects: erase(a.begin(),a.end()). - //! - //! Postcondition: size() == 0. - //! - //! Complexity: linear in size(). - void clear() - { m_tree.clear(); } + #endif //#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) - ////////////////////////////////////////////// - // - // observers - // - ////////////////////////////////////////////// - - //! Effects: Returns the comparison object out - //! of which a was constructed. - //! - //! Complexity: Constant. - key_compare key_comp() const - { return m_tree.key_comp(); } - - //! Effects: Returns an object of value_compare constructed out - //! of the comparison object. - //! - //! Complexity: Constant. - value_compare value_comp() const - { return m_tree.key_comp(); } - - ////////////////////////////////////////////// - // - // set operations - // - ////////////////////////////////////////////// - - //! Returns: An iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - iterator find(const key_type& x) - { return m_tree.find(x); } - - //! Returns: Allocator const iterator pointing to an element with the key - //! equivalent to x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic. - const_iterator find(const key_type& x) const - { return m_tree.find(x); } - - //! Returns: The number of elements with key equivalent to x. - //! - //! Complexity: log(size())+count(k) - size_type count(const key_type& x) const - { return m_tree.count(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator lower_bound(const key_type& x) - { return m_tree.lower_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than k, or a.end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator lower_bound(const key_type& x) const - { return m_tree.lower_bound(x); } - - //! Returns: An iterator pointing to the first element with key not less - //! than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - iterator upper_bound(const key_type& x) - { return m_tree.upper_bound(x); } - - //! Returns: Allocator const iterator pointing to the first element with key not - //! less than x, or end() if such an element is not found. - //! - //! Complexity: Logarithmic - const_iterator upper_bound(const key_type& x) const - { return m_tree.upper_bound(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) - { return m_tree.equal_range(x); } - - //! Effects: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). - //! - //! Complexity: Logarithmic - std::pair equal_range(const key_type& x) const - { return m_tree.equal_range(x); } - - /// @cond - template - friend bool operator== (const multiset&, - const multiset&); - template - friend bool operator< (const multiset&, - const multiset&); + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: template iterator priv_insert(BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_equal(::boost::forward(x)); } + { return this->base_t::insert_equal(::boost::forward(x)); } template iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) - { return m_tree.insert_equal(p, ::boost::forward(x)); } + { return this->base_t::insert_equal(p, ::boost::forward(x)); } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool operator==(const multiset& x, - const multiset& y) -{ return x.m_tree == y.m_tree; } - -template -inline bool operator<(const multiset& x, - const multiset& y) -{ return x.m_tree < y.m_tree; } - -template -inline bool operator!=(const multiset& x, - const multiset& y) -{ return !(x == y); } - -template -inline bool operator>(const multiset& x, - const multiset& y) -{ return y < x; } - -template -inline bool operator<=(const multiset& x, - const multiset& y) -{ return !(y < x); } - -template -inline bool operator>=(const multiset& x, - const multiset& y) -{ return !(x < y); } - -template -inline void swap(multiset& x, multiset& y) -{ x.swap(y); } - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED } //namespace container { //!has_trivial_destructor_after_move<> == true_type //!specialization for optimizations -template -struct has_trivial_destructor_after_move > +template +struct has_trivial_destructor_after_move > { static const bool value = has_trivial_destructor_after_move::value && has_trivial_destructor_after_move::value; }; namespace container { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }} diff --git a/include/boost/container/slist.hpp b/include/boost/container/slist.hpp index 9d2d761..eede912 100644 --- a/include/boost/container/slist.hpp +++ b/include/boost/container/slist.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -48,7 +48,7 @@ namespace boost { namespace container { -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED template class slist; @@ -106,7 +106,7 @@ struct intrusive_slist_type } //namespace container_detail { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! An slist is a singly linked list: a list where each element is linked to the next //! element, but not to the previous element. That is, it is a Sequence that @@ -140,6 +140,9 @@ struct intrusive_slist_type //! possible. If you find that insert_after and erase_after aren't adequate for your //! needs, and that you often need to use insert and erase in the middle of the list, //! then you should probably use list instead of slist. +//! +//! \tparam T The type of object that is stored in the list +//! \tparam Allocator The allocator used for all internal memory management #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template > #else @@ -149,7 +152,7 @@ class slist : protected container_detail::node_alloc_holder ::type> { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED typedef typename container_detail::intrusive_slist_type::type Icont; typedef container_detail::node_alloc_holder AllocHolder; @@ -195,7 +198,7 @@ class slist BOOST_COPYABLE_AND_MOVABLE(slist) typedef container_detail::iterator iterator_impl; typedef container_detail::iterator const_iterator_impl; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -313,7 +316,7 @@ class slist this->icont().swap(x.icont()); } else{ - this->insert(this->cbegin(), x.begin(), x.end()); + this->insert_after(this->cbefore_begin(), x.begin(), x.end()); } } @@ -1423,14 +1426,70 @@ class slist void splice(const_iterator p, BOOST_RV_REF(slist) x, const_iterator first, const_iterator last) BOOST_CONTAINER_NOEXCEPT { this->splice(p, static_cast(x), first, last); } - /// @cond + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const slist& x, const slist& y) + { + if(x.size() != y.size()){ + return false; + } + typedef typename slist::const_iterator const_iterator; + const_iterator end1 = x.end(); + + const_iterator i1 = x.begin(); + const_iterator i2 = y.begin(); + while (i1 != end1 && *i1 == *i2){ + ++i1; + ++i2; + } + return i1 == end1; + } + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const slist& x, const slist& y) + { return !(x == y); } + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const slist& x, const slist& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const slist& x, const slist& y) + { return y < x; } + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const slist& x, const slist& y) + { return !(y < x); } + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const slist& x, const slist& y) + { return !(x < y); } + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(slist& x, slist& y) + { x.swap(y); } + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: void priv_push_front (const T &x) - { this->insert(this->cbegin(), x); } + { this->insert_after(this->cbefore_begin(), x); } void priv_push_front (BOOST_RV_REF(T) x) - { this->insert(this->cbegin(), ::boost::move(x)); } + { this->insert_after(this->cbefore_begin(), ::boost::move(x)); } bool priv_try_shrink(size_type new_size, const_iterator &last_pos) { @@ -1505,63 +1564,12 @@ class slist const value_type &m_ref; }; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool -operator==(const slist& x, const slist& y) -{ - if(x.size() != y.size()){ - return false; - } - typedef typename slist::const_iterator const_iterator; - const_iterator end1 = x.end(); - - const_iterator i1 = x.begin(); - const_iterator i2 = y.begin(); - while (i1 != end1 && *i1 == *i2){ - ++i1; - ++i2; - } - return i1 == end1; -} - -template -inline bool -operator<(const slist& sL1, const slist& sL2) -{ - return std::lexicographical_compare - (sL1.begin(), sL1.end(), sL2.begin(), sL2.end()); -} - -template -inline bool -operator!=(const slist& sL1, const slist& sL2) - { return !(sL1 == sL2); } - -template -inline bool -operator>(const slist& sL1, const slist& sL2) - { return sL2 < sL1; } - -template -inline bool -operator<=(const slist& sL1, const slist& sL2) - { return !(sL2 < sL1); } - -template -inline bool -operator>=(const slist& sL1, const slist& sL2) - { return !(sL1 < sL2); } - -template -inline void swap(slist& x, slist& y) - { x.swap(y); } - }} -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { @@ -1574,14 +1582,14 @@ struct has_trivial_destructor_after_move > namespace container { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }} //namespace boost{ namespace container { // Specialization of insert_iterator so that insertions will be constant // time rather than linear time. -///@cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //Ummm, I don't like to define things in namespace std, but //there is no other way @@ -1620,7 +1628,7 @@ class insert_iterator > } //namespace std; -///@endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #include diff --git a/include/boost/container/stable_vector.hpp b/include/boost/container/stable_vector.hpp index 7b31cc4..84e6d7c 100644 --- a/include/boost/container/stable_vector.hpp +++ b/include/boost/container/stable_vector.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2008-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2008-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -47,18 +47,18 @@ #include #include //placement new -///@cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #include //#define STABLE_VECTOR_ENABLE_INVARIANT_CHECKING -///@endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { namespace container { -///@cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace stable_vector_detail{ @@ -393,7 +393,7 @@ struct index_traits #endif //#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! Originally developed by Joaquin M. Lopez Munoz, stable_vector is a std::vector //! drop-in replacement implemented as a node container, offering iterator and reference @@ -426,6 +426,9 @@ struct index_traits //! //! Exception safety: As stable_vector does not internally copy elements around, some //! operations provide stronger exception safety guarantees than in std::vector. +//! +//! \tparam T The type of object that is stored in the stable_vector +//! \tparam Allocator The allocator used for all internal memory management #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template > #else @@ -433,7 +436,7 @@ template #endif class stable_vector { - ///@cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED typedef allocator_traits allocator_traits_type; typedef boost::intrusive:: pointer_traits @@ -504,7 +507,7 @@ class stable_vector typedef stable_vector_detail::iterator < typename allocator_traits::pointer , false> const_iterator_impl; - ///@endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -526,7 +529,7 @@ class stable_vector typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - ///@cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(stable_vector) static const size_type ExtraPointers = index_traits_type::ExtraPointers; @@ -536,7 +539,7 @@ class stable_vector class push_back_rollback; friend class push_back_rollback; - ///@endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -1510,8 +1513,49 @@ class stable_vector void clear() BOOST_CONTAINER_NOEXCEPT { this->erase(this->cbegin(),this->cend()); } - /// @cond + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const stable_vector& x, const stable_vector& y) + { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const stable_vector& x, const stable_vector& y) + { return !(x == y); } + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const stable_vector& x, const stable_vector& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const stable_vector& x, const stable_vector& y) + { return y < x; } + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const stable_vector& x, const stable_vector& y) + { return !(y < x); } + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const stable_vector& x, const stable_vector& y) + { return !(x < y); } + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(stable_vector& x, stable_vector& y) + { x.swap(y); } + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: class insert_rollback @@ -1836,58 +1880,14 @@ class stable_vector const node_allocator_type &priv_node_alloc() const { return internal_data; } index_type index; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -bool operator==(const stable_vector& x,const stable_vector& y) -{ - return x.size()==y.size()&&std::equal(x.begin(),x.end(),y.begin()); -} - -template -bool operator< (const stable_vector& x,const stable_vector& y) -{ - return std::lexicographical_compare(x.begin(),x.end(),y.begin(),y.end()); -} - -template -bool operator!=(const stable_vector& x,const stable_vector& y) -{ - return !(x==y); -} - -template -bool operator> (const stable_vector& x,const stable_vector& y) -{ - return y -bool operator>=(const stable_vector& x,const stable_vector& y) -{ - return !(x -bool operator<=(const stable_vector& x,const stable_vector& y) -{ - return !(x>y); -} - -// specialized algorithms: - -template -void swap(stable_vector& x,stable_vector& y) -{ - x.swap(y); -} - -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #undef STABLE_VECTOR_CHECK_INVARIANT -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED /* diff --git a/include/boost/container/static_vector.hpp b/include/boost/container/static_vector.hpp index 6ca0f4f..19e27f5 100644 --- a/include/boost/container/static_vector.hpp +++ b/include/boost/container/static_vector.hpp @@ -21,6 +21,8 @@ namespace boost { namespace container { +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + namespace container_detail { template @@ -61,46 +63,46 @@ class static_storage_allocator } //namespace container_detail { -/** - * @defgroup static_vector_non_member static_vector non-member functions - */ +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED -/** - * @brief A variable-size array container with fixed capacity. - * - * static_vector is a sequence container like boost::container::vector with contiguous storage that can - * change in size, along with the static allocation, low overhead, and fixed capacity of boost::array. - * - * A static_vector is a sequence that supports random access to elements, constant time insertion and - * removal of elements at the end, and linear time insertion and removal of elements at the beginning or - * in the middle. The number of elements in a static_vector may vary dynamically up to a fixed capacity - * because elements are stored within the object itself similarly to an array. However, objects are - * initialized as they are inserted into static_vector unlike C arrays or std::array which must construct - * all elements on instantiation. The behavior of static_vector enables the use of statically allocated - * elements in cases with complex object lifetime requirements that would otherwise not be trivially - * possible. - * - * @par Error Handling - * Insertion beyond the capacity result in throwing std::bad_alloc() if exceptions are enabled or - * calling throw_bad_alloc() if not enabled. - * - * std::out_of_range is thrown if out of bound access is performed in `at()` if exceptions are - * enabled, throw_out_of_range() if not enabled. - * - * @tparam Value The type of element that will be stored. - * @tparam Capacity The maximum number of elements static_vector can store, fixed at compile time. - */ +//! +//!@brief A variable-size array container with fixed capacity. +//! +//!static_vector is a sequence container like boost::container::vector with contiguous storage that can +//!change in size, along with the static allocation, low overhead, and fixed capacity of boost::array. +//! +//!A static_vector is a sequence that supports random access to elements, constant time insertion and +//!removal of elements at the end, and linear time insertion and removal of elements at the beginning or +//!in the middle. The number of elements in a static_vector may vary dynamically up to a fixed capacity +//!because elements are stored within the object itself similarly to an array. However, objects are +//!initialized as they are inserted into static_vector unlike C arrays or std::array which must construct +//!all elements on instantiation. The behavior of static_vector enables the use of statically allocated +//!elements in cases with complex object lifetime requirements that would otherwise not be trivially +//!possible. +//! +//!@par Error Handling +//! Insertion beyond the capacity result in throwing std::bad_alloc() if exceptions are enabled or +//! calling throw_bad_alloc() if not enabled. +//! +//! std::out_of_range is thrown if out of bound access is performed in at() if exceptions are +//! enabled, throw_out_of_range() if not enabled. +//! +//!@tparam Value The type of element that will be stored. +//!@tparam Capacity The maximum number of elements static_vector can store, fixed at compile time. template class static_vector : public vector > { - typedef vector > base_t; + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + typedef vector > base_t; - BOOST_COPYABLE_AND_MOVABLE(static_vector) + BOOST_COPYABLE_AND_MOVABLE(static_vector) template friend class static_vector; + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED + public: //! @brief The type of elements stored in the container. typedef typename base_t::value_type value_type; diff --git a/include/boost/container/string.hpp b/include/boost/container/string.hpp index e006326..95187ee 100644 --- a/include/boost/container/string.hpp +++ b/include/boost/container/string.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -52,7 +52,7 @@ namespace boost { namespace container { -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace container_detail { // ------------------------------------------------------------ // Class basic_string_base. @@ -268,7 +268,12 @@ class basic_string_base } size_type next_capacity(size_type additional_objects) const - { return get_next_capacity(allocator_traits_type::max_size(this->alloc()), this->priv_storage(), additional_objects); } + { + return next_capacity_calculator + :: + get( allocator_traits_type::max_size(this->alloc()) + , this->priv_storage(), additional_objects ); + } void deallocate(pointer p, size_type n) { @@ -433,7 +438,7 @@ class basic_string_base } //namespace container_detail { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! The basic_string class represents a Sequence of characters. It contains all the //! usual operations of a Sequence, and, additionally, it contains standard string @@ -463,6 +468,10 @@ class basic_string_base //! end(), rbegin(), rend(), operator[], c_str(), and data() do not invalidate iterators. //! In this implementation, iterators are only invalidated by member functions that //! explicitly change the string's contents. +//! +//! \tparam CharT The type of character it contains. +//! \tparam Traits The Character Traits type, which encapsulates basic character operations +//! \tparam Allocator The allocator, used for internal memory management. #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template , class Allocator = std::allocator > #else @@ -471,7 +480,7 @@ template class basic_string : private container_detail::basic_string_base { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: typedef allocator_traits allocator_traits_type; BOOST_COPYABLE_AND_MOVABLE(basic_string) @@ -483,19 +492,22 @@ class basic_string template struct Eq_traits - : public std::binary_function { - bool operator()(const typename Tr::char_type& x, - const typename Tr::char_type& y) const + //Compatibility with std::binary_function + typedef typename Tr::char_type first_argument_type; + typedef typename Tr::char_type second_argument_type; + typedef bool result_type; + + bool operator()(const first_argument_type& x, const second_argument_type& y) const { return Tr::eq(x, y); } }; template struct Not_within_traits - : public std::unary_function { + typedef typename Tr::char_type argument_type; + typedef bool result_type; + typedef const typename Tr::char_type* Pointer; const Pointer m_first; const Pointer m_last; @@ -509,7 +521,7 @@ class basic_string std::bind1st(Eq_traits(), x)) == m_last; } }; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -533,14 +545,14 @@ class basic_string typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; static const size_type npos = size_type(-1); - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: typedef constant_iterator cvalue_iterator; typedef typename base_t::allocator_v1 allocator_v1; typedef typename base_t::allocator_v2 allocator_v2; typedef typename base_t::alloc_version alloc_version; typedef ::boost::intrusive::pointer_traits pointer_traits; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: // Constructor, destructor, assignment. ////////////////////////////////////////////// @@ -548,7 +560,7 @@ class basic_string // construct/copy/destroy // ////////////////////////////////////////////// - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED struct reserve_t {}; basic_string(reserve_t, size_type n, @@ -559,7 +571,7 @@ class basic_string , n + 1) { this->priv_terminate_string(); } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //! Effects: Default constructs a basic_string. //! @@ -668,6 +680,15 @@ class basic_string this->assign(n, c); } + //! Effects: Constructs a basic_string taking the allocator as parameter, + //! and is initialized by n default-initialized characters. + basic_string(size_type n, default_init_t, const allocator_type& a = allocator_type()) + : base_t(a, n + 1) + { + this->priv_size(n); + this->priv_terminate_string(); + } + //! Effects: Constructs a basic_string taking the allocator as parameter, //! and a range of iterators. template @@ -945,6 +966,26 @@ class basic_string void resize(size_type n) { resize(n, CharT()); } + + //! Effects: Inserts or erases elements at the end such that + //! the size becomes n. New elements are uninitialized. + //! + //! Throws: If memory allocation throws + //! + //! Complexity: Linear to the difference between size() and new_size. + //! + //! Note: Non-standard extension + void resize(size_type n, default_init_t) + { + if (n <= this->size()) + this->erase(this->begin() + n, this->end()); + else{ + this->priv_reserve(n, false); + this->priv_size(n); + this->priv_terminate_string(); + } + } + //! Effects: Number of elements for which memory has been allocated. //! capacity() is always greater than or equal to size(). //! @@ -961,29 +1002,7 @@ class basic_string //! //! Throws: If memory allocation allocation throws void reserve(size_type res_arg) - { - if (res_arg > this->max_size()){ - throw_length_error("basic_string::reserve max_size() exceeded"); - } - - if (this->capacity() < res_arg){ - size_type n = container_detail::max_value(res_arg, this->size()) + 1; - size_type new_cap = this->next_capacity(n); - pointer new_start = this->allocation_command - (allocate_new, n, new_cap, new_cap).first; - size_type new_length = 0; - - const pointer addr = this->priv_addr(); - new_length += priv_uninitialized_copy - (addr, addr + this->priv_size(), new_start); - this->priv_construct_null(new_start + new_length); - this->deallocate_block(); - this->is_short(false); - this->priv_long_addr(new_start); - this->priv_long_size(new_length); - this->priv_storage(new_cap); - } - } + { this->priv_reserve(res_arg); } //! Effects: Tries to deallocate the excess of memory created //! with previous allocations. The size of the string is unchanged @@ -1228,6 +1247,20 @@ class basic_string basic_string& assign(size_type n, CharT c) { return this->assign(cvalue_iterator(c, n), cvalue_iterator()); } + //! Effects: Equivalent to assign(basic_string(first, last)). + //! + //! Returns: *this + basic_string& assign(const CharT* first, const CharT* last) + { + size_type n = static_cast(last - first); + this->reserve(n); + CharT* ptr = container_detail::to_raw_pointer(this->priv_addr()); + Traits::copy(ptr, first, n); + this->priv_construct_null(ptr + n); + this->priv_size(n); + return *this; + } + //! Effects: Equivalent to assign(basic_string(first, last)). //! //! Returns: *this @@ -2296,8 +2329,35 @@ class basic_string int compare(size_type pos1, size_type n1, const CharT* s) const { return this->compare(pos1, n1, s, Traits::length(s)); } - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: + void priv_reserve(size_type res_arg, const bool null_terminate = true) + { + if (res_arg > this->max_size()){ + throw_length_error("basic_string::reserve max_size() exceeded"); + } + + if (this->capacity() < res_arg){ + size_type n = container_detail::max_value(res_arg, this->size()) + 1; + size_type new_cap = this->next_capacity(n); + pointer new_start = this->allocation_command + (allocate_new, n, new_cap, new_cap).first; + size_type new_length = 0; + + const pointer addr = this->priv_addr(); + new_length += priv_uninitialized_copy + (addr, addr + this->priv_size(), new_start); + if(null_terminate){ + this->priv_construct_null(new_start + new_length); + } + this->deallocate_block(); + this->is_short(false); + this->priv_long_addr(new_start); + this->priv_long_size(new_length); + this->priv_storage(new_cap); + } + } + static int s_compare(const_pointer f1, const_pointer l1, const_pointer f2, const_pointer l2) { @@ -2431,9 +2491,11 @@ class basic_string return this->priv_replace(first, last, f, l, Category()); } - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; +#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED + //!Typedef for a basic_string of //!narrow characters typedef basic_string @@ -2450,6 +2512,8 @@ typedef basic_string ,std::allocator > wstring; +#endif + // ------------------------------------------------------------ // Non-member functions. @@ -2663,7 +2727,7 @@ template inline void swap(basic_string& x, basic_string& y) { x.swap(y); } -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED // I/O. namespace container_detail { @@ -2683,7 +2747,7 @@ string_fill(std::basic_ostream& os, } } //namespace container_detail { -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED template std::basic_ostream& @@ -2814,7 +2878,7 @@ inline std::size_t hash_value(basic_string, Allocator> }} -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { @@ -2827,7 +2891,7 @@ struct has_trivial_destructor_after_move diff --git a/include/boost/container/throw_exception.hpp b/include/boost/container/throw_exception.hpp index 7c821c0..ab01c30 100644 --- a/include/boost/container/throw_exception.hpp +++ b/include/boost/container/throw_exception.hpp @@ -76,26 +76,82 @@ namespace container { #else //defined(BOOST_NO_EXCEPTIONS) + //! Exception callback called by Boost.Container when fails to allocate the requested storage space. + //!

inline void throw_bad_alloc() { throw std::bad_alloc(); } + //! Exception callback called by Boost.Container to signal arguments out of range. + //!
    + //!
  • If BOOST_NO_EXCEPTIONS is NOT defined std::out_of_range(str) is thrown.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS + //! is NOT defined BOOST_ASSERT_MSG(!"boost::container out_of_range thrown", str) is called + //! and std::abort() if the former returns.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined + //! the user must provide an implementation and the function should not return.
  • + //!
inline void throw_out_of_range(const char* str) { throw std::out_of_range(str); } + //! Exception callback called by Boost.Container to signal errors resizing. + //!
    + //!
  • If BOOST_NO_EXCEPTIONS is NOT defined std::length_error(str) is thrown.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS + //! is NOT defined BOOST_ASSERT_MSG(!"boost::container length_error thrown", str) is called + //! and std::abort() if the former returns.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined + //! the user must provide an implementation and the function should not return.
  • + //!
inline void throw_length_error(const char* str) { throw std::length_error(str); } + //! Exception callback called by Boost.Container to report errors in the internal logical + //! of the program, such as violation of logical preconditions or class invariants. + //!
    + //!
  • If BOOST_NO_EXCEPTIONS is NOT defined std::logic_error(str) is thrown.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS + //! is NOT defined BOOST_ASSERT_MSG(!"boost::container logic_error thrown", str) is called + //! and std::abort() if the former returns.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined + //! the user must provide an implementation and the function should not return.
  • + //!
inline void throw_logic_error(const char* str) { throw std::logic_error(str); } + //! Exception callback called by Boost.Container to report errors that can only be detected during runtime. + //!
    + //!
  • If BOOST_NO_EXCEPTIONS is NOT defined std::runtime_error(str) is thrown.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS is defined and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS + //! is NOT defined BOOST_ASSERT_MSG(!"boost::container runtime_error thrown", str) is called + //! and std::abort() if the former returns.
  • + //! + //!
  • If BOOST_NO_EXCEPTIONS and BOOST_CONTAINER_USER_DEFINED_THROW_CALLBACKS are defined + //! the user must provide an implementation and the function should not return.
  • + //!
inline void throw_runtime_error(const char* str) { throw std::runtime_error(str); diff --git a/include/boost/container/vector.hpp b/include/boost/container/vector.hpp index eabcab9..e706ac9 100644 --- a/include/boost/container/vector.hpp +++ b/include/boost/container/vector.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -53,7 +53,7 @@ namespace boost { namespace container { -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //#define BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER @@ -80,7 +80,7 @@ class vec_iterator , value_type& >::type reference; - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: Pointer m_ptr; @@ -94,7 +94,7 @@ class vec_iterator explicit vec_iterator(Pointer ptr) BOOST_CONTAINER_NOEXCEPT : m_ptr(ptr) {} - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: @@ -224,6 +224,9 @@ namespace container_detail { #endif //#ifndef BOOST_CONTAINER_VECTOR_ITERATOR_IS_POINTER +struct uninitialized_size_t {}; +static const uninitialized_size_t uninitialized_size = uninitialized_size_t(); + template struct vector_value_traits { @@ -242,17 +245,10 @@ struct vector_value_traits ,container_detail::scoped_destructor_n - >::type OldArrayDestructor; - //This is the anti-exception array destructor - //to destroy objects created with copy construction - typedef typename container_detail::if_c - - ,container_detail::scoped_destructor_n >::type ArrayDestructor; //This is the anti-exception array deallocator typedef typename container_detail::if_c - ,container_detail::scoped_array_deallocator >::type ArrayDeallocator; @@ -291,7 +287,7 @@ struct vector_alloc_holder //Constructor, does not throw template - explicit vector_alloc_holder(BOOST_FWD_REF(AllocConvertible) a, size_type initial_size) + vector_alloc_holder(uninitialized_size_t, BOOST_FWD_REF(AllocConvertible) a, size_type initial_size) : Allocator(boost::forward(a)) , m_start() , m_size(initial_size) //Size is initialized here so vector should only call uninitialized_xxx after this @@ -303,7 +299,7 @@ struct vector_alloc_holder } //Constructor, does not throw - explicit vector_alloc_holder(size_type initial_size) + vector_alloc_holder(uninitialized_size_t, size_type initial_size) : Allocator() , m_start() , m_size(initial_size) //Size is initialized here so vector should only call uninitialized_xxx after this @@ -344,7 +340,7 @@ struct vector_alloc_holder } std::pair - allocation_command(allocation_type command, + allocation_command(boost::container::allocation_type command, size_type limit_size, size_type preferred_size, size_type &received_size, const pointer &reuse = pointer()) @@ -355,11 +351,10 @@ struct vector_alloc_holder size_type next_capacity(size_type additional_objects) const { - std::size_t num_objects = this->m_size + additional_objects; - std::size_t next_cap = this->m_capacity + this->m_capacity/2; - return num_objects > next_cap ? num_objects : next_cap;/* - return get_next_capacity( allocator_traits_type::max_size(this->m_holder.alloc()) - , this->m_capacity, additional_objects);*/ + return next_capacity_calculator + :: + get( allocator_traits_type::max_size(this->alloc()) + , this->m_capacity, additional_objects ); } pointer m_start; @@ -425,7 +420,7 @@ struct vector_alloc_holder - explicit vector_alloc_holder(BOOST_FWD_REF(AllocConvertible) a, size_type initial_size) + vector_alloc_holder(uninitialized_size_t, BOOST_FWD_REF(AllocConvertible) a, size_type initial_size) : Allocator(boost::forward(a)) , m_size(initial_size) //Size is initialized here... { @@ -434,7 +429,7 @@ struct vector_alloc_holder > #else @@ -542,7 +537,7 @@ template #endif class vector { - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED typedef container_detail::integral_constant ::value > alloc_version; @@ -557,7 +552,7 @@ class vector typedef container_detail::vec_iterator iterator_impl; typedef container_detail::vec_iterator const_iterator_impl; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// // @@ -584,7 +579,7 @@ class vector typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) reverse_iterator; typedef BOOST_CONTAINER_IMPDEF(std::reverse_iterator) const_reverse_iterator; - /// @cond + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED private: BOOST_COPYABLE_AND_MOVABLE(vector) typedef container_detail::vector_value_traits value_traits; @@ -594,7 +589,7 @@ class vector typedef container_detail::integral_constant allocator_v2; typedef constant_iterator cvalue_iterator; - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED public: ////////////////////////////////////////////// @@ -630,7 +625,7 @@ class vector //! //! Complexity: Linear to n. explicit vector(size_type n) - : m_holder(n) + : m_holder(container_detail::uninitialized_size, n) { boost::container::uninitialized_value_init_alloc_n (this->m_holder.alloc(), n, container_detail::to_raw_pointer(this->m_holder.start())); @@ -645,8 +640,8 @@ class vector //! Complexity: Linear to n. //! //! Note: Non-standard extension - explicit vector(size_type n, default_init_t) - : m_holder(n) + vector(size_type n, default_init_t) + : m_holder(container_detail::uninitialized_size, n) { boost::container::uninitialized_default_init_alloc_n (this->m_holder.alloc(), n, container_detail::to_raw_pointer(this->m_holder.start())); @@ -660,7 +655,7 @@ class vector //! //! Complexity: Linear to n. vector(size_type n, const T& value) - : m_holder(n) + : m_holder(container_detail::uninitialized_size, n) { boost::container::uninitialized_fill_alloc_n (this->m_holder.alloc(), value, n, container_detail::to_raw_pointer(this->m_holder.start())); @@ -674,7 +669,7 @@ class vector //! //! Complexity: Linear to n. vector(size_type n, const T& value, const allocator_type& a) - : m_holder(a, n) + : m_holder(container_detail::uninitialized_size, a, n) { boost::container::uninitialized_fill_alloc_n (this->m_holder.alloc(), value, n, container_detail::to_raw_pointer(this->m_holder.start())); @@ -713,7 +708,9 @@ class vector //! //! Complexity: Linear to the elements x contains. vector(const vector &x) - : m_holder(allocator_traits_type::select_on_container_copy_construction(x.m_holder.alloc()), x.size()) + : m_holder( container_detail::uninitialized_size + , allocator_traits_type::select_on_container_copy_construction(x.m_holder.alloc()) + , x.size()) { ::boost::container::uninitialized_copy_alloc_n ( this->m_holder.alloc(), container_detail::to_raw_pointer(x.m_holder.start()) @@ -754,7 +751,7 @@ class vector //! //! Complexity: Linear to the elements x contains. vector(const vector &x, const allocator_type &a) - : m_holder(a, x.size()) + : m_holder(container_detail::uninitialized_size, a, x.size()) { ::boost::container::uninitialized_copy_alloc_n_source ( this->m_holder.alloc(), container_detail::to_raw_pointer(x.m_holder.start()) @@ -808,7 +805,7 @@ class vector vector& operator=(BOOST_COPY_ASSIGN_REF(vector) x) { if (&x != this){ - this->priv_copy_assign(boost::move(x), alloc_version()); + this->priv_copy_assign(x, alloc_version()); } return *this; } @@ -858,8 +855,9 @@ class vector void assign(InIt first, InIt last #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) , typename container_detail::enable_if_c - < !container_detail::is_convertible::value - //&& container_detail::is_input_iterator::value + < !container_detail::is_convertible::value && + ( container_detail::is_input_iterator::value || + container_detail::is_same::value ) >::type * = 0 #endif ) @@ -883,6 +881,64 @@ class vector } } + //! Effects: Assigns the the range [first, last) to *this. + //! + //! Throws: If memory allocation throws or T's copy/move constructor/assignment or + //! T's constructor/assignment from dereferencing InpIt throws. + //! + //! Complexity: Linear to n. + template + void assign(FwdIt first, FwdIt last + #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) + , typename container_detail::enable_if_c + < !container_detail::is_convertible::value && + ( !container_detail::is_input_iterator::value && + !container_detail::is_same::value ) + >::type * = 0 + #endif + ) + { + //For Fwd iterators the standard only requires EmplaceConstructible and assignble from *first + //so we can't do any backwards allocation + const size_type input_sz = static_cast(std::distance(first, last)); + const size_type old_capacity = this->capacity(); + if(input_sz > old_capacity){ //If input range is too big, we need to reallocate + size_type real_cap; + std::pair ret = + this->m_holder.allocation_command(allocate_new, input_sz, input_sz, real_cap, this->m_holder.start()); + if(!ret.second){ //New allocation, just emplace new values + pointer const old_p = this->m_holder.start(); + if(old_p){ + this->priv_destroy_all(); + this->m_holder.alloc().deallocate(old_p, old_capacity); + } + this->m_holder.start(ret.first); + this->m_holder.capacity(real_cap); + this->m_holder.m_size = 0; + this->priv_uninitialized_construct_at_end(first, last); + return; + } + else{ + //Forward expansion, use assignment + back deletion/construction that comes later + } + } + //Overwrite all elements we can from [first, last) + iterator cur = this->begin(); + const iterator end_it = this->end(); + for ( ; first != last && cur != end_it; ++cur, ++first){ + *cur = *first; + } + + if (first == last){ + //There are no more elements in the sequence, erase remaining + this->priv_destroy_last_n(this->size() - input_sz); + } + else{ + //Uninitialized construct at end the remaining range + this->priv_uninitialized_construct_at_end(first, last); + } + } + //! Effects: Assigns the n copies of val to *this. //! //! Throws: If memory allocation throws or @@ -1065,18 +1121,7 @@ class vector //! //! Complexity: Linear to the difference between size() and new_size. void resize(size_type new_size) - { - const size_type sz = this->size(); - if (new_size < sz){ - //Destroy last elements - this->priv_destroy_last_n(sz - new_size); - } - else{ - const size_type n = new_size - this->size(); - container_detail::insert_value_initialized_n_proxy proxy(this->m_holder.alloc()); - this->priv_forward_range_insert_at_end(n, proxy, alloc_version()); - } - } + { this->priv_resize(new_size, value_init); } //! Effects: Inserts or erases elements at the end such that //! the size becomes n. New elements are value initialized. @@ -1087,18 +1132,7 @@ class vector //! //! Note: Non-standard extension void resize(size_type new_size, default_init_t) - { - const size_type sz = this->size(); - if (new_size < sz){ - //Destroy last elements - this->priv_destroy_last_n(sz - new_size); - } - else{ - const size_type n = new_size - this->size(); - container_detail::insert_default_initialized_n_proxy proxy(this->m_holder.alloc()); - this->priv_forward_range_insert_at_end(n, proxy, alloc_version()); - } - } + { this->priv_resize(new_size, default_init); } //! Effects: Inserts or erases elements at the end such that //! the size becomes n. New elements are copy constructed from x. @@ -1107,18 +1141,7 @@ class vector //! //! Complexity: Linear to the difference between size() and new_size. void resize(size_type new_size, const T& x) - { - const size_type sz = this->size(); - if (new_size < sz){ - //Destroy last elements - this->priv_destroy_last_n(sz - new_size); - } - else{ - const size_type n = new_size - this->size(); - container_detail::insert_n_copies_proxy proxy(this->m_holder.alloc(), x); - this->priv_forward_range_insert_at_end(n, proxy, alloc_version()); - } - } + { this->priv_resize(new_size, x); } //! Effects: Number of elements for which memory has been allocated. //! capacity() is always greater than or equal to size(). @@ -1295,7 +1318,7 @@ class vector else{ typedef container_detail::insert_emplace_proxy type; this->priv_forward_range_insert_no_capacity - (vector_iterator_get_ptr(this->cend()), 1, type(this->m_holder.alloc(), ::boost::forward(args)...), alloc_version()); + (vector_iterator_get_ptr(this->cend()), 1, type(::boost::forward(args)...), alloc_version()); } } @@ -1314,8 +1337,8 @@ class vector { //Just call more general insert(pos, size, value) and return iterator typedef container_detail::insert_emplace_proxy type; - return this->priv_forward_range_insert( vector_iterator_get_ptr(position), 1, type(this->m_holder.alloc() - , ::boost::forward(args)...), alloc_version()); + return this->priv_forward_range_insert( vector_iterator_get_ptr(position), 1 + , type(::boost::forward(args)...), alloc_version()); } #else @@ -1332,11 +1355,11 @@ class vector ++this->m_holder.m_size; \ } \ else{ \ - container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ - proxy \ - (this->m_holder.alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ + typedef container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ + type; \ this->priv_forward_range_insert_no_capacity \ - (vector_iterator_get_ptr(this->cend()), 1, proxy, alloc_version()); \ + ( vector_iterator_get_ptr(this->cend()), 1 \ + , type(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)), alloc_version()); \ } \ } \ \ @@ -1344,11 +1367,11 @@ class vector iterator emplace(const_iterator pos \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ { \ - container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ - proxy \ - (this->m_holder.alloc() BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); \ + typedef container_detail::BOOST_PP_CAT(insert_emplace_proxy_arg, n) \ + type; \ return this->priv_forward_range_insert \ - (container_detail::to_raw_pointer(vector_iterator_get_ptr(pos)), 1, proxy, alloc_version()); \ + ( container_detail::to_raw_pointer(vector_iterator_get_ptr(pos)), 1 \ + , type(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)), alloc_version()); \ } \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) @@ -1412,7 +1435,7 @@ class vector //! Complexity: Linear to n. iterator insert(const_iterator p, size_type n, const T& x) { - container_detail::insert_n_copies_proxy proxy(this->m_holder.alloc(), x); + container_detail::insert_n_copies_proxy proxy(x); return this->priv_forward_range_insert(vector_iterator_get_ptr(p), n, proxy, alloc_version()); } @@ -1454,7 +1477,7 @@ class vector >::type * = 0 ) { - container_detail::insert_range_proxy proxy(this->m_holder.alloc(), first); + container_detail::insert_range_proxy proxy(first); return this->priv_forward_range_insert(vector_iterator_get_ptr(pos), std::distance(first, last), proxy, alloc_version()); } #endif @@ -1534,9 +1557,7 @@ class vector //! Note: non-standard extension. template void swap(vector & x) - { - this->m_holder.swap(x.m_holder); - } + { this->m_holder.swap(x.m_holder); } #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED @@ -1544,11 +1565,53 @@ class vector //! //! Throws: Nothing. //! - //! Complexity: Linear to the number of elements in the vector. + //! Complexity: Linear to the number of elements in the container. void clear() BOOST_CONTAINER_NOEXCEPT { this->priv_destroy_all(); } - /// @cond + //! Effects: Returns true if x and y are equal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator==(const vector& x, const vector& y) + { return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); } + + //! Effects: Returns true if x and y are unequal + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator!=(const vector& x, const vector& y) + { return !(x == y); } + + //! Effects: Returns true if x is less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<(const vector& x, const vector& y) + { return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); } + + //! Effects: Returns true if x is greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>(const vector& x, const vector& y) + { return y < x; } + + //! Effects: Returns true if x is equal or less than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator<=(const vector& x, const vector& y) + { return !(y < x); } + + //! Effects: Returns true if x is equal or greater than y + //! + //! Complexity: Linear to the number of elements in the container. + friend bool operator>=(const vector& x, const vector& y) + { return !(x < y); } + + //! Effects: x.swap(y) + //! + //! Complexity: Constant. + friend void swap(vector& x, vector& y) + { x.swap(y); } + + #ifndef BOOST_CONTAINER_DOXYGEN_INVOKED //Absolutely experimental. This function might change, disappear or simply crash! template @@ -1560,7 +1623,8 @@ class vector //Absolutely experimental. This function might change, disappear or simply crash! template - void insert_ordered_at(size_type element_count, BiDirPosConstIt last_position_it, BiDirSkipConstIt last_skip_it, BiDirValueIt last_value_it) + void insert_ordered_at( size_type element_count, BiDirPosConstIt last_position_it + , BiDirSkipConstIt last_skip_it, BiDirValueIt last_value_it) { this->priv_insert_ordered_at(element_count, last_position_it, true, last_skip_it, last_value_it); } @@ -1588,9 +1652,7 @@ class vector < !container_detail::is_same::value || container_detail::is_same::value >::type * = 0) - { - this->priv_move_assign_impl(boost::move(x), AllocVersion()); - } + { this->priv_move_assign_impl(boost::move(x), AllocVersion()); } template void priv_move_assign_impl(BOOST_RV_REF_BEG vector BOOST_RV_REF_END x @@ -1669,29 +1731,23 @@ class vector } void priv_reserve(size_type, allocator_v0) + { throw_bad_alloc(); } + + container_detail::insert_range_proxy, T*> priv_dummy_empty_proxy() { - throw_bad_alloc(); + return container_detail::insert_range_proxy, T*> + (::boost::make_move_iterator((T *)0)); } void priv_reserve(size_type new_cap, allocator_v1) { //There is not enough memory, allocate a new buffer pointer p = this->m_holder.allocate(new_cap); - //Backwards (and possibly forward) expansion - #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS - ++this->num_alloc; - #endif - T * const raw_beg = container_detail::to_raw_pointer(this->m_holder.start()); - const size_type sz = m_holder.m_size; - ::boost::container::uninitialized_move_alloc_n_source - ( this->m_holder.alloc(), raw_beg, sz, container_detail::to_raw_pointer(p) ); - if(this->m_holder.capacity()){ - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->m_holder.alloc(), raw_beg, sz); - this->m_holder.deallocate(this->m_holder.start(), this->m_holder.capacity()); - } - this->m_holder.start(p); - this->m_holder.capacity(new_cap); + //We will reuse insert code, so create a dummy input iterator + this->priv_forward_range_insert_new_allocation + ( container_detail::to_raw_pointer(p), new_cap + , container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size + , 0, this->priv_dummy_empty_proxy()); } void priv_reserve(size_type new_cap, allocator_v2) @@ -1700,10 +1756,8 @@ class vector //buffer or expand the old one. bool same_buffer_start; size_type real_cap = 0; - std::pair ret = - this->m_holder.allocation_command - (allocate_new | expand_fwd | expand_bwd, - new_cap, new_cap, real_cap, this->m_holder.start()); + std::pair ret = this->m_holder.allocation_command + (allocate_new | expand_fwd | expand_bwd, new_cap, new_cap, real_cap, this->m_holder.start()); //Check for forward expansion same_buffer_start = ret.second && this->m_holder.start() == ret.first; @@ -1713,52 +1767,26 @@ class vector #endif this->m_holder.capacity(real_cap); } - //If there is no forward expansion, move objects - else{ - //Backwards (and possibly forward) expansion - if(ret.second){ - //We will reuse insert code, so create a dummy input iterator - container_detail::insert_range_proxy, T*> - proxy(this->m_holder.alloc(), ::boost::make_move_iterator((T *)0)); + else{ //If there is no forward expansion, move objects, we will reuse insertion code + T * const new_mem = container_detail::to_raw_pointer(ret.first); + T * const ins_pos = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; + if(ret.second){ //Backwards (and possibly forward) expansion #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS ++this->num_expand_bwd; #endif this->priv_forward_range_insert_expand_backwards - ( container_detail::to_raw_pointer(ret.first) - , real_cap - , container_detail::to_raw_pointer(this->m_holder.start()) - , 0 - , proxy); + ( new_mem , real_cap, ins_pos, 0, this->priv_dummy_empty_proxy()); } - //New buffer - else{ + else{ //New buffer #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS ++this->num_alloc; #endif - T * const raw_beg = container_detail::to_raw_pointer(this->m_holder.start()); - const size_type sz = m_holder.m_size; - ::boost::container::uninitialized_move_alloc_n_source - ( this->m_holder.alloc(), raw_beg, sz, container_detail::to_raw_pointer(ret.first) ); - if(this->m_holder.capacity()){ - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->m_holder.alloc(), raw_beg, sz); - this->m_holder.deallocate(this->m_holder.start(), this->m_holder.capacity()); - } - this->m_holder.start(ret.first); - this->m_holder.capacity(real_cap); + this->priv_forward_range_insert_new_allocation + ( new_mem, real_cap, ins_pos, 0, this->priv_dummy_empty_proxy()); } } } - template - void priv_uninitialized_fill(Proxy proxy, size_type n) const - { - //Copy first new elements in pos - proxy.uninitialized_copy_n_and_update - (container_detail::to_raw_pointer(this->m_holder.start()), n); - //m_holder.size was already initialized to n in vector_alloc_holder's constructor - } - void priv_destroy(value_type* p) BOOST_CONTAINER_NOEXCEPT { if(!value_traits::trivial_dctr) @@ -1772,6 +1800,16 @@ class vector this->m_holder.m_size -= n; } + template + void priv_uninitialized_construct_at_end(InpIt first, InpIt last) + { + T* end_pos = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; + for(; first != last; ++first, ++end_pos, ++this->m_holder.m_size){ + //There is more memory, just construct a new object at the end + allocator_traits_type::construct(this->m_holder.alloc(), end_pos, *first); + } + } + void priv_destroy_all() BOOST_CONTAINER_NOEXCEPT { boost::container::destroy_alloc_n @@ -1783,39 +1821,54 @@ class vector iterator priv_insert(const const_iterator &p, BOOST_FWD_REF(U) x) { return this->priv_forward_range_insert - ( vector_iterator_get_ptr(p), 1, container_detail::get_insert_value_proxy(this->m_holder.alloc() - , ::boost::forward(x)), alloc_version()); + ( vector_iterator_get_ptr(p), 1, container_detail::get_insert_value_proxy + (::boost::forward(x)), alloc_version()); } - void priv_push_back(const T &x) + container_detail::insert_copy_proxy priv_single_insert_proxy(const T &x) + { return container_detail::insert_copy_proxy (x); } + + container_detail::insert_move_proxy priv_single_insert_proxy(BOOST_RV_REF(T) x) + { return container_detail::insert_move_proxy (x); } + + template + void priv_push_back(BOOST_FWD_REF(U) u) { if (this->m_holder.m_size < this->m_holder.capacity()){ //There is more memory, just construct a new object at the end allocator_traits_type::construct ( this->m_holder.alloc() , container_detail::to_raw_pointer(this->m_holder.start() + this->m_holder.m_size) - , x ); + , ::boost::forward(u) ); ++this->m_holder.m_size; } else{ - container_detail::insert_copy_proxy proxy(this->m_holder.alloc(), x); - this->priv_forward_range_insert_no_capacity(vector_iterator_get_ptr(this->cend()), 1, proxy, alloc_version()); + this->priv_forward_range_insert_no_capacity + ( vector_iterator_get_ptr(this->cend()), 1 + , this->priv_single_insert_proxy(::boost::forward(u)), alloc_version()); } } - void priv_push_back(BOOST_RV_REF(T) x) + container_detail::insert_n_copies_proxy priv_resize_proxy(const T &x) + { return container_detail::insert_n_copies_proxy(x); } + + container_detail::insert_default_initialized_n_proxy priv_resize_proxy(default_init_t) + { return container_detail::insert_default_initialized_n_proxy(); } + + container_detail::insert_value_initialized_n_proxy priv_resize_proxy(value_init_t) + { return container_detail::insert_value_initialized_n_proxy(); } + + template + void priv_resize(size_type new_size, const U& u) { - if (this->m_holder.m_size < this->m_holder.capacity()){ - //There is more memory, just construct a new object at the end - allocator_traits_type::construct - ( this->m_holder.alloc() - , container_detail::to_raw_pointer(this->m_holder.start() + this->m_holder.m_size) - , ::boost::move(x) ); - ++this->m_holder.m_size; + const size_type sz = this->size(); + if (new_size < sz){ + //Destroy last elements + this->priv_destroy_last_n(sz - new_size); } else{ - container_detail::insert_move_proxy proxy(this->m_holder.alloc(), x); - this->priv_forward_range_insert_no_capacity(vector_iterator_get_ptr(this->cend()), 1, proxy, alloc_version()); + const size_type n = new_size - this->size(); + this->priv_forward_range_insert_at_end(n, this->priv_resize_proxy(u), alloc_version()); } } @@ -1837,17 +1890,13 @@ class vector pointer p = this->m_holder.allocate(sz); //We will reuse insert code, so create a dummy input iterator - container_detail::insert_range_proxy, T*> - proxy(this->m_holder.alloc(), ::boost::make_move_iterator((T *)0)); #ifdef BOOST_CONTAINER_VECTOR_ALLOC_STATS ++this->num_alloc; #endif this->priv_forward_range_insert_new_allocation - ( container_detail::to_raw_pointer(p) - , sz + ( container_detail::to_raw_pointer(p), sz , container_detail::to_raw_pointer(this->m_holder.start()) - , 0 - , proxy); + , 0, this->priv_dummy_empty_proxy()); } } } @@ -1902,7 +1951,6 @@ class vector return iterator(this->m_holder.start() + n_pos); } - template iterator priv_forward_range_insert_no_capacity (const pointer &pos, const size_type n, const InsertionProxy insert_range_proxy, allocator_v2) @@ -1979,8 +2027,7 @@ class vector if (n <= remaining){ const size_type n_pos = raw_pos - container_detail::to_raw_pointer(this->m_holder.start()); - this->priv_forward_range_insert_expand_forward - (raw_pos, n, insert_range_proxy); + this->priv_forward_range_insert_expand_forward(raw_pos, n, insert_range_proxy); return iterator(this->m_holder.start() + n_pos); } else{ @@ -2162,7 +2209,7 @@ class vector T* const last_ptr = begin_ptr + last_pos; size_type hole_size = 0; - //Case Allocator: + //Case A: if((last_pos + shift_count) <= limit_pos){ //All move assigned boost::move_backward(first_ptr, last_ptr, last_ptr + shift_count); @@ -2191,7 +2238,7 @@ class vector void priv_forward_range_insert_at_end_expand_forward(const size_type n, InsertionProxy insert_range_proxy) { T* const old_finish = container_detail::to_raw_pointer(this->m_holder.start()) + this->m_holder.m_size; - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, n); + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), old_finish, n); this->m_holder.m_size += n; } @@ -2205,7 +2252,7 @@ class vector const size_type elems_after = old_finish - pos; if (!elems_after){ - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, n); + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), old_finish, n); this->m_holder.m_size += n; } else if (elems_after >= n){ @@ -2217,7 +2264,7 @@ class vector //Copy previous to last objects to the initialized end boost::move_backward(pos, old_finish - n, old_finish); //Insert new objects in the pos - insert_range_proxy.copy_n_and_update(pos, n); + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), pos, n); } else { //The new elements don't fit in the [pos, end()) range. @@ -2226,9 +2273,9 @@ class vector ::boost::container::uninitialized_move_alloc(this->m_holder.alloc(), pos, old_finish, pos + n); BOOST_TRY{ //Copy first new elements in pos (gap is still there) - insert_range_proxy.copy_n_and_update(pos, elems_after); + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), pos, elems_after); //Copy to the beginning of the unallocated zone the last new elements (the gap is closed). - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, n - elems_after); + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), old_finish, n - elems_after); this->m_holder.m_size += n; } BOOST_CATCH(...){ @@ -2247,21 +2294,22 @@ class vector T *new_finish = new_start; T *old_finish; //Anti-exception rollbacks - typename value_traits::ArrayDeallocator scoped_alloc(new_start, this->m_holder.alloc(), new_cap); - typename value_traits::ArrayDestructor constructed_values_destroyer(new_start, this->m_holder.alloc(), 0u); + typename value_traits::ArrayDeallocator new_buffer_deallocator(new_start, this->m_holder.alloc(), new_cap); + typename value_traits::ArrayDestructor new_values_destroyer(new_start, this->m_holder.alloc(), 0u); //Initialize with [begin(), pos) old buffer //the start of the new buffer - T *old_buffer = container_detail::to_raw_pointer(this->m_holder.start()); + T * const old_buffer = container_detail::to_raw_pointer(this->m_holder.start()); if(old_buffer){ new_finish = ::boost::container::uninitialized_move_alloc (this->m_holder.alloc(), container_detail::to_raw_pointer(this->m_holder.start()), pos, old_finish = new_finish); - constructed_values_destroyer.increment_size(new_finish - old_finish); + new_values_destroyer.increment_size(new_finish - old_finish); } //Initialize new objects, starting from previous point - insert_range_proxy.uninitialized_copy_n_and_update(old_finish = new_finish, n); + old_finish = new_finish; + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), old_finish, n); new_finish += n; - constructed_values_destroyer.increment_size(new_finish - old_finish); + new_values_destroyer.increment_size(new_finish - old_finish); //Initialize from the rest of the old buffer, //starting from previous point if(old_buffer){ @@ -2277,8 +2325,8 @@ class vector this->m_holder.m_size = new_finish - new_start; this->m_holder.capacity(new_cap); //All construction successful, disable rollbacks - constructed_values_destroyer.release(); - scoped_alloc.release(); + new_values_destroyer.release(); + new_buffer_deallocator.release(); } template @@ -2289,8 +2337,8 @@ class vector //n can be zero to just expand capacity //Backup old data T* const old_start = container_detail::to_raw_pointer(this->m_holder.start()); - T* const old_finish = old_start + this->m_holder.m_size; const size_type old_size = this->m_holder.m_size; + T* const old_finish = old_start + old_size; //We can have 8 possibilities: const size_type elemsbefore = static_cast(pos - old_start); @@ -2304,17 +2352,18 @@ class vector //If anything goes wrong, this object will destroy //all the old objects to fulfill previous vector state - typename value_traits::OldArrayDestructor old_values_destroyer(old_start, this->m_holder.alloc(), old_size); + typename value_traits::ArrayDestructor old_values_destroyer(old_start, this->m_holder.alloc(), old_size); //Check if s_before is big enough to hold the beginning of old data + new data if(s_before >= before_plus_new){ //Copy first old values before pos, after that the new objects - T *const new_elem_pos = ::boost::container::uninitialized_move_alloc(this->m_holder.alloc(), old_start, pos, new_start); + T *const new_elem_pos = + ::boost::container::uninitialized_move_alloc(this->m_holder.alloc(), old_start, pos, new_start); this->m_holder.m_size = elemsbefore; - insert_range_proxy.uninitialized_copy_n_and_update(new_elem_pos, n); - this->m_holder.m_size += n; + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), new_elem_pos, n); + this->m_holder.m_size = before_plus_new; + const size_type new_size = old_size + n; //Check if s_before is so big that even copying the old data + new data //there is a gap between the new data and the old data - const size_type new_size = old_size + n; if(s_before >= new_size){ //Old situation: // _________________________________________________________ @@ -2327,10 +2376,12 @@ class vector //|___________|__________|_________|________________________| // //Now initialize the rest of memory with the last old values - ::boost::container::uninitialized_move_alloc - (this->m_holder.alloc(), pos, old_finish, new_start + before_plus_new); - //All new elements correctly constructed, avoid new element destruction - this->m_holder.m_size = new_size; + if(before_plus_new != new_size){ //Special case to avoid operations in back insertion + ::boost::container::uninitialized_move_alloc + (this->m_holder.alloc(), pos, old_finish, new_start + before_plus_new); + //All new elements correctly constructed, avoid new element destruction + this->m_holder.m_size = new_size; + } //Old values destroyed automatically with "old_values_destroyer" //when "old_values_destroyer" goes out of scope unless the have trivial //destructor after move. @@ -2352,22 +2403,28 @@ class vector //Now initialize the rest of memory with the last old values //All new elements correctly constructed, avoid new element destruction const size_type raw_gap = s_before - before_plus_new; - //Now initialize the rest of s_before memory with the - //first of elements after new values - ::boost::container::uninitialized_move_alloc_n - (this->m_holder.alloc(), pos, raw_gap, new_start + before_plus_new); - //Update size since we have a contiguous buffer - this->m_holder.m_size = old_size + s_before; - //All new elements correctly constructed, avoid old element destruction - old_values_destroyer.release(); - //Now copy remaining last objects in the old buffer begin - T * const to_destroy = ::boost::move(pos + raw_gap, old_finish, old_start); - //Now destroy redundant elements except if they were moved and - //they have trivial destructor after move - size_type n_destroy = old_finish - to_destroy; - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->get_stored_allocator(), to_destroy, n_destroy); - this->m_holder.m_size -= n_destroy; + if(!value_traits::trivial_dctr){ + //Now initialize the rest of s_before memory with the + //first of elements after new values + ::boost::container::uninitialized_move_alloc_n + (this->m_holder.alloc(), pos, raw_gap, new_start + before_plus_new); + //Now we have a contiguous buffer so program trailing element destruction + //and update size to the final size. + old_values_destroyer.shrink_forward(elemsbefore + raw_gap); + this->m_holder.m_size = new_size; + //Now move remaining last objects in the old buffer begin + ::boost::move(pos + raw_gap, old_finish, old_start); + //Once moved, avoid calling the destructors if trivial after move + if(value_traits::trivial_dctr_after_move){ + old_values_destroyer.release(); + } + } + else{ //If trivial destructor, we can uninitialized copy + copy in a single uninitialized copy + ::boost::container::uninitialized_move_alloc_n + (this->m_holder.alloc(), pos, old_finish - pos, new_start + before_plus_new); + this->m_holder.m_size = new_size; + old_values_destroyer.release(); + } } } else{ @@ -2421,27 +2478,30 @@ class vector //Copy the first part of old_begin to raw_mem ::boost::container::uninitialized_move_alloc_n (this->m_holder.alloc(), old_start, s_before, new_start); - //The buffer is all constructed until old_end, - //release destroyer and update size - old_values_destroyer.release(); - this->m_holder.m_size = old_size + s_before; - //Now copy the second part of old_begin overwriting itself - T *const next = ::boost::move(old_start + s_before, pos, old_start); + //The buffer is all constructed until old_end if(do_after){ + //release destroyer and update size + old_values_destroyer.release(); + this->m_holder.m_size = old_size + s_before; + //Now copy the second part of old_begin overwriting itself + T *const next = ::boost::move(old_start + s_before, pos, old_start); //Now copy the new_beg elements - insert_range_proxy.copy_n_and_update(next, s_before); + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), next, s_before); } else{ - //Now copy the all the new elements - insert_range_proxy.copy_n_and_update(next, n); - //Now displace old_end elements - T* const move_end = ::boost::move(pos, old_finish, next + n); - //Destroy remaining moved elements from old_end except if - //they have trivial destructor after being moved + //The buffer is all constructed until old_end, + //so program trailing destruction and assign final size + this->m_holder.m_size = old_size + n; const size_type n_destroy = s_before - n; - if(!value_traits::trivial_dctr_after_move) - boost::container::destroy_alloc_n(this->get_stored_allocator(), move_end, n_destroy); - this->m_holder.m_size -= n_destroy; + old_values_destroyer.shrink_forward(old_size - n_destroy); + //Now copy the second part of old_begin overwriting itself + T *const next = ::boost::move(old_start + s_before, pos, old_start); + //Now copy the all the new elements + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), next, n); + //Now displace old_end elements + ::boost::move(pos, old_finish, next + n); + if(value_traits::trivial_dctr_after_move) + old_values_destroyer.release(); } } else { @@ -2475,7 +2535,7 @@ class vector (this->m_holder.alloc(), old_start, pos, new_start); this->m_holder.m_size = elemsbefore; const size_type mid_n = s_before - elemsbefore; - insert_range_proxy.uninitialized_copy_n_and_update(new_pos, mid_n); + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), new_pos, mid_n); //The buffer is all constructed until old_end, //release destroyer this->m_holder.m_size = old_size + s_before; @@ -2483,15 +2543,15 @@ class vector if(do_after){ //Copy new_beg part - insert_range_proxy.copy_n_and_update(old_start, elemsbefore); + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), old_start, elemsbefore); } else{ //Copy all new elements const size_type rest_new = n - mid_n; - insert_range_proxy.copy_n_and_update(old_start, rest_new); - T* move_start = old_start + rest_new; + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), old_start, rest_new); + T* const move_start = old_start + rest_new; //Displace old_end - T* move_end = ::boost::move(pos, old_finish, move_start); + T* const move_end = ::boost::move(pos, old_finish, move_start); //Destroy remaining moved elements from old_end except if they //have trivial destructor after being moved size_type n_destroy = s_before - n; @@ -2546,7 +2606,7 @@ class vector boost::move_backward(pos, finish_n, old_finish); //Now overwrite with new_end //The new_end part is [first + (n - n_after), last) - insert_range_proxy.copy_n_and_update(pos, n_after); + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), pos, n_after); } else { //The raw_mem from end will divide new_end part @@ -2571,9 +2631,9 @@ class vector BOOST_TRY{ //Copy the first part to the already constructed old_end zone - insert_range_proxy.copy_n_and_update(pos, elemsafter); + insert_range_proxy.copy_n_and_update(this->m_holder.alloc(), pos, elemsafter); //Copy the rest to the uninitialized zone filling the gap - insert_range_proxy.uninitialized_copy_n_and_update(old_finish, mid_last_dist); + insert_range_proxy.uninitialized_copy_n_and_update(this->m_holder.alloc(), old_finish, mid_last_dist); this->m_holder.m_size += n_after; } BOOST_CATCH(...){ @@ -2615,39 +2675,12 @@ class vector void reset_alloc_stats() { num_expand_fwd = num_expand_bwd = num_alloc = 0, num_shrink = 0; } #endif - /// @endcond + #endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED }; -template -inline bool -operator==(const vector& x, const vector& y) -{ - //Check first size and each element if needed - return x.size() == y.size() && std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator!=(const vector& x, const vector& y) -{ - //Check first size and each element if needed - return x.size() != y.size() || !std::equal(x.begin(), x.end(), y.begin()); -} - -template -inline bool -operator<(const vector& x, const vector& y) -{ - return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); -} - -template -inline void swap(vector& x, vector& y) -{ x.swap(y); } - }} -/// @cond +#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED namespace boost { @@ -2676,9 +2709,8 @@ inline void swap(boost::container::vector& x, boost::container::ve #endif -/// @endcond +#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED #include #endif // #ifndef BOOST_CONTAINER_CONTAINER_VECTOR_HPP - diff --git a/index.html b/index.html index 1251783..fe55e4d 100644 --- a/index.html +++ b/index.html @@ -1,5 +1,5 @@ diff --git a/proj/to-do.txt b/proj/to-do.txt index 01d497a..a101c69 100644 --- a/proj/to-do.txt +++ b/proj/to-do.txt @@ -60,4 +60,6 @@ Add hash for containers Add std:: hashing support -Fix trivial destructor after move and other optimizing traits \ No newline at end of file +Fix trivial destructor after move and other optimizing traits + +Implement n3586, "Splicing Maps and Sets" (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3586.pdf) diff --git a/proj/vc7ide/alloc_basic_test.vcproj b/proj/vc7ide/alloc_basic_test.vcproj new file mode 100644 index 0000000..43051b4 --- /dev/null +++ b/proj/vc7ide/alloc_basic_test.vcproj @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/alloc_full_test.vcproj b/proj/vc7ide/alloc_full_test.vcproj new file mode 100644 index 0000000..b5b5067 --- /dev/null +++ b/proj/vc7ide/alloc_full_test.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/alloc_lib.vcproj b/proj/vc7ide/alloc_lib.vcproj new file mode 100644 index 0000000..71615f0 --- /dev/null +++ b/proj/vc7ide/alloc_lib.vcproj @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/allocator_traits_test.vcproj b/proj/vc7ide/allocator_traits_test.vcproj index 6e73236..dcb62fc 100644 --- a/proj/vc7ide/allocator_traits_test.vcproj +++ b/proj/vc7ide/allocator_traits_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" GeneratePreprocessedFile="0" MinimalRebuild="TRUE" BasicRuntimeChecks="3" @@ -74,7 +74,7 @@ - - - - diff --git a/proj/vc7ide/bench_adaptive_node_pool.vcproj b/proj/vc7ide/bench_adaptive_node_pool.vcproj new file mode 100644 index 0000000..0967943 --- /dev/null +++ b/proj/vc7ide/bench_adaptive_node_pool.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_alloc.vcproj b/proj/vc7ide/bench_alloc.vcproj new file mode 100644 index 0000000..703f837 --- /dev/null +++ b/proj/vc7ide/bench_alloc.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_alloc_expand_bwd.vcproj b/proj/vc7ide/bench_alloc_expand_bwd.vcproj new file mode 100644 index 0000000..df07e31 --- /dev/null +++ b/proj/vc7ide/bench_alloc_expand_bwd.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_alloc_expand_fwd.vcproj b/proj/vc7ide/bench_alloc_expand_fwd.vcproj new file mode 100644 index 0000000..56d3685 --- /dev/null +++ b/proj/vc7ide/bench_alloc_expand_fwd.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_alloc_shrink_to_fit.vcproj b/proj/vc7ide/bench_alloc_shrink_to_fit.vcproj new file mode 100644 index 0000000..1eb6ad0 --- /dev/null +++ b/proj/vc7ide/bench_alloc_shrink_to_fit.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_alloc_stable_vector_burst_allocation.vcproj b/proj/vc7ide/bench_alloc_stable_vector_burst_allocation.vcproj new file mode 100644 index 0000000..b4a39ac --- /dev/null +++ b/proj/vc7ide/bench_alloc_stable_vector_burst_allocation.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_flat_multiset.vcproj b/proj/vc7ide/bench_flat_multiset.vcproj new file mode 100644 index 0000000..589774a --- /dev/null +++ b/proj/vc7ide/bench_flat_multiset.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_flat_set.vcproj b/proj/vc7ide/bench_flat_set.vcproj new file mode 100644 index 0000000..b898aae --- /dev/null +++ b/proj/vc7ide/bench_flat_set.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_set.vcproj b/proj/vc7ide/bench_set.vcproj index 327e6fe..42ab275 100644 --- a/proj/vc7ide/bench_set.vcproj +++ b/proj/vc7ide/bench_set.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" ExceptionHandling="TRUE" BasicRuntimeChecks="3" @@ -74,7 +74,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_set_avl.vcproj b/proj/vc7ide/bench_set_avl.vcproj new file mode 100644 index 0000000..8f74720 --- /dev/null +++ b/proj/vc7ide/bench_set_avl.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_set_multi.vcproj b/proj/vc7ide/bench_set_multi.vcproj new file mode 100644 index 0000000..b400b7d --- /dev/null +++ b/proj/vc7ide/bench_set_multi.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_set_sg.vcproj b/proj/vc7ide/bench_set_sg.vcproj new file mode 100644 index 0000000..e6560e9 --- /dev/null +++ b/proj/vc7ide/bench_set_sg.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_set_sp.vcproj b/proj/vc7ide/bench_set_sp.vcproj new file mode 100644 index 0000000..4e92a22 --- /dev/null +++ b/proj/vc7ide/bench_set_sp.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/bench_static_vector.vcproj b/proj/vc7ide/bench_static_vector.vcproj index a518d54..575a038 100644 --- a/proj/vc7ide/bench_static_vector.vcproj +++ b/proj/vc7ide/bench_static_vector.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" ExceptionHandling="TRUE" BasicRuntimeChecks="3" @@ -74,7 +74,7 @@ + RelativePath="..\..\..\..\boost\container\adaptive_pool.hpp"> + RelativePath="..\..\..\..\boost\container\allocator.hpp"> + + @@ -122,6 +125,12 @@ + + + + @@ -155,6 +164,9 @@ + + @@ -164,12 +176,21 @@ + + + + + + @@ -203,9 +224,15 @@ + + + + @@ -215,9 +242,15 @@ + + + + @@ -282,6 +315,9 @@ + + diff --git a/proj/vc7ide/deque_test.vcproj b/proj/vc7ide/deque_test.vcproj index b416a71..aab9341 100644 --- a/proj/vc7ide/deque_test.vcproj +++ b/proj/vc7ide/deque_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -73,7 +73,7 @@ - - diff --git a/proj/vc7ide/doc_custom_tree.vcproj b/proj/vc7ide/doc_custom_tree.vcproj new file mode 100644 index 0000000..2a08e67 --- /dev/null +++ b/proj/vc7ide/doc_custom_tree.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/doc_emplace.vcproj b/proj/vc7ide/doc_emplace.vcproj new file mode 100644 index 0000000..76affef --- /dev/null +++ b/proj/vc7ide/doc_emplace.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/doc_extended_allocators.vcproj b/proj/vc7ide/doc_extended_allocators.vcproj new file mode 100644 index 0000000..b488dc2 --- /dev/null +++ b/proj/vc7ide/doc_extended_allocators.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/doc_move_containers.vcproj b/proj/vc7ide/doc_move_containers.vcproj new file mode 100644 index 0000000..2bf8d40 --- /dev/null +++ b/proj/vc7ide/doc_move_containers.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/doc_recursive_containers.vcproj b/proj/vc7ide/doc_recursive_containers.vcproj new file mode 100644 index 0000000..1f36a8b --- /dev/null +++ b/proj/vc7ide/doc_recursive_containers.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/doc_type_erasure.vcproj b/proj/vc7ide/doc_type_erasure.vcproj new file mode 100644 index 0000000..fe5cf68 --- /dev/null +++ b/proj/vc7ide/doc_type_erasure.vcproj @@ -0,0 +1,134 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/flat_map_test.vcproj b/proj/vc7ide/flat_map_test.vcproj new file mode 100644 index 0000000..f40bbd4 --- /dev/null +++ b/proj/vc7ide/flat_map_test.vcproj @@ -0,0 +1,135 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/flat_tree_test.vcproj b/proj/vc7ide/flat_set_test.vcproj similarity index 81% rename from proj/vc7ide/flat_tree_test.vcproj rename to proj/vc7ide/flat_set_test.vcproj index 4e05a16..21cd7fe 100644 --- a/proj/vc7ide/flat_tree_test.vcproj +++ b/proj/vc7ide/flat_set_test.vcproj @@ -2,7 +2,7 @@ @@ -13,14 +13,14 @@ @@ -69,13 +69,13 @@ + UniqueIdentifier="{4FC737F1-C7A5-4376-A066-252A26A32D7A}"> + RelativePath="..\..\test\flat_set_test.cpp"> - - diff --git a/proj/vc7ide/tree_test.vcproj b/proj/vc7ide/hash_table_test.vcproj similarity index 84% rename from proj/vc7ide/tree_test.vcproj rename to proj/vc7ide/hash_table_test.vcproj index 0231de2..faaac30 100644 --- a/proj/vc7ide/tree_test.vcproj +++ b/proj/vc7ide/hash_table_test.vcproj @@ -2,7 +2,7 @@ @@ -13,14 +13,14 @@ @@ -67,13 +67,13 @@ + RelativePath="..\..\test\hash_table_test.cpp"> - - diff --git a/proj/vc7ide/list_test.vcproj b/proj/vc7ide/list_test.vcproj index e3198de..4aa86f9 100644 --- a/proj/vc7ide/list_test.vcproj +++ b/proj/vc7ide/list_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" GeneratePreprocessedFile="0" KeepComments="FALSE" MinimalRebuild="TRUE" @@ -75,7 +75,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/pair_test.vcproj b/proj/vc7ide/pair_test.vcproj index 6f32b3e..374663a 100644 --- a/proj/vc7ide/pair_test.vcproj +++ b/proj/vc7ide/pair_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -73,7 +73,7 @@ - - diff --git a/proj/vc7ide/scoped_allocator_usage_test.vcproj b/proj/vc7ide/scoped_allocator_usage_test.vcproj index a19b214..1b185c4 100644 --- a/proj/vc7ide/scoped_allocator_usage_test.vcproj +++ b/proj/vc7ide/scoped_allocator_usage_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" GeneratePreprocessedFile="0" MinimalRebuild="TRUE" BasicRuntimeChecks="3" @@ -74,7 +74,7 @@ - - diff --git a/proj/vc7ide/set_test.vcproj b/proj/vc7ide/set_test.vcproj new file mode 100644 index 0000000..eccbb82 --- /dev/null +++ b/proj/vc7ide/set_test.vcproj @@ -0,0 +1,133 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/proj/vc7ide/slist_test.vcproj b/proj/vc7ide/slist_test.vcproj index 2e813bb..386c09a 100644 --- a/proj/vc7ide/slist_test.vcproj +++ b/proj/vc7ide/slist_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -73,7 +73,7 @@ - - diff --git a/proj/vc7ide/stable_vector_test.vcproj b/proj/vc7ide/stable_vector_test.vcproj index fdc2192..8a05024 100644 --- a/proj/vc7ide/stable_vector_test.vcproj +++ b/proj/vc7ide/stable_vector_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" BasicRuntimeChecks="3" RuntimeLibrary="3" @@ -73,7 +73,7 @@ - - diff --git a/proj/vc7ide/string_test.vcproj b/proj/vc7ide/string_test.vcproj index 77f6f35..e49c2f5 100644 --- a/proj/vc7ide/string_test.vcproj +++ b/proj/vc7ide/string_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" GeneratePreprocessedFile="0" MinimalRebuild="TRUE" BasicRuntimeChecks="3" @@ -74,7 +74,7 @@ - - diff --git a/proj/vc7ide/throw_exception_test.vcproj b/proj/vc7ide/throw_exception_test.vcproj index 12b7bb8..521e9c5 100644 --- a/proj/vc7ide/throw_exception_test.vcproj +++ b/proj/vc7ide/throw_exception_test.vcproj @@ -20,7 +20,7 @@ Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="../../../.." - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE;BOOST_DATE_TIME_NO_LIB" + PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" MinimalRebuild="TRUE" ExceptionHandling="TRUE" BasicRuntimeChecks="3" @@ -74,7 +74,7 @@ - - diff --git a/src/alloc_lib.c b/src/alloc_lib.c new file mode 100644 index 0000000..3b24be4 --- /dev/null +++ b/src/alloc_lib.c @@ -0,0 +1,22 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2012-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + + +#define DLMALLOC_VERSION 286 + +#ifndef DLMALLOC_VERSION + #error "DLMALLOC_VERSION undefined" +#endif + +#if DLMALLOC_VERSION == 286 + #include "dlmalloc_ext_2_8_6.c" +#else + #error "Unsupported boost_cont_VERSION version" +#endif diff --git a/src/dlmalloc_2_8_6.c b/src/dlmalloc_2_8_6.c new file mode 100644 index 0000000..649cfbc --- /dev/null +++ b/src/dlmalloc_2_8_6.c @@ -0,0 +1,6280 @@ +/* + This is a version (aka dlmalloc) of malloc/free/realloc written by + Doug Lea and released to the public domain, as explained at + http://creativecommons.org/publicdomain/zero/1.0/ Send questions, + comments, complaints, performance data, etc to dl@cs.oswego.edu + +* Version 2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + Note: There may be an updated version of this malloc obtainable at + ftp://gee.cs.oswego.edu/pub/misc/malloc.c + Check before installing! + +* Quickstart + + This library is all in one file to simplify the most common usage: + ftp it, compile it (-O3), and link it into another program. All of + the compile-time options default to reasonable values for use on + most platforms. You might later want to step through various + compile-time and dynamic tuning options. + + For convenience, an include file for code using this malloc is at: + ftp://gee.cs.oswego.edu/pub/misc/malloc-2.8.6.h + You don't really need this .h file unless you call functions not + defined in your system include files. The .h file contains only the + excerpts from this file needed for using this malloc on ANSI C/C++ + systems, so long as you haven't changed compile-time options about + naming and tuning parameters. If you do, then you can create your + own malloc.h that does include all settings by cutting at the point + indicated below. Note that you may already by default be using a C + library containing a malloc that is based on some version of this + malloc (for example in linux). You might still want to use the one + in this file to customize settings or to avoid overheads associated + with library versions. + +* Vital statistics: + + Supported pointer/size_t representation: 4 or 8 bytes + size_t MUST be an unsigned type of the same width as + pointers. (If you are using an ancient system that declares + size_t as a signed type, or need it to be a different width + than pointers, you can use a previous release of this malloc + (e.g. 2.7.2) supporting these.) + + Alignment: 8 bytes (minimum) + This suffices for nearly all current machines and C compilers. + However, you can define MALLOC_ALIGNMENT to be wider than this + if necessary (up to 128bytes), at the expense of using more space. + + Minimum overhead per allocated chunk: 4 or 8 bytes (if 4byte sizes) + 8 or 16 bytes (if 8byte sizes) + Each malloced chunk has a hidden word of overhead holding size + and status information, and additional cross-check word + if FOOTERS is defined. + + Minimum allocated size: 4-byte ptrs: 16 bytes (including overhead) + 8-byte ptrs: 32 bytes (including overhead) + + Even a request for zero bytes (i.e., malloc(0)) returns a + pointer to something of the minimum allocatable size. + The maximum overhead wastage (i.e., number of extra bytes + allocated than were requested in malloc) is less than or equal + to the minimum size, except for requests >= mmap_threshold that + are serviced via mmap(), where the worst case wastage is about + 32 bytes plus the remainder from a system page (the minimal + mmap unit); typically 4096 or 8192 bytes. + + Security: static-safe; optionally more or less + The "security" of malloc refers to the ability of malicious + code to accentuate the effects of errors (for example, freeing + space that is not currently malloc'ed or overwriting past the + ends of chunks) in code that calls malloc. This malloc + guarantees not to modify any memory locations below the base of + heap, i.e., static variables, even in the presence of usage + errors. The routines additionally detect most improper frees + and reallocs. All this holds as long as the static bookkeeping + for malloc itself is not corrupted by some other means. This + is only one aspect of security -- these checks do not, and + cannot, detect all possible programming errors. + + If FOOTERS is defined nonzero, then each allocated chunk + carries an additional check word to verify that it was malloced + from its space. These check words are the same within each + execution of a program using malloc, but differ across + executions, so externally crafted fake chunks cannot be + freed. This improves security by rejecting frees/reallocs that + could corrupt heap memory, in addition to the checks preventing + writes to statics that are always on. This may further improve + security at the expense of time and space overhead. (Note that + FOOTERS may also be worth using with MSPACES.) + + By default detected errors cause the program to abort (calling + "abort()"). You can override this to instead proceed past + errors by defining PROCEED_ON_ERROR. In this case, a bad free + has no effect, and a malloc that encounters a bad address + caused by user overwrites will ignore the bad address by + dropping pointers and indices to all known memory. This may + be appropriate for programs that should continue if at all + possible in the face of programming errors, although they may + run out of memory because dropped memory is never reclaimed. + + If you don't like either of these options, you can define + CORRUPTION_ERROR_ACTION and USAGE_ERROR_ACTION to do anything + else. And if if you are sure that your program using malloc has + no errors or vulnerabilities, you can define INSECURE to 1, + which might (or might not) provide a small performance improvement. + + It is also possible to limit the maximum total allocatable + space, using malloc_set_footprint_limit. This is not + designed as a security feature in itself (calls to set limits + are not screened or privileged), but may be useful as one + aspect of a secure implementation. + + Thread-safety: NOT thread-safe unless USE_LOCKS defined non-zero + When USE_LOCKS is defined, each public call to malloc, free, + etc is surrounded with a lock. By default, this uses a plain + pthread mutex, win32 critical section, or a spin-lock if if + available for the platform and not disabled by setting + USE_SPIN_LOCKS=0. However, if USE_RECURSIVE_LOCKS is defined, + recursive versions are used instead (which are not required for + base functionality but may be needed in layered extensions). + Using a global lock is not especially fast, and can be a major + bottleneck. It is designed only to provide minimal protection + in concurrent environments, and to provide a basis for + extensions. If you are using malloc in a concurrent program, + consider instead using nedmalloc + (http://www.nedprod.com/programs/portable/nedmalloc/) or + ptmalloc (See http://www.malloc.de), which are derived from + versions of this malloc. + + System requirements: Any combination of MORECORE and/or MMAP/MUNMAP + This malloc can use unix sbrk or any emulation (invoked using + the CALL_MORECORE macro) and/or mmap/munmap or any emulation + (invoked using CALL_MMAP/CALL_MUNMAP) to get and release system + memory. On most unix systems, it tends to work best if both + MORECORE and MMAP are enabled. On Win32, it uses emulations + based on VirtualAlloc. It also uses common C library functions + like memset. + + Compliance: I believe it is compliant with the Single Unix Specification + (See http://www.unix.org). Also SVID/XPG, ANSI C, and probably + others as well. + +* Overview of algorithms + + This is not the fastest, most space-conserving, most portable, or + most tunable malloc ever written. However it is among the fastest + while also being among the most space-conserving, portable and + tunable. Consistent balance across these factors results in a good + general-purpose allocator for malloc-intensive programs. + + In most ways, this malloc is a best-fit allocator. Generally, it + chooses the best-fitting existing chunk for a request, with ties + broken in approximately least-recently-used order. (This strategy + normally maintains low fragmentation.) However, for requests less + than 256bytes, it deviates from best-fit when there is not an + exactly fitting available chunk by preferring to use space adjacent + to that used for the previous small request, as well as by breaking + ties in approximately most-recently-used order. (These enhance + locality of series of small allocations.) And for very large requests + (>= 256Kb by default), it relies on system memory mapping + facilities, if supported. (This helps avoid carrying around and + possibly fragmenting memory used only for large chunks.) + + All operations (except malloc_stats and mallinfo) have execution + times that are bounded by a constant factor of the number of bits in + a size_t, not counting any clearing in calloc or copying in realloc, + or actions surrounding MORECORE and MMAP that have times + proportional to the number of non-contiguous regions returned by + system allocation routines, which is often just 1. In real-time + applications, you can optionally suppress segment traversals using + NO_SEGMENT_TRAVERSAL, which assures bounded execution even when + system allocators return non-contiguous spaces, at the typical + expense of carrying around more memory and increased fragmentation. + + The implementation is not very modular and seriously overuses + macros. Perhaps someday all C compilers will do as good a job + inlining modular code as can now be done by brute-force expansion, + but now, enough of them seem not to. + + Some compilers issue a lot of warnings about code that is + dead/unreachable only on some platforms, and also about intentional + uses of negation on unsigned types. All known cases of each can be + ignored. + + For a longer but out of date high-level description, see + http://gee.cs.oswego.edu/dl/html/malloc.html + +* MSPACES + If MSPACES is defined, then in addition to malloc, free, etc., + this file also defines mspace_malloc, mspace_free, etc. These + are versions of malloc routines that take an "mspace" argument + obtained using create_mspace, to control all internal bookkeeping. + If ONLY_MSPACES is defined, only these versions are compiled. + So if you would like to use this allocator for only some allocations, + and your system malloc for others, you can compile with + ONLY_MSPACES and then do something like... + static mspace mymspace = create_mspace(0,0); // for example + #define mymalloc(bytes) mspace_malloc(mymspace, bytes) + + (Note: If you only need one instance of an mspace, you can instead + use "USE_DL_PREFIX" to relabel the global malloc.) + + You can similarly create thread-local allocators by storing + mspaces as thread-locals. For example: + static __thread mspace tlms = 0; + void* tlmalloc(size_t bytes) { + if (tlms == 0) tlms = create_mspace(0, 0); + return mspace_malloc(tlms, bytes); + } + void tlfree(void* mem) { mspace_free(tlms, mem); } + + Unless FOOTERS is defined, each mspace is completely independent. + You cannot allocate from one and free to another (although + conformance is only weakly checked, so usage errors are not always + caught). If FOOTERS is defined, then each chunk carries around a tag + indicating its originating mspace, and frees are directed to their + originating spaces. Normally, this requires use of locks. + + ------------------------- Compile-time options --------------------------- + +Be careful in setting #define values for numerical constants of type +size_t. On some systems, literal values are not automatically extended +to size_t precision unless they are explicitly casted. You can also +use the symbolic values MAX_SIZE_T, SIZE_T_ONE, etc below. + +WIN32 default: defined if _WIN32 defined + Defining WIN32 sets up defaults for MS environment and compilers. + Otherwise defaults are for unix. Beware that there seem to be some + cases where this malloc might not be a pure drop-in replacement for + Win32 malloc: Random-looking failures from Win32 GDI API's (eg; + SetDIBits()) may be due to bugs in some video driver implementations + when pixel buffers are malloc()ed, and the region spans more than + one VirtualAlloc()ed region. Because dlmalloc uses a small (64Kb) + default granularity, pixel buffers may straddle virtual allocation + regions more often than when using the Microsoft allocator. You can + avoid this by using VirtualAlloc() and VirtualFree() for all pixel + buffers rather than using malloc(). If this is not possible, + recompile this malloc with a larger DEFAULT_GRANULARITY. Note: + in cases where MSC and gcc (cygwin) are known to differ on WIN32, + conditions use _MSC_VER to distinguish them. + +DLMALLOC_EXPORT default: extern + Defines how public APIs are declared. If you want to export via a + Windows DLL, you might define this as + #define DLMALLOC_EXPORT extern __declspec(dllexport) + If you want a POSIX ELF shared object, you might use + #define DLMALLOC_EXPORT extern __attribute__((visibility("default"))) + +MALLOC_ALIGNMENT default: (size_t)(2 * sizeof(void *)) + Controls the minimum alignment for malloc'ed chunks. It must be a + power of two and at least 8, even on machines for which smaller + alignments would suffice. It may be defined as larger than this + though. Note however that code and data structures are optimized for + the case of 8-byte alignment. + +MSPACES default: 0 (false) + If true, compile in support for independent allocation spaces. + This is only supported if HAVE_MMAP is true. + +ONLY_MSPACES default: 0 (false) + If true, only compile in mspace versions, not regular versions. + +USE_LOCKS default: 0 (false) + Causes each call to each public routine to be surrounded with + pthread or WIN32 mutex lock/unlock. (If set true, this can be + overridden on a per-mspace basis for mspace versions.) If set to a + non-zero value other than 1, locks are used, but their + implementation is left out, so lock functions must be supplied manually, + as described below. + +USE_SPIN_LOCKS default: 1 iff USE_LOCKS and spin locks available + If true, uses custom spin locks for locking. This is currently + supported only gcc >= 4.1, older gccs on x86 platforms, and recent + MS compilers. Otherwise, posix locks or win32 critical sections are + used. + +USE_RECURSIVE_LOCKS default: not defined + If defined nonzero, uses recursive (aka reentrant) locks, otherwise + uses plain mutexes. This is not required for malloc proper, but may + be needed for layered allocators such as nedmalloc. + +LOCK_AT_FORK default: not defined + If defined nonzero, performs pthread_atfork upon initialization + to initialize child lock while holding parent lock. The implementation + assumes that pthread locks (not custom locks) are being used. In other + cases, you may need to customize the implementation. + +FOOTERS default: 0 + If true, provide extra checking and dispatching by placing + information in the footers of allocated chunks. This adds + space and time overhead. + +INSECURE default: 0 + If true, omit checks for usage errors and heap space overwrites. + +USE_DL_PREFIX default: NOT defined + Causes compiler to prefix all public routines with the string 'dl'. + This can be useful when you only want to use this malloc in one part + of a program, using your regular system malloc elsewhere. + +MALLOC_INSPECT_ALL default: NOT defined + If defined, compiles malloc_inspect_all and mspace_inspect_all, that + perform traversal of all heap space. Unless access to these + functions is otherwise restricted, you probably do not want to + include them in secure implementations. + +ABORT default: defined as abort() + Defines how to abort on failed checks. On most systems, a failed + check cannot die with an "assert" or even print an informative + message, because the underlying print routines in turn call malloc, + which will fail again. Generally, the best policy is to simply call + abort(). It's not very useful to do more than this because many + errors due to overwriting will show up as address faults (null, odd + addresses etc) rather than malloc-triggered checks, so will also + abort. Also, most compilers know that abort() does not return, so + can better optimize code conditionally calling it. + +PROCEED_ON_ERROR default: defined as 0 (false) + Controls whether detected bad addresses cause them to bypassed + rather than aborting. If set, detected bad arguments to free and + realloc are ignored. And all bookkeeping information is zeroed out + upon a detected overwrite of freed heap space, thus losing the + ability to ever return it from malloc again, but enabling the + application to proceed. If PROCEED_ON_ERROR is defined, the + static variable malloc_corruption_error_count is compiled in + and can be examined to see if errors have occurred. This option + generates slower code than the default abort policy. + +DEBUG default: NOT defined + The DEBUG setting is mainly intended for people trying to modify + this code or diagnose problems when porting to new platforms. + However, it may also be able to better isolate user errors than just + using runtime checks. The assertions in the check routines spell + out in more detail the assumptions and invariants underlying the + algorithms. The checking is fairly extensive, and will slow down + execution noticeably. Calling malloc_stats or mallinfo with DEBUG + set will attempt to check every non-mmapped allocated and free chunk + in the course of computing the summaries. + +ABORT_ON_ASSERT_FAILURE default: defined as 1 (true) + Debugging assertion failures can be nearly impossible if your + version of the assert macro causes malloc to be called, which will + lead to a cascade of further failures, blowing the runtime stack. + ABORT_ON_ASSERT_FAILURE cause assertions failures to call abort(), + which will usually make debugging easier. + +MALLOC_FAILURE_ACTION default: sets errno to ENOMEM, or no-op on win32 + The action to take before "return 0" when malloc fails to be able to + return memory because there is none available. + +HAVE_MORECORE default: 1 (true) unless win32 or ONLY_MSPACES + True if this system supports sbrk or an emulation of it. + +MORECORE default: sbrk + The name of the sbrk-style system routine to call to obtain more + memory. See below for guidance on writing custom MORECORE + functions. The type of the argument to sbrk/MORECORE varies across + systems. It cannot be size_t, because it supports negative + arguments, so it is normally the signed type of the same width as + size_t (sometimes declared as "intptr_t"). It doesn't much matter + though. Internally, we only call it with arguments less than half + the max value of a size_t, which should work across all reasonable + possibilities, although sometimes generating compiler warnings. + +MORECORE_CONTIGUOUS default: 1 (true) if HAVE_MORECORE + If true, take advantage of fact that consecutive calls to MORECORE + with positive arguments always return contiguous increasing + addresses. This is true of unix sbrk. It does not hurt too much to + set it true anyway, since malloc copes with non-contiguities. + Setting it false when definitely non-contiguous saves time + and possibly wasted space it would take to discover this though. + +MORECORE_CANNOT_TRIM default: NOT defined + True if MORECORE cannot release space back to the system when given + negative arguments. This is generally necessary only if you are + using a hand-crafted MORECORE function that cannot handle negative + arguments. + +NO_SEGMENT_TRAVERSAL default: 0 + If non-zero, suppresses traversals of memory segments + returned by either MORECORE or CALL_MMAP. This disables + merging of segments that are contiguous, and selectively + releasing them to the OS if unused, but bounds execution times. + +HAVE_MMAP default: 1 (true) + True if this system supports mmap or an emulation of it. If so, and + HAVE_MORECORE is not true, MMAP is used for all system + allocation. If set and HAVE_MORECORE is true as well, MMAP is + primarily used to directly allocate very large blocks. It is also + used as a backup strategy in cases where MORECORE fails to provide + space from system. Note: A single call to MUNMAP is assumed to be + able to unmap memory that may have be allocated using multiple calls + to MMAP, so long as they are adjacent. + +HAVE_MREMAP default: 1 on linux, else 0 + If true realloc() uses mremap() to re-allocate large blocks and + extend or shrink allocation spaces. + +MMAP_CLEARS default: 1 except on WINCE. + True if mmap clears memory so calloc doesn't need to. This is true + for standard unix mmap using /dev/zero and on WIN32 except for WINCE. + +USE_BUILTIN_FFS default: 0 (i.e., not used) + Causes malloc to use the builtin ffs() function to compute indices. + Some compilers may recognize and intrinsify ffs to be faster than the + supplied C version. Also, the case of x86 using gcc is special-cased + to an asm instruction, so is already as fast as it can be, and so + this setting has no effect. Similarly for Win32 under recent MS compilers. + (On most x86s, the asm version is only slightly faster than the C version.) + +malloc_getpagesize default: derive from system includes, or 4096. + The system page size. To the extent possible, this malloc manages + memory from the system in page-size units. This may be (and + usually is) a function rather than a constant. This is ignored + if WIN32, where page size is determined using getSystemInfo during + initialization. + +USE_DEV_RANDOM default: 0 (i.e., not used) + Causes malloc to use /dev/random to initialize secure magic seed for + stamping footers. Otherwise, the current time is used. + +NO_MALLINFO default: 0 + If defined, don't compile "mallinfo". This can be a simple way + of dealing with mismatches between system declarations and + those in this file. + +MALLINFO_FIELD_TYPE default: size_t + The type of the fields in the mallinfo struct. This was originally + defined as "int" in SVID etc, but is more usefully defined as + size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set + +NO_MALLOC_STATS default: 0 + If defined, don't compile "malloc_stats". This avoids calls to + fprintf and bringing in stdio dependencies you might not want. + +REALLOC_ZERO_BYTES_FREES default: not defined + This should be set if a call to realloc with zero bytes should + be the same as a call to free. Some people think it should. Otherwise, + since this malloc returns a unique pointer for malloc(0), so does + realloc(p, 0). + +LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H +LACKS_STRINGS_H, LACKS_STRING_H, LACKS_SYS_TYPES_H, LACKS_ERRNO_H +LACKS_STDLIB_H LACKS_SCHED_H LACKS_TIME_H default: NOT defined unless on WIN32 + Define these if your system does not have these header files. + You might need to manually insert some of the declarations they provide. + +DEFAULT_GRANULARITY default: page size if MORECORE_CONTIGUOUS, + system_info.dwAllocationGranularity in WIN32, + otherwise 64K. + Also settable using mallopt(M_GRANULARITY, x) + The unit for allocating and deallocating memory from the system. On + most systems with contiguous MORECORE, there is no reason to + make this more than a page. However, systems with MMAP tend to + either require or encourage larger granularities. You can increase + this value to prevent system allocation functions to be called so + often, especially if they are slow. The value must be at least one + page and must be a power of two. Setting to 0 causes initialization + to either page size or win32 region size. (Note: In previous + versions of malloc, the equivalent of this option was called + "TOP_PAD") + +DEFAULT_TRIM_THRESHOLD default: 2MB + Also settable using mallopt(M_TRIM_THRESHOLD, x) + The maximum amount of unused top-most memory to keep before + releasing via malloc_trim in free(). Automatic trimming is mainly + useful in long-lived programs using contiguous MORECORE. Because + trimming via sbrk can be slow on some systems, and can sometimes be + wasteful (in cases where programs immediately afterward allocate + more large chunks) the value should be high enough so that your + overall system performance would improve by releasing this much + memory. As a rough guide, you might set to a value close to the + average size of a process (program) running on your system. + Releasing this much memory would allow such a process to run in + memory. Generally, it is worth tuning trim thresholds when a + program undergoes phases where several large chunks are allocated + and released in ways that can reuse each other's storage, perhaps + mixed with phases where there are no such chunks at all. The trim + value must be greater than page size to have any useful effect. To + disable trimming completely, you can set to MAX_SIZE_T. Note that the trick + some people use of mallocing a huge space and then freeing it at + program startup, in an attempt to reserve system memory, doesn't + have the intended effect under automatic trimming, since that memory + will immediately be returned to the system. + +DEFAULT_MMAP_THRESHOLD default: 256K + Also settable using mallopt(M_MMAP_THRESHOLD, x) + The request size threshold for using MMAP to directly service a + request. Requests of at least this size that cannot be allocated + using already-existing space will be serviced via mmap. (If enough + normal freed space already exists it is used instead.) Using mmap + segregates relatively large chunks of memory so that they can be + individually obtained and released from the host system. A request + serviced through mmap is never reused by any other request (at least + not directly; the system may just so happen to remap successive + requests to the same locations). Segregating space in this way has + the benefits that: Mmapped space can always be individually released + back to the system, which helps keep the system level memory demands + of a long-lived program low. Also, mapped memory doesn't become + `locked' between other chunks, as can happen with normally allocated + chunks, which means that even trimming via malloc_trim would not + release them. However, it has the disadvantage that the space + cannot be reclaimed, consolidated, and then used to service later + requests, as happens with normal chunks. The advantages of mmap + nearly always outweigh disadvantages for "large" chunks, but the + value of "large" may vary across systems. The default is an + empirically derived value that works well in most systems. You can + disable mmap by setting to MAX_SIZE_T. + +MAX_RELEASE_CHECK_RATE default: 4095 unless not HAVE_MMAP + The number of consolidated frees between checks to release + unused segments when freeing. When using non-contiguous segments, + especially with multiple mspaces, checking only for topmost space + doesn't always suffice to trigger trimming. To compensate for this, + free() will, with a period of MAX_RELEASE_CHECK_RATE (or the + current number of segments, if greater) try to release unused + segments to the OS when freeing chunks that result in + consolidation. The best value for this parameter is a compromise + between slowing down frees with relatively costly checks that + rarely trigger versus holding on to unused memory. To effectively + disable, set to MAX_SIZE_T. This may lead to a very slight speed + improvement at the expense of carrying around more memory. +*/ + +/* Version identifier to allow people to support multiple versions */ +#ifndef DLMALLOC_VERSION +#define DLMALLOC_VERSION 20806 +#endif /* DLMALLOC_VERSION */ + +#ifndef DLMALLOC_EXPORT +#define DLMALLOC_EXPORT extern +#endif + +#ifndef WIN32 +#ifdef _WIN32 +#define WIN32 1 +#endif /* _WIN32 */ +#ifdef _WIN32_WCE +#define LACKS_FCNTL_H +#define WIN32 1 +#endif /* _WIN32_WCE */ +#endif /* WIN32 */ +#ifdef WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#include +#define HAVE_MMAP 1 +#define HAVE_MORECORE 0 +#define LACKS_UNISTD_H +#define LACKS_SYS_PARAM_H +#define LACKS_SYS_MMAN_H +#define LACKS_STRING_H +#define LACKS_STRINGS_H +#define LACKS_SYS_TYPES_H +#define LACKS_ERRNO_H +#define LACKS_SCHED_H +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef MMAP_CLEARS +#ifdef _WIN32_WCE /* WINCE reportedly does not clear */ +#define MMAP_CLEARS 0 +#else +#define MMAP_CLEARS 1 +#endif /* _WIN32_WCE */ +#endif /*MMAP_CLEARS */ +#endif /* WIN32 */ + +#if defined(DARWIN) || defined(_DARWIN) +/* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ +#ifndef HAVE_MORECORE +#define HAVE_MORECORE 0 +#define HAVE_MMAP 1 +/* OSX allocators provide 16 byte alignment */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)16U) +#endif +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ + +#ifndef LACKS_SYS_TYPES_H +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ + +/* The maximum possible size_t value has all bits set */ +#define MAX_SIZE_T (~(size_t)0) + +#ifndef USE_LOCKS /* ensure true if spin or recursive locks set */ +#define USE_LOCKS ((defined(USE_SPIN_LOCKS) && USE_SPIN_LOCKS != 0) || \ + (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0)) +#endif /* USE_LOCKS */ + +#if USE_LOCKS /* Spin locks for gcc >= 4.1, older gcc on x86, MSC >= 1310 */ +#if ((defined(__GNUC__) && \ + ((__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) || \ + defined(__i386__) || defined(__x86_64__))) || \ + (defined(_MSC_VER) && _MSC_VER>=1310)) +#ifndef USE_SPIN_LOCKS +#define USE_SPIN_LOCKS 1 +#endif /* USE_SPIN_LOCKS */ +#elif USE_SPIN_LOCKS +#error "USE_SPIN_LOCKS defined without implementation" +#endif /* ... locks available... */ +#elif !defined(USE_SPIN_LOCKS) +#define USE_SPIN_LOCKS 0 +#endif /* USE_LOCKS */ + +#ifndef ONLY_MSPACES +#define ONLY_MSPACES 0 +#endif /* ONLY_MSPACES */ +#ifndef MSPACES +#if ONLY_MSPACES +#define MSPACES 1 +#else /* ONLY_MSPACES */ +#define MSPACES 0 +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ +#ifndef MALLOC_ALIGNMENT +#define MALLOC_ALIGNMENT ((size_t)(2 * sizeof(void *))) +#endif /* MALLOC_ALIGNMENT */ +#ifndef FOOTERS +#define FOOTERS 0 +#endif /* FOOTERS */ +#ifndef ABORT +#define ABORT abort() +#endif /* ABORT */ +#ifndef ABORT_ON_ASSERT_FAILURE +#define ABORT_ON_ASSERT_FAILURE 1 +#endif /* ABORT_ON_ASSERT_FAILURE */ +#ifndef PROCEED_ON_ERROR +#define PROCEED_ON_ERROR 0 +#endif /* PROCEED_ON_ERROR */ + +#ifndef INSECURE +#define INSECURE 0 +#endif /* INSECURE */ +#ifndef MALLOC_INSPECT_ALL +#define MALLOC_INSPECT_ALL 0 +#endif /* MALLOC_INSPECT_ALL */ +#ifndef HAVE_MMAP +#define HAVE_MMAP 1 +#endif /* HAVE_MMAP */ +#ifndef MMAP_CLEARS +#define MMAP_CLEARS 1 +#endif /* MMAP_CLEARS */ +#ifndef HAVE_MREMAP +#ifdef linux +#define HAVE_MREMAP 1 +#define _GNU_SOURCE /* Turns on mremap() definition */ +#else /* linux */ +#define HAVE_MREMAP 0 +#endif /* linux */ +#endif /* HAVE_MREMAP */ +#ifndef MALLOC_FAILURE_ACTION +#define MALLOC_FAILURE_ACTION errno = ENOMEM; +#endif /* MALLOC_FAILURE_ACTION */ +#ifndef HAVE_MORECORE +#if ONLY_MSPACES +#define HAVE_MORECORE 0 +#else /* ONLY_MSPACES */ +#define HAVE_MORECORE 1 +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ +#if !HAVE_MORECORE +#define MORECORE_CONTIGUOUS 0 +#else /* !HAVE_MORECORE */ +#define MORECORE_DEFAULT sbrk +#ifndef MORECORE_CONTIGUOUS +#define MORECORE_CONTIGUOUS 1 +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ +#ifndef DEFAULT_GRANULARITY +#if (MORECORE_CONTIGUOUS || defined(WIN32)) +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ +#ifndef DEFAULT_TRIM_THRESHOLD +#ifndef MORECORE_CANNOT_TRIM +#define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) +#else /* MORECORE_CANNOT_TRIM */ +#define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ +#ifndef DEFAULT_MMAP_THRESHOLD +#if HAVE_MMAP +#define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) +#else /* HAVE_MMAP */ +#define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ +#ifndef MAX_RELEASE_CHECK_RATE +#if HAVE_MMAP +#define MAX_RELEASE_CHECK_RATE 4095 +#else +#define MAX_RELEASE_CHECK_RATE MAX_SIZE_T +#endif /* HAVE_MMAP */ +#endif /* MAX_RELEASE_CHECK_RATE */ +#ifndef USE_BUILTIN_FFS +#define USE_BUILTIN_FFS 0 +#endif /* USE_BUILTIN_FFS */ +#ifndef USE_DEV_RANDOM +#define USE_DEV_RANDOM 0 +#endif /* USE_DEV_RANDOM */ +#ifndef NO_MALLINFO +#define NO_MALLINFO 0 +#endif /* NO_MALLINFO */ +#ifndef MALLINFO_FIELD_TYPE +#define MALLINFO_FIELD_TYPE size_t +#endif /* MALLINFO_FIELD_TYPE */ +#ifndef NO_MALLOC_STATS +#define NO_MALLOC_STATS 0 +#endif /* NO_MALLOC_STATS */ +#ifndef NO_SEGMENT_TRAVERSAL +#define NO_SEGMENT_TRAVERSAL 0 +#endif /* NO_SEGMENT_TRAVERSAL */ + +/* + mallopt tuning options. SVID/XPG defines four standard parameter + numbers for mallopt, normally defined in malloc.h. None of these + are used in this malloc, so setting them has no effect. But this + malloc does support the following options. +*/ + +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) + +/* ------------------------ Mallinfo declarations ------------------------ */ + +#if !NO_MALLINFO +/* + This version of malloc supports the standard SVID/XPG mallinfo + routine that returns a struct containing usage properties and + statistics. It should work on any system that has a + /usr/include/malloc.h defining struct mallinfo. The main + declaration needed is the mallinfo struct that is returned (by-copy) + by mallinfo(). The malloinfo struct contains a bunch of fields that + are not even meaningful in this version of malloc. These fields are + are instead filled by mallinfo() with other numbers that might be of + interest. + + HAVE_USR_INCLUDE_MALLOC_H should be set if you have a + /usr/include/malloc.h file that includes a declaration of struct + mallinfo. If so, it is included; else a compliant version is + declared below. These must be precisely the same for mallinfo() to + work. The original SVID version of this struct, defined on most + systems with mallinfo, declares all fields as ints. But some others + define as unsigned long. If your system defines the fields using a + type of different width than listed here, you MUST #include your + system version and #define HAVE_USR_INCLUDE_MALLOC_H. +*/ + +/* #define HAVE_USR_INCLUDE_MALLOC_H */ + +#ifdef HAVE_USR_INCLUDE_MALLOC_H +#include "/usr/include/malloc.h" +#else /* HAVE_USR_INCLUDE_MALLOC_H */ +#ifndef STRUCT_MALLINFO_DECLARED +/* HP-UX (and others?) redefines mallinfo unless _STRUCT_MALLINFO is defined */ +#define _STRUCT_MALLINFO +#define STRUCT_MALLINFO_DECLARED 1 +struct mallinfo { + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +}; +#endif /* STRUCT_MALLINFO_DECLARED */ +#endif /* HAVE_USR_INCLUDE_MALLOC_H */ +#endif /* NO_MALLINFO */ + +/* + Try to persuade compilers to inline. The most critical functions for + inlining are defined as macros, so these aren't used for them. +*/ + +#ifndef FORCEINLINE + #if defined(__GNUC__) +#define FORCEINLINE __inline __attribute__ ((always_inline)) + #elif defined(_MSC_VER) + #define FORCEINLINE __forceinline + #endif +#endif +#ifndef NOINLINE + #if defined(__GNUC__) + #define NOINLINE __attribute__ ((noinline)) + #elif defined(_MSC_VER) + #define NOINLINE __declspec(noinline) + #else + #define NOINLINE + #endif +#endif + +#ifdef __cplusplus +extern "C" { +#ifndef FORCEINLINE + #define FORCEINLINE inline +#endif +#endif /* __cplusplus */ +#ifndef FORCEINLINE + #define FORCEINLINE +#endif + +#if !ONLY_MSPACES + +/* ------------------- Declarations of public routines ------------------- */ + +#ifndef USE_DL_PREFIX +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlposix_memalign posix_memalign +#define dlrealloc realloc +#define dlrealloc_in_place realloc_in_place +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint +#define dlmalloc_max_footprint malloc_max_footprint +#define dlmalloc_footprint_limit malloc_footprint_limit +#define dlmalloc_set_footprint_limit malloc_set_footprint_limit +#define dlmalloc_inspect_all malloc_inspect_all +#define dlindependent_calloc independent_calloc +#define dlindependent_comalloc independent_comalloc +#define dlbulk_free bulk_free +#endif /* USE_DL_PREFIX */ + +/* + malloc(size_t n) + Returns a pointer to a newly allocated chunk of at least n bytes, or + null if no space is available, in which case errno is set to ENOMEM + on ANSI C systems. + + If n is zero, malloc returns a minimum-sized chunk. (The minimum + size is 16 bytes on most 32bit systems, and 32 bytes on 64bit + systems.) Note that size_t is an unsigned type, so calls with + arguments that would be negative if signed are interpreted as + requests for huge amounts of space, which will often fail. The + maximum supported value of n differs across systems, but is in all + cases less than the maximum representable value of a size_t. +*/ +DLMALLOC_EXPORT void* dlmalloc(size_t); + +/* + free(void* p) + Releases the chunk of memory pointed to by p, that had been previously + allocated using malloc or a related routine such as realloc. + It has no effect if p is null. If p was not malloced or already + freed, free(p) will by default cause the current program to abort. +*/ +DLMALLOC_EXPORT void dlfree(void*); + +/* + calloc(size_t n_elements, size_t element_size); + Returns a pointer to n_elements * element_size bytes, with all locations + set to zero. +*/ +DLMALLOC_EXPORT void* dlcalloc(size_t, size_t); + +/* + realloc(void* p, size_t n) + Returns a pointer to a chunk of size n that contains the same data + as does chunk p up to the minimum of (n, p's size) bytes, or null + if no space is available. + + The returned pointer may or may not be the same as p. The algorithm + prefers extending p in most cases when possible, otherwise it + employs the equivalent of a malloc-copy-free sequence. + + If p is null, realloc is equivalent to malloc. + + If space is not available, realloc returns null, errno is set (if on + ANSI) and p is NOT freed. + + if n is for fewer bytes than already held by p, the newly unused + space is lopped off and freed if possible. realloc with a size + argument of zero (re)allocates a minimum-sized chunk. + + The old unix realloc convention of allowing the last-free'd chunk + to be used as an argument to realloc is not supported. +*/ +DLMALLOC_EXPORT void* dlrealloc(void*, size_t); + +/* + realloc_in_place(void* p, size_t n) + Resizes the space allocated for p to size n, only if this can be + done without moving p (i.e., only if there is adjacent space + available if n is greater than p's current allocated size, or n is + less than or equal to p's size). This may be used instead of plain + realloc if an alternative allocation strategy is needed upon failure + to expand space; for example, reallocation of a buffer that must be + memory-aligned or cleared. You can use realloc_in_place to trigger + these alternatives only when needed. + + Returns p if successful; otherwise null. +*/ +DLMALLOC_EXPORT void* dlrealloc_in_place(void*, size_t); + +/* + memalign(size_t alignment, size_t n); + Returns a pointer to a newly allocated chunk of n bytes, aligned + in accord with the alignment argument. + + The alignment argument should be a power of two. If the argument is + not a power of two, the nearest greater power is used. + 8-byte alignment is guaranteed by normal malloc calls, so don't + bother calling memalign with an argument of 8 or less. + + Overreliance on memalign is a sure way to fragment space. +*/ +DLMALLOC_EXPORT void* dlmemalign(size_t, size_t); + +/* + int posix_memalign(void** pp, size_t alignment, size_t n); + Allocates a chunk of n bytes, aligned in accord with the alignment + argument. Differs from memalign only in that it (1) assigns the + allocated memory to *pp rather than returning it, (2) fails and + returns EINVAL if the alignment is not a power of two (3) fails and + returns ENOMEM if memory cannot be allocated. +*/ +DLMALLOC_EXPORT int dlposix_memalign(void**, size_t, size_t); + +/* + valloc(size_t n); + Equivalent to memalign(pagesize, n), where pagesize is the page + size of the system. If the pagesize is unknown, 4096 is used. +*/ +DLMALLOC_EXPORT void* dlvalloc(size_t); + +/* + mallopt(int parameter_number, int parameter_value) + Sets tunable parameters The format is to provide a + (parameter-number, parameter-value) pair. mallopt then sets the + corresponding parameter to the argument value if it can (i.e., so + long as the value is meaningful), and returns 1 if successful else + 0. To workaround the fact that mallopt is specified to use int, + not size_t parameters, the value -1 is specially treated as the + maximum unsigned size_t value. + + SVID/XPG/ANSI defines four standard param numbers for mallopt, + normally defined in malloc.h. None of these are use in this malloc, + so setting them has no effect. But this malloc also supports other + options in mallopt. See below for details. Briefly, supported + parameters are as follows (listed defaults are for "typical" + configurations). + + Symbol param # default allowed param values + M_TRIM_THRESHOLD -1 2*1024*1024 any (-1 disables) + M_GRANULARITY -2 page size any power of 2 >= page size + M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) +*/ +DLMALLOC_EXPORT int dlmallopt(int, int); + +/* + malloc_footprint(); + Returns the number of bytes obtained from the system. The total + number of bytes allocated by malloc, realloc etc., is less than this + value. Unlike mallinfo, this function returns only a precomputed + result, so can be called frequently to monitor memory consumption. + Even if locks are otherwise defined, this function does not use them, + so results might not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint(void); + +/* + malloc_max_footprint(); + Returns the maximum number of bytes obtained from the system. This + value will be greater than current footprint if deallocated space + has been reclaimed by the system. The peak number of bytes allocated + by malloc, realloc etc., is less than this value. Unlike mallinfo, + this function returns only a precomputed result, so can be called + frequently to monitor memory consumption. Even if locks are + otherwise defined, this function does not use them, so results might + not be up to date. +*/ +DLMALLOC_EXPORT size_t dlmalloc_max_footprint(void); + +/* + malloc_footprint_limit(); + Returns the number of bytes that the heap is allowed to obtain from + the system, returning the last value returned by + malloc_set_footprint_limit, or the maximum size_t value if + never set. The returned value reflects a permission. There is no + guarantee that this number of bytes can actually be obtained from + the system. +*/ +DLMALLOC_EXPORT size_t dlmalloc_footprint_limit(); + +/* + malloc_set_footprint_limit(); + Sets the maximum number of bytes to obtain from the system, causing + failure returns from malloc and related functions upon attempts to + exceed this value. The argument value may be subject to page + rounding to an enforceable limit; this actual value is returned. + Using an argument of the maximum possible size_t effectively + disables checks. If the argument is less than or equal to the + current malloc_footprint, then all future allocations that require + additional system memory will fail. However, invocation cannot + retroactively deallocate existing used memory. +*/ +DLMALLOC_EXPORT size_t dlmalloc_set_footprint_limit(size_t bytes); + +#if MALLOC_INSPECT_ALL +/* + malloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg); + Traverses the heap and calls the given handler for each managed + region, skipping all bytes that are (or may be) used for bookkeeping + purposes. Traversal does not include include chunks that have been + directly memory mapped. Each reported region begins at the start + address, and continues up to but not including the end address. The + first used_bytes of the region contain allocated data. If + used_bytes is zero, the region is unallocated. The handler is + invoked with the given callback argument. If locks are defined, they + are held during the entire traversal. It is a bad idea to invoke + other malloc functions from within the handler. + + For example, to count the number of in-use chunks with size greater + than 1000, you could write: + static int count = 0; + void count_chunks(void* start, void* end, size_t used, void* arg) { + if (used >= 1000) ++count; + } + then: + malloc_inspect_all(count_chunks, NULL); + + malloc_inspect_all is compiled only if MALLOC_INSPECT_ALL is defined. +*/ +DLMALLOC_EXPORT void dlmalloc_inspect_all(void(*handler)(void*, void *, size_t, void*), + void* arg); + +#endif /* MALLOC_INSPECT_ALL */ + +#if !NO_MALLINFO +/* + mallinfo() + Returns (by copy) a struct containing various summary statistics: + + arena: current total non-mmapped bytes allocated from system + ordblks: the number of free chunks + smblks: always zero. + hblks: current number of mmapped regions + hblkhd: total bytes held in mmapped regions + usmblks: the maximum total allocated space. This will be greater + than current total if trimming has occurred. + fsmblks: always zero + uordblks: current total allocated space (normal or mmapped) + fordblks: total free space + keepcost: the maximum number of bytes that could ideally be released + back to system via malloc_trim. ("ideally" means that + it ignores page restrictions etc.) + + Because these fields are ints, but internal bookkeeping may + be kept as longs, the reported values may wrap around zero and + thus be inaccurate. +*/ +DLMALLOC_EXPORT struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ + +/* + independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); + + independent_calloc is similar to calloc, but instead of returning a + single cleared space, it returns an array of pointers to n_elements + independent elements that can hold contents of size elem_size, each + of which starts out cleared, and can be independently freed, + realloc'ed etc. The elements are guaranteed to be adjacently + allocated (this is not guaranteed to occur with multiple callocs or + mallocs), which may also improve cache locality in some + applications. + + The "chunks" argument is optional (i.e., may be null, which is + probably the most typical usage). If it is null, the returned array + is itself dynamically allocated and should also be freed when it is + no longer needed. Otherwise, the chunks array must be of at least + n_elements in length. It is filled in with the pointers to the + chunks. + + In either case, independent_calloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and "chunks" + is null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_calloc simplifies and speeds up implementations of many + kinds of pools. It may also be useful when constructing large data + structures that initially have a fixed number of fixed-sized nodes, + but the number is not known at compile time, and some of the nodes + may later need to be freed. For example: + + struct Node { int item; struct Node* next; }; + + struct Node* build_list() { + struct Node** pool; + int n = read_number_of_nodes_needed(); + if (n <= 0) return 0; + pool = (struct Node**)(independent_calloc(n, sizeof(struct Node), 0); + if (pool == 0) die(); + // organize into a linked list... + struct Node* first = pool[0]; + for (i = 0; i < n-1; ++i) + pool[i]->next = pool[i+1]; + free(pool); // Can now free the array (or not, if it is needed later) + return first; + } +*/ +DLMALLOC_EXPORT void** dlindependent_calloc(size_t, size_t, void**); + +/* + independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); + + independent_comalloc allocates, all at once, a set of n_elements + chunks with sizes indicated in the "sizes" array. It returns + an array of pointers to these elements, each of which can be + independently freed, realloc'ed etc. The elements are guaranteed to + be adjacently allocated (this is not guaranteed to occur with + multiple callocs or mallocs), which may also improve cache locality + in some applications. + + The "chunks" argument is optional (i.e., may be null). If it is null + the returned array is itself dynamically allocated and should also + be freed when it is no longer needed. Otherwise, the chunks array + must be of at least n_elements in length. It is filled in with the + pointers to the chunks. + + In either case, independent_comalloc returns this pointer array, or + null if the allocation failed. If n_elements is zero and chunks is + null, it returns a chunk representing an array with zero elements + (which should be freed if not wanted). + + Each element must be freed when it is no longer needed. This can be + done all at once using bulk_free. + + independent_comallac differs from independent_calloc in that each + element may have a different size, and also that it does not + automatically clear elements. + + independent_comalloc can be used to speed up allocation in cases + where several structs or objects must always be allocated at the + same time. For example: + + struct Head { ... } + struct Foot { ... } + + void send_message(char* msg) { + int msglen = strlen(msg); + size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) }; + void* chunks[3]; + if (independent_comalloc(3, sizes, chunks) == 0) + die(); + struct Head* head = (struct Head*)(chunks[0]); + char* body = (char*)(chunks[1]); + struct Foot* foot = (struct Foot*)(chunks[2]); + // ... + } + + In general though, independent_comalloc is worth using only for + larger values of n_elements. For small values, you probably won't + detect enough difference from series of malloc calls to bother. + + Overuse of independent_comalloc can increase overall memory usage, + since it cannot reuse existing noncontiguous small chunks that + might be available for some of the elements. +*/ +DLMALLOC_EXPORT void** dlindependent_comalloc(size_t, size_t*, void**); + +/* + bulk_free(void* array[], size_t n_elements) + Frees and clears (sets to null) each non-null pointer in the given + array. This is likely to be faster than freeing them one-by-one. + If footers are used, pointers that have been allocated in different + mspaces are not freed or cleared, and the count of all such pointers + is returned. For large arrays of pointers with poor locality, it + may be worthwhile to sort this array before calling bulk_free. +*/ +DLMALLOC_EXPORT size_t dlbulk_free(void**, size_t n_elements); + +/* + pvalloc(size_t n); + Equivalent to valloc(minimum-page-that-holds(n)), that is, + round up n to nearest pagesize. + */ +DLMALLOC_EXPORT void* dlpvalloc(size_t); + +/* + malloc_trim(size_t pad); + + If possible, gives memory back to the system (via negative arguments + to sbrk) if there is unused memory at the `high' end of the malloc + pool or in unused MMAP segments. You can call this after freeing + large blocks of memory to potentially reduce the system-level memory + requirements of a program. However, it cannot guarantee to reduce + memory. Under some allocation patterns, some large free blocks of + memory will be locked between two used chunks, so they cannot be + given back to the system. + + The `pad' argument to malloc_trim represents the amount of free + trailing space to leave untrimmed. If this argument is zero, only + the minimum amount of memory to maintain internal data structures + will be left. Non-zero arguments can be supplied to maintain enough + trailing space to service future expected allocations without having + to re-obtain memory from the system. + + Malloc_trim returns 1 if it actually released any memory, else 0. +*/ +DLMALLOC_EXPORT int dlmalloc_trim(size_t); + +/* + malloc_stats(); + Prints on stderr the amount of space obtained from the system (both + via sbrk and mmap), the maximum amount (which may be more than + current if malloc_trim and/or munmap got called), and the current + number of bytes allocated via malloc (or realloc, etc) but not yet + freed. Note that this is the number of bytes allocated, not the + number requested. It will be larger than the number requested + because of alignment and bookkeeping overhead. Because it includes + alignment wastage as being in use, this figure may be greater than + zero even when no user-level chunks are allocated. + + The reported current and maximum system memory can be inaccurate if + a program makes other calls to system memory allocation functions + (normally sbrk) outside of malloc. + + malloc_stats prints only the most commonly interesting statistics. + More information can be obtained by calling mallinfo. +*/ +DLMALLOC_EXPORT void dlmalloc_stats(void); + +/* + malloc_usable_size(void* p); + + Returns the number of bytes you can actually use in + an allocated chunk, which may be more than you requested (although + often not) due to alignment and minimum size constraints. + You can use this many bytes without worrying about + overwriting other allocated objects. This is not a particularly great + programming practice. malloc_usable_size can be more useful in + debugging and assertions, for example: + + p = malloc(n); + assert(malloc_usable_size(p) >= 256); +*/ +size_t dlmalloc_usable_size(void*); + +#endif /* ONLY_MSPACES */ + +#if MSPACES + +/* + mspace is an opaque type representing an independent + region of space that supports mspace_malloc, etc. +*/ +typedef void* mspace; + +/* + create_mspace creates and returns a new independent space with the + given initial capacity, or, if 0, the default granularity size. It + returns null if there is no system memory available to create the + space. If argument locked is non-zero, the space uses a separate + lock to control access. The capacity of the space will grow + dynamically as needed to service mspace_malloc requests. You can + control the sizes of incremental increases of this space by + compiling with a different DEFAULT_GRANULARITY or dynamically + setting with mallopt(M_GRANULARITY, value). +*/ +DLMALLOC_EXPORT mspace create_mspace(size_t capacity, int locked); + +/* + destroy_mspace destroys the given space, and attempts to return all + of its memory back to the system, returning the total number of + bytes freed. After destruction, the results of access to all memory + used by the space become undefined. +*/ +DLMALLOC_EXPORT size_t destroy_mspace(mspace msp); + +/* + create_mspace_with_base uses the memory supplied as the initial base + of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this + space is used for bookkeeping, so the capacity must be at least this + large. (Otherwise 0 is returned.) When this initial space is + exhausted, additional memory will be obtained from the system. + Destroying this space will deallocate all additionally allocated + space (if possible) but not the initial base. +*/ +DLMALLOC_EXPORT mspace create_mspace_with_base(void* base, size_t capacity, int locked); + +/* + mspace_track_large_chunks controls whether requests for large chunks + are allocated in their own untracked mmapped regions, separate from + others in this mspace. By default large chunks are not tracked, + which reduces fragmentation. However, such chunks are not + necessarily released to the system upon destroy_mspace. Enabling + tracking by setting to true may increase fragmentation, but avoids + leakage when relying on destroy_mspace to release all memory + allocated using this space. The function returns the previous + setting. +*/ +DLMALLOC_EXPORT int mspace_track_large_chunks(mspace msp, int enable); + + +/* + mspace_malloc behaves as malloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_malloc(mspace msp, size_t bytes); + +/* + mspace_free behaves as free, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_free is not actually needed. + free may be called instead of mspace_free because freed chunks from + any space are handled by their originating spaces. +*/ +DLMALLOC_EXPORT void mspace_free(mspace msp, void* mem); + +/* + mspace_realloc behaves as realloc, but operates within + the given space. + + If compiled with FOOTERS==1, mspace_realloc is not actually + needed. realloc may be called instead of mspace_realloc because + realloced chunks from any space are handled by their originating + spaces. +*/ +DLMALLOC_EXPORT void* mspace_realloc(mspace msp, void* mem, size_t newsize); + +/* + mspace_calloc behaves as calloc, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + +/* + mspace_memalign behaves as memalign, but operates within + the given space. +*/ +DLMALLOC_EXPORT void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + +/* + mspace_independent_calloc behaves as independent_calloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]); + +/* + mspace_independent_comalloc behaves as independent_comalloc, but + operates within the given space. +*/ +DLMALLOC_EXPORT void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]); + +/* + mspace_footprint() returns the number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_footprint(mspace msp); + +/* + mspace_max_footprint() returns the peak number of bytes obtained from the + system for this space. +*/ +DLMALLOC_EXPORT size_t mspace_max_footprint(mspace msp); + + +#if !NO_MALLINFO +/* + mspace_mallinfo behaves as mallinfo, but reports properties of + the given space. +*/ +DLMALLOC_EXPORT struct mallinfo mspace_mallinfo(mspace msp); +#endif /* NO_MALLINFO */ + +/* + malloc_usable_size(void* p) behaves the same as malloc_usable_size; +*/ +DLMALLOC_EXPORT size_t mspace_usable_size(const void* mem); + +/* + mspace_malloc_stats behaves as malloc_stats, but reports + properties of the given space. +*/ +DLMALLOC_EXPORT void mspace_malloc_stats(mspace msp); + +/* + mspace_trim behaves as malloc_trim, but + operates within the given space. +*/ +DLMALLOC_EXPORT int mspace_trim(mspace msp, size_t pad); + +/* + An alias for mallopt. +*/ +DLMALLOC_EXPORT int mspace_mallopt(int, int); + +#endif /* MSPACES */ + +#ifdef __cplusplus +} /* end of extern "C" */ +#endif /* __cplusplus */ + +/* + ======================================================================== + To make a fully customizable malloc.h header file, cut everything + above this line, put into file malloc.h, edit to suit, and #include it + on the next line, as well as in programs that use this malloc. + ======================================================================== +*/ + +/* #include "malloc.h" */ + +/*------------------------------ internal #includes ---------------------- */ + +#ifdef _MSC_VER +#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ +#endif /* _MSC_VER */ +#if !NO_MALLOC_STATS +#include /* for printing in malloc_stats */ +#endif /* NO_MALLOC_STATS */ +#ifndef LACKS_ERRNO_H +#include /* for MALLOC_FAILURE_ACTION */ +#endif /* LACKS_ERRNO_H */ +#ifdef DEBUG +#if ABORT_ON_ASSERT_FAILURE +#undef assert +#define assert(x) if(!(x)) ABORT +#else /* ABORT_ON_ASSERT_FAILURE */ +#include +#endif /* ABORT_ON_ASSERT_FAILURE */ +#else /* DEBUG */ +#ifndef assert +#define assert(x) +#endif +#define DEBUG 0 +#endif /* DEBUG */ +#if !defined(WIN32) && !defined(LACKS_TIME_H) +#include /* for magic initialization */ +#endif /* WIN32 */ +#ifndef LACKS_STDLIB_H +#include /* for abort() */ +#endif /* LACKS_STDLIB_H */ +#ifndef LACKS_STRING_H +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ +#if USE_BUILTIN_FFS +#ifndef LACKS_STRINGS_H +#include /* for ffs */ +#endif /* LACKS_STRINGS_H */ +#endif /* USE_BUILTIN_FFS */ +#if HAVE_MMAP +#ifndef LACKS_SYS_MMAN_H +/* On some versions of linux, mremap decl in mman.h needs __USE_GNU set */ +#if (defined(linux) && !defined(__USE_GNU)) +#define __USE_GNU 1 +#include /* for mmap */ +#undef __USE_GNU +#else +#include /* for mmap */ +#endif /* linux */ +#endif /* LACKS_SYS_MMAN_H */ +#ifndef LACKS_FCNTL_H +#include +#endif /* LACKS_FCNTL_H */ +#endif /* HAVE_MMAP */ +#ifndef LACKS_UNISTD_H +#include /* for sbrk, sysconf */ +#else /* LACKS_UNISTD_H */ +#if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) +extern void* sbrk(ptrdiff_t); +#endif /* FreeBSD etc */ +#endif /* LACKS_UNISTD_H */ + +/* Declarations for locking */ +#if USE_LOCKS +#ifndef WIN32 +#if defined (__SVR4) && defined (__sun) /* solaris */ +#include +#elif !defined(LACKS_SCHED_H) +#include +#endif /* solaris or LACKS_SCHED_H */ +#if (defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0) || !USE_SPIN_LOCKS +#include +#endif /* USE_RECURSIVE_LOCKS ... */ +#elif defined(_MSC_VER) +#ifndef _M_AMD64 +/* These are already defined on AMD64 builds */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +LONG __cdecl _InterlockedCompareExchange(LONG volatile *Dest, LONG Exchange, LONG Comp); +LONG __cdecl _InterlockedExchange(LONG volatile *Target, LONG Value); +#ifdef __cplusplus +} +#endif /* __cplusplus */ +#endif /* _M_AMD64 */ +#pragma intrinsic (_InterlockedCompareExchange) +#pragma intrinsic (_InterlockedExchange) +#define interlockedcompareexchange _InterlockedCompareExchange +#define interlockedexchange _InterlockedExchange +#elif defined(WIN32) && defined(__GNUC__) +#define interlockedcompareexchange(a, b, c) __sync_val_compare_and_swap(a, c, b) +#define interlockedexchange __sync_lock_test_and_set +#endif /* Win32 */ +#else /* USE_LOCKS */ +#endif /* USE_LOCKS */ + +#ifndef LOCK_AT_FORK +#define LOCK_AT_FORK 0 +#endif + +/* Declarations for bit scanning on win32 */ +#if defined(_MSC_VER) && _MSC_VER>=1300 +#ifndef BitScanForward /* Try to avoid pulling in WinNT.h */ +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ +unsigned char _BitScanForward(unsigned long *index, unsigned long mask); +unsigned char _BitScanReverse(unsigned long *index, unsigned long mask); +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#define BitScanForward _BitScanForward +#define BitScanReverse _BitScanReverse +#pragma intrinsic(_BitScanForward) +#pragma intrinsic(_BitScanReverse) +#endif /* BitScanForward */ +#endif /* defined(_MSC_VER) && _MSC_VER>=1300 */ + +#ifndef WIN32 +#ifndef malloc_getpagesize +# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +# ifndef _SC_PAGE_SIZE +# define _SC_PAGE_SIZE _SC_PAGESIZE +# endif +# endif +# ifdef _SC_PAGE_SIZE +# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) +# else +# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) + extern size_t getpagesize(); +# define malloc_getpagesize getpagesize() +# else +# ifdef WIN32 /* use supplied emulation of getpagesize */ +# define malloc_getpagesize getpagesize() +# else +# ifndef LACKS_SYS_PARAM_H +# include +# endif +# ifdef EXEC_PAGESIZE +# define malloc_getpagesize EXEC_PAGESIZE +# else +# ifdef NBPG +# ifndef CLSIZE +# define malloc_getpagesize NBPG +# else +# define malloc_getpagesize (NBPG * CLSIZE) +# endif +# else +# ifdef NBPC +# define malloc_getpagesize NBPC +# else +# ifdef PAGESIZE +# define malloc_getpagesize PAGESIZE +# else /* just guess */ +# define malloc_getpagesize ((size_t)4096U) +# endif +# endif +# endif +# endif +# endif +# endif +# endif +#endif +#endif + +/* ------------------- size_t and alignment properties -------------------- */ + +/* The byte and bit size of a size_t */ +#define SIZE_T_SIZE (sizeof(size_t)) +#define SIZE_T_BITSIZE (sizeof(size_t) << 3) + +/* Some constants coerced to size_t */ +/* Annoying but necessary to avoid errors on some platforms */ +#define SIZE_T_ZERO ((size_t)0) +#define SIZE_T_ONE ((size_t)1) +#define SIZE_T_TWO ((size_t)2) +#define SIZE_T_FOUR ((size_t)4) +#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) +#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) +#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) +#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) + +/* The bit mask value corresponding to MALLOC_ALIGNMENT */ +#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) + +/* True if address a has acceptable alignment */ +#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) + +/* the number of bytes to offset an address to align it */ +#define align_offset(A)\ + ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ + ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) + +/* -------------------------- MMAP preliminaries ------------------------- */ + +/* + If HAVE_MORECORE or HAVE_MMAP are false, we just define calls and + checks to fail so compiler optimizer can delete code rather than + using so many "#if"s. +*/ + + +/* MORECORE and MMAP must return MFAIL on failure */ +#define MFAIL ((void*)(MAX_SIZE_T)) +#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ + +#if HAVE_MMAP + +#ifndef WIN32 +#define MUNMAP_DEFAULT(a, s) munmap((a), (s)) +#define MMAP_PROT (PROT_READ|PROT_WRITE) +#if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) +#define MAP_ANONYMOUS MAP_ANON +#endif /* MAP_ANON */ +#ifdef MAP_ANONYMOUS +#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) +#define MMAP_DEFAULT(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) +#else /* MAP_ANONYMOUS */ +/* + Nearly all versions of mmap support MAP_ANONYMOUS, so the following + is unlikely to be needed, but is supplied just in case. +*/ +#define MMAP_FLAGS (MAP_PRIVATE) +static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ +#define MMAP_DEFAULT(s) ((dev_zero_fd < 0) ? \ + (dev_zero_fd = open("/dev/zero", O_RDWR), \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) +#endif /* MAP_ANONYMOUS */ + +#define DIRECT_MMAP_DEFAULT(s) MMAP_DEFAULT(s) + +#else /* WIN32 */ + +/* Win32 MMAP via VirtualAlloc */ +static FORCEINLINE void* win32mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ +static FORCEINLINE void* win32direct_mmap(size_t size) { + void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, + PAGE_READWRITE); + return (ptr != 0)? ptr: MFAIL; +} + +/* This function supports releasing coalesed segments */ +static FORCEINLINE int win32munmap(void* ptr, size_t size) { + MEMORY_BASIC_INFORMATION minfo; + char* cptr = (char*)ptr; + while (size) { + if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || + minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; +} + +#define MMAP_DEFAULT(s) win32mmap(s) +#define MUNMAP_DEFAULT(a, s) win32munmap((a), (s)) +#define DIRECT_MMAP_DEFAULT(s) win32direct_mmap(s) +#endif /* WIN32 */ +#endif /* HAVE_MMAP */ + +#if HAVE_MREMAP +#ifndef WIN32 +#define MREMAP_DEFAULT(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) +#endif /* WIN32 */ +#endif /* HAVE_MREMAP */ + +/** + * Define CALL_MORECORE + */ +#if HAVE_MORECORE + #ifdef MORECORE + #define CALL_MORECORE(S) MORECORE(S) + #else /* MORECORE */ + #define CALL_MORECORE(S) MORECORE_DEFAULT(S) + #endif /* MORECORE */ +#else /* HAVE_MORECORE */ + #define CALL_MORECORE(S) MFAIL +#endif /* HAVE_MORECORE */ + +/** + * Define CALL_MMAP/CALL_MUNMAP/CALL_DIRECT_MMAP + */ +#if HAVE_MMAP + #define USE_MMAP_BIT (SIZE_T_ONE) + + #ifdef MMAP + #define CALL_MMAP(s) MMAP(s) + #else /* MMAP */ + #define CALL_MMAP(s) MMAP_DEFAULT(s) + #endif /* MMAP */ + #ifdef MUNMAP + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) + #else /* MUNMAP */ + #define CALL_MUNMAP(a, s) MUNMAP_DEFAULT((a), (s)) + #endif /* MUNMAP */ + #ifdef DIRECT_MMAP + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #else /* DIRECT_MMAP */ + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP_DEFAULT(s) + #endif /* DIRECT_MMAP */ +#else /* HAVE_MMAP */ + #define USE_MMAP_BIT (SIZE_T_ZERO) + + #define MMAP(s) MFAIL + #define MUNMAP(a, s) (-1) + #define DIRECT_MMAP(s) MFAIL + #define CALL_DIRECT_MMAP(s) DIRECT_MMAP(s) + #define CALL_MMAP(s) MMAP(s) + #define CALL_MUNMAP(a, s) MUNMAP((a), (s)) +#endif /* HAVE_MMAP */ + +/** + * Define CALL_MREMAP + */ +#if HAVE_MMAP && HAVE_MREMAP + #ifdef MREMAP + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP((addr), (osz), (nsz), (mv)) + #else /* MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MREMAP_DEFAULT((addr), (osz), (nsz), (mv)) + #endif /* MREMAP */ +#else /* HAVE_MMAP && HAVE_MREMAP */ + #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL +#endif /* HAVE_MMAP && HAVE_MREMAP */ + +/* mstate bit set if continguous morecore disabled or failed */ +#define USE_NONCONTIGUOUS_BIT (4U) + +/* segment bit set in create_mspace_with_base */ +#define EXTERN_BIT (8U) + + +/* --------------------------- Lock preliminaries ------------------------ */ + +/* + When locks are defined, there is one global lock, plus + one per-mspace lock. + + The global lock_ensures that mparams.magic and other unique + mparams values are initialized only once. It also protects + sequences of calls to MORECORE. In many cases sys_alloc requires + two calls, that should not be interleaved with calls by other + threads. This does not protect against direct calls to MORECORE + by other threads not using this lock, so there is still code to + cope the best we can on interference. + + Per-mspace locks surround calls to malloc, free, etc. + By default, locks are simple non-reentrant mutexes. + + Because lock-protected regions generally have bounded times, it is + OK to use the supplied simple spinlocks. Spinlocks are likely to + improve performance for lightly contended applications, but worsen + performance under heavy contention. + + If USE_LOCKS is > 1, the definitions of lock routines here are + bypassed, in which case you will need to define the type MLOCK_T, + and at least INITIAL_LOCK, DESTROY_LOCK, ACQUIRE_LOCK, RELEASE_LOCK + and TRY_LOCK. You must also declare a + static MLOCK_T malloc_global_mutex = { initialization values };. + +*/ + +#if !USE_LOCKS +#define USE_LOCK_BIT (0U) +#define INITIAL_LOCK(l) (0) +#define DESTROY_LOCK(l) (0) +#define ACQUIRE_MALLOC_GLOBAL_LOCK() +#define RELEASE_MALLOC_GLOBAL_LOCK() + +#else +#if USE_LOCKS > 1 +/* ----------------------- User-defined locks ------------------------ */ +/* Define your own lock implementation here */ +/* #define INITIAL_LOCK(lk) ... */ +/* #define DESTROY_LOCK(lk) ... */ +/* #define ACQUIRE_LOCK(lk) ... */ +/* #define RELEASE_LOCK(lk) ... */ +/* #define TRY_LOCK(lk) ... */ +/* static MLOCK_T malloc_global_mutex = ... */ + +#elif USE_SPIN_LOCKS + +/* First, define CAS_LOCK and CLEAR_LOCK on ints */ +/* Note CAS_LOCK defined to return 0 on success */ + +#if defined(__GNUC__)&& (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 1)) +#define CAS_LOCK(sl) __sync_lock_test_and_set(sl, 1) +#define CLEAR_LOCK(sl) __sync_lock_release(sl) + +#elif (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) +/* Custom spin locks for older gcc on x86 */ +static FORCEINLINE int x86_cas_lock(int *sl) { + int ret; + int val = 1; + int cmp = 0; + __asm__ __volatile__ ("lock; cmpxchgl %1, %2" + : "=a" (ret) + : "r" (val), "m" (*(sl)), "0"(cmp) + : "memory", "cc"); + return ret; +} + +static FORCEINLINE void x86_clear_lock(int* sl) { + assert(*sl != 0); + int prev = 0; + int ret; + __asm__ __volatile__ ("lock; xchgl %0, %1" + : "=r" (ret) + : "m" (*(sl)), "0"(prev) + : "memory"); +} + +#define CAS_LOCK(sl) x86_cas_lock(sl) +#define CLEAR_LOCK(sl) x86_clear_lock(sl) + +#else /* Win32 MSC */ +#define CAS_LOCK(sl) interlockedexchange(sl, (LONG)1) +#define CLEAR_LOCK(sl) interlockedexchange (sl, (LONG)0) + +#endif /* ... gcc spins locks ... */ + +/* How to yield for a spin lock */ +#define SPINS_PER_YIELD 63 +#if defined(_MSC_VER) +#define SLEEP_EX_DURATION 50 /* delay for yield/sleep */ +#define SPIN_LOCK_YIELD SleepEx(SLEEP_EX_DURATION, FALSE) +#elif defined (__SVR4) && defined (__sun) /* solaris */ +#define SPIN_LOCK_YIELD thr_yield(); +#elif !defined(LACKS_SCHED_H) +#define SPIN_LOCK_YIELD sched_yield(); +#else +#define SPIN_LOCK_YIELD +#endif /* ... yield ... */ + +#if !defined(USE_RECURSIVE_LOCKS) || USE_RECURSIVE_LOCKS == 0 +/* Plain spin locks use single word (embedded in malloc_states) */ +static int spin_acquire_lock(int *sl) { + int spins = 0; + while (*(volatile int *)sl != 0 || CAS_LOCK(sl)) { + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } + return 0; +} + +#define MLOCK_T int +#define TRY_LOCK(sl) !CAS_LOCK(sl) +#define RELEASE_LOCK(sl) CLEAR_LOCK(sl) +#define ACQUIRE_LOCK(sl) (CAS_LOCK(sl)? spin_acquire_lock(sl) : 0) +#define INITIAL_LOCK(sl) (*sl = 0) +#define DESTROY_LOCK(sl) (0) +static MLOCK_T malloc_global_mutex = 0; + +#else /* USE_RECURSIVE_LOCKS */ +/* types for lock owners */ +#ifdef WIN32 +#define THREAD_ID_T DWORD +#define CURRENT_THREAD GetCurrentThreadId() +#define EQ_OWNER(X,Y) ((X) == (Y)) +#else +/* + Note: the following assume that pthread_t is a type that can be + initialized to (casted) zero. If this is not the case, you will need to + somehow redefine these or not use spin locks. +*/ +#define THREAD_ID_T pthread_t +#define CURRENT_THREAD pthread_self() +#define EQ_OWNER(X,Y) pthread_equal(X, Y) +#endif + +struct malloc_recursive_lock { + int sl; + unsigned int c; + THREAD_ID_T threadid; +}; + +#define MLOCK_T struct malloc_recursive_lock +static MLOCK_T malloc_global_mutex = { 0, 0, (THREAD_ID_T)0}; + +static FORCEINLINE void recursive_release_lock(MLOCK_T *lk) { + assert(lk->sl != 0); + if (--lk->c == 0) { + CLEAR_LOCK(&lk->sl); + } +} + +static FORCEINLINE int recursive_acquire_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + int spins = 0; + for (;;) { + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 0; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 0; + } + if ((++spins & SPINS_PER_YIELD) == 0) { + SPIN_LOCK_YIELD; + } + } +} + +static FORCEINLINE int recursive_try_lock(MLOCK_T *lk) { + THREAD_ID_T mythreadid = CURRENT_THREAD; + if (*((volatile int *)(&lk->sl)) == 0) { + if (!CAS_LOCK(&lk->sl)) { + lk->threadid = mythreadid; + lk->c = 1; + return 1; + } + } + else if (EQ_OWNER(lk->threadid, mythreadid)) { + ++lk->c; + return 1; + } + return 0; +} + +#define RELEASE_LOCK(lk) recursive_release_lock(lk) +#define TRY_LOCK(lk) recursive_try_lock(lk) +#define ACQUIRE_LOCK(lk) recursive_acquire_lock(lk) +#define INITIAL_LOCK(lk) ((lk)->threadid = (THREAD_ID_T)0, (lk)->sl = 0, (lk)->c = 0) +#define DESTROY_LOCK(lk) (0) +#endif /* USE_RECURSIVE_LOCKS */ + +#elif defined(WIN32) /* Win32 critical sections */ +#define MLOCK_T CRITICAL_SECTION +#define ACQUIRE_LOCK(lk) (EnterCriticalSection(lk), 0) +#define RELEASE_LOCK(lk) LeaveCriticalSection(lk) +#define TRY_LOCK(lk) TryEnterCriticalSection(lk) +#define INITIAL_LOCK(lk) (!InitializeCriticalSectionAndSpinCount((lk), 0x80000000|4000)) +#define DESTROY_LOCK(lk) (DeleteCriticalSection(lk), 0) +#define NEED_GLOBAL_LOCK_INIT + +static MLOCK_T malloc_global_mutex; +static volatile LONG malloc_global_mutex_status; + +/* Use spin loop to initialize global lock */ +static void init_malloc_global_mutex() { + for (;;) { + long stat = malloc_global_mutex_status; + if (stat > 0) + return; + /* transition to < 0 while initializing, then to > 0) */ + if (stat == 0 && + interlockedcompareexchange(&malloc_global_mutex_status, (LONG)-1, (LONG)0) == 0) { + InitializeCriticalSection(&malloc_global_mutex); + interlockedexchange(&malloc_global_mutex_status, (LONG)1); + return; + } + SleepEx(0, FALSE); + } +} + +#else /* pthreads-based locks */ +#define MLOCK_T pthread_mutex_t +#define ACQUIRE_LOCK(lk) pthread_mutex_lock(lk) +#define RELEASE_LOCK(lk) pthread_mutex_unlock(lk) +#define TRY_LOCK(lk) (!pthread_mutex_trylock(lk)) +#define INITIAL_LOCK(lk) pthread_init_lock(lk) +#define DESTROY_LOCK(lk) pthread_mutex_destroy(lk) + +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 && defined(linux) && !defined(PTHREAD_MUTEX_RECURSIVE) +/* Cope with old-style linux recursive lock initialization by adding */ +/* skipped internal declaration from pthread.h */ +extern int pthread_mutexattr_setkind_np __P ((pthread_mutexattr_t *__attr, + int __kind)); +#define PTHREAD_MUTEX_RECURSIVE PTHREAD_MUTEX_RECURSIVE_NP +#define pthread_mutexattr_settype(x,y) pthread_mutexattr_setkind_np(x,y) +#endif /* USE_RECURSIVE_LOCKS ... */ + +static MLOCK_T malloc_global_mutex = PTHREAD_MUTEX_INITIALIZER; + +static int pthread_init_lock (MLOCK_T *lk) { + pthread_mutexattr_t attr; + if (pthread_mutexattr_init(&attr)) return 1; +#if defined(USE_RECURSIVE_LOCKS) && USE_RECURSIVE_LOCKS != 0 + if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) return 1; +#endif + if (pthread_mutex_init(lk, &attr)) return 1; + if (pthread_mutexattr_destroy(&attr)) return 1; + return 0; +} + +#endif /* ... lock types ... */ + +/* Common code for all lock types */ +#define USE_LOCK_BIT (2U) + +#ifndef ACQUIRE_MALLOC_GLOBAL_LOCK +#define ACQUIRE_MALLOC_GLOBAL_LOCK() ACQUIRE_LOCK(&malloc_global_mutex); +#endif + +#ifndef RELEASE_MALLOC_GLOBAL_LOCK +#define RELEASE_MALLOC_GLOBAL_LOCK() RELEASE_LOCK(&malloc_global_mutex); +#endif + +#endif /* USE_LOCKS */ + +/* ----------------------- Chunk representations ------------------------ */ + +/* + (The following includes lightly edited explanations by Colin Plumb.) + + The malloc_chunk declaration below is misleading (but accurate and + necessary). It declares a "view" into memory allowing access to + necessary fields at known offsets from a given base. + + Chunks of memory are maintained using a `boundary tag' method as + originally described by Knuth. (See the paper by Paul Wilson + ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a survey of such + techniques.) Sizes of free chunks are stored both in the front of + each chunk and at the end. This makes consolidating fragmented + chunks into bigger chunks fast. The head fields also hold bits + representing whether chunks are free or in use. + + Here are some pictures to make it clearer. They are "exploded" to + show that the state of a chunk can be thought of as extending from + the high 31 bits of the head field of its header through the + prev_foot and PINUSE_BIT bit of the following chunk header. + + A chunk that's in use looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk (if P = 0) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 1| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | | + +- -+ + | | + +- -+ + | : + +- size - sizeof(size_t) available payload bytes -+ + : | + chunk-> +- -+ + | | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |1| + | Size of next chunk (may or may not be in use) | +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + And if it's free, it looks like this: + + chunk-> +- -+ + | User payload (must be in use, or we would have merged!) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |P| + | Size of this chunk 0| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Next pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Prev pointer | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- size - sizeof(struct chunk) unused bytes -+ + : | + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |0| + | Size of next chunk (must be in use, or we would have merged)| +-+ + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | : + +- User payload -+ + : | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |0| + +-+ + Note that since we always merge adjacent free chunks, the chunks + adjacent to a free chunk must be in use. + + Given a pointer to a chunk (which can be derived trivially from the + payload pointer) we can, in O(1) time, find out whether the adjacent + chunks are free, and if so, unlink them from the lists that they + are on and merge them with the current chunk. + + Chunks always begin on even word boundaries, so the mem portion + (which is returned to the user) is also on an even word boundary, and + thus at least double-word aligned. + + The P (PINUSE_BIT) bit, stored in the unused low-order bit of the + chunk size (which is always a multiple of two words), is an in-use + bit for the *previous* chunk. If that bit is *clear*, then the + word before the current chunk size contains the previous chunk + size, and can be used to find the front of the previous chunk. + The very first chunk allocated always has this bit set, preventing + access to non-existent (or non-owned) memory. If pinuse is set for + any given chunk, then you CANNOT determine the size of the + previous chunk, and might even get a memory addressing fault when + trying to do so. + + The C (CINUSE_BIT) bit, stored in the unused second-lowest bit of + the chunk size redundantly records whether the current chunk is + inuse (unless the chunk is mmapped). This redundancy enables usage + checks within free and realloc, and reduces indirection when freeing + and consolidating chunks. + + Each freshly allocated chunk must have both cinuse and pinuse set. + That is, each allocated chunk borders either a previously allocated + and still in-use chunk, or the base of its memory arena. This is + ensured by making all allocations from the `lowest' part of any + found chunk. Further, no free chunk physically borders another one, + so each free chunk is known to be preceded and followed by either + inuse chunks or the ends of memory. + + Note that the `foot' of the current chunk is actually represented + as the prev_foot of the NEXT chunk. This makes it easier to + deal with alignments etc but can be very confusing when trying + to extend or adapt this code. + + The exceptions to all this are + + 1. The special chunk `top' is the top-most available chunk (i.e., + the one bordering the end of available memory). It is treated + specially. Top is never included in any bin, is used only if + no other chunk is available, and is released back to the + system if it is very large (see M_TRIM_THRESHOLD). In effect, + the top chunk is treated as larger (and thus less well + fitting) than any other available chunk. The top chunk + doesn't update its trailing size field since there is no next + contiguous chunk that would have to index off it. However, + space is still allocated for it (TOP_FOOT_SIZE) to enable + separation or merging when space is extended. + + 3. Chunks allocated via mmap, have both cinuse and pinuse bits + cleared in their head fields. Because they are allocated + one-by-one, each must carry its own prev_foot field, which is + also used to hold the offset this chunk has within its mmapped + region, which is needed to preserve alignment. Each mmapped + chunk is trailed by the first two fields of a fake next-chunk + for sake of usage checks. + +*/ + +struct malloc_chunk { + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk* fd; /* double links -- used only if free. */ + struct malloc_chunk* bk; +}; + +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk* mchunkptr; +typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ +typedef unsigned int bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ + +/* ------------------- Chunks sizes and alignments ----------------------- */ + +#define MCHUNK_SIZE (sizeof(mchunk)) + +#if FOOTERS +#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +#else /* FOOTERS */ +#define CHUNK_OVERHEAD (SIZE_T_SIZE) +#endif /* FOOTERS */ + +/* MMapped chunks need a second word of overhead ... */ +#define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +/* ... and additional padding for fake next-chunk at foot */ +#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) + +/* The smallest size we can malloc is an aligned minimal chunk */ +#define MIN_CHUNK_SIZE\ + ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* conversion from malloc headers to user pointers, and back */ +#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) +#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) +/* chunk associated with aligned address A */ +#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) + +/* Bounds on request (not chunk) sizes. */ +#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) + +/* pad request bytes into a usable size */ +#define pad_request(req) \ + (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + +/* pad request, checking for minimum (but not maximum) */ +#define request2size(req) \ + (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) + + +/* ------------------ Operations on head and foot fields ----------------- */ + +/* + The head field of a chunk is or'ed with PINUSE_BIT when previous + adjacent chunk in use, and or'ed with CINUSE_BIT if this chunk is in + use, unless mmapped, in which case both bits are cleared. + + FLAG4_BIT is not used by this malloc, but might be useful in extensions. +*/ + +#define PINUSE_BIT (SIZE_T_ONE) +#define CINUSE_BIT (SIZE_T_TWO) +#define FLAG4_BIT (SIZE_T_FOUR) +#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) +#define FLAG_BITS (PINUSE_BIT|CINUSE_BIT|FLAG4_BIT) + +/* Head value for fenceposts */ +#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) + +/* extraction of fields from head words */ +#define cinuse(p) ((p)->head & CINUSE_BIT) +#define pinuse(p) ((p)->head & PINUSE_BIT) +#define flag4inuse(p) ((p)->head & FLAG4_BIT) +#define is_inuse(p) (((p)->head & INUSE_BITS) != PINUSE_BIT) +#define is_mmapped(p) (((p)->head & INUSE_BITS) == 0) + +#define chunksize(p) ((p)->head & ~(FLAG_BITS)) + +#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) +#define set_flag4(p) ((p)->head |= FLAG4_BIT) +#define clear_flag4(p) ((p)->head &= ~FLAG4_BIT) + +/* Treat space at ptr +/- offset as a chunk */ +#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) +#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) + +/* Ptr to next or previous physical malloc_chunk. */ +#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~FLAG_BITS))) +#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) )) + +/* extract next chunk's pinuse bit */ +#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) + +/* Get/set size at footer */ +#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) +#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) + +/* Set size, pinuse bit, and foot */ +#define set_size_and_pinuse_of_free_chunk(p, s)\ + ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) + +/* Set size, pinuse bit, foot, and clear next pinuse */ +#define set_free_with_pinuse(p, s, n)\ + (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) + +/* Get the internal overhead associated with chunk p */ +#define overhead_for(p)\ + (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) + +/* Return true if malloced space is not necessarily cleared */ +#if MMAP_CLEARS +#define calloc_must_clear(p) (!is_mmapped(p)) +#else /* MMAP_CLEARS */ +#define calloc_must_clear(p) (1) +#endif /* MMAP_CLEARS */ + +/* ---------------------- Overlaid data structures ----------------------- */ + +/* + When chunks are not in use, they are treated as nodes of either + lists or trees. + + "Small" chunks are stored in circular doubly-linked lists, and look + like this: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk in list | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space (may be 0 bytes long) . + . . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Larger chunks are kept in a form of bitwise digital trees (aka + tries) keyed on chunksizes. Because malloc_tree_chunks are only for + free chunks greater than 256 bytes, their size doesn't impose any + constraints on user chunk sizes. Each node looks like: + + chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Size of previous chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `head:' | Size of chunk, in bytes |P| + mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Forward pointer to next chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Back pointer to previous chunk of same size | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to left child (child[0]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to right child (child[1]) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Pointer to parent | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | bin index of this chunk | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | Unused space . + . | +nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + `foot:' | Size of chunk, in bytes | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + + Each tree holding treenodes is a tree of unique chunk sizes. Chunks + of the same size are arranged in a circularly-linked list, with only + the oldest chunk (the next to be used, in our FIFO ordering) + actually in the tree. (Tree members are distinguished by a non-null + parent pointer.) If a chunk with the same size an an existing node + is inserted, it is linked off the existing node using pointers that + work in the same way as fd/bk pointers of small chunks. + + Each tree contains a power of 2 sized range of chunk sizes (the + smallest is 0x100 <= x < 0x180), which is is divided in half at each + tree level, with the chunks in the smaller half of the range (0x100 + <= x < 0x140 for the top nose) in the left subtree and the larger + half (0x140 <= x < 0x180) in the right subtree. This is, of course, + done by inspecting individual bits. + + Using these rules, each node's left subtree contains all smaller + sizes than its right subtree. However, the node at the root of each + subtree has no particular ordering relationship to either. (The + dividing line between the subtree sizes is based on trie relation.) + If we remove the last chunk of a given size from the interior of the + tree, we need to replace it with a leaf node. The tree ordering + rules permit a node to be replaced by any leaf below it. + + The smallest chunk in a tree (a common operation in a best-fit + allocator) can be found by walking a path to the leftmost leaf in + the tree. Unlike a usual binary tree, where we follow left child + pointers until we reach a null, here we follow the right child + pointer any time the left one is null, until we reach a leaf with + both child pointers null. The smallest chunk in the tree will be + somewhere along that path. + + The worst case number of steps to add, find, or remove a node is + bounded by the number of bits differentiating chunks within + bins. Under current bin calculations, this ranges from 6 up to 21 + (for 32 bit sizes) or up to 53 (for 64 bit sizes). The typical case + is of course much better. +*/ + +struct malloc_tree_chunk { + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk* fd; + struct malloc_tree_chunk* bk; + + struct malloc_tree_chunk* child[2]; + struct malloc_tree_chunk* parent; + bindex_t index; +}; + +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk* tchunkptr; +typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ + +/* A little helper macro for trees */ +#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) + +/* ----------------------------- Segments -------------------------------- */ + +/* + Each malloc space may include non-contiguous segments, held in a + list headed by an embedded malloc_segment record representing the + top-most space. Segments also include flags holding properties of + the space. Large chunks that are directly allocated by mmap are not + included in this list. They are instead independently created and + destroyed without otherwise keeping track of them. + + Segment management mainly comes into play for spaces allocated by + MMAP. Any call to MMAP might or might not return memory that is + adjacent to an existing segment. MORECORE normally contiguously + extends the current space, so this space is almost always adjacent, + which is simpler and faster to deal with. (This is why MORECORE is + used preferentially to MMAP when both are available -- see + sys_alloc.) When allocating using MMAP, we don't use any of the + hinting mechanisms (inconsistently) supported in various + implementations of unix mmap, or distinguish reserving from + committing memory. Instead, we just ask for space, and exploit + contiguity when we get it. It is probably possible to do + better than this on some systems, but no general scheme seems + to be significantly better. + + Management entails a simpler variant of the consolidation scheme + used for chunks to reduce fragmentation -- new adjacent memory is + normally prepended or appended to an existing segment. However, + there are limitations compared to chunk consolidation that mostly + reflect the fact that segment processing is relatively infrequent + (occurring only when getting memory from system) and that we + don't expect to have huge numbers of segments: + + * Segments are not indexed, so traversal requires linear scans. (It + would be possible to index these, but is not worth the extra + overhead and complexity for most programs on most platforms.) + * New segments are only appended to old ones when holding top-most + memory; if they cannot be prepended to others, they are held in + different segments. + + Except for the top-most segment of an mstate, each segment record + is kept at the tail of its segment. Segments are added by pushing + segment records onto the list headed by &mstate.seg for the + containing mstate. + + Segment flags control allocation/merge/deallocation policies: + * If EXTERN_BIT set, then we did not allocate this segment, + and so should not try to deallocate or merge with others. + (This currently holds only for the initial segment passed + into create_mspace_with_base.) + * If USE_MMAP_BIT set, the segment may be merged with + other surrounding mmapped segments and trimmed/de-allocated + using munmap. + * If neither bit is set, then the segment was obtained using + MORECORE so can be merged with surrounding MORECORE'd segments + and deallocated/trimmed using MORECORE with negative arguments. +*/ + +struct malloc_segment { + char* base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment* next; /* ptr to next segment */ + flag_t sflags; /* mmap and extern flag */ +}; + +#define is_mmapped_segment(S) ((S)->sflags & USE_MMAP_BIT) +#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) + +typedef struct malloc_segment msegment; +typedef struct malloc_segment* msegmentptr; + +/* ---------------------------- malloc_state ----------------------------- */ + +/* + A malloc_state holds all of the bookkeeping for a space. + The main fields are: + + Top + The topmost chunk of the currently active segment. Its size is + cached in topsize. The actual size of topmost space is + topsize+TOP_FOOT_SIZE, which includes space reserved for adding + fenceposts and segment records if necessary when getting more + space from the system. The size at which to autotrim top is + cached from mparams in trim_check, except that it is disabled if + an autotrim fails. + + Designated victim (dv) + This is the preferred chunk for servicing small requests that + don't have exact fits. It is normally the chunk split off most + recently to service another small request. Its size is cached in + dvsize. The link fields of this chunk are not maintained since it + is not kept in a bin. + + SmallBins + An array of bin headers for free chunks. These bins hold chunks + with sizes less than MIN_LARGE_SIZE bytes. Each bin contains + chunks of all the same size, spaced 8 bytes apart. To simplify + use in double-linked lists, each bin header acts as a malloc_chunk + pointing to the real first node, if it exists (else pointing to + itself). This avoids special-casing for headers. But to avoid + waste, we allocate only the fd/bk pointers of bins, and then use + repositioning tricks to treat these as the fields of a chunk. + + TreeBins + Treebins are pointers to the roots of trees holding a range of + sizes. There are 2 equally spaced treebins for each power of two + from TREE_SHIFT to TREE_SHIFT+16. The last bin holds anything + larger. + + Bin maps + There is one bit map for small bins ("smallmap") and one for + treebins ("treemap). Each bin sets its bit when non-empty, and + clears the bit when empty. Bit operations are then used to avoid + bin-by-bin searching -- nearly all "search" is done without ever + looking at bins that won't be selected. The bit maps + conservatively use 32 bits per map word, even if on 64bit system. + For a good description of some of the bit-based techniques used + here, see Henry S. Warren Jr's book "Hacker's Delight" (and + supplement at http://hackersdelight.org/). Many of these are + intended to reduce the branchiness of paths through malloc etc, as + well as to reduce the number of memory locations read or written. + + Segments + A list of segments headed by an embedded malloc_segment record + representing the initial space. + + Address check support + The least_addr field is the least address ever obtained from + MORECORE or MMAP. Attempted frees and reallocs of any address less + than this are trapped (unless INSECURE is defined). + + Magic tag + A cross-check field that should always hold same value as mparams.magic. + + Max allowed footprint + The maximum allowed bytes to allocate from system (zero means no limit) + + Flags + Bits recording whether to use MMAP, locks, or contiguous MORECORE + + Statistics + Each space keeps track of current and maximum system memory + obtained via MORECORE or MMAP. + + Trim support + Fields holding the amount of unused topmost memory that should trigger + trimming, and a counter to force periodic scanning to release unused + non-topmost segments. + + Locking + If USE_LOCKS is defined, the "mutex" lock is acquired and released + around every public call using this mspace. + + Extension support + A void* pointer and a size_t field that can be used to help implement + extensions to this malloc. +*/ + +/* Bin types, widths and sizes */ +#define NSMALLBINS (32U) +#define NTREEBINS (32U) +#define SMALLBIN_SHIFT (3U) +#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) +#define TREEBIN_SHIFT (8U) +#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) +#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) +#define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) + +struct malloc_state { + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char* least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t release_checks; + size_t magic; + mchunkptr smallbins[(NSMALLBINS+1)*2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + size_t footprint_limit; /* zero means no limit */ + flag_t mflags; +#if USE_LOCKS + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; + void* extp; /* Unused but available for extensions */ + size_t exts; +}; + +typedef struct malloc_state* mstate; + +/* ------------- Global malloc_state and malloc_params ------------------- */ + +/* + malloc_params holds global properties, including those that can be + dynamically set using mallopt. There is a single instance, mparams, + initialized in init_mparams. Note that the non-zeroness of "magic" + also serves as an initialization flag. +*/ + +struct malloc_params { + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; +}; + +static struct malloc_params mparams; + +/* Ensure mparams initialized */ +#define ensure_initialization() (void)(mparams.magic != 0 || init_mparams()) + +#if !ONLY_MSPACES + +/* The global malloc_state used for all non-"mspace" calls */ +static struct malloc_state _gm_; +#define gm (&_gm_) +#define is_global(M) ((M) == &_gm_) + +#endif /* !ONLY_MSPACES */ + +#define is_initialized(M) ((M)->top != 0) + +/* -------------------------- system alloc setup ------------------------- */ + +/* Operations on mflags */ + +#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) +#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) +#if USE_LOCKS +#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) +#else +#define disable_lock(M) +#endif + +#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) +#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) +#if HAVE_MMAP +#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) +#else +#define disable_mmap(M) +#endif + +#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) +#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) + +#define set_lock(M,L)\ + ((M)->mflags = (L)?\ + ((M)->mflags | USE_LOCK_BIT) :\ + ((M)->mflags & ~USE_LOCK_BIT)) + +/* page-align a size */ +#define page_align(S)\ + (((S) + (mparams.page_size - SIZE_T_ONE)) & ~(mparams.page_size - SIZE_T_ONE)) + +/* granularity-align a size */ +#define granularity_align(S)\ + (((S) + (mparams.granularity - SIZE_T_ONE))\ + & ~(mparams.granularity - SIZE_T_ONE)) + + +/* For mmap, use granularity alignment on windows, else page-align */ +#ifdef WIN32 +#define mmap_align(S) granularity_align(S) +#else +#define mmap_align(S) page_align(S) +#endif + +/* For sys_alloc, enough padding to ensure can malloc request on success */ +#define SYS_ALLOC_PADDING (TOP_FOOT_SIZE + MALLOC_ALIGNMENT) + +#define is_page_aligned(S)\ + (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) +#define is_granularity_aligned(S)\ + (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) + +/* True if segment S holds address A */ +#define segment_holds(S, A)\ + ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) + +/* Return segment holding given address */ +static msegmentptr segment_holding(mstate m, char* addr) { + msegmentptr sp = &m->seg; + for (;;) { + if (addr >= sp->base && addr < sp->base + sp->size) + return sp; + if ((sp = sp->next) == 0) + return 0; + } +} + +/* Return true if segment contains a segment link */ +static int has_segment_link(mstate m, msegmentptr ss) { + msegmentptr sp = &m->seg; + for (;;) { + if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) + return 1; + if ((sp = sp->next) == 0) + return 0; + } +} + +#ifndef MORECORE_CANNOT_TRIM +#define should_trim(M,s) ((s) > (M)->trim_check) +#else /* MORECORE_CANNOT_TRIM */ +#define should_trim(M,s) (0) +#endif /* MORECORE_CANNOT_TRIM */ + +/* + TOP_FOOT_SIZE is padding at the end of a segment, including space + that may be needed to place segment records and fenceposts when new + noncontiguous segments are added. +*/ +#define TOP_FOOT_SIZE\ + (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) + + +/* ------------------------------- Hooks -------------------------------- */ + +/* + PREACTION should be defined to return 0 on success, and nonzero on + failure. If you are not using locking, you can redefine these to do + anything you like. +*/ + +#if USE_LOCKS +#define PREACTION(M) ((use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0) +#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); } +#else /* USE_LOCKS */ + +#ifndef PREACTION +#define PREACTION(M) (0) +#endif /* PREACTION */ + +#ifndef POSTACTION +#define POSTACTION(M) +#endif /* POSTACTION */ + +#endif /* USE_LOCKS */ + +/* + CORRUPTION_ERROR_ACTION is triggered upon detected bad addresses. + USAGE_ERROR_ACTION is triggered on detected bad frees and + reallocs. The argument p is an address that might have triggered the + fault. It is ignored by the two predefined actions, but might be + useful in custom actions that try to help diagnose errors. +*/ + +#if PROCEED_ON_ERROR + +/* A count of the number of corruption errors causing resets */ +int malloc_corruption_error_count; + +/* default corruption action */ +static void reset_on_error(mstate m); + +#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) +#define USAGE_ERROR_ACTION(m, p) + +#else /* PROCEED_ON_ERROR */ + +#ifndef CORRUPTION_ERROR_ACTION +#define CORRUPTION_ERROR_ACTION(m) ABORT +#endif /* CORRUPTION_ERROR_ACTION */ + +#ifndef USAGE_ERROR_ACTION +#define USAGE_ERROR_ACTION(m,p) ABORT +#endif /* USAGE_ERROR_ACTION */ + +#endif /* PROCEED_ON_ERROR */ + + +/* -------------------------- Debugging setup ---------------------------- */ + +#if ! DEBUG + +#define check_free_chunk(M,P) +#define check_inuse_chunk(M,P) +#define check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) +#define check_malloc_state(M) +#define check_top_chunk(M,P) + +#else /* DEBUG */ +#define check_free_chunk(M,P) do_check_free_chunk(M,P) +#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P) +#define check_top_chunk(M,P) do_check_top_chunk(M,P) +#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N) +#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) +#define check_malloc_state(M) do_check_malloc_state(M) + +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void* mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); +static size_t traverse_and_check(mstate m); +#endif /* DEBUG */ + +/* ---------------------------- Indexing Bins ---------------------------- */ + +#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) +#define small_index(s) (bindex_t)((s) >> SMALLBIN_SHIFT) +#define small_index2size(i) ((i) << SMALLBIN_SHIFT) +#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) + +/* addressing by index. See above about smallbin repositioning */ +#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1]))) +#define treebin_at(M,i) (&((M)->treebins[i])) + +/* assign tree index for size S to variable I. Use x86 asm if possible */ +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_tree_index(S, I)\ +{\ + unsigned int X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = (unsigned) sizeof(X)*__CHAR_BIT__ - 1 - (unsigned) __builtin_clz(X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K = _bit_scan_reverse (X); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int K;\ + _BitScanReverse((DWORD *) &K, (DWORD) X);\ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ + }\ +} + +#else /* GNUC */ +#define compute_tree_index(S, I)\ +{\ + size_t X = S >> TREEBIN_SHIFT;\ + if (X == 0)\ + I = 0;\ + else if (X > 0xFFFF)\ + I = NTREEBINS-1;\ + else {\ + unsigned int Y = (unsigned int)X;\ + unsigned int N = ((Y - 0x100) >> 16) & 8;\ + unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\ + N += K;\ + N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\ + K = 14 - N + ((Y <<= K) >> 15);\ + I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\ + }\ +} +#endif /* GNUC */ + +/* Bit representing maximum resolved size in a treebin at i */ +#define bit_for_tree_index(i) \ + (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) + +/* Shift placing maximum resolved bit in a treebin at i as sign bit */ +#define leftshift_for_tree_index(i) \ + ((i == NTREEBINS-1)? 0 : \ + ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) + +/* The size of the smallest chunk held in bin with index i */ +#define minsize_for_tree_index(i) \ + ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ + (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) + + +/* ------------------------ Operations on bin maps ----------------------- */ + +/* bit corresponding to given index */ +#define idx2bit(i) ((binmap_t)(1) << (i)) + +/* Mark/Clear bits with given index */ +#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) +#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) +#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) + +#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) +#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) +#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) + +/* isolate the least set bit of a bitmap */ +#define least_bit(x) ((x) & -(x)) + +/* mask with all bits to left of least bit of x on */ +#define left_bits(x) ((x<<1) | -(x<<1)) + +/* mask with all bits to left of or equal to least bit of x on */ +#define same_or_left_bits(x) ((x) | -(x)) + +/* index corresponding to given bit. Use x86 asm if possible */ + +#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = __builtin_ctz(X); \ + I = (bindex_t)J;\ +} + +#elif defined (__INTEL_COMPILER) +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + J = _bit_scan_forward (X); \ + I = (bindex_t)J;\ +} + +#elif defined(_MSC_VER) && _MSC_VER>=1300 +#define compute_bit2idx(X, I)\ +{\ + unsigned int J;\ + _BitScanForward((DWORD *) &J, X);\ + I = (bindex_t)J;\ +} + +#elif USE_BUILTIN_FFS +#define compute_bit2idx(X, I) I = ffs(X)-1 + +#else +#define compute_bit2idx(X, I)\ +{\ + unsigned int Y = X - 1;\ + unsigned int K = Y >> (16-4) & 16;\ + unsigned int N = K; Y >>= K;\ + N += K = Y >> (8-3) & 8; Y >>= K;\ + N += K = Y >> (4-2) & 4; Y >>= K;\ + N += K = Y >> (2-1) & 2; Y >>= K;\ + N += K = Y >> (1-0) & 1; Y >>= K;\ + I = (bindex_t)(N + Y);\ +} +#endif /* GNUC */ + + +/* ----------------------- Runtime Check Support ------------------------- */ + +/* + For security, the main invariant is that malloc/free/etc never + writes to a static address other than malloc_state, unless static + malloc_state itself has been corrupted, which cannot occur via + malloc (because of these checks). In essence this means that we + believe all pointers, sizes, maps etc held in malloc_state, but + check all of those linked or offsetted from other embedded data + structures. These checks are interspersed with main code in a way + that tends to minimize their run-time cost. + + When FOOTERS is defined, in addition to range checking, we also + verify footer fields of inuse chunks, which can be used guarantee + that the mstate controlling malloc/free is intact. This is a + streamlined version of the approach described by William Robertson + et al in "Run-time Detection of Heap-based Overflows" LISA'03 + http://www.usenix.org/events/lisa03/tech/robertson.html The footer + of an inuse chunk holds the xor of its mstate and a random seed, + that is checked upon calls to free() and realloc(). This is + (probabalistically) unguessable from outside the program, but can be + computed by any code successfully malloc'ing any chunk, so does not + itself provide protection against code that has already broken + security through some other means. Unlike Robertson et al, we + always dynamically check addresses of all offset chunks (previous, + next, etc). This turns out to be cheaper than relying on hashes. +*/ + +#if !INSECURE +/* Check if address a is at least as high as any from MORECORE or MMAP */ +#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) +/* Check if address of next chunk n is higher than base chunk p */ +#define ok_next(p, n) ((char*)(p) < (char*)(n)) +/* Check if p has inuse status */ +#define ok_inuse(p) is_inuse(p) +/* Check if p has its pinuse bit on */ +#define ok_pinuse(p) pinuse(p) + +#else /* !INSECURE */ +#define ok_address(M, a) (1) +#define ok_next(b, n) (1) +#define ok_inuse(p) (1) +#define ok_pinuse(p) (1) +#endif /* !INSECURE */ + +#if (FOOTERS && !INSECURE) +/* Check if (alleged) mstate m has expected magic field */ +#define ok_magic(M) ((M)->magic == mparams.magic) +#else /* (FOOTERS && !INSECURE) */ +#define ok_magic(M) (1) +#endif /* (FOOTERS && !INSECURE) */ + +/* In gcc, use __builtin_expect to minimize impact of checks */ +#if !INSECURE +#if defined(__GNUC__) && __GNUC__ >= 3 +#define RTCHECK(e) __builtin_expect(e, 1) +#else /* GNUC */ +#define RTCHECK(e) (e) +#endif /* GNUC */ +#else /* !INSECURE */ +#define RTCHECK(e) (1) +#endif /* !INSECURE */ + +/* macros to set up inuse chunks with or without footers */ + +#if !FOOTERS + +#define mark_inuse_foot(M,p,s) + +/* Macros for setting head/foot of non-mmapped chunks */ + +/* Set cinuse bit and pinuse bit of next chunk */ +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set cinuse and pinuse of this chunk and pinuse of next chunk */ +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) + +/* Set size, cinuse and pinuse bit of this chunk */ +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) + +#else /* FOOTERS */ + +/* Set foot of inuse chunk to be xor of mstate and seed */ +#define mark_inuse_foot(M,p,s)\ + (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) + +#define get_mstate_for(p)\ + ((mstate)(((mchunkptr)((char*)(p) +\ + (chunksize(p))))->prev_foot ^ mparams.magic)) + +#define set_inuse(M,p,s)\ + ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M,p,s)) + +#define set_inuse_and_pinuse(M,p,s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\ + mark_inuse_foot(M,p,s)) + +#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ + ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ + mark_inuse_foot(M, p, s)) + +#endif /* !FOOTERS */ + +/* ---------------------------- setting mparams -------------------------- */ + +#if LOCK_AT_FORK +static void pre_fork(void) { ACQUIRE_LOCK(&(gm)->mutex); } +static void post_fork_parent(void) { RELEASE_LOCK(&(gm)->mutex); } +static void post_fork_child(void) { INITIAL_LOCK(&(gm)->mutex); } +#endif /* LOCK_AT_FORK */ + +/* Initialize mparams */ +static int init_mparams(void) { +#ifdef NEED_GLOBAL_LOCK_INIT + if (malloc_global_mutex_status <= 0) + init_malloc_global_mutex(); +#endif + + ACQUIRE_MALLOC_GLOBAL_LOCK(); + if (mparams.magic == 0) { + size_t magic; + size_t psize; + size_t gsize; + +#ifndef WIN32 + psize = malloc_getpagesize; + gsize = ((DEFAULT_GRANULARITY != 0)? DEFAULT_GRANULARITY : psize); +#else /* WIN32 */ + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + psize = system_info.dwPageSize; + gsize = ((DEFAULT_GRANULARITY != 0)? + DEFAULT_GRANULARITY : system_info.dwAllocationGranularity); + } +#endif /* WIN32 */ + + /* Sanity-check configuration: + size_t must be unsigned and as wide as pointer type. + ints must be at least 4 bytes. + alignment must be at least 8. + Alignment, min chunk size, and page size must all be powers of 2. + */ + if ((sizeof(size_t) != sizeof(char*)) || + (MAX_SIZE_T < MIN_CHUNK_SIZE) || + (sizeof(int) < 4) || + (MALLOC_ALIGNMENT < (size_t)8U) || + ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || + ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || + ((gsize & (gsize-SIZE_T_ONE)) != 0) || + ((psize & (psize-SIZE_T_ONE)) != 0)) + ABORT; + mparams.granularity = gsize; + mparams.page_size = psize; + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; +#if MORECORE_CONTIGUOUS + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; +#else /* MORECORE_CONTIGUOUS */ + mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; +#endif /* MORECORE_CONTIGUOUS */ + +#if !ONLY_MSPACES + /* Set up lock for main malloc area */ + gm->mflags = mparams.default_mflags; + (void)INITIAL_LOCK(&gm->mutex); +#endif +#if LOCK_AT_FORK + pthread_atfork(&pre_fork, &post_fork_parent, &post_fork_child); +#endif + + { +#if USE_DEV_RANDOM + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && + read(fd, buf, sizeof(buf)) == sizeof(buf)) { + magic = *((size_t *) buf); + close(fd); + } + else +#endif /* USE_DEV_RANDOM */ +#ifdef WIN32 + magic = (size_t)(GetTickCount() ^ (size_t)0x55555555U); +#elif defined(LACKS_TIME_H) + magic = (size_t)&magic ^ (size_t)0x55555555U; +#else + magic = (size_t)(time(0) ^ (size_t)0x55555555U); +#endif + magic |= (size_t)8U; /* ensure nonzero */ + magic &= ~(size_t)7U; /* improve chances of fault for bad values */ + /* Until memory modes commonly available, use volatile-write */ + (*(volatile size_t *)(&(mparams.magic))) = magic; + } + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + return 1; +} + +/* support for mallopt */ +static int change_mparam(int param_number, int value) { + size_t val; + ensure_initialization(); + val = (value == -1)? MAX_SIZE_T : (size_t)value; + switch(param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if (val >= mparams.page_size && ((val & (val-1)) == 0)) { + mparams.granularity = val; + return 1; + } + else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; + } +} + +#if DEBUG +/* ------------------------- Debugging Support --------------------------- */ + +/* Check properties of any chunk, whether free, inuse, mmapped etc */ +static void do_check_any_chunk(mstate m, mchunkptr p) { + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); +} + +/* Check properties of top chunk */ +static void do_check_top_chunk(mstate m, mchunkptr p) { + msegmentptr sp = segment_holding(m, (char*)p); + size_t sz = p->head & ~INUSE_BITS; /* third-lowest bit can be set! */ + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!pinuse(chunk_plus_offset(p, sz))); +} + +/* Check properties of (inuse) mmapped chunks */ +static void do_check_mmapped_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +} + +/* Check properties of inuse chunks */ +static void do_check_inuse_chunk(mstate m, mchunkptr p) { + do_check_any_chunk(m, p); + assert(is_inuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if (is_mmapped(p)) + do_check_mmapped_chunk(m, p); +} + +/* Check properties of free chunks */ +static void do_check_free_chunk(mstate m, mchunkptr p) { + size_t sz = chunksize(p); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!is_inuse(p)); + assert(!next_pinuse(p)); + assert (!is_mmapped(p)); + if (p != m->dv && p != m->top) { + if (sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert (next == m->top || is_inuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } + else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); + } +} + +/* Check properties of malloced chunks at the point they are malloced */ +static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~INUSE_BITS; + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } +} + +/* Check a tree and its subtrees. */ +static void do_check_tree(mstate m, tchunkptr t) { + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr)u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!is_inuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if (u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } + else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert (u->parent->child[0] == u || + u->parent->child[1] == u || + *((tbinptr*)(u->parent)) == u); + if (u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if (u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if (u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; + } while (u != t); + assert(head != 0); +} + +/* Check all the chunks in a treebin. */ +static void do_check_treebin(mstate m, bindex_t i) { + tbinptr* tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if (t == 0) + assert(empty); + if (!empty) + do_check_tree(m, t); +} + +/* Check all the chunks in a smallbin. */ +static void do_check_smallbin(mstate m, bindex_t i) { + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if (p == b) + assert(empty); + if (!empty) { + for (; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if (q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } + } +} + +/* Find x in a bin. Used in other check functions. */ +static int bin_find(mstate m, mchunkptr x) { + size_t size = chunksize(x); + if (is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if (smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if (p == x) + return 1; + } while ((p = p->fd) != b); + } + } + else { + bindex_t tidx; + compute_tree_index(size, tidx); + if (treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while (t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if (t != 0) { + tchunkptr u = t; + do { + if (u == (tchunkptr)x) + return 1; + } while ((u = u->fd) != t); + } + } + } + return 0; +} + +/* Traverse each chunk and check it; return total */ +static size_t traverse_and_check(mstate m) { + size_t sum = 0; + if (is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if (is_inuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } + else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 || is_inuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; + } + } + return sum; +} + + +/* Check all properties of malloc_state. */ +static void do_check_malloc_state(mstate m) { + bindex_t i; + size_t total; + /* check bins */ + for (i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for (i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if (m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } + + if (m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + /*assert(m->topsize == chunksize(m->top)); redundant */ + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } + + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); +} +#endif /* DEBUG */ + +/* ----------------------------- statistics ------------------------------ */ + +#if !NO_MALLINFO +static struct mallinfo internal_mallinfo(mstate m) { + struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + ensure_initialization(); + if (!PREACTION(m)) { + check_malloc_state(m); + if (is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if (!is_inuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; + } + + POSTACTION(m); + } + return nm; +} +#endif /* !NO_MALLINFO */ + +#if !NO_MALLOC_STATS +static void internal_malloc_stats(mstate m) { + ensure_initialization(); + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!is_inuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + POSTACTION(m); /* drop lock */ + fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + } +} +#endif /* NO_MALLOC_STATS */ + +/* ----------------------- Operations on smallbins ----------------------- */ + +/* + Various forms of linking and unlinking are defined as macros. Even + the ones for trees, which are very long but have very short typical + paths. This is ugly but reduces reliance on inlining support of + compilers. +*/ + +/* Link a free chunk into a smallbin */ +#define insert_small_chunk(M, P, S) {\ + bindex_t I = small_index(S);\ + mchunkptr B = smallbin_at(M, I);\ + mchunkptr F = B;\ + assert(S >= MIN_CHUNK_SIZE);\ + if (!smallmap_is_marked(M, I))\ + mark_smallmap(M, I);\ + else if (RTCHECK(ok_address(M, B->fd)))\ + F = B->fd;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + B->fd = P;\ + F->bk = P;\ + P->fd = F;\ + P->bk = B;\ +} + +/* Unlink a chunk from a smallbin */ +#define unlink_small_chunk(M, P, S) {\ + mchunkptr F = P->fd;\ + mchunkptr B = P->bk;\ + bindex_t I = small_index(S);\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (RTCHECK(F == smallbin_at(M,I) || (ok_address(M, F) && F->bk == P))) { \ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(B == smallbin_at(M,I) ||\ + (ok_address(M, B) && B->fd == P))) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Unlink the first chunk from a smallbin */ +#define unlink_first_small_chunk(M, B, P, I) {\ + mchunkptr F = P->fd;\ + assert(P != B);\ + assert(P != F);\ + assert(chunksize(P) == small_index2size(I));\ + if (B == F) {\ + clear_smallmap(M, I);\ + }\ + else if (RTCHECK(ok_address(M, F) && F->bk == P)) {\ + F->bk = B;\ + B->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ +} + +/* Replace dv node, binning the old one */ +/* Used only when dvsize known to be small */ +#define replace_dv(M, P, S) {\ + size_t DVS = M->dvsize;\ + assert(is_small(DVS));\ + if (DVS != 0) {\ + mchunkptr DV = M->dv;\ + insert_small_chunk(M, DV, DVS);\ + }\ + M->dvsize = S;\ + M->dv = P;\ +} + +/* ------------------------- Operations on trees ------------------------- */ + +/* Insert chunk into tree */ +#define insert_large_chunk(M, X, S) {\ + tbinptr* H;\ + bindex_t I;\ + compute_tree_index(S, I);\ + H = treebin_at(M, I);\ + X->index = I;\ + X->child[0] = X->child[1] = 0;\ + if (!treemap_is_marked(M, I)) {\ + mark_treemap(M, I);\ + *H = X;\ + X->parent = (tchunkptr)H;\ + X->fd = X->bk = X;\ + }\ + else {\ + tchunkptr T = *H;\ + size_t K = S << leftshift_for_tree_index(I);\ + for (;;) {\ + if (chunksize(T) != S) {\ + tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ + K <<= 1;\ + if (*C != 0)\ + T = *C;\ + else if (RTCHECK(ok_address(M, C))) {\ + *C = X;\ + X->parent = T;\ + X->fd = X->bk = X;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + else {\ + tchunkptr F = T->fd;\ + if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\ + T->fd = F->bk = X;\ + X->fd = F;\ + X->bk = T;\ + X->parent = 0;\ + break;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + break;\ + }\ + }\ + }\ + }\ +} + +/* + Unlink steps: + + 1. If x is a chained node, unlink it from its same-sized fd/bk links + and choose its bk node as its replacement. + 2. If x was the last node of its size, but not a leaf node, it must + be replaced with a leaf node (not merely one with an open left or + right), to make sure that lefts and rights of descendents + correspond properly to bit masks. We use the rightmost descendent + of x. We could use any other leaf, but this is easy to locate and + tends to counteract removal of leftmosts elsewhere, and so keeps + paths shorter than minimally guaranteed. This doesn't loop much + because on average a node in a tree is near the bottom. + 3. If x is the base of a chain (i.e., has parent links) relink + x's parent and children to x's replacement (or null if none). +*/ + +#define unlink_large_chunk(M, X) {\ + tchunkptr XP = X->parent;\ + tchunkptr R;\ + if (X->bk != X) {\ + tchunkptr F = X->fd;\ + R = X->bk;\ + if (RTCHECK(ok_address(M, F) && F->bk == X && R->fd == X)) {\ + F->bk = R;\ + R->fd = F;\ + }\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else {\ + tchunkptr* RP;\ + if (((R = *(RP = &(X->child[1]))) != 0) ||\ + ((R = *(RP = &(X->child[0]))) != 0)) {\ + tchunkptr* CP;\ + while ((*(CP = &(R->child[1])) != 0) ||\ + (*(CP = &(R->child[0])) != 0)) {\ + R = *(RP = CP);\ + }\ + if (RTCHECK(ok_address(M, RP)))\ + *RP = 0;\ + else {\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + }\ + if (XP != 0) {\ + tbinptr* H = treebin_at(M, X->index);\ + if (X == *H) {\ + if ((*H = R) == 0) \ + clear_treemap(M, X->index);\ + }\ + else if (RTCHECK(ok_address(M, XP))) {\ + if (XP->child[0] == X) \ + XP->child[0] = R;\ + else \ + XP->child[1] = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + if (R != 0) {\ + if (RTCHECK(ok_address(M, R))) {\ + tchunkptr C0, C1;\ + R->parent = XP;\ + if ((C0 = X->child[0]) != 0) {\ + if (RTCHECK(ok_address(M, C0))) {\ + R->child[0] = C0;\ + C0->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + if ((C1 = X->child[1]) != 0) {\ + if (RTCHECK(ok_address(M, C1))) {\ + R->child[1] = C1;\ + C1->parent = R;\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ + else\ + CORRUPTION_ERROR_ACTION(M);\ + }\ + }\ +} + +/* Relays to large vs small bin operations */ + +#define insert_chunk(M, P, S)\ + if (is_small(S)) insert_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } + +#define unlink_chunk(M, P, S)\ + if (is_small(S)) unlink_small_chunk(M, P, S)\ + else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } + + +/* Relays to internal calls to malloc/free from realloc, memalign etc */ + +#if ONLY_MSPACES +#define internal_malloc(m, b) mspace_malloc(m, b) +#define internal_free(m, mem) mspace_free(m,mem); +#else /* ONLY_MSPACES */ +#if MSPACES +#define internal_malloc(m, b)\ + ((m == gm)? dlmalloc(b) : mspace_malloc(m, b)) +#define internal_free(m, mem)\ + if (m == gm) dlfree(mem); else mspace_free(m,mem); +#else /* MSPACES */ +#define internal_malloc(m, b) dlmalloc(b) +#define internal_free(m, mem) dlfree(mem) +#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ + +/* ----------------------- Direct-mmapping chunks ----------------------- */ + +/* + Directly mmapped chunks are set up with an offset to the start of + the mmapped region stored in the prev_foot field of the chunk. This + allows reconstruction of the required argument to MUNMAP when freed, + and also allows adjustment of the returned chunk to meet alignment + requirements (especially in memalign). +*/ + +/* Malloc using mmap */ +static void* mmap_alloc(mstate m, size_t nb) { + size_t mmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if (m->footprint_limit != 0) { + size_t fp = m->footprint + mmsize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + if (mmsize > nb) { /* Check for wrap around 0 */ + char* mm = (char*)(CALL_DIRECT_MMAP(mmsize)); + if (mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr)(mm + offset); + p->prev_foot = offset; + p->head = psize; + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; + + if (m->least_addr == 0 || mm < m->least_addr) + m->least_addr = mm; + if ((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } + } + return 0; +} + +/* Realloc using mmap */ +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb, int flags) { + size_t oldsize = chunksize(oldp); + (void)flags; /* placate people compiling -Wunused */ + if (is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= nb + SIZE_T_SIZE && + (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = mmap_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + char* cp = (char*)CALL_MREMAP((char*)oldp - offset, + oldmmsize, newmmsize, flags); + if (cp != CMFAIL) { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = psize; + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } + } + return 0; +} + + +/* -------------------------- mspace management -------------------------- */ + +/* Initialize top chunk and its size */ +static void init_top(mstate m, mchunkptr p, size_t psize) { + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr)((char*)p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ +} + +/* Initialize bins for a new mstate that is otherwise zeroed out */ +static void init_bins(mstate m) { + /* Establish circular links for smallbins */ + bindex_t i; + for (i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m,i); + bin->fd = bin->bk = bin; + } +} + +#if PROCEED_ON_ERROR + +/* default corruption action */ +static void reset_on_error(mstate m) { + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallmap = m->treemap = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for (i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); +} +#endif /* PROCEED_ON_ERROR */ + +/* Allocate chunk and prepend remainder with chunk in successor base. */ +static void* prepend_alloc(mstate m, char* newbase, char* oldbase, + size_t nb) { + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char*)oldfirst - (char*)p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char*)oldfirst > (char*)q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if (oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } + else if (oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } + else { + if (!is_inuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); + } + + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); +} + +/* Add a segment to hold a new noncontiguous region */ +static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { + /* Determine locations and sizes of segment, fenceposts, old top */ + char* old_top = (char*)m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char* old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char* asp = rawsp + offset; + char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; + mchunkptr sp = (mchunkptr)csp; + msegmentptr ss = (msegmentptr)(chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmapped; + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for (;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if ((char*)(&(nextp->head)) < old_end) + p = nextp; + else + break; + } + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if (csp != old_top) { + mchunkptr q = (mchunkptr)old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } + + check_top_chunk(m, m->top); +} + +/* -------------------------- System allocation -------------------------- */ + +/* Get memory from system using MORECORE or MMAP */ +static void* sys_alloc(mstate m, size_t nb) { + char* tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; + size_t asize; /* allocation size */ + + ensure_initialization(); + + /* Directly map large chunks, but only if already initialized */ + if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) { + void* mem = mmap_alloc(m, nb); + if (mem != 0) + return mem; + } + + asize = granularity_align(nb + SYS_ALLOC_PADDING); + if (asize <= nb) + return 0; /* wraparound */ + if (m->footprint_limit != 0) { + size_t fp = m->footprint + asize; + if (fp <= m->footprint || fp > m->footprint_limit) + return 0; + } + + /* + Try getting memory in any of three ways (in most-preferred to + least-preferred order): + 1. A call to MORECORE that can normally contiguously extend memory. + (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or + or main space is mmapped or a previous contiguous call failed) + 2. A call to MMAP new space (disabled if not HAVE_MMAP). + Note that under the default settings, if MORECORE is unable to + fulfill a request, and HAVE_MMAP is true, then mmap is + used as a noncontiguous system allocator. This is a useful backup + strategy for systems with holes in address spaces -- in this case + sbrk cannot contiguously expand the heap, but mmap may be able to + find space. + 3. A call to MORECORE that cannot usually contiguously extend memory. + (disabled if not HAVE_MORECORE) + + In all cases, we need to request enough bytes from system to ensure + we can malloc nb bytes upon success, so pad with enough space for + top_foot, plus alignment-pad to make sure we don't lose bytes if + not on boundary, and round this up to a granularity unit. + */ + + if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char* br = CMFAIL; + size_t ssize = asize; /* sbrk call size */ + msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); + ACQUIRE_MALLOC_GLOBAL_LOCK(); + + if (ss == 0) { /* First time through or recovery */ + char* base = (char*)CALL_MORECORE(0); + if (base != CMFAIL) { + size_t fp; + /* Adjust to end on a page boundary */ + if (!is_page_aligned(base)) + ssize += (page_align((size_t)base) - (size_t)base); + fp = m->footprint + ssize; /* recheck limits */ + if (ssize > nb && ssize < HALF_MAX_SIZE_T && + (m->footprint_limit == 0 || + (fp > m->footprint && fp <= m->footprint_limit)) && + (br = (char*)(CALL_MORECORE(ssize))) == base) { + tbase = base; + tsize = ssize; + } + } + } + else { + /* Subtract out existing available top space from MORECORE request. */ + ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING); + /* Use mem here only if it did continuously extend old space */ + if (ssize < HALF_MAX_SIZE_T && + (br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) { + tbase = br; + tsize = ssize; + } + } + + if (tbase == CMFAIL) { /* Cope with partial failure */ + if (br != CMFAIL) { /* Try to use/extend the space we did get */ + if (ssize < HALF_MAX_SIZE_T && + ssize < nb + SYS_ALLOC_PADDING) { + size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize); + if (esize < HALF_MAX_SIZE_T) { + char* end = (char*)CALL_MORECORE(esize); + if (end != CMFAIL) + ssize += esize; + else { /* Can't use; try to release */ + (void) CALL_MORECORE(-ssize); + br = CMFAIL; + } + } + } + } + if (br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = ssize; + } + else + disable_contiguous(m); /* Don't try contiguous path in the future */ + } + + RELEASE_MALLOC_GLOBAL_LOCK(); + } + + if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + char* mp = (char*)(CALL_MMAP(asize)); + if (mp != CMFAIL) { + tbase = mp; + tsize = asize; + mmap_flag = USE_MMAP_BIT; + } + } + + if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + if (asize < HALF_MAX_SIZE_T) { + char* br = CMFAIL; + char* end = CMFAIL; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + br = (char*)(CALL_MORECORE(asize)); + end = (char*)(CALL_MORECORE(0)); + RELEASE_MALLOC_GLOBAL_LOCK(); + if (br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if (ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } + } + + if (tbase != CMFAIL) { + + if ((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if (!is_initialized(m)) { /* first-time initialization */ + if (m->least_addr == 0 || tbase < m->least_addr) + m->least_addr = tbase; + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmap_flag; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + init_bins(m); +#if !ONLY_MSPACES + if (is_global(m)) + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + else +#endif + { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + /* Only consider most recent segment if traversal suppressed */ + while (sp != 0 && tbase != sp->base + sp->size) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag && + segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } + else { + if (tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while (sp != 0 && sp->base != tbase + tsize) + sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; + if (sp != 0 && + !is_extern_segment(sp) && + (sp->sflags & USE_MMAP_BIT) == mmap_flag) { + char* oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } + else + add_segment(m, tbase, tsize, mmap_flag); + } + } + + if (nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } + } + + MALLOC_FAILURE_ACTION; + return 0; +} + +/* ----------------------- system deallocation -------------------------- */ + +/* Unmap and unlink any mmapped segments that don't contain used chunks */ +static size_t release_unused_segments(mstate m) { + size_t released = 0; + int nsegs = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + ++nsegs; + if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr)p; + assert(segment_holds(sp, (char*)sp)); + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + else { + unlink_large_chunk(m, tp); + } + if (CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } + else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } + } + if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */ + break; + pred = sp; + sp = next; + } + /* Reset check counter */ + m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)? + (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE); + return released; +} + +static int sys_trim(mstate m, size_t pad) { + size_t released = 0; + ensure_initialization(); + if (pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if (m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - + SIZE_T_ONE) * unit; + msegmentptr sp = segment_holding(m, (char*)m->top); + + if (!is_extern_segment(sp)) { + if (is_mmapped_segment(sp)) { + if (HAVE_MMAP && + sp->size >= extra && + !has_segment_link(m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + (void)newsize; /* placate people compiling -Wunused-variable */ + /* Prefer mremap, fall back to munmap */ + if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || + (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { + released = extra; + } + } + } + else if (HAVE_MORECORE) { + if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MALLOC_GLOBAL_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char* old_br = (char*)(CALL_MORECORE(0)); + if (old_br == sp->base + sp->size) { + char* rel_br = (char*)(CALL_MORECORE(-extra)); + char* new_br = (char*)(CALL_MORECORE(0)); + if (rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MALLOC_GLOBAL_LOCK(); + } + } + + if (released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); + } + } + + /* Unmap any unused mmapped segments */ + if (HAVE_MMAP) + released += release_unused_segments(m); + + /* On failure, disable autotrim to avoid repeated failed future calls */ + if (released == 0 && m->topsize > m->trim_check) + m->trim_check = MAX_SIZE_T; + } + + return (released != 0)? 1 : 0; +} + +/* Consolidate and bin a chunk. Differs from exported versions + of free mainly in that the chunk need not be marked as inuse. +*/ +static void dispose_chunk(mstate m, mchunkptr p, size_t psize) { + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + mchunkptr prev; + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + m->footprint -= psize; + return; + } + prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */ + if (p != m->dv) { + unlink_chunk(m, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + m->dvsize = psize; + set_free_with_pinuse(p, psize, next); + return; + } + } + else { + CORRUPTION_ERROR_ACTION(m); + return; + } + } + if (RTCHECK(ok_address(m, next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == m->top) { + size_t tsize = m->topsize += psize; + m->top = p; + p->head = tsize | PINUSE_BIT; + if (p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } + return; + } + else if (next == m->dv) { + size_t dsize = m->dvsize += psize; + m->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + return; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(m, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == m->dv) { + m->dvsize = psize; + return; + } + } + } + else { + set_free_with_pinuse(p, psize, next); + } + insert_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + } +} + +/* ---------------------------- malloc --------------------------- */ + +/* allocate a large request from the best fitting chunk in a treebin */ +static void* tmalloc_large(mstate m, size_t nb) { + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + if ((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for (;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + v = t; + if ((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; + if (rt != 0 && rt != t) + rst = rt; + if (t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } + } + if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if (leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } + } + + while (t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); + } + + /* If dv is a better fit, return 0 so malloc will use it */ + if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { + if (RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } + } + CORRUPTION_ERROR_ACTION(m); + } + return 0; +} + +/* allocate a small request from the best fitting chunk in a treebin */ +static void* tmalloc_small(mstate m, size_t nb) { + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while ((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if (trem < rsize) { + rsize = trem; + v = t; + } + } + + if (RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if (RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if (rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } + } + + CORRUPTION_ERROR_ACTION(m); + return 0; +} + +#if !ONLY_MSPACES + +void* dlmalloc(size_t bytes) { + /* + Basic algorithm: + If a small request (< 256 bytes minus per-chunk overhead): + 1. If one exists, use a remainderless chunk in associated smallbin. + (Remainderless means that there are too few excess bytes to + represent as a chunk.) + 2. If it is big enough, use the dv chunk, which is normally the + chunk adjacent to the one used for the most recent small request. + 3. If one exists, split the smallest available chunk in a bin, + saving remainder in dv. + 4. If it is big enough, use the top chunk. + 5. If available, get memory from system and use it + Otherwise, for a large request: + 1. Find the smallest available binned chunk that fits, and use it + if it is better fitting than dv chunk, splitting if necessary. + 2. If better fitting than any binned chunk, use the dv chunk. + 3. If it is big enough, use the top chunk. + 4. If request size >= mmap threshold, try to directly mmap this chunk. + 5. If available, get memory from system and use it + + The ugly goto's here ensure that postaction occurs along all paths. + */ + +#if USE_LOCKS + ensure_initialization(); /* initialize in sys_alloc if not using locks */ +#endif + + if (!PREACTION(gm)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb > gm->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + + if (nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } + else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if (nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + mem = sys_alloc(gm, nb); + + postaction: + POSTACTION(gm); + return mem; + } + + return 0; +} + +/* ---------------------------- free --------------------------- */ + +void dlfree(void* mem) { + /* + Consolidate freed chunks with preceeding or succeeding bordering + free chunks, if they exist, and then place in a bin. Intermixed + with special cases for top, dv, mmapped chunks, and usage errors. + */ + + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } +#else /* FOOTERS */ +#define fm gm +#endif /* FOOTERS */ + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +#if !FOOTERS +#undef fm +#endif /* FOOTERS */ +} + +void* dlcalloc(size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +#endif /* !ONLY_MSPACES */ + +/* ------------ Internal support for realloc, memalign, etc -------------- */ + +/* Try to realloc; only in-place unless can_move true */ +static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb, + int can_move) { + mchunkptr newp = 0; + size_t oldsize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, oldsize); + if (RTCHECK(ok_address(m, p) && ok_inuse(p) && + ok_next(p, next) && ok_pinuse(next))) { + if (is_mmapped(p)) { + newp = mmap_resize(m, p, nb, can_move); + } + else if (oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + else if (next == m->top) { /* extend into top */ + if (oldsize + m->topsize > nb) { + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + newtop->head = newtopsize |PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = p; + } + } + else if (next == m->dv) { /* extend into dv */ + size_t dvs = m->dvsize; + if (oldsize + dvs >= nb) { + size_t dsize = oldsize + dvs - nb; + if (dsize >= MIN_CHUNK_SIZE) { + mchunkptr r = chunk_plus_offset(p, nb); + mchunkptr n = chunk_plus_offset(r, dsize); + set_inuse(m, p, nb); + set_size_and_pinuse_of_free_chunk(r, dsize); + clear_pinuse(n); + m->dvsize = dsize; + m->dv = r; + } + else { /* exhaust dv */ + size_t newsize = oldsize + dvs; + set_inuse(m, p, newsize); + m->dvsize = 0; + m->dv = 0; + } + newp = p; + } + } + else if (!cinuse(next)) { /* extend into next free chunk */ + size_t nextsize = chunksize(next); + if (oldsize + nextsize >= nb) { + size_t rsize = oldsize + nextsize - nb; + unlink_chunk(m, next, nextsize); + if (rsize < MIN_CHUNK_SIZE) { + size_t newsize = oldsize + nextsize; + set_inuse(m, p, newsize); + } + else { + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + } + } + else { + USAGE_ERROR_ACTION(m, chunk2mem(p)); + } + return newp; +} + +static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while (a < alignment) a <<= 1; + alignment = a; + } + if (bytes >= MAX_REQUEST - alignment) { + if (m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; + } + } + else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + mem = internal_malloc(m, req); + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (PREACTION(m)) + return 0; + if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */ + /* + Find an aligned spot inside chunk. Since we need to give + back leading space in a chunk of at least MIN_CHUNK_SIZE, if + the first calculation places us at a spot with less than + MIN_CHUNK_SIZE leader, we can move to the next aligned spot. + We've allocated enough total room so that this is always + possible. + */ + char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment - + SIZE_T_ONE)) & + -alignment)); + char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? + br : br+alignment; + mchunkptr newp = (mchunkptr)pos; + size_t leadsize = pos - (char*)(p); + size_t newsize = chunksize(p) - leadsize; + + if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = newsize; + } + else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + dispose_chunk(m, p, leadsize); + } + p = newp; + } + + /* Give back spare room at the end */ + if (!is_mmapped(p)) { + size_t size = chunksize(p); + if (size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + dispose_chunk(m, remainder, remainder_size); + } + } + + mem = chunk2mem(p); + assert (chunksize(p) >= nb); + assert(((size_t)mem & (alignment - 1)) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + } + } + return mem; +} + +/* + Common support for independent_X routines, handling + all of the combinations that can result. + The opts arg has: + bit 0 set if all elements are same size (using sizes[0]) + bit 1 set if elements should be zeroed +*/ +static void** ialloc(mstate m, + size_t n_elements, + size_t* sizes, + int opts, + void* chunks[]) { + + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void** marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + ensure_initialization(); + /* compute array length, if needed */ + if (chunks != 0) { + if (n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } + else { + /* if empty req, must still return chunk representing empty array */ + if (n_elements == 0) + return (void**)internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void*))); + } + + /* compute total element size */ + if (opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } + else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for (i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } + + size = contents_size + array_size; + + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if (was_enabled) + enable_mmap(m); + if (mem == 0) + return 0; + + if (PREACTION(m)) return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if (opts & 0x2) { /* optionally clear the elements */ + memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } + + /* If not provided, allocate the pointer array as final part of chunk */ + if (marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void**) (chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; + } + + /* split out elements */ + for (i = 0; ; ++i) { + marray[i] = chunk2mem(p); + if (i != n_elements-1) { + if (element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } + else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } + } + +#if DEBUG + if (marray != chunks) { + /* final element must have exactly exhausted chunk */ + if (element_size != 0) { + assert(remainder_size == element_size); + } + else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); + } + for (i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); + +#endif /* DEBUG */ + + POSTACTION(m); + return marray; +} + +/* Try to free all pointers in the given array. + Note: this could be made faster, by delaying consolidation, + at the price of disabling some user integrity checks, We + still optimize some consolidations by combining adjacent + chunks before freeing, which will occur often if allocated + with ialloc or the array is sorted. +*/ +static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) { + size_t unfreed = 0; + if (!PREACTION(m)) { + void** a; + void** fence = &(array[nelem]); + for (a = array; a != fence; ++a) { + void* mem = *a; + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t psize = chunksize(p); +#if FOOTERS + if (get_mstate_for(p) != m) { + ++unfreed; + continue; + } +#endif + check_inuse_chunk(m, p); + *a = 0; + if (RTCHECK(ok_address(m, p) && ok_inuse(p))) { + void ** b = a + 1; /* try to merge with next chunk */ + mchunkptr next = next_chunk(p); + if (b != fence && *b == chunk2mem(next)) { + size_t newsize = chunksize(next) + psize; + set_inuse(m, p, newsize); + *b = chunk2mem(p); + } + else + dispose_chunk(m, p, psize); + } + else { + CORRUPTION_ERROR_ACTION(m); + break; + } + } + } + if (should_trim(m, m->topsize)) + sys_trim(m, 0); + POSTACTION(m); + } + return unfreed; +} + +/* Traversal */ +#if MALLOC_INSPECT_ALL +static void internal_inspect_all(mstate m, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + if (is_initialized(m)) { + mchunkptr top = m->top; + msegmentptr s; + for (s = &m->seg; s != 0; s = s->next) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) { + mchunkptr next = next_chunk(q); + size_t sz = chunksize(q); + size_t used; + void* start; + if (is_inuse(q)) { + used = sz - CHUNK_OVERHEAD; /* must not be mmapped */ + start = chunk2mem(q); + } + else { + used = 0; + if (is_small(sz)) { /* offset by possible bookkeeping */ + start = (void*)((char*)q + sizeof(struct malloc_chunk)); + } + else { + start = (void*)((char*)q + sizeof(struct malloc_tree_chunk)); + } + } + if (start < (void*)next) /* skip if all space is bookkeeping */ + handler(start, next, used, arg); + if (q == top) + break; + q = next; + } + } + } +} +#endif /* MALLOC_INSPECT_ALL */ + +/* ------------------ Exported realloc, memalign, etc -------------------- */ + +#if !ONLY_MSPACES + +void* dlrealloc(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = dlmalloc(bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + dlfree(oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = internal_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + internal_free(m, oldmem); + } + } + } + } + return mem; +} + +void* dlrealloc_in_place(void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* dlmemalign(size_t alignment, size_t bytes) { + if (alignment <= MALLOC_ALIGNMENT) { + return dlmalloc(bytes); + } + return internal_memalign(gm, alignment, bytes); +} + +int dlposix_memalign(void** pp, size_t alignment, size_t bytes) { + void* mem = 0; + if (alignment == MALLOC_ALIGNMENT) + mem = dlmalloc(bytes); + else { + size_t d = alignment / sizeof(void*); + size_t r = alignment % sizeof(void*); + if (r != 0 || d == 0 || (d & (d-SIZE_T_ONE)) != 0) + return EINVAL; + else if (bytes <= MAX_REQUEST - alignment) { + if (alignment < MIN_CHUNK_SIZE) + alignment = MIN_CHUNK_SIZE; + mem = internal_memalign(gm, alignment, bytes); + } + } + if (mem == 0) + return ENOMEM; + else { + *pp = mem; + return 0; + } +} + +void* dlvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); +} + +void* dlpvalloc(size_t bytes) { + size_t pagesz; + ensure_initialization(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +} + +void** dlindependent_calloc(size_t n_elements, size_t elem_size, + void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); +} + +void** dlindependent_comalloc(size_t n_elements, size_t sizes[], + void* chunks[]) { + return ialloc(gm, n_elements, sizes, 0, chunks); +} + +size_t dlbulk_free(void* array[], size_t nelem) { + return internal_bulk_free(gm, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void dlmalloc_inspect_all(void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + ensure_initialization(); + if (!PREACTION(gm)) { + internal_inspect_all(gm, handler, arg); + POSTACTION(gm); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int dlmalloc_trim(size_t pad) { + int result = 0; + ensure_initialization(); + if (!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; +} + +size_t dlmalloc_footprint(void) { + return gm->footprint; +} + +size_t dlmalloc_max_footprint(void) { + return gm->max_footprint; +} + +size_t dlmalloc_footprint_limit(void) { + size_t maf = gm->footprint_limit; + return maf == 0 ? MAX_SIZE_T : maf; +} + +size_t dlmalloc_set_footprint_limit(size_t bytes) { + size_t result; /* invert sense of 0 */ + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + return gm->footprint_limit = result; +} + +#if !NO_MALLINFO +struct mallinfo dlmallinfo(void) { + return internal_mallinfo(gm); +} +#endif /* NO_MALLINFO */ + +#if !NO_MALLOC_STATS +void dlmalloc_stats() { + internal_malloc_stats(gm); +} +#endif /* NO_MALLOC_STATS */ + +int dlmallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +size_t dlmalloc_usable_size(void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +#endif /* !ONLY_MSPACES */ + +/* ----------------------------- user mspaces ---------------------------- */ + +#if MSPACES + +static mstate init_user_mstate(char* tbase, size_t tsize) { + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate)(chunk2mem(msp)); + memset(m, 0, msize); + (void)INITIAL_LOCK(&m->mutex); + msp->head = (msize|INUSE_BITS); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->release_checks = MAX_RELEASE_CHECK_RATE; + m->mflags = mparams.default_mflags; + m->extp = 0; + m->exts = 0; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; +} + +mspace create_mspace(size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0)? mparams.granularity : + (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char* tbase = (char*)(CALL_MMAP(tsize)); + if (tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + m->seg.sflags = USE_MMAP_BIT; + set_lock(m, locked); + } + } + return (mspace)m; +} + +mspace create_mspace_with_base(void* base, size_t capacity, int locked) { + mstate m = 0; + size_t msize; + ensure_initialization(); + msize = pad_request(sizeof(struct malloc_state)); + if (capacity > msize + TOP_FOOT_SIZE && + capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { + m = init_user_mstate((char*)base, capacity); + m->seg.sflags = EXTERN_BIT; + set_lock(m, locked); + } + return (mspace)m; +} + +int mspace_track_large_chunks(mspace msp, int enable) { + int ret = 0; + mstate ms = (mstate)msp; + if (!PREACTION(ms)) { + if (!use_mmap(ms)) { + ret = 1; + } + if (!enable) { + enable_mmap(ms); + } else { + disable_mmap(ms); + } + POSTACTION(ms); + } + return ret; +} + +size_t destroy_mspace(mspace msp) { + size_t freed = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + msegmentptr sp = &ms->seg; + (void)DESTROY_LOCK(&ms->mutex); /* destroy before unmapped */ + while (sp != 0) { + char* base = sp->base; + size_t size = sp->size; + flag_t flag = sp->sflags; + (void)base; /* placate people compiling -Wunused-variable */ + sp = sp->next; + if ((flag & USE_MMAP_BIT) && !(flag & EXTERN_BIT) && + CALL_MUNMAP(base, size) == 0) + freed += size; + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return freed; +} + +/* + mspace versions of routines are near-clones of the global + versions. This is not so nice but better than the alternatives. +*/ + +void* mspace_malloc(mspace msp, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (!PREACTION(ms)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } + else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + mem = sys_alloc(ms, nb); + + postaction: + POSTACTION(ms); + return mem; + } + + return 0; +} + +void mspace_free(mspace msp, void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + (void)msp; /* placate people compiling -Wunused */ +#else /* FOOTERS */ + mstate fm = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if (!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } +} + +void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { + void* mem; + size_t req = 0; + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (n_elements != 0) { + req = n_elements * elem_size; + if (((n_elements | elem_size) & ~(size_t)0xffff) && + (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if (mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; +} + +void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem == 0) { + mem = mspace_malloc(msp, bytes); + } + else if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } +#ifdef REALLOC_ZERO_BYTES_FREES + else if (bytes == 0) { + mspace_free(msp, oldmem); + } +#endif /* REALLOC_ZERO_BYTES_FREES */ + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); + POSTACTION(m); + if (newp != 0) { + check_inuse_chunk(m, newp); + mem = chunk2mem(newp); + } + else { + mem = mspace_malloc(m, bytes); + if (mem != 0) { + size_t oc = chunksize(oldp) - overhead_for(oldp); + memcpy(mem, oldmem, (oc < bytes)? oc : bytes); + mspace_free(m, oldmem); + } + } + } + } + return mem; +} + +void* mspace_realloc_in_place(mspace msp, void* oldmem, size_t bytes) { + void* mem = 0; + if (oldmem != 0) { + if (bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + } + else { + size_t nb = request2size(bytes); + mchunkptr oldp = mem2chunk(oldmem); +#if ! FOOTERS + mstate m = (mstate)msp; +#else /* FOOTERS */ + mstate m = get_mstate_for(oldp); + (void)msp; /* placate people compiling -Wunused */ + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } +#endif /* FOOTERS */ + if (!PREACTION(m)) { + mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); + POSTACTION(m); + if (newp == oldp) { + check_inuse_chunk(m, newp); + mem = oldmem; + } + } + } + } + return mem; +} + +void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (alignment <= MALLOC_ALIGNMENT) + return mspace_malloc(msp, bytes); + return internal_memalign(ms, alignment, bytes); +} + +void** mspace_independent_calloc(mspace msp, size_t n_elements, + size_t elem_size, void* chunks[]) { + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); +} + +void** mspace_independent_comalloc(mspace msp, size_t n_elements, + size_t sizes[], void* chunks[]) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); +} + +size_t mspace_bulk_free(mspace msp, void* array[], size_t nelem) { + return internal_bulk_free((mstate)msp, array, nelem); +} + +#if MALLOC_INSPECT_ALL +void mspace_inspect_all(mspace msp, + void(*handler)(void *start, + void *end, + size_t used_bytes, + void* callback_arg), + void* arg) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + internal_inspect_all(ms, handler, arg); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* MALLOC_INSPECT_ALL */ + +int mspace_trim(mspace msp, size_t pad) { + int result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLOC_STATS +void mspace_malloc_stats(mspace msp) { + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + internal_malloc_stats(ms); + } + else { + USAGE_ERROR_ACTION(ms,ms); + } +} +#endif /* NO_MALLOC_STATS */ + +size_t mspace_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_max_footprint(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + result = ms->max_footprint; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_footprint_limit(mspace msp) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + size_t maf = ms->footprint_limit; + result = (maf == 0) ? MAX_SIZE_T : maf; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +size_t mspace_set_footprint_limit(mspace msp, size_t bytes) { + size_t result = 0; + mstate ms = (mstate)msp; + if (ok_magic(ms)) { + if (bytes == 0) + result = granularity_align(1); /* Use minimal size */ + if (bytes == MAX_SIZE_T) + result = 0; /* disable */ + else + result = granularity_align(bytes); + ms->footprint_limit = result; + } + else { + USAGE_ERROR_ACTION(ms,ms); + } + return result; +} + +#if !NO_MALLINFO +struct mallinfo mspace_mallinfo(mspace msp) { + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + return internal_mallinfo(ms); +} +#endif /* NO_MALLINFO */ + +size_t mspace_usable_size(const void* mem) { + if (mem != 0) { + mchunkptr p = mem2chunk(mem); + if (is_inuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; +} + +int mspace_mallopt(int param_number, int value) { + return change_mparam(param_number, value); +} + +#endif /* MSPACES */ + + +/* -------------------- Alternative MORECORE functions ------------------- */ + +/* + Guidelines for creating a custom version of MORECORE: + + * For best performance, MORECORE should allocate in multiples of pagesize. + * MORECORE may allocate more memory than requested. (Or even less, + but this will usually result in a malloc failure.) + * MORECORE must not allocate memory when given argument zero, but + instead return one past the end address of memory from previous + nonzero call. + * For best performance, consecutive calls to MORECORE with positive + arguments should return increasing addresses, indicating that + space has been contiguously extended. + * Even though consecutive calls to MORECORE need not return contiguous + addresses, it must be OK for malloc'ed chunks to span multiple + regions in those cases where they do happen to be contiguous. + * MORECORE need not handle negative arguments -- it may instead + just return MFAIL when given negative arguments. + Negative arguments are always multiples of pagesize. MORECORE + must not misinterpret negative args as large positive unsigned + args. You can suppress all such calls from even occurring by defining + MORECORE_CANNOT_TRIM, + + As an example alternative MORECORE, here is a custom allocator + kindly contributed for pre-OSX macOS. It uses virtually but not + necessarily physically contiguous non-paged memory (locked in, + present and won't get swapped out). You can use it by uncommenting + this section, adding some #includes, and setting up the appropriate + defines above: + + #define MORECORE osMoreCore + + There is also a shutdown routine that should somehow be called for + cleanup upon program exit. + + #define MAX_POOL_ENTRIES 100 + #define MINIMUM_MORECORE_SIZE (64 * 1024U) + static int next_os_pool; + void *our_os_pools[MAX_POOL_ENTRIES]; + + void *osMoreCore(int size) + { + void *ptr = 0; + static void *sbrk_top = 0; + + if (size > 0) + { + if (size < MINIMUM_MORECORE_SIZE) + size = MINIMUM_MORECORE_SIZE; + if (CurrentExecutionLevel() == kTaskLevel) + ptr = PoolAllocateResident(size + RM_PAGE_SIZE, 0); + if (ptr == 0) + { + return (void *) MFAIL; + } + // save ptrs so they can be freed during cleanup + our_os_pools[next_os_pool] = ptr; + next_os_pool++; + ptr = (void *) ((((size_t) ptr) + RM_PAGE_MASK) & ~RM_PAGE_MASK); + sbrk_top = (char *) ptr + size; + return ptr; + } + else if (size < 0) + { + // we don't currently support shrink behavior + return (void *) MFAIL; + } + else + { + return sbrk_top; + } + } + + // cleanup any allocated memory pools + // called as last thing before shutting down driver + + void osCleanupMem(void) + { + void **ptr; + + for (ptr = our_os_pools; ptr < &our_os_pools[MAX_POOL_ENTRIES]; ptr++) + if (*ptr) + { + PoolDeallocate(*ptr); + *ptr = 0; + } + } + +*/ + + +/* ----------------------------------------------------------------------- +History: + v2.8.6 Wed Aug 29 06:57:58 2012 Doug Lea + * fix bad comparison in dlposix_memalign + * don't reuse adjusted asize in sys_alloc + * add LOCK_AT_FORK -- thanks to Kirill Artamonov for the suggestion + * reduce compiler warnings -- thanks to all who reported/suggested these + + v2.8.5 Sun May 22 10:26:02 2011 Doug Lea (dl at gee) + * Always perform unlink checks unless INSECURE + * Add posix_memalign. + * Improve realloc to expand in more cases; expose realloc_in_place. + Thanks to Peter Buhr for the suggestion. + * Add footprint_limit, inspect_all, bulk_free. Thanks + to Barry Hayes and others for the suggestions. + * Internal refactorings to avoid calls while holding locks + * Use non-reentrant locks by default. Thanks to Roland McGrath + for the suggestion. + * Small fixes to mspace_destroy, reset_on_error. + * Various configuration extensions/changes. Thanks + to all who contributed these. + + V2.8.4a Thu Apr 28 14:39:43 2011 (dl at gee.cs.oswego.edu) + * Update Creative Commons URL + + V2.8.4 Wed May 27 09:56:23 2009 Doug Lea (dl at gee) + * Use zeros instead of prev foot for is_mmapped + * Add mspace_track_large_chunks; thanks to Jean Brouwers + * Fix set_inuse in internal_realloc; thanks to Jean Brouwers + * Fix insufficient sys_alloc padding when using 16byte alignment + * Fix bad error check in mspace_footprint + * Adaptations for ptmalloc; thanks to Wolfram Gloger. + * Reentrant spin locks; thanks to Earl Chew and others + * Win32 improvements; thanks to Niall Douglas and Earl Chew + * Add NO_SEGMENT_TRAVERSAL and MAX_RELEASE_CHECK_RATE options + * Extension hook in malloc_state + * Various small adjustments to reduce warnings on some compilers + * Various configuration extensions/changes for more platforms. Thanks + to all who contributed these. + + V2.8.3 Thu Sep 22 11:16:32 2005 Doug Lea (dl at gee) + * Add max_footprint functions + * Ensure all appropriate literals are size_t + * Fix conditional compilation problem for some #define settings + * Avoid concatenating segments with the one provided + in create_mspace_with_base + * Rename some variables to avoid compiler shadowing warnings + * Use explicit lock initialization. + * Better handling of sbrk interference. + * Simplify and fix segment insertion, trimming and mspace_destroy + * Reinstate REALLOC_ZERO_BYTES_FREES option from 2.7.x + * Thanks especially to Dennis Flanagan for help on these. + + V2.8.2 Sun Jun 12 16:01:10 2005 Doug Lea (dl at gee) + * Fix memalign brace error. + + V2.8.1 Wed Jun 8 16:11:46 2005 Doug Lea (dl at gee) + * Fix improper #endif nesting in C++ + * Add explicit casts needed for C++ + + V2.8.0 Mon May 30 14:09:02 2005 Doug Lea (dl at gee) + * Use trees for large bins + * Support mspaces + * Use segments to unify sbrk-based and mmap-based system allocation, + removing need for emulation on most platforms without sbrk. + * Default safety checks + * Optional footer checks. Thanks to William Robertson for the idea. + * Internal code refactoring + * Incorporate suggestions and platform-specific changes. + Thanks to Dennis Flanagan, Colin Plumb, Niall Douglas, + Aaron Bachmann, Emery Berger, and others. + * Speed up non-fastbin processing enough to remove fastbins. + * Remove useless cfree() to avoid conflicts with other apps. + * Remove internal memcpy, memset. Compilers handle builtins better. + * Remove some options that no one ever used and rename others. + + V2.7.2 Sat Aug 17 09:07:30 2002 Doug Lea (dl at gee) + * Fix malloc_state bitmap array misdeclaration + + V2.7.1 Thu Jul 25 10:58:03 2002 Doug Lea (dl at gee) + * Allow tuning of FIRST_SORTED_BIN_SIZE + * Use PTR_UINT as type for all ptr->int casts. Thanks to John Belmonte. + * Better detection and support for non-contiguousness of MORECORE. + Thanks to Andreas Mueller, Conal Walsh, and Wolfram Gloger + * Bypass most of malloc if no frees. Thanks To Emery Berger. + * Fix freeing of old top non-contiguous chunk im sysmalloc. + * Raised default trim and map thresholds to 256K. + * Fix mmap-related #defines. Thanks to Lubos Lunak. + * Fix copy macros; added LACKS_FCNTL_H. Thanks to Neal Walfield. + * Branch-free bin calculation + * Default trim and mmap thresholds now 256K. + + V2.7.0 Sun Mar 11 14:14:06 2001 Doug Lea (dl at gee) + * Introduce independent_comalloc and independent_calloc. + Thanks to Michael Pachos for motivation and help. + * Make optional .h file available + * Allow > 2GB requests on 32bit systems. + * new WIN32 sbrk, mmap, munmap, lock code from . + Thanks also to Andreas Mueller , + and Anonymous. + * Allow override of MALLOC_ALIGNMENT (Thanks to Ruud Waij for + helping test this.) + * memalign: check alignment arg + * realloc: don't try to shift chunks backwards, since this + leads to more fragmentation in some programs and doesn't + seem to help in any others. + * Collect all cases in malloc requiring system memory into sysmalloc + * Use mmap as backup to sbrk + * Place all internal state in malloc_state + * Introduce fastbins (although similar to 2.5.1) + * Many minor tunings and cosmetic improvements + * Introduce USE_PUBLIC_MALLOC_WRAPPERS, USE_MALLOC_LOCK + * Introduce MALLOC_FAILURE_ACTION, MORECORE_CONTIGUOUS + Thanks to Tony E. Bennett and others. + * Include errno.h to support default failure action. + + V2.6.6 Sun Dec 5 07:42:19 1999 Doug Lea (dl at gee) + * return null for negative arguments + * Added Several WIN32 cleanups from Martin C. Fong + * Add 'LACKS_SYS_PARAM_H' for those systems without 'sys/param.h' + (e.g. WIN32 platforms) + * Cleanup header file inclusion for WIN32 platforms + * Cleanup code to avoid Microsoft Visual C++ compiler complaints + * Add 'USE_DL_PREFIX' to quickly allow co-existence with existing + memory allocation routines + * Set 'malloc_getpagesize' for WIN32 platforms (needs more work) + * Use 'assert' rather than 'ASSERT' in WIN32 code to conform to + usage of 'assert' in non-WIN32 code + * Improve WIN32 'sbrk()' emulation's 'findRegion()' routine to + avoid infinite loop + * Always call 'fREe()' rather than 'free()' + + V2.6.5 Wed Jun 17 15:57:31 1998 Doug Lea (dl at gee) + * Fixed ordering problem with boundary-stamping + + V2.6.3 Sun May 19 08:17:58 1996 Doug Lea (dl at gee) + * Added pvalloc, as recommended by H.J. Liu + * Added 64bit pointer support mainly from Wolfram Gloger + * Added anonymously donated WIN32 sbrk emulation + * Malloc, calloc, getpagesize: add optimizations from Raymond Nijssen + * malloc_extend_top: fix mask error that caused wastage after + foreign sbrks + * Add linux mremap support code from HJ Liu + + V2.6.2 Tue Dec 5 06:52:55 1995 Doug Lea (dl at gee) + * Integrated most documentation with the code. + * Add support for mmap, with help from + Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Use last_remainder in more cases. + * Pack bins using idea from colin@nyx10.cs.du.edu + * Use ordered bins instead of best-fit threshhold + * Eliminate block-local decls to simplify tracing and debugging. + * Support another case of realloc via move into top + * Fix error occuring when initial sbrk_base not word-aligned. + * Rely on page size for units instead of SBRK_UNIT to + avoid surprises about sbrk alignment conventions. + * Add mallinfo, mallopt. Thanks to Raymond Nijssen + (raymond@es.ele.tue.nl) for the suggestion. + * Add `pad' argument to malloc_trim and top_pad mallopt parameter. + * More precautions for cases where other routines call sbrk, + courtesy of Wolfram Gloger (Gloger@lrz.uni-muenchen.de). + * Added macros etc., allowing use in linux libc from + H.J. Lu (hjl@gnu.ai.mit.edu) + * Inverted this history list + + V2.6.1 Sat Dec 2 14:10:57 1995 Doug Lea (dl at gee) + * Re-tuned and fixed to behave more nicely with V2.6.0 changes. + * Removed all preallocation code since under current scheme + the work required to undo bad preallocations exceeds + the work saved in good cases for most test programs. + * No longer use return list or unconsolidated bins since + no scheme using them consistently outperforms those that don't + given above changes. + * Use best fit for very large chunks to prevent some worst-cases. + * Added some support for debugging + + V2.6.0 Sat Nov 4 07:05:23 1995 Doug Lea (dl at gee) + * Removed footers when chunks are in use. Thanks to + Paul Wilson (wilson@cs.texas.edu) for the suggestion. + + V2.5.4 Wed Nov 1 07:54:51 1995 Doug Lea (dl at gee) + * Added malloc_trim, with help from Wolfram Gloger + (wmglo@Dent.MED.Uni-Muenchen.DE). + + V2.5.3 Tue Apr 26 10:16:01 1994 Doug Lea (dl at g) + + V2.5.2 Tue Apr 5 16:20:40 1994 Doug Lea (dl at g) + * realloc: try to expand in both directions + * malloc: swap order of clean-bin strategy; + * realloc: only conditionally expand backwards + * Try not to scavenge used bins + * Use bin counts as a guide to preallocation + * Occasionally bin return list chunks in first scan + * Add a few optimizations from colin@nyx10.cs.du.edu + + V2.5.1 Sat Aug 14 15:40:43 1993 Doug Lea (dl at g) + * faster bin computation & slightly different binning + * merged all consolidations to one part of malloc proper + (eliminating old malloc_find_space & malloc_clean_bin) + * Scan 2 returns chunks (not just 1) + * Propagate failure in realloc if malloc returns 0 + * Add stuff to allow compilation on non-ANSI compilers + from kpv@research.att.com + + V2.5 Sat Aug 7 07:41:59 1993 Doug Lea (dl at g.oswego.edu) + * removed potential for odd address access in prev_chunk + * removed dependency on getpagesize.h + * misc cosmetics and a bit more internal documentation + * anticosmetics: mangled names in macros to evade debugger strangeness + * tested on sparc, hp-700, dec-mips, rs6000 + with gcc & native cc (hp, dec only) allowing + Detlefs & Zorn comparison study (in SIGPLAN Notices.) + + Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) + * Based loosely on libg++-1.2X malloc. (It retains some of the overall + structure of old version, but most details differ.) + +*/ diff --git a/src/dlmalloc_ext_2_8_6.c b/src/dlmalloc_ext_2_8_6.c new file mode 100644 index 0000000..813f3e0 --- /dev/null +++ b/src/dlmalloc_ext_2_8_6.c @@ -0,0 +1,1382 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + + +#define BOOST_CONTAINER_SOURCE +#include + +#include "errno.h" //dlmalloc bug EINVAL is used in posix_memalign without checking LACKS_ERRNO_H +#include "limits.h" //CHAR_BIT +#ifdef BOOST_CONTAINER_DLMALLOC_FOOTERS +#define FOOTERS 1 +#endif +#define USE_LOCKS 1 +#define MSPACES 1 +#define NO_MALLINFO 0 + +#if !defined(NDEBUG) + #if !defined(DEBUG) + #define DEBUG 1 + #define DL_DEBUG_DEFINED + #endif +#endif + +#define USE_DL_PREFIX +#define FORCEINLINE +#include "dlmalloc_2_8_6.c" + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable : 4127) +#pragma warning (disable : 4267) +#pragma warning (disable : 4127) +#pragma warning (disable : 4702) +#pragma warning (disable : 4390) /*empty controlled statement found; is this the intent?*/ +#pragma warning (disable : 4251 4231 4660) /*dll warnings*/ +#endif + +#define DL_SIZE_IMPL(p) (chunksize(mem2chunk(p)) - overhead_for(mem2chunk(p))) + +static size_t s_allocated_memory; + +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +// +// SLIGHTLY MODIFIED DLMALLOC FUNCTIONS +// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// + +//This function is equal to mspace_free +//replacing PREACTION with 0 and POSTACTION with nothing +static void mspace_free_lockless(mspace msp, void* mem) +{ + if (mem != 0) { + mchunkptr p = mem2chunk(mem); +#if FOOTERS + mstate fm = get_mstate_for(p); + msp = msp; /* placate people compiling -Wunused */ +#else /* FOOTERS */ + mstate fm = (mstate)msp; +#endif /* FOOTERS */ + if (!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if (!0){//PREACTION(fm)) { + check_inuse_chunk(fm, p); + if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + s_allocated_memory -= psize; + if (!pinuse(p)) { + size_t prevsize = p->prev_foot; + if (is_mmapped(p)) { + psize += prevsize + MMAP_FOOT_PAD; + if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } + else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ + if (p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } + else if ((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } + else + goto erroraction; + } + } + + if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if (!cinuse(next)) { /* consolidate forward */ + if (next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if (p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if (should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } + else if (next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } + else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if (p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } + else + set_free_with_pinuse(p, psize, next); + + if (is_small(psize)) { + insert_small_chunk(fm, p, psize); + check_free_chunk(fm, p); + } + else { + tchunkptr tp = (tchunkptr)p; + insert_large_chunk(fm, tp, psize); + check_free_chunk(fm, p); + if (--fm->release_checks == 0) + release_unused_segments(fm); + } + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + ;//POSTACTION(fm); + } + } +} + +//This function is equal to mspace_malloc +//replacing PREACTION with 0 and POSTACTION with nothing +void* mspace_malloc_lockless(mspace msp, size_t bytes) +{ + mstate ms = (mstate)msp; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + if (!0){//PREACTION(ms)) { + void* mem; + size_t nb; + if (bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb > ms->dvsize) { + if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } + else if (bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if (nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } + else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if (nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + mem = sys_alloc(ms, nb); + + postaction: + ;//POSTACTION(ms); + return mem; + } + + return 0; +} + +//This function is equal to try_realloc_chunk but handling +//minimum and desired bytes +static mchunkptr try_realloc_chunk_with_min(mstate m, mchunkptr p, size_t min_nb, size_t des_nb, int can_move) +{ + mchunkptr newp = 0; + size_t oldsize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, oldsize); + if (RTCHECK(ok_address(m, p) && ok_inuse(p) && + ok_next(p, next) && ok_pinuse(next))) { + if (is_mmapped(p)) { + newp = mmap_resize(m, p, des_nb, can_move); + if(!newp) //mmap does not return how many bytes we could reallocate, so go the minimum + newp = mmap_resize(m, p, min_nb, can_move); + } + else if (oldsize >= min_nb) { /* already big enough */ + size_t nb = oldsize >= des_nb ? des_nb : oldsize; + size_t rsize = oldsize - nb; + if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + else if (next == m->top) { /* extend into top */ + if (oldsize + m->topsize > min_nb) { + size_t nb = (oldsize + m->topsize) > des_nb ? des_nb : (oldsize + m->topsize - MALLOC_ALIGNMENT); + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + newtop->head = newtopsize |PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = p; + } + } + else if (next == m->dv) { /* extend into dv */ + size_t dvs = m->dvsize; + if (oldsize + dvs >= min_nb) { + size_t nb = (oldsize + dvs) >= des_nb ? des_nb : (oldsize + dvs); + size_t dsize = oldsize + dvs - nb; + if (dsize >= MIN_CHUNK_SIZE) { + mchunkptr r = chunk_plus_offset(p, nb); + mchunkptr n = chunk_plus_offset(r, dsize); + set_inuse(m, p, nb); + set_size_and_pinuse_of_free_chunk(r, dsize); + clear_pinuse(n); + m->dvsize = dsize; + m->dv = r; + } + else { /* exhaust dv */ + size_t newsize = oldsize + dvs; + set_inuse(m, p, newsize); + m->dvsize = 0; + m->dv = 0; + } + newp = p; + } + } + else if (!cinuse(next)) { /* extend into next free chunk */ + size_t nextsize = chunksize(next); + if (oldsize + nextsize >= min_nb) { + size_t nb = (oldsize + nextsize) >= des_nb ? des_nb : (oldsize + nextsize); + size_t rsize = oldsize + nextsize - nb; + unlink_chunk(m, next, nextsize); + if (rsize < MIN_CHUNK_SIZE) { + size_t newsize = oldsize + nextsize; + set_inuse(m, p, newsize); + } + else { + mchunkptr r = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, r, rsize); + dispose_chunk(m, r, rsize); + } + newp = p; + } + } + } + else { + USAGE_ERROR_ACTION(m, chunk2mem(p)); + } + return newp; +} + +#define BOOST_ALLOC_PLUS_MEMCHAIN_MEM_JUMP_NEXT(THISMEM, NEXTMEM) \ + *((void**)(THISMEM)) = *((void**)((NEXTMEM))) + +//This function is based on internal_bulk_free +//replacing iteration over array[] with boost_cont_memchain. +//Instead of returning the unallocated nodes, returns a chain of non-deallocated nodes. +//After forward merging, backwards merging is also tried +static void internal_multialloc_free(mstate m, boost_cont_memchain *pchain) +{ +#if FOOTERS + boost_cont_memchain ret_chain; + BOOST_CONTAINER_MEMCHAIN_INIT(&ret_chain); +#endif + if (!PREACTION(m)) { + boost_cont_memchain_it a_it = BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(pchain); + while(!BOOST_CONTAINER_MEMCHAIN_IS_END_IT(pchain, a_it)) { /* Iterate though all memory holded by the chain */ + void* a_mem = BOOST_CONTAINER_MEMIT_ADDR(a_it); + mchunkptr a_p = mem2chunk(a_mem); + size_t psize = chunksize(a_p); +#if FOOTERS + if (get_mstate_for(a_p) != m) { + BOOST_CONTAINER_MEMIT_NEXT(a_it); + BOOST_CONTAINER_MEMCHAIN_PUSH_BACK(&ret_chain, a_mem); + continue; + } +#endif + check_inuse_chunk(m, a_p); + if (RTCHECK(ok_address(m, a_p) && ok_inuse(a_p))) { + while(1) { /* Internal loop to speed up forward and backward merging (avoids some redundant checks) */ + boost_cont_memchain_it b_it = a_it; + BOOST_CONTAINER_MEMIT_NEXT(b_it); + if(!BOOST_CONTAINER_MEMCHAIN_IS_END_IT(pchain, b_it)){ + void *b_mem = BOOST_CONTAINER_MEMIT_ADDR(b_it); + mchunkptr b_p = mem2chunk(b_mem); + if (b_p == next_chunk(a_p)) { /* b chunk is contiguous and next so b's size can be added to a */ + psize += chunksize(b_p); + set_inuse(m, a_p, psize); + BOOST_ALLOC_PLUS_MEMCHAIN_MEM_JUMP_NEXT(a_mem, b_mem); + continue; + } + if(RTCHECK(ok_address(m, b_p) && ok_inuse(b_p))){ + /* b chunk is contiguous and previous so a's size can be added to b */ + if(a_p == next_chunk(b_p)) { + psize += chunksize(b_p); + set_inuse(m, b_p, psize); + a_it = b_it; + a_p = b_p; + a_mem = b_mem; + continue; + } + } + } + /* Normal deallocation starts again in the outer loop */ + a_it = b_it; + s_allocated_memory -= psize; + dispose_chunk(m, a_p, psize); + break; + } + } + else { + CORRUPTION_ERROR_ACTION(m); + break; + } + } + if (should_trim(m, m->topsize)) + sys_trim(m, 0); + POSTACTION(m); + } +#if FOOTERS + { + boost_cont_memchain_it last_pchain = BOOST_CONTAINER_MEMCHAIN_LAST_IT(pchain); + BOOST_CONTAINER_MEMCHAIN_INIT(pchain); + BOOST_CONTAINER_MEMCHAIN_INCORPORATE_AFTER + (pchain + , last_pchain + , BOOST_CONTAINER_MEMCHAIN_FIRSTMEM(&ret_chain) + , BOOST_CONTAINER_MEMCHAIN_LASTMEM(&ret_chain) + , BOOST_CONTAINER_MEMCHAIN_SIZE(&ret_chain) + ); + } +#endif +} + +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +// +// NEW FUNCTIONS BASED ON DLMALLOC INTERNALS +// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////// + +#define GET_TRUNCATED_SIZE(ORIG_SIZE, ROUNDTO) ((ORIG_SIZE)/(ROUNDTO)*(ROUNDTO)) +#define GET_ROUNDED_SIZE(ORIG_SIZE, ROUNDTO) ((((ORIG_SIZE)-1)/(ROUNDTO)+1)*(ROUNDTO)) +#define GET_TRUNCATED_PO2_SIZE(ORIG_SIZE, ROUNDTO) ((ORIG_SIZE) & (~(ROUNDTO-1))) +#define GET_ROUNDED_PO2_SIZE(ORIG_SIZE, ROUNDTO) (((ORIG_SIZE - 1) & (~(ROUNDTO-1))) + ROUNDTO) + +/* Greatest common divisor and least common multiple + gcd is an algorithm that calculates the greatest common divisor of two + integers, using Euclid's algorithm. + + Pre: A > 0 && B > 0 + Recommended: A > B*/ +#define CALCULATE_GCD(A, B, OUT)\ +{\ + size_t a = A;\ + size_t b = B;\ + do\ + {\ + size_t tmp = b;\ + b = a % b;\ + a = tmp;\ + } while (b != 0);\ +\ + OUT = a;\ +} + +/* lcm is an algorithm that calculates the least common multiple of two + integers. + + Pre: A > 0 && B > 0 + Recommended: A > B*/ +#define CALCULATE_LCM(A, B, OUT)\ +{\ + CALCULATE_GCD(A, B, OUT);\ + OUT = (A / OUT)*B;\ +} + +static int calculate_lcm_and_needs_backwards_lcmed + (size_t backwards_multiple, size_t received_size, size_t size_to_achieve, + size_t *plcm, size_t *pneeds_backwards_lcmed) +{ + /* Now calculate lcm */ + size_t max = backwards_multiple; + size_t min = MALLOC_ALIGNMENT; + size_t needs_backwards; + size_t needs_backwards_lcmed; + size_t lcm; + size_t current_forward; + /*Swap if necessary*/ + if(max < min){ + size_t tmp = min; + min = max; + max = tmp; + } + /*Check if it's power of two*/ + if((backwards_multiple & (backwards_multiple-1)) == 0){ + if(0 != (size_to_achieve & ((backwards_multiple-1)))){ + USAGE_ERROR_ACTION(m, oldp); + return 0; + } + + lcm = max; + /*If we want to use minbytes data to get a buffer between maxbytes + and minbytes if maxbytes can't be achieved, calculate the + biggest of all possibilities*/ + current_forward = GET_TRUNCATED_PO2_SIZE(received_size, backwards_multiple); + needs_backwards = size_to_achieve - current_forward; + assert((needs_backwards % backwards_multiple) == 0); + needs_backwards_lcmed = GET_ROUNDED_PO2_SIZE(needs_backwards, lcm); + *plcm = lcm; + *pneeds_backwards_lcmed = needs_backwards_lcmed; + return 1; + } + /*Check if it's multiple of alignment*/ + else if((backwards_multiple & (MALLOC_ALIGNMENT - 1u)) == 0){ + lcm = backwards_multiple; + current_forward = GET_TRUNCATED_SIZE(received_size, backwards_multiple); + //No need to round needs_backwards because backwards_multiple == lcm + needs_backwards_lcmed = needs_backwards = size_to_achieve - current_forward; + assert((needs_backwards_lcmed & (MALLOC_ALIGNMENT - 1u)) == 0); + *plcm = lcm; + *pneeds_backwards_lcmed = needs_backwards_lcmed; + return 1; + } + /*Check if it's multiple of the half of the alignmment*/ + else if((backwards_multiple & ((MALLOC_ALIGNMENT/2u) - 1u)) == 0){ + lcm = backwards_multiple*2u; + current_forward = GET_TRUNCATED_SIZE(received_size, backwards_multiple); + needs_backwards_lcmed = needs_backwards = size_to_achieve - current_forward; + if(0 != (needs_backwards_lcmed & (MALLOC_ALIGNMENT-1))) + //while(0 != (needs_backwards_lcmed & (MALLOC_ALIGNMENT-1))) + needs_backwards_lcmed += backwards_multiple; + assert((needs_backwards_lcmed % lcm) == 0); + *plcm = lcm; + *pneeds_backwards_lcmed = needs_backwards_lcmed; + return 1; + } + /*Check if it's multiple of the quarter of the alignmment*/ + else if((backwards_multiple & ((MALLOC_ALIGNMENT/4u) - 1u)) == 0){ + size_t remainder; + lcm = backwards_multiple*4u; + current_forward = GET_TRUNCATED_SIZE(received_size, backwards_multiple); + needs_backwards_lcmed = needs_backwards = size_to_achieve - current_forward; + //while(0 != (needs_backwards_lcmed & (MALLOC_ALIGNMENT-1))) + //needs_backwards_lcmed += backwards_multiple; + if(0 != (remainder = ((needs_backwards_lcmed & (MALLOC_ALIGNMENT-1))>>(MALLOC_ALIGNMENT/8u)))){ + if(backwards_multiple & MALLOC_ALIGNMENT/2u){ + needs_backwards_lcmed += (remainder)*backwards_multiple; + } + else{ + needs_backwards_lcmed += (4-remainder)*backwards_multiple; + } + } + assert((needs_backwards_lcmed % lcm) == 0); + *plcm = lcm; + *pneeds_backwards_lcmed = needs_backwards_lcmed; + return 1; + } + else{ + CALCULATE_LCM(max, min, lcm); + /*If we want to use minbytes data to get a buffer between maxbytes + and minbytes if maxbytes can't be achieved, calculate the + biggest of all possibilities*/ + current_forward = GET_TRUNCATED_SIZE(received_size, backwards_multiple); + needs_backwards = size_to_achieve - current_forward; + assert((needs_backwards % backwards_multiple) == 0); + needs_backwards_lcmed = GET_ROUNDED_SIZE(needs_backwards, lcm); + *plcm = lcm; + *pneeds_backwards_lcmed = needs_backwards_lcmed; + return 1; + } +} + +static void *internal_grow_both_sides + (mstate m + ,allocation_type command + ,void *oldmem + ,size_t minbytes + ,size_t maxbytes + ,size_t *received_size + ,size_t backwards_multiple + ,int only_preferred_backwards) +{ + mchunkptr oldp = mem2chunk(oldmem); + size_t oldsize = chunksize(oldp); + *received_size = oldsize - overhead_for(oldp); + if(minbytes <= *received_size) + return oldmem; + + if (RTCHECK(ok_address(m, oldp) && ok_inuse(oldp))) { + if(command & BOOST_CONTAINER_EXPAND_FWD){ + if(try_realloc_chunk_with_min(m, oldp, request2size(minbytes), request2size(maxbytes), 0)){ + check_inuse_chunk(m, oldp); + *received_size = DL_SIZE_IMPL(oldmem); + s_allocated_memory += chunksize(oldp) - oldsize; + return oldmem; + } + } + else{ + *received_size = DL_SIZE_IMPL(oldmem); + if(*received_size >= maxbytes) + return oldmem; + } +/* + Should we check this? + if(backwards_multiple && + (0 != (minbytes % backwards_multiple) && + 0 != (maxbytes % backwards_multiple)) ){ + USAGE_ERROR_ACTION(m, oldp); + return 0; + } +*/ + /* We reach here only if forward expansion fails */ + if(!(command & BOOST_CONTAINER_EXPAND_BWD) || pinuse(oldp)){ + return 0; + } + { + size_t prevsize = oldp->prev_foot; + if ((prevsize & USE_MMAP_BIT) != 0){ + /*Return failure the previous chunk was mmapped. + mremap does not allow expanding to a fixed address (MREMAP_MAYMOVE) without + copying (MREMAP_MAYMOVE must be also set).*/ + return 0; + } + else { + mchunkptr prev = chunk_minus_offset(oldp, prevsize); + size_t dsize = oldsize + prevsize; + size_t needs_backwards_lcmed; + size_t lcm; + + /* Let's calculate the number of extra bytes of data before the current + block's begin. The value is a multiple of backwards_multiple + and the alignment*/ + if(!calculate_lcm_and_needs_backwards_lcmed + ( backwards_multiple, *received_size + , only_preferred_backwards ? maxbytes : minbytes + , &lcm, &needs_backwards_lcmed) + || !RTCHECK(ok_address(m, prev))){ + USAGE_ERROR_ACTION(m, oldp); + return 0; + } + /* Check if previous block has enough size */ + else if(prevsize < needs_backwards_lcmed){ + /* preferred size? */ + return 0; + } + /* Now take all next space. This must succeed, as we've previously calculated the correct size */ + if(command & BOOST_CONTAINER_EXPAND_FWD){ + if(!try_realloc_chunk_with_min(m, oldp, request2size(*received_size), request2size(*received_size), 0)){ + assert(0); + } + check_inuse_chunk(m, oldp); + *received_size = DL_SIZE_IMPL(oldmem); + s_allocated_memory += chunksize(oldp) - oldsize; + oldsize = chunksize(oldp); + dsize = oldsize + prevsize; + } + /* We need a minimum size to split the previous one */ + if(prevsize >= (needs_backwards_lcmed + MIN_CHUNK_SIZE)){ + mchunkptr r = chunk_minus_offset(oldp, needs_backwards_lcmed); + size_t rsize = oldsize + needs_backwards_lcmed; + size_t newprevsize = dsize - rsize; + int prev_was_dv = prev == m->dv; + + assert(newprevsize >= MIN_CHUNK_SIZE); + + if (prev_was_dv) { + m->dvsize = newprevsize; + } + else{/* if ((next->head & INUSE_BITS) == INUSE_BITS) { */ + unlink_chunk(m, prev, prevsize); + insert_chunk(m, prev, newprevsize); + } + + set_size_and_pinuse_of_free_chunk(prev, newprevsize); + clear_pinuse(r); + set_inuse(m, r, rsize); + check_malloced_chunk(m, chunk2mem(r), rsize); + *received_size = chunksize(r) - overhead_for(r); + s_allocated_memory += chunksize(r) - oldsize; + return chunk2mem(r); + } + /* Check if there is no place to create a new block and + the whole new block is multiple of the backwards expansion multiple */ + else if(prevsize >= needs_backwards_lcmed && !(prevsize % lcm)) { + /* Just merge the whole previous block */ + /* prevsize is multiple of lcm (and backwards_multiple)*/ + *received_size += prevsize; + + if (prev != m->dv) { + unlink_chunk(m, prev, prevsize); + } + else{ + m->dvsize = 0; + m->dv = 0; + } + set_inuse(m, prev, dsize); + check_malloced_chunk(m, chunk2mem(prev), dsize); + s_allocated_memory += chunksize(prev) - oldsize; + return chunk2mem(prev); + } + else{ + /* Previous block was big enough but there is no room + to create an empty block and taking the whole block does + not fulfill alignment requirements */ + return 0; + } + } + } + } + else{ + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } + return 0; +} + +/* This is similar to mmap_resize but: + * Only to shrink + * It takes min and max sizes + * Takes additional 'do_commit' argument to obtain the final + size before doing the real shrink operation. +*/ +static int internal_mmap_shrink_in_place(mstate m, mchunkptr oldp, size_t nbmin, size_t nbmax, size_t *received_size, int do_commit) +{ + size_t oldsize = chunksize(oldp); + *received_size = oldsize; + #if HAVE_MREMAP + if (is_small(nbmax)) /* Can't shrink mmap regions below small size */ + return 0; + { + size_t effective_min = nbmin > MIN_LARGE_SIZE ? nbmin : MIN_LARGE_SIZE; + /* Keep old chunk if big enough but not too big */ + if (oldsize >= effective_min + SIZE_T_SIZE && + (oldsize - effective_min) <= (mparams.granularity << 1)) + return 0; + /* Now calculate new sizes */ + { + size_t offset = oldp->prev_foot; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = mmap_align(effective_min + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + *received_size = newmmsize; + if(!do_commit){ + const int flags = 0; /* placate people compiling -Wunused */ + char* cp = (char*)CALL_MREMAP((char*)oldp - offset, + oldmmsize, newmmsize, flags); + /*This must always succeed */ + if(!cp){ + USAGE_ERROR_ACTION(m, m); + return 0; + } + { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = psize; + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; + + if (cp < m->least_addr) + m->least_addr = cp; + if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + } + } + } + return 1; + } + #else //#if HAVE_MREMAP + (void)m; + (void)oldp; + (void)nbmin; + (void)nbmax; + (void)received_size; + (void)do_commit; + return 0; + #endif //#if HAVE_MREMAP +} + +static int internal_shrink(mstate m, void* oldmem, size_t minbytes, size_t maxbytes, size_t *received_size, int do_commit) +{ + *received_size = chunksize(mem2chunk(oldmem)) - overhead_for(mem2chunk(oldmem)); + if (minbytes >= MAX_REQUEST || maxbytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + return 0; + } + else if(minbytes < MIN_REQUEST){ + minbytes = MIN_REQUEST; + } + if (minbytes > maxbytes) { + return 0; + } + + { + mchunkptr oldp = mem2chunk(oldmem); + size_t oldsize = chunksize(oldp); + mchunkptr next = chunk_plus_offset(oldp, oldsize); + void* extra = 0; + + /* Try to either shrink or extend into top. Else malloc-copy-free*/ + if (RTCHECK(ok_address(m, oldp) && ok_inuse(oldp) && + ok_next(oldp, next) && ok_pinuse(next))) { + size_t nbmin = request2size(minbytes); + size_t nbmax = request2size(maxbytes); + + if (nbmin > oldsize){ + /* Return error if old size is too small */ + } + else if (is_mmapped(oldp)){ + return internal_mmap_shrink_in_place(m, oldp, nbmin, nbmax, received_size, do_commit); + } + else{ // nbmin <= oldsize /* already big enough*/ + size_t nb = nbmin; + size_t rsize = oldsize - nb; + if (rsize >= MIN_CHUNK_SIZE) { + if(do_commit){ + mchunkptr remainder = chunk_plus_offset(oldp, nb); + set_inuse(m, oldp, nb); + set_inuse(m, remainder, rsize); + extra = chunk2mem(remainder); + } + *received_size = nb - overhead_for(oldp); + if(!do_commit) + return 1; + } + } + } + else { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } + + if (extra != 0 && do_commit) { + mspace_free_lockless(m, extra); + check_inuse_chunk(m, oldp); + return 1; + } + else { + return 0; + } + } +} + + +#define INTERNAL_MULTIALLOC_DEFAULT_CONTIGUOUS_MEM 4096 + +#define SQRT_MAX_SIZE_T (((size_t)-1)>>(sizeof(size_t)*CHAR_BIT/2)) + +static int internal_node_multialloc + (mstate m, size_t n_elements, size_t element_size, size_t contiguous_elements, boost_cont_memchain *pchain) { + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + flag_t was_enabled; /* to disable mmap */ + size_t elements_per_segment = 0; + size_t element_req_size = request2size(element_size); + boost_cont_memchain_it prev_last_it = BOOST_CONTAINER_MEMCHAIN_LAST_IT(pchain); + + /*Error if wrong element_size parameter */ + if( !element_size || + /*OR Error if n_elements less thatn contiguous_elements */ + ((contiguous_elements + 1) > (DL_MULTIALLOC_DEFAULT_CONTIGUOUS + 1) && n_elements < contiguous_elements) || + /* OR Error if integer overflow */ + (SQRT_MAX_SIZE_T < (element_req_size | contiguous_elements) && + (MAX_SIZE_T/element_req_size) < contiguous_elements)){ + return 0; + } + switch(contiguous_elements){ + case DL_MULTIALLOC_DEFAULT_CONTIGUOUS: + { + /* Default contiguous, just check that we can store at least one element */ + elements_per_segment = INTERNAL_MULTIALLOC_DEFAULT_CONTIGUOUS_MEM/element_req_size; + elements_per_segment += (size_t)(!elements_per_segment); + } + break; + case DL_MULTIALLOC_ALL_CONTIGUOUS: + /* All elements should be allocated in a single call */ + elements_per_segment = n_elements; + break; + default: + /* Allocate in chunks of "contiguous_elements" */ + elements_per_segment = contiguous_elements; + } + + { + size_t i; + size_t next_i; + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + for(i = 0; i != n_elements; i = next_i) + { + size_t accum_size; + size_t n_elements_left = n_elements - i; + next_i = i + ((n_elements_left < elements_per_segment) ? n_elements_left : elements_per_segment); + accum_size = element_req_size*(next_i - i); + + mem = mspace_malloc_lockless(m, accum_size - CHUNK_OVERHEAD); + if (mem == 0){ + BOOST_CONTAINER_MEMIT_NEXT(prev_last_it); + while(i--){ + void *addr = BOOST_CONTAINER_MEMIT_ADDR(prev_last_it); + BOOST_CONTAINER_MEMIT_NEXT(prev_last_it); + mspace_free_lockless(m, addr); + } + if (was_enabled) + enable_mmap(m); + return 0; + } + p = mem2chunk(mem); + remainder_size = chunksize(p); + s_allocated_memory += remainder_size; + + assert(!is_mmapped(p)); + { /* split out elements */ + void *mem_orig = mem; + boost_cont_memchain_it last_it = BOOST_CONTAINER_MEMCHAIN_LAST_IT(pchain); + size_t num_elements = next_i-i; + + size_t num_loops = num_elements - 1; + remainder_size -= element_req_size*num_loops; + while(num_loops--){ + void **mem_prev = ((void**)mem); + set_size_and_pinuse_of_inuse_chunk(m, p, element_req_size); + p = chunk_plus_offset(p, element_req_size); + mem = chunk2mem(p); + *mem_prev = mem; + } + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + BOOST_CONTAINER_MEMCHAIN_INCORPORATE_AFTER(pchain, last_it, mem_orig, mem, num_elements); + } + } + if (was_enabled) + enable_mmap(m); + } + return 1; +} + +static int internal_multialloc_arrays + (mstate m, size_t n_elements, const size_t* sizes, size_t element_size, size_t contiguous_elements, boost_cont_memchain *pchain) { + void* mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t boost_cont_multialloc_segmented_malloc_size; + size_t max_size; + + /* Check overflow */ + if(!element_size){ + return 0; + } + max_size = MAX_REQUEST/element_size; + /* Different sizes*/ + switch(contiguous_elements){ + case DL_MULTIALLOC_DEFAULT_CONTIGUOUS: + /* Use default contiguous mem */ + boost_cont_multialloc_segmented_malloc_size = INTERNAL_MULTIALLOC_DEFAULT_CONTIGUOUS_MEM; + break; + case DL_MULTIALLOC_ALL_CONTIGUOUS: + boost_cont_multialloc_segmented_malloc_size = MAX_REQUEST + CHUNK_OVERHEAD; + break; + default: + if(max_size < contiguous_elements){ + return 0; + } + else{ + /* The suggested buffer is just the the element count by the size */ + boost_cont_multialloc_segmented_malloc_size = element_size*contiguous_elements; + } + } + + { + size_t i; + size_t next_i; + /* + Allocate the aggregate chunk. First disable direct-mmapping so + malloc won't use it, since we would not be able to later + free/realloc space internal to a segregated mmap region. + */ + was_enabled = use_mmap(m); + disable_mmap(m); + for(i = 0, next_i = 0; i != n_elements; i = next_i) + { + int error = 0; + size_t accum_size; + for(accum_size = 0; next_i != n_elements; ++next_i){ + size_t cur_array_size = sizes[next_i]; + if(max_size < cur_array_size){ + error = 1; + break; + } + else{ + size_t reqsize = request2size(cur_array_size*element_size); + if(((boost_cont_multialloc_segmented_malloc_size - CHUNK_OVERHEAD) - accum_size) < reqsize){ + if(!accum_size){ + accum_size += reqsize; + ++next_i; + } + break; + } + accum_size += reqsize; + } + } + + mem = error ? 0 : mspace_malloc_lockless(m, accum_size - CHUNK_OVERHEAD); + if (mem == 0){ + boost_cont_memchain_it it = BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(pchain); + while(i--){ + void *addr = BOOST_CONTAINER_MEMIT_ADDR(it); + BOOST_CONTAINER_MEMIT_NEXT(it); + mspace_free_lockless(m, addr); + } + if (was_enabled) + enable_mmap(m); + return 0; + } + p = mem2chunk(mem); + remainder_size = chunksize(p); + s_allocated_memory += remainder_size; + + assert(!is_mmapped(p)); + + { /* split out elements */ + void *mem_orig = mem; + boost_cont_memchain_it last_it = BOOST_CONTAINER_MEMCHAIN_LAST_IT(pchain); + size_t num_elements = next_i-i; + + for(++i; i != next_i; ++i) { + void **mem_prev = ((void**)mem); + size = request2size(sizes[i]*element_size); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + mem = chunk2mem(p); + *mem_prev = mem; + } + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + BOOST_CONTAINER_MEMCHAIN_INCORPORATE_AFTER(pchain, last_it, mem_orig, mem, num_elements); + } + } + if (was_enabled) + enable_mmap(m); + } + return 1; +} + +BOOST_CONTAINER_DECL int boost_cont_multialloc_arrays + (size_t n_elements, const size_t *sizes, size_t element_size, size_t contiguous_elements, boost_cont_memchain *pchain) +{ + int ret = 0; + mstate ms = (mstate)gm; + ensure_initialization(); + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + else if (!PREACTION(ms)) { + ret = internal_multialloc_arrays(ms, n_elements, sizes, element_size, contiguous_elements, pchain); + POSTACTION(ms); + } + return ret; +} + + +/*Doug Lea malloc extensions*/ +static boost_cont_malloc_stats_t get_malloc_stats(mstate m) +{ + boost_cont_malloc_stats_t ret; + ensure_initialization(); + if (!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if (is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while (s != 0) { + mchunkptr q = align_as_chunk(s->base); + while (segment_holds(s, q) && + q != m->top && q->head != FENCEPOST_HEAD) { + if (!cinuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + + ret.max_system_bytes = maxfp; + ret.system_bytes = fp; + ret.in_use_bytes = used; + POSTACTION(m); + } + return ret; +} + +BOOST_CONTAINER_DECL size_t boost_cont_size(const void *p) +{ return DL_SIZE_IMPL(p); } + +BOOST_CONTAINER_DECL void* boost_cont_malloc(size_t bytes) +{ + size_t received_bytes; + ensure_initialization(); + return boost_cont_allocation_command + (BOOST_CONTAINER_ALLOCATE_NEW, 1, bytes, bytes, &received_bytes, 0).first; +} + +BOOST_CONTAINER_DECL void boost_cont_free(void* mem) +{ + mstate ms = (mstate)gm; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + else if (!PREACTION(ms)) { + mspace_free_lockless(ms, mem); + POSTACTION(ms); + } +} + +BOOST_CONTAINER_DECL void* boost_cont_memalign(size_t bytes, size_t alignment) +{ + void *addr; + ensure_initialization(); + addr = mspace_memalign(gm, alignment, bytes); + if(addr){ + s_allocated_memory += chunksize(mem2chunk(addr)); + } + return addr; +} + +BOOST_CONTAINER_DECL int boost_cont_multialloc_nodes + (size_t n_elements, size_t elem_size, size_t contiguous_elements, boost_cont_memchain *pchain) +{ + int ret = 0; + mstate ms = (mstate)gm; + ensure_initialization(); + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + } + else if (!PREACTION(ms)) { + ret = internal_node_multialloc(ms, n_elements, elem_size, contiguous_elements, pchain); + POSTACTION(ms); + } + return ret; +} + +BOOST_CONTAINER_DECL size_t boost_cont_footprint() +{ + return ((mstate)gm)->footprint; +} + +BOOST_CONTAINER_DECL size_t boost_cont_allocated_memory() +{ + struct mallinfo info = mspace_mallinfo(gm); + ensure_initialization(); + if(info.ordblks) + return (size_t)(info.uordblks - (info.ordblks-1)*TOP_FOOT_SIZE); + else + return info.uordblks; +} + +BOOST_CONTAINER_DECL size_t boost_cont_chunksize(const void *p) +{ return chunksize(mem2chunk(p)); } + +BOOST_CONTAINER_DECL int boost_cont_all_deallocated() +{ return !s_allocated_memory; } + +BOOST_CONTAINER_DECL boost_cont_malloc_stats_t boost_cont_malloc_stats() +{ + mstate ms = (mstate)gm; + if (ok_magic(ms)) { + return get_malloc_stats(ms); + } + else { + boost_cont_malloc_stats_t r = { 0, 0, 0 }; + USAGE_ERROR_ACTION(ms,ms); + return r; + } +} + +BOOST_CONTAINER_DECL size_t boost_cont_in_use_memory() +{ return s_allocated_memory; } + +BOOST_CONTAINER_DECL int boost_cont_trim(size_t pad) +{ + ensure_initialization(); + return dlmalloc_trim(pad); +} + +BOOST_CONTAINER_DECL int boost_cont_grow + (void* oldmem, size_t minbytes, size_t maxbytes, size_t *received) +{ + mstate ms = (mstate)gm; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + + if (!PREACTION(ms)) { + mchunkptr p = mem2chunk(oldmem); + size_t oldsize = chunksize(p); + p = try_realloc_chunk_with_min(ms, p, request2size(minbytes), request2size(maxbytes), 0); + POSTACTION(ms); + if(p){ + check_inuse_chunk(ms, p); + *received = DL_SIZE_IMPL(oldmem); + s_allocated_memory += chunksize(p) - oldsize; + } + return 0 != p; + } + return 0; +} + +BOOST_CONTAINER_DECL int boost_cont_shrink + (void* oldmem, size_t minbytes, size_t maxbytes, size_t *received, int do_commit) +{ + mstate ms = (mstate)gm; + if (!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + + if (!PREACTION(ms)) { + int ret = internal_shrink(ms, oldmem, minbytes, maxbytes, received, do_commit); + POSTACTION(ms); + return 0 != ret; + } + return 0; +} + + +BOOST_CONTAINER_DECL void* boost_cont_alloc + (size_t minbytes, size_t preferred_bytes, size_t *received_bytes) +{ + //ensure_initialization provided by boost_cont_allocation_command + return boost_cont_allocation_command + (BOOST_CONTAINER_ALLOCATE_NEW, 1, minbytes, preferred_bytes, received_bytes, 0).first; +} + +BOOST_CONTAINER_DECL void boost_cont_multidealloc(boost_cont_memchain *pchain) +{ + mstate ms = (mstate)gm; + if (!ok_magic(ms)) { + (void)ms; + USAGE_ERROR_ACTION(ms,ms); + } + internal_multialloc_free(ms, pchain); +} + +BOOST_CONTAINER_DECL int boost_cont_malloc_check() +{ +#ifdef DEBUG + mstate ms = (mstate)gm; + ensure_initialization(); + if (!ok_magic(ms)) { + (void)ms; + USAGE_ERROR_ACTION(ms,ms); + return 0; + } + check_malloc_state(ms); + return 1; +#else + return 1; +#endif +} + + +BOOST_CONTAINER_DECL boost_cont_command_ret_t boost_cont_allocation_command + (allocation_type command, size_t sizeof_object, size_t limit_size + , size_t preferred_size, size_t *received_size, void *reuse_ptr) +{ + boost_cont_command_ret_t ret = { 0, 0 }; + ensure_initialization(); + if(command & (BOOST_CONTAINER_SHRINK_IN_PLACE | BOOST_CONTAINER_TRY_SHRINK_IN_PLACE)){ + int success = boost_cont_shrink( reuse_ptr, preferred_size, limit_size + , received_size, (command & BOOST_CONTAINER_SHRINK_IN_PLACE)); + ret.first = success ? reuse_ptr : 0; + return ret; + } + + *received_size = 0; + + if(limit_size > preferred_size) + return ret; + + { + mstate ms = (mstate)gm; + + /*Expand in place*/ + if (!PREACTION(ms)) { + #if FOOTERS + if(reuse_ptr){ + mstate m = get_mstate_for(mem2chunk(reuse_ptr)); + if (!ok_magic(m)) { + USAGE_ERROR_ACTION(m, reuse_ptr); + return ret; + } + } + #endif + if(reuse_ptr && (command & (BOOST_CONTAINER_EXPAND_FWD | BOOST_CONTAINER_EXPAND_BWD))){ + void *r = internal_grow_both_sides + ( ms, command, reuse_ptr, limit_size + , preferred_size, received_size, sizeof_object, 1); + if(r){ + ret.first = r; + ret.second = 1; + goto postaction; + } + } + + if(command & BOOST_CONTAINER_ALLOCATE_NEW){ + void *addr = mspace_malloc_lockless(ms, preferred_size); + if(!addr) addr = mspace_malloc_lockless(ms, limit_size); + if(addr){ + s_allocated_memory += chunksize(mem2chunk(addr)); + } + *received_size = DL_SIZE_IMPL(addr); + ret.first = addr; + ret.second = 0; + if(addr){ + goto postaction; + } + } + + //Now try to expand both sides with min size + if(reuse_ptr && (command & (BOOST_CONTAINER_EXPAND_FWD | BOOST_CONTAINER_EXPAND_BWD))){ + void *r = internal_grow_both_sides + ( ms, command, reuse_ptr, limit_size + , preferred_size, received_size, sizeof_object, 0); + if(r){ + ret.first = r; + ret.second = 1; + goto postaction; + } + } + postaction: + POSTACTION(ms); + } + } + return ret; +} + +BOOST_CONTAINER_DECL int boost_cont_mallopt(int param_number, int value) +{ + return change_mparam(param_number, value); +} + +//#ifdef DL_DEBUG_DEFINED +// #undef DEBUG +//#endif + +#ifdef _MSC_VER +#pragma warning (pop) +#endif diff --git a/test/Jamfile.v2 b/test/Jamfile.v2 index af84010..074630b 100644 --- a/test/Jamfile.v2 +++ b/test/Jamfile.v2 @@ -1,6 +1,6 @@ # Boost Container Library Test Jamfile -# (C) Copyright Ion Gaztanaga 2009. +# (C) Copyright Ion Gaztanaga 2009-2013. # Use, modification and distribution are subject to the # Boost Software License, Version 1.0. (See accompanying file # LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -21,7 +21,7 @@ rule test_all for local fileb in [ glob *.cpp ] { - all_rules += [ run $(fileb) + all_rules += [ run $(fileb) /boost/container//boost_container /boost/timer//boost_timer : # additional args : # test-files : # requirements diff --git a/test/alloc_basic_test.cpp b/test/alloc_basic_test.cpp new file mode 100644 index 0000000..757af76 --- /dev/null +++ b/test/alloc_basic_test.cpp @@ -0,0 +1,119 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include + +using namespace boost::container; + +bool basic_test() +{ + size_t received; + if(!boost_cont_all_deallocated()) + return false; + void *ptr = boost_cont_alloc(50, 98, &received); + if(boost_cont_size(ptr) != received) + return false; + if(boost_cont_allocated_memory() != boost_cont_chunksize(ptr)) + return false; + + if(boost_cont_all_deallocated()) + return false; + + boost_cont_grow(ptr, received + 20, received + 30, &received); + + if(boost_cont_allocated_memory() != boost_cont_chunksize(ptr)) + return false; + + if(boost_cont_size(ptr) != received) + return false; + + if(!boost_cont_shrink(ptr, 100, 140, &received, 1)) + return false; + + if(boost_cont_allocated_memory() != boost_cont_chunksize(ptr)) + return false; + + if(!boost_cont_shrink(ptr, 0, 140, &received, 1)) + return false; + + if(boost_cont_allocated_memory() != boost_cont_chunksize(ptr)) + return false; + + if(boost_cont_shrink(ptr, 0, received/2, &received, 1)) + return false; + + if(boost_cont_allocated_memory() != boost_cont_chunksize(ptr)) + return false; + + if(boost_cont_size(ptr) != received) + return false; + + boost_cont_free(ptr); + + boost_cont_malloc_check(); + if(!boost_cont_all_deallocated()) + return false; + return true; +} + +bool vector_test() +{ + typedef boost::container::vector > Vector; + if(!boost_cont_all_deallocated()) + return false; + { + const int NumElem = 1000; + Vector v; + v.resize(NumElem); + int *orig_buf = &v[0]; + int *new_buf = &v[0]; + while(orig_buf == new_buf){ + Vector::size_type cl = v.capacity() - v.size(); + while(cl--){ + v.push_back(0); + } + v.push_back(0); + new_buf = &v[0]; + } + } + if(!boost_cont_all_deallocated()) + return false; + return true; +} + +bool list_test() +{ + typedef boost::container::list > List; + if(!boost_cont_all_deallocated()) + return false; + { + const int NumElem = 1000; + List l; + int values[NumElem]; + l.insert(l.end(), &values[0], &values[NumElem]); + } + if(!boost_cont_all_deallocated()) + return false; + return true; +} + +int main() +{ + if(!basic_test()) + return 1; + if(!vector_test()) + return 1; + if(!list_test()) + return 1; + return 0; +} diff --git a/test/alloc_full_test.cpp b/test/alloc_full_test.cpp new file mode 100644 index 0000000..0553c8b --- /dev/null +++ b/test/alloc_full_test.cpp @@ -0,0 +1,851 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2007-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + + +#ifdef _MSC_VER +#pragma warning (disable:4702) +#endif + +#include +#include +#include +#include +#include +#include //std::remove +#include + +namespace boost { namespace container { namespace test { + +static const int NumIt = 2000; + +enum deallocation_type { DirectDeallocation, InverseDeallocation, MixedDeallocation, EndDeallocationType }; + +//This test allocates until there is no more memory +//and after that deallocates all in the inverse order + +bool test_allocation() +{ + if(!boost_cont_all_deallocated()) + return false; + boost_cont_malloc_check(); + for( deallocation_type t = DirectDeallocation + ; t != EndDeallocationType + ; t = (deallocation_type)((int)t + 1)){ + std::vector buffers; + //std::size_t free_memory = a.get_free_memory(); + + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i); + if(!ptr) + break; + buffers.push_back(ptr); + } + + switch(t){ + case DirectDeallocation: + { + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + boost_cont_free(buffers[j]); + } + } + break; + case InverseDeallocation: + { + for(int j = (int)buffers.size() + ;j-- + ;){ + boost_cont_free(buffers[j]); + } + } + break; + case MixedDeallocation: + { + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + } + break; + default: + break; + } + if(!boost_cont_all_deallocated()) + return false; + //bool ok = free_memory == a.get_free_memory() && + //a.all_memory_deallocated() && a.check_sanity(); + //if(!ok) return ok; + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated(); +} + +//This test allocates until there is no more memory +//and after that tries to shrink all the buffers to the +//half of the original size + +bool test_allocation_shrink() +{ + boost_cont_malloc_check(); + std::vector buffers; + + //Allocate buffers with extra memory + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i*2); + if(!ptr) + break; + buffers.push_back(ptr); + } + + //Now shrink to half + for(int i = 0, max = (int)buffers.size() + ;i < max + ; ++i){ + std::size_t try_received_size; + void* try_result = boost_cont_allocation_command + ( BOOST_CONTAINER_TRY_SHRINK_IN_PLACE, 1, i*2 + , i, &try_received_size, (char*)buffers[i]).first; + + std::size_t received_size; + void* result = boost_cont_allocation_command + ( BOOST_CONTAINER_SHRINK_IN_PLACE, 1, i*2 + , i, &received_size, (char*)buffers[i]).first; + + if(result != try_result) + return false; + + if(received_size != try_received_size) + return false; + + if(result){ + if(received_size > std::size_t(i*2)){ + return false; + } + if(received_size < std::size_t(i)){ + return false; + } + } + } + + //Deallocate it in non sequential order + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated();//a.all_memory_deallocated() && a.check_sanity(); +} + +//This test allocates until there is no more memory +//and after that tries to expand all the buffers to +//avoid the wasted internal fragmentation + +bool test_allocation_expand() +{ + boost_cont_malloc_check(); + std::vector buffers; + + //Allocate buffers with extra memory + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i); + if(!ptr) + break; + buffers.push_back(ptr); + } + + //Now try to expand to the double of the size + for(int i = 0, max = (int)buffers.size() + ;i < max + ;++i){ + std::size_t received_size; + std::size_t min_size = i+1; + std::size_t preferred_size = i*2; + preferred_size = min_size > preferred_size ? min_size : preferred_size; + while(boost_cont_allocation_command + ( BOOST_CONTAINER_EXPAND_FWD, 1, min_size + , preferred_size, &received_size, (char*)buffers[i]).first){ + //Check received size is bigger than minimum + if(received_size < min_size){ + return false; + } + //Now, try to expand further + min_size = received_size+1; + preferred_size = min_size*2; + } + } + + //Deallocate it in non sequential order + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated();//a.all_memory_deallocated() && a.check_sanity(); +} + +//This test allocates until there is no more memory +//and after that tries to expand all the buffers to +//avoid the wasted internal fragmentation +bool test_allocation_shrink_and_expand() +{ + std::vector buffers; + std::vector received_sizes; + std::vector size_reduced; + + //Allocate buffers wand store received sizes + for(int i = 0; i != NumIt; ++i){ + std::size_t received_size; + void *ptr = boost_cont_allocation_command + (BOOST_CONTAINER_ALLOCATE_NEW, 1, i, i*2, &received_size, 0).first; + if(!ptr){ + ptr = boost_cont_allocation_command + ( BOOST_CONTAINER_ALLOCATE_NEW, 1, 1, i*2, &received_size, 0).first; + if(!ptr) + break; + } + buffers.push_back(ptr); + received_sizes.push_back(received_size); + } + + //Now shrink to half + for(int i = 0, max = (int)buffers.size() + ; i < max + ; ++i){ + std::size_t received_size; + bool size_reduced_flag; + if(true == (size_reduced_flag = !! + boost_cont_allocation_command + ( BOOST_CONTAINER_SHRINK_IN_PLACE, 1, received_sizes[i] + , i, &received_size, (char*)buffers[i]).first)){ + if(received_size > std::size_t(received_sizes[i])){ + return false; + } + if(received_size < std::size_t(i)){ + return false; + } + } + size_reduced.push_back(size_reduced_flag); + } + + //Now try to expand to the original size + for(int i = 0, max = (int)buffers.size() + ;i < max + ;++i){ + if(!size_reduced[i]) continue; + std::size_t received_size; + std::size_t request_size = received_sizes[i]; + if(boost_cont_allocation_command + ( BOOST_CONTAINER_EXPAND_FWD, 1, request_size + , request_size, &received_size, (char*)buffers[i]).first){ + if(received_size != request_size){ + return false; + } + } + else{ + return false; + } + } + + //Deallocate it in non sequential order + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + + return 0 != boost_cont_all_deallocated();//a.all_memory_deallocated() && a.check_sanity(); +} + +//This test allocates until there is no more memory +//and after that deallocates the odd buffers to +//make room for expansions. The expansion will probably +//success since the deallocation left room for that. + +bool test_allocation_deallocation_expand() +{ + boost_cont_malloc_check(); + std::vector buffers; + + //Allocate buffers with extra memory + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i); + if(!ptr) + break; + buffers.push_back(ptr); + } + + //Now deallocate the half of the blocks + //so expand maybe can merge new free blocks + for(int i = 0, max = (int)buffers.size() + ;i < max + ;++i){ + if(i%2){ + boost_cont_free(buffers[i]); + buffers[i] = 0; + } + } + + //Now try to expand to the double of the size + for(int i = 0, max = (int)buffers.size() + ;i < max + ;++i){ + // + if(buffers[i]){ + std::size_t received_size; + std::size_t min_size = i+1; + std::size_t preferred_size = i*2; + preferred_size = min_size > preferred_size ? min_size : preferred_size; + + while(boost_cont_allocation_command + ( BOOST_CONTAINER_EXPAND_FWD, 1, min_size + , preferred_size, &received_size, (char*)buffers[i]).first){ + //Check received size is bigger than minimum + if(received_size < min_size){ + return false; + } + //Now, try to expand further + min_size = received_size+1; + preferred_size = min_size*2; + } + } + } + + //Now erase null values from the vector + buffers.erase(std::remove(buffers.begin(), buffers.end(), (void*)0) + ,buffers.end()); + + //Deallocate it in non sequential order + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated();//a.all_memory_deallocated() && a.check_sanity(); +} + +//This test allocates until there is no more memory +//and after that deallocates all except the last. +//If the allocation algorithm is a bottom-up algorithm +//the last buffer will be in the end of the segment. +//Then the test will start expanding backwards, until +//the buffer fills all the memory + +bool test_allocation_with_reuse() +{ + boost_cont_malloc_check(); + //We will repeat this test for different sized elements + for(int sizeof_object = 1; sizeof_object < 20; ++sizeof_object){ + std::vector buffers; + + //Allocate buffers with extra memory + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i*sizeof_object); + if(!ptr) + break; + buffers.push_back(ptr); + } + + //Now deallocate all except the latest + //Now try to expand to the double of the size + for(int i = 0, max = (int)buffers.size() - 1 + ;i < max + ;++i){ + boost_cont_free(buffers[i]); + } + + //Save the unique buffer and clear vector + void *ptr = buffers.back(); + buffers.clear(); + + //Now allocate with reuse + std::size_t received_size = 0; + for(int i = 0; i != NumIt; ++i){ + std::size_t min_size = (received_size/sizeof_object + 1)*sizeof_object; + std::size_t prf_size = (received_size/sizeof_object + (i+1)*2)*sizeof_object; + boost_cont_command_ret_t ret = boost_cont_allocation_command + ( BOOST_CONTAINER_EXPAND_BWD, sizeof_object, min_size + , prf_size, &received_size, (char*)ptr); + //If we have memory, this must be a buffer reuse + if(!ret.first) + break; + //If we have memory, this must be a buffer reuse + if(!ret.second) + return false; + if(received_size < min_size) + return false; + ptr = ret.first; + } + //There should be only a single block so deallocate it + boost_cont_free(ptr); + boost_cont_malloc_check(); + if(!boost_cont_all_deallocated()) + return false; + } + return true; +} + + +//This test allocates memory with different alignments +//and checks returned memory is aligned. + +bool test_aligned_allocation() +{ + boost_cont_malloc_check(); + //Allocate aligned buffers in a loop + //and then deallocate it + for(unsigned int i = 1; i != (1 << (sizeof(int)/2)); i <<= 1){ + for(unsigned int j = 1; j != 512; j <<= 1){ + void *ptr = boost_cont_memalign(i-1, j); + if(!ptr){ + return false; + } + + if(((std::size_t)ptr & (j - 1)) != 0) + return false; + boost_cont_free(ptr); + //if(!a.all_memory_deallocated() || !a.check_sanity()){ + // return false; + //} + } + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated();//a.all_memory_deallocated() && a.check_sanity(); +} + +//This test allocates memory with different alignments +//and checks returned memory is aligned. + +bool test_continuous_aligned_allocation() +{ + boost_cont_malloc_check(); + std::vector buffers; + //Allocate aligned buffers in a loop + //and then deallocate it + bool continue_loop = true; + unsigned int MaxAlign = 4096; + unsigned int MaxSize = 4096; + for(unsigned i = 1; i < MaxSize; i <<= 1){ + for(unsigned int j = 1; j < MaxAlign; j <<= 1){ + for(int k = 0; k != NumIt; ++k){ + void *ptr = boost_cont_memalign(i-1, j); + buffers.push_back(ptr); + if(!ptr){ + continue_loop = false; + break; + } + + if(((std::size_t)ptr & (j - 1)) != 0) + return false; + } + //Deallocate all + for(int k = (int)buffers.size(); k--;){ + boost_cont_free(buffers[k]); + } + buffers.clear(); + //if(!a.all_memory_deallocated() && a.check_sanity()) + // return false; + if(!continue_loop) + break; + } + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated();//a.all_memory_deallocated() && a.check_sanity(); +} + +//This test allocates multiple values until there is no more memory +//and after that deallocates all in the inverse order +bool test_many_equal_allocation() +{ + boost_cont_malloc_check(); + for( deallocation_type t = DirectDeallocation + ; t != EndDeallocationType + ; t = (deallocation_type)((int)t + 1)){ + //std::size_t free_memory = a.get_free_memory(); + + std::vector buffers2; + + //Allocate buffers with extra memory + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i); + if(!ptr) + break; + //if(!a.check_sanity()) + //return false; + buffers2.push_back(ptr); + } + + //Now deallocate the half of the blocks + //so expand maybe can merge new free blocks + for(int i = 0, max = (int)buffers2.size() + ;i < max + ;++i){ + if(i%2){ + boost_cont_free(buffers2[i]); + buffers2[i] = 0; + } + } + + //if(!a.check_sanity()) + //return false; + + std::vector buffers; + for(int i = 0; i != NumIt/10; ++i){ + boost_cont_memchain chain; + BOOST_CONTAINER_MEMCHAIN_INIT(&chain); + boost_cont_multialloc_nodes((i+1)*2, i+1, DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &chain); + boost_cont_memchain_it it = BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(&chain); + if(BOOST_CONTAINER_MEMCHAIN_IS_END_IT(chain, it)) + break; + + std::size_t n = 0; + for(; !BOOST_CONTAINER_MEMCHAIN_IS_END_IT(chain, it); ++n){ + buffers.push_back(BOOST_CONTAINER_MEMIT_ADDR(it)); + BOOST_CONTAINER_MEMIT_NEXT(it); + } + if(n != std::size_t((i+1)*2)) + return false; + } + + //if(!a.check_sanity()) + //return false; + + switch(t){ + case DirectDeallocation: + { + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + boost_cont_free(buffers[j]); + } + } + break; + case InverseDeallocation: + { + for(int j = (int)buffers.size() + ;j-- + ;){ + boost_cont_free(buffers[j]); + } + } + break; + case MixedDeallocation: + { + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + } + break; + default: + break; + } + + //Deallocate the rest of the blocks + + //Deallocate it in non sequential order + for(int j = 0, max = (int)buffers2.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers2.size())/4; + boost_cont_free(buffers2[pos]); + buffers2.erase(buffers2.begin()+pos); + } + + //bool ok = free_memory == a.get_free_memory() && + //a.all_memory_deallocated() && a.check_sanity(); + //if(!ok) return ok; + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated(); +} + +//This test allocates multiple values until there is no more memory +//and after that deallocates all in the inverse order + +bool test_many_different_allocation() +{ + boost_cont_malloc_check(); + const std::size_t ArraySize = 11; + std::size_t requested_sizes[ArraySize]; + for(std::size_t i = 0; i < ArraySize; ++i){ + requested_sizes[i] = 4*i; + } + + for( deallocation_type t = DirectDeallocation + ; t != EndDeallocationType + ; t = (deallocation_type)((int)t + 1)){ + //std::size_t free_memory = a.get_free_memory(); + + std::vector buffers2; + + //Allocate buffers with extra memory + for(int i = 0; i != NumIt; ++i){ + void *ptr = boost_cont_malloc(i); + if(!ptr) + break; + buffers2.push_back(ptr); + } + + //Now deallocate the half of the blocks + //so expand maybe can merge new free blocks + for(int i = 0, max = (int)buffers2.size() + ;i < max + ;++i){ + if(i%2){ + boost_cont_free(buffers2[i]); + buffers2[i] = 0; + } + } + + std::vector buffers; + for(int i = 0; i != NumIt; ++i){ + boost_cont_memchain chain; + BOOST_CONTAINER_MEMCHAIN_INIT(&chain); + boost_cont_multialloc_arrays(ArraySize, requested_sizes, 1, DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &chain); + boost_cont_memchain_it it = BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(&chain); + if(BOOST_CONTAINER_MEMCHAIN_IS_END_IT(chain, it)) + break; + std::size_t n = 0; + for(; !BOOST_CONTAINER_MEMCHAIN_IS_END_IT(chain, it); ++n){ + buffers.push_back(BOOST_CONTAINER_MEMIT_ADDR(it)); + BOOST_CONTAINER_MEMIT_NEXT(it); + } + if(n != ArraySize) + return false; + } + + switch(t){ + case DirectDeallocation: + { + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + boost_cont_free(buffers[j]); + } + } + break; + case InverseDeallocation: + { + for(int j = (int)buffers.size() + ;j-- + ;){ + boost_cont_free(buffers[j]); + } + } + break; + case MixedDeallocation: + { + for(int j = 0, max = (int)buffers.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers.size())/4; + boost_cont_free(buffers[pos]); + buffers.erase(buffers.begin()+pos); + } + } + break; + default: + break; + } + + //Deallocate the rest of the blocks + + //Deallocate it in non sequential order + for(int j = 0, max = (int)buffers2.size() + ;j < max + ;++j){ + int pos = (j%4)*((int)buffers2.size())/4; + boost_cont_free(buffers2[pos]); + buffers2.erase(buffers2.begin()+pos); + } + + //bool ok = free_memory == a.get_free_memory() && + //a.all_memory_deallocated() && a.check_sanity(); + //if(!ok) return ok; + } + boost_cont_malloc_check(); + return 0 != boost_cont_all_deallocated(); +} + +bool test_many_deallocation() +{ + const std::size_t ArraySize = 11; + std::vector buffers; + std::size_t requested_sizes[ArraySize]; + for(std::size_t i = 0; i < ArraySize; ++i){ + requested_sizes[i] = 4*i; + } + + for(int i = 0; i != NumIt; ++i){ + boost_cont_memchain chain; + BOOST_CONTAINER_MEMCHAIN_INIT(&chain); + boost_cont_multialloc_arrays(ArraySize, requested_sizes, 1, DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &chain); + boost_cont_memchain_it it = BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(&chain); + if(BOOST_CONTAINER_MEMCHAIN_IS_END_IT(chain, it)) + return false; + buffers.push_back(chain); + } + for(int i = 0; i != NumIt; ++i){ + boost_cont_multidealloc(&buffers[i]); + } + buffers.clear(); + + boost_cont_malloc_check(); + if(!boost_cont_all_deallocated()) + return false; + + for(int i = 0; i != NumIt; ++i){ + boost_cont_memchain chain; + BOOST_CONTAINER_MEMCHAIN_INIT(&chain); + boost_cont_multialloc_nodes(ArraySize, i*4+1, DL_MULTIALLOC_DEFAULT_CONTIGUOUS, &chain); + boost_cont_memchain_it it = BOOST_CONTAINER_MEMCHAIN_BEGIN_IT(&chain); + if(BOOST_CONTAINER_MEMCHAIN_IS_END_IT(chain, it)) + return false; + buffers.push_back(chain); + } + for(int i = 0; i != NumIt; ++i){ + boost_cont_multidealloc(&buffers[i]); + } + buffers.clear(); + + boost_cont_malloc_check(); + if(!boost_cont_all_deallocated()) + return false; + + return true; +} + +//This function calls all tests + +bool test_all_allocation() +{ + std::cout << "Starting test_allocation" + << std::endl; + + if(!test_allocation()){ + std::cout << "test_allocation_direct_deallocation failed" + << std::endl; + return false; + } + + std::cout << "Starting test_many_equal_allocation" + << std::endl; + + if(!test_many_equal_allocation()){ + std::cout << "test_many_equal_allocation failed" + << std::endl; + return false; + } + + std::cout << "Starting test_many_different_allocation" + << std::endl; + + if(!test_many_different_allocation()){ + std::cout << "test_many_different_allocation failed" + << std::endl; + return false; + } + + std::cout << "Starting test_allocation_shrink" + << std::endl; + + if(!test_allocation_shrink()){ + std::cout << "test_allocation_shrink failed" + << std::endl; + return false; + } + + if(!test_allocation_shrink_and_expand()){ + std::cout << "test_allocation_shrink_and_expand failed" + << std::endl; + return false; + } + + std::cout << "Starting test_allocation_expand" + << std::endl; + + if(!test_allocation_expand()){ + std::cout << "test_allocation_expand failed" + << std::endl; + return false; + } + + std::cout << "Starting test_allocation_deallocation_expand" + << std::endl; + + if(!test_allocation_deallocation_expand()){ + std::cout << "test_allocation_deallocation_expand failed" + << std::endl; + return false; + } + + std::cout << "Starting test_allocation_with_reuse" + << std::endl; + + if(!test_allocation_with_reuse()){ + std::cout << "test_allocation_with_reuse failed" + << std::endl; + return false; + } + + std::cout << "Starting test_aligned_allocation" + << std::endl; + + if(!test_aligned_allocation()){ + std::cout << "test_aligned_allocation failed" + << std::endl; + return false; + } + + std::cout << "Starting test_continuous_aligned_allocation" + << std::endl; + + if(!test_continuous_aligned_allocation()){ + std::cout << "test_continuous_aligned_allocation failed" + << std::endl; + return false; + } + + if(!test_many_deallocation()){ + std::cout << "test_many_deallocation failed" + << std::endl; + return false; + } + + return 0 != boost_cont_all_deallocated(); +} + +}}} //namespace boost { namespace container { namespace test { + + +int main() +{ + if(!boost::container::test::test_all_allocation()) + return 1; + return 0; +} diff --git a/test/allocator_traits_test.cpp b/test/allocator_traits_test.cpp index 119ec72..ac6a1a1 100644 --- a/test/allocator_traits_test.cpp +++ b/test/allocator_traits_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/test/check_equal_containers.hpp b/test/check_equal_containers.hpp index d2cd6b6..b5b2a2f 100644 --- a/test/check_equal_containers.hpp +++ b/test/check_equal_containers.hpp @@ -30,6 +30,23 @@ bool CheckEqual( const T1 &t1, const T2 &t2 >::type* = 0) { return t1 == t2; } + +template +bool CheckEqualIt( const T1 &i1, const T2 &i2, const C1 &c1, const C2 &c2 ) +{ + bool c1end = i1 == c1.end(); + bool c2end = i2 == c2.end(); + if( c1end != c2end ){ + return false; + } + else if(c1end){ + return true; + } + else{ + return CheckEqual(*i1, *i2); + } +} + template< class Pair1, class Pair2> bool CheckEqual( const Pair1 &pair1, const Pair2 &pair2 , typename boost::container::container_detail::enable_if_c diff --git a/test/default_init_test.hpp b/test/default_init_test.hpp new file mode 100644 index 0000000..121f7a4 --- /dev/null +++ b/test/default_init_test.hpp @@ -0,0 +1,164 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2013-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#ifndef BOOST_CONTAINER_TEST_DEFAULT_INIT_TEST_HEADER +#define BOOST_CONTAINER_TEST_DEFAULT_INIT_TEST_HEADER + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "print_container.hpp" +#include "check_equal_containers.hpp" +#include "movable_int.hpp" +#include +#include +#include "emplace_test.hpp" +#include "input_from_forward_iterator.hpp" +#include +#include +#include +#include +#include "insert_test.hpp" + +namespace boost{ +namespace container { +namespace test{ + +// +template +class default_init_allocator_base +{ + protected: + static unsigned char s_pattern; + static bool s_ascending; + + public: + static void reset_pattern(unsigned char value) + { s_pattern = value; } + + static void set_ascending(bool enable) + { s_ascending = enable; } +}; + +template +unsigned char default_init_allocator_base::s_pattern = 0u; + +template +bool default_init_allocator_base::s_ascending = true; + +template +class default_init_allocator + : public default_init_allocator_base<0> +{ + typedef default_init_allocator_base<0> base_t; + public: + typedef Integral value_type; + + default_init_allocator() + {} + + template + default_init_allocator(default_init_allocator) + {} + + Integral* allocate(std::size_t n) + { + //Initialize memory to a pattern + const std::size_t max = sizeof(Integral)*n; + unsigned char *puc_raw = ::new unsigned char[max]; + + if(base_t::s_ascending){ + for(std::size_t i = 0; i != max; ++i){ + puc_raw[i] = static_cast(s_pattern++); + } + } + else{ + for(std::size_t i = 0; i != max; ++i){ + puc_raw[i] = static_cast(s_pattern--); + } + } + return (Integral*)puc_raw;; + } + + void deallocate(Integral *p, std::size_t) + { delete[] (unsigned char*)p; } +}; + +template +inline bool check_ascending_byte_pattern(const Integral&t) +{ + const unsigned char *pch = &reinterpret_cast(t); + const std::size_t max = sizeof(Integral); + for(std::size_t i = 1; i != max; ++i){ + if( (pch[i-1] != ((unsigned char)(pch[i]-1u))) ){ + return false; + } + } + return true; +} + +template +inline bool check_descending_byte_pattern(const Integral&t) +{ + const unsigned char *pch = &reinterpret_cast(t); + const std::size_t max = sizeof(Integral); + for(std::size_t i = 1; i != max; ++i){ + if( (pch[i-1] != ((unsigned char)(pch[i]+1u))) ){ + return false; + } + } + return true; +} + +template +bool default_init_test()//Test for default initialization +{ + const std::size_t Capacity = 100; + + { + test::default_init_allocator::reset_pattern(0); + test::default_init_allocator::set_ascending(true); + IntDefaultInitAllocVector v(Capacity, default_init); + typename IntDefaultInitAllocVector::iterator it = v.begin(); + //Compare with the pattern + for(std::size_t i = 0; i != Capacity; ++i, ++it){ + if(!test::check_ascending_byte_pattern(*it)) + return false; + } + } + { + test::default_init_allocator::reset_pattern(100); + test::default_init_allocator::set_ascending(false); + IntDefaultInitAllocVector v; + v.resize(Capacity, default_init); + typename IntDefaultInitAllocVector::iterator it = v.begin(); + //Compare with the pattern + for(std::size_t i = 0; i != Capacity; ++i, ++it){ + if(!test::check_descending_byte_pattern(*it)) + return false; + } + } + return true; +} + +} //namespace test{ +} //namespace container { +} //namespace boost{ + +#include + +#endif //BOOST_CONTAINER_TEST_DEFAULT_INIT_TEST_HEADER diff --git a/test/deque_test.cpp b/test/deque_test.cpp index f483fd6..871dbd6 100644 --- a/test/deque_test.cpp +++ b/test/deque_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -17,6 +17,10 @@ #include #include +#include +#include +#include + #include "print_container.hpp" #include "check_equal_containers.hpp" #include "dummy_test_allocator.hpp" @@ -29,6 +33,7 @@ #include "emplace_test.hpp" #include "propagate_allocator_test.hpp" #include "vector_test.hpp" +#include "default_init_test.hpp" #include using namespace boost::container; @@ -49,6 +54,18 @@ template class boost::container::deque < test::movable_and_copyable_int , std::allocator >; +template class boost::container::deque + < test::movable_and_copyable_int + , allocator >; + +template class boost::container::deque + < test::movable_and_copyable_int + , adaptive_pool >; + +template class boost::container::deque + < test::movable_and_copyable_int + , node_allocator >; + }} //Function to check if both sets are equal @@ -145,11 +162,8 @@ bool do_test() typedef std::deque MyStdDeque; const int max = 100; BOOST_TRY{ - //Shared memory allocator must be always be initialized - //since it has no default constructor MyCntDeque *cntdeque = new MyCntDeque; MyStdDeque *stddeque = new MyStdDeque; - //Compare several shared memory deque operations with std::deque for(int i = 0; i < max*100; ++i){ IntType move_me(i); cntdeque->insert(cntdeque->end(), boost::move(move_me)); @@ -295,6 +309,38 @@ bool do_test() return true; } +template +struct GetAllocatorCont +{ + template + struct apply + { + typedef deque< ValueType + , typename allocator_traits + ::template portable_rebind_alloc::type + > type; + }; +}; + +template +int test_cont_variants() +{ + typedef typename GetAllocatorCont::template apply::type MyCont; + typedef typename GetAllocatorCont::template apply::type MyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyCont; + + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + return 0; +} + int main () { @@ -319,31 +365,48 @@ int main () d.resize(1); } - { - typedef deque MyDeque; - typedef deque MyMoveDeque; - typedef deque MyCopyMoveDeque; - typedef deque MyCopyDeque; - if(test::vector_test()) - return 1; - if(test::vector_test()) - return 1; - if(test::vector_test()) - return 1; - if(test::vector_test()) - return 1; - if(!test::default_init_test< deque > >()){ - std::cerr << "Default init test failed" << std::endl; - return 1; - } + //////////////////////////////////// + // Allocator implementations + //////////////////////////////////// + // std:allocator + if(test_cont_variants< std::allocator >()){ + std::cerr << "test_cont_variants< std::allocator > failed" << std::endl; + return 1; + } + // boost::container::allocator + if(test_cont_variants< allocator >()){ + std::cerr << "test_cont_variants< allocator > failed" << std::endl; + return 1; + } + // boost::container::node_allocator + if(test_cont_variants< node_allocator >()){ + std::cerr << "test_cont_variants< node_allocator > failed" << std::endl; + return 1; + } + // boost::container::adaptive_pool + if(test_cont_variants< adaptive_pool >()){ + std::cerr << "test_cont_variants< adaptive_pool > failed" << std::endl; + return 1; + } + //////////////////////////////////// + // Default init test + //////////////////////////////////// + if(!test::default_init_test< deque > >()){ + std::cerr << "Default init test failed" << std::endl; + return 1; } + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// const test::EmplaceOptions Options = (test::EmplaceOptions)(test::EMPLACE_BACK | test::EMPLACE_FRONT | test::EMPLACE_BEFORE); if(!boost::container::test::test_emplace < deque, Options>()) return 1; - + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// if(!boost::container::test::test_propagate_allocator()) return 1; diff --git a/test/dummy_test_allocator.hpp b/test/dummy_test_allocator.hpp index 29feec3..dd4872a 100644 --- a/test/dummy_test_allocator.hpp +++ b/test/dummy_test_allocator.hpp @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,7 +11,7 @@ #ifndef BOOST_CONTAINER_DUMMY_TEST_ALLOCATOR_HPP #define BOOST_CONTAINER_DUMMY_TEST_ALLOCATOR_HPP -#if (defined _MSC_VER) +#if defined(_MSC_VER) # pragma once #endif @@ -33,9 +33,6 @@ #include #include -//!\file -//!Describes an allocator to test expand capabilities - namespace boost { namespace container { namespace test { diff --git a/test/expand_bwd_test_allocator.hpp b/test/expand_bwd_test_allocator.hpp index 1bd375a..745fc53 100644 --- a/test/expand_bwd_test_allocator.hpp +++ b/test/expand_bwd_test_allocator.hpp @@ -1,6 +1,6 @@ /////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2005-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -11,7 +11,7 @@ #ifndef BOOST_CONTAINER_EXPAND_BWD_TEST_ALLOCATOR_HPP #define BOOST_CONTAINER_EXPAND_BWD_TEST_ALLOCATOR_HPP -#if (defined _MSC_VER) +#if defined(_MSC_VER) # pragma once #endif @@ -29,9 +29,6 @@ #include #include -//!\file -//!Describes an allocator to test expand capabilities - namespace boost { namespace container { namespace test { diff --git a/test/expand_bwd_test_template.hpp b/test/expand_bwd_test_template.hpp index 7014466..98c30f0 100644 --- a/test/expand_bwd_test_template.hpp +++ b/test/expand_bwd_test_template.hpp @@ -187,8 +187,8 @@ bool test_assign_with_expand_bwd() const int Offset[] = { 50, 50, 50}; const int InitialSize[] = { 25, 25, 25}; - const int AssignSize[] = { 40, 60, 80}; - const int Iterations = sizeof(AssignSize)/sizeof(int); + const int InsertSize[] = { 15, 35, 55}; + const int Iterations = sizeof(InsertSize)/sizeof(int); for(int iteration = 0; iteration data_to_assign; - data_to_assign.resize(AssignSize[iteration]); - for(int i = 0; i < AssignSize[iteration]; ++i){ - data_to_assign[i] = -i; + std::vector data_to_insert; + data_to_insert.resize(InsertSize[iteration]); + for(int i = 0; i < InsertSize[iteration]; ++i){ + data_to_insert[i] = -i; } //Insert initial data to the vector to test @@ -216,8 +216,8 @@ bool test_assign_with_expand_bwd() , initial_data.begin(), initial_data.end()); //Assign data - vector.assign(data_to_assign.begin(), data_to_assign.end()); - initial_data.assign(data_to_assign.begin(), data_to_assign.end()); + vector.insert(vector.cbegin(), data_to_insert.begin(), data_to_insert.end()); + initial_data.insert(initial_data.begin(), data_to_insert.begin(), data_to_insert.end()); //Now check that values are equal if(!CheckEqualVector(vector, initial_data)){ diff --git a/test/flat_map_test.cpp b/test/flat_map_test.cpp new file mode 100644 index 0000000..a2feb0e --- /dev/null +++ b/test/flat_map_test.cpp @@ -0,0 +1,459 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include + +#include "print_container.hpp" +#include "dummy_test_allocator.hpp" +#include "movable_int.hpp" +#include "map_test.hpp" +#include "propagate_allocator_test.hpp" +#include "emplace_test.hpp" +#include +#include + +using namespace boost::container; + +namespace boost { +namespace container { + +//Explicit instantiation to detect compilation errors + +//flat_map +template class flat_map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + < std::pair > + >; + +template class flat_map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::simple_allocator + < std::pair > + >; + +template class flat_map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , std::allocator + < std::pair > + >; + +template class flat_map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , allocator + < std::pair > + >; + +template class flat_map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , adaptive_pool + < std::pair > + >; + +template class flat_map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , node_allocator + < std::pair > + >; + +//flat_multimap +template class flat_multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + < std::pair > + >; + +template class flat_multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::simple_allocator + < std::pair > + >; + +template class flat_multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , std::allocator + < std::pair > + >; + +template class flat_multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , allocator + < std::pair > + >; + +template class flat_multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , adaptive_pool + < std::pair > + >; + +template class flat_multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , node_allocator + < std::pair > + >; + +//As flat container iterators are typedefs for vector::[const_]iterator, +//no need to explicit instantiate them + +}} //boost::container + + +class recursive_flat_map +{ + public: + recursive_flat_map(const recursive_flat_map &c) + : id_(c.id_), map_(c.map_) + {} + + recursive_flat_map & operator =(const recursive_flat_map &c) + { + id_ = c.id_; + map_= c.map_; + return *this; + } + + int id_; + flat_map map_; + + friend bool operator< (const recursive_flat_map &a, const recursive_flat_map &b) + { return a.id_ < b.id_; } +}; + + +class recursive_flat_multimap +{ +public: + recursive_flat_multimap(const recursive_flat_multimap &c) + : id_(c.id_), map_(c.map_) + {} + + recursive_flat_multimap & operator =(const recursive_flat_multimap &c) + { + id_ = c.id_; + map_= c.map_; + return *this; + } + int id_; + flat_map map_; + friend bool operator< (const recursive_flat_multimap &a, const recursive_flat_multimap &b) + { return a.id_ < b.id_; } +}; + +template +void test_move() +{ + //Now test move semantics + C original; + C move_ctor(boost::move(original)); + C move_assign; + move_assign = boost::move(move_ctor); + move_assign.swap(original); +} + +template +class flat_map_propagate_test_wrapper + : public boost::container::flat_map + < T, T, std::less + , typename boost::container::allocator_traits
::template + portable_rebind_alloc< std::pair >::type> +{ + BOOST_COPYABLE_AND_MOVABLE(flat_map_propagate_test_wrapper) + typedef boost::container::flat_map + < T, T, std::less + , typename boost::container::allocator_traits::template + portable_rebind_alloc< std::pair >::type> Base; + public: + flat_map_propagate_test_wrapper() + : Base() + {} + + flat_map_propagate_test_wrapper(const flat_map_propagate_test_wrapper &x) + : Base(x) + {} + + flat_map_propagate_test_wrapper(BOOST_RV_REF(flat_map_propagate_test_wrapper) x) + : Base(boost::move(static_cast(x))) + {} + + flat_map_propagate_test_wrapper &operator=(BOOST_COPY_ASSIGN_REF(flat_map_propagate_test_wrapper) x) + { this->Base::operator=(x); return *this; } + + flat_map_propagate_test_wrapper &operator=(BOOST_RV_REF(flat_map_propagate_test_wrapper) x) + { this->Base::operator=(boost::move(static_cast(x))); return *this; } + + void swap(flat_map_propagate_test_wrapper &x) + { this->Base::swap(x); } +}; + +namespace boost{ +namespace container { +namespace test{ + +bool flat_tree_ordered_insertion_test() +{ + using namespace boost::container; + const std::size_t NumElements = 100; + + //Ordered insertion multimap + { + std::multimap int_mmap; + for(std::size_t i = 0; i != NumElements; ++i){ + int_mmap.insert(std::multimap::value_type(static_cast(i), static_cast(i))); + } + //Construction insertion + flat_multimap fmmap(ordered_range, int_mmap.begin(), int_mmap.end()); + if(!CheckEqualContainers(&int_mmap, &fmmap)) + return false; + //Insertion when empty + fmmap.clear(); + fmmap.insert(ordered_range, int_mmap.begin(), int_mmap.end()); + if(!CheckEqualContainers(&int_mmap, &fmmap)) + return false; + //Re-insertion + fmmap.insert(ordered_range, int_mmap.begin(), int_mmap.end()); + std::multimap int_mmap2(int_mmap); + int_mmap2.insert(int_mmap.begin(), int_mmap.end()); + if(!CheckEqualContainers(&int_mmap2, &fmmap)) + return false; + //Re-re-insertion + fmmap.insert(ordered_range, int_mmap2.begin(), int_mmap2.end()); + std::multimap int_mmap4(int_mmap2); + int_mmap4.insert(int_mmap2.begin(), int_mmap2.end()); + if(!CheckEqualContainers(&int_mmap4, &fmmap)) + return false; + //Re-re-insertion of even + std::multimap int_even_mmap; + for(std::size_t i = 0; i < NumElements; i+=2){ + int_mmap.insert(std::multimap::value_type(static_cast(i), static_cast(i))); + } + fmmap.insert(ordered_range, int_even_mmap.begin(), int_even_mmap.end()); + int_mmap4.insert(int_even_mmap.begin(), int_even_mmap.end()); + if(!CheckEqualContainers(&int_mmap4, &fmmap)) + return false; + } + + //Ordered insertion map + { + std::map int_map; + for(std::size_t i = 0; i != NumElements; ++i){ + int_map.insert(std::map::value_type(static_cast(i), static_cast(i))); + } + //Construction insertion + flat_map fmap(ordered_unique_range, int_map.begin(), int_map.end()); + if(!CheckEqualContainers(&int_map, &fmap)) + return false; + //Insertion when empty + fmap.clear(); + fmap.insert(ordered_unique_range, int_map.begin(), int_map.end()); + if(!CheckEqualContainers(&int_map, &fmap)) + return false; + //Re-insertion + fmap.insert(ordered_unique_range, int_map.begin(), int_map.end()); + std::map int_map2(int_map); + int_map2.insert(int_map.begin(), int_map.end()); + if(!CheckEqualContainers(&int_map2, &fmap)) + return false; + //Re-re-insertion + fmap.insert(ordered_unique_range, int_map2.begin(), int_map2.end()); + std::map int_map4(int_map2); + int_map4.insert(int_map2.begin(), int_map2.end()); + if(!CheckEqualContainers(&int_map4, &fmap)) + return false; + //Re-re-insertion of even + std::map int_even_map; + for(std::size_t i = 0; i < NumElements; i+=2){ + int_map.insert(std::map::value_type(static_cast(i), static_cast(i))); + } + fmap.insert(ordered_unique_range, int_even_map.begin(), int_even_map.end()); + int_map4.insert(int_even_map.begin(), int_even_map.end()); + if(!CheckEqualContainers(&int_map4, &fmap)) + return false; + } + + return true; +} + +}}} + + +template +struct GetAllocatorMap +{ + template + struct apply + { + typedef flat_map< ValueType + , ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc< std::pair >::type + > map_type; + + typedef flat_multimap< ValueType + , ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc< std::pair >::type + > multimap_type; + }; +}; + +template +int test_map_variants() +{ + typedef typename GetAllocatorMap::template apply::map_type MyMap; + typedef typename GetAllocatorMap::template apply::map_type MyMoveMap; + typedef typename GetAllocatorMap::template apply::map_type MyCopyMoveMap; + typedef typename GetAllocatorMap::template apply::map_type MyCopyMap; + + typedef typename GetAllocatorMap::template apply::multimap_type MyMultiMap; + typedef typename GetAllocatorMap::template apply::multimap_type MyMoveMultiMap; + typedef typename GetAllocatorMap::template apply::multimap_type MyCopyMoveMultiMap; + typedef typename GetAllocatorMap::template apply::multimap_type MyCopyMultiMap; + + typedef std::map MyStdMap; + typedef std::multimap MyStdMultiMap; + + if (0 != test::map_test< + MyMap + ,MyStdMap + ,MyMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + if (0 != test::map_test< + MyMoveMap + ,MyStdMap + ,MyMoveMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + if (0 != test::map_test< + MyCopyMoveMap + ,MyStdMap + ,MyCopyMoveMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + if (0 != test::map_test< + MyCopyMap + ,MyStdMap + ,MyCopyMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + return 0; +} + + +int main() +{ + using namespace boost::container::test; + + //Allocator argument container + { + flat_map map_((std::allocator >())); + flat_multimap multimap_((std::allocator >())); + } + //Now test move semantics + { + test_move >(); + test_move >(); + } + + //////////////////////////////////// + // Ordered insertion test + //////////////////////////////////// + if(!flat_tree_ordered_insertion_test()){ + return 1; + } + + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std::allocator + if(test_map_variants< std::allocator >()){ + std::cerr << "test_map_variants< std::allocator > failed" << std::endl; + return 1; + } + // boost::container::allocator + if(test_map_variants< allocator >()){ + std::cerr << "test_map_variants< allocator > failed" << std::endl; + return 1; + } + // boost::container::node_allocator + if(test_map_variants< node_allocator >()){ + std::cerr << "test_map_variants< node_allocator > failed" << std::endl; + return 1; + } + // boost::container::adaptive_pool + if(test_map_variants< adaptive_pool >()){ + std::cerr << "test_map_variants< adaptive_pool > failed" << std::endl; + return 1; + } + + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// + const test::EmplaceOptions MapOptions = (test::EmplaceOptions)(test::EMPLACE_HINT_PAIR | test::EMPLACE_ASSOC_PAIR); + + if(!boost::container::test::test_emplace, MapOptions>()) + return 1; + if(!boost::container::test::test_emplace, MapOptions>()) + return 1; + + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// + if(!boost::container::test::test_propagate_allocator()) + return 1; + + return 0; +} + +#include + diff --git a/test/flat_set_test.cpp b/test/flat_set_test.cpp new file mode 100644 index 0000000..541fb27 --- /dev/null +++ b/test/flat_set_test.cpp @@ -0,0 +1,481 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include + +#include "print_container.hpp" +#include "dummy_test_allocator.hpp" +#include "movable_int.hpp" +#include "set_test.hpp" +#include "propagate_allocator_test.hpp" +#include "emplace_test.hpp" +#include +#include + +using namespace boost::container; + +namespace boost { +namespace container { + +//Explicit instantiation to detect compilation errors + +//flat_set +template class flat_set + < test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + >; + +template class flat_set + < test::movable_and_copyable_int + , std::less + , test::simple_allocator + >; + +template class flat_set + < test::movable_and_copyable_int + , std::less + , std::allocator + >; + +template class flat_set + < test::movable_and_copyable_int + , std::less + , allocator + >; + +template class flat_set + < test::movable_and_copyable_int + , std::less + , adaptive_pool + >; + +template class flat_set + < test::movable_and_copyable_int + , std::less + , node_allocator + >; + +//flat_multiset +template class flat_multiset + < test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + >; + +template class flat_multiset + < test::movable_and_copyable_int + , std::less + , test::simple_allocator + >; + +template class flat_multiset + < test::movable_and_copyable_int + , std::less + , std::allocator + >; + +template class flat_multiset + < test::movable_and_copyable_int + , std::less + , allocator + >; + +template class flat_multiset + < test::movable_and_copyable_int + , std::less + , adaptive_pool + >; + +template class flat_multiset + < test::movable_and_copyable_int + , std::less + , node_allocator + >; + +namespace container_detail { + +//Instantiate base class as previous instantiations don't instantiate inherited members +template class flat_tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , test::dummy_test_allocator + >; + +template class flat_tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , test::simple_allocator + >; + +template class flat_tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , std::allocator + >; + +template class flat_tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , allocator + >; + +template class flat_tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , adaptive_pool + >; + +template class flat_tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , node_allocator + >; + +} //container_detail { + +//As flat container iterators are typedefs for vector::[const_]iterator, +//no need to explicit instantiate them + +}} //boost::container + +//Test recursive structures +class recursive_flat_set +{ + public: + recursive_flat_set(const recursive_flat_set &c) + : id_(c.id_), flat_set_(c.flat_set_) + {} + + recursive_flat_set & operator =(const recursive_flat_set &c) + { + id_ = c.id_; + flat_set_= c.flat_set_; + return *this; + } + int id_; + flat_set flat_set_; + friend bool operator< (const recursive_flat_set &a, const recursive_flat_set &b) + { return a.id_ < b.id_; } +}; + + +//Test recursive structures +class recursive_flat_multiset +{ + public: + recursive_flat_multiset(const recursive_flat_multiset &c) + : id_(c.id_), flat_multiset_(c.flat_multiset_) + {} + + recursive_flat_multiset & operator =(const recursive_flat_multiset &c) + { + id_ = c.id_; + flat_multiset_= c.flat_multiset_; + return *this; + } + int id_; + flat_multiset flat_multiset_; + friend bool operator< (const recursive_flat_multiset &a, const recursive_flat_multiset &b) + { return a.id_ < b.id_; } +}; + + +template +void test_move() +{ + //Now test move semantics + C original; + C move_ctor(boost::move(original)); + C move_assign; + move_assign = boost::move(move_ctor); + move_assign.swap(original); +} + +template +class flat_set_propagate_test_wrapper + : public boost::container::flat_set, A> +{ + BOOST_COPYABLE_AND_MOVABLE(flat_set_propagate_test_wrapper) + typedef boost::container::flat_set, A> Base; + public: + flat_set_propagate_test_wrapper() + : Base() + {} + + flat_set_propagate_test_wrapper(const flat_set_propagate_test_wrapper &x) + : Base(x) + {} + + flat_set_propagate_test_wrapper(BOOST_RV_REF(flat_set_propagate_test_wrapper) x) + : Base(boost::move(static_cast(x))) + {} + + flat_set_propagate_test_wrapper &operator=(BOOST_COPY_ASSIGN_REF(flat_set_propagate_test_wrapper) x) + { this->Base::operator=(x); return *this; } + + flat_set_propagate_test_wrapper &operator=(BOOST_RV_REF(flat_set_propagate_test_wrapper) x) + { this->Base::operator=(boost::move(static_cast(x))); return *this; } + + void swap(flat_set_propagate_test_wrapper &x) + { this->Base::swap(x); } +}; + +namespace boost{ +namespace container { +namespace test{ + +bool flat_tree_ordered_insertion_test() +{ + using namespace boost::container; + const std::size_t NumElements = 100; + + //Ordered insertion multiset + { + std::multiset int_mset; + for(std::size_t i = 0; i != NumElements; ++i){ + int_mset.insert(static_cast(i)); + } + //Construction insertion + flat_multiset fmset(ordered_range, int_mset.begin(), int_mset.end()); + if(!CheckEqualContainers(&int_mset, &fmset)) + return false; + //Insertion when empty + fmset.clear(); + fmset.insert(ordered_range, int_mset.begin(), int_mset.end()); + if(!CheckEqualContainers(&int_mset, &fmset)) + return false; + //Re-insertion + fmset.insert(ordered_range, int_mset.begin(), int_mset.end()); + std::multiset int_mset2(int_mset); + int_mset2.insert(int_mset.begin(), int_mset.end()); + if(!CheckEqualContainers(&int_mset2, &fmset)) + return false; + //Re-re-insertion + fmset.insert(ordered_range, int_mset2.begin(), int_mset2.end()); + std::multiset int_mset4(int_mset2); + int_mset4.insert(int_mset2.begin(), int_mset2.end()); + if(!CheckEqualContainers(&int_mset4, &fmset)) + return false; + //Re-re-insertion of even + std::multiset int_even_mset; + for(std::size_t i = 0; i < NumElements; i+=2){ + int_mset.insert(static_cast(i)); + } + fmset.insert(ordered_range, int_even_mset.begin(), int_even_mset.end()); + int_mset4.insert(int_even_mset.begin(), int_even_mset.end()); + if(!CheckEqualContainers(&int_mset4, &fmset)) + return false; + } + + //Ordered insertion set + { + std::set int_set; + for(std::size_t i = 0; i != NumElements; ++i){ + int_set.insert(static_cast(i)); + } + //Construction insertion + flat_set fset(ordered_unique_range, int_set.begin(), int_set.end()); + if(!CheckEqualContainers(&int_set, &fset)) + return false; + //Insertion when empty + fset.clear(); + fset.insert(ordered_unique_range, int_set.begin(), int_set.end()); + if(!CheckEqualContainers(&int_set, &fset)) + return false; + //Re-insertion + fset.insert(ordered_unique_range, int_set.begin(), int_set.end()); + std::set int_set2(int_set); + int_set2.insert(int_set.begin(), int_set.end()); + if(!CheckEqualContainers(&int_set2, &fset)) + return false; + //Re-re-insertion + fset.insert(ordered_unique_range, int_set2.begin(), int_set2.end()); + std::set int_set4(int_set2); + int_set4.insert(int_set2.begin(), int_set2.end()); + if(!CheckEqualContainers(&int_set4, &fset)) + return false; + //Re-re-insertion of even + std::set int_even_set; + for(std::size_t i = 0; i < NumElements; i+=2){ + int_set.insert(static_cast(i)); + } + fset.insert(ordered_unique_range, int_even_set.begin(), int_even_set.end()); + int_set4.insert(int_even_set.begin(), int_even_set.end()); + if(!CheckEqualContainers(&int_set4, &fset)) + return false; + } + + return true; +} + +}}} + + +template +struct GetAllocatorSet +{ + template + struct apply + { + typedef flat_set < ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc::type + > set_type; + + typedef flat_multiset < ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc::type + > multiset_type; + }; +}; + +template +int test_set_variants() +{ + typedef typename GetAllocatorSet::template apply::set_type MySet; + typedef typename GetAllocatorSet::template apply::set_type MyMoveSet; + typedef typename GetAllocatorSet::template apply::set_type MyCopyMoveSet; + typedef typename GetAllocatorSet::template apply::set_type MyCopySet; + + typedef typename GetAllocatorSet::template apply::multiset_type MyMultiSet; + typedef typename GetAllocatorSet::template apply::multiset_type MyMoveMultiSet; + typedef typename GetAllocatorSet::template apply::multiset_type MyCopyMoveMultiSet; + typedef typename GetAllocatorSet::template apply::multiset_type MyCopyMultiSet; + + typedef std::set MyStdSet; + typedef std::multiset MyStdMultiSet; + + if (0 != test::set_test< + MySet + ,MyStdSet + ,MyMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + if (0 != test::set_test< + MyMoveSet + ,MyStdSet + ,MyMoveMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + if (0 != test::set_test< + MyCopyMoveSet + ,MyStdSet + ,MyCopyMoveMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + if (0 != test::set_test< + MyCopySet + ,MyStdSet + ,MyCopyMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + return 0; +} + + +int main() +{ + using namespace boost::container::test; + + //Allocator argument container + { + flat_set set_((std::allocator())); + flat_multiset multiset_((std::allocator())); + } + //Now test move semantics + { + test_move >(); + test_move >(); + } + + //////////////////////////////////// + // Ordered insertion test + //////////////////////////////////// + if(!flat_tree_ordered_insertion_test()){ + return 1; + } + + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std::allocator + if(test_set_variants< std::allocator >()){ + std::cerr << "test_set_variants< std::allocator > failed" << std::endl; + return 1; + } + // boost::container::allocator + if(test_set_variants< allocator >()){ + std::cerr << "test_set_variants< allocator > failed" << std::endl; + return 1; + } + // boost::container::node_allocator + if(test_set_variants< node_allocator >()){ + std::cerr << "test_set_variants< node_allocator > failed" << std::endl; + return 1; + } + // boost::container::adaptive_pool + if(test_set_variants< adaptive_pool >()){ + std::cerr << "test_set_variants< adaptive_pool > failed" << std::endl; + return 1; + } + + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// + const test::EmplaceOptions SetOptions = (test::EmplaceOptions)(test::EMPLACE_HINT | test::EMPLACE_ASSOC); + + if(!boost::container::test::test_emplace, SetOptions>()) + return 1; + if(!boost::container::test::test_emplace, SetOptions>()) + return 1; + + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// + if(!boost::container::test::test_propagate_allocator()) + return 1; + + return 0; +} + +#include + diff --git a/test/flat_tree_test.cpp b/test/flat_tree_test.cpp deleted file mode 100644 index aac8a27..0000000 --- a/test/flat_tree_test.cpp +++ /dev/null @@ -1,640 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// - -#include -#include -#include -#include -#include "print_container.hpp" -#include "dummy_test_allocator.hpp" -#include "movable_int.hpp" -#include "set_test.hpp" -#include "map_test.hpp" -#include "propagate_allocator_test.hpp" -#include "emplace_test.hpp" -#include -#include - -using namespace boost::container; - -namespace boost { -namespace container { - -//Explicit instantiation to detect compilation errors - -//flat_map -template class flat_map - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - < std::pair > - >; - -template class flat_map - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::simple_allocator - < std::pair > - >; - -template class flat_map - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , std::allocator - < std::pair > - >; - -//flat_multimap -template class flat_multimap - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - < std::pair > - >; - -template class flat_multimap - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::simple_allocator - < std::pair > - >; - -template class flat_multimap - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , std::allocator - < std::pair > - >; -//flat_set -template class flat_set - < test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - >; - -template class flat_set - < test::movable_and_copyable_int - , std::less - , test::simple_allocator - >; - -template class flat_set - < test::movable_and_copyable_int - , std::less - , std::allocator - >; - -//flat_multiset -template class flat_multiset - < test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - >; - -template class flat_multiset - < test::movable_and_copyable_int - , std::less - , test::simple_allocator - >; - -template class flat_multiset - < test::movable_and_copyable_int - , std::less - , std::allocator - >; - -//As flat container iterators are typedefs for vector::[const_]iterator, -//no need to explicit instantiate them - -}} //boost::container - - -//Alias allocator type -typedef std::allocator allocator_t; -typedef std::allocator - movable_allocator_t; -typedef std::allocator > - pair_allocator_t; -typedef std::allocator > - movable_pair_allocator_t; -typedef std::allocator - move_copy_allocator_t; -typedef std::allocator > - move_copy_pair_allocator_t; -typedef std::allocator - copy_allocator_t; -typedef std::allocator > - copy_pair_allocator_t; - - -//Alias set types -typedef std::set MyStdSet; -typedef std::multiset MyStdMultiSet; -typedef std::map MyStdMap; -typedef std::multimap MyStdMultiMap; - -typedef flat_set, allocator_t> MyBoostSet; -typedef flat_multiset, allocator_t> MyBoostMultiSet; -typedef flat_map, pair_allocator_t> MyBoostMap; -typedef flat_multimap, pair_allocator_t> MyBoostMultiMap; - -typedef flat_set - ,movable_allocator_t> MyMovableBoostSet; -typedef flat_multiset - ,movable_allocator_t> MyMovableBoostMultiSet; -typedef flat_map - ,movable_pair_allocator_t> MyMovableBoostMap; -typedef flat_multimap - ,movable_pair_allocator_t> MyMovableBoostMultiMap; - -typedef flat_set - ,move_copy_allocator_t> MyMoveCopyBoostSet; -typedef flat_multiset - ,move_copy_allocator_t> MyMoveCopyBoostMultiSet; -typedef flat_map - ,move_copy_pair_allocator_t> MyMoveCopyBoostMap; -typedef flat_multimap - ,move_copy_pair_allocator_t> MyMoveCopyBoostMultiMap; - -typedef flat_set - ,copy_allocator_t> MyCopyBoostSet; -typedef flat_multiset - ,copy_allocator_t> MyCopyBoostMultiSet; -typedef flat_map - ,copy_pair_allocator_t> MyCopyBoostMap; -typedef flat_multimap - ,copy_pair_allocator_t> MyCopyBoostMultiMap; - - -//Test recursive structures -class recursive_flat_set -{ - public: - recursive_flat_set(const recursive_flat_set &c) - : id_(c.id_), flat_set_(c.flat_set_) - {} - - recursive_flat_set & operator =(const recursive_flat_set &c) - { - id_ = c.id_; - flat_set_= c.flat_set_; - return *this; - } - int id_; - flat_set flat_set_; - friend bool operator< (const recursive_flat_set &a, const recursive_flat_set &b) - { return a.id_ < b.id_; } -}; - - - -class recursive_flat_map -{ - public: - recursive_flat_map(const recursive_flat_map &c) - : id_(c.id_), map_(c.map_) - {} - - recursive_flat_map & operator =(const recursive_flat_map &c) - { - id_ = c.id_; - map_= c.map_; - return *this; - } - - int id_; - flat_map map_; - - friend bool operator< (const recursive_flat_map &a, const recursive_flat_map &b) - { return a.id_ < b.id_; } -}; - -//Test recursive structures -class recursive_flat_multiset -{ - public: - recursive_flat_multiset(const recursive_flat_multiset &c) - : id_(c.id_), flat_multiset_(c.flat_multiset_) - {} - - recursive_flat_multiset & operator =(const recursive_flat_multiset &c) - { - id_ = c.id_; - flat_multiset_= c.flat_multiset_; - return *this; - } - int id_; - flat_multiset flat_multiset_; - friend bool operator< (const recursive_flat_multiset &a, const recursive_flat_multiset &b) - { return a.id_ < b.id_; } -}; - -class recursive_flat_multimap -{ -public: - recursive_flat_multimap(const recursive_flat_multimap &c) - : id_(c.id_), map_(c.map_) - {} - - recursive_flat_multimap & operator =(const recursive_flat_multimap &c) - { - id_ = c.id_; - map_= c.map_; - return *this; - } - int id_; - flat_map map_; - friend bool operator< (const recursive_flat_multimap &a, const recursive_flat_multimap &b) - { return a.id_ < b.id_; } -}; - -template -void test_move() -{ - //Now test move semantics - C original; - C move_ctor(boost::move(original)); - C move_assign; - move_assign = boost::move(move_ctor); - move_assign.swap(original); -} - -template -class flat_tree_propagate_test_wrapper - : public container_detail::flat_tree, std::less, A> -{ - BOOST_COPYABLE_AND_MOVABLE(flat_tree_propagate_test_wrapper) - typedef container_detail::flat_tree, std::less, A> Base; - public: - flat_tree_propagate_test_wrapper() - : Base() - {} - - flat_tree_propagate_test_wrapper(const flat_tree_propagate_test_wrapper &x) - : Base(x) - {} - - flat_tree_propagate_test_wrapper(BOOST_RV_REF(flat_tree_propagate_test_wrapper) x) - : Base(boost::move(static_cast(x))) - {} - - flat_tree_propagate_test_wrapper &operator=(BOOST_COPY_ASSIGN_REF(flat_tree_propagate_test_wrapper) x) - { this->Base::operator=(x); return *this; } - - flat_tree_propagate_test_wrapper &operator=(BOOST_RV_REF(flat_tree_propagate_test_wrapper) x) - { this->Base::operator=(boost::move(static_cast(x))); return *this; } - - void swap(flat_tree_propagate_test_wrapper &x) - { this->Base::swap(x); } -}; - -namespace boost{ -namespace container { -namespace test{ - -bool flat_tree_ordered_insertion_test() -{ - using namespace boost::container; - const std::size_t NumElements = 100; - - //Ordered insertion multiset - { - std::multiset int_mset; - for(std::size_t i = 0; i != NumElements; ++i){ - int_mset.insert(static_cast(i)); - } - //Construction insertion - flat_multiset fmset(ordered_range, int_mset.begin(), int_mset.end()); - if(!CheckEqualContainers(&int_mset, &fmset)) - return false; - //Insertion when empty - fmset.clear(); - fmset.insert(ordered_range, int_mset.begin(), int_mset.end()); - if(!CheckEqualContainers(&int_mset, &fmset)) - return false; - //Re-insertion - fmset.insert(ordered_range, int_mset.begin(), int_mset.end()); - std::multiset int_mset2(int_mset); - int_mset2.insert(int_mset.begin(), int_mset.end()); - if(!CheckEqualContainers(&int_mset2, &fmset)) - return false; - //Re-re-insertion - fmset.insert(ordered_range, int_mset2.begin(), int_mset2.end()); - std::multiset int_mset4(int_mset2); - int_mset4.insert(int_mset2.begin(), int_mset2.end()); - if(!CheckEqualContainers(&int_mset4, &fmset)) - return false; - //Re-re-insertion of even - std::multiset int_even_mset; - for(std::size_t i = 0; i < NumElements; i+=2){ - int_mset.insert(static_cast(i)); - } - fmset.insert(ordered_range, int_even_mset.begin(), int_even_mset.end()); - int_mset4.insert(int_even_mset.begin(), int_even_mset.end()); - if(!CheckEqualContainers(&int_mset4, &fmset)) - return false; - } - //Ordered insertion multimap - { - std::multimap int_mmap; - for(std::size_t i = 0; i != NumElements; ++i){ - int_mmap.insert(std::multimap::value_type(static_cast(i), static_cast(i))); - } - //Construction insertion - flat_multimap fmmap(ordered_range, int_mmap.begin(), int_mmap.end()); - if(!CheckEqualContainers(&int_mmap, &fmmap)) - return false; - //Insertion when empty - fmmap.clear(); - fmmap.insert(ordered_range, int_mmap.begin(), int_mmap.end()); - if(!CheckEqualContainers(&int_mmap, &fmmap)) - return false; - //Re-insertion - fmmap.insert(ordered_range, int_mmap.begin(), int_mmap.end()); - std::multimap int_mmap2(int_mmap); - int_mmap2.insert(int_mmap.begin(), int_mmap.end()); - if(!CheckEqualContainers(&int_mmap2, &fmmap)) - return false; - //Re-re-insertion - fmmap.insert(ordered_range, int_mmap2.begin(), int_mmap2.end()); - std::multimap int_mmap4(int_mmap2); - int_mmap4.insert(int_mmap2.begin(), int_mmap2.end()); - if(!CheckEqualContainers(&int_mmap4, &fmmap)) - return false; - //Re-re-insertion of even - std::multimap int_even_mmap; - for(std::size_t i = 0; i < NumElements; i+=2){ - int_mmap.insert(std::multimap::value_type(static_cast(i), static_cast(i))); - } - fmmap.insert(ordered_range, int_even_mmap.begin(), int_even_mmap.end()); - int_mmap4.insert(int_even_mmap.begin(), int_even_mmap.end()); - if(!CheckEqualContainers(&int_mmap4, &fmmap)) - return false; - } - - //Ordered insertion set - { - std::set int_set; - for(std::size_t i = 0; i != NumElements; ++i){ - int_set.insert(static_cast(i)); - } - //Construction insertion - flat_set fset(ordered_unique_range, int_set.begin(), int_set.end()); - if(!CheckEqualContainers(&int_set, &fset)) - return false; - //Insertion when empty - fset.clear(); - fset.insert(ordered_unique_range, int_set.begin(), int_set.end()); - if(!CheckEqualContainers(&int_set, &fset)) - return false; - //Re-insertion - fset.insert(ordered_unique_range, int_set.begin(), int_set.end()); - std::set int_set2(int_set); - int_set2.insert(int_set.begin(), int_set.end()); - if(!CheckEqualContainers(&int_set2, &fset)) - return false; - //Re-re-insertion - fset.insert(ordered_unique_range, int_set2.begin(), int_set2.end()); - std::set int_set4(int_set2); - int_set4.insert(int_set2.begin(), int_set2.end()); - if(!CheckEqualContainers(&int_set4, &fset)) - return false; - //Re-re-insertion of even - std::set int_even_set; - for(std::size_t i = 0; i < NumElements; i+=2){ - int_set.insert(static_cast(i)); - } - fset.insert(ordered_unique_range, int_even_set.begin(), int_even_set.end()); - int_set4.insert(int_even_set.begin(), int_even_set.end()); - if(!CheckEqualContainers(&int_set4, &fset)) - return false; - } - //Ordered insertion map - { - std::map int_map; - for(std::size_t i = 0; i != NumElements; ++i){ - int_map.insert(std::map::value_type(static_cast(i), static_cast(i))); - } - //Construction insertion - flat_map fmap(ordered_unique_range, int_map.begin(), int_map.end()); - if(!CheckEqualContainers(&int_map, &fmap)) - return false; - //Insertion when empty - fmap.clear(); - fmap.insert(ordered_unique_range, int_map.begin(), int_map.end()); - if(!CheckEqualContainers(&int_map, &fmap)) - return false; - //Re-insertion - fmap.insert(ordered_unique_range, int_map.begin(), int_map.end()); - std::map int_map2(int_map); - int_map2.insert(int_map.begin(), int_map.end()); - if(!CheckEqualContainers(&int_map2, &fmap)) - return false; - //Re-re-insertion - fmap.insert(ordered_unique_range, int_map2.begin(), int_map2.end()); - std::map int_map4(int_map2); - int_map4.insert(int_map2.begin(), int_map2.end()); - if(!CheckEqualContainers(&int_map4, &fmap)) - return false; - //Re-re-insertion of even - std::map int_even_map; - for(std::size_t i = 0; i < NumElements; i+=2){ - int_map.insert(std::map::value_type(static_cast(i), static_cast(i))); - } - fmap.insert(ordered_unique_range, int_even_map.begin(), int_even_map.end()); - int_map4.insert(int_even_map.begin(), int_even_map.end()); - if(!CheckEqualContainers(&int_map4, &fmap)) - return false; - } - - return true; -} - -}}} - -int main() -{ - using namespace boost::container::test; - - //Allocator argument container - { - flat_set set_((std::allocator())); - flat_multiset multiset_((std::allocator())); - flat_map map_((std::allocator >())); - flat_multimap multimap_((std::allocator >())); - } - //Now test move semantics - { - test_move >(); - test_move >(); - test_move >(); - test_move >(); - } - - if(!flat_tree_ordered_insertion_test()){ - return 1; - } - - if (0 != set_test< - MyBoostSet - ,MyStdSet - ,MyBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != set_test_copyable< - MyBoostSet - ,MyStdSet - ,MyBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != set_test< - MyMovableBoostSet - ,MyStdSet - ,MyMovableBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != set_test< - MyMoveCopyBoostSet - ,MyStdSet - ,MyMoveCopyBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != set_test_copyable< - MyMoveCopyBoostSet - ,MyStdSet - ,MyMoveCopyBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != set_test< - MyCopyBoostSet - ,MyStdSet - ,MyCopyBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != set_test_copyable< - MyCopyBoostSet - ,MyStdSet - ,MyCopyBoostMultiSet - ,MyStdMultiSet>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != map_test< - MyBoostMap - ,MyStdMap - ,MyBoostMultiMap - ,MyStdMultiMap>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != map_test_copyable< - MyBoostMap - ,MyStdMap - ,MyBoostMultiMap - ,MyStdMultiMap>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != map_test< - MyMovableBoostMap - ,MyStdMap - ,MyMovableBoostMultiMap - ,MyStdMultiMap>()){ - return 1; - } - - if (0 != map_test< - MyMoveCopyBoostMap - ,MyStdMap - ,MyMoveCopyBoostMultiMap - ,MyStdMultiMap>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != map_test_copyable< - MyMoveCopyBoostMap - ,MyStdMap - ,MyMoveCopyBoostMultiMap - ,MyStdMultiMap>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != map_test< - MyCopyBoostMap - ,MyStdMap - ,MyCopyBoostMultiMap - ,MyStdMultiMap>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - if (0 != map_test_copyable< - MyCopyBoostMap - ,MyStdMap - ,MyCopyBoostMultiMap - ,MyStdMultiMap>()){ - std::cout << "Error in set_test" << std::endl; - return 1; - } - - const test::EmplaceOptions SetOptions = (test::EmplaceOptions)(test::EMPLACE_HINT | test::EMPLACE_ASSOC); - const test::EmplaceOptions MapOptions = (test::EmplaceOptions)(test::EMPLACE_HINT_PAIR | test::EMPLACE_ASSOC_PAIR); - - if(!boost::container::test::test_emplace, MapOptions>()) - return 1; - if(!boost::container::test::test_emplace, MapOptions>()) - return 1; - if(!boost::container::test::test_emplace, SetOptions>()) - return 1; - if(!boost::container::test::test_emplace, SetOptions>()) - return 1; - if(!boost::container::test::test_propagate_allocator()) - return 1; - - return 0; -} - -#include - diff --git a/test/hash_table_test.cppx b/test/hash_table_test.cppx new file mode 100644 index 0000000..e69de29 diff --git a/test/heap_allocator_v1.hpp b/test/heap_allocator_v1.hpp deleted file mode 100644 index b6661d1..0000000 --- a/test/heap_allocator_v1.hpp +++ /dev/null @@ -1,158 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -/////////////////////////////////////////////////////////////////////////////// - -#ifndef BOOST_CONTAINER_HEAP_ALLOCATOR_V1_HPP -#define BOOST_CONTAINER_HEAP_ALLOCATOR_V1_HPP - -#if (defined _MSC_VER) -# pragma once -#endif - -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -//!\file -//!Describes an heap_allocator_v1 that allocates portions of fixed size -//!memory buffer (shared memory, mapped file...) - -namespace boost { -namespace container { -namespace test { - -//!An STL compatible heap_allocator_v1 that uses a segment manager as -//!memory source. The internal pointer type will of the same type (raw, smart) as -//!"typename SegmentManager::void_pointer" type. This allows -//!placing the heap_allocator_v1 in shared memory, memory mapped-files, etc...*/ -template -class heap_allocator_v1 -{ - private: - typedef heap_allocator_v1 self_t; - typedef SegmentManager segment_manager; - typedef typename segment_manager::void_pointer aux_pointer_t; - - typedef typename - boost::pointer_to_other - ::type cvoid_ptr; - - typedef typename boost::pointer_to_other - ::type alloc_ptr_t; - - template - heap_allocator_v1& operator=(const heap_allocator_v1&); - - heap_allocator_v1& operator=(const heap_allocator_v1&); - - alloc_ptr_t mp_mngr; - - public: - typedef T value_type; - typedef typename boost::pointer_to_other - ::type pointer; - typedef typename boost:: - pointer_to_other::type const_pointer; - typedef typename detail::add_reference - ::type reference; - typedef typename detail::add_reference - ::type const_reference; - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; - - //!Obtains an heap_allocator_v1 of other type - template - struct rebind - { - typedef heap_allocator_v1 other; - }; - - //!Returns the segment manager. Never throws - segment_manager* get_segment_manager()const - { return detail::get_pointer(mp_mngr); } -/* - //!Returns address of mutable object. Never throws - pointer address(reference value) const - { return pointer(addressof(value)); } - - //!Returns address of non mutable object. Never throws - const_pointer address(const_reference value) const - { return const_pointer(addressof(value)); } -*/ - //!Constructor from the segment manager. Never throws - heap_allocator_v1(segment_manager *segment_mngr) - : mp_mngr(segment_mngr) { } - - //!Constructor from other heap_allocator_v1. Never throws - heap_allocator_v1(const heap_allocator_v1 &other) - : mp_mngr(other.get_segment_manager()){ } - - //!Constructor from related heap_allocator_v1. Never throws - template - heap_allocator_v1(const heap_allocator_v1 &other) - : mp_mngr(other.get_segment_manager()){} - - //!Allocates memory for an array of count elements. - //!Throws boost::container::bad_alloc if there is no enough memory - pointer allocate(size_type count, cvoid_ptr hint = 0) - { (void)hint; return ::new value_type[count]; } - - //!Deallocates memory previously allocated. Never throws - void deallocate(const pointer &ptr, size_type) - { return ::delete[] detail::get_pointer(ptr) ; } - - //!Construct object, calling constructor. - //!Throws if T(const T&) throws - void construct(const pointer &ptr, const_reference value) - { new((void*)detail::get_pointer(ptr)) value_type(value); } - - //!Destroys object. Throws if object's destructor throws - void destroy(const pointer &ptr) - { BOOST_ASSERT(ptr != 0); (*ptr).~value_type(); } - - //!Returns the number of elements that could be allocated. Never throws - size_type max_size() const - { return mp_mngr->get_size(); } - - //!Swap segment manager. Does not throw. If each heap_allocator_v1 is placed in - //!different memory segments, the result is undefined. - friend void swap(self_t &alloc1, self_t &alloc2) - { boost::container::boost::container::swap_dispatch(alloc1.mp_mngr, alloc2.mp_mngr); } -}; - -//!Equality test for same type of heap_allocator_v1 -template inline -bool operator==(const heap_allocator_v1 &alloc1, - const heap_allocator_v1 &alloc2) - { return alloc1.get_segment_manager() == alloc2.get_segment_manager(); } - -//!Inequality test for same type of heap_allocator_v1 -template inline -bool operator!=(const heap_allocator_v1 &alloc1, - const heap_allocator_v1 &alloc2) - { return alloc1.get_segment_manager() != alloc2.get_segment_manager(); } - -} //namespace test { -} //namespace container { -} //namespace boost { - -#include - -#endif //BOOST_CONTAINER_HEAP_ALLOCATOR_V1_HPP - diff --git a/test/input_from_forward_iterator.hpp b/test/input_from_forward_iterator.hpp index 348d144..ebc3973 100644 --- a/test/input_from_forward_iterator.hpp +++ b/test/input_from_forward_iterator.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2012-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2012-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/test/list_test.cpp b/test/list_test.cpp index c7198e7..578fac2 100644 --- a/test/list_test.cpp +++ b/test/list_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -10,6 +10,10 @@ #include #include +#include +#include +#include + #include "dummy_test_allocator.hpp" #include #include "movable_int.hpp" @@ -23,14 +27,29 @@ namespace boost { namespace container { //Explicit instantiation to detect compilation errors -template class boost::container::list >; +template class boost::container::list + < test::movable_and_copyable_int + , test::simple_allocator >; -template class boost::container::list >; +template class boost::container::list + < test::movable_and_copyable_int + , test::dummy_test_allocator >; -template class boost::container::list >; +template class boost::container::list + < test::movable_and_copyable_int + , std::allocator >; + +template class boost::container::list + < test::movable_and_copyable_int + , allocator >; + +template class boost::container::list + < test::movable_and_copyable_int + , adaptive_pool >; + +template class boost::container::list + < test::movable_and_copyable_int + , node_allocator >; namespace container_detail { @@ -43,12 +62,6 @@ template class iterator }} -typedef list MyList; - -typedef list MyMoveList; -typedef list MyCopyMoveList; -typedef list MyCopyList; - class recursive_list { public: @@ -67,6 +80,42 @@ void recursive_list_test()//Test for recursive types } } +template +struct GetAllocatorCont +{ + template + struct apply + { + typedef list< ValueType + , typename allocator_traits + ::template portable_rebind_alloc::type + > type; + }; +}; + +template +int test_cont_variants() +{ + typedef typename GetAllocatorCont::template apply::type MyCont; + typedef typename GetAllocatorCont::template apply::type MyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyCont; + + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + + return 0; +} + + int main () { recursive_list_test(); @@ -78,23 +127,42 @@ int main () move_assign = boost::move(move_ctor); move_assign.swap(original); } - if(test::list_test()) - return 1; - if(test::list_test()) + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std:allocator + if(test_cont_variants< std::allocator >()){ + std::cerr << "test_cont_variants< std::allocator > failed" << std::endl; return 1; - - if(test::list_test()) + } + // boost::container::allocator + if(test_cont_variants< allocator >()){ + std::cerr << "test_cont_variants< allocator > failed" << std::endl; return 1; - - if(test::list_test()) + } + // boost::container::node_allocator + if(test_cont_variants< node_allocator >()){ + std::cerr << "test_cont_variants< node_allocator > failed" << std::endl; return 1; + } + // boost::container::adaptive_pool + if(test_cont_variants< adaptive_pool >()){ + std::cerr << "test_cont_variants< adaptive_pool > failed" << std::endl; + return 1; + } + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// const test::EmplaceOptions Options = (test::EmplaceOptions)(test::EMPLACE_BACK | test::EMPLACE_FRONT | test::EMPLACE_BEFORE); if(!boost::container::test::test_emplace, Options>()) return 1; + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// if(!boost::container::test::test_propagate_allocator()) return 1; diff --git a/test/map_test.cpp b/test/map_test.cpp new file mode 100644 index 0000000..565d2b1 --- /dev/null +++ b/test/map_test.cpp @@ -0,0 +1,459 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include +#include + +#include "print_container.hpp" +#include "movable_int.hpp" +#include "dummy_test_allocator.hpp" +#include "map_test.hpp" +#include "propagate_allocator_test.hpp" +#include "emplace_test.hpp" + +using namespace boost::container; + +namespace boost { +namespace container { + +//Explicit instantiation to detect compilation errors + +//map +template class map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + < std::pair > + >; + +template class map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::simple_allocator + < std::pair > + >; + +template class map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , std::allocator + < std::pair > + >; + + +template class map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , allocator + < std::pair > + >; + +template class map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , adaptive_pool + < std::pair > + >; + +template class map + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , node_allocator + < std::pair > + >; + +//multimap +template class multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + < std::pair > + >; + +template class multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , test::simple_allocator + < std::pair > + >; + +template class multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , std::allocator + < std::pair > + >; + +template class multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , allocator + < std::pair > + >; + +template class multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , adaptive_pool + < std::pair > + >; + +template class multimap + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , std::less + , node_allocator + < std::pair > + >; + +namespace container_detail { + +template class tree + < const test::movable_and_copyable_int + , std::pair + , container_detail::select1st< std::pair > + , std::less + , test::dummy_test_allocator + < std::pair > + , tree_assoc_defaults >; + +template class tree + < const test::movable_and_copyable_int + , std::pair + , container_detail::select1st< std::pair > + , std::less + , test::simple_allocator + < std::pair > + , tree_assoc_defaults >; + +template class tree + < const test::movable_and_copyable_int + , std::pair + , container_detail::select1st< std::pair > + , std::less + , std::allocator + < std::pair > + , tree_assoc_defaults >; + +template class tree + < const test::movable_and_copyable_int + , std::pair + , container_detail::select1st< std::pair > + , std::less + , allocator + < std::pair > + , tree_assoc_defaults >; + +template class tree + < const test::movable_and_copyable_int + , std::pair + , container_detail::select1st< std::pair > + , std::less + , adaptive_pool + < std::pair > + , tree_assoc_defaults >; + +template class tree + < const test::movable_and_copyable_int + , std::pair + , container_detail::select1st< std::pair > + , std::less + , node_allocator + < std::pair > + , tree_assoc_defaults >; + +} //container_detail { + +}} //boost::container + +class recursive_map +{ + public: + recursive_map & operator=(const recursive_map &x) + { id_ = x.id_; map_ = x.map_; return *this; } + + int id_; + map map_; + friend bool operator< (const recursive_map &a, const recursive_map &b) + { return a.id_ < b.id_; } +}; + +class recursive_multimap +{ + public: + recursive_multimap & operator=(const recursive_multimap &x) + { id_ = x.id_; multimap_ = x.multimap_; return *this; } + + int id_; + multimap multimap_; + friend bool operator< (const recursive_multimap &a, const recursive_multimap &b) + { return a.id_ < b.id_; } +}; + +template +void test_move() +{ + //Now test move semantics + C original; + original.emplace(); + C move_ctor(boost::move(original)); + C move_assign; + move_assign.emplace(); + move_assign = boost::move(move_ctor); + move_assign.swap(original); +} + +template +class map_propagate_test_wrapper + : public boost::container::map + < T, T, std::less + , typename boost::container::allocator_traits::template + portable_rebind_alloc< std::pair >::type + //tree_assoc_defaults + > +{ + BOOST_COPYABLE_AND_MOVABLE(map_propagate_test_wrapper) + typedef boost::container::map + < T, T, std::less + , typename boost::container::allocator_traits::template + portable_rebind_alloc< std::pair >::type + > Base; + public: + map_propagate_test_wrapper() + : Base() + {} + + map_propagate_test_wrapper(const map_propagate_test_wrapper &x) + : Base(x) + {} + + map_propagate_test_wrapper(BOOST_RV_REF(map_propagate_test_wrapper) x) + : Base(boost::move(static_cast(x))) + {} + + map_propagate_test_wrapper &operator=(BOOST_COPY_ASSIGN_REF(map_propagate_test_wrapper) x) + { this->Base::operator=(x); return *this; } + + map_propagate_test_wrapper &operator=(BOOST_RV_REF(map_propagate_test_wrapper) x) + { this->Base::operator=(boost::move(static_cast(x))); return *this; } + + void swap(map_propagate_test_wrapper &x) + { this->Base::swap(x); } +}; + + +template +struct GetAllocatorMap +{ + template + struct apply + { + typedef map< ValueType + , ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc< std::pair >::type + , typename boost::container::tree_assoc_options + < boost::container::tree_type + >::type + > map_type; + + typedef multimap< ValueType + , ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc< std::pair >::type + , typename boost::container::tree_assoc_options + < boost::container::tree_type + >::type + > multimap_type; + }; +}; + +template +int test_map_variants() +{ + typedef typename GetAllocatorMap::template apply::map_type MyMap; + typedef typename GetAllocatorMap::template apply::map_type MyMoveMap; + typedef typename GetAllocatorMap::template apply::map_type MyCopyMoveMap; + typedef typename GetAllocatorMap::template apply::map_type MyCopyMap; + + typedef typename GetAllocatorMap::template apply::multimap_type MyMultiMap; + typedef typename GetAllocatorMap::template apply::multimap_type MyMoveMultiMap; + typedef typename GetAllocatorMap::template apply::multimap_type MyCopyMoveMultiMap; + typedef typename GetAllocatorMap::template apply::multimap_type MyCopyMultiMap; + + typedef std::map MyStdMap; + typedef std::multimap MyStdMultiMap; + + if (0 != test::map_test< + MyMap + ,MyStdMap + ,MyMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + if (0 != test::map_test< + MyMoveMap + ,MyStdMap + ,MyMoveMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + if (0 != test::map_test< + MyCopyMoveMap + ,MyStdMap + ,MyCopyMoveMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + if (0 != test::map_test< + MyCopyMap + ,MyStdMap + ,MyCopyMultiMap + ,MyStdMultiMap>()){ + std::cout << "Error in map_test" << std::endl; + return 1; + } + + return 0; +} + +int main () +{ + //Recursive container instantiation + { + map map_; + multimap multimap_; + } + //Allocator argument container + { + map map_((std::allocator >())); + multimap multimap_((std::allocator >())); + } + //Now test move semantics + { + test_move >(); + test_move >(); + } + + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std:allocator + if(test_map_variants< std::allocator, red_black_tree >()){ + std::cerr << "test_map_variants< std::allocator > failed" << std::endl; + return 1; + } + // boost::container::allocator + if(test_map_variants< allocator, red_black_tree >()){ + std::cerr << "test_map_variants< allocator > failed" << std::endl; + return 1; + } + // boost::container::node_allocator + if(test_map_variants< node_allocator, red_black_tree >()){ + std::cerr << "test_map_variants< node_allocator > failed" << std::endl; + return 1; + } + // boost::container::adaptive_pool + if(test_map_variants< adaptive_pool, red_black_tree >()){ + std::cerr << "test_map_variants< adaptive_pool > failed" << std::endl; + return 1; + } + + //////////////////////////////////// + // Tree implementations + //////////////////////////////////// + // AVL + if(test_map_variants< std::allocator, avl_tree >()){ + std::cerr << "test_map_variants< std::allocator, avl_tree > failed" << std::endl; + return 1; + } + // SCAPEGOAT TREE + if(test_map_variants< std::allocator, scapegoat_tree >()){ + std::cerr << "test_map_variants< std::allocator, scapegoat_tree > failed" << std::endl; + return 1; + } + // SPLAY TREE + if(test_map_variants< std::allocator, splay_tree >()){ + std::cerr << "test_map_variants< std::allocator, splay_tree > failed" << std::endl; + return 1; + } + + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// + const test::EmplaceOptions MapOptions = (test::EmplaceOptions)(test::EMPLACE_HINT_PAIR | test::EMPLACE_ASSOC_PAIR); + if(!boost::container::test::test_emplace, MapOptions>()) + return 1; + if(!boost::container::test::test_emplace, MapOptions>()) + return 1; + + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// + if(!boost::container::test::test_propagate_allocator()) + return 1; + + //////////////////////////////////// + // Test optimize_size option + //////////////////////////////////// + // + // map + // + typedef map< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > rbmap_size_optimized_no; + typedef map< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > rbmap_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(rbmap_size_optimized_yes) < sizeof(rbmap_size_optimized_no)); + + typedef map< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > avlmap_size_optimized_no; + typedef map< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > avlmap_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(avlmap_size_optimized_yes) < sizeof(avlmap_size_optimized_no)); + // + // multimap + // + typedef multimap< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > rbmmap_size_optimized_no; + typedef multimap< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > rbmmap_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(rbmmap_size_optimized_yes) < sizeof(rbmmap_size_optimized_no)); + + typedef multimap< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > avlmmap_size_optimized_no; + typedef multimap< int*, int*, std::less, std::allocator< std::pair > + , tree_assoc_options< optimize_size, tree_type >::type > avlmmap_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(avlmmap_size_optimized_yes) < sizeof(avlmmap_size_optimized_no)); + + return 0; +} + +#include diff --git a/test/map_test.hpp b/test/map_test.hpp index 523eb37..98e1ba5 100644 --- a/test/map_test.hpp +++ b/test/map_test.hpp @@ -23,6 +23,13 @@ #include #include +#include +#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME rebalance +#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace test { +#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} +#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, )) +#include BOOST_PP_ITERATE() + template bool operator ==(std::pair &p1, std::pair &p2) { @@ -33,11 +40,99 @@ namespace boost{ namespace container { namespace test{ +template +void map_test_rebalanceable(C &, boost::container::container_detail::false_type) +{} + +template +void map_test_rebalanceable(C &c, boost::container::container_detail::true_type) +{ + c.rebalance(); +} + template -int map_test () +int map_test_copyable(boost::container::container_detail::false_type) +{ return 0; } + +template +int map_test_copyable(boost::container::container_detail::true_type) +{ + typedef typename MyBoostMap::key_type IntType; + typedef container_detail::pair IntPairType; + typedef typename MyStdMap::value_type StdPairType; + + const int max = 100; + + BOOST_TRY{ + MyBoostMap *boostmap = new MyBoostMap; + MyStdMap *stdmap = new MyStdMap; + MyBoostMultiMap *boostmultimap = new MyBoostMultiMap; + MyStdMultiMap *stdmultimap = new MyStdMultiMap; + + int i; + for(i = 0; i < max; ++i){ + { + IntType i1(i), i2(i); + IntPairType intpair1(boost::move(i1), boost::move(i2)); + boostmap->insert(boost::move(intpair1)); + stdmap->insert(StdPairType(i, i)); + } + { + IntType i1(i), i2(i); + IntPairType intpair2(boost::move(i1), boost::move(i2)); + boostmultimap->insert(boost::move(intpair2)); + stdmultimap->insert(StdPairType(i, i)); + } + } + if(!CheckEqualContainers(boostmap, stdmap)) return 1; + if(!CheckEqualContainers(boostmultimap, stdmultimap)) return 1; + + { + //Now, test copy constructor + MyBoostMap boostmapcopy(*boostmap); + MyStdMap stdmapcopy(*stdmap); + MyBoostMultiMap boostmmapcopy(*boostmultimap); + MyStdMultiMap stdmmapcopy(*stdmultimap); + + if(!CheckEqualContainers(&boostmapcopy, &stdmapcopy)) + return 1; + if(!CheckEqualContainers(&boostmmapcopy, &stdmmapcopy)) + return 1; + + //And now assignment + boostmapcopy = *boostmap; + stdmapcopy = *stdmap; + boostmmapcopy = *boostmultimap; + stdmmapcopy = *stdmultimap; + + if(!CheckEqualContainers(&boostmapcopy, &stdmapcopy)) + return 1; + if(!CheckEqualContainers(&boostmmapcopy, &stdmmapcopy)) + return 1; + delete boostmap; + delete boostmultimap; + delete stdmap; + delete stdmultimap; + } + } + BOOST_CATCH(...){ + BOOST_RETHROW; + } + BOOST_CATCH_END + return 0; +} + +template +int map_test() { typedef typename MyBoostMap::key_type IntType; typedef container_detail::pair IntPairType; @@ -423,6 +518,19 @@ int map_test () return 1; if(!CheckEqualPairContainers(boostmultimap, stdmultimap)) return 1; + + map_test_rebalanceable(*boostmap + , container_detail::bool_::value>()); + if(!CheckEqualContainers(boostmap, stdmap)){ + std::cout << "Error in boostmap->rebalance()" << std::endl; + return 1; + } + map_test_rebalanceable(*boostmultimap + , container_detail::bool_::value>()); + if(!CheckEqualContainers(boostmultimap, stdmultimap)){ + std::cout << "Error in boostmultimap->rebalance()" << std::endl; + return 1; + } } //Compare count with std containers @@ -471,77 +579,11 @@ int map_test () BOOST_RETHROW; } BOOST_CATCH_END - return 0; -} -template -int map_test_copyable () -{ - typedef typename MyBoostMap::key_type IntType; - typedef container_detail::pair IntPairType; - typedef typename MyStdMap::value_type StdPairType; - - const int max = 100; - - BOOST_TRY{ - MyBoostMap *boostmap = new MyBoostMap; - MyStdMap *stdmap = new MyStdMap; - MyBoostMultiMap *boostmultimap = new MyBoostMultiMap; - MyStdMultiMap *stdmultimap = new MyStdMultiMap; - - int i; - for(i = 0; i < max; ++i){ - { - IntType i1(i), i2(i); - IntPairType intpair1(boost::move(i1), boost::move(i2)); - boostmap->insert(boost::move(intpair1)); - stdmap->insert(StdPairType(i, i)); - } - { - IntType i1(i), i2(i); - IntPairType intpair2(boost::move(i1), boost::move(i2)); - boostmultimap->insert(boost::move(intpair2)); - stdmultimap->insert(StdPairType(i, i)); - } + if(map_test_copyable + (container_detail::bool_::value>())){ + return 1; } - if(!CheckEqualContainers(boostmap, stdmap)) return 1; - if(!CheckEqualContainers(boostmultimap, stdmultimap)) return 1; - - { - //Now, test copy constructor - MyBoostMap boostmapcopy(*boostmap); - MyStdMap stdmapcopy(*stdmap); - MyBoostMultiMap boostmmapcopy(*boostmultimap); - MyStdMultiMap stdmmapcopy(*stdmultimap); - - if(!CheckEqualContainers(&boostmapcopy, &stdmapcopy)) - return 1; - if(!CheckEqualContainers(&boostmmapcopy, &stdmmapcopy)) - return 1; - - //And now assignment - boostmapcopy = *boostmap; - stdmapcopy = *stdmap; - boostmmapcopy = *boostmultimap; - stdmmapcopy = *stdmultimap; - - if(!CheckEqualContainers(&boostmapcopy, &stdmapcopy)) - return 1; - if(!CheckEqualContainers(&boostmmapcopy, &stdmmapcopy)) - return 1; - delete boostmap; - delete boostmultimap; - delete stdmap; - delete stdmultimap; - } - } - BOOST_CATCH(...){ - BOOST_RETHROW; - } - BOOST_CATCH_END return 0; } diff --git a/test/pair_test.cpp b/test/pair_test.cpp index 6b75b01..3560b74 100644 --- a/test/pair_test.cpp +++ b/test/pair_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/test/print_container.hpp b/test/print_container.hpp index a3de94e..4a09cdc 100644 --- a/test/print_container.hpp +++ b/test/print_container.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -20,8 +20,11 @@ namespace boost{ namespace container { namespace test{ -struct PrintValues : public std::unary_function +struct PrintValues { + typedef int argument_type; + typedef void result_type; + void operator() (int value) const { std::cout << value << " "; diff --git a/test/scoped_allocator_adaptor_test.cpp b/test/scoped_allocator_adaptor_test.cpp index 3464aa4..75f1655 100644 --- a/test/scoped_allocator_adaptor_test.cpp +++ b/test/scoped_allocator_adaptor_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2011-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2011-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // diff --git a/test/scoped_allocator_usage_test.cpp b/test/scoped_allocator_usage_test.cpp index f8dafa4..058d997 100644 --- a/test/scoped_allocator_usage_test.cpp +++ b/test/scoped_allocator_usage_test.cpp @@ -114,9 +114,9 @@ typedef multiset, AllocIntAllocator> MultiSet; //[multi]flat_map/set typedef std::pair FlatMapNode; typedef scoped_allocator_adaptor > FlatMapAllocator; -typedef flat_map, MapAllocator> FlatMap; +typedef flat_map, FlatMapAllocator> FlatMap; typedef flat_set, AllocIntAllocator> FlatSet; -typedef flat_multimap, MapAllocator> FlatMultiMap; +typedef flat_multimap, FlatMapAllocator> FlatMultiMap; typedef flat_multiset, AllocIntAllocator> FlatMultiSet; //vector, deque, list, slist, stable_vector. diff --git a/test/set_test.cpp b/test/set_test.cpp new file mode 100644 index 0000000..d613421 --- /dev/null +++ b/test/set_test.cpp @@ -0,0 +1,428 @@ +////////////////////////////////////////////////////////////////////////////// +// +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost +// Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// See http://www.boost.org/libs/container for documentation. +// +////////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include +#include +#include + +#include "print_container.hpp" +#include "movable_int.hpp" +#include "dummy_test_allocator.hpp" +#include "set_test.hpp" +#include "propagate_allocator_test.hpp" +#include "emplace_test.hpp" + +using namespace boost::container; + +namespace boost { +namespace container { + +//Explicit instantiation to detect compilation errors + +//set +template class set + < test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + >; + +template class set + < test::movable_and_copyable_int + , std::less + , test::simple_allocator + >; + +template class set + < test::movable_and_copyable_int + , std::less + , std::allocator + >; + +template class set + < test::movable_and_copyable_int + , std::less + , allocator + >; + +template class set + < test::movable_and_copyable_int + , std::less + , adaptive_pool + >; + +template class set + < test::movable_and_copyable_int + , std::less + , node_allocator + >; + +//multiset +template class multiset + < test::movable_and_copyable_int + , std::less + , test::dummy_test_allocator + >; + +template class multiset + < test::movable_and_copyable_int + , std::less + , test::simple_allocator + >; + +template class multiset + < test::movable_and_copyable_int + , std::less + , std::allocator + >; + +template class multiset + < test::movable_and_copyable_int + , std::less + , allocator + >; + +template class multiset + < test::movable_and_copyable_int + , std::less + , adaptive_pool + >; + +template class multiset + < test::movable_and_copyable_int + , std::less + , node_allocator + >; + +namespace container_detail { + +//Instantiate base class as previous instantiations don't instantiate inherited members +template class tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , test::dummy_test_allocator + , tree_assoc_defaults + >; + +template class tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , test::simple_allocator + , tree_assoc_defaults + >; + +template class tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , std::allocator + , tree_assoc_defaults + >; + +template class tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , allocator + , tree_assoc_defaults + >; + +template class tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , adaptive_pool + , tree_assoc_defaults + >; + +template class tree + < test::movable_and_copyable_int + , test::movable_and_copyable_int + , identity + , std::less + , node_allocator + , tree_assoc_defaults + >; + +} //container_detail { + +}} //boost::container + +//Test recursive structures +class recursive_set +{ +public: + recursive_set & operator=(const recursive_set &x) + { id_ = x.id_; set_ = x.set_; return *this; } + + int id_; + set set_; + friend bool operator< (const recursive_set &a, const recursive_set &b) + { return a.id_ < b.id_; } +}; + +//Test recursive structures +class recursive_multiset +{ + public: + recursive_multiset & operator=(const recursive_multiset &x) + { id_ = x.id_; multiset_ = x.multiset_; return *this; } + + int id_; + multiset multiset_; + friend bool operator< (const recursive_multiset &a, const recursive_multiset &b) + { return a.id_ < b.id_; } +}; + +template +void test_move() +{ + //Now test move semantics + C original; + original.emplace(); + C move_ctor(boost::move(original)); + C move_assign; + move_assign.emplace(); + move_assign = boost::move(move_ctor); + move_assign.swap(original); +} + +template +class set_propagate_test_wrapper + : public boost::container::set, A + //tree_assoc_defaults + > +{ + BOOST_COPYABLE_AND_MOVABLE(set_propagate_test_wrapper) + typedef boost::container::set, A > Base; + public: + set_propagate_test_wrapper() + : Base() + {} + + set_propagate_test_wrapper(const set_propagate_test_wrapper &x) + : Base(x) + {} + + set_propagate_test_wrapper(BOOST_RV_REF(set_propagate_test_wrapper) x) + : Base(boost::move(static_cast(x))) + {} + + set_propagate_test_wrapper &operator=(BOOST_COPY_ASSIGN_REF(set_propagate_test_wrapper) x) + { this->Base::operator=(x); return *this; } + + set_propagate_test_wrapper &operator=(BOOST_RV_REF(set_propagate_test_wrapper) x) + { this->Base::operator=(boost::move(static_cast(x))); return *this; } + + void swap(set_propagate_test_wrapper &x) + { this->Base::swap(x); } +}; + +template +struct GetAllocatorSet +{ + template + struct apply + { + typedef set < ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc::type + , typename boost::container::tree_assoc_options + < boost::container::tree_type + >::type + > set_type; + + typedef multiset < ValueType + , std::less + , typename allocator_traits + ::template portable_rebind_alloc::type + , typename boost::container::tree_assoc_options + < boost::container::tree_type + >::type + > multiset_type; + }; +}; + +template +int test_set_variants() +{ + typedef typename GetAllocatorSet::template apply::set_type MySet; + typedef typename GetAllocatorSet::template apply::set_type MyMoveSet; + typedef typename GetAllocatorSet::template apply::set_type MyCopyMoveSet; + typedef typename GetAllocatorSet::template apply::set_type MyCopySet; + + typedef typename GetAllocatorSet::template apply::multiset_type MyMultiSet; + typedef typename GetAllocatorSet::template apply::multiset_type MyMoveMultiSet; + typedef typename GetAllocatorSet::template apply::multiset_type MyCopyMoveMultiSet; + typedef typename GetAllocatorSet::template apply::multiset_type MyCopyMultiSet; + + typedef std::set MyStdSet; + typedef std::multiset MyStdMultiSet; + + if (0 != test::set_test< + MySet + ,MyStdSet + ,MyMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + if (0 != test::set_test< + MyMoveSet + ,MyStdSet + ,MyMoveMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + if (0 != test::set_test< + MyCopyMoveSet + ,MyStdSet + ,MyCopyMoveMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + if (0 != test::set_test< + MyCopySet + ,MyStdSet + ,MyCopyMultiSet + ,MyStdMultiSet>()){ + std::cout << "Error in set_test" << std::endl; + return 1; + } + + return 0; +} + + +int main () +{ + //Recursive container instantiation + { + set set_; + multiset multiset_; + } + //Allocator argument container + { + set set_((std::allocator())); + multiset multiset_((std::allocator())); + } + //Now test move semantics + { + test_move >(); + test_move >(); + } + + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std:allocator + if(test_set_variants< std::allocator, red_black_tree >()){ + std::cerr << "test_set_variants< std::allocator > failed" << std::endl; + return 1; + } + // boost::container::allocator + if(test_set_variants< allocator, red_black_tree>()){ + std::cerr << "test_set_variants< allocator > failed" << std::endl; + return 1; + } + // boost::container::node_allocator + if(test_set_variants< node_allocator, red_black_tree>()){ + std::cerr << "test_set_variants< node_allocator > failed" << std::endl; + return 1; + } + // boost::container::adaptive_pool + if(test_set_variants< adaptive_pool, red_black_tree>()){ + std::cerr << "test_set_variants< adaptive_pool > failed" << std::endl; + return 1; + } + + //////////////////////////////////// + // Tree implementations + //////////////////////////////////// + // AVL + if(test_set_variants< std::allocator, avl_tree >()){ + std::cerr << "test_set_variants< std::allocator, avl_tree > failed" << std::endl; + return 1; + } + // SCAPEGOAT TREE + if(test_set_variants< std::allocator, scapegoat_tree >()){ + std::cerr << "test_set_variants< std::allocator, scapegoat_tree > failed" << std::endl; + return 1; + } + // SPLAY TREE + if(test_set_variants< std::allocator, splay_tree >()){ + std::cerr << "test_set_variants< std::allocator, splay_tree > failed" << std::endl; + return 1; + } + + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// + const test::EmplaceOptions SetOptions = (test::EmplaceOptions)(test::EMPLACE_HINT | test::EMPLACE_ASSOC); + if(!boost::container::test::test_emplace, SetOptions>()) + return 1; + if(!boost::container::test::test_emplace, SetOptions>()) + return 1; + + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// + if(!boost::container::test::test_propagate_allocator()) + return 1; + + //////////////////////////////////// + // Test optimize_size option + //////////////////////////////////// + // + // set + // + typedef set< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > rbset_size_optimized_no; + typedef set< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > rbset_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(rbset_size_optimized_yes) < sizeof(rbset_size_optimized_no)); + + typedef set< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > avlset_size_optimized_no; + typedef set< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > avlset_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(avlset_size_optimized_yes) < sizeof(avlset_size_optimized_no)); + // + // multiset + // + typedef multiset< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > rbmset_size_optimized_no; + typedef multiset< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > rbmset_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(rbmset_size_optimized_yes) < sizeof(rbmset_size_optimized_no)); + + typedef multiset< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > avlmset_size_optimized_no; + typedef multiset< int*, std::less, std::allocator + , tree_assoc_options< optimize_size, tree_type >::type > avlmset_size_optimized_yes; + BOOST_STATIC_ASSERT(sizeof(avlmset_size_optimized_yes) < sizeof(avlmset_size_optimized_no)); + return 0; +} + +#include diff --git a/test/set_test.hpp b/test/set_test.hpp index a0a56e8..56fb4a0 100644 --- a/test/set_test.hpp +++ b/test/set_test.hpp @@ -1,6 +1,6 @@ //////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -21,10 +21,99 @@ #include #include +#include +#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_FUNCNAME rebalance +#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_BEGIN namespace boost { namespace container { namespace test { +#define BOOST_INTRUSIVE_HAS_MEMBER_FUNCTION_CALLABLE_WITH_NS_END }}} +#define BOOST_PP_ITERATION_PARAMS_1 (3, (0, 0, )) +#include BOOST_PP_ITERATE() + + namespace boost{ namespace container { namespace test{ +template +void set_test_rebalanceable(C &, boost::container::container_detail::false_type) +{} + +template +void set_test_rebalanceable(C &c, boost::container::container_detail::true_type) +{ + c.rebalance(); +} + +template +int set_test_copyable(boost::container::container_detail::false_type) +{ return 0; } + +template +int set_test_copyable(boost::container::container_detail::true_type) +{ + typedef typename MyBoostSet::value_type IntType; + const int max = 100; + + BOOST_TRY{ + MyBoostSet *boostset = new MyBoostSet; + MyStdSet *stdset = new MyStdSet; + MyBoostMultiSet *boostmultiset = new MyBoostMultiSet; + MyStdMultiSet *stdmultiset = new MyStdMultiSet; + + for(int i = 0; i < max; ++i){ + IntType move_me(i); + boostset->insert(boost::move(move_me)); + stdset->insert(i); + IntType move_me2(i); + boostmultiset->insert(boost::move(move_me2)); + stdmultiset->insert(i); + } + if(!CheckEqualContainers(boostset, stdset)) return 1; + if(!CheckEqualContainers(boostmultiset, stdmultiset)) return 1; + + { + //Now, test copy constructor + MyBoostSet boostsetcopy(*boostset); + MyStdSet stdsetcopy(*stdset); + + if(!CheckEqualContainers(&boostsetcopy, &stdsetcopy)) + return 1; + + MyBoostMultiSet boostmsetcopy(*boostmultiset); + MyStdMultiSet stdmsetcopy(*stdmultiset); + + if(!CheckEqualContainers(&boostmsetcopy, &stdmsetcopy)) + return 1; + + //And now assignment + boostsetcopy = *boostset; + stdsetcopy = *stdset; + + if(!CheckEqualContainers(&boostsetcopy, &stdsetcopy)) + return 1; + + boostmsetcopy = *boostmultiset; + stdmsetcopy = *stdmultiset; + + if(!CheckEqualContainers(&boostmsetcopy, &stdmsetcopy)) + return 1; + } + delete boostset; + delete boostmultiset; + } + BOOST_CATCH(...){ + BOOST_RETHROW; + } + BOOST_CATCH_END + return 0; +} + + templateinsert(boostset->upper_bound(move_me), boost::move(move_me)); - stdset->insert(stdset->upper_bound(i), i); - //PrintContainers(boostset, stdset); - IntType move_me2(i); - boostmultiset->insert(boostmultiset->upper_bound(move_me2), boost::move(move_me2)); - stdmultiset->insert(stdmultiset->upper_bound(i), i); - //PrintContainers(boostmultiset, stdmultiset); - if(!CheckEqualContainers(boostset, stdset)){ - std::cout << "Error in boostset->insert(boostset->upper_bound(move_me), boost::move(move_me))" << std::endl; - return 1; - } - if(!CheckEqualContainers(boostmultiset, stdmultiset)){ - std::cout << "Error in boostmultiset->insert(boostmultiset->upper_bound(move_me2), boost::move(move_me2))" << std::endl; - return 1; - } + IntType move_me(i); + boostset->insert(boostset->upper_bound(move_me), boost::move(move_me)); + stdset->insert(stdset->upper_bound(i), i); + //PrintContainers(boostset, stdset); + IntType move_me2(i); + boostmultiset->insert(boostmultiset->upper_bound(move_me2), boost::move(move_me2)); + stdmultiset->insert(stdmultiset->upper_bound(i), i); + //PrintContainers(boostmultiset, stdmultiset); + if(!CheckEqualContainers(boostset, stdset)){ + std::cout << "Error in boostset->insert(boostset->upper_bound(move_me), boost::move(move_me))" << std::endl; + return 1; + } + if(!CheckEqualContainers(boostmultiset, stdmultiset)){ + std::cout << "Error in boostmultiset->insert(boostmultiset->upper_bound(move_me2), boost::move(move_me2))" << std::endl; + return 1; + } } { - IntType move_me(i); - IntType move_me2(i); - boostset->insert(boostset->lower_bound(move_me), boost::move(move_me2)); - stdset->insert(stdset->lower_bound(i), i); - //PrintContainers(boostset, stdset); - move_me2 = i; - boostmultiset->insert(boostmultiset->lower_bound(move_me2), boost::move(move_me2)); - stdmultiset->insert(stdmultiset->lower_bound(i), i); - //PrintContainers(boostmultiset, stdmultiset); - if(!CheckEqualContainers(boostset, stdset)){ - std::cout << "Error in boostset->insert(boostset->lower_bound(move_me), boost::move(move_me2))" << std::endl; - return 1; - } - if(!CheckEqualContainers(boostmultiset, stdmultiset)){ - std::cout << "Error in boostmultiset->insert(boostmultiset->lower_bound(move_me2), boost::move(move_me2))" << std::endl; - return 1; - } + IntType move_me(i); + IntType move_me2(i); + boostset->insert(boostset->lower_bound(move_me), boost::move(move_me2)); + stdset->insert(stdset->lower_bound(i), i); + //PrintContainers(boostset, stdset); + move_me2 = i; + boostmultiset->insert(boostmultiset->lower_bound(move_me2), boost::move(move_me2)); + stdmultiset->insert(stdmultiset->lower_bound(i), i); + //PrintContainers(boostmultiset, stdmultiset); + if(!CheckEqualContainers(boostset, stdset)){ + std::cout << "Error in boostset->insert(boostset->lower_bound(move_me), boost::move(move_me2))" << std::endl; + return 1; + } + if(!CheckEqualContainers(boostmultiset, stdmultiset)){ + std::cout << "Error in boostmultiset->insert(boostmultiset->lower_bound(move_me2), boost::move(move_me2))" << std::endl; + return 1; + } + set_test_rebalanceable(*boostset + , container_detail::bool_::value>()); + if(!CheckEqualContainers(boostset, stdset)){ + std::cout << "Error in boostset->rebalance()" << std::endl; + return 1; + } + set_test_rebalanceable(*boostmultiset + , container_detail::bool_::value>()); + if(!CheckEqualContainers(boostmultiset, stdmultiset)){ + std::cout << "Error in boostmultiset->rebalance()" << std::endl; + return 1; + } } } @@ -404,6 +503,97 @@ int set_test () } } + //Compare find/lower_bound/upper_bound in set + { + typename MyBoostSet::iterator bs_b = boostset->begin(); + typename MyBoostSet::iterator bs_e = boostset->end(); + typename MyStdSet::iterator ss_b = stdset->begin(); + + std::size_t i = 0; + while(bs_b != bs_e){ + ++i; + typename MyBoostSet::iterator bs_i; + typename MyStdSet::iterator ss_i; + //find + bs_i = boostset->find(*bs_b); + ss_i = stdset->find(*ss_b); + if(!CheckEqualIt(bs_i, ss_i, *boostset, *stdset)){ + return -1; + } + //lower bound + bs_i = boostset->lower_bound(*bs_b); + ss_i = stdset->lower_bound(*ss_b); + if(!CheckEqualIt(bs_i, ss_i, *boostset, *stdset)){ + return -1; + } + //upper bound + bs_i = boostset->upper_bound(*bs_b); + ss_i = stdset->upper_bound(*ss_b); + if(!CheckEqualIt(bs_i, ss_i, *boostset, *stdset)){ + return -1; + } + //equal range + std::pair bs_ip; + std::pair ss_ip; + bs_ip = boostset->equal_range(*bs_b); + ss_ip = stdset->equal_range(*ss_b); + if(!CheckEqualIt(bs_ip.first, ss_ip.first, *boostset, *stdset)){ + return -1; + } + if(!CheckEqualIt(bs_ip.second, ss_ip.second, *boostset, *stdset)){ + return -1; + } + ++bs_b; + ++ss_b; + } + } + //Compare find/lower_bound/upper_bound in multiset + { + typename MyBoostMultiSet::iterator bm_b = boostmultiset->begin(); + typename MyBoostMultiSet::iterator bm_e = boostmultiset->end(); + typename MyStdMultiSet::iterator sm_b = stdmultiset->begin(); + + while(bm_b != bm_e){ + typename MyBoostMultiSet::iterator bm_i; + typename MyStdMultiSet::iterator sm_i; + //find + bm_i = boostmultiset->find(*bm_b); + sm_i = stdmultiset->find(*sm_b); + if(!CheckEqualIt(bm_i, sm_i, *boostmultiset, *stdmultiset)){ + return -1; + } + //lower bound + bm_i = boostmultiset->lower_bound(*bm_b); + sm_i = stdmultiset->lower_bound(*sm_b); + if(!CheckEqualIt(bm_i, sm_i, *boostmultiset, *stdmultiset)){ + return -1; + } + //upper bound + bm_i = boostmultiset->upper_bound(*bm_b); + sm_i = stdmultiset->upper_bound(*sm_b); + if(!CheckEqualIt(bm_i, sm_i, *boostmultiset, *stdmultiset)){ + return -1; + } + //equal range + std::pair bm_ip; + std::pair sm_ip; + bm_ip = boostmultiset->equal_range(*bm_b); + sm_ip = stdmultiset->equal_range(*sm_b); + if(!CheckEqualIt(bm_ip.first, sm_ip.first, *boostmultiset, *stdmultiset)){ + return -1; + } + if(!CheckEqualIt(bm_ip.second, sm_ip.second, *boostmultiset, *stdmultiset)){ + return -1; + } + ++bm_b; + ++sm_b; + } + } + //Now do count exercise boostset->erase(boostset->begin(), boostset->end()); boostmultiset->erase(boostmultiset->begin(), boostmultiset->end()); @@ -431,71 +621,12 @@ int set_test () delete stdset; delete boostmultiset; delete stdmultiset; - return 0; -} -template -int set_test_copyable () -{ - typedef typename MyBoostSet::value_type IntType; - const int max = 100; - - BOOST_TRY{ - //Shared memory allocator must be always be initialized - //since it has no default constructor - MyBoostSet *boostset = new MyBoostSet; - MyStdSet *stdset = new MyStdSet; - MyBoostMultiSet *boostmultiset = new MyBoostMultiSet; - MyStdMultiSet *stdmultiset = new MyStdMultiSet; - - for(int i = 0; i < max; ++i){ - IntType move_me(i); - boostset->insert(boost::move(move_me)); - stdset->insert(i); - IntType move_me2(i); - boostmultiset->insert(boost::move(move_me2)); - stdmultiset->insert(i); - } - if(!CheckEqualContainers(boostset, stdset)) return 1; - if(!CheckEqualContainers(boostmultiset, stdmultiset)) return 1; - - { - //Now, test copy constructor - MyBoostSet boostsetcopy(*boostset); - MyStdSet stdsetcopy(*stdset); - - if(!CheckEqualContainers(&boostsetcopy, &stdsetcopy)) - return 1; - - MyBoostMultiSet boostmsetcopy(*boostmultiset); - MyStdMultiSet stdmsetcopy(*stdmultiset); - - if(!CheckEqualContainers(&boostmsetcopy, &stdmsetcopy)) - return 1; - - //And now assignment - boostsetcopy = *boostset; - stdsetcopy = *stdset; - - if(!CheckEqualContainers(&boostsetcopy, &stdsetcopy)) - return 1; - - boostmsetcopy = *boostmultiset; - stdmsetcopy = *stdmultiset; - - if(!CheckEqualContainers(&boostmsetcopy, &stdmsetcopy)) - return 1; - } - delete boostset; - delete boostmultiset; + if(set_test_copyable + (container_detail::bool_::value>())){ + return 1; } - BOOST_CATCH(...){ - BOOST_RETHROW; - } - BOOST_CATCH_END + return 0; } diff --git a/test/slist_test.cpp b/test/slist_test.cpp index 785bcc2..dbcf78b 100644 --- a/test/slist_test.cpp +++ b/test/slist_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -9,6 +9,10 @@ ////////////////////////////////////////////////////////////////////////////// #include #include +#include +#include +#include + #include #include "dummy_test_allocator.hpp" #include "movable_int.hpp" @@ -22,22 +26,32 @@ namespace boost { namespace container { //Explicit instantiation to detect compilation errors -template class boost::container::slist >; +template class boost::container::slist + < test::movable_and_copyable_int + , test::simple_allocator >; -template class boost::container::slist >; +template class boost::container::slist + < test::movable_and_copyable_int + , test::dummy_test_allocator >; -template class boost::container::slist >; +template class boost::container::slist + < test::movable_and_copyable_int + , std::allocator >; + +template class boost::container::slist + < test::movable_and_copyable_int + , allocator >; + +template class boost::container::slist + < test::movable_and_copyable_int + , adaptive_pool >; + +template class boost::container::slist + < test::movable_and_copyable_int + , node_allocator >; }} -typedef slist MyList; -typedef slist MyMoveList; -typedef slist MyCopyMoveList; -typedef slist MyCopyList; - class recursive_slist { public: @@ -52,6 +66,42 @@ void recursive_slist_test()//Test for recursive types slist recursive_list_list; } +template +struct GetAllocatorCont +{ + template + struct apply + { + typedef slist< ValueType + , typename allocator_traits + ::template portable_rebind_alloc::type + > type; + }; +}; + +template +int test_cont_variants() +{ + typedef typename GetAllocatorCont::template apply::type MyCont; + typedef typename GetAllocatorCont::template apply::type MyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyCont; + + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + if(test::list_test()) + return 1; + + return 0; +} + + int main () { recursive_slist_test(); @@ -70,19 +120,33 @@ int main () } } } - - if(test::list_test()) + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std:allocator + if(test_cont_variants< std::allocator >()){ + std::cerr << "test_cont_variants< std::allocator > failed" << std::endl; return 1; - - if(test::list_test()) + } + // boost::container::allocator + if(test_cont_variants< allocator >()){ + std::cerr << "test_cont_variants< allocator > failed" << std::endl; return 1; - - if(test::list_test()) + } + // boost::container::node_allocator + if(test_cont_variants< node_allocator >()){ + std::cerr << "test_cont_variants< node_allocator > failed" << std::endl; return 1; - - if(test::list_test()) + } + // boost::container::adaptive_pool + if(test_cont_variants< adaptive_pool >()){ + std::cerr << "test_cont_variants< adaptive_pool > failed" << std::endl; return 1; + } + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// const test::EmplaceOptions Options = (test::EmplaceOptions) (test::EMPLACE_FRONT | test::EMPLACE_AFTER | test::EMPLACE_BEFORE | test::EMPLACE_AFTER); @@ -90,6 +154,9 @@ int main () < slist, Options>()) return 1; + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// if(!boost::container::test::test_propagate_allocator()) return 1; } diff --git a/test/stable_vector_test.cpp b/test/stable_vector_test.cpp index 6390d7e..d60e022 100644 --- a/test/stable_vector_test.cpp +++ b/test/stable_vector_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -16,6 +16,10 @@ #include #include +#include +#include +#include + #include "check_equal_containers.hpp" #include "movable_int.hpp" #include "expand_bwd_test_allocator.hpp" @@ -23,6 +27,7 @@ #include "dummy_test_allocator.hpp" #include "propagate_allocator_test.hpp" #include "vector_test.hpp" +#include "default_init_test.hpp" using namespace boost::container; @@ -39,6 +44,18 @@ template class stable_vector >; +template class stable_vector + < test::movable_and_copyable_int + , allocator >; + +template class stable_vector + < test::movable_and_copyable_int + , adaptive_pool >; + +template class stable_vector + < test::movable_and_copyable_int + , node_allocator >; + namespace stable_vector_detail{ template class iterator; @@ -66,34 +83,37 @@ void recursive_vector_test()//Test for recursive types } } -bool default_init_test()//Test for default initialization +template +struct GetAllocatorCont { - typedef stable_vector > svector_t; - - const std::size_t Capacity = 100; - + template + struct apply { - test::default_init_allocator::reset_pattern(0); - svector_t v(Capacity, default_init); - svector_t::iterator it = v.begin(); - //Compare with the pattern - for(std::size_t i = 0; i != Capacity; ++i, ++it){ - if(*it != static_cast(i)) - return false; - } - } - { - test::default_init_allocator::reset_pattern(100); - svector_t v; - v.resize(Capacity, default_init); - svector_t::iterator it = v.begin(); - //Compare with the pattern - for(std::size_t i = 0; i != Capacity; ++i, ++it){ - if(*it != static_cast(i+100)) - return false; - } - } - return true; + typedef stable_vector< ValueType + , typename allocator_traits + ::template portable_rebind_alloc::type + > type; + }; +}; + +template +int test_cont_variants() +{ + typedef typename GetAllocatorCont::template apply::type MyCont; + typedef typename GetAllocatorCont::template apply::type MyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyCont; + + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + + return 0; } int main() @@ -115,33 +135,50 @@ int main() sv.resize(10); sv.resize(1); } - typedef stable_vector MyVector; - typedef stable_vector MyMoveVector; - typedef stable_vector MyCopyMoveVector; - typedef stable_vector MyCopyVector; - if(test::vector_test()) + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std:allocator + if(test_cont_variants< std::allocator >()){ + std::cerr << "test_cont_variants< std::allocator > failed" << std::endl; return 1; - - if(test::vector_test()) + } + // boost::container::allocator + if(test_cont_variants< allocator >()){ + std::cerr << "test_cont_variants< allocator > failed" << std::endl; return 1; - - if(test::vector_test()) + } + // boost::container::node_allocator + if(test_cont_variants< node_allocator >()){ + std::cerr << "test_cont_variants< node_allocator > failed" << std::endl; return 1; - - if(test::vector_test()) + } + // boost::container::adaptive_pool + if(test_cont_variants< adaptive_pool >()){ + std::cerr << "test_cont_variants< adaptive_pool > failed" << std::endl; return 1; + } + //////////////////////////////////// + // Default init test + //////////////////////////////////// if(!test::default_init_test< stable_vector > >()){ std::cerr << "Default init test failed" << std::endl; return 1; } + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// const test::EmplaceOptions Options = (test::EmplaceOptions)(test::EMPLACE_BACK | test::EMPLACE_BEFORE); if(!boost::container::test::test_emplace < stable_vector, Options>()) return 1; + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// if(!boost::container::test::test_propagate_allocator()) return 1; diff --git a/test/string_test.cpp b/test/string_test.cpp index f68482d..b44f7ef 100644 --- a/test/string_test.cpp +++ b/test/string_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -23,6 +23,7 @@ #include "expand_bwd_test_allocator.hpp" #include "expand_bwd_test_template.hpp" #include "propagate_allocator_test.hpp" +#include "default_init_test.hpp" using namespace boost::container; @@ -137,7 +138,6 @@ int string_test() const int MaxSize = 100; - //Create shared memory { BoostStringVector *boostStringVect = new BoostStringVector; StdStringVector *stdStringVect = new StdStringVector; @@ -471,12 +471,31 @@ int main() return 1; } + //////////////////////////////////// + // Backwards expansion test + //////////////////////////////////// if(!test_expand_bwd()) return 1; + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// if(!boost::container::test::test_propagate_allocator()) return 1; + //////////////////////////////////// + // Default init test + //////////////////////////////////// + if(!test::default_init_test< basic_string, test::default_init_allocator > >()){ + std::cerr << "Default init test failed" << std::endl; + return 1; + } + + if(!test::default_init_test< basic_string, test::default_init_allocator > >()){ + std::cerr << "Default init test failed" << std::endl; + return 1; + } + return 0; } diff --git a/test/tree_test.cpp b/test/tree_test.cpp deleted file mode 100644 index 60d593f..0000000 --- a/test/tree_test.cpp +++ /dev/null @@ -1,380 +0,0 @@ -////////////////////////////////////////////////////////////////////////////// -// -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost -// Software License, Version 1.0. (See accompanying file -// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// -// See http://www.boost.org/libs/container for documentation. -// -////////////////////////////////////////////////////////////////////////////// -#include -#include -#include -#include -#include "print_container.hpp" -#include "movable_int.hpp" -#include "dummy_test_allocator.hpp" -#include "set_test.hpp" -#include "map_test.hpp" -#include "propagate_allocator_test.hpp" -#include "emplace_test.hpp" - -using namespace boost::container; - -//Alias standard types -typedef std::set MyStdSet; -typedef std::multiset MyStdMultiSet; -typedef std::map MyStdMap; -typedef std::multimap MyStdMultiMap; - -//Alias non-movable types -typedef set MyBoostSet; -typedef multiset MyBoostMultiSet; -typedef map MyBoostMap; -typedef multimap MyBoostMultiMap; - -//Alias movable types -typedef set MyMovableBoostSet; -typedef multiset MyMovableBoostMultiSet; -typedef map MyMovableBoostMap; -typedef multimap MyMovableBoostMultiMap; -typedef set MyMoveCopyBoostSet; -typedef set MyCopyBoostSet; -typedef multiset MyMoveCopyBoostMultiSet; -typedef multiset MyCopyBoostMultiSet; -typedef map MyMoveCopyBoostMap; -typedef multimap MyMoveCopyBoostMultiMap; -typedef map MyCopyBoostMap; -typedef multimap MyCopyBoostMultiMap; - -namespace boost { -namespace container { - -//Explicit instantiation to detect compilation errors - -//map -template class map - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - < std::pair > - >; - -template class map - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::simple_allocator - < std::pair > - >; - -template class map - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , std::allocator - < std::pair > - >; - -//multimap -template class multimap - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - < std::pair > - >; - -template class multimap - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , test::simple_allocator - < std::pair > - >; - -template class multimap - < test::movable_and_copyable_int - , test::movable_and_copyable_int - , std::less - , std::allocator - < std::pair > - >; - -//set -template class set - < test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - >; - -template class set - < test::movable_and_copyable_int - , std::less - , test::simple_allocator - >; - -template class set - < test::movable_and_copyable_int - , std::less - , std::allocator - >; - -//multiset -template class multiset - < test::movable_and_copyable_int - , std::less - , test::dummy_test_allocator - >; - -template class multiset - < test::movable_and_copyable_int - , std::less - , test::simple_allocator - >; - -template class multiset - < test::movable_and_copyable_int - , std::less - , std::allocator - >; - -}} //boost::container - -//Test recursive structures -class recursive_set -{ -public: - recursive_set & operator=(const recursive_set &x) - { id_ = x.id_; set_ = x.set_; return *this; } - - int id_; - set set_; - friend bool operator< (const recursive_set &a, const recursive_set &b) - { return a.id_ < b.id_; } -}; - -class recursive_map -{ - public: - recursive_map & operator=(const recursive_map &x) - { id_ = x.id_; map_ = x.map_; return *this; } - - int id_; - map map_; - friend bool operator< (const recursive_map &a, const recursive_map &b) - { return a.id_ < b.id_; } -}; - -//Test recursive structures -class recursive_multiset -{ - public: - recursive_multiset & operator=(const recursive_multiset &x) - { id_ = x.id_; multiset_ = x.multiset_; return *this; } - - int id_; - multiset multiset_; - friend bool operator< (const recursive_multiset &a, const recursive_multiset &b) - { return a.id_ < b.id_; } -}; - -class recursive_multimap -{ - public: - recursive_multimap & operator=(const recursive_multimap &x) - { id_ = x.id_; multimap_ = x.multimap_; return *this; } - - int id_; - multimap multimap_; - friend bool operator< (const recursive_multimap &a, const recursive_multimap &b) - { return a.id_ < b.id_; } -}; - -template -void test_move() -{ - //Now test move semantics - C original; - original.emplace(); - C move_ctor(boost::move(original)); - C move_assign; - move_assign.emplace(); - move_assign = boost::move(move_ctor); - move_assign.swap(original); -} - -template -class tree_propagate_test_wrapper - : public container_detail::rbtree, std::less, A> -{ - BOOST_COPYABLE_AND_MOVABLE(tree_propagate_test_wrapper) - typedef container_detail::rbtree, std::less, A> Base; - public: - tree_propagate_test_wrapper() - : Base() - {} - - tree_propagate_test_wrapper(const tree_propagate_test_wrapper &x) - : Base(x) - {} - - tree_propagate_test_wrapper(BOOST_RV_REF(tree_propagate_test_wrapper) x) - : Base(boost::move(static_cast(x))) - {} - - tree_propagate_test_wrapper &operator=(BOOST_COPY_ASSIGN_REF(tree_propagate_test_wrapper) x) - { this->Base::operator=(x); return *this; } - - tree_propagate_test_wrapper &operator=(BOOST_RV_REF(tree_propagate_test_wrapper) x) - { this->Base::operator=(boost::move(static_cast(x))); return *this; } - - void swap(tree_propagate_test_wrapper &x) - { this->Base::swap(x); } -}; - -int main () -{ - //Recursive container instantiation - { - set set_; - multiset multiset_; - map map_; - multimap multimap_; - } - //Allocator argument container - { - set set_((std::allocator())); - multiset multiset_((std::allocator())); - map map_((std::allocator >())); - multimap multimap_((std::allocator >())); - } - //Now test move semantics - { - test_move >(); - test_move >(); - test_move >(); - test_move >(); - } - - - if(0 != test::set_test()){ - return 1; - } - - if(0 != test::set_test_copyable()){ - return 1; - } - - if(0 != test::set_test()){ - return 1; - } - - if(0 != test::set_test()){ - return 1; - } - - if(0 != test::set_test_copyable()){ - return 1; - } - - if(0 != test::set_test()){ - return 1; - } - - if(0 != test::set_test_copyable()){ - return 1; - } - - if (0 != test::map_test()){ - return 1; - } - - if(0 != test::map_test_copyable()){ - return 1; - } - - if (0 != test::map_test()){ - return 1; - } - - if (0 != test::map_test()){ - return 1; - } - - if (0 != test::map_test_copyable()){ - return 1; - } - - if (0 != test::map_test()){ - return 1; - } - - if (0 != test::map_test_copyable()){ - return 1; - } - - const test::EmplaceOptions SetOptions = (test::EmplaceOptions)(test::EMPLACE_HINT | test::EMPLACE_ASSOC); - if(!boost::container::test::test_emplace, SetOptions>()) - return 1; - if(!boost::container::test::test_emplace, SetOptions>()) - return 1; - const test::EmplaceOptions MapOptions = (test::EmplaceOptions)(test::EMPLACE_HINT_PAIR | test::EMPLACE_ASSOC_PAIR); - if(!boost::container::test::test_emplace, MapOptions>()) - return 1; - if(!boost::container::test::test_emplace, MapOptions>()) - return 1; - if(!boost::container::test::test_propagate_allocator()) - return 1; - - return 0; -} - -#include diff --git a/test/vector_test.cpp b/test/vector_test.cpp index 80417c3..ab7a4a4 100644 --- a/test/vector_test.cpp +++ b/test/vector_test.cpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -15,6 +15,10 @@ #include #include +#include +#include +#include + #include #include "check_equal_containers.hpp" #include "movable_int.hpp" @@ -23,6 +27,7 @@ #include "dummy_test_allocator.hpp" #include "propagate_allocator_test.hpp" #include "vector_test.hpp" +#include "default_init_test.hpp" using namespace boost::container; @@ -30,14 +35,29 @@ namespace boost { namespace container { //Explicit instantiation to detect compilation errors -template class boost::container::vector >; +template class boost::container::vector + < test::movable_and_copyable_int + , test::simple_allocator >; -template class boost::container::vector >; +template class boost::container::vector + < test::movable_and_copyable_int + , test::dummy_test_allocator >; -template class boost::container::vector >; +template class boost::container::vector + < test::movable_and_copyable_int + , std::allocator >; + +template class boost::container::vector + < test::movable_and_copyable_int + , allocator >; + +template class boost::container::vector + < test::movable_and_copyable_int + , adaptive_pool >; + +template class boost::container::vector + < test::movable_and_copyable_int + , node_allocator >; namespace container_detail { @@ -104,6 +124,39 @@ enum Test zero, one, two, three, four, five, six }; +template +struct GetAllocatorCont +{ + template + struct apply + { + typedef vector< ValueType + , typename allocator_traits + ::template portable_rebind_alloc::type + > type; + }; +}; + +template +int test_cont_variants() +{ + typedef typename GetAllocatorCont::template apply::type MyCont; + typedef typename GetAllocatorCont::template apply::type MyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyMoveCont; + typedef typename GetAllocatorCont::template apply::type MyCopyCont; + + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + if(test::vector_test()) + return 1; + + return 0; +} + int main() { { @@ -135,38 +188,65 @@ int main() move_assign = boost::move(move_ctor); move_assign.swap(original); } - typedef vector MyVector; - typedef vector MyMoveVector; - typedef vector MyCopyMoveVector; - typedef vector MyCopyVector; - typedef vector MyEnumVector; - if(test::vector_test()) + //////////////////////////////////// + // Testing allocator implementations + //////////////////////////////////// + // std:allocator + if(test_cont_variants< std::allocator >()){ + std::cerr << "test_cont_variants< std::allocator > failed" << std::endl; return 1; - if(test::vector_test()) + } + // boost::container::allocator + if(test_cont_variants< allocator >()){ + std::cerr << "test_cont_variants< allocator > failed" << std::endl; return 1; - if(test::vector_test()) + } + // boost::container::node_allocator + if(test_cont_variants< node_allocator >()){ + std::cerr << "test_cont_variants< node_allocator > failed" << std::endl; return 1; - if(test::vector_test()) + } + // boost::container::adaptive_pool + if(test_cont_variants< adaptive_pool >()){ + std::cerr << "test_cont_variants< adaptive_pool > failed" << std::endl; return 1; + } + + { + typedef vector > MyEnumCont; + MyEnumCont v; + Test t; + v.push_back(t); + v.push_back(::boost::move(t)); + v.push_back(Test()); + } + + //////////////////////////////////// + // Backwards expansion test + //////////////////////////////////// if(test_expand_bwd()) return 1; + + //////////////////////////////////// + // Default init test + //////////////////////////////////// if(!test::default_init_test< vector > >()){ std::cerr << "Default init test failed" << std::endl; return 1; } - MyEnumVector v; - Test t; - v.push_back(t); - v.push_back(::boost::move(t)); - v.push_back(Test()); - + //////////////////////////////////// + // Emplace testing + //////////////////////////////////// const test::EmplaceOptions Options = (test::EmplaceOptions)(test::EMPLACE_BACK | test::EMPLACE_BEFORE); if(!boost::container::test::test_emplace< vector, Options>()){ return 1; } + //////////////////////////////////// + // Allocator propagation testing + //////////////////////////////////// if(!boost::container::test::test_propagate_allocator()){ return 1; } diff --git a/test/vector_test.hpp b/test/vector_test.hpp index 3dc2401..c3e92e6 100644 --- a/test/vector_test.hpp +++ b/test/vector_test.hpp @@ -1,6 +1,6 @@ ////////////////////////////////////////////////////////////////////////////// // -// (C) Copyright Ion Gaztanaga 2004-2012. Distributed under the Boost +// (C) Copyright Ion Gaztanaga 2004-2013. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // @@ -38,123 +38,6 @@ namespace boost{ namespace container { namespace test{ -// -template -class default_init_allocator_base -{ - protected: - static unsigned char s_pattern; - static bool s_ascending; - - public: - static void reset_pattern(unsigned char value) - { s_pattern = value; } - - static void set_ascending(bool enable) - { s_ascending = enable; } -}; - -template -unsigned char default_init_allocator_base::s_pattern = 0u; - -template -bool default_init_allocator_base::s_ascending = true; - -template -class default_init_allocator - : public default_init_allocator_base<0> -{ - typedef default_init_allocator_base<0> base_t; - public: - typedef T value_type; - - default_init_allocator() - {} - - template - default_init_allocator(default_init_allocator) - {} - - T* allocate(std::size_t n) - { - //Initialize memory to a pattern - T *const p = ::new T[n]; - unsigned char *puc_raw = reinterpret_cast(p); - std::size_t max = sizeof(T)*n; - if(base_t::s_ascending){ - for(std::size_t i = 0; i != max; ++i){ - puc_raw[i] = static_cast(s_pattern++); - } - } - else{ - for(std::size_t i = 0; i != max; ++i){ - puc_raw[i] = static_cast(s_pattern--); - } - } - return p; - } - - void deallocate(T *p, std::size_t) - { delete[] p; } -}; - -template -inline bool check_ascending_byte_pattern(const T&t) -{ - const unsigned char *pch = &reinterpret_cast(t); - const std::size_t max = sizeof(T); - for(std::size_t i = 1; i != max; ++i){ - if( (pch[i-1] != ((unsigned char)(pch[i]-1u))) ){ - return false; - } - } - return true; -} - -template -inline bool check_descending_byte_pattern(const T&t) -{ - const unsigned char *pch = &reinterpret_cast(t); - const std::size_t max = sizeof(T); - for(std::size_t i = 1; i != max; ++i){ - if( (pch[i-1] != ((unsigned char)(pch[i]+1u))) ){ - return false; - } - } - return true; -} - -template -bool default_init_test()//Test for default initialization -{ - const std::size_t Capacity = 100; - - { - test::default_init_allocator::reset_pattern(0); - test::default_init_allocator::set_ascending(true); - IntDefaultInitAllocVector v(Capacity, default_init); - typename IntDefaultInitAllocVector::iterator it = v.begin(); - //Compare with the pattern - for(std::size_t i = 0; i != Capacity; ++i, ++it){ - if(!test::check_ascending_byte_pattern(*it)) - return false; - } - } - { - test::default_init_allocator::reset_pattern(100); - test::default_init_allocator::set_ascending(false); - IntDefaultInitAllocVector v; - v.resize(Capacity, default_init); - typename IntDefaultInitAllocVector::iterator it = v.begin(); - //Compare with the pattern - for(std::size_t i = 0; i != Capacity; ++i, ++it){ - if(!test::check_descending_byte_pattern(*it)) - return false; - } - } - return true; -} - template bool vector_copyable_only(V1 *, V2 *, boost::container::container_detail::false_type) {