mpdclient 0.2.0

Rust interface to MPD using libmpdclient
Documentation
use std::ffi::CStr;

use mpdclient_sys::{
    mpd_settings, mpd_settings_get_host, mpd_settings_get_password, mpd_settings_get_port,
    mpd_settings_get_timeout_ms,
};

/// Settings used for a [`Connection`](crate::Connection) to the MPD.
#[derive(Debug)]
pub struct Settings {
    inner: *mut mpd_settings,
}

impl Settings {
    /// Get the host name without password and port.
    #[must_use]
    pub fn host(&self) -> Option<String> {
        unsafe {
            let host = mpd_settings_get_host(self.inner);
            if host.is_null() {
                None
            } else {
                Some(CStr::from_ptr(host).to_string_lossy().to_string())
            }
        }
    }

    /// Get the port, if applicable for the connection type.
    #[must_use]
    pub fn port(&self) -> Option<u16> {
        unsafe {
            let port = mpd_settings_get_port(self.inner);
            if port == 0 {
                None
            } else {
                // Unreachable, as a port can't be bigger than u16
                Some(u16::try_from(port).unwrap_or_else(|_| unreachable!()))
            }
        }
    }

    /// Get the timeout in ms.
    #[must_use]
    pub fn timeout(&self) -> Option<u32> {
        unsafe {
            let timeout = mpd_settings_get_timeout_ms(self.inner);
            if timeout == 0 { None } else { Some(timeout) }
        }
    }

    /// Get the password.
    #[must_use]
    pub fn password(&self) -> Option<String> {
        unsafe {
            let password = mpd_settings_get_password(self.inner);
            if password.is_null() {
                None
            } else {
                Some(CStr::from_ptr(password).to_string_lossy().to_string())
            }
        }
    }
}

unsafe impl Send for Settings {}

impl From<*const mpd_settings> for Settings {
    fn from(value: *const mpd_settings) -> Self {
        Settings {
            inner: value.cast_mut(),
        }
    }
}