gdritter repos gunpowder_treason / 5b72ea1
Add an output function, which tries generating to a fresh new file Getty Ritter 6 years ago
1 changed file(s) with 29 addition(s) and 4 deletion(s). Collapse all Expand all
1 use std::fmt::Display;
2 use std::fmt::{Formatter, Error};
3 use std::io::Write;
1 use std::fmt::{self, Display, Formatter};
2 use std::fs::OpenOptions;
3 use std::io::{self, Write};
44
55 /// An SVG document
66 pub struct SVG {
1212 pub struct Inches { amt: f64 }
1313
1414 impl Display for Inches {
15 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
15 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
1616 self.amt.fmt(f)?;
1717 write!(f, "in")
1818 }
6161 w.write(&buf)?;
6262 Ok(())
6363 }
64
65 /// Print this SVG document to stdout
66 pub fn output(self, p: &str) -> Result<(), std::io::Error> {
67 let mut file = {
68 let mut n = 0u32;
69 let mut path = format!("output/{}{:05}.svg", p, n);
70 let mut f = OpenOptions::new().write(true).create_new(true).open(&path);
71 loop {
72 match f {
73 Ok(_) => break,
74 Err(ref e) if e.kind() != io::ErrorKind::AlreadyExists =>
75 return Err(io::Error::new(e.kind(), "failed to create file")),
76 _ => (),
77 }
78 n += 1;
79 path = format!("output/{}{:05}.svg", p, n);
80 f = OpenOptions::new().write(true).create_new(true).open(&path);
81 }
82 f.unwrap()
83 };
84 let buf = self.to_bytes();
85 file.write(&buf)?;
86 Ok(())
87 }
88
6489
6590 pub fn to_bytes(self) -> Vec<u8> {
6691 let mut buf = Vec::new();