Skip to content

Commit 8fe4c79

Browse files
committed
Add &str support for rs.
Signed-off-by: Tricster <[email protected]>
1 parent 4f411d4 commit 8fe4c79

File tree

4 files changed

+19
-2
lines changed

4 files changed

+19
-2
lines changed

source/loaders/rs_loader/rust/compiler/src/ast.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ pub fn handle_ty(ty: &rustc_ast::Ty) -> FunctionParameter {
2727
"f32" => result.ty = FunctionType::f32,
2828
"f64" => result.ty = FunctionType::f64,
2929
"bool" => result.ty = FunctionType::bool,
30-
"str" => result.ty = FunctionType::str,
30+
"str" => result.ty = FunctionType::String,
3131
"Vec" => {
3232
result.ty = FunctionType::Array;
3333
if let Some(args) = &segment.args {

source/loaders/rs_loader/rust/compiler/src/wrapper/class.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,9 @@ impl ToMetaResult for String {
555555

556556
impl ToMetaResult for &str {
557557
fn to_meta_result(self) -> Result<MetacallValue> {
558-
Ok(unsafe { metacall_value_create_string(self.as_ptr() as *const i8, self.len()) })
558+
let cstring = CString::new(self).expect("Unable to cast str to CString");
559+
let ptr = cstring.as_ptr();
560+
Ok(unsafe { metacall_value_create_string(ptr, self.len()) })
559561
}
560562
}
561563

source/scripts/rust/basic/source/basic.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,3 +56,12 @@ pub fn string_len(s: String) -> usize {
5656
pub fn new_string(idx: i32) -> String {
5757
format!("get number {idx}")
5858
}
59+
60+
pub fn str_slice(s: &str) -> &str {
61+
if s.len() < 4 {
62+
return s;
63+
} else {
64+
println!("{:?}", &s[0..3]);
65+
&s[0..3]
66+
}
67+
}

source/tests/metacall_rust_test/source/metacall_rust_test.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,12 @@ TEST_F(metacall_rust_test, DefaultConstructor)
9898
// metacall_value_destroy(ret);
9999
// }
100100

101+
{
102+
void *ret = metacall("str_slice", "hellow");
103+
EXPECT_EQ((int)0, (int)strcmp(metacall_value_to_string(ret), "hel"));
104+
metacall_value_destroy(ret);
105+
}
106+
101107
{
102108
// test if we can return vec
103109
void *ret_vec = metacall("return_vec");

0 commit comments

Comments
 (0)