Skip to content

Commit 5ee74ff

Browse files
committed
Support Span to construct from a single element similar to ArrayRef
Pull Request resolved: #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/)
1 parent 1309849 commit 5ee74ff

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

runtime/core/span.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ class Span final {
5555
template <size_t N>
5656
/* implicit */ constexpr Span(T (&Arr)[N]) : data_(Arr), length_(N) {}
5757

58+
/// Construct a Span from a single element reference.
59+
/* implicit */ constexpr Span(T& single_element)
60+
: data_(&single_element), length_(1) {}
61+
5862
/// @returns a pointer to the start of the underlying element buffer.
5963
iterator begin() const noexcept {
6064
return data_;

runtime/core/test/span_test.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,3 +61,19 @@ TEST(SpanTest, TriviallyCopyable) {
6161
EXPECT_EQ(span.size(), span_copy.size());
6262
EXPECT_TRUE(std::is_trivially_copyable<Span<int64_t>>::value);
6363
}
64+
65+
TEST(SpanTest, SingleElementConstructor) {
66+
int64_t single_value = 42;
67+
Span<int64_t> span = single_value;
68+
69+
EXPECT_EQ(span.size(), 1);
70+
EXPECT_EQ(span.data(), &single_value);
71+
EXPECT_EQ(span[0], 42);
72+
EXPECT_EQ(*span.begin(), 42);
73+
EXPECT_EQ(span.end(), span.begin() + 1);
74+
75+
// Test that modifying through span affects original value
76+
span[0] = 100;
77+
EXPECT_EQ(single_value, 100);
78+
EXPECT_EQ(span[0], 100);
79+
}

0 commit comments

Comments
 (0)