1
use std::ptr::NonNull;
2

            
3
use crate::{
4
    Error,
5
    capture::{Capture, Dead},
6
    linktype::Linktype,
7
    raw,
8
};
9

            
10
#[cfg(libpcap_1_5_0)]
11
use crate::capture::Precision;
12

            
13
impl Capture<Dead> {
14
    /// Creates a "fake" capture handle for the given link type.
15
70
    pub fn dead(linktype: Linktype) -> Result<Capture<Dead>, Error> {
16
70
        let handle = unsafe { raw::pcap_open_dead(linktype.0, 65535) };
17
70
        Ok(Capture::from(
18
70
            NonNull::<raw::pcap_t>::new(handle).ok_or(Error::InsufficientMemory)?,
19
        ))
20
70
    }
21

            
22
    /// Creates a "fake" capture handle for the given link type and timestamp precision.
23
    #[cfg(libpcap_1_5_0)]
24
2
    pub fn dead_with_precision(
25
2
        linktype: Linktype,
26
2
        precision: Precision,
27
2
    ) -> Result<Capture<Dead>, Error> {
28
2
        let handle = unsafe {
29
2
            raw::pcap_open_dead_with_tstamp_precision(linktype.0, 65535, precision as u32)
30
        };
31
2
        Ok(Capture::from(
32
2
            NonNull::<raw::pcap_t>::new(handle).ok_or(Error::InsufficientMemory)?,
33
        ))
34
2
    }
35
}
36

            
37
#[cfg(test)]
38
mod tests {
39
    #[cfg(libpcap_1_5_0)]
40
    use mockall::predicate;
41

            
42
    use crate::raw::testmod::{RAWMTX, as_pcap_t};
43

            
44
    use super::*;
45

            
46
    #[test]
47
    fn test_dead() {
48
        let _m = RAWMTX.lock();
49

            
50
        let mut dummy: isize = 777;
51
        let pcap = as_pcap_t(&mut dummy);
52

            
53
        let ctx = raw::pcap_open_dead_context();
54
        ctx.expect().return_once_st(move |_, _| pcap);
55

            
56
        let ctx = raw::pcap_close_context();
57
        ctx.expect()
58
            .withf_st(move |ptr| *ptr == pcap)
59
            .return_once(|_| {});
60

            
61
        let result = Capture::dead(Linktype::ETHERNET);
62
        assert!(result.is_ok());
63
    }
64

            
65
    #[test]
66
    #[cfg(libpcap_1_5_0)]
67
    fn test_dead_with_precision() {
68
        let _m = RAWMTX.lock();
69

            
70
        let mut dummy: isize = 777;
71
        let pcap = as_pcap_t(&mut dummy);
72

            
73
        let ctx = raw::pcap_open_dead_with_tstamp_precision_context();
74
        ctx.expect()
75
            .with(predicate::always(), predicate::always(), predicate::eq(1))
76
            .return_once_st(move |_, _, _| pcap);
77

            
78
        let ctx = raw::pcap_close_context();
79
        ctx.expect()
80
            .withf_st(move |ptr| *ptr == pcap)
81
            .return_once(|_| {});
82

            
83
        let result = Capture::dead_with_precision(Linktype::ETHERNET, Precision::Nano);
84
        assert!(result.is_ok());
85
    }
86
}