Skip to content
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

SLabel methods for unprefixed strings #56

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions protocol/src/slabel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,32 @@ impl<'a> TryFrom<&'a [u8]> for SLabelRef<'a> {
}
}

impl SLabel {
pub fn as_str_unprefixed(&self) -> Result<&str, core::str::Utf8Error> {
let label_len = self.0[0] as usize;
let label = &self.0[1..=label_len];
core::str::from_utf8(label)
}

pub fn to_string_unprefixed(&self) -> Result<String, core::str::Utf8Error> {
self.as_str_unprefixed().map(|s| s.to_string())
}

pub fn from_str_unprefixed(label: &str) -> Result<Self, Error> {
if label.is_empty() {
return Err(Error::Name(NameErrorKind::ZeroLength));
}
if label.len() > MAX_LABEL_LEN {
return Err(Error::Name(NameErrorKind::TooLong));
}
let mut label_bytes = [0; MAX_LABEL_LEN + 1];
label_bytes[0] = label.len() as u8;
label_bytes[1..=label.len()].copy_from_slice(label.as_bytes());

SLabel::try_from(label_bytes.as_slice())
}
}

impl TryFrom<String> for SLabel {
type Error = Error;

Expand All @@ -204,26 +230,13 @@ impl TryFrom<&str> for SLabel {
return Err(Error::Name(NameErrorKind::NotCanonical));
}
let label = &value[1..];
if label.is_empty() {
return Err(Error::Name(NameErrorKind::ZeroLength));
}
if label.len() > MAX_LABEL_LEN {
return Err(Error::Name(NameErrorKind::TooLong));
}
let mut label_bytes = [0; MAX_LABEL_LEN + 1];
label_bytes[0] = label.len() as u8;
label_bytes[1..=label.len()].copy_from_slice(label.as_bytes());

SLabel::try_from(label_bytes.as_slice())
Self::from_str_unprefixed(label)
}
}

impl Display for SLabel {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
let label_len = self.0[0] as usize;
let label = &self.0[1..=label_len];

let label_str = core::str::from_utf8(label).map_err(|_| core::fmt::Error)?;
let label_str = self.as_str_unprefixed().map_err(|_| core::fmt::Error)?;
write!(f, "@{}", label_str)
}
}
Expand Down
Loading