Skip to content

Commit

Permalink
Moved ClientId::suffix() into cosmos.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
adizere committed May 28, 2021
1 parent 0efdcab commit ad9ddf3
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 23 deletions.
20 changes: 0 additions & 20 deletions modules/src/ics24_host/identifier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,26 +179,6 @@ impl ClientId {
pub fn as_bytes(&self) -> &[u8] {
&self.0.as_bytes()
}

/// Returns the suffix counter of this client.
/// Returns `None` if the client identifier is malformed
/// and the suffix could not be parsed.
/// ```rust
/// # use ibc::ics24_host::identifier::ClientId;
/// # use ibc::ics02_client::client_type::ClientType;
/// # use std::str::FromStr;
/// let cl_a = ClientId::new(ClientType::Mock, 670).unwrap();
/// assert_eq!(cl_a.suffix(), Some(670));
/// let cl_b = ClientId::from_str("nosuffix_client").unwrap();
/// assert_eq!(cl_b.suffix(), None);
/// ```
pub fn suffix(&self) -> Option<u64> {
self.as_str()
.split('-')
.last()
.map(|e| e.parse::<u64>().ok())
.flatten()
}
}

/// This implementation provides a `to_string` method.
Expand Down
17 changes: 14 additions & 3 deletions relayer/src/chain/cosmos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,10 +511,9 @@ impl Chain for CosmosSdkChain {

// Sort by client identifier counter
clients.sort_by(|a, b| {

This comment has been minimized.

Copy link
@romac

romac Jun 1, 2021

Member

Two nitpicks:

a) We should probably use sort_by_cached_key here to avoid recomputing the suffix on every comparison
b) This could be rewritten in a slightly simpler way using sort_by_{cached_}key:

clients.sort_by_cached_key(|c| client_id_suffix(&c.client_id).unwrap_or(0))
a.client_id
.suffix()
client_id_suffix(&a.client_id)
.unwrap_or(0) // Fallback to `0` suffix (no sorting) if client id is malformed
.cmp(&b.client_id.suffix().unwrap_or(0))
.cmp(&client_id_suffix(&b.client_id).unwrap_or(0))
});

Ok(clients)
Expand Down Expand Up @@ -1505,3 +1504,15 @@ fn encode_to_bech32(address: &str, account_prefix: &str) -> Result<String, Error

Ok(encoded)
}

/// Returns the suffix counter for a CosmosSDK client id.
/// Returns `None` if the client identifier is malformed
/// and the suffix could not be parsed.
pub fn client_id_suffix(client_id: &ClientId) -> Option<u64> {
client_id
.as_str()
.split('-')
.last()
.map(|e| e.parse::<u64>().ok())
.flatten()
}

0 comments on commit ad9ddf3

Please sign in to comment.