Skip to content

Commit df1242f

Browse files
authored
Merge pull request #348 from szymonlesisz/feat/deviceid-from-str
Add DeviceId from str conversion
2 parents 23ab0f2 + e4200f5 commit df1242f

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

bluez-async/src/device.rs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use dbus::Path;
33
use dbus::arg::{PropMap, RefArg, Variant, cast};
44
use serde::{Deserialize, Serialize};
55
use std::collections::HashMap;
6+
use std::convert::TryFrom;
67
use std::fmt::{self, Display, Formatter};
78
use std::str::FromStr;
89
use uuid::Uuid;
@@ -41,6 +42,23 @@ impl From<DeviceId> for Path<'static> {
4142
}
4243
}
4344

45+
impl FromStr for DeviceId {
46+
type Err = BluetoothError;
47+
48+
fn from_str(s: &str) -> Result<Self, Self::Err> {
49+
if !s.starts_with("hci") {
50+
return Err(BluetoothError::DeviceIdParseError(s.to_string()));
51+
}
52+
53+
let path = Path::new(format!("/org/bluez/{}", s))
54+
.map_err(|_| BluetoothError::DeviceIdParseError(s.to_string()))?;
55+
56+
Ok(DeviceId {
57+
object_path: path.into_static(),
58+
})
59+
}
60+
}
61+
4462
impl Display for DeviceId {
4563
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
4664
write!(
@@ -296,6 +314,18 @@ mod tests {
296314
assert_eq!(device_id.to_string(), "hci0/dev_11_22_33_44_55_66");
297315
}
298316

317+
#[test]
318+
fn from_string() {
319+
let device_id = DeviceId::from_str("hci0/dev_11_22_33_44_55_66");
320+
assert_eq!(device_id.unwrap().to_string(), "hci0/dev_11_22_33_44_55_66");
321+
322+
let invalid_id = DeviceId::from_str("dev_11_22_33_44_55_66");
323+
assert_eq!(
324+
invalid_id.unwrap_err().to_string(),
325+
"Error parsing DeviceId string: dev_11_22_33_44_55_66"
326+
);
327+
}
328+
299329
#[test]
300330
fn service_data() {
301331
let uuid = uuid_from_u32(0x11223344);

bluez-async/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,9 @@ pub enum BluetoothError {
9696
/// Error parsing a `Modalias` from a string.
9797
#[error(transparent)]
9898
ModaliasParseError(#[from] ParseModaliasError),
99+
/// Error parsing DeviceId from a string.
100+
#[error("Error parsing DeviceId string: {0}")]
101+
DeviceIdParseError(String),
99102
}
100103

101104
/// Error type for futures representing tasks spawned by this crate.

0 commit comments

Comments
 (0)