use core::{
fmt::{Debug, Display, Error as FmtError, Formatter},
str::FromStr,
};
use ibc_types_identifier::{
validate_channel_identifier, validate_port_identifier, IdentifierError,
};
use crate::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PortId(pub String);
impl PortId {
pub fn transfer() -> Self {
Self("transfer".to_string())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl Display for PortId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.0)
}
}
impl FromStr for PortId {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_port_identifier(s).map(|_| Self(s.to_string()))
}
}
impl AsRef<str> for PortId {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl Default for PortId {
fn default() -> Self {
"defaultPort".to_string().parse().unwrap()
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ChannelId(pub String);
impl ChannelId {
const PREFIX: &'static str = "channel-";
pub fn new(identifier: u64) -> Self {
let id = format!("{}{}", Self::PREFIX, identifier);
Self(id)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl Display for ChannelId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.0)
}
}
impl FromStr for ChannelId {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_channel_identifier(s).map(|_| Self(s.to_string()))
}
}
impl AsRef<str> for ChannelId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Default for ChannelId {
fn default() -> Self {
Self::new(0)
}
}
impl PartialEq<str> for ChannelId {
fn eq(&self, other: &str) -> bool {
self.as_str().eq(other)
}
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PortChannelId {
pub channel_id: ChannelId,
pub port_id: PortId,
}
impl Display for PortChannelId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}/{}", self.port_id, self.channel_id)
}
}