Wyatt Hepler | ee3e02f | 2019-12-05 10:52:31 -0800 | [diff] [blame] | 1 | .. _chapter-pw-span: |
| 2 | |
| 3 | .. default-domain:: cpp |
| 4 | |
| 5 | .. highlight:: sh |
| 6 | |
| 7 | ------- |
| 8 | pw_span |
| 9 | ------- |
| 10 | The pw_span module provides an implementation of C++20's |
| 11 | `std::span <https://en.cppreference.com/w/cpp/container/span>`_, which is a |
| 12 | non-owning view of an array of values. The intent is for ``pw::span``'s |
| 13 | interface 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 Frolov | 44d5473 | 2020-01-10 14:45:43 -0800 | [diff] [blame] | 17 | from C arrays, ``std::array``, or any STL-style container, such as |
Wyatt Hepler | ee3e02f | 2019-12-05 10:52:31 -0800 | [diff] [blame] | 18 | ``std::string_view``. |
| 19 | |
| 20 | Functions operating on an array of bytes typically accept pointer and size |
| 21 | arguments: |
| 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 | |
| 33 | Pointer 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 Hepler | 867d42d | 2019-12-09 18:54:31 -0800 | [diff] [blame] | 43 | ProcessBuffer(pw::span(data_pointer, data_size)); |
Wyatt Hepler | ee3e02f | 2019-12-05 10:52:31 -0800 | [diff] [blame] | 44 | } |
| 45 | |
| 46 | .. tip:: |
Wyatt Hepler | 867d42d | 2019-12-09 18:54:31 -0800 | [diff] [blame] | 47 | 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 Hepler | ee3e02f | 2019-12-05 10:52:31 -0800 | [diff] [blame] | 50 | |
| 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 Hepler | 867d42d | 2019-12-09 18:54:31 -0800 | [diff] [blame] | 57 | ProcessData(pw::as_bytes(pw::span(data))); |
Wyatt Hepler | ee3e02f | 2019-12-05 10:52:31 -0800 | [diff] [blame] | 58 | } |
| 59 | |
| 60 | Compatibility |
| 61 | ============= |
| 62 | C++17 |