Skip to content

Commit f0e889e

Browse files
committed
Add libcc2rs::char_array to initialize fixed sized arrays
1 parent 3284cba commit f0e889e

3 files changed

Lines changed: 19 additions & 5 deletions

File tree

cpp2rust/converter/converter.cpp

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1927,13 +1927,17 @@ bool Converter::VisitStringLiteral(clang::StringLiteral *expr) {
19271927
uint64_t pad = arr_size > expr->getString().size()
19281928
? arr_size - expr->getString().size()
19291929
: 0;
1930-
StrCat(token::kStar,
1931-
std::format("b{}", GetEscapedStringLiteral(expr, pad)));
1930+
StrCat(std::format("libcc2rs::char_array(b{})",
1931+
GetEscapedStringLiteral(expr, pad)));
19321932
return false;
19331933
}
1934-
StrCat(token::kStar);
1934+
StrCat(std::format("libcc2rs::char_array(b{})",
1935+
GetEscapedStringLiteral(expr, 1)));
1936+
return false;
19351937
}
1936-
StrCat(std::format("b{}", GetEscapedStringLiteral(expr, 1)));
1938+
assert(!expr->getString().contains('\0') &&
1939+
"interior null byte in string literal");
1940+
StrCat(std::format("c{}", GetEscapedStringLiteral(expr, 0)));
19371941
return false;
19381942
}
19391943

cpp2rust/converter/models/converter_refcount.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1045,7 +1045,7 @@ bool ConverterRefCount::VisitStringLiteral(clang::StringLiteral *expr) {
10451045
? arr_size - expr->getString().size()
10461046
: 0;
10471047
}
1048-
StrCat(std::format("Box::<[u8]>::from(b{}.as_slice())",
1048+
StrCat(std::format("Box::from(libcc2rs::char_array(b{}))",
10491049
GetEscapedStringLiteral(expr, pad)));
10501050
return false;
10511051
}

libcc2rs/src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,13 @@ mod va_args;
3535
pub use va_args::*;
3636

3737
pub use libcc2rs_macros::{goto, goto_block, switch};
38+
39+
pub const fn char_array<const N: usize>(s: &[u8; N]) -> [core::ffi::c_char; N] {
40+
let mut out = [0 as core::ffi::c_char; N];
41+
let mut i = 0;
42+
while i < N {
43+
out[i] = s[i] as core::ffi::c_char;
44+
i += 1;
45+
}
46+
out
47+
}

0 commit comments

Comments
 (0)