@@ -172,6 +172,19 @@ impl<A: Array> ArrayVec<A> {
172
172
/// ```
173
173
pub fn is_full ( & self ) -> bool { self . len ( ) == self . capacity ( ) }
174
174
175
+ /// Returns the capacity left in the `ArrayVec`.
176
+ ///
177
+ /// ```
178
+ /// use arrayvec::ArrayVec;
179
+ ///
180
+ /// let mut array = ArrayVec::from([1, 2, 3]);
181
+ /// array.pop();
182
+ /// assert_eq!(array.capacity_left(), 1);
183
+ /// ```
184
+ pub fn capacity_left ( & self ) -> usize {
185
+ self . capacity ( ) - self . len ( )
186
+ }
187
+
175
188
/// Push `element` to the end of the vector.
176
189
///
177
190
/// ***Panics*** if the vector is already full.
@@ -523,6 +536,39 @@ impl<A: Array> ArrayVec<A> {
523
536
self . len = Index :: from ( length) ;
524
537
}
525
538
539
+ /// Copy and appends all elements in a slice to the `ArrayVec`.
540
+ ///
541
+ /// ```
542
+ /// use arrayvec::ArrayVec;
543
+ ///
544
+ /// let mut vec: ArrayVec<[usize; 10]> = ArrayVec::new();
545
+ /// vec.push(1);
546
+ /// vec.extend_from_slice(&[2, 3]);
547
+ /// assert_eq!(&vec[..], &[1, 2, 3]);
548
+ /// ```
549
+ ///
550
+ /// # Panics
551
+ ///
552
+ /// This method will panic if the capacity left (see [`capacity_left`]) is
553
+ /// smaller then the length of the provided slice.
554
+ ///
555
+ /// [`capacity_left`]: #method.capacity_left
556
+ pub fn extend_from_slice ( & mut self , other : & [ A :: Item ] )
557
+ where A :: Item : Copy ,
558
+ {
559
+ if self . capacity_left ( ) < other. len ( ) {
560
+ panic ! ( "ArrayVec::extend_from_slice: slice is larger then capacity left" ) ;
561
+ }
562
+
563
+ let self_len = self . len ( ) ;
564
+ let other_len = other. len ( ) ;
565
+
566
+ unsafe {
567
+ let dst = self . xs . as_mut_ptr ( ) . offset ( self_len as isize ) ;
568
+ ptr:: copy_nonoverlapping ( other. as_ptr ( ) , dst, other_len) ;
569
+ self . set_len ( self_len + other_len) ;
570
+ }
571
+ }
526
572
527
573
/// Create a draining iterator that removes the specified range in the vector
528
574
/// and yields the removed items from start to end. The element range is
@@ -1033,16 +1079,9 @@ impl<A: Array> Ord for ArrayVec<A> where A::Item: Ord {
1033
1079
/// Requires `features="std"`.
1034
1080
impl < A : Array < Item =u8 > > io:: Write for ArrayVec < A > {
1035
1081
fn write ( & mut self , data : & [ u8 ] ) -> io:: Result < usize > {
1036
- unsafe {
1037
- let len = self . len ( ) ;
1038
- let mut tail = slice:: from_raw_parts_mut ( self . get_unchecked_mut ( len) ,
1039
- A :: capacity ( ) - len) ;
1040
- let result = tail. write ( data) ;
1041
- if let Ok ( written) = result {
1042
- self . set_len ( len + written) ;
1043
- }
1044
- result
1045
- }
1082
+ let len = cmp:: min ( self . capacity_left ( ) , data. len ( ) ) ;
1083
+ self . extend_from_slice ( & data[ ..len] ) ;
1084
+ Ok ( len)
1046
1085
}
1047
1086
fn flush ( & mut self ) -> io:: Result < ( ) > { Ok ( ( ) ) }
1048
1087
}
0 commit comments