Debian Codegraph @

tests/test_bytes.rs

raw
1 #![warn(rust_2018_idioms)]
2
3 use bytes::{Buf, BufMut, Bytes, BytesMut};
4 use std::sync::atomic::{AtomicUsize, Ordering};
5 use std::sync::Arc;
6
7 use std::panic::{self, AssertUnwindSafe};
8
9 const LONG: &[u8] = b"mary had a little lamb, little lamb, little lamb";
10 const SHORT: &[u8] = b"hello world";
11
12 fn is_sync<T: Sync>() {}
13 fn is_send<T: Send>() {}
14
15 #[test]
16 fn test_bounds() {
17 is_sync::<Bytes>();
18 is_sync::<BytesMut>();
19 is_send::<Bytes>();
20 is_send::<BytesMut>();
21 }
22
23 #[test]
24 fn test_layout() {
25 use std::mem;
26
27 assert_eq!(
28 mem::size_of::<Bytes>(),
29 mem::size_of::<usize>() * 4,
30 "Bytes size should be 4 words",
31 );
32 assert_eq!(
33 mem::size_of::<BytesMut>(),
34 mem::size_of::<usize>() * 4,
35 "BytesMut should be 4 words",
36 );
37
38 assert_eq!(
39 mem::size_of::<Bytes>(),
40 mem::size_of::<Option<Bytes>>(),
41 "Bytes should be same size as Option<Bytes>",
42 );
43
44 assert_eq!(
45 mem::size_of::<BytesMut>(),
46 mem::size_of::<Option<BytesMut>>(),
47 "BytesMut should be same size as Option<BytesMut>",
48 );
49 }
50
51 #[test]
52 fn from_slice() {
53 let a = Bytes::from(&b"abcdefgh"[..]);
54 assert_eq!(a, b"abcdefgh"[..]);
55 assert_eq!(a, &b"abcdefgh"[..]);
56 assert_eq!(a, Vec::from(&b"abcdefgh"[..]));
57 assert_eq!(b"abcdefgh"[..], a);
58 assert_eq!(&b"abcdefgh"[..], a);
59 assert_eq!(Vec::from(&b"abcdefgh"[..]), a);
60
61 let a = BytesMut::from(&b"abcdefgh"[..]);
62 assert_eq!(a, b"abcdefgh"[..]);
63 assert_eq!(a, &b"abcdefgh"[..]);
64 assert_eq!(a, Vec::from(&b"abcdefgh"[..]));
65 assert_eq!(b"abcdefgh"[..], a);
66 assert_eq!(&b"abcdefgh"[..], a);
67 assert_eq!(Vec::from(&b"abcdefgh"[..]), a);
68 }
69
70 #[test]
71 fn fmt() {
72 let a = format!("{:?}", Bytes::from(&b"abcdefg"[..]));
73 let b = "b\"abcdefg\"";
74
75 assert_eq!(a, b);
76
77 let a = format!("{:?}", BytesMut::from(&b"abcdefg"[..]));
78 assert_eq!(a, b);
79 }
80
81 #[test]
82 fn fmt_write() {
83 use std::fmt::Write;
84 let s = String::from_iter((0..10).map(|_| "abcdefg"));
85
86 let mut a = BytesMut::with_capacity(64);
87 write!(a, "{}", &s[..64]).unwrap();
88 assert_eq!(a, s[..64].as_bytes());
89
90 let mut b = BytesMut::with_capacity(64);
91 write!(b, "{}", &s[..32]).unwrap();
92 write!(b, "{}", &s[32..64]).unwrap();
93 assert_eq!(b, s[..64].as_bytes());
94
95 let mut c = BytesMut::with_capacity(64);
96 write!(c, "{}", s).unwrap();
97 assert_eq!(c, s[..].as_bytes());
98 }
99
100 #[test]
101 fn len() {
102 let a = Bytes::from(&b"abcdefg"[..]);
103 assert_eq!(a.len(), 7);
104
105 let a = BytesMut::from(&b"abcdefg"[..]);
106 assert_eq!(a.len(), 7);
107
108 let a = Bytes::from(&b""[..]);
109 assert!(a.is_empty());
110
111 let a = BytesMut::from(&b""[..]);
112 assert!(a.is_empty());
113 }
114
115 #[test]
116 fn index() {
117 let a = Bytes::from(&b"hello world"[..]);
118 assert_eq!(a[0..5], *b"hello");
119 }
120
121 #[test]
122 fn slice() {
123 let a = Bytes::from(&b"hello world"[..]);
124
125 let b = a.slice(3..5);
126 assert_eq!(b, b"lo"[..]);
127
128 let b = a.slice(0..0);
129 assert_eq!(b, b""[..]);
130
131 let b = a.slice(3..3);
132 assert_eq!(b, b""[..]);
133
134 let b = a.slice(a.len()..a.len());
135 assert_eq!(b, b""[..]);
136
137 let b = a.slice(..5);
138 assert_eq!(b, b"hello"[..]);
139
140 let b = a.slice(3..);
141 assert_eq!(b, b"lo world"[..]);
142 }
143
144 #[test]
145 #[should_panic]
146 fn slice_oob_1() {
147 let a = Bytes::from(&b"hello world"[..]);
148 a.slice(5..44);
149 }
150
151 #[test]
152 #[should_panic]
153 fn slice_oob_2() {
154 let a = Bytes::from(&b"hello world"[..]);
155 a.slice(44..49);
156 }
157
158 #[test]
159 #[should_panic]
160 fn slice_start_greater_than_end() {
161 let a = Bytes::from(&b"hello world"[..]);
162 a.slice(5..3);
163 }
164
165 #[test]
166 fn split_off() {
167 let mut hello = Bytes::from(&b"helloworld"[..]);
168 let world = hello.split_off(5);
169
170 assert_eq!(hello, &b"hello"[..]);
171 assert_eq!(world, &b"world"[..]);
172
173 let mut hello = BytesMut::from(&b"helloworld"[..]);
174 let world = hello.split_off(5);
175
176 assert_eq!(hello, &b"hello"[..]);
177 assert_eq!(world, &b"world"[..]);
178 }
179
180 #[test]
181 #[should_panic]
182 fn split_off_oob() {
183 let mut hello = Bytes::from(&b"helloworld"[..]);
184 let _ = hello.split_off(44);
185 }
186
187 #[test]
188 #[should_panic = "split_off out of bounds"]
189 fn bytes_mut_split_off_oob() {
190 let mut hello = BytesMut::from(&b"helloworld"[..]);
191 let _ = hello.split_off(44);
192 }
193
194 #[test]
195 fn split_off_uninitialized() {
196 let mut bytes = BytesMut::with_capacity(1024);
197 let other = bytes.split_off(128);
198
199 assert_eq!(bytes.len(), 0);
200 assert_eq!(bytes.capacity(), 128);
201
202 assert_eq!(other.len(), 0);
203 assert_eq!(other.capacity(), 896);
204 }
205
206 #[test]
207 fn split_off_to_loop() {
208 let s = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
209
210 for i in 0..(s.len() + 1) {
211 {
212 let mut bytes = Bytes::from(&s[..]);
213 let off = bytes.split_off(i);
214 assert_eq!(i, bytes.len());
215 let mut sum = Vec::new();
216 sum.extend(bytes.iter());
217 sum.extend(off.iter());
218 assert_eq!(&s[..], &sum[..]);
219 }
220 {
221 let mut bytes = BytesMut::from(&s[..]);
222 let off = bytes.split_off(i);
223 assert_eq!(i, bytes.len());
224 let mut sum = Vec::new();
225 sum.extend(&bytes);
226 sum.extend(&off);
227 assert_eq!(&s[..], &sum[..]);
228 }
229 {
230 let mut bytes = Bytes::from(&s[..]);
231 let off = bytes.split_to(i);
232 assert_eq!(i, off.len());
233 let mut sum = Vec::new();
234 sum.extend(off.iter());
235 sum.extend(bytes.iter());
236 assert_eq!(&s[..], &sum[..]);
237 }
238 {
239 let mut bytes = BytesMut::from(&s[..]);
240 let off = bytes.split_to(i);
241 assert_eq!(i, off.len());
242 let mut sum = Vec::new();
243 sum.extend(&off);
244 sum.extend(&bytes);
245 assert_eq!(&s[..], &sum[..]);
246 }
247 }
248 }
249
250 #[test]
251 fn split_to_1() {
252 // Static
253 let mut a = Bytes::from_static(SHORT);
254 let b = a.split_to(4);
255
256 assert_eq!(SHORT[4..], a);
257 assert_eq!(SHORT[..4], b);
258
259 // Allocated
260 let mut a = Bytes::copy_from_slice(LONG);
261 let b = a.split_to(4);
262
263 assert_eq!(LONG[4..], a);
264 assert_eq!(LONG[..4], b);
265
266 let mut a = Bytes::copy_from_slice(LONG);
267 let b = a.split_to(30);
268
269 assert_eq!(LONG[30..], a);
270 assert_eq!(LONG[..30], b);
271 }
272
273 #[test]
274 fn split_to_2() {
275 let mut a = Bytes::from(LONG);
276 assert_eq!(LONG, a);
277
278 let b = a.split_to(1);
279
280 assert_eq!(LONG[1..], a);
281 drop(b);
282 }
283
284 #[test]
285 #[should_panic]
286 fn split_to_oob() {
287 let mut hello = Bytes::from(&b"helloworld"[..]);
288 let _ = hello.split_to(33);
289 }
290
291 #[test]
292 #[should_panic]
293 fn split_to_oob_mut() {
294 let mut hello = BytesMut::from(&b"helloworld"[..]);
295 let _ = hello.split_to(33);
296 }
297
298 #[test]
299 #[should_panic]
300 fn split_to_uninitialized() {
301 let mut bytes = BytesMut::with_capacity(1024);
302 let _other = bytes.split_to(128);
303 }
304
305 #[test]
306 #[cfg_attr(not(panic = "unwind"), ignore)]
307 fn split_off_to_at_gt_len() {
308 fn make_bytes() -> Bytes {
309 let mut bytes = BytesMut::with_capacity(100);
310 bytes.put_slice(&[10, 20, 30, 40]);
311 bytes.freeze()
312 }
313
314 use std::panic;
315
316 let _ = make_bytes().split_to(4);
317 let _ = make_bytes().split_off(4);
318
319 assert!(panic::catch_unwind(move || {
320 let _ = make_bytes().split_to(5);
321 })
322 .is_err());
323
324 assert!(panic::catch_unwind(move || {
325 let _ = make_bytes().split_off(5);
326 })
327 .is_err());
328 }
329
330 #[test]
331 fn truncate() {
332 let s = &b"helloworld"[..];
333 let mut hello = Bytes::from(s);
334 hello.truncate(15);
335 assert_eq!(hello, s);
336 hello.truncate(10);
337 assert_eq!(hello, s);
338 hello.truncate(5);
339 assert_eq!(hello, "hello");
340 }
341
342 #[test]
343 fn freeze_clone_shared() {
344 let s = &b"abcdefgh"[..];
345 let b = BytesMut::from(s).split().freeze();
346 assert_eq!(b, s);
347 let c = b.clone();
348 assert_eq!(c, s);
349 }
350
351 #[test]
352 fn freeze_clone_unique() {
353 let s = &b"abcdefgh"[..];
354 let b = BytesMut::from(s).freeze();
355 assert_eq!(b, s);
356 let c = b.clone();
357 assert_eq!(c, s);
358 }
359
360 #[test]
361 fn freeze_after_advance() {
362 let s = &b"abcdefgh"[..];
363 let mut b = BytesMut::from(s);
364 b.advance(1);
365 assert_eq!(b, s[1..]);
366 let b = b.freeze();
367 // Verify fix for #352. Previously, freeze would ignore the start offset
368 // for BytesMuts in Vec mode.
369 assert_eq!(b, s[1..]);
370 }
371
372 #[test]
373 fn freeze_after_advance_arc() {
374 let s = &b"abcdefgh"[..];
375 let mut b = BytesMut::from(s);
376 // Make b Arc
377 let _ = b.split_to(0);
378 b.advance(1);
379 assert_eq!(b, s[1..]);
380 let b = b.freeze();
381 assert_eq!(b, s[1..]);
382 }
383
384 #[test]
385 fn freeze_after_split_to() {
386 let s = &b"abcdefgh"[..];
387 let mut b = BytesMut::from(s);
388 let _ = b.split_to(1);
389 assert_eq!(b, s[1..]);
390 let b = b.freeze();
391 assert_eq!(b, s[1..]);
392 }
393
394 #[test]
395 fn freeze_after_truncate() {
396 let s = &b"abcdefgh"[..];
397 let mut b = BytesMut::from(s);
398 b.truncate(7);
399 assert_eq!(b, s[..7]);
400 let b = b.freeze();
401 assert_eq!(b, s[..7]);
402 }
403
404 #[test]
405 fn freeze_after_truncate_arc() {
406 let s = &b"abcdefgh"[..];
407 let mut b = BytesMut::from(s);
408 // Make b Arc
409 let _ = b.split_to(0);
410 b.truncate(7);
411 assert_eq!(b, s[..7]);
412 let b = b.freeze();
413 assert_eq!(b, s[..7]);
414 }
415
416 #[test]
417 fn freeze_after_split_off() {
418 let s = &b"abcdefgh"[..];
419 let mut b = BytesMut::from(s);
420 let _ = b.split_off(7);
421 assert_eq!(b, s[..7]);
422 let b = b.freeze();
423 assert_eq!(b, s[..7]);
424 }
425
426 #[test]
427 fn fns_defined_for_bytes_mut() {
428 let mut bytes = BytesMut::from(&b"hello world"[..]);
429
430 let _ = bytes.as_ptr();
431 let _ = bytes.as_mut_ptr();
432
433 // Iterator
434 let v: Vec<u8> = bytes.as_ref().iter().cloned().collect();
435 assert_eq!(&v[..], bytes);
436 }
437
438 #[test]
439 fn reserve_convert() {
440 // Vec -> Vec
441 let mut bytes = BytesMut::from(LONG);
442 bytes.reserve(64);
443 assert_eq!(bytes.capacity(), LONG.len() + 64);
444
445 // Arc -> Vec
446 let mut bytes = BytesMut::from(LONG);
447 let a = bytes.split_to(30);
448
449 bytes.reserve(128);
450 assert!(bytes.capacity() >= bytes.len() + 128);
451
452 drop(a);
453 }
454
455 #[test]
456 fn reserve_growth() {
457 let mut bytes = BytesMut::with_capacity(64);
458 bytes.put("hello world".as_bytes());
459 let _ = bytes.split();
460
461 bytes.reserve(65);
462 assert_eq!(bytes.capacity(), 117);
463 }
464
465 #[test]
466 fn reserve_allocates_at_least_original_capacity() {
467 let mut bytes = BytesMut::with_capacity(1024);
468
469 for i in 0..1020 {
470 bytes.put_u8(i as u8);
471 }
472
473 let _other = bytes.split();
474
475 bytes.reserve(16);
476 assert_eq!(bytes.capacity(), 1024);
477 }
478
479 #[test]
480 #[cfg_attr(miri, ignore)] // Miri is too slow
481 fn reserve_max_original_capacity_value() {
482 const SIZE: usize = 128 * 1024;
483
484 let mut bytes = BytesMut::with_capacity(SIZE);
485
486 for _ in 0..SIZE {
487 bytes.put_u8(0u8);
488 }
489
490 let _other = bytes.split();
491
492 bytes.reserve(16);
493 assert_eq!(bytes.capacity(), 64 * 1024);
494 }
495
496 #[test]
497 fn reserve_vec_recycling() {
498 let mut bytes = BytesMut::with_capacity(16);
499 assert_eq!(bytes.capacity(), 16);
500 let addr = bytes.as_ptr() as usize;
501 bytes.put("0123456789012345".as_bytes());
502 assert_eq!(bytes.as_ptr() as usize, addr);
503 bytes.advance(10);
504 assert_eq!(bytes.capacity(), 6);
505 bytes.reserve(8);
506 assert_eq!(bytes.capacity(), 16);
507 assert_eq!(bytes.as_ptr() as usize, addr);
508 }
509
510 #[test]
511 fn reserve_in_arc_unique_does_not_overallocate() {
512 let mut bytes = BytesMut::with_capacity(1000);
513 let _ = bytes.split();
514
515 // now bytes is Arc and refcount == 1
516
517 assert_eq!(1000, bytes.capacity());
518 bytes.reserve(2001);
519 assert_eq!(2001, bytes.capacity());
520 }
521
522 #[test]
523 fn reserve_in_arc_unique_doubles() {
524 let mut bytes = BytesMut::with_capacity(1000);
525 let _ = bytes.split();
526
527 // now bytes is Arc and refcount == 1
528
529 assert_eq!(1000, bytes.capacity());
530 bytes.reserve(1001);
531 assert_eq!(2000, bytes.capacity());
532 }
533
534 #[test]
535 fn reserve_in_arc_unique_does_not_overallocate_after_split() {
536 let mut bytes = BytesMut::from(LONG);
537 let orig_capacity = bytes.capacity();
538 drop(bytes.split_off(LONG.len() / 2));
539
540 // now bytes is Arc and refcount == 1
541
542 let new_capacity = bytes.capacity();
543 bytes.reserve(orig_capacity - new_capacity);
544 assert_eq!(bytes.capacity(), orig_capacity);
545 }
546
547 #[test]
548 fn reserve_in_arc_unique_does_not_overallocate_after_multiple_splits() {
549 let mut bytes = BytesMut::from(LONG);
550 let orig_capacity = bytes.capacity();
551 for _ in 0..10 {
552 drop(bytes.split_off(LONG.len() / 2));
553
554 // now bytes is Arc and refcount == 1
555
556 let new_capacity = bytes.capacity();
557 bytes.reserve(orig_capacity - new_capacity);
558 }
559 assert_eq!(bytes.capacity(), orig_capacity);
560 }
561
562 #[test]
563 fn reserve_in_arc_nonunique_does_not_overallocate() {
564 let mut bytes = BytesMut::with_capacity(1000);
565 let _copy = bytes.split();
566
567 // now bytes is Arc and refcount == 2
568
569 assert_eq!(1000, bytes.capacity());
570 bytes.reserve(2001);
571 assert_eq!(2001, bytes.capacity());
572 }
573
574 /// This function tests `BytesMut::reserve_inner`, where `BytesMut` holds
575 /// a unique reference to the shared vector and decide to reuse it
576 /// by reallocating the `Vec`.
577 #[test]
578 fn reserve_shared_reuse() {
579 let mut bytes = BytesMut::with_capacity(1000);
580 bytes.put_slice(b"Hello, World!");
581 drop(bytes.split());
582
583 bytes.put_slice(b"!123ex123,sadchELLO,_wORLD!");
584 // Use split_off so that v.capacity() - self.cap != off
585 drop(bytes.split_off(9));
586 assert_eq!(&*bytes, b"!123ex123");
587
588 bytes.reserve(2000);
589 assert_eq!(&*bytes, b"!123ex123");
590 assert_eq!(bytes.capacity(), 2009);
591 }
592
593 #[test]
594 fn extend_mut() {
595 let mut bytes = BytesMut::with_capacity(0);
596 bytes.extend(LONG);
597 assert_eq!(*bytes, LONG[..]);
598 }
599
600 #[test]
601 fn extend_from_slice_mut() {
602 for &i in &[3, 34] {
603 let mut bytes = BytesMut::new();
604 bytes.extend_from_slice(&LONG[..i]);
605 bytes.extend_from_slice(&LONG[i..]);
606 assert_eq!(LONG[..], *bytes);
607 }
608 }
609
610 #[test]
611 fn extend_from_within_normal() {
612 let mut bytes = BytesMut::new();
613 bytes.extend_from_slice(&LONG[..23]);
614 bytes.extend_from_within(10..22);
615 bytes.extend_from_within(22..35);
616 assert_eq!(LONG[..], *bytes);
617 }
618
619 #[test]
620 #[should_panic]
621 fn extend_from_within_out_of_range() {
622 let mut bytes = BytesMut::new();
623 bytes.extend_from_slice(&LONG[..23]);
624 bytes.extend_from_within(23..=23);
625 }
626
627 #[test]
628 fn extend_mut_from_bytes() {
629 let mut bytes = BytesMut::with_capacity(0);
630 bytes.extend([Bytes::from(LONG)]);
631 assert_eq!(*bytes, LONG[..]);
632 }
633
634 #[test]
635 fn extend_past_lower_limit_of_size_hint() {
636 // See https://github.com/tokio-rs/bytes/pull/674#pullrequestreview-1913035700
637 struct Iter<I>(I);
638
639 impl<I: Iterator<Item = u8>> Iterator for Iter<I> {
640 type Item = u8;
641
642 fn next(&mut self) -> Option<Self::Item> {
643 self.0.next()
644 }
645
646 fn size_hint(&self) -> (usize, Option<usize>) {
647 (5, None)
648 }
649 }
650
651 let mut bytes = BytesMut::with_capacity(5);
652 bytes.extend(Iter(std::iter::repeat(0).take(10)));
653 assert_eq!(bytes.len(), 10);
654 }
655
656 #[test]
657 fn extend_mut_without_size_hint() {
658 let mut bytes = BytesMut::with_capacity(0);
659 let mut long_iter = LONG.iter();
660
661 // Use iter::from_fn since it doesn't know a size_hint
662 bytes.extend(std::iter::from_fn(|| long_iter.next()));
663 assert_eq!(*bytes, LONG[..]);
664 }
665
666 #[test]
667 fn from_static() {
668 let mut a = Bytes::from_static(b"ab");
669 let b = a.split_off(1);
670
671 assert_eq!(a, b"a"[..]);
672 assert_eq!(b, b"b"[..]);
673 }
674
675 #[test]
676 fn advance_static() {
677 let mut a = Bytes::from_static(b"hello world");
678 a.advance(6);
679 assert_eq!(a, &b"world"[..]);
680 }
681
682 #[test]
683 fn advance_vec() {
684 let mut a = Bytes::from(b"hello world boooo yah world zomg wat wat".to_vec());
685 a.advance(16);
686 assert_eq!(a, b"o yah world zomg wat wat"[..]);
687
688 a.advance(4);
689 assert_eq!(a, b"h world zomg wat wat"[..]);
690
691 a.advance(6);
692 assert_eq!(a, b"d zomg wat wat"[..]);
693 }
694
695 #[test]
696 fn advance_bytes_mut() {
697 let mut a = BytesMut::from("hello world boooo yah world zomg wat wat");
698 a.advance(16);
699 assert_eq!(a, b"o yah world zomg wat wat"[..]);
700
701 a.advance(4);
702 assert_eq!(a, b"h world zomg wat wat"[..]);
703
704 // Reserve some space.
705 a.reserve(1024);
706 assert_eq!(a, b"h world zomg wat wat"[..]);
707
708 a.advance(6);
709 assert_eq!(a, b"d zomg wat wat"[..]);
710 }
711
712 // Ensures BytesMut::advance reduces always capacity
713 //
714 // See https://github.com/tokio-rs/bytes/issues/725
715 #[test]
716 fn advance_bytes_mut_remaining_capacity() {
717 // reduce the search space under miri
718 let max_capacity = if cfg!(miri) { 16 } else { 256 };
719 for capacity in 0..=max_capacity {
720 for len in 0..=capacity {
721 for advance in 0..=len {
722 eprintln!("testing capacity={capacity}, len={len}, advance={advance}");
723 let mut buf = BytesMut::with_capacity(capacity);
724
725 buf.resize(len, 42);
726 assert_eq!(buf.len(), len, "resize should write `len` bytes");
727 assert_eq!(
728 buf.remaining(),
729 len,
730 "Buf::remaining() should equal BytesMut::len"
731 );
732
733 buf.advance(advance);
734 assert_eq!(
735 buf.remaining(),
736 len - advance,
737 "Buf::advance should reduce the remaining len"
738 );
739 assert_eq!(
740 buf.capacity(),
741 capacity - advance,
742 "Buf::advance should reduce the remaining capacity"
743 );
744 }
745 }
746 }
747 }
748
749 #[test]
750 #[should_panic]
751 fn advance_past_len() {
752 let mut a = BytesMut::from("hello world");
753 a.advance(20);
754 }
755
756 #[test]
757 #[should_panic]
758 fn mut_advance_past_len() {
759 let mut a = BytesMut::from("hello world");
760 unsafe {
761 a.advance_mut(20);
762 }
763 }
764
765 #[test]
766 // Only run these tests on little endian systems. CI uses qemu for testing
767 // big endian... and qemu doesn't really support threading all that well.
768 #[cfg(any(miri, target_endian = "little"))]
769 #[cfg(not(target_family = "wasm"))] // wasm without experimental threads proposal doesn't support threads
770 fn stress() {
771 // Tests promoting a buffer from a vec -> shared in a concurrent situation
772 use std::sync::{Arc, Barrier};
773 use std::thread;
774
775 const THREADS: usize = 8;
776 const ITERS: usize = if cfg!(miri) { 100 } else { 1_000 };
777
778 for i in 0..ITERS {
779 let data = [i as u8; 256];
780 let buf = Arc::new(Bytes::copy_from_slice(&data[..]));
781
782 let barrier = Arc::new(Barrier::new(THREADS));
783 let mut joins = Vec::with_capacity(THREADS);
784
785 for _ in 0..THREADS {
786 let c = barrier.clone();
787 let buf = buf.clone();
788
789 joins.push(thread::spawn(move || {
790 c.wait();
791 let buf: Bytes = (*buf).clone();
792 drop(buf);
793 }));
794 }
795
796 for th in joins {
797 th.join().unwrap();
798 }
799
800 assert_eq!(*buf, data[..]);
801 }
802 }
803
804 #[test]
805 fn partial_eq_bytesmut() {
806 let bytes = Bytes::from(&b"The quick red fox"[..]);
807 let bytesmut = BytesMut::from(&b"The quick red fox"[..]);
808 assert!(bytes == bytesmut);
809 assert!(bytesmut == bytes);
810 let bytes2 = Bytes::from(&b"Jumped over the lazy brown dog"[..]);
811 assert!(bytes2 != bytesmut);
812 assert!(bytesmut != bytes2);
813 }
814
815 #[test]
816 fn bytes_mut_unsplit_basic() {
817 let mut buf = BytesMut::with_capacity(64);
818 buf.extend_from_slice(b"aaabbbcccddd");
819
820 let splitted = buf.split_off(6);
821 assert_eq!(b"aaabbb", &buf[..]);
822 assert_eq!(b"cccddd", &splitted[..]);
823
824 buf.unsplit(splitted);
825 assert_eq!(b"aaabbbcccddd", &buf[..]);
826 }
827
828 #[test]
829 fn bytes_mut_unsplit_empty_other() {
830 let mut buf = BytesMut::with_capacity(64);
831 buf.extend_from_slice(b"aaabbbcccddd");
832
833 // empty other
834 let other = BytesMut::new();
835
836 buf.unsplit(other);
837 assert_eq!(b"aaabbbcccddd", &buf[..]);
838 }
839
840 #[test]
841 fn bytes_mut_unsplit_empty_self() {
842 // empty self
843 let mut buf = BytesMut::new();
844
845 let mut other = BytesMut::with_capacity(64);
846 other.extend_from_slice(b"aaabbbcccddd");
847
848 buf.unsplit(other);
849 assert_eq!(b"aaabbbcccddd", &buf[..]);
850 }
851
852 #[test]
853 fn bytes_mut_unsplit_other_keeps_capacity() {
854 let mut buf = BytesMut::with_capacity(64);
855 buf.extend_from_slice(b"aabb");
856
857 // non empty other created "from" buf
858 let mut other = buf.split_off(buf.len());
859 other.extend_from_slice(b"ccddee");
860 buf.unsplit(other);
861
862 assert_eq!(buf.capacity(), 64);
863 }
864
865 #[test]
866 fn bytes_mut_unsplit_empty_other_keeps_capacity() {
867 let mut buf = BytesMut::with_capacity(64);
868 buf.extend_from_slice(b"aabbccddee");
869
870 // empty other created "from" buf
871 let other = buf.split_off(buf.len());
872 buf.unsplit(other);
873
874 assert_eq!(buf.capacity(), 64);
875 }
876
877 #[test]
878 fn bytes_mut_unsplit_arc_different() {
879 let mut buf = BytesMut::with_capacity(64);
880 buf.extend_from_slice(b"aaaabbbbeeee");
881
882 let _ = buf.split_off(8); //arc
883
884 let mut buf2 = BytesMut::with_capacity(64);
885 buf2.extend_from_slice(b"ccccddddeeee");
886
887 let _ = buf2.split_off(8); //arc
888
889 buf.unsplit(buf2);
890 assert_eq!(b"aaaabbbbccccdddd", &buf[..]);
891 }
892
893 #[test]
894 fn bytes_mut_unsplit_arc_non_contiguous() {
895 let mut buf = BytesMut::with_capacity(64);
896 buf.extend_from_slice(b"aaaabbbbeeeeccccdddd");
897
898 let mut buf2 = buf.split_off(8); //arc
899
900 let buf3 = buf2.split_off(4); //arc
901
902 buf.unsplit(buf3);
903 assert_eq!(b"aaaabbbbccccdddd", &buf[..]);
904 }
905
906 #[test]
907 fn bytes_mut_unsplit_two_split_offs() {
908 let mut buf = BytesMut::with_capacity(64);
909 buf.extend_from_slice(b"aaaabbbbccccdddd");
910
911 let mut buf2 = buf.split_off(8); //arc
912 let buf3 = buf2.split_off(4); //arc
913
914 buf2.unsplit(buf3);
915 buf.unsplit(buf2);
916 assert_eq!(b"aaaabbbbccccdddd", &buf[..]);
917 }
918
919 #[test]
920 fn from_iter_no_size_hint() {
921 use std::iter;
922
923 let mut expect = vec![];
924
925 let actual: Bytes = iter::repeat(b'x')
926 .scan(100, |cnt, item| {
927 if *cnt >= 1 {
928 *cnt -= 1;
929 expect.push(item);
930 Some(item)
931 } else {
932 None
933 }
934 })
935 .collect();
936
937 assert_eq!(&actual[..], &expect[..]);
938 }
939
940 fn test_slice_ref(bytes: &Bytes, start: usize, end: usize, expected: &[u8]) {
941 let slice = &(bytes.as_ref()[start..end]);
942 let sub = bytes.slice_ref(slice);
943 assert_eq!(&sub[..], expected);
944 }
945
946 #[test]
947 fn slice_ref_works() {
948 let bytes = Bytes::from(&b"012345678"[..]);
949
950 test_slice_ref(&bytes, 0, 0, b"");
951 test_slice_ref(&bytes, 0, 3, b"012");
952 test_slice_ref(&bytes, 2, 6, b"2345");
953 test_slice_ref(&bytes, 7, 9, b"78");
954 test_slice_ref(&bytes, 9, 9, b"");
955 }
956
957 #[test]
958 fn slice_ref_empty() {
959 let bytes = Bytes::from(&b""[..]);
960 let slice = &(bytes.as_ref()[0..0]);
961
962 let sub = bytes.slice_ref(slice);
963 assert_eq!(&sub[..], b"");
964 }
965
966 #[test]
967 fn slice_ref_empty_subslice() {
968 let bytes = Bytes::from(&b"abcde"[..]);
969 let subbytes = bytes.slice(0..0);
970 let slice = &subbytes[..];
971 // The `slice` object is derived from the original `bytes` object
972 // so `slice_ref` should work.
973 assert_eq!(Bytes::new(), bytes.slice_ref(slice));
974 }
975
976 #[test]
977 #[should_panic]
978 fn slice_ref_catches_not_a_subset() {
979 let bytes = Bytes::from(&b"012345678"[..]);
980 let slice = &b"012345"[0..4];
981
982 bytes.slice_ref(slice);
983 }
984
985 #[test]
986 fn slice_ref_not_an_empty_subset() {
987 let bytes = Bytes::from(&b"012345678"[..]);
988 let slice = &b""[0..0];
989
990 assert_eq!(Bytes::new(), bytes.slice_ref(slice));
991 }
992
993 #[test]
994 fn empty_slice_ref_not_an_empty_subset() {
995 let bytes = Bytes::new();
996 let slice = &b"some other slice"[0..0];
997
998 assert_eq!(Bytes::new(), bytes.slice_ref(slice));
999 }
1000
1001 #[test]
1002 fn bytes_buf_mut_advance() {
1003 let mut bytes = BytesMut::with_capacity(1024);
1004
1005 unsafe {
1006 let ptr = bytes.chunk_mut().as_mut_ptr();
1007 assert_eq!(1024, bytes.chunk_mut().len());
1008
1009 bytes.advance_mut(10);
1010
1011 let next = bytes.chunk_mut().as_mut_ptr();
1012 assert_eq!(1024 - 10, bytes.chunk_mut().len());
1013 assert_eq!(ptr.offset(10), next);
1014
1015 // advance to the end
1016 bytes.advance_mut(1024 - 10);
1017
1018 // The buffer size is doubled
1019 assert_eq!(1024, bytes.chunk_mut().len());
1020 }
1021 }
1022
1023 #[test]
1024 fn bytes_buf_mut_reuse_when_fully_consumed() {
1025 use bytes::{Buf, BytesMut};
1026 let mut buf = BytesMut::new();
1027 buf.reserve(8192);
1028 buf.extend_from_slice(&[0u8; 100][..]);
1029
1030 let p = &buf[0] as *const u8;
1031 buf.advance(100);
1032
1033 buf.reserve(8192);
1034 buf.extend_from_slice(b" ");
1035
1036 assert_eq!(&buf[0] as *const u8, p);
1037 }
1038
1039 #[test]
1040 #[should_panic]
1041 fn bytes_reserve_overflow() {
1042 let mut bytes = BytesMut::with_capacity(1024);
1043 bytes.put_slice(b"hello world");
1044
1045 bytes.reserve(usize::MAX);
1046 }
1047
1048 #[test]
1049 fn bytes_with_capacity_but_empty() {
1050 // See https://github.com/tokio-rs/bytes/issues/340
1051 let vec = Vec::with_capacity(1);
1052 let _ = Bytes::from(vec);
1053 }
1054
1055 #[test]
1056 fn bytes_put_bytes() {
1057 let mut bytes = BytesMut::new();
1058 bytes.put_u8(17);
1059 bytes.put_bytes(19, 2);
1060 assert_eq!([17, 19, 19], bytes.as_ref());
1061 }
1062
1063 #[test]
1064 fn box_slice_empty() {
1065 // See https://github.com/tokio-rs/bytes/issues/340
1066 let empty: Box<[u8]> = Default::default();
1067 let b = Bytes::from(empty);
1068 assert!(b.is_empty());
1069 }
1070
1071 #[test]
1072 fn bytes_into_vec() {
1073 // Test kind == KIND_VEC
1074 let content = b"helloworld";
1075
1076 let mut bytes = BytesMut::new();
1077 bytes.put_slice(content);
1078
1079 let vec: Vec<u8> = bytes.into();
1080 assert_eq!(&vec, content);
1081
1082 // Test kind == KIND_ARC, shared.is_unique() == True
1083 let mut bytes = BytesMut::new();
1084 bytes.put_slice(b"abcdewe23");
1085 bytes.put_slice(content);
1086
1087 // Overwrite the bytes to make sure only one reference to the underlying
1088 // Vec exists.
1089 bytes = bytes.split_off(9);
1090
1091 let vec: Vec<u8> = bytes.into();
1092 assert_eq!(&vec, content);
1093
1094 // Test kind == KIND_ARC, shared.is_unique() == False
1095 let prefix = b"abcdewe23";
1096
1097 let mut bytes = BytesMut::new();
1098 bytes.put_slice(prefix);
1099 bytes.put_slice(content);
1100
1101 let vec: Vec<u8> = bytes.split_off(prefix.len()).into();
1102 assert_eq!(&vec, content);
1103
1104 let vec: Vec<u8> = bytes.into();
1105 assert_eq!(&vec, prefix);
1106 }
1107
1108 #[test]
1109 fn test_bytes_into_vec() {
1110 // Test STATIC_VTABLE.to_vec
1111 let bs = b"1b23exfcz3r";
1112 let vec: Vec<u8> = Bytes::from_static(bs).into();
1113 assert_eq!(&*vec, bs);
1114
1115 // Test bytes_mut.SHARED_VTABLE.to_vec impl
1116 eprintln!("1");
1117 let mut bytes_mut: BytesMut = bs[..].into();
1118
1119 // Set kind to KIND_ARC so that after freeze, Bytes will use bytes_mut.SHARED_VTABLE
1120 eprintln!("2");
1121 drop(bytes_mut.split_off(bs.len()));
1122
1123 eprintln!("3");
1124 let b1 = bytes_mut.freeze();
1125 eprintln!("4");
1126 let b2 = b1.clone();
1127
1128 eprintln!("{:#?}", (&*b1).as_ptr());
1129
1130 // shared.is_unique() = False
1131 eprintln!("5");
1132 assert_eq!(&*Vec::from(b2), bs);
1133
1134 // shared.is_unique() = True
1135 eprintln!("6");
1136 assert_eq!(&*Vec::from(b1), bs);
1137
1138 // Test bytes_mut.SHARED_VTABLE.to_vec impl where offset != 0
1139 let mut bytes_mut1: BytesMut = bs[..].into();
1140 let bytes_mut2 = bytes_mut1.split_off(9);
1141
1142 let b1 = bytes_mut1.freeze();
1143 let b2 = bytes_mut2.freeze();
1144
1145 assert_eq!(Vec::from(b2), bs[9..]);
1146 assert_eq!(Vec::from(b1), bs[..9]);
1147 }
1148
1149 #[test]
1150 fn test_bytes_into_vec_promotable_even() {
1151 let vec = vec![33u8; 1024];
1152
1153 // Test cases where kind == KIND_VEC
1154 let b1 = Bytes::from(vec.clone());
1155 assert_eq!(Vec::from(b1), vec);
1156
1157 // Test cases where kind == KIND_ARC, ref_cnt == 1
1158 let b1 = Bytes::from(vec.clone());
1159 drop(b1.clone());
1160 assert_eq!(Vec::from(b1), vec);
1161
1162 // Test cases where kind == KIND_ARC, ref_cnt == 2
1163 let b1 = Bytes::from(vec.clone());
1164 let b2 = b1.clone();
1165 assert_eq!(Vec::from(b1), vec);
1166
1167 // Test cases where vtable = SHARED_VTABLE, kind == KIND_ARC, ref_cnt == 1
1168 assert_eq!(Vec::from(b2), vec);
1169
1170 // Test cases where offset != 0
1171 let mut b1 = Bytes::from(vec.clone());
1172 let b2 = b1.split_off(20);
1173
1174 assert_eq!(Vec::from(b2), vec[20..]);
1175 assert_eq!(Vec::from(b1), vec[..20]);
1176 }
1177
1178 #[test]
1179 fn test_bytes_vec_conversion() {
1180 let mut vec = Vec::with_capacity(10);
1181 vec.extend(b"abcdefg");
1182 let b = Bytes::from(vec);
1183 let v = Vec::from(b);
1184 assert_eq!(v.len(), 7);
1185 assert_eq!(v.capacity(), 10);
1186
1187 let mut b = Bytes::from(v);
1188 b.advance(1);
1189 let v = Vec::from(b);
1190 assert_eq!(v.len(), 6);
1191 assert_eq!(v.capacity(), 10);
1192 assert_eq!(v.as_slice(), b"bcdefg");
1193 }
1194
1195 #[test]
1196 fn test_bytes_mut_conversion() {
1197 let mut b1 = BytesMut::with_capacity(10);
1198 b1.extend(b"abcdefg");
1199 let b2 = Bytes::from(b1);
1200 let v = Vec::from(b2);
1201 assert_eq!(v.len(), 7);
1202 assert_eq!(v.capacity(), 10);
1203
1204 let mut b = Bytes::from(v);
1205 b.advance(1);
1206 let v = Vec::from(b);
1207 assert_eq!(v.len(), 6);
1208 assert_eq!(v.capacity(), 10);
1209 assert_eq!(v.as_slice(), b"bcdefg");
1210 }
1211
1212 #[test]
1213 fn test_bytes_capacity_len() {
1214 for cap in 0..100 {
1215 for len in 0..=cap {
1216 let mut v = Vec::with_capacity(cap);
1217 v.resize(len, 0);
1218 let _ = Bytes::from(v);
1219 }
1220 }
1221 }
1222
1223 #[test]
1224 fn static_is_unique() {
1225 let b = Bytes::from_static(LONG);
1226 assert!(!b.is_unique());
1227 }
1228
1229 #[test]
1230 fn vec_is_unique() {
1231 let v: Vec<u8> = LONG.to_vec();
1232 let b = Bytes::from(v);
1233 assert!(b.is_unique());
1234 }
1235
1236 #[test]
1237 fn arc_is_unique() {
1238 let v: Vec<u8> = LONG.to_vec();
1239 let b = Bytes::from(v);
1240 let c = b.clone();
1241 assert!(!b.is_unique());
1242 drop(c);
1243 assert!(b.is_unique());
1244 }
1245
1246 #[test]
1247 fn shared_is_unique() {
1248 let v: Vec<u8> = LONG.to_vec();
1249 let b = Bytes::from(v);
1250 let c = b.clone();
1251 assert!(!c.is_unique());
1252 drop(b);
1253 assert!(c.is_unique());
1254 }
1255
1256 #[test]
1257 fn mut_shared_is_unique() {
1258 let mut b = BytesMut::from(LONG);
1259 let c = b.split().freeze();
1260 assert!(!c.is_unique());
1261 drop(b);
1262 assert!(c.is_unique());
1263 }
1264
1265 #[test]
1266 fn test_bytesmut_from_bytes_static() {
1267 let bs = b"1b23exfcz3r";
1268
1269 // Test STATIC_VTABLE.to_mut
1270 let bytes_mut = BytesMut::from(Bytes::from_static(bs));
1271 assert_eq!(bytes_mut, bs[..]);
1272 }
1273
1274 #[test]
1275 fn test_bytesmut_from_bytes_bytes_mut_vec() {
1276 let bs = b"1b23exfcz3r";
1277 let bs_long = b"1b23exfcz3r1b23exfcz3r";
1278
1279 // Test case where kind == KIND_VEC
1280 let mut bytes_mut: BytesMut = bs[..].into();
1281 bytes_mut = BytesMut::from(bytes_mut.freeze());
1282 assert_eq!(bytes_mut, bs[..]);
1283 bytes_mut.extend_from_slice(&bs[..]);
1284 assert_eq!(bytes_mut, bs_long[..]);
1285 }
1286
1287 #[test]
1288 fn test_bytesmut_from_bytes_bytes_mut_shared() {
1289 let bs = b"1b23exfcz3r";
1290
1291 // Set kind to KIND_ARC so that after freeze, Bytes will use bytes_mut.SHARED_VTABLE
1292 let mut bytes_mut: BytesMut = bs[..].into();
1293 drop(bytes_mut.split_off(bs.len()));
1294
1295 let b1 = bytes_mut.freeze();
1296 let b2 = b1.clone();
1297
1298 // shared.is_unique() = False
1299 let mut b1m = BytesMut::from(b1);
1300 assert_eq!(b1m, bs[..]);
1301 b1m[0] = b'9';
1302
1303 // shared.is_unique() = True
1304 let b2m = BytesMut::from(b2);
1305 assert_eq!(b2m, bs[..]);
1306 }
1307
1308 #[test]
1309 fn test_bytesmut_from_bytes_bytes_mut_offset() {
1310 let bs = b"1b23exfcz3r";
1311
1312 // Test bytes_mut.SHARED_VTABLE.to_mut impl where offset != 0
1313 let mut bytes_mut1: BytesMut = bs[..].into();
1314 let bytes_mut2 = bytes_mut1.split_off(9);
1315
1316 let b1 = bytes_mut1.freeze();
1317 let b2 = bytes_mut2.freeze();
1318
1319 let b1m = BytesMut::from(b1);
1320 let b2m = BytesMut::from(b2);
1321
1322 assert_eq!(b2m, bs[9..]);
1323 assert_eq!(b1m, bs[..9]);
1324 }
1325
1326 #[test]
1327 fn test_bytesmut_from_bytes_promotable_even_vec() {
1328 let vec = vec![33u8; 1024];
1329
1330 // Test case where kind == KIND_VEC
1331 let b1 = Bytes::from(vec.clone());
1332 let b1m = BytesMut::from(b1);
1333 assert_eq!(b1m, vec);
1334 }
1335
1336 #[test]
1337 fn test_bytesmut_from_bytes_promotable_even_arc_1() {
1338 let vec = vec![33u8; 1024];
1339
1340 // Test case where kind == KIND_ARC, ref_cnt == 1
1341 let b1 = Bytes::from(vec.clone());
1342 drop(b1.clone());
1343 let b1m = BytesMut::from(b1);
1344 assert_eq!(b1m, vec);
1345 }
1346
1347 #[test]
1348 fn test_bytesmut_from_bytes_promotable_even_arc_2() {
1349 let vec = vec![33u8; 1024];
1350
1351 // Test case where kind == KIND_ARC, ref_cnt == 2
1352 let b1 = Bytes::from(vec.clone());
1353 let b2 = b1.clone();
1354 let b1m = BytesMut::from(b1);
1355 assert_eq!(b1m, vec);
1356
1357 // Test case where vtable = SHARED_VTABLE, kind == KIND_ARC, ref_cnt == 1
1358 let b2m = BytesMut::from(b2);
1359 assert_eq!(b2m, vec);
1360 }
1361
1362 #[test]
1363 fn test_bytesmut_from_bytes_promotable_even_arc_offset() {
1364 let vec = vec![33u8; 1024];
1365
1366 // Test case where offset != 0
1367 let mut b1 = Bytes::from(vec.clone());
1368 let b2 = b1.split_off(20);
1369 let b1m = BytesMut::from(b1);
1370 let b2m = BytesMut::from(b2);
1371
1372 assert_eq!(b2m, vec[20..]);
1373 assert_eq!(b1m, vec[..20]);
1374 }
1375
1376 #[test]
1377 fn try_reclaim_empty() {
1378 let mut buf = BytesMut::new();
1379 assert_eq!(false, buf.try_reclaim(6));
1380 buf.reserve(6);
1381 assert_eq!(true, buf.try_reclaim(6));
1382 let cap = buf.capacity();
1383 assert!(cap >= 6);
1384 assert_eq!(false, buf.try_reclaim(cap + 1));
1385
1386 let mut buf = BytesMut::new();
1387 buf.reserve(6);
1388 let cap = buf.capacity();
1389 assert!(cap >= 6);
1390 let mut split = buf.split();
1391 drop(buf);
1392 assert_eq!(0, split.capacity());
1393 assert_eq!(true, split.try_reclaim(6));
1394 assert_eq!(false, split.try_reclaim(cap + 1));
1395 }
1396
1397 #[test]
1398 fn try_reclaim_vec() {
1399 let mut buf = BytesMut::with_capacity(6);
1400 buf.put_slice(b"abc");
1401 // Reclaiming a ludicrous amount of space should calmly return false
1402 assert_eq!(false, buf.try_reclaim(usize::MAX));
1403
1404 assert_eq!(false, buf.try_reclaim(6));
1405 buf.advance(2);
1406 assert_eq!(4, buf.capacity());
1407 // We can reclaim 5 bytes, because the byte in the buffer can be moved to the front. 6 bytes
1408 // cannot be reclaimed because there is already one byte stored
1409 assert_eq!(false, buf.try_reclaim(6));
1410 assert_eq!(true, buf.try_reclaim(5));
1411 buf.advance(1);
1412 assert_eq!(true, buf.try_reclaim(6));
1413 assert_eq!(6, buf.capacity());
1414 }
1415
1416 #[test]
1417 fn try_reclaim_arc() {
1418 let mut buf = BytesMut::with_capacity(6);
1419 buf.put_slice(b"abc");
1420 let x = buf.split().freeze();
1421 buf.put_slice(b"def");
1422 // Reclaiming a ludicrous amount of space should calmly return false
1423 assert_eq!(false, buf.try_reclaim(usize::MAX));
1424
1425 let y = buf.split().freeze();
1426 let z = y.clone();
1427 assert_eq!(false, buf.try_reclaim(6));
1428 drop(x);
1429 drop(z);
1430 assert_eq!(false, buf.try_reclaim(6));
1431 drop(y);
1432 assert_eq!(true, buf.try_reclaim(6));
1433 assert_eq!(6, buf.capacity());
1434 assert_eq!(0, buf.len());
1435 buf.put_slice(b"abc");
1436 buf.put_slice(b"def");
1437 assert_eq!(6, buf.capacity());
1438 assert_eq!(6, buf.len());
1439 assert_eq!(false, buf.try_reclaim(6));
1440 buf.advance(4);
1441 assert_eq!(true, buf.try_reclaim(4));
1442 buf.advance(2);
1443 assert_eq!(true, buf.try_reclaim(6));
1444 }
1445
1446 #[test]
1447 fn slice_empty_addr() {
1448 let buf = Bytes::from(vec![0; 1024]);
1449
1450 let ptr_start = buf.as_ptr();
1451 let ptr_end = ptr_start.wrapping_add(1024);
1452
1453 let empty_end = buf.slice(1024..);
1454 assert_eq!(empty_end.len(), 0);
1455 assert_eq!(empty_end.as_ptr(), ptr_end);
1456
1457 let empty_start = buf.slice(..0);
1458 assert_eq!(empty_start.len(), 0);
1459 assert_eq!(empty_start.as_ptr(), ptr_start);
1460
1461 // Is miri happy about the provenance?
1462 let _ = &empty_end[..];
1463 let _ = &empty_start[..];
1464 }
1465
1466 #[test]
1467 fn split_off_empty_addr() {
1468 let mut buf = Bytes::from(vec![0; 1024]);
1469
1470 let ptr_start = buf.as_ptr();
1471 let ptr_end = ptr_start.wrapping_add(1024);
1472
1473 let empty_end = buf.split_off(1024);
1474 assert_eq!(empty_end.len(), 0);
1475 assert_eq!(empty_end.as_ptr(), ptr_end);
1476
1477 let _ = buf.split_off(0);
1478 assert_eq!(buf.len(), 0);
1479 assert_eq!(buf.as_ptr(), ptr_start);
1480
1481 // Is miri happy about the provenance?
1482 let _ = &empty_end[..];
1483 let _ = &buf[..];
1484 }
1485
1486 #[test]
1487 fn split_to_empty_addr() {
1488 let mut buf = Bytes::from(vec![0; 1024]);
1489
1490 let ptr_start = buf.as_ptr();
1491 let ptr_end = ptr_start.wrapping_add(1024);
1492
1493 let empty_start = buf.split_to(0);
1494 assert_eq!(empty_start.len(), 0);
1495 assert_eq!(empty_start.as_ptr(), ptr_start);
1496
1497 let _ = buf.split_to(1024);
1498 assert_eq!(buf.len(), 0);
1499 assert_eq!(buf.as_ptr(), ptr_end);
1500
1501 // Is miri happy about the provenance?
1502 let _ = &empty_start[..];
1503 let _ = &buf[..];
1504 }
1505
1506 #[test]
1507 fn split_off_empty_addr_mut() {
1508 let mut buf = BytesMut::from([0; 1024].as_slice());
1509
1510 let ptr_start = buf.as_ptr();
1511 let ptr_end = ptr_start.wrapping_add(1024);
1512
1513 let empty_end = buf.split_off(1024);
1514 assert_eq!(empty_end.len(), 0);
1515 assert_eq!(empty_end.as_ptr(), ptr_end);
1516
1517 let _ = buf.split_off(0);
1518 assert_eq!(buf.len(), 0);
1519 assert_eq!(buf.as_ptr(), ptr_start);
1520
1521 // Is miri happy about the provenance?
1522 let _ = &empty_end[..];
1523 let _ = &buf[..];
1524 }
1525
1526 #[test]
1527 fn split_to_empty_addr_mut() {
1528 let mut buf = BytesMut::from([0; 1024].as_slice());
1529
1530 let ptr_start = buf.as_ptr();
1531 let ptr_end = ptr_start.wrapping_add(1024);
1532
1533 let empty_start = buf.split_to(0);
1534 assert_eq!(empty_start.len(), 0);
1535 assert_eq!(empty_start.as_ptr(), ptr_start);
1536
1537 let _ = buf.split_to(1024);
1538 assert_eq!(buf.len(), 0);
1539 assert_eq!(buf.as_ptr(), ptr_end);
1540
1541 // Is miri happy about the provenance?
1542 let _ = &empty_start[..];
1543 let _ = &buf[..];
1544 }
1545
1546 #[test]
1547 fn bytes_mut_split_boundary_capacities() {
1548 // VEC mode
1549 for at in [0, 5, 11] {
1550 let mut buf = BytesMut::with_capacity(64);
1551 buf.extend_from_slice(b"hello world");
1552
1553 let other = buf.split_off(at);
1554 assert_eq!(
1555 buf.capacity() + other.capacity(),
1556 64,
1557 "split_off at {} should preserve total capacity",
1558 at
1559 );
1560 }
1561
1562 for at in [0, 5, 11] {
1563 let mut buf = BytesMut::with_capacity(64);
1564 buf.extend_from_slice(b"hello world");
1565
1566 let other = buf.split_to(at);
1567 assert_eq!(
1568 buf.capacity() + other.capacity(),
1569 64,
1570 "split_to at {} should preserve total capacity",
1571 at
1572 );
1573 }
1574
1575 // ARC mode (promote via a no-op split)
1576 for at in [0, 5, 11] {
1577 let mut buf = BytesMut::with_capacity(64);
1578 buf.extend_from_slice(b"hello world");
1579 let _ = buf.split_to(0); // promotes to ARC
1580
1581 let other = buf.split_off(at);
1582 assert_eq!(
1583 buf.capacity() + other.capacity(),
1584 64,
1585 "ARC split_off at {} should preserve total capacity",
1586 at
1587 );
1588 }
1589
1590 for at in [0, 5, 11] {
1591 let mut buf = BytesMut::with_capacity(64);
1592 buf.extend_from_slice(b"hello world");
1593 let _ = buf.split_to(0); // promotes to ARC
1594
1595 let other = buf.split_to(at);
1596 assert_eq!(
1597 buf.capacity() + other.capacity(),
1598 64,
1599 "ARC split_to at {} should preserve total capacity",
1600 at
1601 );
1602 }
1603 }
1604
1605 #[derive(Clone)]
1606 struct SharedAtomicCounter(Arc<AtomicUsize>);
1607
1608 impl SharedAtomicCounter {
1609 pub fn new() -> Self {
1610 SharedAtomicCounter(Arc::new(AtomicUsize::new(0)))
1611 }
1612
1613 pub fn increment(&self) {
1614 self.0.fetch_add(1, Ordering::AcqRel);
1615 }
1616
1617 pub fn get(&self) -> usize {
1618 self.0.load(Ordering::Acquire)
1619 }
1620 }
1621
1622 #[derive(Clone)]
1623 struct OwnedTester<const L: usize> {
1624 buf: [u8; L],
1625 drop_count: SharedAtomicCounter,
1626 pub panic_as_ref: bool,
1627 }
1628
1629 impl<const L: usize> OwnedTester<L> {
1630 fn new(buf: [u8; L], drop_count: SharedAtomicCounter) -> Self {
1631 Self {
1632 buf,
1633 drop_count,
1634 panic_as_ref: false,
1635 }
1636 }
1637 }
1638
1639 impl<const L: usize> AsRef<[u8]> for OwnedTester<L> {
1640 fn as_ref(&self) -> &[u8] {
1641 if self.panic_as_ref {
1642 panic!("test-triggered panic in `AsRef<[u8]> for OwnedTester`");
1643 }
1644 self.buf.as_slice()
1645 }
1646 }
1647
1648 impl<const L: usize> Drop for OwnedTester<L> {
1649 fn drop(&mut self) {
1650 self.drop_count.increment();
1651 }
1652 }
1653
1654 #[test]
1655 fn owned_is_unique_always_false() {
1656 let b1 = Bytes::from_owner([1, 2, 3, 4, 5, 6, 7]);
1657 assert!(!b1.is_unique()); // even if ref_cnt == 1
1658 let b2 = b1.clone();
1659 assert!(!b1.is_unique());
1660 assert!(!b2.is_unique());
1661 drop(b1);
1662 assert!(!b2.is_unique()); // even if ref_cnt == 1
1663 }
1664
1665 #[test]
1666 fn owned_buf_sharing() {
1667 let buf = [1, 2, 3, 4, 5, 6, 7];
1668 let b1 = Bytes::from_owner(buf);
1669 let b2 = b1.clone();
1670 assert_eq!(&buf[..], &b1[..]);
1671 assert_eq!(&buf[..], &b2[..]);
1672 assert_eq!(b1.as_ptr(), b2.as_ptr());
1673 assert_eq!(b1.len(), b2.len());
1674 assert_eq!(b1.len(), buf.len());
1675 }
1676
1677 #[test]
1678 fn owned_buf_slicing() {
1679 let b1 = Bytes::from_owner(SHORT);
1680 assert_eq!(SHORT, &b1[..]);
1681 let b2 = b1.slice(1..(b1.len() - 1));
1682 assert_eq!(&SHORT[1..(SHORT.len() - 1)], b2);
1683 assert_eq!(unsafe { SHORT.as_ptr().add(1) }, b2.as_ptr());
1684 assert_eq!(SHORT.len() - 2, b2.len());
1685 }
1686
1687 #[test]
1688 fn owned_dropped_exactly_once() {
1689 let buf: [u8; 5] = [1, 2, 3, 4, 5];
1690 let drop_counter = SharedAtomicCounter::new();
1691 let owner = OwnedTester::new(buf, drop_counter.clone());
1692 let b1 = Bytes::from_owner(owner);
1693 let b2 = b1.clone();
1694 assert_eq!(drop_counter.get(), 0);
1695 drop(b1);
1696 assert_eq!(drop_counter.get(), 0);
1697 let b3 = b2.slice(1..b2.len() - 1);
1698 drop(b2);
1699 assert_eq!(drop_counter.get(), 0);
1700 drop(b3);
1701 assert_eq!(drop_counter.get(), 1);
1702 }
1703
1704 #[test]
1705 fn owned_to_mut() {
1706 let buf: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1707 let drop_counter = SharedAtomicCounter::new();
1708 let owner = OwnedTester::new(buf, drop_counter.clone());
1709 let b1 = Bytes::from_owner(owner);
1710
1711 // Holding an owner will fail converting to a BytesMut,
1712 // even when the bytes instance has a ref_cnt == 1.
1713 let b1 = b1.try_into_mut().unwrap_err();
1714
1715 // That said, it's still possible, just not cheap.
1716 let bm1: BytesMut = b1.into();
1717 let new_buf = &bm1[..];
1718 assert_eq!(new_buf, &buf[..]);
1719
1720 // `.into::<BytesMut>()` has correctly dropped the owner
1721 assert_eq!(drop_counter.get(), 1);
1722 }
1723
1724 #[test]
1725 fn owned_to_vec() {
1726 let buf: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1727 let drop_counter = SharedAtomicCounter::new();
1728 let owner = OwnedTester::new(buf, drop_counter.clone());
1729 let b1 = Bytes::from_owner(owner);
1730
1731 let v1 = b1.to_vec();
1732 assert_eq!(&v1[..], &buf[..]);
1733 assert_eq!(&v1[..], &b1[..]);
1734
1735 drop(b1);
1736 assert_eq!(drop_counter.get(), 1);
1737 }
1738
1739 #[test]
1740 fn owned_into_vec() {
1741 let drop_counter = SharedAtomicCounter::new();
1742 let buf: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1743 let owner = OwnedTester::new(buf, drop_counter.clone());
1744 let b1 = Bytes::from_owner(owner);
1745
1746 let v1: Vec<u8> = b1.into();
1747 assert_eq!(&v1[..], &buf[..]);
1748 // into() vec will copy out of the owner and drop it
1749 assert_eq!(drop_counter.get(), 1);
1750 }
1751
1752 #[test]
1753 #[cfg_attr(not(panic = "unwind"), ignore)]
1754 fn owned_safe_drop_on_as_ref_panic() {
1755 let buf: [u8; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1756 let drop_counter = SharedAtomicCounter::new();
1757 let mut owner = OwnedTester::new(buf, drop_counter.clone());
1758 owner.panic_as_ref = true;
1759
1760 let result = panic::catch_unwind(AssertUnwindSafe(|| {
1761 let _ = Bytes::from_owner(owner);
1762 }));
1763
1764 assert!(result.is_err());
1765 assert_eq!(drop_counter.get(), 1);
1766 }
1767
1768 /// Test `BytesMut::put` reuses allocation of `Bytes`.
1769 #[test]
1770 fn bytes_mut_put_bytes_specialization() {
1771 let mut vec = Vec::with_capacity(1234);
1772 vec.push(10);
1773 let capacity = vec.capacity();
1774 assert!(capacity >= 1234);
1775
1776 // Make `Bytes` backed by `Vec`.
1777 let bytes = Bytes::from(vec);
1778 let mut bytes_mut = BytesMut::new();
1779 bytes_mut.put(bytes);
1780
1781 // Check contents is correct.
1782 assert_eq!(&[10], bytes_mut.as_ref());
1783 // If allocation is reused, capacity should be equal to original vec capacity.
1784 assert_eq!(bytes_mut.capacity(), capacity);
1785 }
1786
1787 #[test]
1788 #[should_panic]
1789 fn bytes_mut_reserve_overflow() {
1790 let mut a = BytesMut::from(&b"hello world"[..]);
1791 let mut b = a.split_off(5);
1792 // Ensure b becomes the unique owner of the backing storage
1793 drop(a);
1794 // Trigger overflow in new_cap + offset inside reserve
1795 b.reserve(usize::MAX - 6);
1796 // This call relies on the corrupted cap and may cause UB & HBO
1797 b.put_u8(b'h');
1798 }