ntex_bytes/bytesmut.rs
1use std::{borrow, fmt, ops, ptr};
2
3use crate::{Buf, BufMut, Bytes, buf::IntoIter, buf::UninitSlice, debug, storage::Storage};
4
5/// A unique reference to a contiguous slice of memory.
6///
7/// `BytesMut` represents a unique view into a potentially shared memory region.
8/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
9/// mutate the memory. It is similar to a `Vec<u8>` but with less copies and
10/// allocations.
11///
12/// For more detail, see [Bytes](struct.Bytes.html).
13///
14/// # Growth
15///
16/// One key difference from `Vec<u8>` is that most operations **do not
17/// implicitly grow the buffer**. This means that calling `my_bytes.put("hello
18/// world");` could panic if `my_bytes` does not have enough capacity. Before
19/// writing to the buffer, ensure that there is enough remaining capacity by
20/// calling `my_bytes.remaining_mut()`. In general, avoiding calls to `reserve`
21/// is preferable.
22///
23/// The only exception is `extend` which implicitly reserves required capacity.
24///
25/// # Examples
26///
27/// ```
28/// use ntex_bytes::{BytesMut, BufMut};
29///
30/// let mut buf = BytesMut::with_capacity(64);
31///
32/// buf.put_u8(b'h');
33/// buf.put_u8(b'e');
34/// buf.put("llo");
35///
36/// assert_eq!(buf, b"hello");
37///
38/// // Freeze the buffer so that it can be shared
39/// let a = buf.freeze();
40///
41/// // This does not allocate, instead `b` points to the same memory.
42/// let b = a.clone();
43///
44/// assert_eq!(a, b"hello");
45/// assert_eq!(b, b"hello");
46/// ```
47pub struct BytesMut {
48 pub(crate) storage: Storage,
49}
50
51/*
52 *
53 * ===== BytesMut =====
54 *
55 */
56
57impl BytesMut {
58 /// Creates a new `BytesMut` with the specified capacity.
59 ///
60 /// The returned `BytesMut` will be able to hold at least `capacity` bytes
61 /// without reallocating. If `capacity` is under `4 * size_of::<usize>() - 1`,
62 /// then `BytesMut` will not allocate.
63 ///
64 /// It is important to note that this function does not specify the length
65 /// of the returned `BytesMut`, but only the capacity.
66 ///
67 /// # Panics
68 ///
69 /// Panics if `capacity` greater than 60bit for 64bit systems
70 /// and 28bit for 32bit systems
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// use ntex_bytes::{BytesMut, BufMut};
76 ///
77 /// let mut bytes = BytesMut::with_capacity(64);
78 ///
79 /// // `bytes` contains no data, even though there is capacity
80 /// assert_eq!(bytes.len(), 0);
81 ///
82 /// bytes.put(&b"hello world"[..]);
83 ///
84 /// assert_eq!(&bytes[..], b"hello world");
85 /// ```
86 #[inline]
87 pub fn with_capacity(capacity: usize) -> BytesMut {
88 BytesMut {
89 storage: Storage::with_capacity(capacity),
90 }
91 }
92
93 /// Creates a new `BytesMut` from slice, by copying it.
94 pub fn copy_from_slice<T: AsRef<[u8]>>(src: T) -> Self {
95 BytesMut {
96 storage: Storage::from_slice(src.as_ref()),
97 }
98 }
99
100 #[inline]
101 /// Convert a `Vec` into a `BytesMut`
102 pub fn from_vec(src: Vec<u8>) -> BytesMut {
103 BytesMut {
104 storage: Storage::from_vec(src),
105 }
106 }
107
108 /// Creates a new `BytesMut` with default capacity.
109 ///
110 /// Resulting object has length 0 and unspecified capacity.
111 /// This function does not allocate.
112 ///
113 /// # Examples
114 ///
115 /// ```
116 /// use ntex_bytes::{BytesMut, BufMut};
117 ///
118 /// let mut bytes = BytesMut::new();
119 ///
120 /// assert_eq!(0, bytes.len());
121 ///
122 /// bytes.reserve(2);
123 /// bytes.put_slice(b"xy");
124 ///
125 /// assert_eq!(&b"xy"[..], &bytes[..]);
126 /// ```
127 #[inline]
128 pub fn new() -> BytesMut {
129 BytesMut {
130 storage: Storage::empty_inline(),
131 }
132 }
133
134 /// Returns the number of bytes contained in this `BytesMut`.
135 ///
136 /// # Examples
137 ///
138 /// ```
139 /// use ntex_bytes::BytesMut;
140 ///
141 /// let b = BytesMut::from(&b"hello"[..]);
142 /// assert_eq!(b.len(), 5);
143 /// ```
144 #[inline]
145 pub fn len(&self) -> usize {
146 self.storage.len()
147 }
148
149 /// Returns true if the `BytesMut` has a length of 0.
150 ///
151 /// # Examples
152 ///
153 /// ```
154 /// use ntex_bytes::BytesMut;
155 ///
156 /// let b = BytesMut::with_capacity(64);
157 /// assert!(b.is_empty());
158 /// ```
159 #[inline]
160 pub fn is_empty(&self) -> bool {
161 self.storage.is_empty()
162 }
163
164 /// Returns the number of bytes the `BytesMut` can hold without reallocating.
165 ///
166 /// # Examples
167 ///
168 /// ```
169 /// use ntex_bytes::BytesMut;
170 ///
171 /// let b = BytesMut::with_capacity(64);
172 /// assert_eq!(b.capacity(), 64);
173 /// ```
174 #[inline]
175 pub fn capacity(&self) -> usize {
176 self.storage.capacity()
177 }
178
179 /// Converts `self` into an immutable `Bytes`.
180 ///
181 /// The conversion is zero cost and is used to indicate that the slice
182 /// referenced by the handle will no longer be mutated. Once the conversion
183 /// is done, the handle can be cloned and shared across threads.
184 ///
185 /// # Examples
186 ///
187 /// ```
188 /// use ntex_bytes::{BytesMut, BufMut};
189 /// use std::thread;
190 ///
191 /// let mut b = BytesMut::with_capacity(64);
192 /// b.put("hello world");
193 /// let b1 = b.freeze();
194 /// let b2 = b1.clone();
195 ///
196 /// let th = thread::spawn(move || {
197 /// assert_eq!(b1, b"hello world");
198 /// });
199 ///
200 /// assert_eq!(b2, b"hello world");
201 /// th.join().unwrap();
202 /// ```
203 #[inline]
204 pub fn freeze(self) -> Bytes {
205 Bytes {
206 storage: self.storage.freeze(),
207 }
208 }
209
210 /// Removes the bytes from the current view, returning them in a new
211 /// `BytesMut` handle.
212 ///
213 /// Afterwards, `self` will be empty, but will retain any additional
214 /// capacity that it had before the operation. This is identical to
215 /// `self.split_to(self.len())`.
216 ///
217 /// This is an `O(1)` operation that just increases the reference count and
218 /// sets a few indices.
219 ///
220 /// # Examples
221 ///
222 /// ```
223 /// use ntex_bytes::{BytesMut, BufMut};
224 ///
225 /// let mut buf = BytesMut::with_capacity(1024);
226 /// buf.put(&b"hello world"[..]);
227 ///
228 /// let other = buf.take();
229 ///
230 /// assert!(buf.is_empty());
231 /// assert_eq!(1013, buf.capacity());
232 ///
233 /// assert_eq!(other, b"hello world"[..]);
234 /// ```
235 pub fn take(&mut self) -> BytesMut {
236 BytesMut {
237 storage: self.storage.split_to(self.len()),
238 }
239 }
240
241 /// Removes the bytes from the current view, returning them in a new
242 /// `Bytes` handle.
243 ///
244 /// This is identical to `self.take().freeze()`.
245 ///
246 /// # Examples
247 ///
248 /// ```
249 /// use ntex_bytes::{BytesMut, BufMut};
250 ///
251 /// let mut buf = BytesMut::with_capacity(1024);
252 /// buf.put(&b"hello world"[..]);
253 ///
254 /// let other = buf.take_bytes();
255 ///
256 /// assert_eq!(other, b"hello world"[..]);
257 /// ```
258 pub fn take_bytes(&mut self) -> Bytes {
259 Bytes {
260 storage: self.storage.split_to(self.len()),
261 }
262 }
263
264 #[doc(hidden)]
265 #[deprecated]
266 pub fn split(&mut self) -> BytesMut {
267 self.take()
268 }
269
270 /// Splits the bytes into two at the given index.
271 ///
272 /// Afterwards `self` contains elements `[0, at)`, and the returned
273 /// `BytesMut` contains elements `[at, capacity)`.
274 ///
275 /// This is an `O(1)` operation that just increases the reference count
276 /// and sets a few indices.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use ntex_bytes::BytesMut;
282 ///
283 /// let mut a = BytesMut::from(&b"hello world"[..]);
284 /// let mut b = a.split_off(5);
285 ///
286 /// a[0] = b'j';
287 /// b[0] = b'!';
288 ///
289 /// assert_eq!(&a[..], b"jello");
290 /// assert_eq!(&b[..], b"!world");
291 /// ```
292 ///
293 /// # Panics
294 ///
295 /// Panics if `at > capacity`.
296 pub fn split_off(&mut self, at: usize) -> BytesMut {
297 BytesMut {
298 storage: self.storage.split_off(at, false),
299 }
300 }
301
302 /// Splits the buffer into two at the given index.
303 ///
304 /// Afterwards `self` contains elements `[at, len)`, and the returned `BytesMut`
305 /// contains elements `[0, at)`.
306 ///
307 /// This is an `O(1)` operation that just increases the reference count and
308 /// sets a few indices.
309 ///
310 /// # Examples
311 ///
312 /// ```
313 /// use ntex_bytes::BytesMut;
314 ///
315 /// let mut a = BytesMut::from(&b"hello world"[..]);
316 /// let mut b = a.split_to(5);
317 ///
318 /// a[0] = b'!';
319 /// b[0] = b'j';
320 ///
321 /// assert_eq!(&a[..], b"!world");
322 /// assert_eq!(&b[..], b"jello");
323 /// ```
324 ///
325 /// # Panics
326 ///
327 /// Panics if `at > len`.
328 pub fn split_to(&mut self, at: usize) -> BytesMut {
329 self.split_to_checked(at)
330 .expect("at value must be <= self.len()`")
331 }
332
333 /// Splits the buffer into two at the given index.
334 ///
335 /// Same as .split_to() but returns `Bytes` instance
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// use ntex_bytes::BytesMut;
341 ///
342 /// let mut a = BytesMut::from(&b"hello world"[..]);
343 /// let mut b = a.split_to_bytes(5);
344 ///
345 /// a[0] = b'!';
346 ///
347 /// assert_eq!(&a[..], b"!world");
348 /// assert_eq!(&b[..], b"hello");
349 /// ```
350 ///
351 /// # Panics
352 ///
353 /// Panics if `at > len`.
354 pub fn split_to_bytes(&mut self, at: usize) -> Bytes {
355 Bytes {
356 storage: self.split_to(at).storage,
357 }
358 }
359
360 /// Splits the bytes into two at the given index.
361 ///
362 /// Does nothing if `at > len`.
363 pub fn split_to_checked(&mut self, at: usize) -> Option<BytesMut> {
364 if at <= self.len() {
365 Some(BytesMut {
366 storage: self.storage.split_to(at),
367 })
368 } else {
369 None
370 }
371 }
372
373 /// Advance the internal cursor.
374 ///
375 /// Afterwards `self` contains elements `[cnt, len)`.
376 /// This is an `O(1)` operation.
377 ///
378 /// # Examples
379 ///
380 /// ```
381 /// use ntex_bytes::BytesMut;
382 ///
383 /// let mut a = BytesMut::copy_from_slice(&b"hello world"[..]);
384 /// a.advance_to(5);
385 ///
386 /// a[0] = b'!';
387 ///
388 /// assert_eq!(&a[..], b"!world");
389 /// ```
390 ///
391 /// # Panics
392 ///
393 /// Panics if `cnt > len`.
394 pub fn advance_to(&mut self, cnt: usize) {
395 unsafe {
396 self.storage.set_start(cnt);
397 }
398 }
399
400 /// Shortens the buffer, keeping the first `len` bytes and dropping the
401 /// rest.
402 ///
403 /// If `len` is greater than the buffer's current length, this has no
404 /// effect.
405 ///
406 /// The [`split_off`] method can emulate `truncate`, but this causes the
407 /// excess bytes to be returned instead of dropped.
408 ///
409 /// # Examples
410 ///
411 /// ```
412 /// use ntex_bytes::BytesMut;
413 ///
414 /// let mut buf = BytesMut::from(&b"hello world"[..]);
415 /// buf.truncate(5);
416 /// assert_eq!(buf, b"hello"[..]);
417 /// ```
418 ///
419 /// [`split_off`]: #method.split_off
420 pub fn truncate(&mut self, len: usize) {
421 self.storage.truncate(len, false);
422 }
423
424 /// Clears the buffer, removing all data.
425 ///
426 /// # Examples
427 ///
428 /// ```
429 /// use ntex_bytes::BytesMut;
430 ///
431 /// let mut buf = BytesMut::from(&b"hello world"[..]);
432 /// buf.clear();
433 /// assert!(buf.is_empty());
434 /// ```
435 pub fn clear(&mut self) {
436 self.truncate(0);
437 }
438
439 /// Resizes the buffer so that `len` is equal to `new_len`.
440 ///
441 /// If `new_len` is greater than `len`, the buffer is extended by the
442 /// difference with each additional byte set to `value`. If `new_len` is
443 /// less than `len`, the buffer is simply truncated.
444 ///
445 /// # Panics
446 ///
447 /// Panics if `new_len` greater than 60bit for 64bit systems
448 /// and 28bit for 32bit systems
449 ///
450 /// # Examples
451 ///
452 /// ```
453 /// use ntex_bytes::BytesMut;
454 ///
455 /// let mut buf = BytesMut::new();
456 ///
457 /// buf.resize(3, 0x1);
458 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
459 ///
460 /// buf.resize(2, 0x2);
461 /// assert_eq!(&buf[..], &[0x1, 0x1]);
462 ///
463 /// buf.resize(4, 0x3);
464 /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
465 /// ```
466 #[inline]
467 pub fn resize(&mut self, new_len: usize, value: u8) {
468 self.storage.resize(new_len, value);
469 }
470
471 /// Sets the length of the buffer.
472 ///
473 /// This will explicitly set the size of the buffer without actually
474 /// modifying the data, so it is up to the caller to ensure that the data
475 /// has been initialized.
476 ///
477 /// # Examples
478 ///
479 /// ```
480 /// use ntex_bytes::BytesMut;
481 ///
482 /// let mut b = BytesMut::from(&b"hello world"[..]);
483 ///
484 /// unsafe {
485 /// b.set_len(5);
486 /// }
487 ///
488 /// assert_eq!(&b[..], b"hello");
489 ///
490 /// unsafe {
491 /// b.set_len(11);
492 /// }
493 ///
494 /// assert_eq!(&b[..], b"hello world");
495 /// ```
496 ///
497 /// # Panics
498 ///
499 /// This method will panic if `len` is out of bounds for the underlying
500 /// slice or if it comes after the `end` of the configured window.
501 #[inline]
502 #[allow(clippy::missing_safety_doc)]
503 pub unsafe fn set_len(&mut self, len: usize) {
504 self.storage.set_len(len)
505 }
506
507 /// Reserves capacity for at least `additional` more bytes to be inserted
508 /// into the given `BytesMut`.
509 ///
510 /// More than `additional` bytes may be reserved in order to avoid frequent
511 /// reallocations. A call to `reserve` may result in an allocation.
512 ///
513 /// Before allocating new buffer space, the function will attempt to reclaim
514 /// space in the existing buffer. If the current handle references a small
515 /// view in the original buffer and all other handles have been dropped,
516 /// and the requested capacity is less than or equal to the existing
517 /// buffer's capacity, then the current view will be copied to the front of
518 /// the buffer and the handle will take ownership of the full buffer.
519 ///
520 /// # Panics
521 ///
522 /// Panics if new capacity is greater than 60bit for 64bit systems
523 /// and 28bit for 32bit systems
524 ///
525 /// # Examples
526 ///
527 /// In the following example, a new buffer is allocated.
528 ///
529 /// ```
530 /// use ntex_bytes::BytesMut;
531 ///
532 /// let mut buf = BytesMut::from(&b"hello"[..]);
533 /// buf.reserve(64);
534 /// assert!(buf.capacity() >= 69);
535 /// ```
536 ///
537 /// In the following example, the existing buffer is reclaimed.
538 ///
539 /// ```
540 /// use ntex_bytes::{BytesMut, BufMut};
541 ///
542 /// let mut buf = BytesMut::with_capacity(128);
543 /// buf.put(&[0; 64][..]);
544 ///
545 /// let ptr = buf.as_ptr();
546 /// let other = buf.take();
547 ///
548 /// assert!(buf.is_empty());
549 /// assert_eq!(buf.capacity(), 64);
550 ///
551 /// drop(other);
552 /// buf.reserve(128);
553 ///
554 /// assert_eq!(buf.capacity(), 128);
555 /// assert_eq!(buf.as_ptr(), ptr);
556 /// ```
557 ///
558 /// # Panics
559 ///
560 /// Panics if the new capacity overflows `usize`.
561 #[inline]
562 pub fn reserve(&mut self, additional: usize) {
563 self.storage.reserve(additional);
564 }
565
566 /// Appends given bytes to this object.
567 ///
568 /// If this `BytesMut` object has not enough capacity, it is resized first.
569 /// So unlike `put_slice` operation, `extend_from_slice` does not panic.
570 ///
571 /// # Examples
572 ///
573 /// ```
574 /// use ntex_bytes::BytesMut;
575 ///
576 /// let mut buf = BytesMut::with_capacity(0);
577 /// buf.extend_from_slice(b"aaabbb");
578 /// buf.extend_from_slice(b"cccddd");
579 ///
580 /// assert_eq!(b"aaabbbcccddd", &buf[..]);
581 /// ```
582 #[inline]
583 pub fn extend_from_slice(&mut self, extend: &[u8]) {
584 self.put_slice(extend);
585 }
586
587 /// Returns an iterator over the bytes contained by the buffer.
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// use ntex_bytes::{Buf, BytesMut};
593 ///
594 /// let buf = BytesMut::from(&b"abc"[..]);
595 /// let mut iter = buf.iter();
596 ///
597 /// assert_eq!(iter.next().map(|b| *b), Some(b'a'));
598 /// assert_eq!(iter.next().map(|b| *b), Some(b'b'));
599 /// assert_eq!(iter.next().map(|b| *b), Some(b'c'));
600 /// assert_eq!(iter.next(), None);
601 /// ```
602 #[inline]
603 pub fn iter(&'_ self) -> std::slice::Iter<'_, u8> {
604 self.chunk().iter()
605 }
606
607 #[inline]
608 #[doc(hidden)]
609 pub fn info(&self) -> crate::info::Info {
610 self.storage.info()
611 }
612}
613
614impl Buf for BytesMut {
615 #[inline]
616 fn remaining(&self) -> usize {
617 self.len()
618 }
619
620 #[inline]
621 fn chunk(&self) -> &[u8] {
622 self.storage.as_ref()
623 }
624
625 #[inline]
626 fn advance(&mut self, cnt: usize) {
627 self.advance_to(cnt)
628 }
629}
630
631impl BufMut for BytesMut {
632 #[inline]
633 fn remaining_mut(&self) -> usize {
634 self.capacity() - self.len()
635 }
636
637 #[inline]
638 unsafe fn advance_mut(&mut self, cnt: usize) {
639 let new_len = self.len() + cnt;
640
641 // This call will panic if `cnt` is too big
642 self.storage.set_len(new_len);
643 }
644
645 #[inline]
646 fn chunk_mut(&mut self) -> &mut UninitSlice {
647 let len = self.len();
648
649 unsafe {
650 // This will never panic as `len` can never become invalid
651 let ptr = &mut self.storage.as_raw()[len..];
652
653 UninitSlice::from_raw_parts_mut(ptr.as_mut_ptr(), self.capacity() - len)
654 }
655 }
656
657 #[inline]
658 fn put_slice(&mut self, src: &[u8]) {
659 let len = src.len();
660 self.reserve(len);
661
662 unsafe {
663 ptr::copy_nonoverlapping(src.as_ptr(), self.chunk_mut().as_mut_ptr(), len);
664 self.advance_mut(len);
665 }
666 }
667
668 #[inline]
669 fn put_u8(&mut self, n: u8) {
670 self.reserve(1);
671 self.storage.put_u8(n);
672 }
673
674 #[inline]
675 fn put_i8(&mut self, n: i8) {
676 self.reserve(1);
677 self.put_u8(n as u8);
678 }
679}
680
681impl bytes::buf::Buf for BytesMut {
682 #[inline]
683 fn remaining(&self) -> usize {
684 self.len()
685 }
686
687 #[inline]
688 fn chunk(&self) -> &[u8] {
689 self.storage.as_ref()
690 }
691
692 #[inline]
693 fn advance(&mut self, cnt: usize) {
694 self.advance_to(cnt)
695 }
696}
697
698unsafe impl bytes::buf::BufMut for BytesMut {
699 #[inline]
700 fn remaining_mut(&self) -> usize {
701 BufMut::remaining_mut(self)
702 }
703
704 #[inline]
705 unsafe fn advance_mut(&mut self, cnt: usize) {
706 BufMut::advance_mut(self, cnt)
707 }
708
709 #[inline]
710 fn chunk_mut(&mut self) -> &mut bytes::buf::UninitSlice {
711 let len = self.len();
712 unsafe {
713 // This will never panic as `len` can never become invalid
714 let ptr = &mut self.storage.as_raw()[len..];
715 bytes::buf::UninitSlice::from_raw_parts_mut(
716 ptr.as_mut_ptr(),
717 self.capacity() - len,
718 )
719 }
720 }
721
722 #[inline]
723 fn put_slice(&mut self, src: &[u8]) {
724 BufMut::put_slice(self, src)
725 }
726
727 #[inline]
728 fn put_u8(&mut self, n: u8) {
729 BufMut::put_u8(self, n)
730 }
731
732 #[inline]
733 fn put_i8(&mut self, n: i8) {
734 BufMut::put_i8(self, n)
735 }
736}
737
738impl AsRef<[u8]> for BytesMut {
739 #[inline]
740 fn as_ref(&self) -> &[u8] {
741 self.storage.as_ref()
742 }
743}
744
745impl AsMut<[u8]> for BytesMut {
746 #[inline]
747 fn as_mut(&mut self) -> &mut [u8] {
748 self.storage.as_mut()
749 }
750}
751
752impl ops::Deref for BytesMut {
753 type Target = [u8];
754
755 #[inline]
756 fn deref(&self) -> &[u8] {
757 self.as_ref()
758 }
759}
760
761impl ops::DerefMut for BytesMut {
762 #[inline]
763 fn deref_mut(&mut self) -> &mut [u8] {
764 self.storage.as_mut()
765 }
766}
767
768impl From<Vec<u8>> for BytesMut {
769 #[inline]
770 /// Convert a `Vec` into a `BytesMut`
771 ///
772 /// This constructor may be used to avoid the inlining optimization used by
773 /// `with_capacity`. A `BytesMut` constructed this way will always store
774 /// its data on the heap.
775 fn from(src: Vec<u8>) -> BytesMut {
776 BytesMut::from_vec(src)
777 }
778}
779
780impl From<String> for BytesMut {
781 #[inline]
782 fn from(src: String) -> BytesMut {
783 BytesMut::from_vec(src.into_bytes())
784 }
785}
786
787impl From<&BytesMut> for BytesMut {
788 #[inline]
789 fn from(src: &BytesMut) -> BytesMut {
790 src.clone()
791 }
792}
793
794impl<'a> From<&'a [u8]> for BytesMut {
795 fn from(src: &'a [u8]) -> BytesMut {
796 if src.is_empty() {
797 BytesMut::new()
798 } else {
799 BytesMut::copy_from_slice(src)
800 }
801 }
802}
803
804impl<const N: usize> From<[u8; N]> for BytesMut {
805 fn from(src: [u8; N]) -> BytesMut {
806 BytesMut::copy_from_slice(src)
807 }
808}
809
810impl<'a, const N: usize> From<&'a [u8; N]> for BytesMut {
811 fn from(src: &'a [u8; N]) -> BytesMut {
812 BytesMut::copy_from_slice(src)
813 }
814}
815
816impl<'a> From<&'a str> for BytesMut {
817 #[inline]
818 fn from(src: &'a str) -> BytesMut {
819 BytesMut::from(src.as_bytes())
820 }
821}
822
823impl From<Bytes> for BytesMut {
824 #[inline]
825 fn from(src: Bytes) -> BytesMut {
826 src.try_mut()
827 .unwrap_or_else(|src| BytesMut::copy_from_slice(&src[..]))
828 }
829}
830
831impl From<&Bytes> for BytesMut {
832 #[inline]
833 fn from(src: &Bytes) -> BytesMut {
834 BytesMut::copy_from_slice(&src[..])
835 }
836}
837
838impl Eq for BytesMut {}
839
840impl PartialEq for BytesMut {
841 #[inline]
842 fn eq(&self, other: &BytesMut) -> bool {
843 self.storage.as_ref() == other.storage.as_ref()
844 }
845}
846
847impl Default for BytesMut {
848 #[inline]
849 fn default() -> BytesMut {
850 BytesMut::new()
851 }
852}
853
854impl borrow::Borrow<[u8]> for BytesMut {
855 #[inline]
856 fn borrow(&self) -> &[u8] {
857 self.as_ref()
858 }
859}
860
861impl borrow::BorrowMut<[u8]> for BytesMut {
862 #[inline]
863 fn borrow_mut(&mut self) -> &mut [u8] {
864 self.as_mut()
865 }
866}
867
868impl fmt::Debug for BytesMut {
869 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
870 fmt::Debug::fmt(&debug::BsDebug(self.storage.as_ref()), fmt)
871 }
872}
873
874impl fmt::Write for BytesMut {
875 #[inline]
876 fn write_str(&mut self, s: &str) -> fmt::Result {
877 if self.remaining_mut() >= s.len() {
878 self.put_slice(s.as_bytes());
879 Ok(())
880 } else {
881 Err(fmt::Error)
882 }
883 }
884
885 #[inline]
886 fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
887 fmt::write(self, args)
888 }
889}
890
891impl Clone for BytesMut {
892 #[inline]
893 fn clone(&self) -> BytesMut {
894 BytesMut::from(&self[..])
895 }
896}
897
898impl IntoIterator for BytesMut {
899 type Item = u8;
900 type IntoIter = IntoIter<BytesMut>;
901
902 fn into_iter(self) -> Self::IntoIter {
903 IntoIter::new(self)
904 }
905}
906
907impl<'a> IntoIterator for &'a BytesMut {
908 type Item = &'a u8;
909 type IntoIter = std::slice::Iter<'a, u8>;
910
911 fn into_iter(self) -> Self::IntoIter {
912 self.as_ref().iter()
913 }
914}
915
916impl FromIterator<u8> for BytesMut {
917 fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
918 let iter = into_iter.into_iter();
919 let (min, maybe_max) = iter.size_hint();
920
921 let mut out = BytesMut::with_capacity(maybe_max.unwrap_or(min));
922 for i in iter {
923 out.reserve(1);
924 out.put_u8(i);
925 }
926
927 out
928 }
929}
930
931impl<'a> FromIterator<&'a u8> for BytesMut {
932 fn from_iter<T: IntoIterator<Item = &'a u8>>(into_iter: T) -> Self {
933 into_iter.into_iter().copied().collect::<BytesMut>()
934 }
935}
936
937impl Extend<u8> for BytesMut {
938 fn extend<T>(&mut self, iter: T)
939 where
940 T: IntoIterator<Item = u8>,
941 {
942 let iter = iter.into_iter();
943
944 let (lower, _) = iter.size_hint();
945 self.reserve(lower);
946
947 for (idx, b) in iter.enumerate() {
948 if idx >= lower {
949 self.reserve(1);
950 }
951 self.put_u8(b);
952 }
953 }
954}
955
956impl<'a> Extend<&'a u8> for BytesMut {
957 fn extend<T>(&mut self, iter: T)
958 where
959 T: IntoIterator<Item = &'a u8>,
960 {
961 self.extend(iter.into_iter().copied())
962 }
963}
964
965/*
966 *
967 * ===== PartialEq / PartialOrd =====
968 *
969 */
970
971impl PartialEq<[u8]> for BytesMut {
972 fn eq(&self, other: &[u8]) -> bool {
973 &**self == other
974 }
975}
976
977impl<const N: usize> PartialEq<[u8; N]> for BytesMut {
978 fn eq(&self, other: &[u8; N]) -> bool {
979 &**self == other
980 }
981}
982
983impl PartialEq<BytesMut> for [u8] {
984 fn eq(&self, other: &BytesMut) -> bool {
985 *other == *self
986 }
987}
988
989impl<const N: usize> PartialEq<BytesMut> for [u8; N] {
990 fn eq(&self, other: &BytesMut) -> bool {
991 *other == *self
992 }
993}
994
995impl<const N: usize> PartialEq<BytesMut> for &[u8; N] {
996 fn eq(&self, other: &BytesMut) -> bool {
997 *other == *self
998 }
999}
1000
1001impl PartialEq<str> for BytesMut {
1002 fn eq(&self, other: &str) -> bool {
1003 &**self == other.as_bytes()
1004 }
1005}
1006
1007impl PartialEq<BytesMut> for str {
1008 fn eq(&self, other: &BytesMut) -> bool {
1009 *other == *self
1010 }
1011}
1012
1013impl PartialEq<Vec<u8>> for BytesMut {
1014 fn eq(&self, other: &Vec<u8>) -> bool {
1015 *self == other[..]
1016 }
1017}
1018
1019impl PartialEq<BytesMut> for Vec<u8> {
1020 fn eq(&self, other: &BytesMut) -> bool {
1021 *other == *self
1022 }
1023}
1024
1025impl PartialEq<String> for BytesMut {
1026 fn eq(&self, other: &String) -> bool {
1027 *self == other[..]
1028 }
1029}
1030
1031impl PartialEq<BytesMut> for String {
1032 fn eq(&self, other: &BytesMut) -> bool {
1033 *other == *self
1034 }
1035}
1036
1037impl<'a, T: ?Sized> PartialEq<&'a T> for BytesMut
1038where
1039 BytesMut: PartialEq<T>,
1040{
1041 fn eq(&self, other: &&'a T) -> bool {
1042 *self == **other
1043 }
1044}
1045
1046impl PartialEq<BytesMut> for &[u8] {
1047 fn eq(&self, other: &BytesMut) -> bool {
1048 *other == *self
1049 }
1050}
1051
1052impl PartialEq<BytesMut> for &str {
1053 fn eq(&self, other: &BytesMut) -> bool {
1054 *other == *self
1055 }
1056}
1057
1058impl PartialEq<Bytes> for BytesMut {
1059 fn eq(&self, other: &Bytes) -> bool {
1060 other[..] == self[..]
1061 }
1062}