Skip to content

Commit 93e8427

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 93e8427

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

src/lifetimes/solution.md

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

0 commit comments

Comments
 (0)