Skip to content

Commit 45d8465

Browse files
committed
lifetimes: add explanatory commentary to solution
This commentary, written by Gemini, focuses on aspects of the solution that differ from the baseline languages (C/Java/Python), highlighting Rust-specific idioms and concepts.
1 parent 0867e24 commit 45d8465

1 file changed

Lines changed: 23 additions & 0 deletions

File tree

src/lifetimes/solution.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,26 @@
33
```rust,editable
44
{{#include exercise.rs:solution}}
55
```
6+
7+
- **Zero-Copy Parsing:** This solution demonstrates zero-copy parsing. The
8+
`Person` and `PhoneNumber` structs borrow string slices (`&'a str`) directly
9+
from the input byte array (`&'a [u8]`). No new strings are allocated for the
10+
field values.
11+
- **Lifetimes:** The lifetime `'a` ensures that the returned `Person` cannot
12+
outlive the input data buffer. If the buffer is dropped, the `Person` becomes
13+
invalid, which the compiler enforces.
14+
- **Slicing:** We use `split_at` to divide the input buffer into the data for
15+
the current field and the remainder. This is efficient as it only manipulates
16+
pointers and lengths, not the data itself.
17+
- **Recursion:** The parsing is recursive. `Person` contains `PhoneNumber`s,
18+
which are themselves parsed by calling `parse_message` on the bytes contained
19+
within the `Len` wire type.
20+
21+
<details>
22+
23+
- Note that `parse_message` requires `T` to implement `Default` so it can start
24+
with an empty message and fill it in.
25+
- The `WireType` enum and `parse_varint` function handle the low-level encoding
26+
details, allowing the main logic to focus on structure.
27+
28+
</details>

0 commit comments

Comments
 (0)