This repository was archived by the owner on Apr 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathuv_compat.rs
More file actions
1961 lines (1819 loc) · 57.5 KB
/
uv_compat.rs
File metadata and controls
1961 lines (1819 loc) · 57.5 KB
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018-2025 the Deno authors. MIT license.
// Drop-in replacement for libuv integrated with deno_core's event loop.
use std::cell::Cell;
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::collections::VecDeque;
use std::ffi::c_char;
use std::ffi::c_int;
use std::ffi::c_uint;
use std::ffi::c_void;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
use std::task::Waker;
use std::time::Instant;
#[cfg(unix)]
use libc::AF_INET;
#[cfg(unix)]
use libc::AF_INET6;
#[cfg(unix)]
use libc::sockaddr_in;
#[cfg(unix)]
use libc::sockaddr_in6;
#[cfg(unix)]
type sa_family_t = libc::sa_family_t;
#[cfg(windows)]
use win_sock::AF_INET;
#[cfg(windows)]
use win_sock::AF_INET6;
#[cfg(windows)]
use win_sock::sockaddr_in;
#[cfg(windows)]
use win_sock::sockaddr_in6;
#[cfg(windows)]
type sa_family_t = win_sock::sa_family_t;
// libc doesn't export socket structs on Windows.
#[cfg(windows)]
mod win_sock {
#[repr(C)]
pub struct in_addr {
pub s_addr: u32,
}
#[repr(C)]
pub struct sockaddr_in {
pub sin_family: u16,
pub sin_port: u16,
pub sin_addr: in_addr,
pub sin_zero: [u8; 8],
}
#[repr(C)]
pub struct in6_addr {
pub s6_addr: [u8; 16],
}
#[repr(C)]
pub struct sockaddr_in6 {
pub sin6_family: u16,
pub sin6_port: u16,
pub sin6_flowinfo: u32,
pub sin6_addr: in6_addr,
pub sin6_scope_id: u32,
}
pub const AF_INET: i32 = 2;
pub const AF_INET6: i32 = 23;
pub type sa_family_t = u16;
pub const SD_SEND: i32 = 1;
unsafe extern "system" {
pub fn shutdown(socket: usize, how: i32) -> i32;
}
}
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum uv_handle_type {
UV_UNKNOWN_HANDLE = 0,
UV_TIMER = 1,
UV_IDLE = 2,
UV_PREPARE = 3,
UV_CHECK = 4,
UV_TCP = 12,
}
const UV_HANDLE_ACTIVE: u32 = 1 << 0;
const UV_HANDLE_REF: u32 = 1 << 1;
const UV_HANDLE_CLOSING: u32 = 1 << 2;
// libuv-compatible error codes (negative errno values on unix,
// which vary depending on platform, fixed values on windows).
macro_rules! uv_errno {
($name:ident, $unix:expr, $win:expr) => {
#[cfg(unix)]
pub const $name: i32 = -($unix);
#[cfg(windows)]
pub const $name: i32 = $win;
};
}
uv_errno!(UV_EAGAIN, libc::EAGAIN, -4088);
uv_errno!(UV_EBADF, libc::EBADF, -4083);
uv_errno!(UV_EADDRINUSE, libc::EADDRINUSE, -4091);
uv_errno!(UV_ECONNREFUSED, libc::ECONNREFUSED, -4078);
uv_errno!(UV_EINVAL, libc::EINVAL, -4071);
uv_errno!(UV_ENOTCONN, libc::ENOTCONN, -4053);
uv_errno!(UV_ECANCELED, libc::ECANCELED, -4081);
uv_errno!(UV_EPIPE, libc::EPIPE, -4047);
pub const UV_EOF: i32 = -4095;
#[repr(C)]
pub struct uv_loop_t {
internal: *mut c_void,
pub data: *mut c_void,
stop_flag: Cell<bool>,
}
#[repr(C)]
pub struct uv_handle_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
}
#[repr(C)]
pub struct uv_timer_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
internal_id: u64,
internal_deadline: u64,
cb: Option<unsafe extern "C" fn(*mut uv_timer_t)>,
timeout: u64,
repeat: u64,
}
#[repr(C)]
pub struct uv_idle_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
cb: Option<unsafe extern "C" fn(*mut uv_idle_t)>,
}
#[repr(C)]
pub struct uv_prepare_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
cb: Option<unsafe extern "C" fn(*mut uv_prepare_t)>,
}
#[repr(C)]
pub struct uv_check_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
cb: Option<unsafe extern "C" fn(*mut uv_check_t)>,
}
#[repr(C)]
pub struct uv_stream_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
}
#[repr(C)]
pub struct uv_tcp_t {
pub r#type: uv_handle_type,
pub loop_: *mut uv_loop_t,
pub data: *mut c_void,
pub flags: u32,
#[cfg(unix)]
internal_fd: Option<std::os::unix::io::RawFd>,
#[cfg(windows)]
internal_fd: Option<std::os::windows::io::RawSocket>,
internal_bind_addr: Option<SocketAddr>,
internal_stream: Option<tokio::net::TcpStream>,
internal_listener: Option<tokio::net::TcpListener>,
internal_listener_addr: Option<SocketAddr>,
internal_nodelay: bool,
internal_alloc_cb: Option<uv_alloc_cb>,
internal_read_cb: Option<uv_read_cb>,
internal_reading: bool,
internal_connect: Option<ConnectPending>,
internal_write_queue: VecDeque<WritePending>,
internal_connection_cb: Option<uv_connection_cb>,
internal_backlog: VecDeque<tokio::net::TcpStream>,
}
/// In-flight TCP connect operation.
///
/// # Safety
/// `req` is a raw pointer to a caller-owned `uv_connect_t`. The caller must
/// ensure it remains valid until the connect callback fires (at which point
/// `ConnectPending` is consumed). This struct is `!Send` -- it lives on the
/// event loop thread alongside `UvLoopInner`.
struct ConnectPending {
future: Pin<Box<dyn Future<Output = std::io::Result<tokio::net::TcpStream>>>>,
req: *mut uv_connect_t,
cb: Option<uv_connect_cb>,
}
/// Queued write operation waiting for the socket to become writable.
///
/// # Safety
/// `req` is a raw pointer to a caller-owned `uv_write_t`. The caller must
/// ensure it remains valid until the write callback fires (at which point
/// `WritePending` is consumed). This struct is `!Send`.
struct WritePending {
req: *mut uv_write_t,
data: Vec<u8>,
offset: usize,
cb: Option<uv_write_cb>,
}
#[repr(C)]
pub struct uv_write_t {
pub r#type: i32, // UV_REQ_TYPE fields
pub data: *mut c_void,
pub handle: *mut uv_stream_t,
}
#[repr(C)]
pub struct uv_connect_t {
pub r#type: i32,
pub data: *mut c_void,
pub handle: *mut uv_stream_t,
}
#[repr(C)]
pub struct uv_shutdown_t {
pub r#type: i32,
pub data: *mut c_void,
pub handle: *mut uv_stream_t,
}
/// I/O buffer descriptor matching libuv's `uv_buf_t`.
///
/// Field order is `{base, len}` which matches the macOS/Windows layout.
/// On Linux, real libuv uses `{len, base}` (matching `struct iovec`).
/// This is fine as long as the struct is only constructed/consumed in Rust;
/// if it ever needs to cross an FFI boundary to real C code on Linux,
/// the field order must be made platform-conditional.
#[repr(C)]
pub struct uv_buf_t {
pub base: *mut c_char,
pub len: usize,
}
pub type uv_timer_cb = unsafe extern "C" fn(*mut uv_timer_t);
pub type uv_idle_cb = unsafe extern "C" fn(*mut uv_idle_t);
pub type uv_prepare_cb = unsafe extern "C" fn(*mut uv_prepare_t);
pub type uv_check_cb = unsafe extern "C" fn(*mut uv_check_t);
pub type uv_close_cb = unsafe extern "C" fn(*mut uv_handle_t);
pub type uv_write_cb = unsafe extern "C" fn(*mut uv_write_t, i32);
pub type uv_alloc_cb =
unsafe extern "C" fn(*mut uv_handle_t, usize, *mut uv_buf_t);
pub type uv_read_cb =
unsafe extern "C" fn(*mut uv_stream_t, isize, *const uv_buf_t);
pub type uv_connection_cb = unsafe extern "C" fn(*mut uv_stream_t, i32);
pub type uv_connect_cb = unsafe extern "C" fn(*mut uv_connect_t, i32);
pub type uv_shutdown_cb = unsafe extern "C" fn(*mut uv_shutdown_t, i32);
pub type UvHandle = uv_handle_t;
pub type UvLoop = uv_loop_t;
pub type UvStream = uv_stream_t;
pub type UvTcp = uv_tcp_t;
pub type UvWrite = uv_write_t;
pub type UvBuf = uv_buf_t;
pub type UvConnect = uv_connect_t;
pub type UvShutdown = uv_shutdown_t;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct TimerKey {
deadline_ms: u64,
id: u64,
}
pub(crate) struct UvLoopInner {
timers: RefCell<BTreeSet<TimerKey>>,
next_timer_id: Cell<u64>,
timer_handles: RefCell<HashMap<u64, *mut uv_timer_t>>,
idle_handles: RefCell<Vec<*mut uv_idle_t>>,
prepare_handles: RefCell<Vec<*mut uv_prepare_t>>,
check_handles: RefCell<Vec<*mut uv_check_t>>,
tcp_handles: RefCell<Vec<*mut uv_tcp_t>>,
waker: RefCell<Option<Waker>>,
closing_handles: RefCell<VecDeque<(*mut uv_handle_t, Option<uv_close_cb>)>>,
time_origin: Instant,
}
impl UvLoopInner {
fn new() -> Self {
Self {
timers: RefCell::new(BTreeSet::new()),
next_timer_id: Cell::new(1),
timer_handles: RefCell::new(HashMap::with_capacity(16)),
idle_handles: RefCell::new(Vec::with_capacity(8)),
prepare_handles: RefCell::new(Vec::with_capacity(8)),
check_handles: RefCell::new(Vec::with_capacity(8)),
tcp_handles: RefCell::new(Vec::with_capacity(8)),
waker: RefCell::new(None),
closing_handles: RefCell::new(VecDeque::with_capacity(16)),
time_origin: Instant::now(),
}
}
pub(crate) fn set_waker(&self, waker: &Waker) {
let mut slot = self.waker.borrow_mut();
match slot.as_ref() {
Some(existing) if existing.will_wake(waker) => {}
_ => *slot = Some(waker.clone()),
}
}
#[inline]
fn alloc_timer_id(&self) -> u64 {
let id = self.next_timer_id.get();
self.next_timer_id.set(id + 1);
id
}
#[inline]
fn now_ms(&self) -> u64 {
Instant::now().duration_since(self.time_origin).as_millis() as u64
}
pub(crate) fn has_alive_handles(&self) -> bool {
for (_, handle_ptr) in self.timer_handles.borrow().iter() {
// SAFETY: Handle pointers in timer_handles are kept valid by the C caller until uv_close.
let handle = unsafe { &**handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& handle.flags & UV_HANDLE_REF != 0
{
return true;
}
}
for handle_ptr in self.idle_handles.borrow().iter() {
// SAFETY: Handle pointers in idle_handles are kept valid by the C caller until uv_close.
let handle = unsafe { &**handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& handle.flags & UV_HANDLE_REF != 0
{
return true;
}
}
for handle_ptr in self.prepare_handles.borrow().iter() {
// SAFETY: Handle pointers in prepare_handles are kept valid by the C caller until uv_close.
let handle = unsafe { &**handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& handle.flags & UV_HANDLE_REF != 0
{
return true;
}
}
for handle_ptr in self.check_handles.borrow().iter() {
// SAFETY: Handle pointers in check_handles are kept valid by the C caller until uv_close.
let handle = unsafe { &**handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& handle.flags & UV_HANDLE_REF != 0
{
return true;
}
}
for handle_ptr in self.tcp_handles.borrow().iter() {
// SAFETY: Handle pointers in tcp_handles are kept valid by the C caller until uv_close.
let handle = unsafe { &**handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& handle.flags & UV_HANDLE_REF != 0
{
return true;
}
}
if !self.closing_handles.borrow().is_empty() {
return true;
}
false
}
/// ### Safety
/// All timer handle pointers stored in `timer_handles` must be valid.
pub(crate) unsafe fn run_timers(&self) {
let now = self.now_ms();
let mut expired = Vec::new();
{
let timers = self.timers.borrow();
for key in timers.iter() {
if key.deadline_ms > now {
break;
}
expired.push(*key);
}
}
for key in expired {
self.timers.borrow_mut().remove(&key);
let handle_ptr = match self.timer_handles.borrow().get(&key.id).copied() {
Some(h) => h,
None => continue,
};
// SAFETY: handle_ptr comes from timer_handles; caller guarantees validity.
let handle = unsafe { &mut *handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE == 0 {
self.timer_handles.borrow_mut().remove(&key.id);
continue;
}
let cb = handle.cb;
let repeat = handle.repeat;
if repeat > 0 {
let new_deadline = now + repeat;
let new_key = TimerKey {
deadline_ms: new_deadline,
id: key.id,
};
handle.internal_deadline = new_deadline;
self.timers.borrow_mut().insert(new_key);
} else {
handle.flags &= !UV_HANDLE_ACTIVE;
self.timer_handles.borrow_mut().remove(&key.id);
}
if let Some(cb) = cb {
// SAFETY: handle_ptr is valid; cb was set by the C caller via uv_timer_start.
unsafe { cb(handle_ptr) };
}
}
}
/// ### Safety
/// All idle handle pointers stored in `idle_handles` must be valid.
pub(crate) unsafe fn run_idle(&self) {
let mut i = 0;
loop {
let handle_ptr = {
let handles = self.idle_handles.borrow();
if i >= handles.len() {
break;
}
handles[i]
};
i += 1;
// SAFETY: handle_ptr comes from idle_handles; caller guarantees validity.
let handle = unsafe { &*handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& let Some(cb) = handle.cb
{
// SAFETY: Callback set by C caller via uv_idle_start; handle_ptr is valid.
unsafe { cb(handle_ptr) };
}
}
}
/// ### Safety
/// All prepare handle pointers stored in `prepare_handles` must be valid.
pub(crate) unsafe fn run_prepare(&self) {
let mut i = 0;
loop {
let handle_ptr = {
let handles = self.prepare_handles.borrow();
if i >= handles.len() {
break;
}
handles[i]
};
i += 1;
// SAFETY: handle_ptr comes from prepare_handles; caller guarantees validity.
let handle = unsafe { &*handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& let Some(cb) = handle.cb
{
// SAFETY: Callback set by C caller via uv_prepare_start; handle_ptr is valid.
unsafe { cb(handle_ptr) };
}
}
}
/// ### Safety
/// All check handle pointers stored in `check_handles` must be valid.
pub(crate) unsafe fn run_check(&self) {
let mut i = 0;
loop {
let handle_ptr = {
let handles = self.check_handles.borrow();
if i >= handles.len() {
break;
}
handles[i]
};
i += 1;
// SAFETY: handle_ptr comes from check_handles; caller guarantees validity.
let handle = unsafe { &*handle_ptr };
if handle.flags & UV_HANDLE_ACTIVE != 0
&& let Some(cb) = handle.cb
{
// SAFETY: Callback set by C caller via uv_check_start; handle_ptr is valid.
unsafe { cb(handle_ptr) };
}
}
}
/// ### Safety
/// All handle pointers in `closing_handles` must be valid.
pub(crate) unsafe fn run_close(&self) {
let mut closing = self.closing_handles.borrow_mut();
let snapshot: Vec<_> = closing.drain(..).collect();
drop(closing);
for (handle_ptr, cb) in snapshot {
if let Some(cb) = cb {
// SAFETY: handle_ptr is valid; cb was registered by C caller via uv_close.
unsafe { cb(handle_ptr) };
}
}
}
/// Poll all TCP handles for I/O readiness and fire callbacks.
///
/// Uses direct polling via tokio's `poll_accept`/`try_read`/`try_write`.
/// No spawned tasks, no channels -- zero allocation in the hot path.
///
/// Multiple passes: after callbacks fire they may produce new data
/// (e.g. HTTP2 frame processing triggers writes which complete
/// immediately). Re-poll up to 16 times to batch I/O within a
/// single event loop tick.
///
/// # Safety
/// All TCP handle pointers in `tcp_handles` must be valid.
pub(crate) unsafe fn run_io(&self) -> bool {
let noop = Waker::noop();
let waker_ref = self.waker.borrow();
let waker = waker_ref.as_ref().unwrap_or(noop);
let mut cx = Context::from_waker(waker);
let mut did_any_work = false;
for _pass in 0..16 {
let mut any_work = false;
let mut i = 0;
loop {
let tcp_ptr = {
let handles = self.tcp_handles.borrow();
if i >= handles.len() {
break;
}
handles[i]
};
i += 1;
// SAFETY: tcp_ptr comes from tcp_handles; caller guarantees validity.
let tcp = unsafe { &mut *tcp_ptr };
if tcp.flags & UV_HANDLE_ACTIVE == 0 {
continue;
}
// 1. Poll pending connect
if let Some(ref mut pending) = tcp.internal_connect
&& let Poll::Ready(result) = pending.future.as_mut().poll(&mut cx)
{
let req = pending.req;
let cb = pending.cb;
let status = match result {
Ok(stream) => {
if tcp.internal_nodelay {
stream.set_nodelay(true).ok();
}
tcp.internal_stream = Some(stream);
0
}
Err(_) => UV_ECONNREFUSED,
};
tcp.internal_connect = None;
// SAFETY: req pointer was provided by the C caller and remains valid until callback.
unsafe {
(*req).handle = tcp_ptr as *mut uv_stream_t;
}
if let Some(cb) = cb {
// SAFETY: Callback and req pointer validated above; set by C caller via uv_tcp_connect.
unsafe { cb(req, status) };
}
}
// 2. Poll listener for new connections
if let Some(ref listener) = tcp.internal_listener
&& tcp.internal_connection_cb.is_some()
{
while let Poll::Ready(Ok((stream, _))) = listener.poll_accept(&mut cx)
{
tcp.internal_backlog.push_back(stream);
any_work = true;
}
while !tcp.internal_backlog.is_empty() {
if let Some(cb) = tcp.internal_connection_cb {
// SAFETY: tcp_ptr is valid; cb set by C caller via uv_listen.
unsafe { cb(tcp_ptr as *mut uv_stream_t, 0) };
}
// If uv_accept wasn't called in the callback, stop
// to avoid an infinite loop.
if !tcp.internal_backlog.is_empty() {
break;
}
}
}
// 3. Poll readable stream
if tcp.internal_reading && tcp.internal_stream.is_some() {
let alloc_cb = tcp.internal_alloc_cb;
let read_cb = tcp.internal_read_cb;
if let (Some(alloc_cb), Some(read_cb)) = (alloc_cb, read_cb) {
// Register interest so tokio's reactor wakes us.
let _ = tcp
.internal_stream
.as_ref()
.unwrap()
.poll_read_ready(&mut cx);
loop {
// Re-check after each callback: the callback may have
// called uv_close or uv_read_stop.
if !tcp.internal_reading || tcp.internal_stream.is_none() {
break;
}
let mut buf = uv_buf_t {
base: std::ptr::null_mut(),
len: 0,
};
// SAFETY: alloc_cb set by C caller via uv_read_start; tcp_ptr is valid.
unsafe {
alloc_cb(tcp_ptr as *mut uv_handle_t, 65536, &mut buf);
}
if buf.base.is_null() || buf.len == 0 {
break;
}
// SAFETY: alloc_cb guarantees buf.base is valid for buf.len bytes.
let slice = unsafe {
std::slice::from_raw_parts_mut(buf.base.cast::<u8>(), buf.len)
};
match tcp.internal_stream.as_ref().unwrap().try_read(slice) {
Ok(0) => {
// SAFETY: read_cb set by C caller via uv_read_start; tcp_ptr and buf are valid.
unsafe {
read_cb(tcp_ptr as *mut uv_stream_t, UV_EOF as isize, &buf)
};
tcp.internal_reading = false;
break;
}
Ok(n) => {
any_work = true;
// SAFETY: read_cb set by C caller via uv_read_start; tcp_ptr and buf are valid.
unsafe {
read_cb(tcp_ptr as *mut uv_stream_t, n as isize, &buf)
};
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
break;
}
Err(_) => {
// SAFETY: read_cb set by C caller via uv_read_start; tcp_ptr and buf are valid.
unsafe {
read_cb(tcp_ptr as *mut uv_stream_t, UV_EOF as isize, &buf)
};
tcp.internal_reading = false;
break;
}
}
}
}
}
// 4. Drain write queue in order
if !tcp.internal_write_queue.is_empty() && tcp.internal_stream.is_some()
{
let stream = tcp.internal_stream.as_ref().unwrap();
let _ = stream.poll_write_ready(&mut cx);
while let Some(pw) = tcp.internal_write_queue.front_mut() {
let mut done = false;
let mut error = false;
loop {
if pw.offset >= pw.data.len() {
done = true;
break;
}
match stream.try_write(&pw.data[pw.offset..]) {
Ok(n) => pw.offset += n,
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
break;
}
Err(_) => {
error = true;
break;
}
}
}
if done {
let pw = tcp.internal_write_queue.pop_front().unwrap();
if let Some(cb) = pw.cb {
// SAFETY: Write cb and req set by C caller via uv_write; req is valid until callback.
unsafe { cb(pw.req, 0) };
}
} else if error {
let pw = tcp.internal_write_queue.pop_front().unwrap();
if let Some(cb) = pw.cb {
// SAFETY: Write cb and req set by C caller via uv_write; req is valid until callback.
unsafe { cb(pw.req, UV_EPIPE) };
}
} else {
break; // WouldBlock -- retry next tick
}
}
}
} // end per-handle loop
if !any_work {
break;
}
did_any_work = true;
} // end multi-pass loop
did_any_work
}
/// ### Safety
/// `handle` must be a valid pointer to an initialized `uv_timer_t`.
unsafe fn stop_timer(&self, handle: *mut uv_timer_t) {
// SAFETY: Caller guarantees handle is valid and initialized.
let handle_ref = unsafe { &mut *handle };
let id = handle_ref.internal_id;
if id != 0 {
let key = TimerKey {
deadline_ms: handle_ref.internal_deadline,
id,
};
self.timers.borrow_mut().remove(&key);
self.timer_handles.borrow_mut().remove(&id);
}
handle_ref.flags &= !UV_HANDLE_ACTIVE;
}
fn stop_idle(&self, handle: *mut uv_idle_t) {
self
.idle_handles
.borrow_mut()
.retain(|&h| !std::ptr::eq(h, handle));
// SAFETY: Caller guarantees handle is valid and initialized.
unsafe {
(*handle).flags &= !UV_HANDLE_ACTIVE;
}
}
fn stop_prepare(&self, handle: *mut uv_prepare_t) {
self
.prepare_handles
.borrow_mut()
.retain(|&h| !std::ptr::eq(h, handle));
// SAFETY: Caller guarantees handle is valid and initialized.
unsafe {
(*handle).flags &= !UV_HANDLE_ACTIVE;
}
}
fn stop_check(&self, handle: *mut uv_check_t) {
self
.check_handles
.borrow_mut()
.retain(|&h| !std::ptr::eq(h, handle));
// SAFETY: Caller guarantees handle is valid and initialized.
unsafe {
(*handle).flags &= !UV_HANDLE_ACTIVE;
}
}
fn stop_tcp(&self, handle: *mut uv_tcp_t) {
self
.tcp_handles
.borrow_mut()
.retain(|&h| !std::ptr::eq(h, handle));
// SAFETY: Caller guarantees handle is valid and initialized.
unsafe {
let tcp = &mut *handle;
tcp.internal_reading = false;
tcp.internal_alloc_cb = None;
tcp.internal_read_cb = None;
tcp.internal_connection_cb = None;
tcp.internal_connect = None;
tcp.internal_write_queue.clear();
tcp.internal_stream = None;
tcp.internal_listener = None;
tcp.internal_backlog.clear();
tcp.flags &= !UV_HANDLE_ACTIVE;
}
}
}
/// ### Safety
/// `loop_` must be a valid pointer to a `uv_loop_t` previously initialized by `uv_loop_init`.
#[inline]
unsafe fn get_inner(loop_: *mut uv_loop_t) -> &'static UvLoopInner {
// SAFETY: Caller guarantees loop_ is valid and was initialized by uv_loop_init.
unsafe { &*((*loop_).internal as *const UvLoopInner) }
}
/// ### Safety
/// `loop_` must be a valid pointer to a `uv_loop_t` previously initialized by `uv_loop_init`.
pub unsafe fn uv_loop_get_inner_ptr(
loop_: *const uv_loop_t,
) -> *const std::ffi::c_void {
// SAFETY: Caller guarantees loop_ is valid and was initialized by uv_loop_init.
unsafe { (*loop_).internal as *const std::ffi::c_void }
}
/// ### Safety
/// `loop_` must be a valid, non-null pointer to an uninitialized `uv_loop_t`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_loop_init(loop_: *mut uv_loop_t) -> c_int {
let inner = Box::new(UvLoopInner::new());
// SAFETY: Caller guarantees loop_ is a valid, writable pointer.
unsafe {
(*loop_).internal = Box::into_raw(inner) as *mut c_void;
(*loop_).data = std::ptr::null_mut();
(*loop_).stop_flag = Cell::new(false);
}
0
}
/// ### Safety
/// `loop_` must be a valid pointer to a `uv_loop_t` initialized by `uv_loop_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_loop_close(loop_: *mut uv_loop_t) -> c_int {
// SAFETY: Caller guarantees loop_ was initialized by uv_loop_init.
unsafe {
let internal = (*loop_).internal;
if !internal.is_null() {
drop(Box::from_raw(internal as *mut UvLoopInner));
(*loop_).internal = std::ptr::null_mut();
}
}
0
}
/// ### Safety
/// `loop_` must be a valid pointer to a `uv_loop_t` initialized by `uv_loop_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_now(loop_: *mut uv_loop_t) -> u64 {
// SAFETY: Caller guarantees loop_ was initialized by uv_loop_init.
let inner = unsafe { get_inner(loop_) };
inner.now_ms()
}
/// ### Safety
/// `_loop_` must be a valid pointer to a `uv_loop_t` initialized by `uv_loop_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_update_time(_loop_: *mut uv_loop_t) {}
/// ### Safety
/// `loop_` must be initialized by `uv_loop_init`. `handle` must be a valid, writable pointer.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_timer_init(
loop_: *mut uv_loop_t,
handle: *mut uv_timer_t,
) -> c_int {
// SAFETY: Caller guarantees both pointers are valid.
unsafe {
(*handle).r#type = uv_handle_type::UV_TIMER;
(*handle).loop_ = loop_;
(*handle).data = std::ptr::null_mut();
(*handle).flags = UV_HANDLE_REF;
(*handle).internal_id = 0;
(*handle).internal_deadline = 0;
(*handle).cb = None;
(*handle).timeout = 0;
(*handle).repeat = 0;
}
0
}
/// ### Safety
/// `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_timer_start(
handle: *mut uv_timer_t,
cb: uv_timer_cb,
timeout: u64,
repeat: u64,
) -> c_int {
// SAFETY: Caller guarantees handle was initialized by uv_timer_init.
unsafe {
let loop_ = (*handle).loop_;
let inner = get_inner(loop_);
if (*handle).flags & UV_HANDLE_ACTIVE != 0 {
inner.stop_timer(handle);
}
let id = inner.alloc_timer_id();
let deadline = inner.now_ms() + timeout;
(*handle).cb = Some(cb);
(*handle).timeout = timeout;
(*handle).repeat = repeat;
(*handle).internal_id = id;
(*handle).internal_deadline = deadline;
(*handle).flags |= UV_HANDLE_ACTIVE;
let key = TimerKey {
deadline_ms: deadline,
id,
};
inner.timers.borrow_mut().insert(key);
inner.timer_handles.borrow_mut().insert(id, handle);
}
0
}
/// ### Safety
/// `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_timer_stop(handle: *mut uv_timer_t) -> c_int {
// SAFETY: Caller guarantees handle was initialized by uv_timer_init.
unsafe {
let loop_ = (*handle).loop_;
if loop_.is_null() || (*loop_).internal.is_null() {
(*handle).flags &= !UV_HANDLE_ACTIVE;
return 0;
}
let inner = get_inner(loop_);
inner.stop_timer(handle);
}
0
}
/// ### Safety
/// `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_timer_again(handle: *mut uv_timer_t) -> c_int {
// SAFETY: Caller guarantees handle was initialized by uv_timer_init.
unsafe {
let repeat = (*handle).repeat;
if repeat == 0 {
return UV_EINVAL;
}
let loop_ = (*handle).loop_;
let inner = get_inner(loop_);
inner.stop_timer(handle);
let id = inner.alloc_timer_id();
let deadline = inner.now_ms() + repeat;
(*handle).internal_id = id;
(*handle).internal_deadline = deadline;
(*handle).flags |= UV_HANDLE_ACTIVE;
let key = TimerKey {
deadline_ms: deadline,
id,
};
inner.timers.borrow_mut().insert(key);
inner.timer_handles.borrow_mut().insert(id, handle);
}
0
}
/// ### Safety
/// `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_timer_get_repeat(handle: *const uv_timer_t) -> u64 {
// SAFETY: Caller guarantees handle is valid and initialized.
unsafe { (*handle).repeat }
}
/// ### Safety
/// `handle` must be a valid pointer to a `uv_timer_t` initialized by `uv_timer_init`.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_timer_set_repeat(
handle: *mut uv_timer_t,
repeat: u64,
) {
// SAFETY: Caller guarantees handle is valid and initialized.
unsafe {
(*handle).repeat = repeat;
}
}
/// ### Safety
/// `loop_` must be initialized by `uv_loop_init`. `handle` must be a valid, writable pointer.
#[cfg_attr(feature = "uv_compat_export", unsafe(no_mangle))]
pub unsafe extern "C" fn uv_idle_init(
loop_: *mut uv_loop_t,
handle: *mut uv_idle_t,