Skip to content

Commit

Permalink
Render the Rust custom section a bit more readably (#863)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
alexcrichton authored Feb 24, 2024
1 parent e0319e9 commit 3e2722d
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
2 changes: 1 addition & 1 deletion crates/rust/src/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ impl Bindgen for FunctionBindgen<'_, '_> {
"let {layout} = alloc::Layout::from_size_align_unchecked({vec}.len() * {size}, {align});\n",
));
self.push_str(&format!(
"let {result} = if {layout}.size() != 0\n{{\nlet ptr = alloc::alloc({layout});\n",
"let {result} = if {layout}.size() != 0 {{\nlet ptr = alloc::alloc({layout});\n",
));
self.push_str(&format!(
"if ptr.is_null()\n{{\nalloc::handle_alloc_error({layout});\n}}\nptr\n}}",
Expand Down
37 changes: 34 additions & 3 deletions crates/rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::process::{Command, Stdio};
use std::str::FromStr;
use wit_bindgen_core::abi::{Bitcast, WasmType};
use wit_bindgen_core::{
uwriteln, wit_parser::*, Files, InterfaceGenerator as _, Source, Types, WorldGenerator,
uwrite, uwriteln, wit_parser::*, Files, InterfaceGenerator as _, Source, Types, WorldGenerator,
};

mod bindgen;
Expand Down Expand Up @@ -560,10 +560,41 @@ impl WorldGenerator for RustWasm {

self.src.push_str("#[doc(hidden)]\n");
self.src.push_str(&format!(
"pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; {}] = ",
"pub static __WIT_BINDGEN_COMPONENT_TYPE: [u8; {}] = *b\"\\\n",
component_type.len()
));
self.src.push_str(&format!("{:?};\n", component_type));
let mut line_length = 0;
let s = self.src.as_mut_string();
for byte in component_type.iter() {
if line_length >= 80 {
s.push_str("\\\n");
line_length = 0;
}
match byte {
b'\\' => {
s.push_str("\\\\");
line_length += 2;
}
b'"' => {
s.push_str("\\\"");
line_length += 2;
}
b if b.is_ascii_alphanumeric() || b.is_ascii_punctuation() => {
s.push(char::from(*byte));
line_length += 1;
}
0 => {
s.push_str("\\0");
line_length += 2;
}
_ => {
uwrite!(s, "\\x{:02x}", byte);
line_length += 4;
}
}
}

self.src.push_str("\";\n");

let rt = self.runtime_path().to_string();
uwriteln!(
Expand Down

0 comments on commit 3e2722d

Please sign in to comment.