-
-
Notifications
You must be signed in to change notification settings - Fork 97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add addr
module
#430
Closed
Closed
Add addr
module
#430
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
81d15bc
⬆️ Bump MSRV to 1.65
elmarco 78a3f97
🚨 zb: use or_default(), as suggested by clippy
elmarco 9c593b6
♻️ zb: export some win32 types
elmarco 241e884
🎉 zb: add `addr` module
elmarco af500ad
♻️ zb: add/rewrite raw stream connection
elmarco 63a1c9e
♻️ zb: use `addr`
elmarco 1f79b4f
🗑️ zb: deprecate Address
elmarco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,219 @@ | ||
use std::{borrow::Cow, collections::HashSet, fmt}; | ||
|
||
use crate::{Error, Guid, Result}; | ||
|
||
use super::{ | ||
percent::{decode_percents, decode_percents_str, Encodable}, | ||
transport::Transport, | ||
}; | ||
|
||
/// A bus address. | ||
#[derive(Debug, PartialEq, Eq, Clone)] | ||
pub struct DBusAddr<'a> { | ||
pub(super) addr: Cow<'a, str>, | ||
} | ||
|
||
impl<'a> DBusAddr<'a> { | ||
/// The connection UUID (guid=) if any. | ||
pub fn guid(&self) -> Option<Result<Guid>> { | ||
match self.get_string("guid") { | ||
Some(Ok(v)) => Some(Guid::try_from(v.as_ref())), | ||
Some(Err(e)) => Some(Err(e)), | ||
_ => None, | ||
} | ||
} | ||
|
||
/// Transport connection details | ||
pub fn transport(&self) -> Result<Transport<'_>> { | ||
self.try_into() | ||
} | ||
|
||
fn validate(&self) -> Result<()> { | ||
self.transport()?; | ||
let mut set = HashSet::new(); | ||
for (k, v) in self.key_val_iter() { | ||
if !set.insert(k) { | ||
return Err(Error::Address(format!("Duplicate key `{k}`"))); | ||
} | ||
if let Some(v) = v { | ||
decode_percents(v)?; | ||
} | ||
} | ||
Ok(()) | ||
} | ||
|
||
fn new<A: Into<Cow<'a, str>>>(addr: A) -> Result<Self> { | ||
let addr = addr.into(); | ||
let addr = Self { addr }; | ||
|
||
addr.validate()?; | ||
Ok(addr) | ||
} | ||
|
||
pub(super) fn key_val_iter(&'a self) -> KeyValIter<'a> { | ||
let mut split = self.addr.splitn(2, ':'); | ||
// skip transport:.. | ||
split.next(); | ||
let kv = split.next().unwrap_or(""); | ||
KeyValIter::new(kv) | ||
} | ||
|
||
fn get_string(&'a self, key: &str) -> Option<Result<Cow<'a, str>>> { | ||
for (k, v) in self.key_val_iter() { | ||
if key == k { | ||
return v.map(decode_percents_str); | ||
} | ||
} | ||
None | ||
} | ||
} | ||
|
||
impl DBusAddr<'_> { | ||
pub(crate) fn to_owned(&self) -> DBusAddr<'static> { | ||
let addr = self.addr.to_string(); | ||
DBusAddr { addr: addr.into() } | ||
} | ||
} | ||
|
||
impl<'a> TryFrom<String> for DBusAddr<'a> { | ||
type Error = Error; | ||
|
||
fn try_from(addr: String) -> Result<Self> { | ||
Self::new(addr) | ||
} | ||
} | ||
|
||
impl<'a> TryFrom<&'a str> for DBusAddr<'a> { | ||
type Error = Error; | ||
|
||
fn try_from(addr: &'a str) -> Result<Self> { | ||
Self::new(addr) | ||
} | ||
} | ||
|
||
impl fmt::Display for DBusAddr<'_> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
let kv = KeyValFmt::new().add("guid", self.guid().and_then(|v| v.ok())); | ||
let t = self.transport().map_err(|_| fmt::Error)?; | ||
let kv = t.key_val_fmt_add(kv); | ||
write!(f, "{t}:{kv}")?; | ||
Ok(()) | ||
} | ||
} | ||
|
||
pub(super) struct KeyValIter<'a> { | ||
data: &'a str, | ||
next_index: usize, | ||
} | ||
|
||
impl<'a> KeyValIter<'a> { | ||
fn new(data: &'a str) -> Self { | ||
KeyValIter { | ||
data, | ||
next_index: 0, | ||
} | ||
} | ||
} | ||
|
||
impl<'a> Iterator for KeyValIter<'a> { | ||
type Item = (&'a str, Option<&'a str>); | ||
|
||
fn next(&mut self) -> Option<Self::Item> { | ||
if self.next_index >= self.data.len() { | ||
return None; | ||
} | ||
|
||
let mut pair = &self.data[self.next_index..]; | ||
if let Some(end) = pair.find(',') { | ||
pair = &pair[..end]; | ||
self.next_index += end + 1; | ||
} else { | ||
self.next_index = self.data.len(); | ||
} | ||
let mut split = pair.split('='); | ||
// SAFETY: first split always returns something | ||
let key = split.next().unwrap(); | ||
Some((key, split.next())) | ||
} | ||
} | ||
|
||
pub(crate) trait KeyValFmtAdd { | ||
fn key_val_fmt_add<'a: 'b, 'b>(&'a self, kv: KeyValFmt<'b>) -> KeyValFmt<'b>; | ||
} | ||
|
||
pub(crate) struct KeyValFmt<'a> { | ||
fields: Vec<(Box<dyn fmt::Display + 'a>, Box<dyn Encodable + 'a>)>, | ||
} | ||
|
||
impl<'a> KeyValFmt<'a> { | ||
fn new() -> Self { | ||
Self { fields: vec![] } | ||
} | ||
|
||
pub(crate) fn add<K, V>(mut self, key: K, val: Option<V>) -> Self | ||
where | ||
K: fmt::Display + 'a, | ||
V: Encodable + 'a, | ||
{ | ||
if let Some(val) = val { | ||
self.fields.push((Box::new(key), Box::new(val))); | ||
} | ||
self | ||
} | ||
} | ||
|
||
impl fmt::Display for KeyValFmt<'_> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
let mut first = true; | ||
for (k, v) in self.fields.iter() { | ||
if !first { | ||
write!(f, ",")?; | ||
} | ||
write!(f, "{k}=")?; | ||
v.encode(f)?; | ||
first = false; | ||
} | ||
Ok(()) | ||
} | ||
} | ||
|
||
/// A trait for objects which can be converted or resolved to one or more [`DBusAddr`] values. | ||
pub trait ToDBusAddrs<'a> { | ||
type Iter: Iterator<Item = Result<DBusAddr<'a>>>; | ||
|
||
fn to_dbus_addrs(&'a self) -> Self::Iter; | ||
} | ||
|
||
impl<'a> ToDBusAddrs<'a> for DBusAddr<'a> { | ||
type Iter = std::iter::Once<Result<DBusAddr<'a>>>; | ||
|
||
/// Get an iterator over the D-Bus addresses. | ||
fn to_dbus_addrs(&'a self) -> Self::Iter { | ||
std::iter::once(Ok(self.clone())) | ||
} | ||
} | ||
|
||
impl<'a> ToDBusAddrs<'a> for str { | ||
type Iter = std::iter::Once<Result<DBusAddr<'a>>>; | ||
|
||
fn to_dbus_addrs(&'a self) -> Self::Iter { | ||
std::iter::once(self.try_into()) | ||
} | ||
} | ||
|
||
impl<'a> ToDBusAddrs<'a> for String { | ||
type Iter = std::iter::Once<Result<DBusAddr<'a>>>; | ||
|
||
fn to_dbus_addrs(&'a self) -> Self::Iter { | ||
std::iter::once(self.as_str().try_into()) | ||
} | ||
} | ||
|
||
impl<'a> ToDBusAddrs<'a> for Vec<Result<DBusAddr<'_>>> { | ||
type Iter = std::iter::Cloned<std::slice::Iter<'a, Result<DBusAddr<'a>>>>; | ||
|
||
/// Get an iterator over the D-Bus addresses. | ||
fn to_dbus_addrs(&'a self) -> Self::Iter { | ||
self.iter().cloned() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
use std::{borrow::Cow, fmt}; | ||
|
||
use crate::{Error, Result}; | ||
|
||
use super::{DBusAddr, ToDBusAddrs}; | ||
|
||
/// A bus address list. | ||
/// | ||
/// D-Bus addresses are `;`-separated. | ||
#[derive(Debug, PartialEq, Eq, Clone)] | ||
pub struct DBusAddrList<'a> { | ||
addr: Cow<'a, str>, | ||
} | ||
|
||
impl<'a> ToDBusAddrs<'a> for DBusAddrList<'a> { | ||
type Iter = DBusAddrListIter<'a>; | ||
|
||
/// Get an iterator over the D-Bus addresses. | ||
fn to_dbus_addrs(&'a self) -> Self::Iter { | ||
DBusAddrListIter::new(self) | ||
} | ||
} | ||
|
||
impl<'a> Iterator for DBusAddrListIter<'a> { | ||
type Item = Result<DBusAddr<'a>>; | ||
|
||
fn next(&mut self) -> Option<Self::Item> { | ||
if self.next_index >= self.data.len() { | ||
return None; | ||
} | ||
|
||
let mut addr = &self.data[self.next_index..]; | ||
if let Some(end) = addr.find(';') { | ||
addr = &addr[..end]; | ||
self.next_index += end + 1; | ||
} else { | ||
self.next_index = self.data.len(); | ||
} | ||
Some(DBusAddr::try_from(addr)) | ||
} | ||
} | ||
|
||
/// An iterator of D-Bus addresses. | ||
pub struct DBusAddrListIter<'a> { | ||
data: &'a str, | ||
next_index: usize, | ||
} | ||
|
||
impl<'a> DBusAddrListIter<'a> { | ||
fn new(list: &'a DBusAddrList<'_>) -> Self { | ||
Self { | ||
data: list.addr.as_ref(), | ||
next_index: 0, | ||
} | ||
} | ||
} | ||
|
||
impl<'a> TryFrom<String> for DBusAddrList<'a> { | ||
type Error = Error; | ||
|
||
fn try_from(value: String) -> Result<Self> { | ||
Ok(Self { | ||
addr: Cow::Owned(value), | ||
}) | ||
} | ||
} | ||
|
||
impl<'a> TryFrom<&'a str> for DBusAddrList<'a> { | ||
type Error = Error; | ||
|
||
fn try_from(value: &'a str) -> Result<Self> { | ||
Ok(Self { | ||
addr: Cow::Borrowed(value), | ||
}) | ||
} | ||
} | ||
|
||
impl fmt::Display for DBusAddrList<'_> { | ||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
write!(f, "{}", self.addr) | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
DBus
prefix? It's part of zbus so it's clear what address we mean.Address
etc.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
No relationship, it's a rewrite from scratch.
I use DBus prefix, and Addr, for consistency with rust standard library. Everything address-related uses
addr
consistently, and for types, has a prefix. IpAddr, SocketAddr etc. Address (or Addr) would be too common, and would likely conflict with other modules/crates and require a rename.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
std lib's context is super generic. That is not the case for zbus.
As discussed before, the mod hierarchy in Rust makes this a complete non-issue. Users can either import only the parent (or its parent mod) or alias during import. They also can choose not to use imports at all and use the full path.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sigh naming... I have a clear preference for DBusAddr, ToDBusAddr.. over Address, ToAddress. But if you insist, I'll just rename stuff.