Skip to content

Commit 3e2722d

Browse files
authored
Render the Rust custom section a bit more readably (#863)
* Render the Rust custom section a bit more readably Instead of using a large literal of integers instead use a byte string which is a bit more compact and allows rendering some ascii inline where possible. * Better escaping
1 parent e0319e9 commit 3e2722d

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

crates/rust/src/bindgen.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -734,7 +734,7 @@ impl Bindgen for FunctionBindgen<'_, '_> {
734734
"let {layout} = alloc::Layout::from_size_align_unchecked({vec}.len() * {size}, {align});\n",
735735
));
736736
self.push_str(&format!(
737-
"let {result} = if {layout}.size() != 0\n{{\nlet ptr = alloc::alloc({layout});\n",
737+
"let {result} = if {layout}.size() != 0 {{\nlet ptr = alloc::alloc({layout});\n",
738738
));
739739
self.push_str(&format!(
740740
"if ptr.is_null()\n{{\nalloc::handle_alloc_error({layout});\n}}\nptr\n}}",

crates/rust/src/lib.rs

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use std::process::{Command, Stdio};
99
use std::str::FromStr;
1010
use wit_bindgen_core::abi::{Bitcast, WasmType};
1111
use wit_bindgen_core::{
12-
uwriteln, wit_parser::*, Files, InterfaceGenerator as _, Source, Types, WorldGenerator,
12+
uwrite, uwriteln, wit_parser::*, Files, InterfaceGenerator as _, Source, Types, WorldGenerator,
1313
};
1414

1515
mod bindgen;
@@ -560,10 +560,41 @@ impl WorldGenerator for RustWasm {
560560

561561
self.src.push_str("#[doc(hidden)]\n");
562562
self.src.push_str(&format!(
563-
"pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; {}] = ",
563+
"pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; {}] = *b\"\\\n",
564564
component_type.len()
565565
));
566-
self.src.push_str(&format!("{:?};\n", component_type));
566+
let mut line_length = 0;
567+
let s = self.src.as_mut_string();
568+
for byte in component_type.iter() {
569+
if line_length >= 80 {
570+
s.push_str("\\\n");
571+
line_length = 0;
572+
}
573+
match byte {
574+
b'\\' => {
575+
s.push_str("\\\\");
576+
line_length += 2;
577+
}
578+
b'"' => {
579+
s.push_str("\\\"");
580+
line_length += 2;
581+
}
582+
b if b.is_ascii_alphanumeric() || b.is_ascii_punctuation() => {
583+
s.push(char::from(*byte));
584+
line_length += 1;
585+
}
586+
0 => {
587+
s.push_str("\\0");
588+
line_length += 2;
589+
}
590+
_ => {
591+
uwrite!(s, "\\x{:02x}", byte);
592+
line_length += 4;
593+
}
594+
}
595+
}
596+
597+
self.src.push_str("\";\n");
567598

568599
let rt = self.runtime_path().to_string();
569600
uwriteln!(

0 commit comments

Comments
 (0)