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
use std::ops::Deref;
use super::from_raw::{FromRawResult, RawResult};
use super::super::err::Error;
use std::mem::transmute;

///Safe wrapper around cont reference.
///
/// This type is intended to be used only inside structures implementing `SymBorApi` trait.
/// In other cases you can as well use normal Rust reference.
#[derive(Debug, Clone, Copy)]
pub struct Ref<'lib, T: 'lib> {
    reference: &'lib T,
}

impl<'lib, T> Ref<'lib, T> {
    pub fn new(reference: &'lib T) -> Ref<'lib, T> {
        Ref {
            reference: reference,
        }
    }
}

impl<'lib, T> FromRawResult for Ref<'lib, T> {
    unsafe fn from_raw_result(raw_result: RawResult) -> Result<Self, Error> {
        match raw_result {
            Ok(ptr) => if ptr.is_null() {
                Err(Error::NullSymbol)
            } else {
                Ok(Ref {
                    reference: transmute(*ptr),
                })
            },
            Err(err) => Err(err),
        }
    }
}

impl<'lib, T> Deref for Ref<'lib, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.reference
    }
}

unsafe impl<'lib, T: Send> Send for Ref<'lib, T> {}
unsafe impl<'lib, T: Sync> Sync for Ref<'lib, T> {}