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
use std::borrow::Cow;

use rect::Rect;

use super::Texture;

pub struct SubTexture<'a, T: 'a + Clone> {
    texture: Cow<'a, T>,
    source: Rect,
}

impl<'a, T: Texture + Clone> SubTexture<'a, T> {
    pub fn new(texture: T, source: Rect) -> SubTexture<'a, T> {
        SubTexture {
            texture: Cow::Owned(texture),
            source: source,
        }
    }

    pub fn from_ref(texture: &'a T, source: Rect) -> SubTexture<'a, T> {
        SubTexture {
            texture: Cow::Borrowed(texture),
            source: source,
        }
    }

}

impl<'a, T: Texture + Clone> Texture for SubTexture<'a, T> {
    type Pixel = T::Pixel;

    fn width(&self) -> u32 {
        self.source.w
    }

    fn height(&self) -> u32 {
        self.source.h
    }

    fn get(&self, x: u32, y: u32) -> Option<T::Pixel> {
        let x = self.source.x + x;
        let y = self.source.y + y;
        self.texture.get(x, y)
    }

    fn set(&mut self, x: u32, y: u32, val: T::Pixel) {
        if let Cow::Owned(ref mut t) = self.texture {
            let x = self.source.x + x;
            let y = self.source.y + y;
            t.set(x, y, val);
        } else {
            panic!("Can't set pixel by borrowed reference");
        }
    }
}