Skip to content

Commit 6af5e09

Browse files
committed
create std feature and adjust imports
The worst change here is substituting `last_os_error` to just reading `errno` from `libc`. However, since ALSA can only be used in `linux` systems, which will always have `errno` in their `libc`, with the correct semantics, this should be fine.
1 parent 6fb4d55 commit 6af5e09

File tree

16 files changed

+132
-72
lines changed

16 files changed

+132
-72
lines changed

Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,7 @@ anyhow = "1.0"
2525
[badges]
2626
is-it-maintained-issue-resolution = { repository = "diwic/alsa-rs" }
2727
is-it-maintained-open-issues = { repository = "diwic/alsa-rs" }
28+
29+
[features]
30+
default = ["std"]
31+
std = []

src/card.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use libc::{c_int, c_char};
33
use super::error::*;
44
use crate::alsa;
55
use core::ffi::CStr;
6+
use ::alloc::string::String;
67

78
/// An ALSA sound card, uniquely identified by its index.
89
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
@@ -48,7 +49,8 @@ impl Card {
4849

4950
#[test]
5051
fn print_cards() {
52+
extern crate std;
5153
for a in Iter::new().map(|a| a.unwrap()) {
52-
println!("Card #{}: {} ({})", a.get_index(), a.get_name().unwrap(), a.get_longname().unwrap())
54+
std::println!("Card #{}: {} ({})", a.get_index(), a.get_name().unwrap(), a.get_longname().unwrap())
5355
}
5456
}

src/chmap.rs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
use crate::alsa;
22
use core::{fmt, mem, slice};
33
use super::error::*;
4+
use ::alloc::vec::Vec;
5+
use ::alloc::vec;
46

57
alsa_enum!(
68
/// [SND_CHMAP_TYPE_xxx](http://www.alsa-project.org/alsa-doc/alsa-lib/group___p_c_m.html) constants
@@ -136,6 +138,7 @@ impl Iterator for ChmapsQuery {
136138

137139
#[test]
138140
fn chmap_for_first_pcm() {
141+
extern crate std;
139142
use super::*;
140143
use ::alloc::ffi::CString;
141144
use crate::device_name::HintIter;
@@ -146,18 +149,18 @@ fn chmap_for_first_pcm() {
146149

147150
let i = HintIter::new(None, &*CString::new("pcm").unwrap()).unwrap();
148151
for p in i.map(|n| n.name.unwrap()) {
149-
println!("Chmaps for {:?}:", p);
152+
std::println!("Chmaps for {:?}:", p);
150153
match PCM::open(&CString::new(p).unwrap(), Direction::Playback, false) {
151154
Ok(a) => for c in a.query_chmaps() {
152-
println!(" {:?}, {}", c.0, c.1);
155+
std::println!(" {:?}, {}", c.0, c.1);
153156
},
154-
Err(a) => println!(" {}", a) // It's okay to have entries in the name hint array that can't be opened
157+
Err(a) => std::println!(" {}", a) // It's okay to have entries in the name hint array that can't be opened
155158
}
156159
}
157160

158161
output.borrow_mut().buffer_string(|buf| {
159162
let str = CString::new(buf).unwrap();
160-
println!("Errors:\n{}", str.to_str().unwrap());
163+
std::println!("Errors:\n{}", str.to_str().unwrap());
161164
});
162165

163166
}

src/config.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ impl Config {
3636

3737
#[test]
3838
fn config_save() {
39+
extern crate std;
3940
let c = update_ref().unwrap();
4041
let mut outp = Output::buffer_open().unwrap();
4142
c.save(&mut outp).unwrap();
42-
println!("== Config save ==\n{}", outp);
43-
}
43+
std::println!("== Config save ==\n{}", outp);
44+
}

src/ctl_int.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ impl Ctl {
6161
}
6262

6363
pub fn from_card(c: &Card, nonblock: bool) -> Result<Ctl> {
64-
let s = format!("hw:{}", c.get_index());
64+
let s = ::alloc::format!("hw:{}", c.get_index());
6565
Ctl::open(&CString::new(s).unwrap(), nonblock)
6666
}
6767

@@ -547,6 +547,7 @@ impl EventMask {
547547

548548
#[test]
549549
fn print_sizeof() {
550+
extern crate std;
550551
let elemid = unsafe { alsa::snd_ctl_elem_id_sizeof() } as usize;
551552
let elemvalue = unsafe { alsa::snd_ctl_elem_value_sizeof() } as usize;
552553
let eleminfo = unsafe { alsa::snd_ctl_elem_info_sizeof() } as usize;
@@ -555,5 +556,5 @@ fn print_sizeof() {
555556
// assert!(elemvalue <= ELEM_VALUE_SIZE);
556557
// assert!(eleminfo <= ELEM_INFO_SIZE);
557558

558-
println!("Elem id: {}, Elem value: {}, Elem info: {}", elemid, elemvalue, eleminfo);
559+
std::println!("Elem id: {}, Elem value: {}, Elem info: {}", elemid, elemvalue, eleminfo);
559560
}

src/device_name.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use super::{Card, Direction};
2121
use super::error::*;
2222
use core::ffi::CStr;
2323
use ::alloc::ffi::CString;
24+
use ::alloc::string::String;
2425

2526
/// [snd_device_name_hint](http://www.alsa-project.org/alsa-doc/alsa-lib/group___control.html) wrapper
2627
pub struct HintIter(*mut *mut c_void, isize);
@@ -83,9 +84,10 @@ impl Hint {
8384

8485
#[test]
8586
fn print_hints() {
87+
extern crate std;
8688
for t in &["pcm", "ctl", "rawmidi", "timer", "seq", "hwdep"] {
87-
println!("{} devices:", t);
89+
std::println!("{} devices:", t);
8890
let i = HintIter::new(None, &*CString::new(*t).unwrap()).unwrap();
89-
for a in i { println!(" {:?}", a) }
91+
for a in i { std::println!(" {:?}", a) }
9092
}
9193
}

src/direct/pcm.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,7 @@ impl<'a, S: 'static> Drop for CaptureIter<'a, S> {
518518
#[test]
519519
#[ignore] // Not everyone has a recording device on plughw:1. So let's ignore this test by default.
520520
fn record_from_plughw_rw() {
521+
extern crate std;
521522
use crate::pcm::*;
522523
use crate::{ValueOr, Direction};
523524
use ::alloc::ffi::CString;
@@ -539,7 +540,7 @@ fn record_from_plughw_rw() {
539540
assert_eq!(ss.state(), State::Prepared);
540541
pcm.start().unwrap();
541542
assert_eq!(c.appl_ptr(), 0);
542-
println!("{:?}, {:?}", ss, c);
543+
std::println!("{:?}, {:?}", ss, c);
543544
let mut buf = [0i16; 512*2];
544545
assert_eq!(pcm.io_i16().unwrap().readi(&mut buf).unwrap(), 512);
545546
assert_eq!(c.appl_ptr(), 512);
@@ -554,10 +555,12 @@ fn record_from_plughw_rw() {
554555
#[test]
555556
#[ignore] // Not everyone has a record device on plughw:1. So let's ignore this test by default.
556557
fn record_from_plughw_mmap() {
558+
extern crate std;
557559
use crate::pcm::*;
558560
use crate::{ValueOr, Direction};
559561
use ::alloc::ffi::CString;
560-
use std::{thread, time};
562+
use ::alloc::vec::Vec;
563+
use std::{thread, time, println};
561564

562565
let pcm = PCM::open(&*CString::new("plughw:1").unwrap(), Direction::Capture, false).unwrap();
563566
let hwp = HwParams::any(&pcm).unwrap();
@@ -598,6 +601,7 @@ fn record_from_plughw_mmap() {
598601
#[test]
599602
#[ignore]
600603
fn playback_to_plughw_mmap() {
604+
extern crate std;
601605
use crate::pcm::*;
602606
use crate::{ValueOr, Direction};
603607
use ::alloc::ffi::CString;
@@ -615,7 +619,7 @@ fn playback_to_plughw_mmap() {
615619
assert_eq!(m.appl_ptr(), 0);
616620
assert_eq!(m.hw_ptr(), 0);
617621

618-
println!("{:?}", m);
622+
std::println!("{:?}", m);
619623
let mut i = (0..(m.buffer_size() * 2)).map(|i|
620624
(((i / 2) as f32 * 2.0 * ::core::f32::consts::PI / 128.0).sin() * 8192.0) as i16);
621625
m.write(&mut i);

src/error.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use libc::{c_char, c_int, c_void, free};
44
use core::error::Error as StdError;
55
use core::ffi::CStr;
66
use core::{fmt, str};
7+
use ::alloc::string::{String, ToString};
78

89
/// ALSA error
910
///
@@ -12,10 +13,14 @@ use core::{fmt, str};
1213
/// An Error is also returned in case ALSA returns a string that
1314
/// cannot be translated into Rust's UTF-8 strings.
1415
#[derive(Clone, PartialEq, Copy)]
15-
pub struct Error(&'static str, i32);
16+
pub struct Error(&'static str, c_int);
1617

1718
pub type Result<T> = ::core::result::Result<T, Error>;
1819

20+
extern "C" {
21+
pub(crate) static errno: c_int;
22+
}
23+
1924
macro_rules! acheck {
2025
($f: ident ( $($x: expr),* ) ) => {{
2126
let r = unsafe { alsa::$f( $($x),* ) };
@@ -67,9 +72,7 @@ impl Error {
6772
pub fn last(func: &'static str) -> Error {
6873
Self(
6974
func,
70-
std::io::Error::last_os_error()
71-
.raw_os_error()
72-
.unwrap_or_default(),
75+
unsafe {errno},
7376
)
7477
}
7578

@@ -123,8 +126,8 @@ impl fmt::Display for Error {
123126
///
124127
/// Note this doesn't include the total set of possible errno variants, but they
125128
/// can easily be added in the future for better error messages
126-
fn desc(errno: i32) -> &'static str {
127-
match errno {
129+
fn desc(err: i32) -> &'static str {
130+
match err {
128131
libc::EPERM => "Operation not permitted",
129132
libc::ENOENT => "No such file or directory",
130133
libc::ESRCH => "No such process",

src/hctl.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ impl HCtl {
6868

6969
/// Wrapper around open. You probably want to call `load` afterwards.
7070
pub fn from_card(c: &Card, nonblock: bool) -> Result<HCtl> {
71-
let s = format!("hw:{}", c.get_index());
71+
let s = ::alloc::format!("hw:{}", c.get_index());
7272
HCtl::new(&s, nonblock)
7373
}
7474

@@ -144,32 +144,34 @@ impl<'a> Elem<'a> {
144144

145145
#[test]
146146
fn print_hctls() {
147+
extern crate std;
147148
for a in super::card::Iter::new().map(|x| x.unwrap()) {
148149
use ::alloc::ffi::CString;
149-
let h = HCtl::open(&CString::new(format!("hw:{}", a.get_index())).unwrap(), false).unwrap();
150+
let h = HCtl::open(&CString::new(::alloc::format!("hw:{}", a.get_index())).unwrap(), false).unwrap();
150151
h.load().unwrap();
151-
println!("Card {}:", a.get_name().unwrap());
152+
std::println!("Card {}:", a.get_name().unwrap());
152153
for b in h.elem_iter() {
153-
println!(" {:?} - {:?}", b.get_id().unwrap(), b.read().unwrap());
154+
std::println!(" {:?} - {:?}", b.get_id().unwrap(), b.read().unwrap());
154155
}
155156
}
156157
}
157158

158159
#[test]
159160
fn print_jacks() {
161+
extern crate std;
160162
for a in super::card::Iter::new().map(|x| x.unwrap()) {
161163
use ::alloc::ffi::CString;
162-
let h = HCtl::open(&CString::new(format!("hw:{}", a.get_index())).unwrap(), false).unwrap();
164+
let h = HCtl::open(&CString::new(::alloc::format!("hw:{}", a.get_index())).unwrap(), false).unwrap();
163165
h.load().unwrap();
164166
for b in h.elem_iter() {
165167
let id = b.get_id().unwrap();
166168
if id.get_interface() != super::ctl_int::ElemIface::Card { continue; }
167169
let name = id.get_name().unwrap();
168170
if !name.ends_with(" Jack") { continue; }
169171
if name.ends_with(" Phantom Jack") {
170-
println!("{} is always present", &name[..name.len()-13])
172+
std::println!("{} is always present", &name[..name.len()-13])
171173
}
172-
else { println!("{} is {}", &name[..name.len()-5],
174+
else { std::println!("{} is {}", &name[..name.len()-5],
173175
if b.read().unwrap().get_boolean(0).unwrap() { "plugged in" } else { "unplugged" })
174176
}
175177
}

src/io.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ pub struct Output(*mut alsa::snd_output_t);
1010

1111
unsafe impl Send for Output {}
1212

13-
thread_local! {
13+
#[cfg(feature = "std")]
14+
std::thread_local! {
1415
static ERROR_OUTPUT: RefCell<Option<Rc<RefCell<Output>>>> = RefCell::new(None);
1516
}
1617

@@ -39,6 +40,7 @@ impl Output {
3940
///
4041
/// Sometimes alsa-lib writes to stderr, but if you prefer, you can write it here instead.
4142
/// Should you wish to empty the buffer; just call local_error_handler again and drop the old instance.
43+
#[cfg(feature = "std")]
4244
pub fn local_error_handler() -> Result<Rc<RefCell<Output>>> {
4345
let output = Output::buffer_open()?;
4446
let r = Rc::new(RefCell::new(output));
@@ -60,14 +62,15 @@ impl fmt::Debug for Output {
6062
impl fmt::Display for Output {
6163
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6264
self.buffer_string(|b| {
63-
let s = String::from_utf8_lossy(b);
65+
let s = ::alloc::string::String::from_utf8_lossy(b);
6466
f.write_str(&*s)
6567
})
6668
}
6769
}
6870

6971
pub fn output_handle(o: &Output) -> *mut alsa::snd_output_t { o.0 }
7072

73+
#[cfg(feature = "std")]
7174
unsafe extern "C" fn our_error_handler(file: *const c_char,
7275
line: c_int,
7376
func: *const c_char,

0 commit comments

Comments
 (0)