Skip to content

Commit

Permalink
impl Into<Vec<u8>> for EasyBuf (cf. tokio-rs#120)
Browse files Browse the repository at this point in the history
  • Loading branch information
manuel-woelker committed Feb 10, 2017
1 parent f86addf commit 676917e
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/io/frame.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::fmt;
use std::io;
use std::mem;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

Expand Down Expand Up @@ -209,6 +210,12 @@ impl fmt::Debug for EasyBuf {
}
}

impl Into<Vec<u8>> for EasyBuf {
fn into(mut self) -> Vec<u8> {
mem::replace(self.get_mut().buf, vec![])
}
}

/// Encoding and decoding of frames via buffers.
///
/// This trait is used when constructing an instance of `Framed`. It provides
Expand Down Expand Up @@ -464,4 +471,49 @@ mod tests {
assert_eq!(*buf.get_mut(), [3, 4, 5, 6, 7, 8]);
mem::drop(clone); // prevent unused warning
}

#[test]
fn easybuf_into_vec_simple() {
let vec: Vec<u8> = (0u8..10u8).collect();
let reference = vec.clone();
let buf: EasyBuf = vec.into();
let original_pointer = buf.buf.as_ref().as_ptr();
let result: Vec<u8> = buf.into();
assert_eq!(result, reference);
let new_pointer = result.as_ptr();
assert_eq!(original_pointer, new_pointer, "Into<Vec<u8>> should be reuse the exclusive Vec");
}

#[test]
fn easybuf_into_vec_sliced() {
let vec: Vec<u8> = (0u8..10u8).collect();
let mut buf: EasyBuf = vec.into();
let original_pointer = buf.buf.as_ref().as_ptr();
buf.split_off(9);
buf.drain_to(3);
let result: Vec<u8> = buf.into();
let reference: Vec<u8> = (3u8..9u8).collect();
assert_eq!(result, reference);
let new_pointer = result.as_ptr();
assert_eq!(original_pointer, new_pointer, "Into<Vec<u8>> should be reuse the exclusive Vec");
}

#[test]
fn easybuf_into_vec_sliced_allocating() {
let vec: Vec<u8> = (0u8..10u8).collect();
let mut buf: EasyBuf = vec.into();
let original_pointer = buf.buf.as_ref().as_ptr();
// Create a clone to create second reference to this EasyBuf and force allocation
let original = buf.clone();
buf.split_off(9);
buf.drain_to(3);
let result: Vec<u8> = buf.into();
let reference: Vec<u8> = (3u8..9u8).collect();
assert_eq!(result, reference);
let original_reference: EasyBuf =(0u8..10u8).collect::<Vec<u8>>().into();
assert_eq!(original.as_ref(), original_reference.as_ref());
let new_pointer = result.as_ptr();
assert_ne!(original_pointer, new_pointer, "A new vec should be allocated");
}

}

0 comments on commit 676917e

Please sign in to comment.