1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright 2018 Evgeniy Reizner
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt;
use std::str::FromStr;

use {
    WriteOptions,
    StrSpan,
};

/// A trait for parsing data from a string.
pub trait FromSpan: FromStr {
    /// Parses data from a `StrSpan`.
    fn from_span(s: StrSpan) -> Result<Self, <Self as FromStr>::Err>;
}

macro_rules! impl_from_str {
    ($t:ty) => (
        impl ::std::str::FromStr for $t {
            type Err = Error;

            fn from_str(s: &str) -> ::std::result::Result<$t, Self::Err> {
                FromSpan::from_span(StrSpan::from(s))
            }
        }
    )
}

/// A trait for writing data to the buffer.
pub trait WriteBuffer {
    /// Writes data to the `Vec<u8>` buffer using specified `WriteOptions`.
    fn write_buf_opt(&self, opt: &WriteOptions, buf: &mut Vec<u8>);

    /// Writes data to the `Vec<u8>` buffer using default `WriteOptions`.
    fn write_buf(&self, buf: &mut Vec<u8>) {
        self.write_buf_opt(&WriteOptions::default(), buf);
    }

    /// Returns an object that implements `fmt::Display` using provided write options.
    fn with_write_opt<'a>(&'a self, opt: &'a WriteOptions) -> DisplaySvg<'a, Self>
        where Self: Sized
    {
        DisplaySvg { value: self, opt }
    }
}

impl<T: WriteBuffer> WriteBuffer for Vec<T> {
    fn write_buf_opt(&self, opt: &WriteOptions, buf: &mut Vec<u8>) {
        for (n, l) in self.iter().enumerate() {
            l.write_buf_opt(opt, buf);
            if n < self.len() - 1 {
                opt.write_separator(buf);
            }
        }
    }
}

/// A wrapper to use `fmt::Display` with [`WriteOptions`].
///
/// Should be used via `WriteBuffer::with_write_opt`.
///
/// # Example
///
/// ```
/// use svgtypes::{Transform, WriteOptions, WriteBuffer, DisplaySvg};
///
/// let ts = Transform::new(1.0, 0.0, 0.0, 1.0, 10.0, 20.0);
/// assert_eq!(ts.to_string(), "matrix(1 0 0 1 10 20)");
///
/// let opt = WriteOptions {
///     simplify_transform_matrices: true,
///     .. WriteOptions::default()
/// };
/// assert_eq!(ts.with_write_opt(&opt).to_string(), "translate(10 20)");
/// ```
///
/// [`WriteOptions`]: struct.WriteOptions.html
pub struct DisplaySvg<'a, T: 'a + WriteBuffer> {
    value: &'a T,
    opt: &'a WriteOptions,
}

impl<'a, T: WriteBuffer> fmt::Debug for DisplaySvg<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // Use Display.
        write!(f, "{}", self)
    }
}

impl<'a, T: WriteBuffer> fmt::Display for DisplaySvg<'a, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use std::str;

        let mut out = Vec::with_capacity(32);
        self.value.write_buf_opt(self.opt, &mut out);
        write!(f, "{}", str::from_utf8(&out).unwrap())
    }
}

macro_rules! impl_display {
    ($t:ty) => (
        impl ::std::fmt::Display for $t {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                write!(f, "{}", self.with_write_opt(&WriteOptions::default()))
            }
        }
    )
}

/// A trait for fuzzy/approximate equality comparisons.
pub trait FuzzyEq<Rhs: ?Sized = Self> {
    /// Returns `true` if values are approximately equal.
    fn fuzzy_eq(&self, other: &Rhs) -> bool;

    /// Returns `true` if values are not approximately equal.
    #[inline]
    fn fuzzy_ne(&self, other: &Rhs) -> bool {
        !self.fuzzy_eq(other)
    }
}

impl<T: FuzzyEq> FuzzyEq for Vec<T> {
    fn fuzzy_eq(&self, other: &Self) -> bool {
        if self.len() != other.len() {
            return false;
        }

        for (a, b) in self.iter().zip(other.iter()) {
            if a.fuzzy_ne(b) {
                return false;
            }
        }

        true
    }
}

/// A trait for fuzzy/approximate comparisons of `f64` numbers.
pub trait FuzzyZero: FuzzyEq {
    /// Returns `true` if the number is approximately zero.
    #[inline]
    fn is_fuzzy_zero(&self) -> bool
        where Self: FuzzyEq<f64>,
    {
        self.fuzzy_eq(&0.0)
    }
}

impl FuzzyZero for f64 {}

macro_rules! impl_vec_defer {
    ($t:ty, $tt:ty) => (
        impl ::std::ops::Deref for $t {
            type Target = Vec<$tt>;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl ::std::ops::DerefMut for $t {
            fn deref_mut(&mut self) -> &mut Self::Target {
                &mut self.0
            }
        }
    )
}

macro_rules! impl_from_vec {
    ($t:ty, $te:expr, $s:ty) => (
        impl From<Vec<$s>> for $t {
            fn from(v: Vec<$s>) -> Self {
                $te(v)
            }
        }
    )
}

macro_rules! impl_debug_from_display {
    ($t:ty) => (
        impl ::std::fmt::Debug for $t {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                // Overload Display.
                write!(f, "{}", &self)
            }
        }
    )
}