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
use prelude::{Protocol, SockAddr};
use ffi::{SockAddrImpl, sockaddr};

use std::slice;
use std::marker::PhantomData;

#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct GenericEndpoint<P: Protocol> {
    sa: SockAddrImpl<Box<[u8]>>,
    protocol: i32,
    _marker: PhantomData<P>,
}

impl<P: Protocol> GenericEndpoint<P> {
    pub fn new<T>(ep: &T, protocol: i32) -> GenericEndpoint<P>
        where T: SockAddr,
    {
        let mut sa = vec![0; ep.capacity()];
        let len = ep.size();
        let src = unsafe { slice::from_raw_parts(ep.as_ref() as *const _ as *const u8, len) };
        sa[..len].copy_from_slice(src);
        GenericEndpoint {
            sa: SockAddrImpl::from_vec(sa, len),
            protocol: protocol,
            _marker: PhantomData,
        }
    }

    fn default(capacity: usize, protocol: i32) -> GenericEndpoint<P> {
        GenericEndpoint {
            sa: SockAddrImpl::from_vec(vec![0; capacity], 0),
            protocol: protocol,
            _marker: PhantomData,
        }
    }
}

impl<P: Protocol> SockAddr for GenericEndpoint<P> {
    type SockAddr = sockaddr;

    fn as_ref(&self) -> &Self::SockAddr {
        unsafe { &*(self.sa.as_ptr() as *const _) }
    }

    unsafe fn as_mut(&mut self) -> &mut Self::SockAddr {
        &mut *(self.sa.as_ptr() as *mut _)
    }

    fn capacity(&self) -> usize {
        self.sa.capacity()
    }

    fn size(&self) -> usize {
        self.sa.size()
    }

    unsafe fn resize(&mut self, size: usize) {
        debug_assert!(size <= self.capacity());
        self.sa.resize(size)
    }
}

mod stream;
pub use self::stream::*;

mod dgram;
pub use self::dgram::*;

mod raw;
pub use self::raw::*;

mod seq_packet;
pub use self::seq_packet::*;