diff --git a/cpp/src/arrow/array/data.h b/cpp/src/arrow/array/data.h index 4c2df8381490a..f29f164d19973 100644 --- a/cpp/src/arrow/array/data.h +++ b/cpp/src/arrow/array/data.h @@ -18,6 +18,7 @@ #pragma once #include // IWYU pragma: export +#include #include #include #include @@ -438,6 +439,36 @@ struct ARROW_EXPORT ArraySpan { return GetValues(i, this->offset); } + /// \brief Access a buffer's data as a span + /// + /// \param i The buffer index + /// \param length The required length (in number of typed values) of the requested span + /// \pre i > 0 + /// \pre length <= the length of the buffer (in number of values) that's expected for + /// this array type + /// \return A span of the requested length + template + util::span GetSpan(int i, int64_t length) const { + const int64_t buffer_length = buffers[i].size / static_cast(sizeof(T)); + assert(i > 0 && length + offset <= buffer_length); + return util::span(buffers[i].data_as() + this->offset, length); + } + + /// \brief Access a buffer's data as a span + /// + /// \param i The buffer index + /// \param length The required length (in number of typed values) of the requested span + /// \pre i > 0 + /// \pre length <= the length of the buffer (in number of values) that's expected for + /// this array type + /// \return A span of the requested length + template + util::span GetSpan(int i, int64_t length) { + const int64_t buffer_length = buffers[i].size / static_cast(sizeof(T)); + assert(i > 0 && length + offset <= buffer_length); + return util::span(buffers[i].mutable_data_as() + this->offset, length); + } + inline bool IsNull(int64_t i) const { return !IsValid(i); } inline bool IsValid(int64_t i) const { diff --git a/cpp/src/arrow/buffer.h b/cpp/src/arrow/buffer.h index ae76550be26fc..52fd94ec1f7d4 100644 --- a/cpp/src/arrow/buffer.h +++ b/cpp/src/arrow/buffer.h @@ -30,6 +30,7 @@ #include "arrow/status.h" #include "arrow/type_fwd.h" #include "arrow/util/macros.h" +#include "arrow/util/span.h" #include "arrow/util/visibility.h" namespace arrow { @@ -233,6 +234,12 @@ class ARROW_EXPORT Buffer { return reinterpret_cast(data()); } + /// \brief Return the buffer's data as a span + template + util::span span_as() const { + return util::span(data_as(), static_cast(size() / sizeof(T))); + } + /// \brief Return a writable pointer to the buffer's data /// /// The buffer has to be a mutable CPU buffer (`is_cpu()` and `is_mutable()` @@ -260,6 +267,12 @@ class ARROW_EXPORT Buffer { return reinterpret_cast(mutable_data()); } + /// \brief Return the buffer's mutable data as a span + template + util::span mutable_span_as() const { + return util::span(mutable_data_as(), static_cast(size() / sizeof(T))); + } + /// \brief Return the device address of the buffer's data uintptr_t address() const { return reinterpret_cast(data_); }