Add an output function, which tries generating to a fresh new file
Getty Ritter
6 years ago
1 | use std::fmt::Display; | |
2 | use std::fmt::{Formatter, Error}; | |
3 |
use std:: |
|
1 | use std::fmt::{self, Display, Formatter}; | |
2 | use std::fs::OpenOptions; | |
3 | use std::io::{self, Write}; | |
4 | 4 | |
5 | 5 | /// An SVG document |
6 | 6 | pub struct SVG { |
12 | 12 | pub struct Inches { amt: f64 } |
13 | 13 | |
14 | 14 | impl Display for Inches { |
15 |
fn fmt(&self, f: &mut Formatter) -> Result<(), |
|
15 | fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> { | |
16 | 16 | self.amt.fmt(f)?; |
17 | 17 | write!(f, "in") |
18 | 18 | } |
61 | 61 | w.write(&buf)?; |
62 | 62 | Ok(()) |
63 | 63 | } |
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 | ||
64 | 89 | |
65 | 90 | pub fn to_bytes(self) -> Vec<u8> { |
66 | 91 | let mut buf = Vec::new(); |