| David Tolnay | 7db7369 | 2019-10-20 14:51:12 -0400 | [diff] [blame^] | 1 | use std::fmt::{self, Arguments, Write}; |
| 2 | |
| 3 | pub(crate) struct OutFile { |
| 4 | pub namespace: Vec<String>, |
| 5 | pub header: bool, |
| 6 | content: Vec<u8>, |
| 7 | section_pending: bool, |
| 8 | block: &'static str, |
| 9 | block_pending: bool, |
| 10 | } |
| 11 | |
| 12 | impl OutFile { |
| 13 | pub fn new(namespace: Vec<String>, header: bool) -> Self { |
| 14 | OutFile { |
| 15 | namespace, |
| 16 | header, |
| 17 | content: Vec::new(), |
| 18 | section_pending: false, |
| 19 | block: "", |
| 20 | block_pending: false, |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // Write a blank line if the preceding section had any contents. |
| 25 | pub fn next_section(&mut self) { |
| 26 | self.section_pending = true; |
| 27 | } |
| 28 | |
| 29 | pub fn begin_block(&mut self, block: &'static str) { |
| 30 | self.block = block; |
| 31 | self.block_pending = true; |
| 32 | } |
| 33 | |
| 34 | pub fn end_block(&mut self) { |
| 35 | if self.block_pending { |
| 36 | self.block_pending = false; |
| 37 | } else { |
| 38 | self.content.extend_from_slice(b"} // "); |
| 39 | self.content.extend_from_slice(self.block.as_bytes()); |
| 40 | self.content.push(b'\n'); |
| 41 | self.block = ""; |
| 42 | self.section_pending = true; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub fn write_fmt(&mut self, args: Arguments) { |
| 47 | Write::write_fmt(self, args).unwrap(); |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | impl Write for OutFile { |
| 52 | fn write_str(&mut self, s: &str) -> fmt::Result { |
| 53 | if !s.is_empty() { |
| 54 | if self.block_pending { |
| 55 | self.content.push(b'\n'); |
| 56 | self.content.extend_from_slice(self.block.as_bytes()); |
| 57 | self.content.extend_from_slice(b" {\n"); |
| 58 | self.block_pending = false; |
| 59 | self.section_pending = false; |
| 60 | } else if self.section_pending { |
| 61 | self.content.push(b'\n'); |
| 62 | self.section_pending = false; |
| 63 | } |
| 64 | self.content.extend_from_slice(s.as_bytes()); |
| 65 | } |
| 66 | Ok(()) |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | impl AsRef<[u8]> for OutFile { |
| 71 | fn as_ref(&self) -> &[u8] { |
| 72 | &self.content |
| 73 | } |
| 74 | } |