浏览代码

Add an output function, which tries generating to a fresh new file

Getty Ritter 5 年之前
父节点
当前提交
5b72ea1a91
共有 1 个文件被更改,包括 29 次插入4 次删除
  1. 29 4
      src/lib.rs

+ 29 - 4
src/lib.rs

@@ -1,6 +1,6 @@
-use std::fmt::Display;
-use std::fmt::{Formatter, Error};
-use std::io::Write;
+use std::fmt::{self, Display, Formatter};
+use std::fs::OpenOptions;
+use std::io::{self, Write};
 
 /// An SVG document
 pub struct SVG {
@@ -12,7 +12,7 @@ pub struct SVG {
 pub struct Inches { amt: f64 }
 
 impl Display for Inches {
-    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
+    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
         self.amt.fmt(f)?;
         write!(f, "in")
     }
@@ -62,6 +62,31 @@ impl SVG {
         Ok(())
     }
 
+    /// Print this SVG document to stdout
+    pub fn output(self, p: &str) -> Result<(), std::io::Error> {
+        let mut file = {
+            let mut n = 0u32;
+            let mut path = format!("output/{}{:05}.svg", p, n);
+            let mut f = OpenOptions::new().write(true).create_new(true).open(&path);
+            loop {
+                match f {
+                    Ok(_) => break,
+                    Err(ref e) if e.kind() != io::ErrorKind::AlreadyExists =>
+                        return Err(io::Error::new(e.kind(), "failed to create file")),
+                    _ => (),
+                }
+                n += 1;
+                path = format!("output/{}{:05}.svg", p, n);
+                f = OpenOptions::new().write(true).create_new(true).open(&path);
+            }
+            f.unwrap()
+        };
+        let buf = self.to_bytes();
+        file.write(&buf)?;
+        Ok(())
+    }
+
+
     pub fn to_bytes(self) -> Vec<u8> {
         let mut buf = Vec::new();
         let (w, h) = self.size;