Skip to content

Commit a9bd0cb

Browse files
authored
Merge pull request #119 from kamuik16/105
chore: add starts_with in MultiAddr
2 parents 01755cc + ac29607 commit a9bd0cb

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
# 0.18.3
2+
3+
- Add `starts_with` on `Multiaddr`. See [PR 119].
4+
5+
[PR 119]: https://github.com/multiformats/rust-multiaddr/pull/119
6+
17
# 0.18.2
28

39
- Implement missing protocols. See [PR 110].

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ keywords = ["multiaddr", "ipfs"]
88
license = "MIT"
99
name = "multiaddr"
1010
readme = "README.md"
11-
version = "0.18.2"
11+
version = "0.18.3"
1212

1313
[features]
1414
default = ["url"]

src/lib.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,16 @@ impl Multiaddr {
210210
self.bytes[(n - m)..] == other.bytes[..]
211211
}
212212

213+
/// Checks whether the given `Multiaddr` is a prefix of this `Multiaddr`.
214+
pub fn starts_with(&self, other: &Multiaddr) -> bool {
215+
let n = self.bytes.len();
216+
let m = other.bytes.len();
217+
if n < m {
218+
return false;
219+
}
220+
self.bytes[..m] == other.bytes[..]
221+
}
222+
213223
/// Returns &str identifiers for the protocol names themselves.
214224
/// This omits specific info like addresses, ports, peer IDs, and the like.
215225
/// Example: `"/ip4/127.0.0.1/tcp/5001"` would return `["ip4", "tcp"]`

tests/lib.rs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,18 @@ fn ends_with() {
6868
QuickCheck::new().quickcheck(prop as fn(_))
6969
}
7070

71+
#[test]
72+
fn starts_with() {
73+
fn prop(Ma(m): Ma) {
74+
let n = m.iter().count();
75+
for i in 0..n {
76+
let prefix = m.iter().take(i + 1).collect::<Multiaddr>();
77+
assert!(m.starts_with(&prefix));
78+
}
79+
}
80+
QuickCheck::new().quickcheck(prop as fn(_))
81+
}
82+
7183
// Arbitrary impls
7284

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

0 commit comments

Comments
 (0)