@@ -795,20 +795,28 @@ pub trait Buf {
795795 f64:: from_bits ( Self :: get_u64_le ( self ) )
796796 }
797797
798- /// Consumes remaining bytes inside self and returns new instance of `Bytes`
798+ /// Consumes `len` bytes inside self and returns new instance of `Bytes`
799+ /// with this data.
800+ ///
801+ /// This function may be optimized by the underlying type to avoid actual
802+ /// copies. For example, `Bytes` implementation will do a shallow copy
803+ /// (ref-count increment).
799804 ///
800805 /// # Examples
801806 ///
802807 /// ```
803808 /// use bytes::Buf;
804809 ///
805- /// let bytes = (&b"hello world"[..]).to_bytes( );
806- /// assert_eq!(&bytes[..], &b"hello world "[..]);
810+ /// let bytes = (&b"hello world"[..]).copy_to_bytes(5 );
811+ /// assert_eq!(&bytes[..], &b"hello"[..]);
807812 /// ```
808- fn to_bytes ( & mut self ) -> crate :: Bytes {
813+ fn copy_to_bytes ( & mut self , len : usize ) -> crate :: Bytes {
809814 use super :: BufMut ;
810- let mut ret = crate :: BytesMut :: with_capacity ( self . remaining ( ) ) ;
811- ret. put ( self ) ;
815+
816+ assert ! ( len <= self . remaining( ) , "`len` greater than remaining" ) ;
817+
818+ let mut ret = crate :: BytesMut :: with_capacity ( len) ;
819+ ret. put ( self . take ( len) ) ;
812820 ret. freeze ( )
813821 }
814822
@@ -852,7 +860,7 @@ pub trait Buf {
852860 ///
853861 /// let mut chain = b"hello "[..].chain(&b"world"[..]);
854862 ///
855- /// let full = chain.to_bytes( );
863+ /// let full = chain.copy_to_bytes(11 );
856864 /// assert_eq!(full.bytes(), b"hello world");
857865 /// ```
858866 fn chain < U : Buf > ( self , next : U ) -> Chain < Self , U >
@@ -993,8 +1001,8 @@ macro_rules! deref_forward_buf {
9931001 ( * * self ) . get_int_le( nbytes)
9941002 }
9951003
996- fn to_bytes ( & mut self ) -> crate :: Bytes {
997- ( * * self ) . to_bytes ( )
1004+ fn copy_to_bytes ( & mut self , len : usize ) -> crate :: Bytes {
1005+ ( * * self ) . copy_to_bytes ( len )
9981006 }
9991007 } ;
10001008}
0 commit comments