Re:Emitting Safer Rust with C2Rust
by neopallium on Thursday March 16, 2023 @07:37AM
(#35180665)
I used c2rust to start rewriting OpenJpeg into Rust code [0].
It was easy to get the Rust code compiled and working as a drop-in-replacement for the C Library. This has been a big help with refactoring the unsafe Rust code into safe Rust (manual work). OpenJpeg has a great testsuite that has allowed testing that each refactor step doesn't add new bugs (has happened at least 3 times).
The original run of c2rust generated 96,842 lines of Rust code (about 1 year ago), now it is down to 46,873 lines code. A lot of the extra 50k lines of code were from C macros that got expanded and from constant lookup tables (C code had 10-30 values per line, Rust 1 value 1 line).
For anyone looking to use c2rust to port C code to Rust, I recommend the following:
1. Setup some automated testing if it doesn't exist already.
2. Do refactoring in small amounts, run the tests and commit the changes before doing more refactoring.
3. Use "search/replace" tools (`sed`) to help with rewriting common patterns. Make sure to follow #2 when doing this.
4. Don't re-organize the code until after most of the unsafe code has been rewritten. This will allow easier side-by-side comparison with the original C code.
5. c2rust expands macros and constants from `#define`. Being able to do side-by-side comparison of the C code will help with adding constants back in and removing expanded code with Rust macros or just normal Rust functions.
It was easy to get the Rust code compiled and working as a drop-in-replacement for the C Library. This has been a big help with refactoring the unsafe Rust code into safe Rust (manual work). OpenJpeg has a great testsuite that has allowed testing that each refactor step doesn't add new bugs (has happened at least 3 times).
The original run of c2rust generated 96,842 lines of Rust code (about 1 year ago), now it is down to 46,873 lines code. A lot of the extra 50k lines of code were from C macros that got expanded and from constant lookup tables (C code had 10-30 values per line, Rust 1 value 1 line).
For anyone looking to use c2rust to port C code to Rust, I recommend the following:
[0] https://github.com/Neopallium/openjpeg/tree/master/openjp2-r...