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
//! Provides a context for loading a file.

use std::sync::Arc;

use rayon::ThreadPool;

use super::source::Source;
use assets::*;

/// A context for loading audio files
pub struct AudioContext {
    cache: Cache<AssetFuture<Source>>,
}

impl AudioContext {
    /// Creates a new audio context.
    pub fn new() -> AudioContext {
        AudioContext { cache: Cache::new() }
    }
}

impl Context for AudioContext {
    type Asset = Source;
    type Data = Vec<u8>;
    type Error = NoError;
    type Result = Result<Self::Asset, Self::Error>;

    fn category(&self) -> &str {
        "audio"
    }

    fn create_asset(&self, data: Vec<u8>, _: &ThreadPool) -> Result<Source, NoError> {
        Ok(Source { pointer: AssetPtr::new(Arc::new(data)) })
    }

    fn update(&self, spec: &AssetSpec, asset: AssetFuture<Source>) {
        if let Some(updated) = self.cache
            .access(spec, |a| match a.peek() {
                Some(Ok(a)) => {
                    (*a).pointer.push_update(asset);
                    None
                }
                _ => Some(asset),
            })
            .and_then(|a| a)
        {
            self.cache.insert(spec.clone(), updated);
        }
    }
}