Merge pull request #24 from bluss/clone_from

impl clone_from for ArrayVec and ArrayString
This commit is contained in:
bluss
2016-02-06 20:22:40 +01:00
3 changed files with 73 additions and 0 deletions
+6
View File
@@ -225,4 +225,10 @@ impl<A: Array<Item=u8> + Copy> Clone for ArrayString<A> {
fn clone(&self) -> ArrayString<A> {
*self
}
fn clone_from(&mut self, rhs: &Self) {
// guaranteed to fit due to types matching.
self.clear();
self.push_str(rhs).ok();
}
}
+30
View File
@@ -624,6 +624,28 @@ impl<A: Array> Clone for ArrayVec<A>
fn clone(&self) -> Self {
self.iter().cloned().collect()
}
fn clone_from(&mut self, rhs: &Self) {
// recursive case for the common prefix
let prefix = cmp::min(self.len(), rhs.len());
{
let a = &mut self[..prefix];
let b = &rhs[..prefix];
for i in 0..prefix {
a[i].clone_from(&b[i]);
}
}
if prefix < self.len() {
// rhs was shorter
for _ in 0..self.len() - prefix {
self.pop();
}
} else {
for elt in &rhs[self.len()..] {
self.push(elt.clone());
}
}
}
}
impl<A: Array> Hash for ArrayVec<A>
@@ -642,6 +664,14 @@ impl<A: Array> PartialEq for ArrayVec<A>
}
}
impl<A: Array> PartialEq<[A::Item]> for ArrayVec<A>
where A::Item: PartialEq
{
fn eq(&self, other: &[A::Item]) -> bool {
**self == *other
}
}
impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq { }
impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> {
+37
View File
@@ -264,6 +264,29 @@ fn test_write() {
assert_eq!(&v[..], &[1, 2, 3, 9, 9, 9, 9, 9]);
}
#[test]
fn array_clone_from() {
let mut v = ArrayVec::<[_; 4]>::new();
v.push(vec![1, 2]);
v.push(vec![3, 4, 5]);
v.push(vec![6]);
let reference = v.to_vec();
let mut u = ArrayVec::<[_; 4]>::new();
u.clone_from(&v);
assert_eq!(&u, &reference[..]);
let mut t = ArrayVec::<[_; 4]>::new();
t.push(vec![97]);
t.push(vec![]);
t.push(vec![5, 6, 2]);
t.push(vec![2]);
t.clone_from(&v);
assert_eq!(&t, &reference[..]);
t.clear();
t.clone_from(&v);
assert_eq!(&t, &reference[..]);
}
#[test]
fn test_string() {
use std::error::Error;
@@ -295,9 +318,23 @@ fn test_string() {
Ok(())
}();
assert!(t.is_err());
}
#[test]
fn test_string_from() {
let text = "hello world";
// Test `from` constructor
let u = ArrayString::<[_; 11]>::from(text).unwrap();
assert_eq!(&u, text);
assert_eq!(u.len(), text.len());
}
#[test]
fn test_string_clone() {
let text = "hi";
let mut s = ArrayString::<[_; 4]>::new();
s.push_str("abcd").unwrap();
let t = ArrayString::<[_; 4]>::from(text).unwrap();
s.clone_from(&t);
assert_eq!(&t, &s);
}