mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-23 00:00:10 +02:00
impl Into<Vec<u8>> for EasyBuf (cf. #120)
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use std::mem;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -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
|
||||
@@ -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 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 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");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user