[Openmp-commits] [clang] [clang-tools-extra] [openmp] [llvm] [mlir] [lldb] [libc] [libcxx] [flang] [compiler-rt] [libc++][span] P2821R5: span.at() (PR #74994)
Mark de Wever via Openmp-commits
openmp-commits at lists.llvm.org
Sat Dec 16 05:27:58 PST 2023
================
@@ -0,0 +1,170 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 <limits>
+#include <span>
+#include <stdexcept>
+#include <string>
+#include <tuple>
+#include <utility>
+#include <vector>
+
+#include "test_macros.h"
+
+template <typename ReferenceT>
+constexpr void testSpanAt(auto&& anySpan, int index, int expectedValue) {
+ // non-const
+ {
+ std::same_as<ReferenceT> decltype(auto) elem = anySpan.at(index);
+ assert(elem == expectedValue);
+ }
+
+ // const
+ {
+ std::same_as<ReferenceT> decltype(auto) elem = std::as_const(anySpan).at(index);
+ 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);
+
+ using ReferenceT = typename decltype(arrSpan)::reference;
+
+ testSpanAt<ReferenceT>(arrSpan, 0, 0);
+ testSpanAt<ReferenceT>(arrSpan, 1, 1);
+ testSpanAt<ReferenceT>(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);
+
+ using ReferenceT = typename decltype(vecSpan)::reference;
+
+ testSpanAt<ReferenceT>(vecSpan, 0, 0);
+ testSpanAt<ReferenceT>(vecSpan, 1, 1);
+ testSpanAt<ReferenceT>(vecSpan, 6, 9084);
+ }
+
+ return true;
+}
+
+void test_exceptions() {
+#ifndef TEST_HAS_NO_EXCEPTIONS
+ using namespace std::string_literals;
+
+ // With static extent
+ {
+ std::array arr{0, 1, 2, 3, 4, 5, 9084, std::numeric_limits<int>::max()};
+ const std::span arrSpan{arr};
+
+ try {
+ std::ignore = arrSpan.at(arr.size());
+ assert(false);
+ } catch (const std::out_of_range& e) {
+ // pass
+ assert(e.what() == "span"s);
+ } catch (...) {
+ assert(false);
+ }
+
+ try {
+ std::ignore = arrSpan.at(arr.size() - 1);
+ // pass
+ assert(arrSpan.at(arr.size() - 1) == std::numeric_limits<int>::max());
+ } catch (const std::out_of_range&) {
+ assert(false);
----------------
mordante wrote:
```suggestion
```
It think it looks better to only use a `catch(...)` when we don't expect an exception.
https://github.com/llvm/llvm-project/pull/74994
More information about the Openmp-commits
mailing list