port-c-module
Provides a systematic workflow for migrating C modules into Rust safely.
Install
mkdir -p .claude/skills/port-c-module && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/2684" && unzip -o skill.zip -d .claude/skills/port-c-module && rm skill.zipInstalls to .claude/skills/port-c-module
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Guide for porting a C module to Rust. Use this when starting to port a C module to Rust.Key capabilities
- →Analyze C header and source files
- →Create Rust crates for ported modules
- →Implement FFI wrappers for C compatibility
- →Generate migration plans
- →Verify parity with existing C tests
How it works
It guides the user through analyzing C code, creating a Rust crate, implementing logic, and establishing an FFI boundary for integration.
Inputs & outputs
When to use port-c-module
- →Migrating C codebase to Rust
- →Analyzing C header exposure
- →Planning FFI implementations
About this skill
Port Module Skill
Guide for porting a C module to Rust.
Arguments
The module name to port should be provided as an argument (e.g., /port-module triemap).
Module to port: $ARGUMENTS
Usage
Use this skill when starting to port a C module to Rust.
Instructions
1. Analyze the C Code
First, understand the C module you're porting (look for $ARGUMENTS.c and $ARGUMENTS.h in src/):
- Read the
.cand.hfiles insrc/ - Identify what is exposed by the header file:
- Does the rest of the codebase have access to the inner fields of the data structures defined in this module?
- Are types always passed by value or by reference? A mix?
- Can the corresponding Rust types be passed over the FFI boundary?
- Understand data structures and their lifetimes
- Identify which types and functions this module imports from other modules:
- Determine if those types are implemented in Rust or C
- If those types are implemented in Rust, identify the relevant Rust crate
- If those types are implemented in C, understand if it makes sense to port them first to Rust or if it's preferable to invoke the C implementation from Rust via FFI
- Note any global state or Redis module interactions
- Identify which tests under
tests/are relevant to this module - Measure how much of the module the Python flow tests cover with
/check-flow-coverage, and close the gaps with/write-flow-testsbefore porting. The port is only as safe as the tests that pin the C, and writing them often surfaces bugs in the C itself
2. Define A Porting Plan
Outline the steps and decisions for porting the module. The plan is working material, not part of the change: keep it in the conversation or your tooling, and never commit a plan, notes, or PR-draft file. Determine if the C code should be modified, at this stage, to ease the porting process. For example:
- Introduce getters and setters to avoid exposing inner fields of data structures defined in this module.
- Split the module into smaller, more manageable parts.
Contract and divergences
The most important part of the plan separates what must stay the same from what may change.
- Contract: the behavior callers rely on — replies and error texts users see, persisted formats, and the C API semantics other modules depend on. List each item with the test that pins it, existing or to be written. Contract tests go through the production path (Python flow tests or existing C/C++ tests), and are written while C still serves production, so they first pin the C and later prove the Rust.
- Divergences: every place the Rust will behave differently from the C — what C does, what Rust does, and why. Behavior outside the contract is incidental: the state of output arguments after an error, how out-of-range enum values or sentinels are handled, a panic that becomes an error. Port it idiomatically rather than replicating it, and list each such change so a human reviewer can accept or reject it. The divergences belong in the PR description and commit message.
Name each test for the behavior it asserts, never for the contract it belongs to, as
/rust-tests-guidelines describes.
Two PRs
A port ships as two stacked PRs, each small enough to review:
- Rust: tests pinning the C behavior the existing tests miss, the pure Rust implementation and its tests, and the benchmark against C. Production still runs the C.
- Swap: the FFI crate exporting the Rust under the C functions' names, production callers switched to it, and the module's C files deleted, headers included. The first PR's tests now exercise the Rust. Whatever else the headers define that other code shares (structs, enums, constants) moves to Rust in this PR, exported through a generated header; plan that move, because every user of those types changes with it.
When closing the coverage gaps of step 1 takes more than a few tests, or they surface C bugs worth fixing first, land them as a PR of their own ahead of the two.
Who the port affects
Each port is one step in a migration carried out module by module, by a team that maintains the result for years. Before each design choice, ask who else it affects:
- Reviewers read every line, and their attention is the migration's scarcest resource: every file touched is one more to open, understand and approve.
- Others work in the same code: changes spread across many files and crates collide with work in flight. A narrow change lands sooner.
- Redis users depend on the behavior: a divergence changes what applications see, and a memory-safety mistake in the FFI crashes the server and can lose data.
- Later ports copy this one: an abstraction, test layout or workaround becomes precedent.
Prefer the change the codebase's own maintainers would make: the smallest one that does the job completely.
3. Create the Rust Crate
cargo new src/redisearch_rs/$ARGUMENTS --lib
Every crate a port creates, this one and the FFI crate, opens its lib.rs with the lints the
workspace does not enable yet, so make lint enforces them for the new code:
#![warn(
clippy::unwrap_used,
clippy::dbg_macro,
clippy::todo,
clippy::unimplemented,
clippy::print_stdout,
clippy::panic,
clippy::unnecessary_safety_comment,
clippy::ptr_as_ptr,
clippy::borrow_as_ptr,
clippy::ref_as_ptr,
clippy::indexing_slicing
)]
src/redisearch_rs/clippy.toml allows unwrap, panic and indexing in tests.
4. Implement Pure Rust Logic
-
Create idiomatic Rust code: model the domain in Rust types rather than mirroring the C structs, enums and sentinels one to one
-
Keep the crate pure: no C ABI types,
#[repr(C)]layouts for C,extern "C"items or#[no_mangle]exports. They belong to the FFI crate (step 6), and so do Rust tests of the C boundary -
Porting is also cleanup: legacy C carries cruft, and a port may simplify where the result is smaller and no caller relies on the old shape, such as a null-pointer fallback no caller uses or a length limit that only existed for a C stack buffer. Keep it measured: a simplification that grows the diff noticeably or changes user-visible behavior beyond a listed divergence is out of scope
-
Test each fact once, at the lowest layer that can observe it:
- logic through the safe Rust API, following
/rust-tests-guidelines; - each FFI function at most once, and only where it does more than forward;
- the contract end to end, through the production path.
Do not add a C/C++ test suite that re-checks what the Rust tests already check. One overlap is expected: until the swap, the flow tests exercise C, so in the Rust PR a Rust test of a contract behavior is the only coverage of the new implementation.
- logic through the safe Rust API, following
-
Document public APIs with doc comments
-
For performance sensitive code, benchmark Rust against C with
criterionin a<module>_benchercrate, written while the C still exists: its build script links C throughbuild_utils::bind_foreign_c_symbols, and each benchmark is a group with acfunction calling the C through the generatedffibindings and arustfunction calling the Rust API. Never copy C sources into the benchmark or rebuild C from git history. -
Use
proptestfor property-based testing where appropriate -
Testing code should be written with the same care reserved to production code
5. Compare Rust API with C API
- Review the public API of the new Rust module against the C API in the header file
- Ensure that differences can be bridged by adding appropriate wrappers or adapters
- Go back to step 1 if discovered differences cannot be bridged without a re-design
6. Create FFI Wrapper
Create an FFI crate to expose the new Rust module to the C codebase:
cargo new src/redisearch_rs/c_entrypoint/${ARGUMENTS}_ffi --lib
FFI crate should:
- Expose
#[unsafe(no_mangle)] pub extern "C" fnfunctions under the C functions' own names, never prefixed with a language: the FFI crate is linked in the same change that deletes the C definitions, so the two never meet in one binary and C callers keep their calls - State preconditions as a numbered
# Safetylist and check the cheap ones with named assertion helpers, as/rust-review§ 3a and § 3c describe; do not add runtime checks for states the contract rules out - Convert between C and Rust types safely, in one place per type
- Document all unsafe blocks with
// SAFETY:comments that discharge the preconditions by number (§ 3b) - Follow the house rules in
/rust-review§ 3k:expectoverunwrap, pointer methods over*p,BoxoverRedisModule_Alloc, thec_wrappers/crates over rawffi::calls - Export only what production C calls: a symbol only C/C++ tests use is not exported, and those tests change with it
- Ask three separate questions of every pointer, because one answer does not imply another.
Initialization: an output parameter may point at uninitialized memory, so write it with
ptr.write, never through a&mutmade from it. Aliasing: may it overlap another argument? Ownership: who frees it, with which allocator, exactly once? - Keep Rust tests of the C boundary in this crate, not in the pure crate or another crate's tests
7. Wire Up C Code
- Delete the C header file and its implementation
- Move whatever else the header defined that other code shares (structs, enums, constants) to Rust, exported through the generated header; every user of those types changes with it, so plan the move
- Update the rest of the C codebase to import the new Rust header wherever the old C header was used
C header files for Rust FFI crates are auto-generated. No need to use their full
Content truncated.
When not to use it
- →When the C module is too complex to port
- →When C performance is strictly required
Prerequisites
Limitations
- →Requires manual effort for complex data structures
- →FFI boundary requires careful safety management
How it compares
It provides a structured migration path rather than manual, ad-hoc porting.
Compared to similar skills
port-c-module side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| port-c-module (this skill) | 2 | 5mo | Review | Advanced |
| arm-cortex-expert | 29 | 7mo | No flags | Advanced |
| compiler-development | 1 | 9mo | No flags | Advanced |
| memory-safety-patterns | 4 | 7mo | No flags | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by RediSearch
View all by RediSearch →You might also like
arm-cortex-expert
sickn33
Senior embedded software engineer specializing in firmware and driver development for ARM Cortex-M microcontrollers (Teensy, STM32, nRF52, SAMD). Decades of experience writing reliable, optimized, and maintainable embedded code with deep expertise in memory barriers, DMA/cache coherency, interrupt-driven I/O, and peripheral drivers.
compiler-development
gmh5225
Expertise in compiler development using LLVM infrastructure including frontend design, IR generation, optimization passes, and code generation. Use this skill when building custom programming languages, implementing DSL compilers, or working on compiler internals.
memory-safety-patterns
sickn33
Implement memory-safe programming with RAII, ownership, smart pointers, and resource management across Rust, C++, and C. Use when writing safe systems code, managing resources, or preventing memory bugs.
debug-lldb
regenrek
Capture and analyze thread backtraces with LLDB/GDB to debug hangs, deadlocks, UI freezes, IPC stalls, or high-CPU loops across any language or project. Use when an app becomes unresponsive, switching contexts stalls, or you need thread stacks to locate lock inversion or blocking calls.
server-tick
dadbodgeoff
Server-authoritative tick system for multiplayer games with lag compensation, anti-cheat validation, and deterministic physics. Prevents speed hacks and teleports while keeping gameplay fair for high-latency players.
deepwiki-rs
sopaco
AI-powered Rust documentation generation engine for comprehensive codebase analysis, C4 architecture diagrams, and automated technical documentation. Use when Claude needs to analyze source code, understand software architecture, generate technical specs, or create professional documentation from any programming language.