use std::fmt::{self, Write};
use crate::formatter::Formatter;
#[derive(Debug, Clone)]
pub struct Doc {
docs: Vec<String>,
}
impl Doc {
pub fn new() -> Self {
Doc { docs: Vec::new() }
}
pub fn with_str(docs: &str) -> Self {
let mut doc = Doc::new();
doc.add_text(docs);
doc
}
pub fn with_string(docs: String) -> Self {
let mut doc = Doc::new();
doc.add_text(&docs);
doc
}
pub fn add_line(&mut self, line: &str) -> &mut Self {
if line.is_empty() {
self.docs.push(String::new())
} else {
for l in line.lines() {
self.docs.push(l.to_string());
}
}
self
}
pub fn add_text(&mut self, text: &str) -> &mut Self {
let mut res = self;
let lines = text.lines();
for l in lines {
if l.is_empty() || l == "\n" {
res = res.add_line("");
continue;
}
let mut start = 0;
let mut end = 0;
for (offset, c) in l.chars().enumerate() {
if c == ' ' && (offset - start) > 90 {
res = res.add_line(&l[start..=end]);
start = end;
}
end = offset;
}
if start == end {
res = res.add_line("");
} else {
res = res.add_line(&l[start..=end]);
}
}
res
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
for line in &self.docs {
writeln!(fmt, "/// {line}")?;
}
Ok(())
}
}
impl Default for Doc {
fn default() -> Self {
Self::new()
}
}