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