Skip to content

Instantly share code, notes, and snippets.

@Verdagon
Created May 20, 2024 21:58
Show Gist options
  • Save Verdagon/85fd126ebb05c50557b9e79ae03f2207 to your computer and use it in GitHub Desktop.
Save Verdagon/85fd126ebb05c50557b9e79ae03f2207 to your computer and use it in GitHub Desktop.
// Seamless C->Rust example: reversing a string
// Import types. More advanced compilers with generics wouldn't need
// to specify these generic args in theory, it would basically be a
// vanilla java import.
#pragma rsuse Str = &str
#pragma rsuse String = std::string::String
#pragma rsuse Chars = core::str::Chars<'static>
#pragma rsuse RevChars = core::iter::Rev<Chars>
// Import methods. More advanced compilers with generics won't need
// any of these imports in theory, AFAICT.
#pragma rsuse Str_chars = str::chars
#pragma rsuse String_as_str = String::as_str
#pragma rsuse String_drop = String::drop
#pragma rsuse Chars_rev = Chars::rev
#pragma rsuse RevChars_collectString = RevChars::collect::<String>
// Import the header generated by the Makefile invoking the tool
#include <rust_deps/rust_deps.h>
#include <stdio.h>
#include <unistd.h>
int main() {
Str str = VR_StrFromCStr("bork");
Chars iter = Str_chars(str);
RevChars revIter = Chars_rev(iter);
String revString = RevChars_collectString(revIter);
Str revStr = String_as_str(&revString);
// Prints "krob"
// Uses write() because Rust String isn't guaranteed null-terminated
write(STDOUT_FILENO, VR_StrToCStr(revStr), VR_StrLen(revStr));
printf("\nSuccess!\n");
String_drop(&revString);
return 0;
}
// More notes:
// - rust_deps.h contains all the auto-generated bindings.
// - This is C, user needs to manage their memory. User shouldn't e.g.:
// - Move `Str str` while Chars is alive.
// - Forget to drop() the revString.
// - VR_StrFromCStr is a builtin that makes a Rust str from a char*.
// - VR_StrToCStr is a builtin that gets the char* back from Rust str.
// - VR_StrLen gets the length of a Rust str.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment