Skip to content

Commit 9ae51c9

Browse files
stepanchegcarllerche
authored andcommitted
Implement truncate, clear for Bytes (#128)
1 parent 2b0602e commit 9ae51c9

File tree

1 file changed

+46
-3
lines changed

1 file changed

+46
-3
lines changed

src/bytes.rs

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,45 @@ impl Bytes {
618618
self.split_to(at)
619619
}
620620

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+
621660
/// Attempt to convert into a `BytesMut` handle.
622661
///
623662
/// This will only succeed if there are no other outstanding references to
@@ -1133,9 +1172,7 @@ impl BytesMut {
11331172
///
11341173
/// [`split_off`]: #method.split_off
11351174
pub fn truncate(&mut self, len: usize) {
1136-
if len <= self.len() {
1137-
unsafe { self.set_len(len); }
1138-
}
1175+
self.inner.truncate(len);
11391176
}
11401177

11411178
/// Clears the buffer, removing all data.
@@ -1709,6 +1746,12 @@ impl Inner {
17091746
return other
17101747
}
17111748

1749+
fn truncate(&mut self, len: usize) {
1750+
if len <= self.len() {
1751+
unsafe { self.set_len(len); }
1752+
}
1753+
}
1754+
17121755
unsafe fn set_start(&mut self, start: usize) {
17131756
// This function should never be called when the buffer is still backed
17141757
// by a `Vec<u8>`

0 commit comments

Comments
 (0)