This patch implements sort member for std::hive and thus completes
the implementation of P0447R28, and thus expose __cpp_lib_hive.
The algorithm is implemented by sorting the pointers to elements
(_Indexed) in separately allocated temporary buffer, and then
shuffling the elements in place. The latter is implemented in two
steps:
* compacting - filling free slots are filled with corresponding element,
and impacted cycle is resolved
* rotating - rotating the elements in cycles of pre-occupied slots.
During compating, after the initial element is moved, the remaining
element in cycle are shifted by one, and both index and pointers are
updated. Update of pointers is necessary to guarantee that the elements
can be later moved in empty-slot in later iteration, while update of
index prevent repeated shifts.
As sorting requires allocation of the buffer that fits _Indexed (size_t
plus two pointers), the elements that have smaller size are instead
moved to the buffer, and sorted directly. To preserve exception safety
we limit that optimization to types that are nothrow move-constructible,
and thus can be reinserted into hive, in case if exception is thrown
during sorting. For similar reason, we do not apply the optimization
if allocator overides move-construction or destruction of elements.
libstdc++-v3/ChangeLog:
* include/bits/hive.h (hive::sort): Define.
* include/bits/version.def (hive): Updated to final
value and expose the name,
* include/bits/version.h: Regenerate.
* testsuite/23_containers/hive/sort.cc: New test.
* testsuite/23_containers/hive/throws.cc: Add tests
for sort.
* testsuite/23_containers/hive/version.cc: New test.
---
v4 fully resolves cycles and updates the elements pointers in the
compacting loop, addressing the issue shared by Patrick.
Aslo add test covering cases of throwing moves.
Tested on x86_64-linux. OK for trunk?
libstdc++-v3/include/bits/hive.h | 169 +++++++++++++++++-
libstdc++-v3/include/bits/version.def | 3 +-
libstdc++-v3/include/bits/version.h | 3 +-
.../testsuite/23_containers/hive/sort.cc | 111 ++++++++++++
.../testsuite/23_containers/hive/throws.cc | 78 ++++++++
.../testsuite/23_containers/hive/version.cc | 10 ++
6 files changed, 368 insertions(+), 6 deletions(-)
create mode 100644 libstdc++-v3/testsuite/23_containers/hive/sort.cc
create mode 100644 libstdc++-v3/testsuite/23_containers/hive/version.cc
diff --git a/libstdc++-v3/include/bits/hive.h b/libstdc++-v3/include/bits/hive.h
index a9db8450768..8ee8de92c35 100644
--- a/libstdc++-v3/include/bits/hive.h
+++ b/libstdc++-v3/include/bits/hive.h
@@ -33,6 +33,7 @@
#ifdef __glibcxx_hive // C++ >= 26
#include <bits/align.h>
+#include <bits/stl_function.h> // less<void>, equal_to<void>
#include <bits/stl_iterator_base_funcs.h>
#include <bits/stdexcept_throw.h>
#include <bits/ranges_util.h> // ranges::subrange, _Repeat_iterator
@@ -41,6 +42,13 @@
#include <initializer_list>
#include <span>
+// TODO, for sort, move to separate file?
+#include <bits/stl_pair.h>
+#include <bits/unique_ptr.h>
+#include <bits/stl_uninitialized.h>
+#include <algorithm>
+#include <utility>
+
#include <debug/assertions.h>
namespace std _GLIBCXX_VISIBILITY(default)
@@ -664,7 +672,7 @@ namespace __hive
if (__alloc_max >= __bistack_max +
_BlockT::_S_extra_elems(__bistack_max))
return hive_limits(2, __bistack_max);
- const size_t __block_bytes = (alignof(_BlockT) > alignof(_Tp))
+ const size_t __block_bytes = (alignof(_BlockT) > alignof(_Tp))
? sizeof(_BlockT) + alignof(_BlockT) -
alignof(_Tp)
: sizeof(_BlockT);
const size_t __chunk_bytes = sizeof(_Bitstack::_ChunkT);
@@ -675,7 +683,7 @@ namespace __hive
size_t __rem_bytes = __alloc_max * sizeof(_Tp) - __block_bytes;
// additional chunk on first level is required for each 64 elements,
// and level two chunk for each 2048 (2b for each 64bit chunk).
- size_t __max_elems = (2048 * __rem_bytes) / (2048 * sizeof(_Tp) +
33 * __chunk_bytes);
+ size_t __max_elems = (2048 * __rem_bytes) / (2048 * sizeof(_Tp) +
33 * __chunk_bytes);
if (__max_elems <= 64)
// only one chunk in level one, no level two
__max_elems = (__rem_bytes - __chunk_bytes) / sizeof(_Tp);
@@ -1748,7 +1756,9 @@ template<typename _Tp, typename _Alloc>
return _M_erase_if(__pred);
}
- // TODO: sort
+
+ template<class _Compare = less<_Tp>>
+ void sort(_Compare comp = _Compare());
iterator
get_iterator(const_pointer __ptr) noexcept
@@ -2330,6 +2340,159 @@ template<typename _Tp, typename _Alloc>
hive(from_range_t, _Rg&&, hive_limits, _Alloc = _Alloc())
-> hive<ranges::range_value_t<_Rg>, _Alloc>;
+ template<class _Tp, class _Alloc>
+ template<class _Compare>
+ void
+ hive<_Tp, _Alloc>::sort(_Compare __comp)
+ {
+ if (empty())
+ return;
+
+ struct _Indexed { size_t _M_idx; _BlockT* _M_block; _Tp* _M_ptr; };
+ // For small objects copy values to temporary buffer and sort them.
+ // Limit to allocators that do not override destroy or construct,
+ // so the information about the source of allocation cannot be
+ // passed to elements.
+ if constexpr (requires { requires (sizeof(_Tp) <= sizeof(_Indexed))
+ && is_nothrow_move_constructible_v<_Tp>
+ && is_same_v<_Tp*, typename _AllocT::pointer>
+ && !requires (_Tp* __p) { _M_blocks._M_alloc.destroy(__p); }
+ && !requires (_Tp* __p, _Tp& __obj)
+ { _M_blocks._M_alloc.construct(__p, std::move(__obj)); };
+ })
+ {
+ struct _Reinsert
+ {
+ hive* _M_self;
+ std::span<_Tp> _M_buffer;
+
+ _Reinsert(hive* __self)
+ : _M_self(__self),
+ _M_buffer(allocator<_Tp>{}.allocate(__self->size()),
__self->size())
+ {
+ std::uninitialized_move(_M_self->begin(), _M_self->end(),
+ _M_buffer.data());
+ // Use only move constructors if assigment can throw.
+ if constexpr (!is_nothrow_move_assignable_v<_Tp>)
+ _M_self->clear();
+ }
+
+ ~_Reinsert()
+ {
+ _M_self->assign(make_move_iterator(_M_buffer.begin()),
+ make_move_iterator(_M_buffer.end()));
+ std::destroy(_M_buffer.begin(), _M_buffer.end());
+ allocator<_Tp>{}.deallocate(_M_buffer.data(), _M_buffer.size());
+ }
+ };
+
+ _Reinsert __reinsert(this);
+ std::ranges::sort(__reinsert._M_buffer, __comp);
+ }
+ else
+ {
+ unique_ptr<_Indexed[]> __indirect(new _Indexed[_M_size]);
+
+ size_t __pos = 0;
+ for (_BlockT* __block = _M_blocks._M_first;
+ !__block->_M_sentinel(); __block = __block->_M_next)
+ {
+ size_t __bpos = 0;
+ while (__bpos != __block->_M_capacity())
+ if (__block->_M_occupied(__bpos))
+ {
+ __indirect[__pos] = _Indexed{__pos, __block,
__block->_M_elems + __bpos};
+ ++__pos; ++__bpos;
+ }
+ else
+ __bpos += __block->_M_free_count(__bpos);
+ }
+
+ std::sort(__indirect.get(), __indirect.get() + _M_size,
+ [&](_Indexed __lhs, _Indexed __rhs)
+ { return __comp(*__lhs._M_ptr, *__rhs._M_ptr); });
+
+ // Erases moved-from state designated by _M_entry on destruction,
+ // guaranteeing that size does not change due to exception.
+ struct _Eraser
+ {
+ hive* _M_self;
+ _Indexed _M_entry;
+
+ ~_Eraser()
+ {
+ size_t __pos = _M_entry._M_ptr - _M_entry._M_block->_M_elems;
+ _M_self->erase(const_iterator(_M_entry._M_block, __pos));
+ }
+ };
+
+ // Firstly, compact all the elements by filling the empty slots.
+ // The remaining parts of the chain are resolved.
+ _BlockT* __dstblock = _M_blocks._M_first;
+ size_t __dstpos = 0;
+ for (size_t __idx = 0; __idx < _M_size; ++__idx, ++__dstpos)
+ {
+ if (__dstpos == __dstblock->_M_capacity())
+ {
+ __dstblock = __dstblock->_M_next;
+ __dstpos = 0;
+ }
+
+ if (__dstblock->_M_occupied(__dstpos))
+ continue;
+
+ _AllocT::construct(_M_blocks._M_alloc, __dstblock->_M_elems +
__dstpos,
+ std::move(*__indirect[__idx]._M_ptr));
+ __dstblock->_M_occupancy.set(__dstpos);
+ ++_M_size;
+ if (__dstblock->_M_full())
+ _M_blocks._M_unlink_free(__dstblock);
+
+ _Eraser __eraser{this, __indirect[__idx]};
+
+ // Move remaining elements in the chain, and update pointers in
+ // entries, so they can be moved-from.
+ size_t __freeidx = std::exchange(__indirect[__idx]._M_idx,
__idx);
+ while (__freeidx != __idx)
+ {
+ const _Indexed __prev = __eraser._M_entry;
+ _Indexed& __entry = __indirect[__freeidx];
+
+ // Move the element to previous entry
+ *__prev._M_ptr = std::move(*__entry._M_ptr);
+ __eraser._M_entry = __entry;
+
+ // Update the entry as resolved and adjust pointer, so it
+ // can be moved from later if needed.
+ __freeidx = std::exchange(__entry._M_idx, __freeidx);
+ __entry._M_block = __prev._M_block;
+ __entry._M_ptr = __prev._M_ptr;
+ }
+ }
+
+ // Only circles between previously occupied slots remain, rotate
them.
+ iterator __it = begin();
+ for (size_t __pos = 0; __pos < _M_size; ++__pos, ++__it)
+ {
+ if (__indirect[__pos]._M_idx == __pos)
+ continue;
+
+ _Tp __aside(std::move(*__it));
+ _Tp* __dest = __it.operator->();
+ size_t __nextpos = __pos;
+ while (__indirect[__nextpos]._M_idx != __pos)
+ {
+ *__dest = std::move(*__indirect[__nextpos]._M_ptr);
+ __dest = __indirect[__nextpos]._M_ptr;
+ __nextpos = std::exchange(__indirect[__nextpos]._M_idx,
__nextpos);
+ }
+ __indirect[__nextpos]._M_idx = __nextpos;
+ *__dest = std::move(__aside);
+ }
+ }
+ }
+
+
template<class _Tp, class _Alloc>
void swap(hive<_Tp, _Alloc>& __lhs, hive<_Tp, _Alloc>& __rhs)
noexcept(noexcept(__lhs.swap(__rhs)))
diff --git a/libstdc++-v3/include/bits/version.def
b/libstdc++-v3/include/bits/version.def
index 992220adaf8..c17cd6f6cc4 100644
--- a/libstdc++-v3/include/bits/version.def
+++ b/libstdc++-v3/include/bits/version.def
@@ -2552,9 +2552,8 @@ ftms = {
ftms = {
name = hive;
values = {
- v = 1; // set to 202502 when implemented
+ v = 202502;
cxxmin = 26;
- no_stdname = true;
};
};
diff --git a/libstdc++-v3/include/bits/version.h
b/libstdc++-v3/include/bits/version.h
index 1a91ced3e5f..16a8b7abf63 100644
--- a/libstdc++-v3/include/bits/version.h
+++ b/libstdc++-v3/include/bits/version.h
@@ -2798,8 +2798,9 @@
#if !defined(__cpp_lib_hive)
# if (__cplusplus > 202302L)
-# define __glibcxx_hive 1L
+# define __glibcxx_hive 202502L
# if defined(__glibcxx_want_all) || defined(__glibcxx_want_hive)
+# define __cpp_lib_hive 202502L
# endif
# endif
#endif /* !defined(__cpp_lib_hive) */
diff --git a/libstdc++-v3/testsuite/23_containers/hive/sort.cc
b/libstdc++-v3/testsuite/23_containers/hive/sort.cc
new file mode 100644
index 00000000000..392bc6dc5df
--- /dev/null
+++ b/libstdc++-v3/testsuite/23_containers/hive/sort.cc
@@ -0,0 +1,111 @@
+// { dg-do run { target c++26 } }
+
+#include <hive>
+
+#include <algorithm>
+#include <vector>
+#include <testsuite_hooks.h>
+
+template<typename T, typename Comp>
+void test_sort(std::hive<T>& hive, const Comp& comp)
+{
+ std::vector<int> expected(std::from_range, hive);
+ std::ranges::sort(expected, comp);
+
+ hive.sort(comp);
+ VERIFY( expected.size() == hive.size() );
+ VERIFY( std::ranges::equal(expected, hive) );
+}
+
+template<typename T, typename Comp>
+void test_comp(const Comp& comp, std::hive_limits hl)
+{
+ const int vals[] =
+ {
+ 635, 416, 959, 593, 8, 348, 639, 811, 858, 998, 393, 895, 625, 161, 706,
+ 308, 747, 562, 381, 588, 60, 935, 141, 58, 127, 255, 71, 692, 420, 830,
+ 703, 638, 557, 625, 235, 527, 326, 984, 718, 277, 879, 711, 121, 397, 461,
+ 956, 622, 799, 432, 437, 858, 314, 215, 782, 845, 814, 934, 569, 853, 633,
+ 16, 96, 515, 707, 459, 940, 217, 616, 579, 225, 368, 205, 749, 620, 750,
+ 154, 703, 511, 681, 66, 207, 939, 621, 275, 438, 521, 828, 501, 654, 35,
+ 223, 241, 684, 863, 403, 202, 849, 827, 930, 92
+ };
+
+ std::hive<int> h1(std::from_range, vals, hl);
+ test_sort(h1, comp);
+
+ std::hive<int> h2(hl);
+ h2.reserve(300);
+ h2.insert_range(vals);
+ test_sort(h2, comp);
+
+ std::hive<int> h3(std::from_range, vals, hl);
+ for (auto it = h3.begin(); it != h3.end(); )
+ it = h3.erase(++it);
+ test_sort(h3, comp);
+
+ std::hive<int> h4(std::from_range, vals, hl);
+ for (auto it = h4.begin(); it != h4.end(); std::advance(it, 10))
+ it = h4.erase(it, std::next(it, 10));
+ test_sort(h4, comp);
+
+ std::hive<int> h5(50, -3, hl);
+ h5.erase(std::next(h5.begin(), 42), std::next(h5.begin(), 48));
+ h5.erase(std::next(h5.begin(), 33), std::next(h5.begin(), 35));
+ h5.erase(std::next(h5.begin(), 36), std::next(h5.begin(), 38));
+ h5.erase(std::next(h5.begin(), 24), std::next(h5.begin(), 28));
+ h5.erase(std::next(h5.begin(), 12), std::next(h5.begin(), 19));
+ h5.erase(std::next(h5.begin()), std::next(h5.begin(), 5));
+ test_sort(h5, comp);
+}
+
+template<typename T>
+void test_type(std::hive_limits hl)
+{
+ test_comp<T>(std::less<T>{}, hl);
+ test_comp<T>(std::greater<T>{}, hl);
+}
+
+template<bool NoexMoveCtor = true, bool NoexMoveAssign = NoexMoveCtor>
+struct Wrap
+{
+ constexpr Wrap(int p) noexcept
+ : x(p) { }
+
+ Wrap(const Wrap&) noexcept(false) = default;
+ Wrap(Wrap&&) noexcept(NoexMoveCtor) = default;
+
+ Wrap& operator=(const Wrap&) noexcept(false) = default;
+ Wrap& operator=(Wrap&&) noexcept(NoexMoveCtor) = default;
+
+ int x;
+
+ friend bool operator==(const Wrap&, const Wrap&) = default;
+ friend auto operator<=>(const Wrap&, const Wrap&) = default;
+
+ friend constexpr bool operator==(const Wrap& lhs, int rhs) noexcept
+ { return lhs.x == rhs; }
+
+ friend constexpr auto operator<=>(const Wrap& lhs, int rhs) noexcept
+ { return lhs.x <=> rhs; }
+};
+
+void test_limits(std::hive_limits hl)
+{
+ test_type<int>(hl);
+ test_type<Wrap<false>>(hl);
+ test_type<Wrap<true>>(hl);
+ test_type<Wrap<true, false>>(hl);
+ test_type<Wrap<false, true>>(hl);
+}
+
+int main()
+{
+ const std::hive_limits def =
std::hive<int>::block_capacity_default_limits();
+ test_limits(def);
+ test_limits(std::hive_limits(2, def.max));
+ test_limits(std::hive_limits(20, 50));
+ test_limits(std::hive_limits(5, 10));
+ test_limits(std::hive_limits(10, 10));
+ test_limits(std::hive_limits(2, 4));
+}
diff --git a/libstdc++-v3/testsuite/23_containers/hive/throws.cc
b/libstdc++-v3/testsuite/23_containers/hive/throws.cc
index cbb24442536..91098cd5365 100644
--- a/libstdc++-v3/testsuite/23_containers/hive/throws.cc
+++ b/libstdc++-v3/testsuite/23_containers/hive/throws.cc
@@ -58,6 +58,9 @@ struct Thrower
friend constexpr bool
operator==(const Thrower&, const Thrower&) = default;
+ friend constexpr auto
+ operator<=>(const Thrower&, const Thrower&) = default;
+
friend constexpr bool
operator==(const Thrower& nm, int y)
{ return nm.x == y; }
@@ -345,9 +348,84 @@ test_reshape()
Thrower::resetCounters();
}
+void
+test_sort()
+{
+ using il = std::initializer_list<int>;
+ auto comp = [](const Thrower& l, const Thrower& r) { return l.x < r.x; };
+ auto make = [] {
+ Thrower::resetCounters();
+ std::hive<Thrower> h({3, 2, 4, 9, 0, 1}, std::hive_limits(6, 6));
+ h.erase(std::next(h.begin(), 3));
+ Thrower::resetCounters();
+ return h;
+ };
+
+ {
+ auto h = make();
+ Thrower::throwAfter = 0; // Constructing in empty block
+ try {
+ h.sort();
+ VERIFY( false );
+ } catch (const Thrower::Exception&) {
+ }
+ VERIFY( std::ranges::equal(h, il{3, 2, 4, 0, 1}) );
+ VERIFY( Thrower::copy == 0 );
+ VERIFY( Thrower::destroy == 0 );
+ }
+
+ {
+ auto h = make();
+ Thrower::throwAfter = 1; // after gap, slot 0: [_, 2, 4, 3, 0, 1]
+ try {
+ h.sort();
+ VERIFY( false );
+ } catch (const Thrower::Exception&) {
+ }
+ VERIFY( h.size() == 5 );
+ VERIFY( std::ranges::equal(h, il{2, 4, 3, 0, 1}) );
+ VERIFY( Thrower::copy == 1 );
+ VERIFY( Thrower::assign == 0 );
+ VERIFY( Thrower::destroy == 1 );
+ }
+
+ {
+ auto h = make();
+ Thrower::throwAfter = 2; // cycle finished: [0, 2, _, 3, 4, 1]
+ try {
+ h.sort();
+ VERIFY( false );
+ } catch (const Thrower::Exception&) {
+ }
+ VERIFY( h.size() == 5 );
+ VERIFY( std::ranges::equal(h, il{0, 2, 4, 3, 1}) );
+ VERIFY( Thrower::copy == 1 );
+ VERIFY( Thrower::assign == 1 );
+ VERIFY( Thrower::destroy == 1 );
+ }
+
+ {
+ auto h = make();
+ Thrower::throwAfter = 3; // moved four: [0, 2, 3, _, 4, 1]
+ try {
+ h.sort();
+ VERIFY( false );
+ } catch (const Thrower::Exception&) {
+ }
+ VERIFY( h.size() == 5 );
+ VERIFY( std::ranges::equal(h, il{0, 2, 3, 4, 1}) );
+ VERIFY( Thrower::copy == 2 );
+ VERIFY( Thrower::assign == 1 );
+ VERIFY( Thrower::destroy == 2 );
+ }
+
+ Thrower::resetCounters();
+}
+
int main()
{
test_inserts();
test_shrink_to_fit();
test_reshape();
+ test_sort();
}
diff --git a/libstdc++-v3/testsuite/23_containers/hive/version.cc
b/libstdc++-v3/testsuite/23_containers/hive/version.cc
new file mode 100644
index 00000000000..c6cdd93f33f
--- /dev/null
+++ b/libstdc++-v3/testsuite/23_containers/hive/version.cc
@@ -0,0 +1,10 @@
+// { dg-do preprocess { target c++26 } }
+// { dg-add-options no_pch }
+
+#include <hive>
+
+#ifndef __cpp_lib_hive
+# error "Feature-test macro __cpp_lib_hive is not present <hive>"
+#elif __cpp_lib_hive != 202502L
+# error "Feature-test macro __cpp_lib_hive has wrong value in <hive>"
+#endif
--
2.56.1