Skip to main content

alsa/
card.rs

1//! Sound card enumeration
2use libc::{c_int, c_char};
3use super::error::*;
4use crate::alsa;
5use core::ffi::CStr;
6use ::alloc::string::String;
7
8/// An ALSA sound card, uniquely identified by its index.
9#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
10pub struct Card(c_int);
11
12/// Iterate over existing sound cards.
13#[derive(Debug)]
14pub struct Iter(c_int);
15
16impl Iter {
17    pub fn new() -> Iter { Iter(-1) }
18}
19
20impl Iterator for Iter {
21    type Item = Result<Card>;
22
23    fn next(&mut self) -> Option<Result<Card>> {
24        match acheck!(snd_card_next(&mut self.0)) {
25            Ok(_) if self.0 == -1 => None,
26            Ok(_) => Some(Ok(Card(self.0))),
27            Err(e) => Some(Err(e)),
28        }
29    }
30}
31
32impl Card {
33    pub fn new(index: c_int) -> Card { Card(index) }
34    pub fn from_str(s: &CStr) -> Result<Card> {
35        acheck!(snd_card_get_index(s.as_ptr())).map(Card)
36    }
37    pub fn get_name(&self) -> Result<String> {
38        let mut c: *mut c_char = ::core::ptr::null_mut();
39        acheck!(snd_card_get_name(self.0, &mut c))
40            .and_then(|_| from_alloc("snd_card_get_name", c)) 
41    }
42    pub fn get_longname(&self) -> Result<String> {
43        let mut c: *mut c_char = ::core::ptr::null_mut();
44        acheck!(snd_card_get_longname(self.0, &mut c))
45            .and_then(|_| from_alloc("snd_card_get_longname", c)) 
46    }
47
48    pub fn get_index(&self) -> c_int { self.0 }
49}
50
51#[test]
52fn print_cards() {
53    extern crate std;
54    for a in Iter::new().map(|a| a.unwrap()) {
55        std::println!("Card #{}: {} ({})", a.get_index(), a.get_name().unwrap(), a.get_longname().unwrap())
56    }
57}