ntex_bytes/
bvec.rs

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