blob: dbfc0536481e8e3e9dff3b509fdc6c839d931167 [file] [log] [blame]
Wyatt Hepleree3e02f2019-12-05 10:52:31 -08001.. _chapter-pw-span:
2
3.. default-domain:: cpp
4
5.. highlight:: sh
6
7-------
8pw_span
9-------
10The pw_span module provides an implementation of C++20's
11`std::span <https://en.cppreference.com/w/cpp/container/span>`_, which is a
12non-owning view of an array of values. The intent is for ``pw::span``'s
13interface to exactly match ``std::span``.
14
15``pw::span`` is a convenient abstraction that wraps a pointer and a size.
16``pw::span`` is especially useful in APIs. Spans support implicit conversions
Alexei Frolov44d54732020-01-10 14:45:43 -080017from C arrays, ``std::array``, or any STL-style container, such as
Wyatt Hepleree3e02f2019-12-05 10:52:31 -080018``std::string_view``.
19
20Functions operating on an array of bytes typically accept pointer and size
21arguments:
22
23.. code-block:: cpp
24
25 bool ProcessBuffer(char* buffer, size_t buffer_size);
26
27 bool DoStuff() {
28 ProcessBuffer(c_array, sizeof(c_array));
29 ProcessBuffer(array_object.data(), array_object.size());
30 ProcessBuffer(data_pointer, data_size);
31 }
32
33Pointer and size arguments can be replaced with a ``pw::span``:
34
35.. code-block:: cpp
36
37 // With pw::span, the buffer is passed as a single argument.
38 bool ProcessBuffer(const pw::span<uint8_t>& buffer);
39
40 bool DoStuff() {
41 ProcessBuffer(c_array);
42 ProcessBuffer(array_object);
Wyatt Hepler867d42d2019-12-09 18:54:31 -080043 ProcessBuffer(pw::span(data_pointer, data_size));
Wyatt Hepleree3e02f2019-12-05 10:52:31 -080044 }
45
46.. tip::
Wyatt Hepler867d42d2019-12-09 18:54:31 -080047 Use ``pw::span<std::byte>`` or ``pw::span<const std::byte>`` to represent
48 spans of binary data. Use ``pw::as_bytes`` or ``pw::as_writeable_bytes``
49 to convert any span to a byte span.
Wyatt Hepleree3e02f2019-12-05 10:52:31 -080050
51 .. code-block:: cpp
52
53 void ProcessData(pw::span<const std::byte> data);
54
55 void DoStuff() {
56 std::array<AnyType, 7> data = { ... };
Wyatt Hepler867d42d2019-12-09 18:54:31 -080057 ProcessData(pw::as_bytes(pw::span(data)));
Wyatt Hepleree3e02f2019-12-05 10:52:31 -080058 }
59
60Compatibility
61=============
62C++17