Project 5: A Safe Wrapper around a C Library
A safe, idiomatic Rust wrapper around a C library like
libz(for compression) orsqlite3. Your Rust library will expose a clean API that usesResultfor errors and handles memory management automatically, hiding theunsafeC-level details.
Quick Reference
| Attribute | Value |
|---|---|
| Primary Language | Rust |
| Alternative Languages | C, Python (with ctypes) |
| Difficulty | Level 4: Expert |
| Time Estimate | 2-3 weeks |
| Knowledge Area | Foreign Function Interface (FFI) / API Design |
| Tooling | bindgen, libclang |
| Prerequisites | Project 1, basic C knowledge. |
What You Will Build
A safe, idiomatic Rust wrapper around a C library like libz (for compression) or sqlite3. Your Rust library will expose a clean API that uses Result for errors and handles memory management automatically, hiding the unsafe C-level details.
Why It Matters
This project builds core skills that appear repeatedly in real-world systems and tooling.
Core Challenges
- Linking to a C library → maps to using a build script (
build.rs) - Generating Rust bindings for C functions → maps to using the
bindgentool - Calling
unsafeC functions → maps to working with raw pointers andunsafeblocks - Creating safe abstractions → maps to wrapping raw pointers in structs that implement
Dropfor automatic cleanup, and converting C integer error codes into RustResulttypes
Key Concepts
unsafekeyword: “The Rust Programming Language” Ch. 19- Foreign Function Interface (FFI): “The Rustonomicon” Ch. 6
- The
DropTrait: “The Rust Programming Language” Ch. 15 (for custom cleanup logic) - Build Scripts (
build.rs): The Cargo Book
Real-World Outcome
// The API you will build
use my_zlib_wrapper::compress;
fn main() -> Result<(), ZlibError> {
let data = b"hello world";
let compressed_data = compress(data, 5)?; // 5 is compression level
// compressed_data is a Vec<u8>, memory is managed automatically.
// The C-level z_stream, mallocs, and frees are all hidden.
println!("Compressed: {:?}", compressed_data);
Ok(())
}
// Contrast with the C API:
// You'd have to manually initialize a z_stream struct, allocate buffers,
// call deflate, check integer return codes, and then call deflateEnd.
Implementation Guide
- Reproduce the simplest happy-path scenario.
- Build the smallest working version of the core feature.
- Add input validation and error handling.
- Add instrumentation/logging to confirm behavior.
- Refactor into clean modules with tests.
Milestones
- Milestone 1: Minimal working program that runs end-to-end.
- Milestone 2: Correct outputs for typical inputs.
- Milestone 3: Robust handling of edge cases.
- Milestone 4: Clean structure and documented usage.
Validation Checklist
- Output matches the real-world outcome example
- Handles invalid inputs safely
- Provides clear errors and exit codes
- Repeatable results across runs
References
- Main guide:
LEARN_RUST_FROM_FIRST_PRINCIPLES.md - “The Rustonomicon” Ch. 6 (FFI)