Support nested blocks in C++ emitter

This commit is contained in:
David Tolnay 2020-03-01 13:36:55 -08:00
parent 7e219b8099
commit b92e66f4dc
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82

View File

@ -5,8 +5,8 @@ pub(crate) struct OutFile {
pub header: bool,
content: Vec<u8>,
section_pending: bool,
block: &'static str,
block_pending: bool,
blocks: Vec<&'static str>,
blocks_pending: usize,
}
impl OutFile {
@ -16,8 +16,8 @@ impl OutFile {
header,
content: Vec::new(),
section_pending: false,
block: "",
block_pending: false,
blocks: Vec::new(),
blocks_pending: 0,
}
}
@ -27,18 +27,18 @@ impl OutFile {
}
pub fn begin_block(&mut self, block: &'static str) {
self.block = block;
self.block_pending = true;
self.blocks.push(block);
self.blocks_pending += 1;
}
pub fn end_block(&mut self) {
if self.block_pending {
self.block_pending = false;
if self.blocks_pending > 0 {
self.blocks_pending -= 1;
} else {
self.content.extend_from_slice(b"} // ");
self.content.extend_from_slice(self.block.as_bytes());
self.content
.extend_from_slice(self.blocks.pop().unwrap().as_bytes());
self.content.push(b'\n');
self.block = "";
self.section_pending = true;
}
}
@ -51,11 +51,13 @@ impl OutFile {
impl Write for OutFile {
fn write_str(&mut self, s: &str) -> fmt::Result {
if !s.is_empty() {
if self.block_pending {
if self.blocks_pending > 0 {
self.content.push(b'\n');
self.content.extend_from_slice(self.block.as_bytes());
for block in &self.blocks[self.blocks.len() - self.blocks_pending..] {
self.content.extend_from_slice(block.as_bytes());
self.content.extend_from_slice(b" {\n");
self.block_pending = false;
}
self.blocks_pending = 0;
self.section_pending = false;
} else if self.section_pending {
self.content.push(b'\n');