Merge pull request #19 from bluss/dispose-and-more

Dispose and more
This commit is contained in:
bluss
2016-01-13 13:07:42 +01:00
4 changed files with 34 additions and 6 deletions
+1
View File
@@ -2,6 +2,7 @@ language: rust
sudo: false
matrix:
include:
- rust: 1.2.0
- rust: stable
- rust: beta
- rust: nightly
+14 -2
View File
@@ -1,7 +1,8 @@
use std::borrow::Borrow;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::str;
use std::slice;
@@ -99,7 +100,7 @@ impl<A: Array<Item=u8>> ArrayString<A> {
pub fn push_str<'a>(&mut self, s: &'a str) -> Result<(), CapacityError<&'a str>> {
use std::io::Write;
if self.len() + s.len() > self.capacity() {
if s.len() > self.capacity() - self.len() {
return Err(CapacityError::new(s));
}
unsafe {
@@ -142,6 +143,17 @@ impl<A: Array<Item=u8>> Deref for ArrayString<A> {
}
}
impl<A: Array<Item=u8>> DerefMut for ArrayString<A> {
#[inline]
fn deref_mut(&mut self) -> &mut str {
unsafe {
let sl = slice::from_raw_parts_mut(self.xs.as_mut_ptr(), self.len.to_usize());
// FIXME: Nothing but transmute to do this right now
mem::transmute(sl)
}
}
}
impl<A: Array<Item=u8>> PartialEq for ArrayString<A> {
fn eq(&self, rhs: &Self) -> bool {
**self == **rhs
+13 -4
View File
@@ -57,9 +57,7 @@ pub struct ArrayVec<A: Array> {
impl<A: Array> Drop for ArrayVec<A> {
fn drop(&mut self) {
// clear all elements
while let Some(_) = self.pop() {
}
self.clear();
// NoDrop inhibits array's drop
// panic safety: NoDrop::drop will trigger on panic, so the inner
@@ -340,6 +338,12 @@ impl<A: Array> ArrayVec<A> {
}
}
}
/// Dispose of `self` without the overwriting that is needed in Drop.
pub fn dispose(mut self) {
self.clear();
mem::forget(self);
}
}
impl<A: Array> Deref for ArrayVec<A> {
@@ -701,7 +705,7 @@ impl<A: Array<Item=u8>> io::Write for ArrayVec<A> {
/// Error value indicating insufficient capacity
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
pub struct CapacityError<T> {
pub struct CapacityError<T = ()> {
element: T,
}
@@ -716,6 +720,11 @@ impl<T> CapacityError<T> {
pub fn element(self) -> T {
self.element
}
/// Convert into a `CapacityError` that does not carry an element.
pub fn simplify(self) -> CapacityError {
CapacityError { element: () }
}
}
const CAPERROR: &'static str = "insufficient capacity";
+6
View File
@@ -283,6 +283,12 @@ fn test_string() {
assert!(t.push_str(text).is_err());
assert_eq!(&t, "");
t.push_str("ab").unwrap();
// DerefMut
let tmut: &mut str = &mut t;
assert_eq!(tmut, "ab");
// Test Error trait / try
let t = || -> Result<(), Box<Error>> {
let mut t = ArrayString::<[_; 2]>::new();