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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#![warn(missing_docs)]
#[macro_use]
extern crate failure_derive;
#[cfg(test)]
#[macro_use]
extern crate lazy_static;
use std::{
os::raw::c_int,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
};
use enet_sys::{enet_deinitialize, enet_host_create, enet_initialize, enet_linked_version};
mod address;
mod event;
mod host;
mod packet;
mod peer;
pub use crate::address::Address;
pub use crate::event::Event;
pub use crate::host::{BandwidthLimit, ChannelLimit, Host};
pub use crate::packet::{Packet, PacketMode};
pub use crate::peer::{Peer, PeerPacket, PeerState};
pub use enet_sys::ENetVersion as EnetVersion;
const ENET_UNINITIALIZED: usize = 1;
const ENET_INITIALIZED: usize = 2;
const ENET_DEINITIALIZED: usize = 3;
static ENET_STATUS: AtomicUsize = AtomicUsize::new(ENET_UNINITIALIZED);
#[derive(Debug, Clone)]
struct EnetKeepAlive;
#[derive(Debug, Clone)]
pub struct Enet {
keep_alive: Arc<EnetKeepAlive>,
}
#[derive(Fail, Debug)]
#[fail(display = "enet failure, returned '{}'", _0)]
pub struct Error(pub c_int);
#[derive(Fail, Debug)]
pub enum InitializationError {
#[fail(display = "ENet has already been initialized before")]
AlreadyInitialized,
#[fail(display = "ENet has already been deinitialized before")]
AlreadyDeinitialized,
#[fail(display = "enet_initialize failed (with '{}')", _0)]
Error(c_int),
}
impl Enet {
pub fn new() -> Result<Enet, InitializationError> {
match ENET_STATUS.compare_and_swap(ENET_UNINITIALIZED, ENET_INITIALIZED, Ordering::SeqCst) {
ENET_UNINITIALIZED => (),
ENET_INITIALIZED => return Err(InitializationError::AlreadyInitialized),
ENET_DEINITIALIZED => return Err(InitializationError::AlreadyDeinitialized),
u => panic!(
"enet-rs internal error; unexpected value in ENET_STATUS (new): {}",
u
),
};
let r = unsafe { enet_initialize() };
if r != 0 {
return Err(InitializationError::Error(r));
}
Ok(Enet {
keep_alive: Arc::new(EnetKeepAlive),
})
}
pub fn create_host<T>(
&self,
address: Option<&Address>,
max_peer_count: usize,
max_channel_count: ChannelLimit,
incoming_bandwidth: BandwidthLimit,
outgoing_bandwidth: BandwidthLimit,
) -> Result<Host<T>, Error> {
let addr = address.map(Address::to_enet_address);
let inner = unsafe {
enet_host_create(
addr.as_ref()
.map(|p| p as *const _)
.unwrap_or(std::ptr::null()),
max_peer_count,
max_channel_count.to_enet_usize(),
incoming_bandwidth.to_enet_u32(),
outgoing_bandwidth.to_enet_u32(),
)
};
if inner.is_null() {
return Err(Error(0));
}
Ok(Host::new(self.keep_alive.clone(), inner))
}
}
pub fn linked_version() -> EnetVersion {
unsafe { enet_linked_version() }
}
impl Drop for EnetKeepAlive {
fn drop(&mut self) {
match ENET_STATUS.compare_and_swap(ENET_INITIALIZED, ENET_DEINITIALIZED, Ordering::SeqCst) {
ENET_INITIALIZED => (),
other => panic!(
"enet-rs internal error; unexpected value in ENET_STATUS (drop): {}",
other
),
};
unsafe {
enet_deinitialize();
}
}
}
#[cfg(test)]
mod tests {
use super::{BandwidthLimit, ChannelLimit, Enet};
lazy_static! {
static ref ENET: Enet = Enet::new().unwrap();
}
#[test]
fn test_enet_new() {
let _ = *ENET;
assert!(Enet::new().is_err());
}
#[test]
fn test_host_create_localhost() {
use crate::Address;
use std::net::Ipv4Addr;
let enet = &ENET;
enet.create_host::<()>(
Some(&Address::new(Ipv4Addr::LOCALHOST, 12345)),
1,
ChannelLimit::Maximum,
BandwidthLimit::Unlimited,
BandwidthLimit::Unlimited,
)
.unwrap();
}
}