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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
//! A module that contians pixels for pixelflut.
use std::fmt;
use std::str::FromStr;
use error::{Error, ErrorKind, Result};

/// pixelflut pixel
#[derive(Copy, Clone, PartialEq, Hash, Debug)]
pub struct Pixel {
    pub position: Coordinate,
    pub color: Color,
}

impl Pixel {
    /// construct a new `Pixel` with a `Coordinate` and a `Color`
    pub fn new<P: Into<Coordinate>, C: Into<Color>>(position: P, color: C) -> Pixel {
        Pixel {
            position: position.into(),
            color: color.into(),
        }
    }
}

impl fmt::Display for Pixel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.position, self.color)
    }
}

impl FromStr for Pixel {
    type Err = Error;

    fn from_str(s: &str) -> Result<Pixel> {
        let mut iter = s.split_whitespace();
        let pixel = Pixel::new(
            Coordinate::new(
                iter.next().ok_or(ErrorKind::WrongNumberOfArguments)?.parse()?,
                iter.next().ok_or(ErrorKind::WrongNumberOfArguments)?.parse()?
            ),
            iter.next().ok_or(ErrorKind::WrongNumberOfArguments)?.parse::<Color>()?
        );
        if iter.next().is_some() {
            Err(ErrorKind::WrongNumberOfArguments.into())
        } else {
            Ok(pixel)
        }
    }
}

/// coordinate on a pixelflut grid
#[derive(Copy, Clone, PartialEq, Hash, Debug)]
pub struct Coordinate {
    pub x: u32,
    pub y: u32,
}

impl Coordinate {
    /// Constructs a new `Coordinate` with given x and y position.
    pub fn new(x: u32, y: u32) -> Coordinate {
        Coordinate { x, y }
    }
}

impl From<(u32, u32)> for Coordinate {
    fn from(coordinate: (u32, u32)) -> Coordinate {
        Coordinate::new(coordinate.0, coordinate.1)
    }
}

impl Into<(u32, u32)> for Coordinate {
    fn into(self) -> (u32, u32) {
        (self.x, self.y)
    }
}

impl fmt::Display for Coordinate {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", self.x, self.y)
    }
}

#[derive(Copy, Clone, PartialEq, Hash)]
pub struct Color {
    r: u8,
    g: u8,
    b: u8,
    a: Option<u8>,
}

impl Color {
    
    /// Constructs a new `Color` without using an alpha channel.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```no_run
    /// use pixelflut::Color;
    /// Color::rgb(255, 255, 255);
    /// ```
    pub fn rgb(r: u8, g: u8, b: u8) -> Color {
        Color {
            r, g, b, a: None
        }
    }

    /// Constructs a new `Color` using an alpha channel.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```no_run
    /// use pixelflut::Color;
    /// Color::rgba(255, 255, 255, 255);
    /// ```
    pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {
        Color {
            r, g, b, a: Some(a)
        }
    }

    /// Constructs a new `Color` using the alpha channel only, if a != 255.
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// 
    /// ```
    /// use pixelflut::Color;
    /// assert_eq!(Color::packed(123, 23, 42, 255), Color::rgb(123, 23, 42));
    /// assert_eq!(Color::packed(123, 23, 42, 64), Color::rgba(123, 23, 42, 64));
    /// ```
    pub fn packed(r: u8, g: u8, b: u8, a: u8) -> Color {
        match a {
            255 => Color::rgb(r, g, b),
            a => Color::rgba(r, g, b, a),
        }
    }

    /// Strips the alpha channel if not existent or value is 255.Color
    /// 
    /// # Examples
    /// 
    /// Basic usage:
    /// 
    /// ```
    /// use pixelflut::Color;
    /// assert_eq!(Color::rgba(12, 34, 56, 255).pack(), Color::rgb(12, 34, 56));
    /// assert_eq!(Color::rgb(12, 34, 56).pack(), Color::rgb(12, 34, 56));
    /// assert_eq!(Color::rgba(12, 34, 56, 78).pack(), Color::rgba(12, 34, 56, 78));
    /// ```
    pub fn pack(&self) -> Color {
        match self.a {
            None | Some(255) => Color::rgb(self.r, self.g, self.b),
            _ => *self
        }
    }

    /// Returns a 4-Tuple with the components red, green, blue and alpha
    ///
    /// If no alpha channel is present, 255 is returned as the alpha channel.
    ///
    /// # Examples
    ///
    /// ```
    /// use pixelflut::Color;
    /// assert_eq!((255, 0, 0, 255), Color::rgb(255, 0, 0).normalized())
    /// ```
    pub fn normalized(self) -> (u8, u8, u8, u8) {
        match self.a {
            Some(a) => (self.r, self.g, self.b, a),
            None    => (self.r, self.g, self.b, 255),
        }
    }
}

impl From<(u8, u8, u8)> for Color {
    /// Returns a RGB Color
    fn from(color: (u8, u8, u8)) -> Color {
        Color::rgb(color.0, color.1, color.2)
    }
}


impl From<(u8, u8, u8, u8)> for Color {
    /// Returns a RGBA Color
    fn from(color: (u8, u8, u8, u8)) -> Color {
        Color::rgba(color.0, color.1, color.2, color.3)
    }
}

impl Into<(u8, u8, u8)> for Color {
    fn into(self) -> (u8, u8, u8) {
        (self.r, self.g, self.b)
    }
}

impl Into<(u8, u8, u8, u8)> for Color {
    fn into(self) -> (u8, u8, u8, u8) {
        match self.a {
            Some(a) => (self.r, self.g, self.b, a),
            None => (self.r, self.g, self.b, 255),
        }
    }
}

#[cfg(feature = "image")]
impl From<image::Rgb<u8>> for Color {
    /// Returns a Rgb Color
    fn from(color: image::Rgb<u8>) -> Color {
        let [r, g, b] = color.data;
        Color::rgb(r, g, b)
    }
}

#[cfg(feature = "image")]
impl Into<image::Rgb<u8>> for Color {
    fn into(self) -> image::Rgb<u8> {
        image::Rgb { data: [self.r, self.g, self.b] }
    }
}

#[cfg(feature = "image")]
impl From<image::Rgba<u8>> for Color {
    /// Returns a Rgba Color
    fn from(color: image::Rgba<u8>) -> Color {
        let [r, g, b, a] = color.data;
        Color::packed(r, g, b, a)
    }
}

#[cfg(feature = "image")]
impl Into<image::Rgba<u8>> for Color {
    fn into(self) -> image::Rgba<u8> {
        image::Rgba { data: [self.r, self.g, self.b, self.a.unwrap_or(255)] }
    }
}

impl FromStr for Color {
    type Err = Error;

    /// Converts a string to a color
    /// 
    /// # Examples
    /// 
    /// ```
    /// use pixelflut::Color;
    /// assert_eq!(Color::rgb(0x11, 0x22, 0x33), "112233".parse().unwrap());
    /// assert_eq!(Color::rgba(0x11, 0x22, 0x33, 0xee), "112233ee".parse().unwrap());
    /// assert!("".parse::<Color>().is_err());
    /// assert!("123".parse::<Color>().is_err());
    /// assert!("12345".parse::<Color>().is_err());
    /// assert!(" 1 2 3".parse::<Color>().is_err());
    /// assert!("112g33".parse::<Color>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Color> {
        match s.len() {
            6  => Ok( Color::rgb (
                u8::from_str_radix(&s[0..2], 16)?,
                u8::from_str_radix(&s[2..4], 16)?,
                u8::from_str_radix(&s[4..6], 16)?,
            )),
            8  => Ok( Color::rgba (
                u8::from_str_radix(&s[0..2], 16)?,
                u8::from_str_radix(&s[2..4], 16)?,
                u8::from_str_radix(&s[4..6], 16)?,
                u8::from_str_radix(&s[6..8], 16)?,
            )),
            _ => Err(ErrorKind::Parse.with_description("color length is wrong"))

        }
    }
}

impl fmt::Display for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.a {
            Some(a) => write!(f, "{:02x}{:02x}{:02x}{:02x}", self.r, self.g, self.b, a),
            None    => write!(f, "{:02x}{:02x}{:02x}", self.r, self.g, self.b),
        }
    }
}

impl fmt::Debug for Color {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Color: 0x{}", self)
    }
}

#[cfg(test)]
mod tests {
    use Pixel;
    use Coordinate;
    use Color;

    #[test]
    fn test_pixel_from_str() {
        assert_eq!(Pixel::new(
            Coordinate::new(10, 20),
            Color::rgb(0x11, 0x22, 0x33),
        ), "10 20 112233".parse().unwrap());
    }

    #[test]
    fn test_color_rgb() {
        assert_eq!(Color { r: 0x11, g: 0x22, b: 0x33, a: None },
                   Color::rgb(0x11, 0x22, 0x33));
    }

    #[test]
    fn test_color_rgba() {
        assert_eq!(Color { r: 0x11, g: 0x22, b: 0x33, a: Some(0x44)},
                   Color::rgba(0x11, 0x22, 0x33, 0x44));
    }

    #[test]
    fn test_color_normalized() {
        assert_eq!((0x11, 0x22, 0x33, 0xff),
                   Color::rgb(0x11, 0x22, 0x33).normalized());
        assert_eq!((0x11, 0x22, 0x33, 0x44),
                   Color::rgba(0x11, 0x22, 0x33, 0x44).normalized());
    }
    
}