summaryrefslogtreecommitdiffstats
path: root/third_party/rust/tokio-util/tests/reusable_box.rs
blob: c8f6da02ae2da3f80e0ae05597101d316f8d1fa4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use futures::future::FutureExt;
use std::alloc::Layout;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio_util::sync::ReusableBoxFuture;

#[test]
fn test_different_futures() {
    let fut = async move { 10 };
    // Not zero sized!
    assert_eq!(Layout::for_value(&fut).size(), 1);

    let mut b = ReusableBoxFuture::new(fut);

    assert_eq!(b.get_pin().now_or_never(), Some(10));

    b.try_set(async move { 20 })
        .unwrap_or_else(|_| panic!("incorrect size"));

    assert_eq!(b.get_pin().now_or_never(), Some(20));

    b.try_set(async move { 30 })
        .unwrap_or_else(|_| panic!("incorrect size"));

    assert_eq!(b.get_pin().now_or_never(), Some(30));
}

#[test]
fn test_different_sizes() {
    let fut1 = async move { 10 };
    let val = [0u32; 1000];
    let fut2 = async move { val[0] };
    let fut3 = ZeroSizedFuture {};

    assert_eq!(Layout::for_value(&fut1).size(), 1);
    assert_eq!(Layout::for_value(&fut2).size(), 4004);
    assert_eq!(Layout::for_value(&fut3).size(), 0);

    let mut b = ReusableBoxFuture::new(fut1);
    assert_eq!(b.get_pin().now_or_never(), Some(10));
    b.set(fut2);
    assert_eq!(b.get_pin().now_or_never(), Some(0));
    b.set(fut3);
    assert_eq!(b.get_pin().now_or_never(), Some(5));
}

struct ZeroSizedFuture {}
impl Future for ZeroSizedFuture {
    type Output = u32;
    fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<u32> {
        Poll::Ready(5)
    }
}

#[test]
fn test_zero_sized() {
    let fut = ZeroSizedFuture {};
    // Zero sized!
    assert_eq!(Layout::for_value(&fut).size(), 0);

    let mut b = ReusableBoxFuture::new(fut);

    assert_eq!(b.get_pin().now_or_never(), Some(5));
    assert_eq!(b.get_pin().now_or_never(), Some(5));

    b.try_set(ZeroSizedFuture {})
        .unwrap_or_else(|_| panic!("incorrect size"));

    assert_eq!(b.get_pin().now_or_never(), Some(5));
    assert_eq!(b.get_pin().now_or_never(), Some(5));
}