Skip to content

Commit

Permalink
Merge pull request #119 from kamuik16/105
Browse files Browse the repository at this point in the history
chore: add starts_with in MultiAddr
  • Loading branch information
jxs authored Nov 18, 2024
2 parents 01755cc + ac29607 commit a9bd0cb
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
# 0.18.3

- Add `starts_with` on `Multiaddr`. See [PR 119].

[PR 119]: https://github.com/multiformats/rust-multiaddr/pull/119

# 0.18.2

- Implement missing protocols. See [PR 110].
Expand Down
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ keywords = ["multiaddr", "ipfs"]
license = "MIT"
name = "multiaddr"
readme = "README.md"
version = "0.18.2"
version = "0.18.3"

[features]
default = ["url"]
Expand Down
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,16 @@ impl Multiaddr {
self.bytes[(n - m)..] == other.bytes[..]
}

/// Checks whether the given `Multiaddr` is a prefix of this `Multiaddr`.
pub fn starts_with(&self, other: &Multiaddr) -> bool {
let n = self.bytes.len();
let m = other.bytes.len();
if n < m {
return false;
}
self.bytes[..m] == other.bytes[..]
}

/// Returns &str identifiers for the protocol names themselves.
/// This omits specific info like addresses, ports, peer IDs, and the like.
/// Example: `"/ip4/127.0.0.1/tcp/5001"` would return `["ip4", "tcp"]`
Expand Down
12 changes: 12 additions & 0 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ fn ends_with() {
QuickCheck::new().quickcheck(prop as fn(_))
}

#[test]
fn starts_with() {
fn prop(Ma(m): Ma) {
let n = m.iter().count();
for i in 0..n {
let prefix = m.iter().take(i + 1).collect::<Multiaddr>();
assert!(m.starts_with(&prefix));
}
}
QuickCheck::new().quickcheck(prop as fn(_))
}

// Arbitrary impls

#[derive(PartialEq, Eq, Clone, Hash, Debug)]
Expand Down

0 comments on commit a9bd0cb

Please sign in to comment.