unicode_names2_generator/
formatting.rs

1use std::{fmt::Debug, io::prelude::*};
2
3static LINE_LIMIT: usize = 95;
4
5pub struct Context {
6    pub out: Box<dyn Write + 'static>,
7}
8
9impl Context {
10    pub fn write_array<T, F>(&mut self, name: &str, ty: &str, elements: &[T], format: F)
11    where
12        F: Fn(&T) -> String,
13    {
14        w!(self, "pub static {}: &'static [{}] = &[", name, ty);
15
16        let mut width = LINE_LIMIT;
17        for e in elements.iter() {
18            let mut text = format(e);
19            text.push(',');
20            if 1 + width + text.len() >= LINE_LIMIT {
21                w!(self, "\n    ");
22                width = 4;
23            } else {
24                w!(self, " ");
25                width += 1
26            }
27            w!(self, "{}", text);
28            width += text.len()
29        }
30        w!(self, "];\n");
31    }
32
33    pub fn write_debugs<T: Debug>(&mut self, name: &str, ty: &str, elements: &[T]) {
34        self.write_array(name, ty, elements, |x| format!("{:?}", x))
35    }
36
37    pub fn write_plain_string(&mut self, name: &str, data: &str) {
38        assert!(!data.contains('\\'));
39
40        w!(self, "pub static {}: &'static str = \"", name);
41
42        for chunk in data.as_bytes().chunks(LINE_LIMIT - 6) {
43            w!(self, "\\\n    ");
44            self.out.write_all(chunk).unwrap();
45        }
46        w!(self, "\";\n");
47    }
48}