@@ -618,6 +618,45 @@ impl Bytes {
618
618
self . split_to ( at)
619
619
}
620
620
621
+ /// Shortens the buffer, keeping the first `len` bytes and dropping the
622
+ /// rest.
623
+ ///
624
+ /// If `len` is greater than the buffer's current length, this has no
625
+ /// effect.
626
+ ///
627
+ /// The [`split_off`] method can emulate `truncate`, but this causes the
628
+ /// excess bytes to be returned instead of dropped.
629
+ ///
630
+ /// # Examples
631
+ ///
632
+ /// ```
633
+ /// use bytes::Bytes;
634
+ ///
635
+ /// let mut buf = Bytes::from(&b"hello world"[..]);
636
+ /// buf.truncate(5);
637
+ /// assert_eq!(buf, b"hello"[..]);
638
+ /// ```
639
+ ///
640
+ /// [`split_off`]: #method.split_off
641
+ pub fn truncate ( & mut self , len : usize ) {
642
+ self . inner . truncate ( len) ;
643
+ }
644
+
645
+ /// Clears the buffer, removing all data.
646
+ ///
647
+ /// # Examples
648
+ ///
649
+ /// ```
650
+ /// use bytes::Bytes;
651
+ ///
652
+ /// let mut buf = Bytes::from(&b"hello world"[..]);
653
+ /// buf.clear();
654
+ /// assert!(buf.is_empty());
655
+ /// ```
656
+ pub fn clear ( & mut self ) {
657
+ self . truncate ( 0 ) ;
658
+ }
659
+
621
660
/// Attempt to convert into a `BytesMut` handle.
622
661
///
623
662
/// This will only succeed if there are no other outstanding references to
@@ -1133,9 +1172,7 @@ impl BytesMut {
1133
1172
///
1134
1173
/// [`split_off`]: #method.split_off
1135
1174
pub fn truncate ( & mut self , len : usize ) {
1136
- if len <= self . len ( ) {
1137
- unsafe { self . set_len ( len) ; }
1138
- }
1175
+ self . inner . truncate ( len) ;
1139
1176
}
1140
1177
1141
1178
/// Clears the buffer, removing all data.
@@ -1709,6 +1746,12 @@ impl Inner {
1709
1746
return other
1710
1747
}
1711
1748
1749
+ fn truncate ( & mut self , len : usize ) {
1750
+ if len <= self . len ( ) {
1751
+ unsafe { self . set_len ( len) ; }
1752
+ }
1753
+ }
1754
+
1712
1755
unsafe fn set_start ( & mut self , start : usize ) {
1713
1756
// This function should never be called when the buffer is still backed
1714
1757
// by a `Vec<u8>`
0 commit comments