2016-02-05 13:40:41 +01:00
|
|
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
|
|
|
|
// This file is part of Parity.
|
|
|
|
|
|
|
|
// Parity is free software: you can redistribute it and/or modify
|
|
|
|
// it under the terms of the GNU General Public License as published by
|
|
|
|
// the Free Software Foundation, either version 3 of the License, or
|
|
|
|
// (at your option) any later version.
|
|
|
|
|
|
|
|
// Parity is distributed in the hope that it will be useful,
|
|
|
|
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
// GNU General Public License for more details.
|
|
|
|
|
|
|
|
// You should have received a copy of the GNU General Public License
|
|
|
|
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2016-02-01 14:48:38 +01:00
|
|
|
//! Vector extensions.
|
2015-11-29 15:41:29 +01:00
|
|
|
|
2015-11-29 18:44:29 +01:00
|
|
|
/// Returns len of prefix shared with elem
|
2016-07-12 10:28:35 +02:00
|
|
|
///
|
2015-11-29 18:44:29 +01:00
|
|
|
/// ```rust
|
|
|
|
/// extern crate ethcore_util as util;
|
|
|
|
/// use util::vector::SharedPrefix;
|
2016-07-12 10:28:35 +02:00
|
|
|
///
|
2015-11-29 18:44:29 +01:00
|
|
|
/// fn main () {
|
|
|
|
/// let a = vec![1,2,3,3,5];
|
|
|
|
/// let b = vec![1,2,3];
|
|
|
|
/// assert_eq!(a.shared_prefix_len(&b), 3);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2016-07-12 10:28:35 +02:00
|
|
|
pub trait SharedPrefix<T> {
|
2016-02-03 16:43:48 +01:00
|
|
|
/// Get common prefix length
|
2015-11-29 18:44:29 +01:00
|
|
|
fn shared_prefix_len(&self, elem: &[T]) -> usize;
|
|
|
|
}
|
|
|
|
|
2016-07-12 10:28:35 +02:00
|
|
|
impl<T> SharedPrefix<T> for [T] where T: Eq {
|
2015-11-29 18:44:29 +01:00
|
|
|
fn shared_prefix_len(&self, elem: &[T]) -> usize {
|
|
|
|
use std::cmp;
|
|
|
|
let len = cmp::min(self.len(), elem.len());
|
|
|
|
(0..len).take_while(|&i| self[i] == elem[i]).count()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
|
|
|
use vector::SharedPrefix;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_shared_prefix() {
|
2015-11-30 00:28:03 +01:00
|
|
|
let a = vec![1,2,3,4,5,6];
|
|
|
|
let b = vec![4,2,3,4,5,6];
|
|
|
|
assert_eq!(a.shared_prefix_len(&b), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_shared_prefix2() {
|
2015-11-29 18:44:29 +01:00
|
|
|
let a = vec![1,2,3,3,5];
|
|
|
|
let b = vec![1,2,3];
|
|
|
|
assert_eq!(a.shared_prefix_len(&b), 3);
|
|
|
|
}
|
2016-07-12 10:28:35 +02:00
|
|
|
|
2015-11-30 00:28:03 +01:00
|
|
|
#[test]
|
|
|
|
fn test_shared_prefix3() {
|
|
|
|
let a = vec![1,2,3,4,5,6];
|
|
|
|
let b = vec![1,2,3,4,5,6];
|
|
|
|
assert_eq!(a.shared_prefix_len(&b), 6);
|
|
|
|
}
|
2015-11-29 15:41:29 +01:00
|
|
|
}
|