From 5ee74ff157a43b3c682142735b4b3dc8d5d28c1d Mon Sep 17 00:00:00 2001 From: Chen Lai Date: Tue, 17 Jun 2025 15:25:23 -0700 Subject: [PATCH] Support Span to construct from a single element similar to ArrayRef Pull Request resolved: https://github.com/pytorch/executorch/pull/11757 Copy the constructor from ArrayRef here https://github.com/pytorch/executorch/blob/5365c5559accc7a0d522eacdfb7385ce8914ef53/runtime/core/array_ref.h#L78-L81 so it's easier to use ghstack-source-id: 291106564 @exported-using-ghexport Differential Revision: [D76825662](https://our.internmc.facebook.com/intern/diff/D76825662/) --- runtime/core/span.h | 4 ++++ runtime/core/test/span_test.cpp | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/runtime/core/span.h b/runtime/core/span.h index 1bcde396ccd..2202204571a 100644 --- a/runtime/core/span.h +++ b/runtime/core/span.h @@ -55,6 +55,10 @@ class Span final { template /* implicit */ constexpr Span(T (&Arr)[N]) : data_(Arr), length_(N) {} + /// Construct a Span from a single element reference. + /* implicit */ constexpr Span(T& single_element) + : data_(&single_element), length_(1) {} + /// @returns a pointer to the start of the underlying element buffer. iterator begin() const noexcept { return data_; diff --git a/runtime/core/test/span_test.cpp b/runtime/core/test/span_test.cpp index c2d65baf8e7..51063b8be0f 100644 --- a/runtime/core/test/span_test.cpp +++ b/runtime/core/test/span_test.cpp @@ -61,3 +61,19 @@ TEST(SpanTest, TriviallyCopyable) { EXPECT_EQ(span.size(), span_copy.size()); EXPECT_TRUE(std::is_trivially_copyable>::value); } + +TEST(SpanTest, SingleElementConstructor) { + int64_t single_value = 42; + Span span = single_value; + + EXPECT_EQ(span.size(), 1); + EXPECT_EQ(span.data(), &single_value); + EXPECT_EQ(span[0], 42); + EXPECT_EQ(*span.begin(), 42); + EXPECT_EQ(span.end(), span.begin() + 1); + + // Test that modifying through span affects original value + span[0] = 100; + EXPECT_EQ(single_value, 100); + EXPECT_EQ(span[0], 100); +}