1use core::mem::{self, ManuallyDrop, MaybeUninit};
2use core::ops::{Deref, RangeBounds};
3use core::ptr::NonNull;
4use core::{cmp, fmt, hash, ptr, slice};
5
6use alloc::{
7 alloc::{dealloc, Layout},
8 borrow::Borrow,
9 boxed::Box,
10 string::String,
11 vec::Vec,
12};
13
14use crate::buf::IntoIter;
15#[allow(unused)]
16use crate::loom::sync::atomic::AtomicMut;
17use crate::loom::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
18use crate::{Buf, BytesMut};
19
20pub struct Bytes {
102 ptr: *const u8,
103 len: usize,
104 data: AtomicPtr<()>,
106 vtable: &'static Vtable,
107}
108
109pub(crate) struct Vtable {
114 pub clone: unsafe fn(&AtomicPtr<()>, *const u8, usize) -> Bytes,
116 pub into_vec: unsafe fn(*mut (), *const u8, usize) -> Vec<u8>,
120 pub into_mut: unsafe fn(*mut (), *const u8, usize) -> BytesMut,
121 pub is_unique: unsafe fn(&AtomicPtr<()>) -> bool,
123 pub drop: unsafe fn(*mut (), *const u8, usize),
125}
126
127impl Bytes {
128 #[inline]
141 #[cfg(not(all(loom, test)))]
142 pub const fn new() -> Self {
143 const EMPTY: &[u8] = &[];
146 Bytes::from_static(EMPTY)
147 }
148
149 #[cfg(all(loom, test))]
151 pub fn new() -> Self {
152 const EMPTY: &[u8] = &[];
153 Bytes::from_static(EMPTY)
154 }
155
156 #[inline]
170 #[cfg(not(all(loom, test)))]
171 pub const fn from_static(bytes: &'static [u8]) -> Self {
172 Bytes {
173 ptr: bytes.as_ptr(),
174 len: bytes.len(),
175 data: AtomicPtr::new(ptr::null_mut()),
176 vtable: &STATIC_VTABLE,
177 }
178 }
179
180 #[cfg(all(loom, test))]
182 pub fn from_static(bytes: &'static [u8]) -> Self {
183 Bytes {
184 ptr: bytes.as_ptr(),
185 len: bytes.len(),
186 data: AtomicPtr::new(ptr::null_mut()),
187 vtable: &STATIC_VTABLE,
188 }
189 }
190
191 fn new_empty_with_ptr(ptr: *const u8) -> Self {
193 debug_assert!(!ptr.is_null());
194
195 let ptr = without_provenance(ptr as usize);
198
199 Bytes {
200 ptr,
201 len: 0,
202 data: AtomicPtr::new(ptr::null_mut()),
203 vtable: &STATIC_VTABLE,
204 }
205 }
206
207 pub fn from_owner<T>(owner: T) -> Self
255 where
256 T: AsRef<[u8]> + Send + 'static,
257 {
258 let owned = Box::into_raw(Box::new(Owned {
274 ref_cnt: AtomicUsize::new(1),
275 owner,
276 }));
277
278 let mut ret = Bytes {
279 ptr: NonNull::dangling().as_ptr(),
280 len: 0,
281 data: AtomicPtr::new(owned.cast()),
282 vtable: &Owned::<T>::VTABLE,
283 };
284
285 let buf = unsafe { &*owned }.owner.as_ref();
286 ret.ptr = buf.as_ptr();
287 ret.len = buf.len();
288
289 ret
290 }
291
292 #[inline]
303 pub const fn len(&self) -> usize {
304 self.len
305 }
306
307 #[inline]
318 pub const fn is_empty(&self) -> bool {
319 self.len == 0
320 }
321
322 pub fn is_unique(&self) -> bool {
343 unsafe { (self.vtable.is_unique)(&self.data) }
344 }
345
346 pub fn copy_from_slice(data: &[u8]) -> Self {
348 data.to_vec().into()
349 }
350
351 pub fn slice(&self, range: impl RangeBounds<usize>) -> Self {
374 let (begin, end) = crate::range(range, self.len());
375
376 if end == begin {
377 return Bytes::new_empty_with_ptr(self.ptr.wrapping_add(begin));
378 }
379
380 let mut ret = self.clone();
381
382 ret.len = end - begin;
383 ret.ptr = unsafe { ret.ptr.add(begin) };
384
385 ret
386 }
387
388 pub fn slice_ref(&self, subset: &[u8]) -> Self {
417 if subset.is_empty() {
420 return Bytes::new();
421 }
422
423 let bytes_p = self.as_ptr() as usize;
424 let bytes_len = self.len();
425
426 let sub_p = subset.as_ptr() as usize;
427 let sub_len = subset.len();
428
429 assert!(
430 sub_p >= bytes_p,
431 "subset pointer ({:p}) is smaller than self pointer ({:p})",
432 subset.as_ptr(),
433 self.as_ptr(),
434 );
435 assert!(
436 sub_p + sub_len <= bytes_p + bytes_len,
437 "subset is out of bounds: self = ({:p}, {}), subset = ({:p}, {})",
438 self.as_ptr(),
439 bytes_len,
440 subset.as_ptr(),
441 sub_len,
442 );
443
444 let sub_offset = sub_p - bytes_p;
445
446 self.slice(sub_offset..(sub_offset + sub_len))
447 }
448
449 #[must_use = "consider Bytes::truncate if you don't need the other half"]
475 pub fn split_off(&mut self, at: usize) -> Self {
476 if at == self.len() {
477 return Bytes::new_empty_with_ptr(self.ptr.wrapping_add(at));
478 }
479
480 if at == 0 {
481 return mem::replace(self, Bytes::new_empty_with_ptr(self.ptr));
482 }
483
484 assert!(
485 at <= self.len(),
486 "split_off out of bounds: {:?} <= {:?}",
487 at,
488 self.len(),
489 );
490
491 let mut ret = self.clone();
492
493 self.len = at;
494
495 unsafe { ret.inc_start(at) };
498
499 ret
500 }
501
502 #[must_use = "consider Bytes::advance if you don't need the other half"]
526 pub fn split_to(&mut self, at: usize) -> Self {
527 if at == self.len() {
528 let end_ptr = self.ptr.wrapping_add(at);
529 return mem::replace(self, Bytes::new_empty_with_ptr(end_ptr));
530 }
531
532 if at == 0 {
533 return Bytes::new_empty_with_ptr(self.ptr);
534 }
535
536 assert!(
537 at <= self.len(),
538 "split_to out of bounds: {:?} <= {:?}",
539 at,
540 self.len(),
541 );
542
543 let mut ret = self.clone();
544
545 unsafe { self.inc_start(at) };
548
549 ret.len = at;
550 ret
551 }
552
553 #[inline]
572 pub fn truncate(&mut self, len: usize) {
573 if len == 0 {
574 drop(mem::replace(self, Bytes::new_empty_with_ptr(self.ptr)));
575 } else if len < self.len {
576 if self.vtable as *const Vtable == &PROMOTABLE_EVEN_VTABLE
580 || self.vtable as *const Vtable == &PROMOTABLE_ODD_VTABLE
581 {
582 drop(self.split_off(len));
583 } else {
584 self.len = len;
585 }
586 }
587 }
588
589 #[inline]
601 pub fn clear(&mut self) {
602 self.truncate(0);
603 }
604
605 pub fn try_into_mut(self) -> Result<BytesMut, Bytes> {
624 if self.is_unique() {
625 Ok(self.into())
626 } else {
627 Err(self)
628 }
629 }
630
631 #[inline]
632 pub(crate) unsafe fn with_vtable(
633 ptr: *const u8,
634 len: usize,
635 data: AtomicPtr<()>,
636 vtable: &'static Vtable,
637 ) -> Bytes {
638 Bytes {
639 ptr,
640 len,
641 data,
642 vtable,
643 }
644 }
645
646 #[inline]
649 fn as_slice(&self) -> &[u8] {
650 unsafe { slice::from_raw_parts(self.ptr, self.len) }
651 }
652
653 #[inline]
654 unsafe fn inc_start(&mut self, by: usize) {
655 debug_assert!(self.len >= by, "internal: inc_start out of bounds");
657 self.len -= by;
658 self.ptr = self.ptr.add(by);
659 }
660
661 #[inline]
662 fn data_mut(&mut self) -> *mut () {
663 self.data.with_mut(|p| *p)
664 }
665}
666
667unsafe impl Send for Bytes {}
669unsafe impl Sync for Bytes {}
670
671impl Drop for Bytes {
672 #[inline]
673 fn drop(&mut self) {
674 let data = self.data_mut();
675 unsafe { (self.vtable.drop)(data, self.ptr, self.len) }
676 }
677}
678
679impl Clone for Bytes {
680 #[inline]
681 fn clone(&self) -> Bytes {
682 unsafe { (self.vtable.clone)(&self.data, self.ptr, self.len) }
683 }
684}
685
686impl Buf for Bytes {
687 #[inline]
688 fn remaining(&self) -> usize {
689 self.len()
690 }
691
692 #[inline]
693 fn chunk(&self) -> &[u8] {
694 self.as_slice()
695 }
696
697 #[inline]
698 fn advance(&mut self, cnt: usize) {
699 assert!(
700 cnt <= self.len(),
701 "cannot advance past `remaining`: {:?} <= {:?}",
702 cnt,
703 self.len(),
704 );
705
706 unsafe {
707 self.inc_start(cnt);
708 }
709 }
710
711 fn copy_to_bytes(&mut self, len: usize) -> Self {
712 self.split_to(len)
713 }
714}
715
716impl Deref for Bytes {
717 type Target = [u8];
718
719 #[inline]
720 fn deref(&self) -> &[u8] {
721 self.as_slice()
722 }
723}
724
725impl AsRef<[u8]> for Bytes {
726 #[inline]
727 fn as_ref(&self) -> &[u8] {
728 self.as_slice()
729 }
730}
731
732impl hash::Hash for Bytes {
733 fn hash<H>(&self, state: &mut H)
734 where
735 H: hash::Hasher,
736 {
737 self.as_slice().hash(state);
738 }
739}
740
741impl Borrow<[u8]> for Bytes {
742 fn borrow(&self) -> &[u8] {
743 self.as_slice()
744 }
745}
746
747impl IntoIterator for Bytes {
748 type Item = u8;
749 type IntoIter = IntoIter<Bytes>;
750
751 fn into_iter(self) -> Self::IntoIter {
752 IntoIter::new(self)
753 }
754}
755
756impl<'a> IntoIterator for &'a Bytes {
757 type Item = &'a u8;
758 type IntoIter = core::slice::Iter<'a, u8>;
759
760 fn into_iter(self) -> Self::IntoIter {
761 self.as_slice().iter()
762 }
763}
764
765impl FromIterator<u8> for Bytes {
766 fn from_iter<T: IntoIterator<Item = u8>>(into_iter: T) -> Self {
767 Vec::from_iter(into_iter).into()
768 }
769}
770
771impl PartialEq for Bytes {
774 fn eq(&self, other: &Bytes) -> bool {
775 self.as_slice() == other.as_slice()
776 }
777}
778
779impl PartialOrd for Bytes {
780 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
781 Some(self.cmp(other))
782 }
783}
784
785impl Ord for Bytes {
786 fn cmp(&self, other: &Bytes) -> cmp::Ordering {
787 self.as_slice().cmp(other.as_slice())
788 }
789}
790
791impl Eq for Bytes {}
792
793impl PartialEq<[u8]> for Bytes {
794 fn eq(&self, other: &[u8]) -> bool {
795 self.as_slice() == other
796 }
797}
798
799impl PartialOrd<[u8]> for Bytes {
800 fn partial_cmp(&self, other: &[u8]) -> Option<cmp::Ordering> {
801 self.as_slice().partial_cmp(other)
802 }
803}
804
805impl PartialEq<Bytes> for [u8] {
806 fn eq(&self, other: &Bytes) -> bool {
807 *other == *self
808 }
809}
810
811impl PartialOrd<Bytes> for [u8] {
812 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
813 <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
814 }
815}
816
817impl PartialEq<str> for Bytes {
818 fn eq(&self, other: &str) -> bool {
819 self.as_slice() == other.as_bytes()
820 }
821}
822
823impl PartialOrd<str> for Bytes {
824 fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
825 self.as_slice().partial_cmp(other.as_bytes())
826 }
827}
828
829impl PartialEq<Bytes> for str {
830 fn eq(&self, other: &Bytes) -> bool {
831 *other == *self
832 }
833}
834
835impl PartialOrd<Bytes> for str {
836 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
837 <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
838 }
839}
840
841impl PartialEq<Vec<u8>> for Bytes {
842 fn eq(&self, other: &Vec<u8>) -> bool {
843 *self == other[..]
844 }
845}
846
847impl PartialOrd<Vec<u8>> for Bytes {
848 fn partial_cmp(&self, other: &Vec<u8>) -> Option<cmp::Ordering> {
849 self.as_slice().partial_cmp(&other[..])
850 }
851}
852
853impl PartialEq<Bytes> for Vec<u8> {
854 fn eq(&self, other: &Bytes) -> bool {
855 *other == *self
856 }
857}
858
859impl PartialOrd<Bytes> for Vec<u8> {
860 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
861 <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
862 }
863}
864
865impl PartialEq<String> for Bytes {
866 fn eq(&self, other: &String) -> bool {
867 *self == other[..]
868 }
869}
870
871impl PartialOrd<String> for Bytes {
872 fn partial_cmp(&self, other: &String) -> Option<cmp::Ordering> {
873 self.as_slice().partial_cmp(other.as_bytes())
874 }
875}
876
877impl PartialEq<Bytes> for String {
878 fn eq(&self, other: &Bytes) -> bool {
879 *other == *self
880 }
881}
882
883impl PartialOrd<Bytes> for String {
884 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
885 <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
886 }
887}
888
889impl PartialEq<Bytes> for &[u8] {
890 fn eq(&self, other: &Bytes) -> bool {
891 *other == *self
892 }
893}
894
895impl PartialOrd<Bytes> for &[u8] {
896 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
897 <[u8] as PartialOrd<[u8]>>::partial_cmp(self, other)
898 }
899}
900
901impl PartialEq<Bytes> for &str {
902 fn eq(&self, other: &Bytes) -> bool {
903 *other == *self
904 }
905}
906
907impl PartialOrd<Bytes> for &str {
908 fn partial_cmp(&self, other: &Bytes) -> Option<cmp::Ordering> {
909 <[u8] as PartialOrd<[u8]>>::partial_cmp(self.as_bytes(), other)
910 }
911}
912
913impl<'a, T: ?Sized> PartialEq<&'a T> for Bytes
914where
915 Bytes: PartialEq<T>,
916{
917 fn eq(&self, other: &&'a T) -> bool {
918 *self == **other
919 }
920}
921
922impl<'a, T: ?Sized> PartialOrd<&'a T> for Bytes
923where
924 Bytes: PartialOrd<T>,
925{
926 fn partial_cmp(&self, other: &&'a T) -> Option<cmp::Ordering> {
927 self.partial_cmp(&**other)
928 }
929}
930
931impl Default for Bytes {
934 #[inline]
935 fn default() -> Bytes {
936 Bytes::new()
937 }
938}
939
940impl From<&'static [u8]> for Bytes {
941 fn from(slice: &'static [u8]) -> Bytes {
942 Bytes::from_static(slice)
943 }
944}
945
946impl From<&'static str> for Bytes {
947 fn from(slice: &'static str) -> Bytes {
948 Bytes::from_static(slice.as_bytes())
949 }
950}
951
952impl From<Vec<u8>> for Bytes {
953 fn from(vec: Vec<u8>) -> Bytes {
954 if vec.len() == vec.capacity() {
956 return Bytes::from(vec.into_boxed_slice());
957 }
958
959 let shared = Box::new(MaybeUninit::<Shared>::uninit());
960 let mut vec = ManuallyDrop::new(vec);
961 let ptr = vec.as_mut_ptr();
962 let len = vec.len();
963 let cap = vec.capacity();
964
965 let shared = Shared::init_to_raw(
966 shared,
967 Shared {
968 buf: ptr,
969 cap,
970 ref_cnt: AtomicUsize::new(1),
971 },
972 );
973
974 debug_assert!(
977 0 == (shared as usize & KIND_MASK),
978 "internal: Box<Shared> should have an aligned pointer",
979 );
980 Bytes {
981 ptr,
982 len,
983 data: AtomicPtr::new(shared as _),
984 vtable: &SHARED_VTABLE,
985 }
986 }
987}
988
989impl From<Box<[u8]>> for Bytes {
990 fn from(slice: Box<[u8]>) -> Bytes {
991 if slice.is_empty() {
995 return Bytes::new();
996 }
997
998 let len = slice.len();
999 let ptr = Box::into_raw(slice) as *mut u8;
1000
1001 if ptr as usize & 0x1 == 0 {
1002 let data = ptr_map(ptr, |addr| addr | KIND_VEC);
1003 Bytes {
1004 ptr,
1005 len,
1006 data: AtomicPtr::new(data.cast()),
1007 vtable: &PROMOTABLE_EVEN_VTABLE,
1008 }
1009 } else {
1010 Bytes {
1011 ptr,
1012 len,
1013 data: AtomicPtr::new(ptr.cast()),
1014 vtable: &PROMOTABLE_ODD_VTABLE,
1015 }
1016 }
1017 }
1018}
1019
1020impl From<Bytes> for BytesMut {
1021 fn from(bytes: Bytes) -> Self {
1037 let mut bytes = ManuallyDrop::new(bytes);
1038 let data = bytes.data_mut();
1039 unsafe { (bytes.vtable.into_mut)(data, bytes.ptr, bytes.len) }
1040 }
1041}
1042
1043impl From<String> for Bytes {
1044 fn from(s: String) -> Bytes {
1045 Bytes::from(s.into_bytes())
1046 }
1047}
1048
1049impl From<Bytes> for Vec<u8> {
1050 fn from(bytes: Bytes) -> Vec<u8> {
1051 let mut bytes = ManuallyDrop::new(bytes);
1052 let data = bytes.data_mut();
1053 unsafe { (bytes.vtable.into_vec)(data, bytes.ptr, bytes.len) }
1054 }
1055}
1056
1057impl fmt::Debug for Vtable {
1060 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1061 f.debug_struct("Vtable")
1062 .field("clone", &(self.clone as *const ()))
1063 .field("drop", &(self.drop as *const ()))
1064 .finish()
1065 }
1066}
1067
1068const STATIC_VTABLE: Vtable = Vtable {
1071 clone: static_clone,
1072 into_vec: static_to_vec,
1073 into_mut: static_to_mut,
1074 is_unique: static_is_unique,
1075 drop: static_drop,
1076};
1077
1078unsafe fn static_clone(_: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1079 let slice = slice::from_raw_parts(ptr, len);
1080 Bytes::from_static(slice)
1081}
1082
1083unsafe fn static_to_vec(_: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1084 let slice = slice::from_raw_parts(ptr, len);
1085 slice.to_vec()
1086}
1087
1088unsafe fn static_to_mut(_: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1089 let slice = slice::from_raw_parts(ptr, len);
1090 BytesMut::from(slice)
1091}
1092
1093fn static_is_unique(_: &AtomicPtr<()>) -> bool {
1094 false
1095}
1096
1097unsafe fn static_drop(_: *mut (), _: *const u8, _: usize) {
1098 }
1100
1101#[repr(C)]
1104struct Owned<T> {
1105 ref_cnt: AtomicUsize,
1106 owner: T,
1107}
1108
1109impl<T> Owned<T> {
1110 const VTABLE: Vtable = Vtable {
1111 clone: owned_clone::<T>,
1112 into_vec: owned_to_vec::<T>,
1113 into_mut: owned_to_mut::<T>,
1114 is_unique: owned_is_unique,
1115 drop: owned_drop::<T>,
1116 };
1117}
1118
1119unsafe fn owned_clone<T>(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1120 let owned = data.load(Ordering::Relaxed);
1121 let old_cnt = (*owned.cast::<AtomicUsize>()).fetch_add(1, Ordering::Relaxed);
1122 if old_cnt > usize::MAX >> 1 {
1123 crate::abort();
1124 }
1125
1126 Bytes {
1127 ptr,
1128 len,
1129 data: AtomicPtr::new(owned as _),
1130 vtable: &Owned::<T>::VTABLE,
1131 }
1132}
1133
1134unsafe fn owned_to_vec<T>(owned: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1135 let slice = slice::from_raw_parts(ptr, len);
1136 let vec = slice.to_vec();
1137 owned_drop_impl::<T>(owned);
1138 vec
1139}
1140
1141unsafe fn owned_to_mut<T>(owned: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1142 BytesMut::from_vec(owned_to_vec::<T>(owned, ptr, len))
1143}
1144
1145unsafe fn owned_is_unique(_data: &AtomicPtr<()>) -> bool {
1146 false
1147}
1148
1149unsafe fn owned_drop_impl<T>(owned: *mut ()) {
1150 {
1151 let ref_cnt = &*owned.cast::<AtomicUsize>();
1152
1153 let old_cnt = ref_cnt.fetch_sub(1, Ordering::Release);
1154 debug_assert!(
1155 old_cnt > 0 && old_cnt <= usize::MAX >> 1,
1156 "expected non-zero refcount and no underflow"
1157 );
1158 if old_cnt != 1 {
1159 return;
1160 }
1161 ref_cnt.load(Ordering::Acquire);
1162 }
1163
1164 drop(Box::<Owned<T>>::from_raw(owned.cast()));
1165}
1166
1167unsafe fn owned_drop<T>(data: *mut (), _ptr: *const u8, _len: usize) {
1168 owned_drop_impl::<T>(data);
1169}
1170
1171static PROMOTABLE_EVEN_VTABLE: Vtable = Vtable {
1174 clone: promotable_even_clone,
1175 into_vec: promotable_even_to_vec,
1176 into_mut: promotable_even_to_mut,
1177 is_unique: promotable_is_unique,
1178 drop: promotable_even_drop,
1179};
1180
1181static PROMOTABLE_ODD_VTABLE: Vtable = Vtable {
1182 clone: promotable_odd_clone,
1183 into_vec: promotable_odd_to_vec,
1184 into_mut: promotable_odd_to_mut,
1185 is_unique: promotable_is_unique,
1186 drop: promotable_odd_drop,
1187};
1188
1189unsafe fn promotable_even_clone(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1190 let shared = data.load(Ordering::Acquire);
1191 let kind = shared as usize & KIND_MASK;
1192
1193 if kind == KIND_ARC {
1194 shallow_clone_arc(shared.cast(), ptr, len)
1195 } else {
1196 debug_assert_eq!(kind, KIND_VEC);
1197 let buf = ptr_map(shared.cast(), |addr| addr & !KIND_MASK);
1198 shallow_clone_vec(data, shared, buf, ptr, len)
1199 }
1200}
1201
1202unsafe fn promotable_to_vec(
1203 shared: *mut (),
1204 ptr: *const u8,
1205 len: usize,
1206 f: fn(*mut ()) -> *mut u8,
1207) -> Vec<u8> {
1208 let kind = shared as usize & KIND_MASK;
1209
1210 if kind == KIND_ARC {
1211 shared_to_vec_impl(shared.cast(), ptr, len)
1212 } else {
1213 debug_assert_eq!(kind, KIND_VEC);
1215
1216 let buf = f(shared);
1217
1218 let cap = ptr.offset_from(buf) as usize + len;
1219
1220 ptr::copy(ptr, buf, len);
1222
1223 Vec::from_raw_parts(buf, len, cap)
1224 }
1225}
1226
1227unsafe fn promotable_to_mut(
1228 shared: *mut (),
1229 ptr: *const u8,
1230 len: usize,
1231 f: fn(*mut ()) -> *mut u8,
1232) -> BytesMut {
1233 let kind = shared as usize & KIND_MASK;
1234
1235 if kind == KIND_ARC {
1236 shared_to_mut_impl(shared.cast(), ptr, len)
1237 } else {
1238 debug_assert_eq!(kind, KIND_VEC);
1243
1244 let buf = f(shared);
1245 let off = ptr.offset_from(buf) as usize;
1246 let cap = off + len;
1247 let v = Vec::from_raw_parts(buf, cap, cap);
1248
1249 let mut b = BytesMut::from_vec(v);
1250 b.advance_unchecked(off);
1251 b
1252 }
1253}
1254
1255unsafe fn promotable_even_to_vec(shared: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1256 promotable_to_vec(shared, ptr, len, |shared| {
1257 ptr_map(shared.cast(), |addr| addr & !KIND_MASK)
1258 })
1259}
1260
1261unsafe fn promotable_even_to_mut(shared: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1262 promotable_to_mut(shared, ptr, len, |shared| {
1263 ptr_map(shared.cast(), |addr| addr & !KIND_MASK)
1264 })
1265}
1266
1267unsafe fn promotable_even_drop(shared: *mut (), ptr: *const u8, len: usize) {
1268 let kind = shared as usize & KIND_MASK;
1269
1270 if kind == KIND_ARC {
1271 release_shared(shared.cast());
1272 } else {
1273 debug_assert_eq!(kind, KIND_VEC);
1274 let buf = ptr_map(shared.cast(), |addr| addr & !KIND_MASK);
1275 free_boxed_slice(buf, ptr, len);
1276 }
1277}
1278
1279unsafe fn promotable_odd_clone(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1280 let shared = data.load(Ordering::Acquire);
1281 let kind = shared as usize & KIND_MASK;
1282
1283 if kind == KIND_ARC {
1284 shallow_clone_arc(shared as _, ptr, len)
1285 } else {
1286 debug_assert_eq!(kind, KIND_VEC);
1287 shallow_clone_vec(data, shared, shared.cast(), ptr, len)
1288 }
1289}
1290
1291unsafe fn promotable_odd_to_vec(shared: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1292 promotable_to_vec(shared, ptr, len, |shared| shared.cast())
1293}
1294
1295unsafe fn promotable_odd_to_mut(shared: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1296 promotable_to_mut(shared, ptr, len, |shared| shared.cast())
1297}
1298
1299unsafe fn promotable_odd_drop(shared: *mut (), ptr: *const u8, len: usize) {
1300 let kind = shared as usize & KIND_MASK;
1301
1302 if kind == KIND_ARC {
1303 release_shared(shared.cast());
1304 } else {
1305 debug_assert_eq!(kind, KIND_VEC);
1306
1307 free_boxed_slice(shared.cast(), ptr, len);
1308 }
1309}
1310
1311unsafe fn promotable_is_unique(data: &AtomicPtr<()>) -> bool {
1312 let shared = data.load(Ordering::Acquire);
1313 let kind = shared as usize & KIND_MASK;
1314
1315 if kind == KIND_ARC {
1316 let ref_cnt = (*shared.cast::<Shared>()).ref_cnt.load(Ordering::Relaxed);
1317 ref_cnt == 1
1318 } else {
1319 true
1320 }
1321}
1322
1323unsafe fn free_boxed_slice(buf: *mut u8, offset: *const u8, len: usize) {
1324 let cap = offset.offset_from(buf) as usize + len;
1325 dealloc(buf, Layout::from_size_align(cap, 1).unwrap())
1326}
1327
1328struct Shared {
1331 buf: *mut u8,
1333 cap: usize,
1334 ref_cnt: AtomicUsize,
1335}
1336
1337impl Shared {
1338 fn init_to_raw(b: Box<MaybeUninit<Self>>, v: Self) -> *mut Self {
1339 let shared = Box::into_raw(b).cast::<Self>();
1340 unsafe { shared.write(v) };
1342 shared
1343 }
1344}
1345
1346impl Drop for Shared {
1347 fn drop(&mut self) {
1348 unsafe { dealloc(self.buf, Layout::from_size_align(self.cap, 1).unwrap()) }
1349 }
1350}
1351
1352const _: () = {
1357 assert!(
1358 mem::align_of::<Shared>() % 2 == 0,
1359 "Shared alignment must be divisible by 2 for pointer tagging"
1360 );
1361};
1362
1363static SHARED_VTABLE: Vtable = Vtable {
1364 clone: shared_clone,
1365 into_vec: shared_to_vec,
1366 into_mut: shared_to_mut,
1367 is_unique: shared_is_unique,
1368 drop: shared_drop,
1369};
1370
1371const KIND_ARC: usize = 0b0;
1372const KIND_VEC: usize = 0b1;
1373const KIND_MASK: usize = 0b1;
1374
1375unsafe fn shared_clone(data: &AtomicPtr<()>, ptr: *const u8, len: usize) -> Bytes {
1376 let shared = data.load(Ordering::Relaxed);
1377 shallow_clone_arc(shared as _, ptr, len)
1378}
1379
1380unsafe fn shared_to_vec_impl(shared: *mut Shared, ptr: *const u8, len: usize) -> Vec<u8> {
1381 if (*shared)
1388 .ref_cnt
1389 .compare_exchange(1, 0, Ordering::AcqRel, Ordering::Relaxed)
1390 .is_ok()
1391 {
1392 let shared = *Box::from_raw(shared);
1394 let shared = ManuallyDrop::new(shared);
1395 let buf = shared.buf;
1396 let cap = shared.cap;
1397
1398 ptr::copy(ptr, buf, len);
1400
1401 Vec::from_raw_parts(buf, len, cap)
1402 } else {
1403 let v = slice::from_raw_parts(ptr, len).to_vec();
1404 release_shared(shared);
1405 v
1406 }
1407}
1408
1409unsafe fn shared_to_vec(shared: *mut (), ptr: *const u8, len: usize) -> Vec<u8> {
1410 shared_to_vec_impl(shared.cast(), ptr, len)
1411}
1412
1413unsafe fn shared_to_mut_impl(shared: *mut Shared, ptr: *const u8, len: usize) -> BytesMut {
1414 if (*shared).ref_cnt.load(Ordering::Acquire) == 1 {
1427 let shared = *Box::from_raw(shared);
1429 let shared = ManuallyDrop::new(shared);
1430 let buf = shared.buf;
1431 let cap = shared.cap;
1432
1433 let off = ptr.offset_from(buf) as usize;
1435 let v = Vec::from_raw_parts(buf, len + off, cap);
1436
1437 let mut b = BytesMut::from_vec(v);
1438 b.advance_unchecked(off);
1439 b
1440 } else {
1441 let v = slice::from_raw_parts(ptr, len).to_vec();
1443 release_shared(shared);
1444 BytesMut::from_vec(v)
1445 }
1446}
1447
1448unsafe fn shared_to_mut(shared: *mut (), ptr: *const u8, len: usize) -> BytesMut {
1449 shared_to_mut_impl(shared.cast(), ptr, len)
1450}
1451
1452pub(crate) unsafe fn shared_is_unique(data: &AtomicPtr<()>) -> bool {
1453 let shared = data.load(Ordering::Acquire);
1454 let ref_cnt = (*shared.cast::<Shared>()).ref_cnt.load(Ordering::Relaxed);
1455 ref_cnt == 1
1456}
1457
1458unsafe fn shared_drop(shared: *mut (), _ptr: *const u8, _len: usize) {
1459 release_shared(shared.cast());
1460}
1461
1462unsafe fn shallow_clone_arc(shared: *mut Shared, ptr: *const u8, len: usize) -> Bytes {
1463 let old_size = (*shared).ref_cnt.fetch_add(1, Ordering::Relaxed);
1464
1465 if old_size > usize::MAX >> 1 {
1466 crate::abort();
1467 }
1468
1469 Bytes {
1470 ptr,
1471 len,
1472 data: AtomicPtr::new(shared as _),
1473 vtable: &SHARED_VTABLE,
1474 }
1475}
1476
1477#[cold]
1478unsafe fn shallow_clone_vec(
1479 atom: &AtomicPtr<()>,
1480 ptr: *const (),
1481 buf: *mut u8,
1482 offset: *const u8,
1483 len: usize,
1484) -> Bytes {
1485 let shared = Box::new(MaybeUninit::<Shared>::uninit());
1497 let shared = Shared::init_to_raw(
1498 shared,
1499 Shared {
1500 buf,
1501 cap: offset.offset_from(buf) as usize + len,
1502 ref_cnt: AtomicUsize::new(2),
1506 },
1507 );
1508
1509 debug_assert!(
1512 0 == (shared as usize & KIND_MASK),
1513 "internal: Box<Shared> should have an aligned pointer",
1514 );
1515
1516 match atom.compare_exchange(ptr as _, shared as _, Ordering::AcqRel, Ordering::Acquire) {
1526 Ok(actual) => {
1527 debug_assert!(core::ptr::eq(actual, ptr));
1528 Bytes {
1531 ptr: offset,
1532 len,
1533 data: AtomicPtr::new(shared as _),
1534 vtable: &SHARED_VTABLE,
1535 }
1536 }
1537 Err(actual) => {
1538 let shared = Box::from_raw(shared);
1542 mem::forget(*shared);
1543
1544 shallow_clone_arc(actual as _, offset, len)
1547 }
1548 }
1549}
1550
1551unsafe fn release_shared(ptr: *mut Shared) {
1552 if (*ptr).ref_cnt.fetch_sub(1, Ordering::Release) != 1 {
1554 return;
1555 }
1556
1557 (*ptr).ref_cnt.load(Ordering::Acquire);
1578
1579 drop(Box::from_raw(ptr));
1581}
1582
1583#[cfg(miri)]
1590fn ptr_map<F>(ptr: *mut u8, f: F) -> *mut u8
1591where
1592 F: FnOnce(usize) -> usize,
1593{
1594 let old_addr = ptr as usize;
1595 let new_addr = f(old_addr);
1596 let diff = new_addr.wrapping_sub(old_addr);
1597 ptr.wrapping_add(diff)
1598}
1599
1600#[cfg(not(miri))]
1601fn ptr_map<F>(ptr: *mut u8, f: F) -> *mut u8
1602where
1603 F: FnOnce(usize) -> usize,
1604{
1605 let old_addr = ptr as usize;
1606 let new_addr = f(old_addr);
1607 new_addr as *mut u8
1608}
1609
1610fn without_provenance(ptr: usize) -> *const u8 {
1611 core::ptr::null::<u8>().wrapping_add(ptr)
1612}
1613
1614fn _split_to_must_use() {}
1625
1626fn _split_off_must_use() {}
1635
1636#[cfg(all(test, loom))]
1638mod fuzz {
1639 use loom::sync::Arc;
1640 use loom::thread;
1641
1642 use super::Bytes;
1643 #[test]
1644 fn bytes_cloning_vec() {
1645 loom::model(|| {
1646 let a = Bytes::from(b"abcdefgh".to_vec());
1647 let addr = a.as_ptr() as usize;
1648
1649 let a1 = Arc::new(a);
1651 let a2 = a1.clone();
1652
1653 let t1 = thread::spawn(move || {
1654 let b: Bytes = (*a1).clone();
1655 assert_eq!(b.as_ptr() as usize, addr);
1656 });
1657
1658 let t2 = thread::spawn(move || {
1659 let b: Bytes = (*a2).clone();
1660 assert_eq!(b.as_ptr() as usize, addr);
1661 });
1662
1663 t1.join().unwrap();
1664 t2.join().unwrap();
1665 });
1666 }
1667}