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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//! Utilities that doesn't fit anywhere else, mostly contains internal crate functions
//! (which are not public) and other useful public items.

/// Must return type on callbacks (send and get files)
#[derive(Debug, Copy, Clone)]
pub enum CallbackReturn {
    /// Return this to continue the operation.
    Continue,
    /// Return this to cancel the operation.
    Cancel,
}

#[allow(clippy::transmute_ptr_to_ref)]
pub(crate) unsafe extern "C" fn progress_func_handler(
    sent: u64,
    total: u64,
    data: *const libc::c_void,
) -> libc::c_int {
    let closure: &mut &mut dyn FnMut(u64, u64) -> CallbackReturn = std::mem::transmute(data);
    match closure(sent, total) {
        CallbackReturn::Continue => 0,
        CallbackReturn::Cancel => 1,
    }
}

/// Must return type of send and getter handlers that deal with raw bytes.
#[derive(Debug, Copy, Clone)]
pub enum HandlerReturn {
    /// Return this if every went ok.
    Ok(u32),

    /// Return this if there was an error.
    Error,

    /// Return this if you want to cancel the operation earlier.
    Cancel,
}

#[allow(clippy::transmute_ptr_to_ref)]
pub(crate) unsafe extern "C" fn data_put_func_handler(
    _params: *mut libc::c_void,
    priv_: *mut libc::c_void,
    sendlen: u32,
    data: *mut libc::c_uchar,
    putlen: *mut u32,
) -> u16 {
    let closure: &mut &mut dyn FnMut(&[u8]) -> HandlerReturn = std::mem::transmute(priv_);
    let data = prim_array_ptr_to_vec!(data, u8, sendlen);

    match closure(&data) {
        HandlerReturn::Ok(len) => {
            // Shouldn't be null
            *putlen = len;

            0
        }

        HandlerReturn::Error => 1,
        HandlerReturn::Cancel => 2,
    }
}

#[allow(clippy::transmute_ptr_to_ref)]
pub(crate) unsafe extern "C" fn data_get_func_handler(
    _params: *mut libc::c_void,
    priv_: *mut libc::c_void,
    wantlen: u32,
    data: *mut libc::c_uchar,
    gotlen: *mut u32,
) -> u16 {
    let closure: &mut &mut dyn FnMut(&mut [u8]) -> HandlerReturn = std::mem::transmute(priv_);
    let mut rsdata = vec![0 as u8; wantlen as usize];

    match closure(&mut rsdata) {
        HandlerReturn::Ok(len) => {
            // Shouldn't be null
            *gotlen = len;

            libc::memcpy(
                data as *mut _,
                rsdata.as_ptr() as *const _,
                wantlen as usize,
            );

            0
        }

        HandlerReturn::Error => 1,
        HandlerReturn::Cancel => 2,
    }
}