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

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Wed Nov 18 14:53:05 PST 2026


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

>From d01647efd77706eec27e4fd4bd726d4c95831e47 Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Wed, 18 Nov 2026 21:28:21 +0000
Subject: [PATCH] [libc] Expand cpp::span and adopt in CPP utilities

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.
---
 libc/src/__support/CPP/CMakeLists.txt         |  31 ++
 libc/src/__support/CPP/bitset.h               |  23 +-
 libc/src/__support/CPP/iterator.h             |  74 +++-
 libc/src/__support/CPP/span.h                 | 128 +++++-
 libc/src/__support/CPP/stringstream.h         |  53 ++-
 libc/test/src/__support/CPP/CMakeLists.txt    |   5 +
 libc/test/src/__support/CPP/span_test.cpp     | 415 ++++++++++++++++--
 .../src/__support/CPP/stringstream_test.cpp   |  29 +-
 8 files changed, 655 insertions(+), 103 deletions(-)

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 constexpr size_t bufsize() const { return data.size(); }
 };
 
 } // namespace cpp
diff --git a/libc/test/src/__support/CPP/CMakeLists.txt b/libc/test/src/__support/CPP/CMakeLists.txt
index 5cc7e644568be4..25fd58137ca77c 100644
--- a/libc/test/src/__support/CPP/CMakeLists.txt
+++ b/libc/test/src/__support/CPP/CMakeLists.txt
@@ -153,6 +153,7 @@ add_libc_test(
     stringstream_test.cpp
   DEPENDS
     libc.src.__support.CPP.span
+    libc.src.__support.CPP.string_view
     libc.src.__support.CPP.stringstream
 )
 
@@ -206,7 +207,11 @@ add_libc_test(
   SRCS
     span_test.cpp
   DEPENDS
+    libc.hdr.stdint_proxy
+    libc.src.__support.CPP.array
+    libc.src.__support.CPP.cstddef
     libc.src.__support.CPP.span
+    libc.src.__support.CPP.type_traits
 )
 
 add_libc_test(
diff --git a/libc/test/src/__support/CPP/span_test.cpp b/libc/test/src/__support/CPP/span_test.cpp
index e8686749f85606..5adc4c7fa85e9a 100644
--- a/libc/test/src/__support/CPP/span_test.cpp
+++ b/libc/test/src/__support/CPP/span_test.cpp
@@ -11,36 +11,174 @@
 ///
 //===----------------------------------------------------------------------===//
 
+#include "hdr/stdint_proxy.h"
 #include "src/__support/CPP/array.h"
+#include "src/__support/CPP/cstddef.h"
 #include "src/__support/CPP/span.h"
+#include "src/__support/CPP/type_traits.h"
 #include "test/UnitTest/Test.h"
 
 using LIBC_NAMESPACE::cpp::array;
+using LIBC_NAMESPACE::cpp::as_bytes;
+using LIBC_NAMESPACE::cpp::as_writable_bytes;
+using LIBC_NAMESPACE::cpp::byte;
+using LIBC_NAMESPACE::cpp::is_same_v;
 using LIBC_NAMESPACE::cpp::span;
+using LIBC_NAMESPACE::cpp::to_integer;
+
+namespace {
+
+template <typename T, typename = void>
+struct HasWritableBytes : LIBC_NAMESPACE::cpp::false_type {};
+
+template <typename T>
+struct HasWritableBytes<
+    T, LIBC_NAMESPACE::cpp::void_t<decltype(as_writable_bytes(span<T>()))>>
+    : LIBC_NAMESPACE::cpp::true_type {};
+
+static_assert(HasWritableBytes<int>::value);
+static_assert(HasWritableBytes<byte>::value);
+static_assert(!HasWritableBytes<const int>::value);
+static_assert(!HasWritableBytes<const byte>::value);
+
+struct Pair {
+  int first;
+  int second;
+};
+
+constexpr bool test_constexpr_span() {
+  constexpr int CONST_ARR[] = {10, 20, 30, 40};
+  span const_s(CONST_ARR);
+  if (const_s.size() != 4 || const_s.size_bytes() != 4 * sizeof(int))
+    return false;
+  if (const_s.front() != 10 || const_s.back() != 40 || const_s[2] != 30)
+    return false;
+
+  int mut_arr[] = {1, 2, 3, 4, 5};
+  span mut_s(mut_arr);
+  mut_s[0] = 11;
+  if (mut_s.front() != 11)
+    return false;
+
+  span range_s(mut_arr + 1, mut_arr + 4);
+  if (range_s.size() != 3 || range_s[0] != 2 || range_s.back() != 4)
+    return false;
+
+  span empty_null(static_cast<int *>(nullptr), static_cast<int *>(nullptr));
+  if (!empty_null.empty() || empty_null.size() != 0)
+    return false;
+
+  span zero_count(mut_arr, 0);
+  if (!zero_count.empty())
+    return false;
+
+  // Forward and const iterators.
+  int sum = 0;
+  for (auto it = mut_s.cbegin(); it != mut_s.cend(); ++it)
+    sum += *it;
+  if (sum != (11 + 2 + 3 + 4 + 5))
+    return false;
+
+  // Reverse iterators.
+  int rev_vals[5] = {};
+  size_t idx = 0;
+  for (auto rit = mut_s.rbegin(); rit != mut_s.rend(); ++rit)
+    rev_vals[idx++] = *rit;
+  if (rev_vals[0] != 5 || rev_vals[4] != 11)
+    return false;
+
+  auto crit = mut_s.crbegin();
+  if (*crit != 5 || crit[4] != 11 || (mut_s.crend() - crit) != 5)
+    return false;
+  ++crit;
+  --crit;
+  if (*crit != 5)
+    return false;
+
+  // Runtime and compile-time subviews.
+  const auto FIRST2 = mut_s.first(2);
+  const auto FIRST2_CT = mut_s.first<2>();
+  if (FIRST2.size() != 2 || FIRST2[0] != 11 || FIRST2_CT[1] != 2)
+    return false;
+
+  const auto LAST2 = mut_s.last(2);
+  const auto LAST2_CT = mut_s.last<2>();
+  if (LAST2.size() != 2 || LAST2[0] != 4 || LAST2_CT[1] != 5)
+    return false;
+
+  const auto SUB = mut_s.subspan(1, 3);
+  const auto SUB_CT = mut_s.subspan<1, 3>();
+  const auto SUB_TAIL_CT = mut_s.subspan<3>();
+  if (SUB.size() != 3 || SUB[0] != 2 || SUB_CT[2] != 4)
+    return false;
+  if (SUB_TAIL_CT.size() != 2 || SUB_TAIL_CT[0] != 4 || SUB_TAIL_CT[1] != 5)
+    return false;
+
+  return true;
+}
+
+static_assert(test_constexpr_span());
+
+} // namespace
 
 TEST(LlvmLibcSpanTest, InitializeEmpty) {
   span<int> s;
   ASSERT_EQ(s.size(), size_t(0));
+  ASSERT_EQ(s.size_bytes(), size_t(0));
   ASSERT_TRUE(s.empty());
-  ASSERT_TRUE(s.data() == nullptr);
+  ASSERT_EQ(s.data(), nullptr);
+  ASSERT_EQ(s.begin(), s.end());
+  ASSERT_EQ(s.cbegin(), s.cend());
+  ASSERT_EQ(s.rbegin().base(), s.rend().base());
+  ASSERT_EQ(s.crbegin().base(), s.crend().base());
+  ASSERT_TRUE(s.rbegin() == s.rend());
+  ASSERT_TRUE(s.crbegin() == s.crend());
 }
 
 TEST(LlvmLibcSpanTest, InitializeSingleton) {
   int a = 42;
   span<int> s(&a, 1);
   ASSERT_EQ(s.size(), size_t(1));
+  ASSERT_EQ(s.size_bytes(), sizeof(int));
   ASSERT_FALSE(s.empty());
-  ASSERT_TRUE(s.data() == &a);
+  ASSERT_EQ(s.data(), &a);
   ASSERT_EQ(s.front(), 42);
   ASSERT_EQ(s.back(), 42);
 }
 
+TEST(LlvmLibcSpanTest, InitializePointerRange) {
+  int a[] = {10, 20, 30, 40};
+  span<int> s(a + 1, a + 3);
+  ASSERT_EQ(s.size(), size_t(2));
+  ASSERT_EQ(s.data(), &a[1]);
+  ASSERT_EQ(s[0], 20);
+  ASSERT_EQ(s[1], 30);
+
+  span<const int> cs(a, a + 4);
+  ASSERT_EQ(cs.size(), size_t(4));
+  ASSERT_EQ(cs.front(), 10);
+  ASSERT_EQ(cs.back(), 40);
+
+  span<int> empty_same(a + 2, a + 2);
+  ASSERT_TRUE(empty_same.empty());
+  ASSERT_EQ(empty_same.data(), &a[2]);
+
+  span<int> empty_null(nullptr, nullptr);
+  ASSERT_TRUE(empty_null.empty());
+  ASSERT_EQ(empty_null.data(), nullptr);
+
+  // Verify literal 0 resolves unambiguously to (pointer, size_type).
+  span<int> empty_zero(a, 0);
+  ASSERT_TRUE(empty_zero.empty());
+  ASSERT_EQ(empty_zero.data(), &a[0]);
+}
+
 TEST(LlvmLibcSpanTest, InitializeCArray) {
   int a[] = {1, 2, 3};
   span<int> s(a);
   ASSERT_EQ(s.size(), size_t(3));
   ASSERT_FALSE(s.empty());
-  ASSERT_TRUE(s.data() == &a[0]);
+  ASSERT_EQ(s.data(), &a[0]);
   ASSERT_EQ(s.front(), 1);
   ASSERT_EQ(s.back(), 3);
   ASSERT_EQ(s[0], 1);
@@ -53,7 +191,7 @@ TEST(LlvmLibcSpanTest, InitializeArray) {
   span<int> s(a);
   ASSERT_EQ(s.size(), size_t(3));
   ASSERT_FALSE(s.empty());
-  ASSERT_TRUE(s.data() == &a[0]);
+  ASSERT_EQ(s.data(), &a[0]);
   ASSERT_EQ(s.front(), 1);
   ASSERT_EQ(s.back(), 3);
   ASSERT_EQ(s[0], 1);
@@ -65,7 +203,7 @@ TEST(LlvmLibcSpanTest, InitializeViewFormMutableSingleton) {
   int a = 42;
   span<const int> s(&a, 1);
   ASSERT_EQ(s.size(), size_t(1));
-  ASSERT_TRUE(s.data() == &a);
+  ASSERT_EQ(s.data(), static_cast<const int *>(&a));
 }
 
 TEST(LlvmLibcSpanTest, InitializeViewFormMutableCArray) {
@@ -87,8 +225,8 @@ TEST(LlvmLibcSpanTest, InitializeViewFormMutableArray) {
 }
 
 TEST(LlvmLibcSpanTest, InitializeViewFromConstArray) {
-  const array<int, 3> a = {1, 2, 3};
-  span<const int> s(a);
+  const array<int, 3> A = {1, 2, 3};
+  span<const int> s(A);
   ASSERT_EQ(s.size(), size_t(3));
   ASSERT_EQ(s[0], 1);
   ASSERT_EQ(s[1], 2);
@@ -100,27 +238,64 @@ TEST(LlvmLibcSpanTest, InitializeFromMutable) {
   span<int> s(a);
   span<const int> view(s);
   ASSERT_EQ(view.size(), size_t(3));
-  ASSERT_TRUE(view.data() == &a[0]);
+  ASSERT_EQ(view.data(), static_cast<const int *>(&a[0]));
   ASSERT_EQ(view[0], 1);
   ASSERT_EQ(view[1], 2);
   ASSERT_EQ(view[2], 3);
 
-  const span<int> const_s(a);
-  span<const int> view_from_const(const_s);
+  const span<int> CONST_S(a);
+  span<const int> view_from_const(CONST_S);
   ASSERT_EQ(view_from_const.size(), size_t(3));
-  ASSERT_TRUE(view_from_const.data() == &a[0]);
+  ASSERT_EQ(view_from_const.data(), static_cast<const int *>(&a[0]));
 
   span<const int> view_from_rvalue(s.subspan(1));
   ASSERT_EQ(view_from_rvalue.size(), size_t(2));
-  ASSERT_TRUE(view_from_rvalue.data() == &a[1]);
+  ASSERT_EQ(view_from_rvalue.data(), static_cast<const int *>(&a[1]));
   ASSERT_EQ(view_from_rvalue[0], 2);
   ASSERT_EQ(view_from_rvalue[1], 3);
 }
 
+TEST(LlvmLibcSpanTest, DeductionGuides) {
+  int c_arr[] = {1, 2, 3};
+  span s_c_arr(c_arr);
+  static_assert(is_same_v<decltype(s_c_arr), span<int>>);
+  ASSERT_EQ(s_c_arr.size(), size_t(3));
+
+  const int CONST_C_ARR[] = {4, 5};
+  span s_const_c_arr(CONST_C_ARR);
+  static_assert(is_same_v<decltype(s_const_c_arr), span<const int>>);
+  ASSERT_EQ(s_const_c_arr.size(), size_t(2));
+
+  array<int, 4> cpp_arr = {1, 2, 3, 4};
+  span s_cpp_arr(cpp_arr);
+  static_assert(is_same_v<decltype(s_cpp_arr), span<int>>);
+  ASSERT_EQ(s_cpp_arr.size(), size_t(4));
+
+  const array<int, 2> CONST_CPP_ARR = {7, 8};
+  span s_const_cpp_arr(CONST_CPP_ARR);
+  static_assert(is_same_v<decltype(s_const_cpp_arr), span<const int>>);
+  ASSERT_EQ(s_const_cpp_arr.size(), size_t(2));
+
+  int *ptr = c_arr;
+  span s_ptr_len(ptr, size_t(2));
+  static_assert(is_same_v<decltype(s_ptr_len), span<int>>);
+  ASSERT_EQ(s_ptr_len.size(), size_t(2));
+
+  span s_ptr_zero(ptr, 0);
+  static_assert(is_same_v<decltype(s_ptr_zero), span<int>>);
+  ASSERT_TRUE(s_ptr_zero.empty());
+
+  const int *const_ptr = CONST_C_ARR;
+  span s_ptr_range(const_ptr, const_ptr + 2);
+  static_assert(is_same_v<decltype(s_ptr_range), span<const int>>);
+  ASSERT_EQ(s_ptr_range.size(), size_t(2));
+}
+
 TEST(LlvmLibcSpanTest, Assign) {
   span<int> s;
   span<int> other;
   other = s;
+  ASSERT_TRUE(other.empty());
 }
 
 TEST(LlvmLibcSpanTest, CopyAssignment) {
@@ -129,7 +304,7 @@ TEST(LlvmLibcSpanTest, CopyAssignment) {
   span<int> s2;
   s2 = s1;
   ASSERT_EQ(s2.size(), size_t(3));
-  ASSERT_TRUE(s2.data() == &a[0]);
+  ASSERT_EQ(s2.data(), &a[0]);
   ASSERT_EQ(s2[0], 1);
   ASSERT_EQ(s2[1], 2);
   ASSERT_EQ(s2[2], 3);
@@ -140,7 +315,7 @@ TEST(LlvmLibcSpanTest, ReassignFromRValueTemporary) {
   span<int> s(a);
   s = s.subspan(1);
   ASSERT_EQ(s.size(), size_t(3));
-  ASSERT_TRUE(s.data() == &a[1]);
+  ASSERT_EQ(s.data(), &a[1]);
   ASSERT_EQ(s[0], 2);
   ASSERT_EQ(s[1], 3);
   ASSERT_EQ(s[2], 4);
@@ -148,13 +323,14 @@ TEST(LlvmLibcSpanTest, ReassignFromRValueTemporary) {
   s = span<int>();
   ASSERT_EQ(s.size(), size_t(0));
   ASSERT_TRUE(s.empty());
-  ASSERT_TRUE(s.data() == nullptr);
+  ASSERT_EQ(s.data(), nullptr);
 }
 
 TEST(LlvmLibcSpanTest, AssignFromMutable) {
   span<int> s;
   span<const int> view;
   view = s;
+  ASSERT_TRUE(view.empty());
 }
 
 TEST(LlvmLibcSpanTest, ConvertingAssignment) {
@@ -163,26 +339,26 @@ TEST(LlvmLibcSpanTest, ConvertingAssignment) {
   span<const int> view;
   view = s;
   ASSERT_EQ(view.size(), size_t(3));
-  ASSERT_TRUE(view.data() == &a[0]);
+  ASSERT_EQ(view.data(), static_cast<const int *>(&a[0]));
   ASSERT_EQ(view[0], 1);
   ASSERT_EQ(view[1], 2);
   ASSERT_EQ(view[2], 3);
 
   view = s.subspan(1);
   ASSERT_EQ(view.size(), size_t(2));
-  ASSERT_TRUE(view.data() == &a[1]);
+  ASSERT_EQ(view.data(), static_cast<const int *>(&a[1]));
   ASSERT_EQ(view[0], 2);
   ASSERT_EQ(view[1], 3);
 
-  const span<int> const_s(a);
-  view = const_s;
+  const span<int> CONST_S(a);
+  view = CONST_S;
   ASSERT_EQ(view.size(), size_t(3));
-  ASSERT_TRUE(view.data() == &a[0]);
+  ASSERT_EQ(view.data(), static_cast<const int *>(&a[0]));
 
   view = span<int>();
   ASSERT_EQ(view.size(), size_t(0));
   ASSERT_TRUE(view.empty());
-  ASSERT_TRUE(view.data() == nullptr);
+  ASSERT_EQ(view.data(), nullptr);
 }
 
 TEST(LlvmLibcSpanTest, Modify) {
@@ -196,29 +372,69 @@ TEST(LlvmLibcSpanTest, Modify) {
   ASSERT_EQ(s[2], 4);
 }
 
+TEST(LlvmLibcSpanTest, IteratorsAndReverseIterators) {
+  Pair pairs[] = {{1, 10}, {2, 20}, {3, 30}};
+  span<Pair> s(pairs);
+
+  static_assert(is_same_v<decltype(s.begin()), Pair *>);
+  static_assert(is_same_v<decltype(s.cbegin()), const Pair *>);
+
+  ASSERT_EQ(s.cbegin(), static_cast<const Pair *>(&pairs[0]));
+  ASSERT_EQ(s.cend(), static_cast<const Pair *>(&pairs[0] + 3));
+
+  auto rit = s.rbegin();
+  ASSERT_EQ(rit->first, 3);
+  ASSERT_EQ(rit->second, 30);
+  ASSERT_EQ(rit[2].first, 1);
+
+  rit->second = 300;
+  ASSERT_EQ(pairs[2].second, 300);
+
+  auto prev = rit++;
+  ASSERT_EQ(prev->first, 3);
+  ASSERT_EQ(rit->first, 2);
+
+  auto next = rit--;
+  ASSERT_EQ(next->first, 2);
+  ASSERT_EQ(rit->first, 3);
+
+  ++rit;
+  --rit;
+  ASSERT_EQ(rit.base(), s.rbegin().base());
+  ASSERT_TRUE(rit == s.rbegin());
+  ASSERT_EQ(s.rend() - s.rbegin(), ptrdiff_t(3));
+
+  // Implicit conversion from reverse_iterator to const_reverse_iterator.
+  span<Pair>::const_reverse_iterator crit = s.rbegin();
+  ASSERT_EQ(crit.base(), s.crbegin().base());
+  ASSERT_TRUE(crit == s.crbegin());
+  ASSERT_TRUE(crit != s.crend());
+  ASSERT_EQ((crit + 2)->first, 1);
+}
+
 TEST(LlvmLibcSpanTest, SubSpan) {
   int a[] = {1, 2, 3};
   span<const int> s(a);
-  { // same span
-    const auto _ = s.subspan(0);
-    ASSERT_EQ(_.size(), size_t(3));
-    ASSERT_EQ(_[0], 1);
-    ASSERT_EQ(_[1], 2);
-    ASSERT_EQ(_[2], 3);
+  {
+    const auto SUB = s.subspan(0);
+    ASSERT_EQ(SUB.size(), size_t(3));
+    ASSERT_EQ(SUB[0], 1);
+    ASSERT_EQ(SUB[1], 2);
+    ASSERT_EQ(SUB[2], 3);
   }
-  { // last element
-    const auto _ = s.subspan(2);
-    ASSERT_EQ(_.size(), size_t(1));
-    ASSERT_EQ(_[0], 3);
+  {
+    const auto SUB = s.subspan(2);
+    ASSERT_EQ(SUB.size(), size_t(1));
+    ASSERT_EQ(SUB[0], 3);
   }
-  { // no element
-    const auto _ = s.subspan(3);
-    ASSERT_EQ(_.size(), size_t(0));
+  {
+    const auto SUB = s.subspan(3);
+    ASSERT_EQ(SUB.size(), size_t(0));
   }
-  { // first element
-    const auto _ = s.subspan(0, 1);
-    ASSERT_EQ(_.size(), size_t(1));
-    ASSERT_EQ(_[0], 1);
+  {
+    const auto SUB = s.subspan(0, 1);
+    ASSERT_EQ(SUB.size(), size_t(1));
+    ASSERT_EQ(SUB[0], 1);
   }
 }
 
@@ -226,13 +442,120 @@ TEST(LlvmLibcSpanTest, FirstAndLastSubSpan) {
   int a[] = {1, 2, 3};
   span<const int> s(a);
 
-  const auto first = s.first(2);
-  ASSERT_EQ(first.size(), size_t(2));
-  ASSERT_EQ(first[0], 1);
-  ASSERT_EQ(first[1], 2);
+  const auto FIRST = s.first(2);
+  ASSERT_EQ(FIRST.size(), size_t(2));
+  ASSERT_EQ(FIRST[0], 1);
+  ASSERT_EQ(FIRST[1], 2);
+
+  const auto LAST = s.last(2);
+  ASSERT_EQ(LAST.size(), size_t(2));
+  ASSERT_EQ(LAST[0], 2);
+  ASSERT_EQ(LAST[1], 3);
+
+  ASSERT_TRUE(s.first(0).empty());
+  ASSERT_TRUE(s.last(0).empty());
+}
+
+TEST(LlvmLibcSpanTest, CompileTimeSubviews) {
+  int a[] = {10, 20, 30, 40};
+  span<int> s(a);
+
+  const auto FIRST_ZERO = s.first<0>();
+  ASSERT_TRUE(FIRST_ZERO.empty());
+
+  const auto FIRST_TWO = s.first<2>();
+  ASSERT_EQ(FIRST_TWO.size(), size_t(2));
+  ASSERT_EQ(FIRST_TWO[0], 10);
+  ASSERT_EQ(FIRST_TWO[1], 20);
+
+  const auto LAST_ZERO = s.last<0>();
+  ASSERT_TRUE(LAST_ZERO.empty());
+
+  const auto LAST_TWO = s.last<2>();
+  ASSERT_EQ(LAST_TWO.size(), size_t(2));
+  ASSERT_EQ(LAST_TWO[0], 30);
+  ASSERT_EQ(LAST_TWO[1], 40);
+
+  const auto SUB_DYNAMIC = s.subspan<1>();
+  ASSERT_EQ(SUB_DYNAMIC.size(), size_t(3));
+  ASSERT_EQ(SUB_DYNAMIC[0], 20);
+  ASSERT_EQ(SUB_DYNAMIC[2], 40);
+
+  const auto SUB_FIXED = s.subspan<1, 2>();
+  ASSERT_EQ(SUB_FIXED.size(), size_t(2));
+  ASSERT_EQ(SUB_FIXED[0], 20);
+  ASSERT_EQ(SUB_FIXED[1], 30);
+
+  const auto SUB_END = s.subspan<4, 0>();
+  ASSERT_TRUE(SUB_END.empty());
+}
+
+TEST(LlvmLibcSpanTest, AsBytesAndWritableBytes) {
+  uint32_t values[] = {0x01020304U, 0x05060708U};
+  span<uint32_t> s(values);
+
+  span<const byte> ro_bytes = as_bytes(s);
+  ASSERT_EQ(ro_bytes.size(), sizeof(values));
+  ASSERT_EQ(ro_bytes.data(), reinterpret_cast<const byte *>(values));
+
+  const auto *raw = reinterpret_cast<const unsigned char *>(values);
+  for (size_t i = 0; i < ro_bytes.size(); ++i)
+    EXPECT_EQ(to_integer<unsigned char>(ro_bytes[i]), raw[i]);
+
+  span<byte> rw_bytes = as_writable_bytes(s);
+  ASSERT_EQ(rw_bytes.size(), sizeof(values));
+  for (byte &b : rw_bytes)
+    b = byte{0};
+  EXPECT_EQ(values[0], uint32_t(0));
+  EXPECT_EQ(values[1], uint32_t(0));
+
+  span<const uint32_t> cs(values);
+  span<const byte> cs_bytes = as_bytes(cs);
+  ASSERT_EQ(cs_bytes.size(), sizeof(values));
+}
+
+#ifndef NDEBUG
+TEST(LlvmLibcSpanTest, PreconditionDeath) {
+  int a[] = {1, 2, 3};
+  span<int> empty_s;
+  span<int> s(a);
+
+  // Inverted [first, end) range.
+  ASSERT_DEATH(([] {
+                 int arr[] = {1, 2, 3};
+                 span<int> bad(arr + 2, arr + 1);
+                 (void)bad;
+               }),
+               WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] {
+                 span<int> bad(a, nullptr);
+                 (void)bad;
+               }),
+               WITH_SIGNAL(-1));
+
+  // Out-of-bounds operator[].
+  ASSERT_DEATH(([&] { (void)empty_s[0]; }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s[3]; }), WITH_SIGNAL(-1));
+
+  // Empty front() and back().
+  ASSERT_DEATH(([&] { (void)empty_s.front(); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)empty_s.back(); }), WITH_SIGNAL(-1));
+
+  // Out-of-bounds first() and last().
+  ASSERT_DEATH(([&] { (void)s.first(4); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s.first<4>(); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s.last(4); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s.last<4>(); }), WITH_SIGNAL(-1));
 
-  const auto last = s.last(2);
-  ASSERT_EQ(last.size(), size_t(2));
-  ASSERT_EQ(last[0], 2);
-  ASSERT_EQ(last[1], 3);
+  // Out-of-bounds and wrapping subspan().
+  ASSERT_DEATH(([&] { (void)s.subspan(4); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s.subspan<4>(); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s.subspan(2, 2); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] { (void)s.subspan<2, 2>(); }), WITH_SIGNAL(-1));
+  ASSERT_DEATH(([&] {
+                 (void)s.subspan(
+                     2, LIBC_NAMESPACE::cpp::numeric_limits<size_t>::max() - 1);
+               }),
+               WITH_SIGNAL(-1));
 }
+#endif // NDEBUG
diff --git a/libc/test/src/__support/CPP/stringstream_test.cpp b/libc/test/src/__support/CPP/stringstream_test.cpp
index e285fc5715bce2..967dce1b854c5f 100644
--- a/libc/test/src/__support/CPP/stringstream_test.cpp
+++ b/libc/test/src/__support/CPP/stringstream_test.cpp
@@ -1,18 +1,34 @@
-//===-- Unittests for StringStream ----------------------------------------===//
+//===----------------------------------------------------------------------===//
 //
 // 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
+/// Unit tests for cpp::StringStream.
+///
+//===----------------------------------------------------------------------===//
 
 #include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
 #include "src/__support/CPP/stringstream.h"
 #include "test/UnitTest/Test.h"
 
 using LIBC_NAMESPACE::cpp::span;
+using LIBC_NAMESPACE::cpp::string_view;
 using LIBC_NAMESPACE::cpp::StringStream;
 
+constexpr bool test_constexpr_stringstream() {
+  char buf[16] = {};
+  StringStream ss(buf);
+  ss << "hi" << '!';
+  return !ss.overflow() && ss.str() == string_view("hi!");
+}
+
+static_assert(test_constexpr_stringstream());
+
 TEST(LlvmLibcStringStreamTest, Simple) {
   char buf[256];
 
@@ -47,3 +63,14 @@ TEST(LlvmLibcStringStreamTest, Overflow) {
   ASSERT_TRUE(ss2.overflow());
   ASSERT_EQ(ss2.str().size(), BUFSIZE);
 }
+
+TEST(LlvmLibcStringStreamTest, EmptyBuffer) {
+  StringStream ss(span<char>{});
+  ASSERT_EQ(ss.bufsize(), size_t(0));
+  ASSERT_FALSE(ss.overflow());
+  ss << "";
+  ASSERT_FALSE(ss.overflow());
+  ss << 'x';
+  ASSERT_TRUE(ss.overflow());
+  ASSERT_EQ(ss.str().size(), size_t(0));
+}



More information about the libc-commits mailing list