[libc++] Add helper type non-propagating-cache

Differential Revision: https://reviews.llvm.org/D102121

NOKEYCHECK=True
GitOrigin-RevId: 3959c95deb115e0bc6122faaa244cfb2fc280b50
diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt
index 007d3f6..fc095df 100644
--- a/include/CMakeLists.txt
+++ b/include/CMakeLists.txt
@@ -193,6 +193,7 @@
   __ranges/empty.h
   __ranges/enable_borrowed_range.h
   __ranges/enable_view.h
+  __ranges/non_propagating_cache.h
   __ranges/ref_view.h
   __ranges/size.h
   __ranges/subrange.h
diff --git a/include/__ranges/drop_view.h b/include/__ranges/drop_view.h
index 7b3b8da..099fd22 100644
--- a/include/__ranges/drop_view.h
+++ b/include/__ranges/drop_view.h
@@ -17,9 +17,11 @@
 #include <__ranges/all.h>
 #include <__ranges/concepts.h>
 #include <__ranges/enable_borrowed_range.h>
+#include <__ranges/non_propagating_cache.h>
 #include <__ranges/size.h>
 #include <__ranges/view_interface.h>
-#include <optional>
+#include <__utility/move.h>
+#include <concepts>
 #include <type_traits>
 
 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
@@ -36,21 +38,16 @@
 namespace ranges {
   template<view _View>
   class drop_view
-    : public view_interface<drop_view<_View>> {
-
+    : public view_interface<drop_view<_View>>
+  {
     // We cache begin() whenever ranges::next is not guaranteed O(1) to provide an
     // amortized O(1) begin() method. If this is an input_range, then we cannot cache
     // begin because begin is not equality preserving.
     // Note: drop_view<input-range>::begin() is still trivially amortized O(1) because
     // one can't call begin() on it more than once.
     static constexpr bool _UseCache = forward_range<_View> && !(random_access_range<_View> && sized_range<_View>);
-    using _Cache = optional<iterator_t<_View>>;
-    struct _Empty { };
-
-    // For forward ranges use std::optional to cache the begin iterator.
-    // No unique address + _Empty means we don't use any extra space when this
-    // is not a forward iterator.
-    [[no_unique_address]] conditional_t<_UseCache, _Cache, _Empty> __cached_begin_;
+    using _Cache = _If<_UseCache, __non_propagating_cache<iterator_t<_View>>, __empty_cache>;
+    [[no_unique_address]] _Cache __cached_begin_ = _Cache();
     range_difference_t<_View> __count_ = 0;
     _View __base_ = _View();
 
@@ -59,48 +56,12 @@
 
     _LIBCPP_HIDE_FROM_ABI
     constexpr drop_view(_View __base, range_difference_t<_View> __count)
-      : __cached_begin_()
-      , __count_(__count)
+      : __count_(__count)
       , __base_(_VSTD::move(__base))
     {
       _LIBCPP_ASSERT(__count_ >= 0, "count must be greater than or equal to zero.");
     }
 
-    _LIBCPP_HIDE_FROM_ABI
-    constexpr drop_view(drop_view const& __other)
-      : __cached_begin_() // Intentionally not propagating the cached begin iterator.
-      , __count_(__other.__count_)
-      , __base_(__other.__base_)
-    { }
-
-    _LIBCPP_HIDE_FROM_ABI
-    constexpr drop_view(drop_view&& __other)
-      : __cached_begin_() // Intentionally not propagating the cached begin iterator.
-      , __count_(_VSTD::move(__other.__count_))
-      , __base_(_VSTD::move(__other.__base_))
-    { }
-
-    _LIBCPP_HIDE_FROM_ABI
-    constexpr drop_view& operator=(drop_view const& __other) {
-      if constexpr (_UseCache) {
-        __cached_begin_.reset();
-      }
-      __base_ = __other.__base_;
-      __count_ = __other.__count_;
-      return *this;
-    }
-
-    _LIBCPP_HIDE_FROM_ABI
-    constexpr drop_view& operator=(drop_view&& __other) {
-      if constexpr (_UseCache) {
-        __cached_begin_.reset();
-        __other.__cached_begin_.reset();
-      }
-      __base_ = _VSTD::move(__other.__base_);
-      __count_ = _VSTD::move(__other.__count_);
-      return *this;
-    }
-
     _LIBCPP_HIDE_FROM_ABI constexpr _View base() const& requires copy_constructible<_View> { return __base_; }
     _LIBCPP_HIDE_FROM_ABI constexpr _View base() && { return _VSTD::move(__base_); }
 
@@ -110,12 +71,12 @@
                   random_access_range<const _View> && sized_range<const _View>))
     {
       if constexpr (_UseCache)
-        if (__cached_begin_)
+        if (__cached_begin_.__has_value())
           return *__cached_begin_;
 
       auto __tmp = ranges::next(ranges::begin(__base_), __count_, ranges::end(__base_));
       if constexpr (_UseCache)
-        __cached_begin_ = __tmp;
+        __cached_begin_.__set(__tmp);
       return __tmp;
     }
 
diff --git a/include/__ranges/non_propagating_cache.h b/include/__ranges/non_propagating_cache.h
new file mode 100644
index 0000000..878f707
--- /dev/null
+++ b/include/__ranges/non_propagating_cache.h
@@ -0,0 +1,99 @@
+// -*- C++ -*-
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+#ifndef _LIBCPP___RANGES_NON_PROPAGATING_CACHE_H
+#define _LIBCPP___RANGES_NON_PROPAGATING_CACHE_H
+
+#include <__config>
+#include <__iterator/concepts.h>        // indirectly_readable
+#include <__iterator/iterator_traits.h> // iter_reference_t
+#include <__memory/addressof.h>
+#include <concepts>                     // constructible_from
+#include <optional>
+#include <type_traits>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#pragma GCC system_header
+#endif
+
+_LIBCPP_PUSH_MACROS
+#include <__undef_macros>
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+// clang-format off
+
+#if !defined(_LIBCPP_HAS_NO_RANGES)
+
+namespace ranges {
+  // __non_propagating_cache is a helper type that allows storing an optional value in it,
+  // but which does not copy the source's value when it is copy constructed/assigned to,
+  // and which resets the source's value when it is moved-from.
+  //
+  // This type is used as an implementation detail of some views that need to cache the
+  // result of `begin()` in order to provide an amortized O(1) begin() method. Typically,
+  // we don't want to propagate the value of the cache upon copy because the cached iterator
+  // may refer to internal details of the source view.
+  template<class _Tp>
+    requires is_object_v<_Tp>
+  class _LIBCPP_TEMPLATE_VIS __non_propagating_cache {
+    optional<_Tp> __value_ = nullopt;
+
+  public:
+    _LIBCPP_HIDE_FROM_ABI __non_propagating_cache() = default;
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache(__non_propagating_cache const&) noexcept
+      : __value_(nullopt)
+    { }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache(__non_propagating_cache&& __other) noexcept
+      : __value_(nullopt)
+    {
+      __other.__value_.reset();
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache& operator=(__non_propagating_cache const& __other) noexcept {
+      if (this != _VSTD::addressof(__other)) {
+        __value_.reset();
+      }
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr __non_propagating_cache& operator=(__non_propagating_cache&& __other) noexcept {
+      __value_.reset();
+      __other.__value_.reset();
+      return *this;
+    }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr _Tp& operator*() { return *__value_; }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr _Tp const& operator*() const { return *__value_; }
+
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr bool __has_value() const { return __value_.has_value(); }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void __set(_Tp const& __value) { __value_.emplace(__value); }
+    _LIBCPP_HIDE_FROM_ABI
+    constexpr void __set(_Tp&& __value) { __value_.emplace(_VSTD::move(__value)); }
+  };
+
+  struct __empty_cache { };
+} // namespace ranges
+
+#endif // _LIBCPP_STD_VER > 17 && !defined(_LIBCPP_HAS_NO_RANGES)
+
+_LIBCPP_END_NAMESPACE_STD
+
+_LIBCPP_POP_MACROS
+
+#endif // _LIBCPP___RANGES_NON_PROPAGATING_CACHE_H
diff --git a/include/module.modulemap b/include/module.modulemap
index 6931698..4d2101e 100644
--- a/include/module.modulemap
+++ b/include/module.modulemap
@@ -613,6 +613,7 @@
       module empty_view             { private header "__ranges/empty_view.h"            }
       module enable_borrowed_range  { private header "__ranges/enable_borrowed_range.h" }
       module enable_view            { private header "__ranges/enable_view.h"           }
+      module non_propagating_cache  { private header "__ranges/non_propagating_cache.h" }
       module ref_view               { private header "__ranges/ref_view.h"              }
       module size                   { private header "__ranges/size.h"                  }
       module subrange               { private header "__ranges/subrange.h"              }