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
use std::sync::{Arc, Mutex};

use ringbuf::Producer;
use thiserror::Error;

use super::Command;

/// Something that can go wrong when sending a command to the
/// audio thread.
#[derive(Debug, Error)]
pub enum CommandError {
	/// The command queue is full.
	#[error("Commands cannot be sent to the audio thread because the command queue is full")]
	CommandQueueFull,
	/// A thread panicked while using the command producer.
	#[error("The command producer cannot be used because a thread panicked while borrowing it.")]
	MutexPoisoned,
}

#[derive(Clone)]
pub(crate) struct CommandProducer {
	producer: Arc<Mutex<Producer<Command>>>,
}

impl CommandProducer {
	pub fn new(producer: Producer<Command>) -> Self {
		Self {
			producer: Arc::new(Mutex::new(producer)),
		}
	}

	pub fn push(&mut self, command: Command) -> Result<(), CommandError> {
		self.producer
			.lock()
			.map_err(|_| CommandError::MutexPoisoned)?
			.push(command)
			.map_err(|_| CommandError::CommandQueueFull)
	}
}

impl std::fmt::Debug for CommandProducer {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.write_str("CommandProducer")
	}
}