svgo/
lib.rs

1pub mod optimizer;
2pub mod svg;
3
4use std::fs::File;
5
6use anyhow::Result;
7
8use optimizer::{Optimization, Optimizer};
9use svg::Svg;
10
11pub struct SvgOptimizer {
12    pub optimizer: Optimizer,
13    pub svg: Svg,
14}
15
16impl SvgOptimizer {
17    pub fn new(svg: Svg, optimizer: Optimizer) -> Self {
18        Self { optimizer, svg }
19    }
20
21    /// Opens a SVG file from a [`File`] and creates an instance of [`SvgOptimizer`]
22    /// with it if valid.
23    pub fn open(buf: File) -> Result<Self> {
24        let svg = Svg::open(buf)?;
25        let optimizer = Optimizer::default();
26
27        Ok(Self::new(svg, optimizer))
28    }
29
30    /// Writes the underlying [`Svg`] to a [`std::io::Write`] instance.
31    pub fn write<W: std::io::Write>(&self, write: W) -> Result<()> {
32        self.svg.write(write)
33    }
34
35    /// Performs the optimizations on the SVG.
36    pub fn optimize(&mut self) -> Result<()> {
37        self.optimizer.apply(&mut self.svg)
38    }
39
40    /// Appends an [`Optimization`] to be performed on the SVG when
41    /// the [`optimize`] method is called.
42    pub fn add_optimization(&mut self, optim: Optimization) {
43        self.optimizer.append(optim);
44    }
45}