[libc-commits] [libc] [libc] Expand cpp::span and adopt in CPP utilities (PR #244026)

via libc-commits libc-commits at lists.llvm.org
Wed Nov 18 14:56:08 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Jeff Bailey (kaladron)

<details>
<summary>Changes</summary>

Bring cpp::span closer to C++20 std::span:

* Const and reverse iterators (with random-access ops on cpp::reverse_iterator)
* Deduction guides and template first, last, and subspan overloads
* Byte views (as_bytes and as_writable_bytes)
* Constexpr-compatible debug bounds checks

span.h uses an inline trap helper rather than libc_assert.h because libc_assert.h transitively includes span.h via integer_to_string.h. Also migrate cpp::bitset and cpp::StringStream to span subviews.

Assisted-by: Automated tooling, human reviewed.

---

Patch is 39.35 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/244026.diff


8 Files Affected:

- (modified) libc/src/__support/CPP/CMakeLists.txt (+31) 
- (modified) libc/src/__support/CPP/bitset.h (+15-8) 
- (modified) libc/src/__support/CPP/iterator.h (+66-8) 
- (modified) libc/src/__support/CPP/span.h (+111-17) 
- (modified) libc/src/__support/CPP/stringstream.h (+30-23) 
- (modified) libc/test/src/__support/CPP/CMakeLists.txt (+5) 
- (modified) libc/test/src/__support/CPP/span_test.cpp (+369-46) 
- (modified) libc/test/src/__support/CPP/stringstream_test.cpp (+28-1) 


``````````diff
diff --git a/libc/src/__support/CPP/CMakeLists.txt b/libc/src/__support/CPP/CMakeLists.txt
index 6c911333f01079..e1da0f4e05f701 100644
--- a/libc/src/__support/CPP/CMakeLists.txt
+++ b/libc/src/__support/CPP/CMakeLists.txt
@@ -8,6 +8,10 @@ add_header_library(
   array
   HDRS
     array.h
+  DEPENDS
+    .iterator
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
 )
 
 add_header_library(
@@ -27,6 +31,11 @@ add_header_library(
   bitset
   HDRS
     bitset.h
+  DEPENDS
+    .span
+    libc.hdr.types.size_t
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
 )
 
 add_header_library(
@@ -58,6 +67,17 @@ add_header_library(
     libc.src.__support.macros.config
 )
 
+add_header_library(
+  iterator
+  HDRS
+    iterator.h
+  DEPENDS
+    .type_traits
+    libc.hdr.types.size_t
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+)
+
 add_header_library(
   limits
   HDRS
@@ -81,7 +101,14 @@ add_header_library(
     span.h
   DEPENDS
     .array
+    .cstddef
+    .iterator
+    .limits
     .type_traits
+    libc.hdr.types.size_t
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
+    libc.src.__support.macros.optimization
 )
 
 add_header_library(
@@ -120,7 +147,11 @@ add_header_library(
   DEPENDS
     .span
     .string_view
+    .type_traits
+    libc.hdr.types.size_t
     libc.src.__support.integer_to_string
+    libc.src.__support.macros.attributes
+    libc.src.__support.macros.config
 )
 
 add_header_library(
diff --git a/libc/src/__support/CPP/bitset.h b/libc/src/__support/CPP/bitset.h
index ab492ab1f549d5..3a503cf71ef293 100644
--- a/libc/src/__support/CPP/bitset.h
+++ b/libc/src/__support/CPP/bitset.h
@@ -1,17 +1,23 @@
-//===-- A self contained equivalent of std::bitset --------------*- 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
 //
 //===----------------------------------------------------------------------===//
+///
+/// \file
+/// A self-contained equivalent of std::bitset.
+///
+//===----------------------------------------------------------------------===//
 
 #ifndef LLVM_LIBC_SRC___SUPPORT_CPP_BITSET_H
 #define LLVM_LIBC_SRC___SUPPORT_CPP_BITSET_H
 
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/span.h"
 #include "src/__support/macros/attributes.h"
 #include "src/__support/macros/config.h"
-#include <stddef.h> // For size_t.
 
 namespace LIBC_NAMESPACE_DECL {
 namespace cpp {
@@ -25,8 +31,8 @@ template <size_t NumberOfBits> struct bitset {
   }
 
   LIBC_INLINE constexpr void reset() {
-    for (size_t i = 0; i < NUMBER_OF_UNITS; ++i)
-      Data[i] = 0;
+    for (size_t &unit : Data)
+      unit = 0;
   }
 
   LIBC_INLINE constexpr void reset(size_t Index) {
@@ -38,8 +44,8 @@ template <size_t NumberOfBits> struct bitset {
   }
 
   LIBC_INLINE constexpr void flip() {
-    for (size_t i = 0; i < NUMBER_OF_UNITS; ++i)
-      Data[i] = ~Data[i];
+    for (size_t &unit : Data)
+      unit = ~unit;
   }
 
   // This function sets all bits in the range from Start to End (inclusive) to
@@ -61,8 +67,9 @@ template <size_t NumberOfBits> struct bitset {
           ~((size_t(1) << (Start - (start_index * BITS_PER_UNIT))) - 1);
       Data[start_index] |= low_bit_mask;
 
-      for (size_t i = start_index + 1; i < end_index; ++i)
-        Data[i] = ~size_t(0);
+      for (size_t &unit : span<size_t>(Data).subspan(
+               start_index + 1, end_index - start_index - 1))
+        unit = ~size_t(0);
 
       // Same as above, by splitting the shift the behavior is more consistent.
       size_t high_bit_mask =
diff --git a/libc/src/__support/CPP/iterator.h b/libc/src/__support/CPP/iterator.h
index 9ea66d38823849..64d44c18348954 100644
--- a/libc/src/__support/CPP/iterator.h
+++ b/libc/src/__support/CPP/iterator.h
@@ -1,14 +1,21 @@
-//===-- Standalone implementation of iterator -------------------*- 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
 //
 //===----------------------------------------------------------------------===//
+///
+/// \file
+/// Standalone implementation of iterator utilities.
+///
+//===----------------------------------------------------------------------===//
 
 #ifndef LLVM_LIBC_SRC___SUPPORT_CPP_ITERATOR_H
 #define LLVM_LIBC_SRC___SUPPORT_CPP_ITERATOR_H
 
+#include <stddef.h> // For ptrdiff_t
+
 #include "hdr/types/size_t.h"
 #include "src/__support/CPP/type_traits/enable_if.h"
 #include "src/__support/CPP/type_traits/is_convertible.h"
@@ -24,22 +31,33 @@ struct random_access_iterator_tag : input_iterator_tag {};
 
 template <typename T> struct iterator_traits;
 template <typename T> struct iterator_traits<T *> {
+  using difference_type = ptrdiff_t;
+  using value_type = T;
+  using pointer = T *;
   using reference = T &;
   using iterator_category = random_access_iterator_tag;
-  using value_type = T;
 };
 
 template <typename Iter> class reverse_iterator {
   Iter current;
 
 public:
-  using reference = typename iterator_traits<Iter>::reference;
-  using value_type = typename iterator_traits<Iter>::value_type;
   using iterator_type = Iter;
+  using difference_type = typename iterator_traits<Iter>::difference_type;
+  using value_type = typename iterator_traits<Iter>::value_type;
+  using pointer = typename iterator_traits<Iter>::pointer;
+  using reference = typename iterator_traits<Iter>::reference;
 
-  LIBC_INLINE reverse_iterator() : current() {}
+  LIBC_INLINE constexpr reverse_iterator() : current() {}
   LIBC_INLINE constexpr explicit reverse_iterator(Iter it) : current(it) {}
 
+  template <typename Other,
+            cpp::enable_if_t<!cpp::is_same_v<Iter, Other> &&
+                                 cpp::is_convertible_v<const Other &, Iter>,
+                             int> = 0>
+  LIBC_INLINE constexpr reverse_iterator(const reverse_iterator<Other> &other)
+      : current(other.base()) {}
+
   template <typename Other,
             cpp::enable_if_t<!cpp::is_same_v<Iter, Other> &&
                                  cpp::is_convertible_v<const Other &, Iter>,
@@ -83,19 +101,60 @@ template <typename Iter> class reverse_iterator {
     Iter tmp = current;
     return *--tmp;
   }
-  LIBC_INLINE constexpr reverse_iterator operator--() {
+
+  LIBC_INLINE constexpr pointer operator->() const {
+    Iter tmp = current;
+    return --tmp;
+  }
+
+  LIBC_INLINE constexpr reference operator[](difference_type n) const {
+    return *(*this + n);
+  }
+
+  LIBC_INLINE constexpr reverse_iterator &operator--() {
     ++current;
     return *this;
   }
+
+  LIBC_INLINE constexpr reverse_iterator operator--(int) {
+    reverse_iterator tmp(*this);
+    ++current;
+    return tmp;
+  }
+
   LIBC_INLINE constexpr reverse_iterator &operator++() {
     --current;
     return *this;
   }
+
   LIBC_INLINE constexpr reverse_iterator operator++(int) {
     reverse_iterator tmp(*this);
     --current;
     return tmp;
   }
+
+  LIBC_INLINE constexpr reverse_iterator operator+(difference_type n) const {
+    return reverse_iterator(current - n);
+  }
+
+  LIBC_INLINE constexpr reverse_iterator &operator+=(difference_type n) {
+    current -= n;
+    return *this;
+  }
+
+  LIBC_INLINE constexpr reverse_iterator operator-(difference_type n) const {
+    return reverse_iterator(current + n);
+  }
+
+  LIBC_INLINE constexpr reverse_iterator &operator-=(difference_type n) {
+    current += n;
+    return *this;
+  }
+
+  LIBC_INLINE friend constexpr difference_type
+  operator-(const reverse_iterator &lhs, const reverse_iterator &rhs) {
+    return rhs.base() - lhs.base();
+  }
 };
 
 namespace cpp_internal {
@@ -109,9 +168,8 @@ LIBC_INLINE constexpr size_t distance(It first, It last,
 template <typename It>
 LIBC_INLINE constexpr auto distance(It first, It last, input_iterator_tag) {
   size_t n = 0;
-  for (; first != last; ++first) {
+  for (; first != last; ++first)
     ++n;
-  }
   return n;
 }
 
diff --git a/libc/src/__support/CPP/span.h b/libc/src/__support/CPP/span.h
index cbf15d160feef1..33ecfff12d7d3d 100644
--- a/libc/src/__support/CPP/span.h
+++ b/libc/src/__support/CPP/span.h
@@ -13,14 +13,17 @@
 #ifndef LLVM_LIBC_SRC___SUPPORT_CPP_SPAN_H
 #define LLVM_LIBC_SRC___SUPPORT_CPP_SPAN_H
 
-#include <stddef.h> // For size_t
-
-#include "array.h" // For array
-#include "limits.h"
-#include "src/__support/macros/config.h"
-#include "type_traits.h" // For remove_cv_t, enable_if_t, is_same_v, is_const_v
-
+#include <stddef.h> // For ptrdiff_t
+
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/array.h"
+#include "src/__support/CPP/cstddef.h"
+#include "src/__support/CPP/iterator.h"
+#include "src/__support/CPP/limits.h"
+#include "src/__support/CPP/type_traits.h"
 #include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
+#include "src/__support/macros/optimization.h"
 
 namespace LIBC_NAMESPACE_DECL {
 namespace cpp {
@@ -28,11 +31,10 @@ namespace cpp {
 // A trimmed down implementation of std::span.
 // Missing features:
 // - No constant size spans (e.g. Span<int, 4>),
-// - Only handle pointer like types, no fancy interators nor object overriding
+// - Only handle pointer like types, no fancy iterators nor object overriding
 //   the & operator,
 // - No implicit type conversion (e.g. Span<B>, initialized with As where A
-//   inherits from B),
-// - No reverse iterators
+//   inherits from B).
 template <typename T> class span {
   template <typename U>
   LIBC_INLINE_VAR static constexpr bool is_const_view_v =
@@ -43,6 +45,27 @@ template <typename T> class span {
   LIBC_INLINE_VAR static constexpr bool is_compatible_v =
       cpp::is_same_v<U, T> || is_const_view_v<U>;
 
+  LIBC_INLINE static constexpr void assert_precondition(bool cond) {
+#ifndef NDEBUG
+    if (LIBC_UNLIKELY(!cond))
+      __builtin_trap();
+#else
+    (void)cond;
+#endif
+  }
+
+  template <typename End>
+  LIBC_INLINE static constexpr size_t distance_to_end(T *first, End end) {
+    if constexpr (cpp::is_null_pointer_v<End>) {
+      assert_precondition(first == nullptr);
+      return 0;
+    } else {
+      T *end_ptr = end;
+      assert_precondition(first <= end_ptr);
+      return first == end_ptr ? 0 : static_cast<size_t>(end_ptr - first);
+    }
+  }
+
 public:
   using element_type = T;
   using value_type = remove_cv_t<T>;
@@ -53,6 +76,9 @@ template <typename T> class span {
   using reference = T &;
   using const_reference = const T &;
   using iterator = T *;
+  using const_iterator = const T *;
+  using reverse_iterator = cpp::reverse_iterator<iterator>;
+  using const_reverse_iterator = cpp::reverse_iterator<const_iterator>;
 
   LIBC_INLINE_VAR static constexpr size_type dynamic_extent =
       cpp::numeric_limits<size_type>::max();
@@ -65,8 +91,13 @@ template <typename T> class span {
   LIBC_INLINE constexpr span(pointer first, size_type count)
       : span_data(first), span_size(count) {}
 
-  LIBC_INLINE constexpr span(pointer first, pointer end)
-      : span_data(first), span_size(static_cast<size_t>(end - first)) {}
+  template <typename End,
+            cpp::enable_if_t<cpp::is_same_v<End, pointer> ||
+                                 cpp::is_same_v<End, value_type *> ||
+                                 cpp::is_null_pointer_v<End>,
+                             bool> = true>
+  LIBC_INLINE constexpr span(pointer first, End end)
+      : span_data(first), span_size(distance_to_end(first, end)) {}
 
   template <typename U, size_t N,
             cpp::enable_if_t<is_compatible_v<U>, bool> = true>
@@ -96,13 +127,38 @@ template <typename T> class span {
   LIBC_INLINE ~span() = default;
 
   LIBC_INLINE constexpr reference operator[](size_type index) const {
+    assert_precondition(index < size());
     return data()[index];
   }
 
   LIBC_INLINE constexpr iterator begin() const { return data(); }
   LIBC_INLINE constexpr iterator end() const { return data() + size(); }
-  LIBC_INLINE constexpr reference front() const { return (*this)[0]; }
-  LIBC_INLINE constexpr reference back() const { return (*this)[size() - 1]; }
+  LIBC_INLINE constexpr const_iterator cbegin() const { return data(); }
+  LIBC_INLINE constexpr const_iterator cend() const { return data() + size(); }
+
+  LIBC_INLINE constexpr reverse_iterator rbegin() const {
+    return reverse_iterator(end());
+  }
+  LIBC_INLINE constexpr reverse_iterator rend() const {
+    return reverse_iterator(begin());
+  }
+  LIBC_INLINE constexpr const_reverse_iterator crbegin() const {
+    return const_reverse_iterator(cend());
+  }
+  LIBC_INLINE constexpr const_reverse_iterator crend() const {
+    return const_reverse_iterator(cbegin());
+  }
+
+  LIBC_INLINE constexpr reference front() const {
+    assert_precondition(!empty());
+    return data()[0];
+  }
+
+  LIBC_INLINE constexpr reference back() const {
+    assert_precondition(!empty());
+    return data()[size() - 1];
+  }
+
   LIBC_INLINE constexpr pointer data() const { return span_data; }
   LIBC_INLINE constexpr size_type size() const { return span_size; }
   LIBC_INLINE constexpr size_type size_bytes() const {
@@ -112,23 +168,41 @@ template <typename T> class span {
 
   LIBC_INLINE constexpr span<element_type>
   subspan(size_type offset, size_type count = dynamic_extent) const {
+    assert_precondition(offset <= size() &&
+                        (count == dynamic_extent || count <= size() - offset));
     return span<element_type>(data() + offset, count_to_size(offset, count));
   }
 
+  template <size_type Offset, size_type Count = dynamic_extent>
+  LIBC_INLINE constexpr span<element_type> subspan() const {
+    return subspan(Offset, Count);
+  }
+
   LIBC_INLINE constexpr span<element_type> first(size_type count) const {
-    return subspan(0, count);
+    assert_precondition(count <= size());
+    return span<element_type>(data(), count);
+  }
+
+  template <size_type Count>
+  LIBC_INLINE constexpr span<element_type> first() const {
+    return first(Count);
   }
 
   LIBC_INLINE constexpr span<element_type> last(size_type count) const {
+    assert_precondition(count <= size());
     return span<element_type>(data() + (size() - count), count);
   }
 
+  template <size_type Count>
+  LIBC_INLINE constexpr span<element_type> last() const {
+    return last(Count);
+  }
+
 private:
   LIBC_INLINE constexpr size_type count_to_size(size_type offset,
                                                 size_type count) const {
-    if (count == dynamic_extent) {
+    if (count == dynamic_extent)
       return size() - offset;
-    }
     return count;
   }
 
@@ -136,6 +210,26 @@ template <typename T> class span {
   size_t span_size;
 };
 
+template <typename T, size_t N> span(T (&)[N]) -> span<T>;
+
+template <typename T, size_t N> span(array<T, N> &) -> span<T>;
+
+template <typename T, size_t N> span(const array<T, N> &) -> span<const T>;
+
+template <typename T> span(T *, size_t) -> span<T>;
+
+template <typename T> span(T *, T *) -> span<T>;
+
+template <typename T> LIBC_INLINE span<const byte> as_bytes(span<T> s) {
+  return span<const byte>(reinterpret_cast<const byte *>(s.data()),
+                          s.size_bytes());
+}
+
+template <typename T, cpp::enable_if_t<!cpp::is_const_v<T>, bool> = true>
+LIBC_INLINE span<byte> as_writable_bytes(span<T> s) {
+  return span<byte>(reinterpret_cast<byte *>(s.data()), s.size_bytes());
+}
+
 } // namespace cpp
 } // namespace LIBC_NAMESPACE_DECL
 
diff --git a/libc/src/__support/CPP/stringstream.h b/libc/src/__support/CPP/stringstream.h
index a16084c848688b..7239f9a4f302c2 100644
--- a/libc/src/__support/CPP/stringstream.h
+++ b/libc/src/__support/CPP/stringstream.h
@@ -1,20 +1,26 @@
-//===-- A simple implementation of string stream class ----------*- 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
 //
 //===----------------------------------------------------------------------===//
+///
+/// \file
+/// A simple implementation of a non-allocating string stream class.
+///
+//===----------------------------------------------------------------------===//
 
 #ifndef LLVM_LIBC_SRC___SUPPORT_CPP_STRINGSTREAM_H
 #define LLVM_LIBC_SRC___SUPPORT_CPP_STRINGSTREAM_H
 
-#include "span.h"
-#include "src/__support/macros/config.h"
-#include "string_view.h"
-#include "type_traits.h"
-
+#include "hdr/types/size_t.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/CPP/type_traits.h"
 #include "src/__support/integer_to_string.h"
+#include "src/__support/macros/attributes.h"
+#include "src/__support/macros/config.h"
 
 namespace LIBC_NAMESPACE_DECL {
 namespace cpp {
@@ -27,44 +33,45 @@ class StringStream {
   size_t write_ptr = 0; // The current write pointer
   bool err = false;     // If an error occurs while writing
 
-  void write(const char *bytes, size_t size) {
+  LIBC_INLINE constexpr void write(span<const char> bytes) {
     size_t i = 0;
     const size_t data_size = data.size();
-    for (; write_ptr < data_size && i < size; ++i, ++write_ptr)
+    for (; write_ptr < data_size && i < bytes.size(); ++i, ++write_ptr)
       data[write_ptr] = bytes[i];
-    if (i < size) {
-      // If some of the characters couldn't be written, set error.
+    if (i < bytes.size())
       err = true;
-    }
   }
 
 public:
   static constexpr char ENDS = '\0';
 
   // Create a string stream which will write into |buf|.
-  constexpr StringStream(const span<char> &buf) : data(buf) {}
+  LIBC_INLINE constexpr StringStream(const span<char> &buf) : data(buf) {}
 
   // Return a string_view to the current characters in the stream. If a
   // null terminator was not explicitly written, then the return value
   // will not include one. In order to produce a string_view to a null
   // terminated string, write ENDS explicitly.
-  string_view str() const { return string_view(data.data(), write_ptr); }
+  LIBC_INLINE constexpr string_view str() const {
+    span<const char> written = data.first(write_ptr);
+    return string_view(written.data(), written.size());
+  }
 
   // Write the characters from |str| to the stream.
-  StringStream &operator<<(string_view str) {
-    write(str.data(), str.size());
+  LIBC_INLINE constexpr StringStream &operator<<(string_view str) {
+    write({str.data(), str.size()});
     return *this;
   }
 
   // Write the |val| as string.
   template <typename T, enable_if_t<is_integral_v<T>, int> = 0>
-  StringStream &operator<<(T val) {
+  LIBC_INLINE StringStream &operator<<(T val) {
     const IntegerToString<T> buffer(val);
     return *this << buffer.view();
   }
 
   template <typename T, enable_if_t<is_floating_point_v<T>, int> = 0>
-  StringStream &operator<<(T) {
+  LIBC_INLINE StringStream &operator<<(T) {
     // If this specialization gets activated, then the static_assert will
     // trigger a compile error about missing floating point number support.
     static_assert(!is_floating_point_v<T>,
@@ -73,21 +80,21 @@ class StringStream {
   }
 
   // Write a null-terminated string. The terminating null character is not
-  // written to allow stremaing to continue.
-  StringStream &operator<<(const char *str) {
+  // written to allow streaming to continue.
+  LIBC_INLINE constexpr StringStream &operator<<(const char *str) {
     return operator<<(string_view(str));
   }
 
   // Write a single character.
-  StringStream &operator<<(char a) {
-    write(&a, 1);
+  LIBC_INLINE constexpr StringStream &operator<<(char a) {
+    write({&a, 1});
     return *this;
   }
 
   // Return true if any write operation(s) failed due to insufficient size.
-  bool overflow() const { return err; }
+  LIBC_INLINE constexpr bool overflow() const { return err; }
 
-  size_t bufsize() const { return data.size(); }
+  LIBC_INLINE cons...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/244026


More information about the libc-commits mailing list