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 - iterating backwards free slots are filled with
  corresponding element
* rotating - rotating the elements in cycles of pre-occupied slots.

After the source element is moved, then the slot is freed if it lies
the current slot. Otherwise, if we moved from already visited slot,
we resolve the chain by moving the next element into that slot, until
we reach position prior the current slot. This guarantees that after
compacting we are left only with cycles between pre-occupied slots.

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/version.cc: New test.
---
 libstdc++-v3/include/bits/hive.h              | 167 +++++++++++++++++-
 libstdc++-v3/include/bits/version.def         |   3 +-
 libstdc++-v3/include/bits/version.h           |   3 +-
 .../testsuite/23_containers/hive/sort.cc      | 100 +++++++++++
 .../testsuite/23_containers/hive/version.cc   |  10 ++
 5 files changed, 279 insertions(+), 4 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 9f1b1d2165b..d13d6e3ac20 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)
@@ -1747,7 +1755,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
@@ -2309,6 +2319,161 @@ template<typename _Tp, typename _Alloc>
       erase_if(hive<_Up, _OAlloc>& __cont, _Predicate __pred);
   };
 
+  template<class _Tp, class _Alloc>
+    template<class _Compare>
+      void
+      hive<_Tp, _Alloc>::sort(_Compare __comp)
+      {
+       if (empty())
+         return;
+
+       struct _Indexed { size_t _M_pos; _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); });
+
+            // Firstly, compact all the elements that can be moved into their 
position.
+            // If element we moved from was already visited, we apply the part 
of chain
+            // inside already visited position, until we reach yet-to-be 
visited element.
+            _BlockT* __dstblock = _M_blocks._M_sent._M_prev;
+            size_t __dstpos = __dstblock->_M_capacity();
+            for (size_t __pos = _M_size; __pos > 0; )
+              {
+                --__pos;
+                if (__indirect[__pos]._M_pos == __pos)
+                  continue;
+
+                --__dstpos;
+                if (!__dstblock->_M_occupied(__dstpos))
+                  {
+                    _AllocT::construct(_M_blocks._M_alloc, 
__dstblock->_M_elems + __dstpos,
+                                       std::move(*__indirect[__pos]._M_ptr));
+                    __dstblock->_M_occupancy.set(__dstpos);
+                    if (__dstblock->_M_full())
+                      _M_blocks._M_unlink_free(__dstblock);
+                    ++_M_size;
+
+                    // Erases moved-from state designed by _M_entry on 
destruction,
+                    // guaranteeing that size does not change due of exception.
+                    struct _Eraser
+                    {
+                      hive*    _M_self;
+                      _Indexed _M_entry;
+
+                      void
+                      _M_move_to(_Indexed __next)
+                      {
+                        *_M_entry._M_ptr = std::move(*__next._M_ptr);
+                        _M_entry = __next;
+                      }
+
+                      ~_Eraser()
+                      {
+                        size_t __pos = _M_entry._M_ptr - 
_M_entry._M_block->_M_elems;
+                        _M_self->erase(const_iterator(_M_entry._M_block, 
__pos));
+                      }
+                    };
+                    _Eraser __eraser{this, __indirect[__pos]};
+
+                    size_t __freepos = std::exchange(__indirect[__pos]._M_pos, 
__pos);
+                    while (__freepos > __pos)
+                      {
+                        __eraser._M_move_to(__indirect[__freepos]);
+                        __freepos = 
std::exchange(__indirect[__freepos]._M_pos, __freepos);
+                      }
+
+                    // Erase element and free up slot will be visiting in 
future
+                  }
+
+                if (__dstpos == 0)
+                  {
+                    __dstblock = __dstblock->_M_prev;
+                    __dstpos = __dstblock->_M_capacity();
+                  }
+              }
+
+            // 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_pos == __pos)
+                  continue;
+
+                _Tp __aside(std::move(*__it));
+                _Tp* __dest = __it.operator->();
+                size_t __nextpos = __pos;
+                do
+                  {
+                    *__dest = std::move(*__indirect[__nextpos]._M_ptr);
+                    __dest = __indirect[__nextpos]._M_ptr;
+                    __nextpos = std::exchange(__indirect[__nextpos]._M_pos, 
__nextpos);
+                  }
+                while (__nextpos != __pos);
+                *__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..a92d8ba714b
--- /dev/null
+++ b/libstdc++-v3/testsuite/23_containers/hive/sort.cc
@@ -0,0 +1,100 @@
+// { 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)
+{
+  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);
+  test_sort(h1, comp);
+
+  std::hive<int> h2;
+  h2.reserve(300);
+  h2.insert_range(vals);
+  test_sort(h2, comp);
+
+  std::hive<int> h3(std::from_range, vals);
+  for (auto it = h3.begin(); it != h3.end(); )
+    it = h3.erase(++it);
+  test_sort(h3, comp);
+
+  std::hive<int> h4(std::from_range, vals);
+  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);
+  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()
+{
+  test_comp<T>(std::less<T>{});
+  test_comp<T>(std::greater<T>{});
+}
+
+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; }
+};
+
+int main()
+{
+  test_type<int>();
+  test_type<Wrap<false>>();
+  test_type<Wrap<true>>();
+  test_type<Wrap<true, false>>();
+  test_type<Wrap<false, true>>();
+}
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

Reply via email to