aboutsummaryrefslogtreecommitdiff
path: root/lib/src/lib.rs
blob: 20078a263c49a023c4de11957821e6cbe6ba16c8 (plain)
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
extern crate phf;

#[cfg(feature = "flate2")]
extern crate flate2;

use std::borrow::{Borrow, Cow};
use std::io::{self, Cursor, Error, ErrorKind, Read};

#[cfg(feature = "flate2")]
use flate2::FlateReadExt;

pub enum Compression {
    None,
    Gzip,
}

/// Runtime access to the included files
pub struct Files {
    /// **Do not access this field, it is only public to allow for code generation!**
    pub files: phf::Map<&'static str, (Compression, &'static [u8])>,
}

#[cfg(windows)]
fn as_key(path: &str) -> Cow<str> {
    Cow::Owned(path.replace("\\", "/"))
}

#[cfg(not(windows))]
fn as_key(path: &str) -> Cow<str> {
    Cow::Borrowed(path)
}

impl Files {
    pub fn available(&self, path: &str) -> bool {
        self.files.contains_key(path)
    }

    pub fn get(&self, path: &str) -> io::Result<Cow<'static, [u8]>> {
        let key = as_key(path);
        match self.files.get(key.borrow() as &str) {
            Some(b) => {
                match b.0 {
                    Compression::None => Ok(Cow::Borrowed(b.1)),
                    #[cfg(feature = "flate2")]
                    Compression::Gzip => {
                        let mut r = try!(Cursor::new(b.1).gz_decode());
                        let mut v = Vec::new();
                        try!(r.read_to_end(&mut v));
                        Ok(Cow::Owned(v))
                    }
                    #[cfg(not(feature = "flate2"))]
                    Compression::Gzip => panic!("Feature 'flate2' not enabled"),
                }
            }
            None => Err(Error::new(ErrorKind::NotFound, "Key not found")),
        }
    }

    pub fn read(&self, path: &str) -> io::Result<Box<Read>> {
        let key = as_key(path);
        match self.files.get(key.borrow() as &str) {
            Some(b) => {
                match b.0 {
                    Compression::None => Ok(Box::new(Cursor::new(b.1))),
                    #[cfg(feature = "flate2")]
                    Compression::Gzip => Ok(Box::new(try!(Cursor::new(b.1).gz_decode()))),
                    #[cfg(not(feature = "flate2"))]
                    Compression::Gzip => panic!("Feature 'flate2' not enabled"),
                }
            }
            None => Err(Error::new(ErrorKind::NotFound, "Key not found")),
        }
    }
}