From 3d534fcc72b69ea9d6c058ab5920999de0151d64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9rald=20Lelong?= Date: Thu, 23 May 2019 12:29:58 +0200 Subject: [PATCH 1/3] rustfmt --- src/connection.rs | 6 +++--- src/dbus_api.rs | 7 ++++--- src/dbus_nm.rs | 27 ++++++++++++++++----------- src/device.rs | 4 ++-- src/errors.rs | 2 +- src/lib.rs | 12 ++++++------ src/manager.rs | 2 +- src/service.rs | 29 +++++++++++++++++------------ src/ssid.rs | 8 ++++---- src/wifi.rs | 7 ++++--- 10 files changed, 58 insertions(+), 46 deletions(-) diff --git a/src/connection.rs b/src/connection.rs index b4df188..e8fe673 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -1,13 +1,13 @@ -use std::rc::Rc; use std::fmt; use std::net::Ipv4Addr; +use std::rc::Rc; -use errors::*; use dbus_nm::DBusNetworkManager; +use errors::*; -use wifi::{AccessPoint, AccessPointCredentials}; use device::{get_active_connection_devices, Device}; use ssid::{AsSsidSlice, Ssid}; +use wifi::{AccessPoint, AccessPointCredentials}; #[derive(Clone)] pub struct Connection { diff --git a/src/dbus_api.rs b/src/dbus_api.rs index 73017e1..e2cdf99 100644 --- a/src/dbus_api.rs +++ b/src/dbus_api.rs @@ -1,7 +1,7 @@ -use dbus::Connection as DBusConnection; -use dbus::{BusType, ConnPath, Message, Path}; use dbus::arg::{Array, Get, Iter, RefArg, Variant}; use dbus::stdintf::OrgFreedesktopDBusProperties; +use dbus::Connection as DBusConnection; +use dbus::{BusType, ConnPath, Message, Path}; use errors::*; @@ -108,7 +108,8 @@ impl DBusApi { } fn send_message_checked(&self, message: Message) -> Option> { - match self.connection + match self + .connection .send_with_reply_and_block(message, self.method_timeout as i32 * 1000) { Ok(response) => Some(Ok(response)), diff --git a/src/dbus_nm.rs b/src/dbus_nm.rs index a89bf5b..67ee580 100644 --- a/src/dbus_nm.rs +++ b/src/dbus_nm.rs @@ -1,17 +1,17 @@ use std::collections::HashMap; use std::net::Ipv4Addr; -use dbus::Path; use dbus::arg::{Array, Dict, Iter, RefArg, Variant}; +use dbus::Path; use ascii::AsciiStr; +use connection::{ConnectionSettings, ConnectionState}; +use dbus_api::{extract, path_to_string, variant_iter_to_vec_u8, DBusApi, VariantTo}; +use device::{DeviceState, DeviceType}; use errors::*; -use dbus_api::{extract, path_to_string, DBusApi, VariantTo, variant_iter_to_vec_u8}; use manager::{Connectivity, NetworkManagerState}; -use connection::{ConnectionSettings, ConnectionState}; use ssid::{AsSsidSlice, Ssid}; -use device::{DeviceState, DeviceType}; use wifi::{AccessPoint, AccessPointCredentials, NM80211ApFlags, NM80211ApSecurityFlags}; type VariantMap = HashMap>>; @@ -51,7 +51,8 @@ impl DBusNetworkManager { } pub fn get_state(&self) -> Result { - let response = self.dbus + let response = self + .dbus .call(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "state")?; let state: u32 = self.dbus.extract(&response)?; @@ -60,8 +61,9 @@ impl DBusNetworkManager { } pub fn check_connectivity(&self) -> Result { - let response = self.dbus - .call(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "CheckConnectivity")?; + let response = + self.dbus + .call(NM_SERVICE_PATH, NM_SERVICE_INTERFACE, "CheckConnectivity")?; let connectivity: u32 = self.dbus.extract(&response)?; @@ -79,8 +81,9 @@ impl DBusNetworkManager { } pub fn list_connections(&self) -> Result> { - let response = self.dbus - .call(NM_SETTINGS_PATH, NM_SETTINGS_INTERFACE, "ListConnections")?; + let response = + self.dbus + .call(NM_SETTINGS_PATH, NM_SETTINGS_INTERFACE, "ListConnections")?; let array: Array = self.dbus.extract(&response)?; @@ -108,7 +111,8 @@ impl DBusNetworkManager { } pub fn get_connection_settings(&self, path: &str) -> Result { - let response = self.dbus + let response = self + .dbus .call(path, NM_CONNECTION_INTERFACE, "GetSettings")?; let dict: Dict<&str, Dict<&str, Variant, _>, _> = self.dbus.extract(&response)?; @@ -416,7 +420,8 @@ impl DBusNetworkManager { } pub fn get_access_point_ssid(&self, path: &str) -> Option { - if let Ok(ssid_vec) = self.dbus + if let Ok(ssid_vec) = self + .dbus .property::>(path, NM_ACCESS_POINT_INTERFACE, "Ssid") { Ssid::from_bytes(ssid_vec).ok() diff --git a/src/device.rs b/src/device.rs index bd7f22b..34a2640 100644 --- a/src/device.rs +++ b/src/device.rs @@ -1,8 +1,8 @@ -use std::rc::Rc; use std::fmt; +use std::rc::Rc; -use errors::*; use dbus_nm::DBusNetworkManager; +use errors::*; use wifi::{new_wifi_device, WiFiDevice}; diff --git a/src/errors.rs b/src/errors.rs index f878e0d..f44548e 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -1,4 +1,4 @@ -error_chain!{ +error_chain! { foreign_links { Ascii(::ascii::AsAsciiStrError); Utf8(::std::str::Utf8Error); diff --git a/src/lib.rs b/src/lib.rs index a8eeb9b..cfd9413 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,17 +18,17 @@ extern crate ascii; pub mod errors; -mod dbus_nm; +mod connection; mod dbus_api; +mod dbus_nm; +mod device; mod manager; mod service; -mod connection; -mod device; -mod wifi; mod ssid; +mod wifi; -pub use manager::{Connectivity, NetworkManager}; pub use connection::{Connection, ConnectionSettings, ConnectionState}; pub use device::{Device, DeviceState, DeviceType}; -pub use wifi::{AccessPoint, AccessPointCredentials, Security}; +pub use manager::{Connectivity, NetworkManager}; pub use service::ServiceState; +pub use wifi::{AccessPoint, AccessPointCredentials, Security}; diff --git a/src/manager.rs b/src/manager.rs index d3188f4..1aef8a5 100644 --- a/src/manager.rs +++ b/src/manager.rs @@ -1,7 +1,7 @@ use std::rc::Rc; -use errors::*; use dbus_nm::DBusNetworkManager; +use errors::*; use connection::{get_active_connections, get_connections, Connection}; use device::{get_device_by_interface, get_devices, Device}; diff --git a/src/service.rs b/src/service.rs index 4f7f094..ab8af46 100644 --- a/src/service.rs +++ b/src/service.rs @@ -3,13 +3,13 @@ extern crate futures; extern crate futures_cpupool; extern crate tokio_timer; -use std::str::FromStr; -use std::time::Duration; -use self::dbus::{BusType, Connection, ConnectionItem, Interface, Member, Message, Path, Props}; use self::dbus::arg::{Dict, Iter, Variant}; +use self::dbus::{BusType, Connection, ConnectionItem, Interface, Member, Message, Path, Props}; use self::futures::Future; use self::futures_cpupool::CpuPool; use self::tokio_timer::Timer; +use std::str::FromStr; +use std::time::Duration; use errors::*; @@ -30,8 +30,9 @@ pub fn start_service(timeout: u64) -> Result { SD_SERVICE_PATH, SD_MANAGER_INTERFACE, "StartUnit", - ).map_err(|_| ErrorKind::Service)? - .append2("NetworkManager.service", "fail"); + ) + .map_err(|_| ErrorKind::Service)? + .append2("NetworkManager.service", "fail"); let connection = Connection::get_private(BusType::System).map_err(|_| ErrorKind::Service)?; @@ -57,8 +58,9 @@ pub fn stop_service(timeout: u64) -> Result { SD_SERVICE_PATH, SD_MANAGER_INTERFACE, "StopUnit", - ).map_err(|_| ErrorKind::Service)? - .append2("NetworkManager.service", "fail"); + ) + .map_err(|_| ErrorKind::Service)? + .append2("NetworkManager.service", "fail"); let connection = Connection::get_private(BusType::System).map_err(|_| ErrorKind::Service)?; @@ -78,8 +80,9 @@ pub fn get_service_state() -> Result { SD_SERVICE_PATH, SD_MANAGER_INTERFACE, "GetUnit", - ).map_err(|_| ErrorKind::Service)? - .append1("NetworkManager.service"); + ) + .map_err(|_| ErrorKind::Service)? + .append1("NetworkManager.service"); let connection = Connection::get_private(BusType::System).map_err(|_| ErrorKind::Service)?; @@ -95,8 +98,9 @@ pub fn get_service_state() -> Result { path, SD_UNIT_INTERFACE, 2000, - ).get("ActiveState") - .map_err(|_| ErrorKind::Service)?; + ) + .get("ActiveState") + .map_err(|_| ErrorKind::Service)?; response .inner::<&str>() @@ -115,7 +119,8 @@ fn handler(timeout: u64, target_state: ServiceState) -> Result { .then(|_| bail!(ErrorKind::Service)); let process = CpuPool::new_num_cpus().spawn_fn(|| { - let connection = Connection::get_private(BusType::System).map_err(|_| ErrorKind::Service)?; + let connection = + Connection::get_private(BusType::System).map_err(|_| ErrorKind::Service)?; connection .add_match( "type='signal', sender='org.freedesktop.systemd1', \ diff --git a/src/ssid.rs b/src/ssid.rs index ed7f09b..813a401 100644 --- a/src/ssid.rs +++ b/src/ssid.rs @@ -1,9 +1,9 @@ -use std::ops::Deref; -use std::mem; -use std::str; +use std::ascii; use std::fmt; use std::fmt::Write; -use std::ascii; +use std::mem; +use std::ops::Deref; +use std::str; use errors::*; diff --git a/src/wifi.rs b/src/wifi.rs index 0cf5e42..2b27c84 100644 --- a/src/wifi.rs +++ b/src/wifi.rs @@ -1,8 +1,8 @@ -use std::rc::Rc; use std::net::Ipv4Addr; +use std::rc::Rc; -use errors::*; use dbus_nm::DBusNetworkManager; +use errors::*; use connection::{connect_to_access_point, create_hotspot, Connection, ConnectionState}; use device::{Device, PathGetter}; @@ -31,7 +31,8 @@ impl<'a> WiFiDevice<'a> { pub fn get_access_points(&self) -> Result> { let mut access_points = Vec::new(); - let paths = self.dbus_manager + let paths = self + .dbus_manager .get_device_access_points(self.device.path())?; for path in paths { From 5722f54916e352e6b05aee477170836d4ac0f215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A9rald=20Lelong?= Date: Thu, 23 May 2019 12:36:31 +0200 Subject: [PATCH 2/3] satisfy clippy --- Cargo.toml | 2 +- src/connection.rs | 8 ++++---- src/dbus_api.rs | 14 +++++++------- src/dbus_nm.rs | 32 ++++++++++++++++---------------- src/device.rs | 12 ++++++------ src/manager.rs | 12 ++++++------ src/ssid.rs | 4 ++-- src/wifi.rs | 8 ++++---- 8 files changed, 46 insertions(+), 46 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index bf905a4..3b84b83 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ ascii = "0.8" log = "0.3" [dependencies.error-chain] -version = "0.11" +version = "0.12" default-features = false [dev-dependencies] diff --git a/src/connection.rs b/src/connection.rs index e8fe673..8dfc74f 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -23,7 +23,7 @@ impl Connection { Ok(Connection { dbus_manager: Rc::clone(dbus_manager), path: path.to_string(), - settings: settings, + settings, }) } @@ -78,7 +78,7 @@ impl Connection { &ConnectionState::Activated, self.dbus_manager.method_timeout(), ) - }, + } } } @@ -120,7 +120,7 @@ impl Connection { } else { Ok(ConnectionState::Deactivated) } - }, + } } } @@ -206,7 +206,7 @@ impl From for ConnectionState { _ => { warn!("Undefined connection state: {}", state); ConnectionState::Unknown - }, + } } } } diff --git a/src/dbus_api.rs b/src/dbus_api.rs index e2cdf99..1cf6a86 100644 --- a/src/dbus_api.rs +++ b/src/dbus_api.rs @@ -26,10 +26,10 @@ impl DBusApi { let method_timeout = method_timeout.unwrap_or(DEFAULT_TIMEOUT); DBusApi { - connection: connection, - method_timeout: method_timeout, - base: base, - method_retry_error_names: method_retry_error_names, + connection, + method_timeout, + base, + method_retry_error_names, } } @@ -102,7 +102,7 @@ impl DBusApi { } self.send_message_checked(message) - }, + } Err(details) => Some(Err(ErrorKind::DBusAPI(details).into())), } } @@ -126,7 +126,7 @@ impl DBusApi { } Some(Err(Error::from(e))) - }, + } } } @@ -160,7 +160,7 @@ impl DBusApi { None => property_error("no details", false), }; Err(e).chain_err(|| dbus_err) - }, + } } } diff --git a/src/dbus_nm.rs b/src/dbus_nm.rs index 67ee580..9d83d3a 100644 --- a/src/dbus_nm.rs +++ b/src/dbus_nm.rs @@ -128,30 +128,30 @@ impl DBusNetworkManager { match k2 { "id" => { id = extract::(&mut v2)?; - }, + } "uuid" => { uuid = extract::(&mut v2)?; - }, + } "type" => { kind = extract::(&mut v2)?; - }, + } "ssid" => { ssid = Ssid::from_bytes(variant_iter_to_vec_u8(&mut v2)?)?; - }, + } "mode" => { mode = extract::(&mut v2)?; - }, - _ => {}, + } + _ => {} } } } Ok(ConnectionSettings { - kind: kind, - id: id, - uuid: uuid, - ssid: ssid, - mode: mode, + kind, + id, + uuid, + ssid, + mode, }) } @@ -223,7 +223,7 @@ impl DBusNetworkManager { ); settings.insert("802-11-wireless-security".to_string(), security_settings); - }, + } AccessPointCredentials::Wpa { ref passphrase } => { let mut security_settings: VariantMap = HashMap::new(); @@ -235,7 +235,7 @@ impl DBusNetworkManager { ); settings.insert("802-11-wireless-security".to_string(), security_settings); - }, + } AccessPointCredentials::Enterprise { ref identity, ref passphrase, @@ -252,8 +252,8 @@ impl DBusNetworkManager { settings.insert("802-11-wireless-security".to_string(), security_settings); settings.insert("802-1x".to_string(), eap); - }, - AccessPointCredentials::None => {}, + } + AccessPointCredentials::None => {} }; let response = self.dbus.call_with_args( @@ -513,6 +513,6 @@ fn verify_ascii_password(password: &str) -> Result<&str> { } else { Ok(password) } - }, + } } } diff --git a/src/device.rs b/src/device.rs index 34a2640..c13b808 100644 --- a/src/device.rs +++ b/src/device.rs @@ -23,8 +23,8 @@ impl Device { Ok(Device { dbus_manager: Rc::clone(dbus_manager), path: path.to_string(), - interface: interface, - device_type: device_type, + interface, + device_type, }) } @@ -72,7 +72,7 @@ impl Device { &DeviceState::Activated, self.dbus_manager.method_timeout(), ) - }, + } } } @@ -100,7 +100,7 @@ impl Device { &DeviceState::Disconnected, self.dbus_manager.method_timeout(), ) - }, + } } } } @@ -181,7 +181,7 @@ impl From for DeviceType { _ => { warn!("Undefined device type: {}", device_type); DeviceType::Unknown - }, + } } } } @@ -222,7 +222,7 @@ impl From for DeviceState { _ => { warn!("Undefined device state: {}", state); DeviceState::Unknown - }, + } } } } diff --git a/src/manager.rs b/src/manager.rs index 1aef8a5..a625948 100644 --- a/src/manager.rs +++ b/src/manager.rs @@ -148,7 +148,7 @@ impl From for NetworkManagerState { _ => { warn!("Undefined Network Manager state: {}", state); NetworkManagerState::Unknown - }, + } } } } @@ -173,7 +173,7 @@ impl From for Connectivity { _ => { warn!("Undefined connectivity state: {}", state); Connectivity::Unknown - }, + } } } } @@ -186,14 +186,14 @@ mod tests { fn test_get_connections() { let manager = NetworkManager::new(); let connections = manager.get_connections().unwrap(); - assert!(connections.len() > 0); + assert!(!connections.is_empty()); } #[test] fn test_get_devices() { let manager = NetworkManager::new(); let devices = manager.get_devices().unwrap(); - assert!(devices.len() > 0); + assert!(!devices.is_empty()); } #[test] @@ -222,7 +222,7 @@ mod tests { ServiceState::Active, NetworkManager::get_service_state().unwrap() ); - }, + } ServiceState::Inactive => { NetworkManager::start_service(10).unwrap(); assert_eq!( @@ -235,7 +235,7 @@ mod tests { ServiceState::Inactive, NetworkManager::get_service_state().unwrap() ); - }, + } _ => (), } } diff --git a/src/ssid.rs b/src/ssid.rs index 813a401..79d4943 100644 --- a/src/ssid.rs +++ b/src/ssid.rs @@ -44,7 +44,7 @@ impl Deref for Ssid { #[inline] fn deref(&self) -> &SsidSlice { - unsafe { mem::transmute(&self.vec[..]) } + unsafe { &*(&self.vec[..] as *const [u8] as *const SsidSlice) } } } @@ -93,7 +93,7 @@ impl AsSsidSlice for [u8] { self.len() ))) } else { - Ok(unsafe { mem::transmute(self) }) + Ok(unsafe { &*(self as *const [u8] as *const SsidSlice) }) } } } diff --git a/src/wifi.rs b/src/wifi.rs index 2b27c84..7baadeb 100644 --- a/src/wifi.rs +++ b/src/wifi.rs @@ -173,7 +173,7 @@ pub fn new_wifi_device<'a>( ) -> WiFiDevice<'a> { WiFiDevice { dbus_manager: Rc::clone(dbus_manager), - device: device, + device, } } @@ -185,9 +185,9 @@ fn get_access_point(manager: &DBusNetworkManager, path: &str) -> Result Date: Thu, 23 May 2019 13:00:44 +0200 Subject: [PATCH 3/3] add serde feature --- Cargo.toml | 5 +++++ src/connection.rs | 6 ++++++ src/device.rs | 6 ++++++ src/lib.rs | 3 +++ src/manager.rs | 4 ++++ src/service.rs | 7 +++++-- src/ssid.rs | 17 +++++++++++++++++ src/wifi.rs | 7 +++++++ 8 files changed, 53 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 3b84b83..3b09a8f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,5 +22,10 @@ log = "0.3" version = "0.12" default-features = false +[dependencies.serde] +version = "1.0" +features = ["derive"] +optional = true + [dev-dependencies] clap = "2.32" diff --git a/src/connection.rs b/src/connection.rs index 8dfc74f..69f8d42 100644 --- a/src/connection.rs +++ b/src/connection.rs @@ -4,13 +4,17 @@ use std::rc::Rc; use dbus_nm::DBusNetworkManager; use errors::*; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; use device::{get_active_connection_devices, Device}; use ssid::{AsSsidSlice, Ssid}; use wifi::{AccessPoint, AccessPointCredentials}; #[derive(Clone)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct Connection { + #[cfg_attr(feature = "serde", serde(skip))] dbus_manager: Rc, path: String, settings: ConnectionSettings, @@ -178,6 +182,7 @@ impl<'a> From<&'a Connection> for i32 { } #[derive(Default, Debug, Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct ConnectionSettings { pub kind: String, // `type` is a reserved word, so we are using `kind` instead pub id: String, @@ -187,6 +192,7 @@ pub struct ConnectionSettings { } #[derive(Debug, Clone, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum ConnectionState { Unknown = 0, Activating = 1, diff --git a/src/device.rs b/src/device.rs index c13b808..f93f569 100644 --- a/src/device.rs +++ b/src/device.rs @@ -3,11 +3,15 @@ use std::rc::Rc; use dbus_nm::DBusNetworkManager; use errors::*; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; use wifi::{new_wifi_device, WiFiDevice}; #[derive(Clone)] +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct Device { + #[cfg_attr(feature = "serde", serde(skip))] dbus_manager: Rc, path: String, interface: String, @@ -126,6 +130,7 @@ impl PathGetter for Device { } #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum DeviceType { Unknown, Ethernet, @@ -187,6 +192,7 @@ impl From for DeviceType { } #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum DeviceState { Unknown, Unmanaged, diff --git a/src/lib.rs b/src/lib.rs index cfd9413..61a6d99 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,6 +16,9 @@ extern crate dbus; extern crate ascii; +#[cfg(feature = "serde")] +extern crate serde; + pub mod errors; mod connection; diff --git a/src/manager.rs b/src/manager.rs index a625948..41e7c8d 100644 --- a/src/manager.rs +++ b/src/manager.rs @@ -2,6 +2,8 @@ use std::rc::Rc; use dbus_nm::DBusNetworkManager; use errors::*; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; use connection::{get_active_connections, get_connections, Connection}; use device::{get_device_by_interface, get_devices, Device}; @@ -123,6 +125,7 @@ impl Default for NetworkManager { } #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum NetworkManagerState { Unknown, Asleep, @@ -154,6 +157,7 @@ impl From for NetworkManagerState { } #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum Connectivity { Unknown, None, diff --git a/src/service.rs b/src/service.rs index ab8af46..d233ac4 100644 --- a/src/service.rs +++ b/src/service.rs @@ -12,6 +12,8 @@ use std::str::FromStr; use std::time::Duration; use errors::*; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; pub const SD_SERVICE_MANAGER: &str = "org.freedesktop.systemd1"; pub const SD_SERVICE_PATH: &str = "/org/freedesktop/systemd1"; @@ -42,7 +44,7 @@ pub fn start_service(timeout: u64) -> Result { .map_err(|_| ErrorKind::Service)?; handler(timeout, ServiceState::Active) - }, + } } } @@ -70,7 +72,7 @@ pub fn stop_service(timeout: u64) -> Result { .map_err(|_| ErrorKind::Service)?; handler(timeout, ServiceState::Inactive) - }, + } } } @@ -176,6 +178,7 @@ fn handler(timeout: u64, target_state: ServiceState) -> Result { } #[derive(Debug, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum ServiceState { Active, Reloading, diff --git a/src/ssid.rs b/src/ssid.rs index 79d4943..438b8b8 100644 --- a/src/ssid.rs +++ b/src/ssid.rs @@ -6,12 +6,27 @@ use std::ops::Deref; use std::str; use errors::*; +#[cfg(feature = "serde")] +use serde::{ser::Error, Deserialize, Serialize, Serializer}; #[derive(Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(transparent))] pub struct Ssid { + #[cfg_attr(feature = "serde", serde(serialize_with = "as_str"))] vec: Vec, } +#[cfg(feature = "serde")] +fn as_str(vec: &[u8], serializer: S) -> std::result::Result +where + S: Serializer, +{ + match str::from_utf8(&vec) { + Ok(value) => serializer.serialize_some(&value), + Err(_) => Err(S::Error::custom("SSID contains invalid UTF-8 characters")), + } +} + impl Ssid { pub fn new() -> Self { Ssid { vec: Vec::new() } @@ -55,7 +70,9 @@ impl fmt::Debug for Ssid { } #[derive(PartialEq, Eq, PartialOrd, Ord, Hash)] +#[cfg_attr(feature = "serde", derive(Serialize), serde(transparent))] pub struct SsidSlice { + #[cfg_attr(feature = "serde", serde(serialize_with = "as_str"))] slice: [u8], } diff --git a/src/wifi.rs b/src/wifi.rs index 7baadeb..2318a7c 100644 --- a/src/wifi.rs +++ b/src/wifi.rs @@ -3,12 +3,16 @@ use std::rc::Rc; use dbus_nm::DBusNetworkManager; use errors::*; +#[cfg(feature = "serde")] +use serde::{Deserialize, Serialize}; use connection::{connect_to_access_point, create_hotspot, Connection, ConnectionState}; use device::{Device, PathGetter}; use ssid::{AsSsidSlice, Ssid, SsidSlice}; +#[cfg_attr(feature = "serde", derive(Serialize))] pub struct WiFiDevice<'a> { + #[cfg_attr(feature = "serde", serde(skip))] dbus_manager: Rc, device: &'a Device, } @@ -87,6 +91,7 @@ impl<'a> WiFiDevice<'a> { } #[derive(Debug)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct AccessPoint { pub path: String, pub ssid: Ssid, @@ -101,6 +106,7 @@ impl AccessPoint { } bitflags! { + #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub struct Security: u32 { const NONE = 0b0000_0000; const WEP = 0b0000_0001; @@ -111,6 +117,7 @@ bitflags! { } #[derive(Debug)] +#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] pub enum AccessPointCredentials { None, Wep {