utf8_bytes/
bytes_mut.rs

1use super::Utf8Bytes;
2
3use core::iter::FromIterator;
4use core::mem::MaybeUninit;
5use core::ops::{Deref, DerefMut};
6use core::ptr::{self};
7use core::{cmp, fmt, hash};
8
9use alloc::{
10    borrow::{Borrow, BorrowMut},
11    string::String,
12    vec::Vec,
13};
14
15/// A unique reference to a contiguous slice of memory.
16///
17/// `BytesMut` represents a unique view into a potentially shared memory region.
18/// Given the uniqueness guarantee, owners of `BytesMut` handles are able to
19/// mutate the memory.
20///
21/// `BytesMut` can be thought of as containing a `buf: Arc<Vec<u8>>`, an offset
22/// into `buf`, a slice length, and a guarantee that no other `BytesMut` for the
23/// same `buf` overlaps with its slice. That guarantee means that a write lock
24/// is not required.
25///
26/// # Growth
27///
28/// `BytesMut`'s `BufMut` implementation will implicitly grow its buffer as
29/// necessary. However, explicitly reserving the required space up-front before
30/// a series of inserts will be more efficient.
31///
32/// # Examples
33///
34/// ```
35/// use bytes::{BytesMut, BufMut};
36///
37/// let mut buf = BytesMut::with_capacity(64);
38///
39/// buf.put_u8(b'h');
40/// buf.put_u8(b'e');
41/// buf.put(&b"llo"[..]);
42///
43/// assert_eq!(&buf[..], b"hello");
44///
45/// // Freeze the buffer so that it can be shared
46/// let a = buf.freeze();
47///
48/// // This does not allocate, instead `b` points to the same memory.
49/// let b = a.clone();
50///
51/// assert_eq!(&a[..], b"hello");
52/// assert_eq!(&b[..], b"hello");
53/// ```
54pub struct Utf8BytesMut {
55    inner: bytes::BytesMut,
56}
57
58impl Utf8BytesMut {
59    pub const unsafe fn from_bytes_mut_unchecked(inner: bytes::BytesMut) -> Self {
60        Self { inner }
61    }
62    pub fn as_str(&self) -> &str {
63        unsafe { str::from_utf8_unchecked(&self.inner) }
64    }
65    pub fn as_mut_str(&mut self) -> &mut str {
66        unsafe { str::from_utf8_unchecked_mut(&mut self.inner) }
67    }
68}
69
70impl Utf8BytesMut {
71    /// Creates a new `BytesMut` with the specified capacity.
72    ///
73    /// The returned `BytesMut` will be able to hold at least `capacity` bytes
74    /// without reallocating.
75    ///
76    /// It is important to note that this function does not specify the length
77    /// of the returned `BytesMut`, but only the capacity.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use bytes::{BytesMut, BufMut};
83    ///
84    /// let mut bytes = BytesMut::with_capacity(64);
85    ///
86    /// // `bytes` contains no data, even though there is capacity
87    /// assert_eq!(bytes.len(), 0);
88    ///
89    /// bytes.put(&b"hello world"[..]);
90    ///
91    /// assert_eq!(&bytes[..], b"hello world");
92    /// ```
93    #[inline]
94    pub fn with_capacity(capacity: usize) -> Utf8BytesMut {
95        unsafe { Self::from_bytes_mut_unchecked(bytes::BytesMut::with_capacity(capacity)) }
96    }
97
98    /// Creates a new `BytesMut` with default capacity.
99    ///
100    /// Resulting object has length 0 and unspecified capacity.
101    /// This function does not allocate.
102    ///
103    /// # Examples
104    ///
105    /// ```
106    /// use bytes::{BytesMut, BufMut};
107    ///
108    /// let mut bytes = BytesMut::new();
109    ///
110    /// assert_eq!(0, bytes.len());
111    ///
112    /// bytes.reserve(2);
113    /// bytes.put_slice(b"xy");
114    ///
115    /// assert_eq!(&b"xy"[..], &bytes[..]);
116    /// ```
117    #[inline]
118    pub fn new() -> Utf8BytesMut {
119        Utf8BytesMut::with_capacity(0)
120    }
121
122    /// Returns the number of bytes contained in this `BytesMut`.
123    ///
124    /// # Examples
125    ///
126    /// ```
127    /// use bytes::BytesMut;
128    ///
129    /// let b = BytesMut::from(&b"hello"[..]);
130    /// assert_eq!(b.len(), 5);
131    /// ```
132    #[inline]
133    pub fn len(&self) -> usize {
134        self.inner.len()
135    }
136
137    /// Returns true if the `BytesMut` has a length of 0.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// use bytes::BytesMut;
143    ///
144    /// let b = BytesMut::with_capacity(64);
145    /// assert!(b.is_empty());
146    /// ```
147    #[inline]
148    pub fn is_empty(&self) -> bool {
149        self.inner.is_empty()
150    }
151
152    /// Returns the number of bytes the `BytesMut` can hold without reallocating.
153    ///
154    /// # Examples
155    ///
156    /// ```
157    /// use bytes::BytesMut;
158    ///
159    /// let b = BytesMut::with_capacity(64);
160    /// assert_eq!(b.capacity(), 64);
161    /// ```
162    #[inline]
163    pub fn capacity(&self) -> usize {
164        self.inner.capacity()
165    }
166
167    /// Converts `self` into an immutable `Bytes`.
168    ///
169    /// The conversion is zero cost and is used to indicate that the slice
170    /// referenced by the handle will no longer be mutated. Once the conversion
171    /// is done, the handle can be cloned and shared across threads.
172    ///
173    /// # Examples
174    ///
175    /// ```
176    /// use bytes::{BytesMut, BufMut};
177    /// use std::thread;
178    ///
179    /// let mut b = BytesMut::with_capacity(64);
180    /// b.put(&b"hello world"[..]);
181    /// let b1 = b.freeze();
182    /// let b2 = b1.clone();
183    ///
184    /// let th = thread::spawn(move || {
185    ///     assert_eq!(&b1[..], b"hello world");
186    /// });
187    ///
188    /// assert_eq!(&b2[..], b"hello world");
189    /// th.join().unwrap();
190    /// ```
191    #[inline]
192    pub fn freeze(self) -> Utf8Bytes {
193        unsafe { Utf8Bytes::from_bytes_unchecked(self.inner.freeze()) }
194    }
195
196    /// Creates a new `BytesMut` containing `len` zeros.
197    ///
198    /// The resulting object has a length of `len` and a capacity greater
199    /// than or equal to `len`. The entire length of the object will be filled
200    /// with zeros.
201    ///
202    /// On some platforms or allocators this function may be faster than
203    /// a manual implementation.
204    ///
205    /// # Examples
206    ///
207    /// ```
208    /// use bytes::BytesMut;
209    ///
210    /// let zeros = BytesMut::zeroed(42);
211    ///
212    /// assert!(zeros.capacity() >= 42);
213    /// assert_eq!(zeros.len(), 42);
214    /// zeros.into_iter().for_each(|x| assert_eq!(x, 0));
215    /// ```
216    pub fn zeroed(len: usize) -> Utf8BytesMut {
217        unsafe { Self::from_bytes_mut_unchecked(bytes::BytesMut::zeroed(len)) }
218    }
219
220    /// Splits the bytes into two at the given index.
221    ///
222    /// Afterwards `self` contains elements `[0, at)`, and the returned
223    /// `BytesMut` contains elements `[at, capacity)`. It's guaranteed that the
224    /// memory does not move, that is, the address of `self` does not change,
225    /// and the address of the returned slice is `at` bytes after that.
226    ///
227    /// This is an `O(1)` operation that just increases the reference count
228    /// and sets a few indices.
229    ///
230    /// # Examples
231    ///
232    /// ```
233    /// use bytes::BytesMut;
234    ///
235    /// let mut a = BytesMut::from(&b"hello world"[..]);
236    /// let mut b = a.split_off(5);
237    ///
238    /// a[0] = b'j';
239    /// b[0] = b'!';
240    ///
241    /// assert_eq!(&a[..], b"jello");
242    /// assert_eq!(&b[..], b"!world");
243    /// ```
244    ///
245    /// # Panics
246    ///
247    /// Panics if `at > capacity`.
248    #[must_use = "consider BytesMut::truncate if you don't need the other half"]
249    pub fn split_off(&mut self, at: usize) -> Utf8BytesMut {
250        let _char_boundary = self.as_str().split_at(at);
251        unsafe { Self::from_bytes_mut_unchecked(self.inner.split_off(at)) }
252    }
253
254    /// Removes the bytes from the current view, returning them in a new
255    /// `BytesMut` handle.
256    ///
257    /// Afterwards, `self` will be empty, but will retain any additional
258    /// capacity that it had before the operation. This is identical to
259    /// `self.split_to(self.len())`.
260    ///
261    /// This is an `O(1)` operation that just increases the reference count and
262    /// sets a few indices.
263    ///
264    /// # Examples
265    ///
266    /// ```
267    /// use bytes::{BytesMut, BufMut};
268    ///
269    /// let mut buf = BytesMut::with_capacity(1024);
270    /// buf.put(&b"hello world"[..]);
271    ///
272    /// let other = buf.split();
273    ///
274    /// assert!(buf.is_empty());
275    /// assert_eq!(1013, buf.capacity());
276    ///
277    /// assert_eq!(other, b"hello world"[..]);
278    /// ```
279    #[must_use = "consider BytesMut::clear if you don't need the other half"]
280    pub fn split(&mut self) -> Utf8BytesMut {
281        unsafe { Self::from_bytes_mut_unchecked(self.inner.split()) }
282    }
283
284    /// Splits the buffer into two at the given index.
285    ///
286    /// Afterwards `self` contains elements `[at, len)`, and the returned `BytesMut`
287    /// contains elements `[0, at)`.
288    ///
289    /// This is an `O(1)` operation that just increases the reference count and
290    /// sets a few indices.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use bytes::BytesMut;
296    ///
297    /// let mut a = BytesMut::from(&b"hello world"[..]);
298    /// let mut b = a.split_to(5);
299    ///
300    /// a[0] = b'!';
301    /// b[0] = b'j';
302    ///
303    /// assert_eq!(&a[..], b"!world");
304    /// assert_eq!(&b[..], b"jello");
305    /// ```
306    ///
307    /// # Panics
308    ///
309    /// Panics if `at > len`.
310    #[must_use = "consider BytesMut::advance if you don't need the other half"]
311    pub fn split_to(&mut self, at: usize) -> Utf8BytesMut {
312        let _char_boundary = self.as_str().split_at(at);
313        unsafe { Self::from_bytes_mut_unchecked(self.inner.split_to(at)) }
314    }
315
316    /// Shortens the buffer, keeping the first `len` bytes and dropping the
317    /// rest.
318    ///
319    /// If `len` is greater than the buffer's current length, this has no
320    /// effect.
321    ///
322    /// Existing underlying capacity is preserved.
323    ///
324    /// The [split_off](`Self::split_off()`) method can emulate `truncate`, but this causes the
325    /// excess bytes to be returned instead of dropped.
326    ///
327    /// # Examples
328    ///
329    /// ```
330    /// use bytes::BytesMut;
331    ///
332    /// let mut buf = BytesMut::from(&b"hello world"[..]);
333    /// buf.truncate(5);
334    /// assert_eq!(buf, b"hello"[..]);
335    /// ```
336    pub fn truncate(&mut self, len: usize) {
337        fn floor_char_boundary(s: &str, index: usize) -> usize {
338            if index >= s.len() {
339                s.len()
340            } else {
341                let lower_bound = index.saturating_sub(3);
342                let new_index = s.as_bytes()[lower_bound..=index]
343                    .iter()
344                    .rposition(|b| is_utf8_char_boundary(*b));
345
346                // SAFETY: we know that the character boundary will be within four bytes
347                unsafe { lower_bound + new_index.unwrap_unchecked() }
348            }
349        }
350
351        fn is_utf8_char_boundary(b: u8) -> bool {
352            // This is bit magic equivalent to: b < 128 || b >= 192
353            (b as i8) >= -0x40
354        }
355        self.inner.truncate(floor_char_boundary(self.as_str(), len));
356    }
357
358    /// Clears the buffer, removing all data. Existing capacity is preserved.
359    ///
360    /// # Examples
361    ///
362    /// ```
363    /// use bytes::BytesMut;
364    ///
365    /// let mut buf = BytesMut::from(&b"hello world"[..]);
366    /// buf.clear();
367    /// assert!(buf.is_empty());
368    /// ```
369    pub fn clear(&mut self) {
370        self.inner.clear();
371    }
372
373    /// Resizes the buffer so that `len` is equal to `new_len`.
374    ///
375    /// If `new_len` is greater than `len`, the buffer is extended by the
376    /// difference with each additional byte set to `value`. If `new_len` is
377    /// less than `len`, the buffer is simply truncated.
378    ///
379    /// # Examples
380    ///
381    /// ```
382    /// use bytes::BytesMut;
383    ///
384    /// let mut buf = BytesMut::new();
385    ///
386    /// buf.resize(3, 0x1);
387    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x1]);
388    ///
389    /// buf.resize(2, 0x2);
390    /// assert_eq!(&buf[..], &[0x1, 0x1]);
391    ///
392    /// buf.resize(4, 0x3);
393    /// assert_eq!(&buf[..], &[0x1, 0x1, 0x3, 0x3]);
394    /// ```
395    pub fn resize(&mut self, new_len: usize, ch: u8) {
396        assert!(ch.is_ascii());
397        let additional = if let Some(additional) = new_len.checked_sub(self.len()) {
398            additional
399        } else {
400            self.truncate(new_len);
401            return;
402        };
403
404        if additional == 0 {
405            return;
406        }
407
408        self.reserve(additional);
409        let dst = self.spare_capacity_mut().as_mut_ptr();
410        // SAFETY: `spare_capacity_mut` returns a valid, properly aligned pointer and we've
411        // reserved enough space to write `additional` bytes.
412        unsafe { ptr::write_bytes(dst, ch, additional) };
413
414        // SAFETY: There are at least `new_len` initialized bytes in the buffer so no
415        // uninitialized bytes are being exposed.
416        unsafe { self.set_len(new_len) };
417    }
418
419    /// Sets the length of the buffer.
420    ///
421    /// This will explicitly set the size of the buffer without actually
422    /// modifying the data, so it is up to the caller to ensure that the data
423    /// has been initialized.
424    ///
425    /// # Examples
426    ///
427    /// ```
428    /// use bytes::BytesMut;
429    ///
430    /// let mut b = BytesMut::from(&b"hello world"[..]);
431    ///
432    /// unsafe {
433    ///     b.set_len(5);
434    /// }
435    ///
436    /// assert_eq!(&b[..], b"hello");
437    ///
438    /// unsafe {
439    ///     b.set_len(11);
440    /// }
441    ///
442    /// assert_eq!(&b[..], b"hello world");
443    /// ```
444    #[inline]
445    pub unsafe fn set_len(&mut self, len: usize) {
446        unsafe { self.inner.set_len(len) }
447    }
448
449    /// Reserves capacity for at least `additional` more bytes to be inserted
450    /// into the given `BytesMut`.
451    ///
452    /// More than `additional` bytes may be reserved in order to avoid frequent
453    /// reallocations. A call to `reserve` may result in an allocation.
454    ///
455    /// Before allocating new buffer space, the function will attempt to reclaim
456    /// space in the existing buffer. If the current handle references a view
457    /// into a larger original buffer, and all other handles referencing part
458    /// of the same original buffer have been dropped, then the current view
459    /// can be copied/shifted to the front of the buffer and the handle can take
460    /// ownership of the full buffer, provided that the full buffer is large
461    /// enough to fit the requested additional capacity.
462    ///
463    /// This optimization will only happen if shifting the data from the current
464    /// view to the front of the buffer is not too expensive in terms of the
465    /// (amortized) time required. The precise condition is subject to change;
466    /// as of now, the length of the data being shifted needs to be at least as
467    /// large as the distance that it's shifted by. If the current view is empty
468    /// and the original buffer is large enough to fit the requested additional
469    /// capacity, then reallocations will never happen.
470    ///
471    /// # Examples
472    ///
473    /// In the following example, a new buffer is allocated.
474    ///
475    /// ```
476    /// use bytes::BytesMut;
477    ///
478    /// let mut buf = BytesMut::from(&b"hello"[..]);
479    /// buf.reserve(64);
480    /// assert!(buf.capacity() >= 69);
481    /// ```
482    ///
483    /// In the following example, the existing buffer is reclaimed.
484    ///
485    /// ```
486    /// use bytes::{BytesMut, BufMut};
487    ///
488    /// let mut buf = BytesMut::with_capacity(128);
489    /// buf.put(&[0; 64][..]);
490    ///
491    /// let ptr = buf.as_ptr();
492    /// let other = buf.split();
493    ///
494    /// assert!(buf.is_empty());
495    /// assert_eq!(buf.capacity(), 64);
496    ///
497    /// drop(other);
498    /// buf.reserve(128);
499    ///
500    /// assert_eq!(buf.capacity(), 128);
501    /// assert_eq!(buf.as_ptr(), ptr);
502    /// ```
503    ///
504    /// # Panics
505    ///
506    /// Panics if the new capacity overflows `usize`.
507    #[inline]
508    pub fn reserve(&mut self, additional: usize) {
509        self.inner.reserve(additional);
510    }
511
512    /// Attempts to cheaply reclaim already allocated capacity for at least `additional` more
513    /// bytes to be inserted into the given `BytesMut` and returns `true` if it succeeded.
514    ///
515    /// `try_reclaim` behaves exactly like `reserve`, except that it never allocates new storage
516    /// and returns a `bool` indicating whether it was successful in doing so:
517    ///
518    /// `try_reclaim` returns false under these conditions:
519    ///  - The spare capacity left is less than `additional` bytes AND
520    ///  - The existing allocation cannot be reclaimed cheaply or it was less than
521    ///    `additional` bytes in size
522    ///
523    /// Reclaiming the allocation cheaply is possible if the `BytesMut` has no outstanding
524    /// references through other `BytesMut`s or `Bytes` which point to the same underlying
525    /// storage.
526    ///
527    /// # Examples
528    ///
529    /// ```
530    /// use bytes::BytesMut;
531    ///
532    /// let mut buf = BytesMut::with_capacity(64);
533    /// assert_eq!(true, buf.try_reclaim(64));
534    /// assert_eq!(64, buf.capacity());
535    ///
536    /// buf.extend_from_slice(b"abcd");
537    /// let mut split = buf.split();
538    /// assert_eq!(60, buf.capacity());
539    /// assert_eq!(4, split.capacity());
540    /// assert_eq!(false, split.try_reclaim(64));
541    /// assert_eq!(false, buf.try_reclaim(64));
542    /// // The split buffer is filled with "abcd"
543    /// assert_eq!(false, split.try_reclaim(4));
544    /// // buf is empty and has capacity for 60 bytes
545    /// assert_eq!(true, buf.try_reclaim(60));
546    ///
547    /// drop(buf);
548    /// assert_eq!(false, split.try_reclaim(64));
549    ///
550    /// split.clear();
551    /// assert_eq!(4, split.capacity());
552    /// assert_eq!(true, split.try_reclaim(64));
553    /// assert_eq!(64, split.capacity());
554    /// ```
555    // I tried splitting out try_reclaim_inner after the short circuits, but it was inlined
556    // regardless with Rust 1.78.0 so probably not worth it
557    #[inline]
558    #[must_use = "consider BytesMut::reserve if you need an infallible reservation"]
559    pub fn try_reclaim(&mut self, additional: usize) -> bool {
560        self.inner.try_reclaim(additional)
561    }
562
563    /// Appends given bytes to this `BytesMut`.
564    ///
565    /// If this `BytesMut` object does not have enough capacity, it is resized
566    /// first.
567    ///
568    /// # Examples
569    ///
570    /// ```
571    /// use bytes::BytesMut;
572    ///
573    /// let mut buf = BytesMut::with_capacity(0);
574    /// buf.extend_from_slice(b"aaabbb");
575    /// buf.extend_from_slice(b"cccddd");
576    ///
577    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
578    /// ```
579    #[inline]
580    pub fn extend_from_str(&mut self, extend: &str) {
581        self.inner.extend_from_slice(extend.as_bytes());
582    }
583
584    /// Absorbs a `BytesMut` that was previously split off.
585    ///
586    /// If the two `BytesMut` objects were previously contiguous and not mutated
587    /// in a way that causes re-allocation i.e., if `other` was created by
588    /// calling `split_off` on this `BytesMut`, then this is an `O(1)` operation
589    /// that just decreases a reference count and sets a few indices.
590    /// Otherwise this method degenerates to
591    /// `self.extend_from_slice(other.as_ref())`.
592    ///
593    /// # Examples
594    ///
595    /// ```
596    /// use bytes::BytesMut;
597    ///
598    /// let mut buf = BytesMut::with_capacity(64);
599    /// buf.extend_from_slice(b"aaabbbcccddd");
600    ///
601    /// let split = buf.split_off(6);
602    /// assert_eq!(b"aaabbb", &buf[..]);
603    /// assert_eq!(b"cccddd", &split[..]);
604    ///
605    /// buf.unsplit(split);
606    /// assert_eq!(b"aaabbbcccddd", &buf[..]);
607    /// ```
608    pub fn unsplit(&mut self, other: Utf8BytesMut) {
609        self.inner.unsplit(other.inner);
610    }
611
612    /// Returns the remaining spare capacity of the buffer as a slice of `MaybeUninit<u8>`.
613    ///
614    /// The returned slice can be used to fill the buffer with data (e.g. by
615    /// reading from a file) before marking the data as initialized using the
616    /// [`set_len`] method.
617    ///
618    /// [`set_len`]: BytesMut::set_len
619    ///
620    /// # Examples
621    ///
622    /// ```
623    /// use bytes::BytesMut;
624    ///
625    /// // Allocate buffer big enough for 10 bytes.
626    /// let mut buf = BytesMut::with_capacity(10);
627    ///
628    /// // Fill in the first 3 elements.
629    /// let uninit = buf.spare_capacity_mut();
630    /// uninit[0].write(0);
631    /// uninit[1].write(1);
632    /// uninit[2].write(2);
633    ///
634    /// // Mark the first 3 bytes of the buffer as being initialized.
635    /// unsafe {
636    ///     buf.set_len(3);
637    /// }
638    ///
639    /// assert_eq!(&buf[..], &[0, 1, 2]);
640    /// ```
641    #[inline]
642    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<u8>] {
643        self.inner.spare_capacity_mut()
644    }
645}
646
647impl AsRef<[u8]> for Utf8BytesMut {
648    #[inline]
649    fn as_ref(&self) -> &[u8] {
650        self.as_str().as_bytes()
651    }
652}
653
654impl AsRef<str> for Utf8BytesMut {
655    fn as_ref(&self) -> &str {
656        self.as_str()
657    }
658}
659
660impl Deref for Utf8BytesMut {
661    type Target = str;
662
663    #[inline]
664    fn deref(&self) -> &str {
665        self.as_str()
666    }
667}
668
669impl AsMut<str> for Utf8BytesMut {
670    #[inline]
671    fn as_mut(&mut self) -> &mut str {
672        self.as_mut_str()
673    }
674}
675
676impl DerefMut for Utf8BytesMut {
677    #[inline]
678    fn deref_mut(&mut self) -> &mut str {
679        self.as_mut_str()
680    }
681}
682
683impl<'a> From<&'a str> for Utf8BytesMut {
684    fn from(src: &'a str) -> Utf8BytesMut {
685        unsafe { Self::from_bytes_mut_unchecked(src.as_bytes().into()) }
686    }
687}
688
689impl From<Utf8BytesMut> for Utf8Bytes {
690    fn from(src: Utf8BytesMut) -> Utf8Bytes {
691        src.freeze()
692    }
693}
694
695impl<T: AsRef<str>> PartialEq<T> for Utf8BytesMut {
696    fn eq(&self, other: &T) -> bool {
697        self.as_str().eq(other.as_ref())
698    }
699}
700
701impl Eq for Utf8BytesMut {}
702
703impl<T: AsRef<str>> PartialOrd<T> for Utf8BytesMut {
704    fn partial_cmp(&self, other: &T) -> Option<cmp::Ordering> {
705        self.as_str().partial_cmp(other.as_ref())
706    }
707}
708
709impl Ord for Utf8BytesMut {
710    fn cmp(&self, other: &Utf8BytesMut) -> cmp::Ordering {
711        self.as_str().cmp(other.as_str())
712    }
713}
714
715impl Default for Utf8BytesMut {
716    #[inline]
717    fn default() -> Utf8BytesMut {
718        Utf8BytesMut::new()
719    }
720}
721
722impl hash::Hash for Utf8BytesMut {
723    fn hash<H>(&self, state: &mut H)
724    where
725        H: hash::Hasher,
726    {
727        self.as_str().hash(state);
728    }
729}
730
731impl Borrow<str> for Utf8BytesMut {
732    fn borrow(&self) -> &str {
733        self.as_str()
734    }
735}
736
737impl BorrowMut<str> for Utf8BytesMut {
738    fn borrow_mut(&mut self) -> &mut str {
739        self.as_mut_str()
740    }
741}
742
743impl fmt::Write for Utf8BytesMut {
744    #[inline]
745    fn write_str(&mut self, s: &str) -> fmt::Result {
746        self.inner.write_str(s)
747    }
748
749    #[inline]
750    fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
751        self.inner.write_fmt(args)
752    }
753}
754
755impl Clone for Utf8BytesMut {
756    fn clone(&self) -> Utf8BytesMut {
757        Utf8BytesMut::from(&self[..])
758    }
759}
760
761impl Extend<char> for Utf8BytesMut {
762    fn extend<T>(&mut self, iter: T)
763    where
764        T: IntoIterator<Item = char>,
765    {
766        let iter = iter.into_iter();
767
768        let (lower, _) = iter.size_hint();
769        self.reserve(lower);
770
771        for c in iter {
772            fmt::Write::write_char(self, c).unwrap()
773        }
774    }
775}
776
777impl<'a> Extend<&'a char> for Utf8BytesMut {
778    fn extend<T>(&mut self, iter: T)
779    where
780        T: IntoIterator<Item = &'a char>,
781    {
782        self.extend(iter.into_iter().copied())
783    }
784}
785
786impl Extend<Utf8Bytes> for Utf8BytesMut {
787    fn extend<T>(&mut self, iter: T)
788    where
789        T: IntoIterator<Item = Utf8Bytes>,
790    {
791        for bytes in iter {
792            self.extend_from_str(&bytes)
793        }
794    }
795}
796
797impl FromIterator<char> for Utf8BytesMut {
798    fn from_iter<T: IntoIterator<Item = char>>(into_iter: T) -> Self {
799        unsafe {
800            Self::from_bytes_mut_unchecked(
801                String::from_iter(into_iter)
802                    .into_bytes()
803                    .into_iter()
804                    .collect(),
805            )
806        }
807    }
808}
809
810impl<'a> FromIterator<&'a char> for Utf8BytesMut {
811    fn from_iter<T: IntoIterator<Item = &'a char>>(into_iter: T) -> Self {
812        Self::from_iter(into_iter.into_iter().copied())
813    }
814}
815
816/*
817 *
818 * ===== PartialEq / PartialOrd =====
819 *
820 */
821
822impl PartialEq<[u8]> for Utf8BytesMut {
823    fn eq(&self, other: &[u8]) -> bool {
824        self.as_str().as_bytes() == other
825    }
826}
827
828impl PartialOrd<[u8]> for Utf8BytesMut {
829    fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
830        self.as_str().as_bytes().partial_cmp(other)
831    }
832}
833
834impl PartialEq<Utf8BytesMut> for [u8] {
835    fn eq(&self, other: &Utf8BytesMut) -> bool {
836        *other == *self
837    }
838}
839
840impl PartialOrd<Utf8BytesMut> for [u8] {
841    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
842        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other.as_bytes())
843    }
844}
845
846impl PartialEq<str> for Utf8BytesMut {
847    fn eq(&self, other: &str) -> bool {
848        &**self == other
849    }
850}
851
852impl PartialOrd<str> for Utf8BytesMut {
853    fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
854        (**self).partial_cmp(other)
855    }
856}
857
858impl PartialEq<Utf8BytesMut> for str {
859    fn eq(&self, other: &Utf8BytesMut) -> bool {
860        *other == *self
861    }
862}
863
864impl PartialOrd<Utf8BytesMut> for str {
865    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
866        <str as PartialOrd<str>>::partial_cmp(self, other)
867    }
868}
869
870impl PartialEq<Utf8BytesMut> for Vec<u8> {
871    fn eq(&self, other: &Utf8BytesMut) -> bool {
872        self == other.as_bytes()
873    }
874}
875
876impl PartialEq<Utf8BytesMut> for String {
877    fn eq(&self, other: &Utf8BytesMut) -> bool {
878        *other == *self
879    }
880}
881
882impl PartialOrd<Utf8BytesMut> for String {
883    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
884        <str as PartialOrd<str>>::partial_cmp(self, other)
885    }
886}
887
888impl PartialEq<Utf8BytesMut> for &[u8] {
889    fn eq(&self, other: &Utf8BytesMut) -> bool {
890        *self == other.as_bytes()
891    }
892}
893
894impl PartialOrd<Utf8BytesMut> for &[u8] {
895    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
896        <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other.as_bytes())
897    }
898}
899
900impl PartialEq<Utf8BytesMut> for &str {
901    fn eq(&self, other: &Utf8BytesMut) -> bool {
902        *self == other.as_str()
903    }
904}
905
906impl PartialOrd<Utf8BytesMut> for &str {
907    fn partial_cmp(&self, other: &Utf8BytesMut) -> Option<cmp::Ordering> {
908        other.partial_cmp(self)
909    }
910}
911
912impl PartialEq<Utf8BytesMut> for bytes::Bytes {
913    fn eq(&self, other: &Utf8BytesMut) -> bool {
914        self == other.as_bytes()
915    }
916}
917
918impl From<Utf8BytesMut> for String {
919    fn from(bytes: Utf8BytesMut) -> Self {
920        unsafe { Self::from_utf8_unchecked(Vec::from(bytes.inner)) }
921    }
922}