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
// Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.

use allegro_audio_sys::ALLEGRO_MIXER;
use libc::c_void;
use mixer::Mixer;

use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;

#[doc(hidden)]
pub trait AttachToMixerImpl
{
	fn create_connection(&mut self, allegro_mixer: *mut ALLEGRO_MIXER) -> Result<Connection, ()>;
}

#[doc(hidden)]
pub trait HasMixer
{
	fn get_mixer<'l>(&'l self) -> &'l Mixer;
	fn get_mixer_mut<'l>(&'l mut self) -> &'l mut Mixer;
}

// When a connection is broken, the callback is called on the payload
pub struct Connection
{
	active: Arc<AtomicBool>,
	payload: *mut c_void,
	callback: fn(*mut c_void),
}

impl Connection
{
	pub fn new(payload: *mut c_void, callback: fn(*mut c_void)) -> (Connection, Connection)
	{
		let active1 = Arc::new(AtomicBool::new(true));
		let active2 = active1.clone();
		(
			Connection {
				active: active1,
				payload: payload,
				callback: callback,
			},
			Connection {
				active: active2,
				payload: payload,
				callback: callback,
			},
		)
	}
}

impl Drop for Connection
{
	fn drop(&mut self)
	{
		if self.active.swap(false, SeqCst)
		{
			(self.callback)(self.payload);
		}
	}
}