diff --git a/CHANGELOG.md b/CHANGELOG.md index c867cc2..d4d8f50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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]. diff --git a/Cargo.toml b/Cargo.toml index 1c7dd96..dc6ae2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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"] diff --git a/src/lib.rs b/src/lib.rs index df596a5..9ad6c6d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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"]` diff --git a/tests/lib.rs b/tests/lib.rs index 9248eb5..936809e 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -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::(); + assert!(m.starts_with(&prefix)); + } + } + QuickCheck::new().quickcheck(prop as fn(_)) +} + // Arbitrary impls #[derive(PartialEq, Eq, Clone, Hash, Debug)]