1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
//! Types for stream decoders.
//!
//! A stream decoder reads a message's fields in wire order and passes the ones you select to your
//! handlers. It builds no message and does not allocate. `rapidproto-build` generates stream decoders
//! when you turn on its [`Config::stream`]. The [`example`](crate::example) module shows the generated
//! code.
//!
//! For each message `Msg`, the generator emits a stream struct `Msg<'a>`, a visitor trait
//! `MsgVisitor<'a>`, and a macro `msg_stream!` that builds a visitor from handlers. Decode with
//! `Msg::new(input)?.decode(visitor)`.
//!
//! # Handlers
//!
//! With `msg_stream! { field => |value| .. }`, each handler is a closure that captures its own state.
//! Two closures cannot both change the same variable. To share state, pass it first, as in
//! `msg_stream!(&mut state; { field => |state, value| .. })`.
//!
//! A handler closure returns `()`, a [`Flow`], or a `Result` of either with [`DecodeError`]. An
//! `on_<field>` method returns `Result<Flow, DecodeError>`. An error ends the decode, and `decode`
//! returns it. `Flow::Stop` ends the decode, and `decode` returns `Ok(Flow::Stop)`. A decode that
//! reaches the end of its message returns `Ok(Flow::Continue)`.
//!
//! A handler for a sub-message chooses how far a stop reaches. `|sub| sub.decode(..)` returns the
//! result, so a stop inside the sub-message ends the outer `decode` too.
//! `|sub| { sub.decode(..)?; Ok(()) }` discards the `Flow`, so it ends only the sub-message. Both pass
//! an error on.
//!
//! # What a handler receives
//!
//! | Field | Handler receives |
//! |---|---|
//! | Scalar, `string` or `bytes` | Its value |
//! | Enum | Its generated enum type, which holds any `i32` |
//! | Sub-message or group | Its stream struct, to `decode` or ignore |
//! | `map` | A `(key, value)` pair, where a message value is its stream struct |
//! | Unknown field | An [`UnknownField`], in the `unknown` handler |
//!
//! A `repeated` field calls its handler once per element, packed or not, and a `map` field once per
//! entry. A singular field that appears twice on the wire calls its handler twice. Each member of a
//! `oneof` has its own handler, and a later member does not replace an earlier one.
//!
//! A declared field that arrives with the wrong wire type is skipped, and does not reach `unknown`. A
//! stream decoder does not check `required` fields.
//!
//! # Untrusted input
//!
//! `decode` does not decode sub-messages itself. It hands them to your handlers. If your handlers
//! follow a recursive schema on untrusted input, limit the depth yourself, because
//! [`MAX_DECODE_DEPTH`](crate::MAX_DECODE_DEPTH) applies only to arena decoders. Groups are the
//! exception. Nesting them deeper than `MAX_DECODE_DEPTH` fails, even when they are skipped.
//!
//! # Many fields
//!
//! The macro takes one recursion step per selected field, and macro calls nested in handlers share
//! rustc's recursion limit. Above about 120 selected fields, add `#![recursion_limit = "256"]` to your
//! crate.
//!
//! # Writing a visitor by hand
//!
//! The `msg_stream!` macro is the usual way to build a visitor, but you can also implement the
//! generated `MsgVisitor` trait yourself, for example for a reusable visitor type. To select a field,
//! set its `WANT_<field>` to `true` and override its `on_<field>` method. The macro does both, but by
//! hand it is easy to forget `WANT_<field>`, and then `on_<field>` is never called.
//!
//! `decode` takes the visitor by value, so implement the trait for a `&mut` reference to your type to
//! keep its state after the decode. A handler for a sub-message passes the same state on with
//! `station.decode(&mut **self)`. This counts the stations and temperatures in `input`, an encoded
//! `Report` from the [`example`](crate::example) schema:
//!
//! ```
//! # mod example { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/example/weather.rs")); }
//! # fn main() -> Result<(), rapidproto::DecodeError> {
//! # let input = b"\x0a\x14\x0a\x06Zurich\x18\x01\x22\x08\x00\x00\x48\x41\x00\x00\x50\x41";
//! use example::stream::weather::{Report, ReportVisitor, Station, StationVisitor};
//! use rapidproto::stream::Flow;
//! use rapidproto::DecodeError;
//!
//! #[derive(Default)]
//! struct Count {
//! stations: usize,
//! temperatures: usize,
//! }
//!
//! impl<'a> ReportVisitor<'a> for &mut Count {
//! const WANT_stations: bool = true;
//! fn on_stations(&mut self, station: Station<'a>) -> Result<Flow, DecodeError> {
//! self.stations += 1;
//! station.decode(&mut **self)
//! }
//! }
//!
//! impl<'a> StationVisitor<'a> for &mut Count {
//! const WANT_temperatures: bool = true; // without it, `on_temperatures` is never called
//! fn on_temperatures(&mut self, _: f32) -> Result<Flow, DecodeError> {
//! self.temperatures += 1;
//! Ok(Flow::Continue)
//! }
//! }
//!
//! let mut count = Count::default();
//! Report::new(input)?.decode(&mut count)?;
//! assert_eq!((count.stations, count.temperatures), (1, 2));
//! # Ok(())
//! # }
//! ```
//!
//! [`Config::stream`]: https://docs.rs/rapidproto-build/latest/rapidproto_build/struct.Config.html#method.stream
use fmt;
use crateDecodeError;
pub use crateWireType;
/// Whether a stream decode continues or stops.
///
/// A handler returns it to choose, and `decode` returns it to say which happened.
/// What a field-handler closure may return, normalized to the driver's `Result<Flow, DecodeError>`:
/// `()` continues, a [`Flow`] continues or stops, and a `Result<_, DecodeError>` lets a handler
/// propagate a failure (e.g. `child.decode(..)?` on a malformed sub-message) out of the outer
/// `decode`. Implemented for `()`, `Flow`, `Result<(), DecodeError>`, and `Result<Flow, DecodeError>`.
/// The glue that lets a field handler be any `FnMut(V)` returning a [`HandlerRet`]. The generated
/// `msg_stream!` macro bounds each selected field's closure as `Handler<V>` and calls
/// [`call`](Handler::call); not implemented by consumers (the blanket impl covers every suitable
/// closure).
/// Fix a field handler's closure parameter to the field's value type `V`, so the consumer need not
/// annotate it even when the body alone does not pin the type (e.g. `|s| s.0`, `|sub| sub.decode(..)`).
/// The generated `msg_stream!` macro wraps each closure with the field's `V` in the turbofish; the
/// returned closure is unchanged. Internal to the generated glue, not called by consumers directly.
/// The glue for the shared-state macro form: a field handler that takes the lent `&mut S` as its first
/// argument and the field's value as its second. The generated `msg_stream!(&mut state; { .. })` form
/// bounds each selected field's closure as `Handler2<S, V>` and calls [`call`](Handler2::call),
/// passing one reborrow of the visitor's `&mut state` per occurrence; because the state is passed, not
/// captured, every field's handler can touch it without the aliasing an `FnMut(V)` capture would need.
/// Not implemented by consumers (the blanket impl covers every suitable closure).
/// Pin a shared-state handler's two parameter types so the consumer annotates neither: the state type
/// `S` is fixed from the `&*state` hint the generated macro passes, and the value type `V` from the
/// turbofish. The `_state_hint` reference is a transient borrow only used to infer `S`; the returned
/// closure is unchanged. Internal to the generated glue, not called by consumers directly.
Sized, V, R, F: FnMut >
/// Builds the anonymous visitor a generated `<msg>_stream!` macro expands to, from the per-field rows
/// that macro collected: `$Tr` is the message's visitor trait at the impl lifetime `'rp_a`. A row is
/// `WANT_<f> on_<f>: V = closure;` -- the trait's const and method names and the field's value type at
/// that lifetime. `on_<f>` doubles as the struct field and its closure's type parameter (separate
/// namespaces), and each `V` gets a
/// block-local alias named by its const (`type WANT_<f><'rp_a> = V`) so the constructor can name it at
/// `'_` to pin the closure's parameter types. A leading `[]` selects the plain form, `[state]` the
/// shared-state form that lends one `&mut state` to every handler. Internal to the generated glue.
/// It expands at the caller's call site, so it names every outside item by an absolute path.
/// A field the schema does not declare, passed to the `unknown` handler.
/// Prints the field number, the wire type and the value bytes as a byte string.