gdritter repos gunpowder_treason / 419e315
Use stat instead of open to check for existing files Getty Ritter 6 years ago
1 changed file(s) with 14 addition(s) and 12 deletion(s). Collapse all Expand all
11 use std::fmt::{self, Display, Formatter};
2 use std::fs::OpenOptions;
2 use std::fs::{self, OpenOptions};
33 use std::io::{self, Write};
4 use std::path::Path;
45
56 const MAX_OUTPUT_FILES: u32 = 500;
67
6768
6869 /// Print this SVG document to stdout
6970 pub fn output(self, p: &str) -> io::Result<()> {
71 let output_dir = Path::new("output");
72 if !output_dir.is_dir() {
73 fs::create_dir(output_dir)?;
74 }
75
7076 let mut file = {
7177 let mut n = 0;
7278 let mut path = format!("output/{}{:05}.svg", p, n);
73 let mut f = OpenOptions::new().write(true).create_new(true).open(&path);
74 loop {
75 match f {
76 Ok(_) => break,
77 Err(ref e) if e.kind() != io::ErrorKind::AlreadyExists =>
78 return Err(io::Error::new(e.kind(), "failed to create file")),
79 _ if n > MAX_OUTPUT_FILES =>
80 return Err(io::Error::new(io::ErrorKind::Other, "Too many output files already")),
81 _ => (),
79 while Path::new(&path).exists() {
80 if n > MAX_OUTPUT_FILES {
81 return Err(io::Error::new(
82 io::ErrorKind::Other,
83 "gunpowder_treason: too many output files",
84 ));
8285 }
8386 n += 1;
8487 path = format!("output/{}{:05}.svg", p, n);
85 f = OpenOptions::new().write(true).create_new(true).open(&path);
8688 }
87 f.unwrap()
89 OpenOptions::new().write(true).create_new(true).open(&path)?
8890 };
8991 self.write_svg(&mut file)
9092 }