[llvm] [libcxx] [clang-tools-extra] [clang] [libc++][span] P2821R5: span.at() (PR #74994)

Mark de Wever via cfe-commits cfe-commits at lists.llvm.org
Sun Dec 10 12:02:10 PST 2023


================
@@ -0,0 +1,136 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// <span>
+
+// constexpr reference at(size_type idx) const; // since C++26
+
+#include <array>
+#include <cassert>
+#include <concepts>
+#include <span>
+#include <stdexcept>
+#include <utility>
+#include <vector>
+
+#include "test_macros.h"
+
+constexpr void testSpanAt(auto span, int idx, int expectedValue) {
+  // non-const
+  {
+    std::same_as<typename decltype(span)::reference> decltype(auto) elem = span.at(idx);
+    assert(elem == expectedValue);
+  }
+
+  // const
+  {
+    std::same_as<typename decltype(span)::reference> decltype(auto) elem = std::as_const(span).at(idx);
+    assert(elem == expectedValue);
+  }
+}
+
+constexpr bool test() {
+  // With static extent
+  {
+    std::array arr{0, 1, 2, 3, 4, 5, 9084};
+    std::span arrSpan{arr};
+
+    assert(std::dynamic_extent != arrSpan.extent);
+
+    testSpanAt(arrSpan, 0, 0);
+    testSpanAt(arrSpan, 1, 1);
+    testSpanAt(arrSpan, 6, 9084);
+  }
+
+  // With dynamic extent
+  {
+    std::vector vec{0, 1, 2, 3, 4, 5, 9084};
+    std::span vecSpan{vec};
+
+    assert(std::dynamic_extent == vecSpan.extent);
+
+    testSpanAt(vecSpan, 0, 0);
+    testSpanAt(vecSpan, 1, 1);
+    testSpanAt(vecSpan, 6, 9084);
+  }
+
+  return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+  // With static extent
+  {
+    std::array arr{1, 2, 3, 4};
+    const std::span arrSpan{arr};
+
+    try {
+      TEST_IGNORE_NODISCARD arrSpan.at(arr.size() + 1);
+      assert(false);
+    } catch (std::out_of_range const&) {
+      // pass
----------------
mordante wrote:

For libc++ you can test for the expected message.

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


More information about the cfe-commits mailing list