use dbus::Path;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display, Formatter};
use uuid::Uuid;
use crate::CharacteristicId;
#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct DescriptorId {
#[serde(with = "crate::serde_path")]
pub(crate) object_path: Path<'static>,
}
impl DescriptorId {
#[cfg(test)]
pub(crate) fn new(object_path: &str) -> Self {
Self {
object_path: object_path.to_owned().into(),
}
}
pub fn characteristic(&self) -> CharacteristicId {
let index = self
.object_path
.rfind('/')
.expect("DescriptorId object_path must contain a slash.");
CharacteristicId::new(&self.object_path[0..index])
}
}
impl From<DescriptorId> for Path<'static> {
fn from(id: DescriptorId) -> Self {
id.object_path
}
}
impl Display for DescriptorId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
self.object_path
.to_string()
.strip_prefix("/org/bluez/")
.ok_or(fmt::Error)?
)
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DescriptorInfo {
pub id: DescriptorId,
pub uuid: Uuid,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn descriptor_characteristic() {
let characteristic_id =
CharacteristicId::new("/org/bluez/hci0/dev_11_22_33_44_55_66/service0022/char0033");
let descriptor_id = DescriptorId::new(
"/org/bluez/hci0/dev_11_22_33_44_55_66/service0022/char0033/desc0034",
);
assert_eq!(descriptor_id.characteristic(), characteristic_id);
}
#[test]
fn to_string() {
let descriptor_id = DescriptorId::new(
"/org/bluez/hci0/dev_11_22_33_44_55_66/service0022/char0033/desc0034",
);
assert_eq!(
descriptor_id.to_string(),
"hci0/dev_11_22_33_44_55_66/service0022/char0033/desc0034"
);
}
}