Skip to content

Commit dab7e80

Browse files
committed
Preserve utf-8 invariant on generated code
We only write to the output buffer using the `write!` macros, which go through std::fmt and are guaranteed that the data written is utf-8.
1 parent 0f312e7 commit dab7e80

File tree

1 file changed

+17
-17
lines changed

1 file changed

+17
-17
lines changed

gen/src/out.rs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ pub(crate) struct OutFile {
1212
}
1313

1414
pub struct Content {
15-
bytes: Vec<u8>,
15+
bytes: String,
1616
section_pending: bool,
1717
blocks_pending: Vec<&'static str>,
1818
}
@@ -42,9 +42,9 @@ impl OutFile {
4242
pub fn end_block(&mut self, block: &'static str) {
4343
let content = self.content.get_mut();
4444
if content.blocks_pending.pop().is_none() {
45-
content.bytes.extend_from_slice(b"} // ");
46-
content.bytes.extend_from_slice(block.as_bytes());
47-
content.bytes.push(b'\n');
45+
content.bytes.push_str("} // ");
46+
content.bytes.push_str(block);
47+
content.bytes.push('\n');
4848
content.section_pending = true;
4949
}
5050
}
@@ -58,19 +58,19 @@ impl OutFile {
5858
let front = &self.front.bytes;
5959
let content = &self.content.borrow().bytes;
6060
let len = front.len() + !front.is_empty() as usize + content.len();
61-
let mut out = Vec::with_capacity(len);
62-
out.extend_from_slice(front);
61+
let mut out = String::with_capacity(len);
62+
out.push_str(front);
6363
if !front.is_empty() {
64-
out.push(b'\n');
64+
out.push('\n');
6565
}
66-
out.extend_from_slice(content);
67-
out
66+
out.push_str(content);
67+
out.into_bytes()
6868
}
6969
}
7070

7171
impl Write for Content {
7272
fn write_str(&mut self, s: &str) -> fmt::Result {
73-
self.write_bytes(s.as_bytes());
73+
self.write(s);
7474
Ok(())
7575
}
7676
}
@@ -82,30 +82,30 @@ impl Content {
8282

8383
fn new() -> Self {
8484
Content {
85-
bytes: Vec::new(),
85+
bytes: String::new(),
8686
section_pending: false,
8787
blocks_pending: Vec::new(),
8888
}
8989
}
9090

91-
fn write_bytes(&mut self, b: &[u8]) {
91+
fn write(&mut self, b: &str) {
9292
if !b.is_empty() {
9393
if !self.blocks_pending.is_empty() {
9494
if !self.bytes.is_empty() {
95-
self.bytes.push(b'\n');
95+
self.bytes.push('\n');
9696
}
9797
for block in self.blocks_pending.drain(..) {
98-
self.bytes.extend_from_slice(block.as_bytes());
99-
self.bytes.extend_from_slice(b" {\n");
98+
self.bytes.push_str(block);
99+
self.bytes.push_str(" {\n");
100100
}
101101
self.section_pending = false;
102102
} else if self.section_pending {
103103
if !self.bytes.is_empty() {
104-
self.bytes.push(b'\n');
104+
self.bytes.push('\n');
105105
}
106106
self.section_pending = false;
107107
}
108-
self.bytes.extend_from_slice(b);
108+
self.bytes.push_str(b);
109109
}
110110
}
111111
}

0 commit comments

Comments
 (0)