blob: 753a0e3ffffeee9d33c2b95801e3504431f0f919 [file] [log] [blame]
Armando Montanez0bcae732020-05-27 13:28:11 -07001.. _chapter-stream:
2
3.. default-domain:: cpp
4
5.. highlight:: sh
6
7---------
8pw_stream
9---------
10
11``pw_stream`` provides a foundational interface for streaming data from one part
12of a system to another. In the simplest use cases, this is basically a memcpy
13behind a reusable interface that can be passed around the system. On the other
14hand, the flexibility of this interface means a ``pw_stream`` could terminate is
15something more complex, like a UART stream or flash memory.
16
17Overview
18========
19At the most basic level, ``pw_stream``'s interfaces provide very simple handles
20to enabling streaming data from one location in a system to an endpoint.
21
22Example:
23
24.. code-block:: cpp
25
26 void DumpSensorData(pw::stream::Writer& writer) {
27 static char temp[64];
28 ImuSample imu_sample;
29 imu.GetSample(&info);
30 size_t bytes_written = imu_sample.AsCsv(temp, sizeof(temp));
31 writer.Write(temp, bytes_written);
32 }
33
34In this example, ``DumpSensorData()`` only cares that it has access to a
35``Writer`` that it can use to stream data to using ``Writer::Write()``. The
36``Writer`` itself can be backed by anything that can act as a data "sink."
37
38
39pw::stream::Writer
40------------------
41This is the foundational stream ``Writer`` abstract class. Any class that wishes
42to implement the ``Writer`` interface **must** provide a ``DoWrite()``
43implementation. Note that ``Write()`` itself is **not** virtual, and should not
44be overridden.
45
46Buffering
47^^^^^^^^^
48If any buffering occurs in a ``Writer`` and data must be flushed before it is
49fully committed to the sink, a ``Writer`` may optionally override ``Flush()``.
50Writes to a buffer may optimistically return ``Status::OK``, so depend on the
51return value of ``Flush()`` to ensure any pending data is committed to a sink.
52
53Generally speaking, the scope that instantiates the concrete ``Writer`` class
54should be in charge of calling ``Flush()``, and functions that only have access
55to the Writer interface should avoid calling this function.
56
57pw::stream::MemoryWriter
58------------------------
59The ``MemoryWriter`` class implements the ``Writer`` interface by backing the
60data destination with an **externally-provided** memory buffer.
61``MemoryWriterBuffer`` extends ``MemoryWriter`` to internally provide a memory
62buffer.
63
64Why use pw_stream?
65==================
66
67Standard API
68------------
69``pw_stream`` provides a standard way for classes to express that they have the
70ability to write data. Writing to one sink versus another sink is a matter of
71just passing a reference to the appropriate ``Writer``.
72
73As an example, imagine dumping sensor data. If written against a random HAL
74or one-off class, there's porting work required to write to a different sink
75(imagine writing over UART vs dumping to flash memory). Building a "dumping"
76implementation against the ``Writer`` interface prevents a dependency from
77forming on an artisainal API that would require porting work.
78
79Similarly, after building a ``Writer`` implementation for a Sink that data
80could be dumped to, that same ``Writer`` can be reused for other contexts that
81already write data to the ``pw::stream::Writer`` interface.
82
83Before:
84
85.. code-block:: cpp
86
87 // Not reusable, depends on `Uart`.
88 void DumpSensorData(Uart& uart) {
89 static char temp[64];
90 ImuSample imu_sample;
91 imu.GetSample(&info);
92 size_t bytes_written = imu_sample.AsCsv(temp, sizeof(temp));
93 uart.Transmit(temp, bytes_written, /*timeout_ms=*/ 200);
94 }
95
96After:
97
98.. code-block:: cpp
99
100 // Reusable; no more Uart dependency!
101 void DumpSensorData(Writer& writer) {
102 static char temp[64];
103 ImuSample imu_sample;
104 imu.GetSample(&info);
105 size_t bytes_written = imu_sample.AsCsv(temp, sizeof(temp));
106 writer.Write(temp, bytes_written);
107 }
108
109Reduce intermediate buffers
110---------------------------
111Often functions that write larger blobs of data request a buffer is passed as
112the destination that data should be written to. This *requires* a buffer is
113allocated, even if the data only exists in that buffer for a very short period
114of time before it's written somewhere else.
115
116In situations where data read from somewhere will immediately be written
117somewhere else, a ``Writer`` interface can cut out the middleman buffer.
118
119Before:
120
121.. code-block:: cpp
122
123 // Requires an intermediate buffer to write the data as CSV.
124 void DumpSensorData(Uart* uart) {
125 char temp[64];
126 ImuSample imu_sample;
127 imu.GetSample(&info);
128 size_t bytes_written = imu_sample.AsCsv(temp, sizeof(temp));
129 uart.Transmit(temp, bytes_written, /*timeout_ms=*/ 200);
130 }
131
132After:
133
134.. code-block:: cpp
135
136 // Both DumpSensorData() and RawSample::AsCsv() use a Writer, eliminating the
137 // need for an intermediate buffer.
138 void DumpSensorData(Writer* writer) {
139 RawSample imu_sample;
140 imu.GetSample(&info);
141 imu_sample.AsCsv(writer);
142 }
143
144Prevent buffer overflow
145-----------------------
146When copying data from one buffer to another, there must be checks to ensure the
147copy does not overflow the destination buffer. As this sort of logic is
148duplicated throughout a codebase, there's more opportunities for bound-checking
149bugs to sneak in. ``Writers`` manage this logic internally rather than pushing
150the bounds checking to the code that is moving or writing the data.
151
152Similarly, since only the ``Writer`` has access to any underlying buffers, it's
153harder for functions that share a ``Writer`` to accidentally clobber data
154written by others using the same buffer.
155
156Before:
157
158.. code-block:: cpp
159
160 Status BuildPacket(Id dest, span<const std::byte> payload,
161 span<std::byte> dest) {
162 Header header;
163 if (dest.size_bytes() + payload.size_bytes() < sizeof(Header)) {
164 return Status::RESOURCE_EXHAUSTED;
165 }
166 header.dest = dest;
167 header.src = DeviceId();
168 header.payload_size = payload.size_bytes();
169
170 memcpy(dest.data(), &header, sizeof(header));
171 // Forgetting this line would clobber buffer contents. Also, using
172 // a temporary span instead could leave `dest` to be misused elsewhere in
173 // the function.
174 dest = dest.subspan(sizeof(header));
175 memcpy(dest.data(), payload.data(), payload.size_bytes());
176 }
177
178After:
179
180.. code-block:: cpp
181
182 Status BuildPacket(Id dest, span<const std::byte> payload, Writer& writer) {
183 Header header;
184 header.dest = dest;
185 header.src = DeviceId();
186 header.payload_size = payload.size_bytes();
187
188 writer.Write(header);
189 return writer.Write(payload);
190 }
191
192Why NOT pw_stream?
193==================
194pw_stream provides a virtual interface. This inherently has more overhead than
195a regular function call. In extremely performance-sensitive contexts, a virtual
196interface might not provide enough utility to justify the performance cost.
197
198Dependencies
199============
200 * ``pw_assert`` module
201 * ``pw_preprocessor`` module
202 * ``pw_status`` module
203 * ``pw_span`` module