• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. _module-pw_span:
2
3-------
4pw_span
5-------
6The ``pw_span`` module provides an implementation of C++20's
7`std::span <https://en.cppreference.com/w/cpp/container/span>`_, which is a
8non-owning view of an array of values. The intent is for this implementation of
9``std::span`` is to exactly match the C++20 standard.
10
11The only header provided by the ``pw_span`` module is ``<span>``. It is included
12as if it were coming from the C++ Standard Library. If the C++ library provides
13``<span>``, the library's version of ``std::span`` is used in place of
14``pw_span``'s.
15
16``pw_span`` requires two include paths -- ``public/`` and ``public_overrides/``.
17The internal implementation header is in ``public/``, and the ``<span>`` header
18that mimics the C++ Standard Library is in ``public_overrides/``.
19
20Using std::span
21===============
22``std::span`` is a convenient abstraction that wraps a pointer and a size.
23``std::span`` is especially useful in APIs. Spans support implicit conversions
24from C arrays, ``std::array``, or any STL-style container, such as
25``std::string_view``.
26
27Functions operating on an array of bytes typically accept pointer and size
28arguments:
29
30.. code-block:: cpp
31
32  bool ProcessBuffer(char* buffer, size_t buffer_size);
33
34  bool DoStuff() {
35    ProcessBuffer(c_array, sizeof(c_array));
36    ProcessBuffer(array_object.data(), array_object.size());
37    ProcessBuffer(data_pointer, data_size);
38  }
39
40Pointer and size arguments can be replaced with a ``std::span``:
41
42.. code-block:: cpp
43
44  #include <span>
45
46  // With std::span, the buffer is passed as a single argument.
47  bool ProcessBuffer(std::span<uint8_t> buffer);
48
49  bool DoStuff() {
50    ProcessBuffer(c_array);
51    ProcessBuffer(array_object);
52    ProcessBuffer(std::span(data_pointer, data_size));
53  }
54
55.. tip::
56  Use ``std::span<std::byte>`` or ``std::span<const std::byte>`` to represent
57  spans of binary data. Use ``std::as_bytes`` or ``std::as_writeable_bytes``
58  to convert any span to a byte span.
59
60  .. code-block:: cpp
61
62    void ProcessData(std::span<const std::byte> data);
63
64    void DoStuff() {
65      std::array<AnyType, 7> data = { ... };
66      ProcessData(std::as_bytes(std::span(data)));
67    }
68
69Compatibility
70=============
71Works with C++11, but some features require C++17.
72