libxev-sys 0.0.1-rc.2

Low-level FFI bindings to libxev (built from vendored sources via Zig).
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const posix = std.posix;
const stream = @import("stream.zig");
const common = @import("common.zig");
const ThreadPool = @import("../ThreadPool.zig");
const net = @import("../posix.zig").net;
const xev_posix = @import("../posix.zig");

/// UDP client and server.
///
/// This is a "higher-level abstraction" in libxev. The goal of higher-level
/// abstractions in libxev are to make it easier to use specific functionality
/// with the event loop, but does not promise perfect flexibility or optimal
/// performance. In almost all cases, the abstraction is good enough. But,
/// if you have specific needs or want to push for the most optimal performance,
/// use the platform-specific Loop directly.
pub fn UDP(comptime xev: type) type {
    if (xev.dynamic) return UDPDynamic(xev);

    return switch (xev.backend) {
        // Supported, uses sendmsg/recvmsg exclusively
        .io_uring,
        .epoll,
        => UDPSendMsg(xev),

        // Supported, uses sendto/recvfrom
        .kqueue => UDPSendto(xev),

        // Supported with tweaks
        .iocp => UDPSendtoIOCP(xev),

        // Noop
        .wasi_poll => struct {},
    };
}

/// UDP implementation that uses sendto/recvfrom.
fn UDPSendto(comptime xev: type) type {
    return struct {
        const Self = @This();

        fd: posix.socket_t,

        /// See UDPSendMsg.State
        pub const State = struct {
            userdata: ?*anyopaque,
        };

        const S = stream.Stream(xev, Self, .{
            .close = true,
            .poll = true,
        });
        pub const close = S.close;
        pub const poll = S.poll;

        /// Initialize a new UDP with the family from the given address. Only
        /// the family is used, the actual address has no impact on the created
        /// resource.
        pub fn init(addr: std.Io.net.IpAddress) !Self {
            const posix_addr = net.Address.fromIpAddress(addr);
            return .{
                .fd = try xev_posix.socket(
                    posix_addr.any.family,
                    posix.SOCK.NONBLOCK | posix.SOCK.DGRAM | posix.SOCK.CLOEXEC,
                    0,
                ),
            };
        }

        /// Initialize a UDP socket from a file descriptor.
        pub fn initFd(fd: posix.socket_t) Self {
            return .{
                .fd = fd,
            };
        }

        /// Bind the address to the socket.
        pub fn bind(self: Self, addr: std.Io.net.IpAddress) !void {
            const posix_addr = net.Address.fromIpAddress(addr);
            try posix.setsockopt(self.fd, posix.SOL.SOCKET, posix.SO.REUSEPORT, &std.mem.toBytes(@as(c_int, 1)));
            try posix.setsockopt(self.fd, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
            try xev_posix.bind(self.fd, &posix_addr.any, posix_addr.getOsSockLen());
        }

        /// Read from the socket. This performs a single read. The callback must
        /// requeue the read if additional reads want to be performed. Additional
        /// reads simultaneously can be queued by calling this multiple times. Note
        /// that depending on the backend, the reads can happen out of order.
        pub fn read(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            buf: xev.ReadBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                addr: std.Io.net.IpAddress,
                s: Self,
                b: xev.ReadBuffer,
                r: xev.ReadError!usize,
            ) xev.CallbackAction,
        ) void {
            s.* = .{
                .userdata = userdata,
            };

            switch (buf) {
                inline .slice, .array => {
                    c.* = .{
                        .op = .{
                            .recvfrom = .{
                                .fd = self.fd,
                                .buffer = buf,
                            },
                        },
                        .userdata = s,
                        .callback = (struct {
                            fn callback(
                                ud: ?*anyopaque,
                                l_inner: *xev.Loop,
                                c_inner: *xev.Completion,
                                r: xev.Result,
                            ) xev.CallbackAction {
                                const s_inner = @as(?*State, @ptrCast(@alignCast(ud))).?;
                                return @call(.always_inline, cb, .{
                                    common.userdataValue(Userdata, s_inner.userdata),
                                    l_inner,
                                    c_inner,
                                    s_inner,
                                    net.Address.initPosix(@alignCast(&c_inner.op.recvfrom.addr)).toIpAddress(),
                                    initFd(c_inner.op.recvfrom.fd),
                                    c_inner.op.recvfrom.buffer,
                                    r.recvfrom,
                                });
                            }
                        }).callback,
                    };

                    loop.add(c);
                },
            }
        }

        /// Write to the socket. This performs a single write. Additional writes
        /// can be queued by calling this multiple times. Note that depending on the
        /// backend, writes can happen out of order.
        pub fn write(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            addr: std.Io.net.IpAddress,
            buf: xev.WriteBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                s: Self,
                b: xev.WriteBuffer,
                r: xev.WriteError!usize,
            ) xev.CallbackAction,
        ) void {
            const posix_addr = net.Address.fromIpAddress(addr);
            s.* = .{
                .userdata = userdata,
            };

            switch (buf) {
                inline .slice, .array => {
                    c.* = .{
                        .op = .{
                            .sendto = .{
                                .fd = self.fd,
                                .buffer = buf,
                                .addr = posix_addr,
                            },
                        },
                        .userdata = s,
                        .callback = (struct {
                            fn callback(
                                ud: ?*anyopaque,
                                l_inner: *xev.Loop,
                                c_inner: *xev.Completion,
                                r: xev.Result,
                            ) xev.CallbackAction {
                                const s_inner = @as(?*State, @ptrCast(@alignCast(ud))).?;
                                return @call(.always_inline, cb, .{
                                    common.userdataValue(Userdata, s_inner.userdata),
                                    l_inner,
                                    c_inner,
                                    s_inner,
                                    initFd(c_inner.op.sendto.fd),
                                    c_inner.op.sendto.buffer,
                                    r.sendto,
                                });
                            }
                        }).callback,
                    };

                    loop.add(c);
                },
            }
        }

        test {
            _ = UDPTests(xev, Self);
        }
    };
}

/// UDP implementation that uses sendto/recvfrom.
fn UDPSendtoIOCP(comptime xev: type) type {
    return struct {
        const Self = @This();
        const windows = @import("../windows.zig");

        fd: windows.HANDLE,

        /// See UDPSendMsg.State
        pub const State = struct {
            userdata: ?*anyopaque,
        };

        const S = stream.Stream(xev, Self, .{
            .close = true,
        });
        pub const close = S.close;

        /// Initialize a new UDP with the family from the given address. Only
        /// the family is used, the actual address has no impact on the created
        /// resource.
        pub fn init(addr: std.Io.net.IpAddress) !Self {
            const posix_addr = net.Address.fromIpAddress(addr);
            const socket = try windows.WSASocketW(posix_addr.any.family, windows.ws2_32.SOCK.DGRAM, 0, null, 0, windows.ws2_32.WSA_FLAG_OVERLAPPED);

            return .{
                .fd = socket,
            };
        }

        /// Initialize a UDP socket from a file descriptor.
        pub fn initFd(fd: windows.HANDLE) Self {
            return .{
                .fd = fd,
            };
        }

        /// Bind the address to the socket.
        pub fn bind(self: Self, addr: std.Io.net.IpAddress) !void {
            const posix_addr = net.Address.fromIpAddress(addr);
            const socket = @as(windows.ws2_32.SOCKET, @ptrCast(self.fd));
            if (windows.ws2_32.setsockopt(socket, windows.ws2_32.SOL.SOCKET, windows.ws2_32.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)), @sizeOf(c_int)) != 0) return error.Unexpected;
            if (windows.ws2_32.bind(socket, &posix_addr.any, @as(i32, @intCast(posix_addr.getOsSockLen()))) != 0) return error.Unexpected;
        }

        /// Read from the socket. This performs a single read. The callback must
        /// requeue the read if additional reads want to be performed. Additional
        /// reads simultaneously can be queued by calling this multiple times. Note
        /// that depending on the backend, the reads can happen out of order.
        ///
        /// TODO(mitchellh): a way to receive the remote addr
        pub fn read(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            buf: xev.ReadBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                addr: std.Io.net.IpAddress,
                s: Self,
                b: xev.ReadBuffer,
                r: xev.ReadError!usize,
            ) xev.CallbackAction,
        ) void {
            s.* = .{
                .userdata = userdata,
            };

            switch (buf) {
                inline .slice, .array => {
                    c.* = .{
                        .op = .{
                            .recvfrom = .{
                                .fd = self.fd,
                                .buffer = buf,
                            },
                        },
                        .userdata = s,
                        .callback = (struct {
                            fn callback(
                                ud: ?*anyopaque,
                                l_inner: *xev.Loop,
                                c_inner: *xev.Completion,
                                r: xev.Result,
                            ) xev.CallbackAction {
                                const s_inner: *State = @ptrCast(@alignCast(ud.?));
                                return @call(.always_inline, cb, .{
                                    common.userdataValue(Userdata, s_inner.userdata),
                                    l_inner,
                                    c_inner,
                                    s_inner,
                                    net.Address.initPosix(@alignCast(&c_inner.op.recvfrom.addr)).toIpAddress(),
                                    initFd(c_inner.op.recvfrom.fd),
                                    c_inner.op.recvfrom.buffer,
                                    r.recvfrom,
                                });
                            }
                        }).callback,
                    };

                    loop.add(c);
                },
            }
        }

        /// Write to the socket. This performs a single write. Additional writes
        /// can be queued by calling this multiple times. Note that depending on the
        /// backend, writes can happen out of order.
        pub fn write(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            addr: std.Io.net.IpAddress,
            buf: xev.WriteBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                s: Self,
                b: xev.WriteBuffer,
                r: xev.WriteError!usize,
            ) xev.CallbackAction,
        ) void {
            const posix_addr = net.Address.fromIpAddress(addr);
            s.* = .{
                .userdata = userdata,
            };

            switch (buf) {
                inline .slice, .array => {
                    c.* = .{
                        .op = .{
                            .sendto = .{
                                .fd = self.fd,
                                .buffer = buf,
                                .addr = posix_addr,
                            },
                        },
                        .userdata = s,
                        .callback = (struct {
                            fn callback(
                                ud: ?*anyopaque,
                                l_inner: *xev.Loop,
                                c_inner: *xev.Completion,
                                r: xev.Result,
                            ) xev.CallbackAction {
                                const s_inner: *State = @ptrCast(@alignCast(ud.?));
                                return @call(.always_inline, cb, .{
                                    common.userdataValue(Userdata, s_inner.userdata),
                                    l_inner,
                                    c_inner,
                                    s_inner,
                                    initFd(c_inner.op.sendto.fd),
                                    c_inner.op.sendto.buffer,
                                    r.sendto,
                                });
                            }
                        }).callback,
                    };

                    loop.add(c);
                },
            }
        }

        test {
            _ = UDPTests(xev, Self);
        }
    };
}

/// UDP implementation that uses sendmsg/recvmsg
fn UDPSendMsg(comptime xev: type) type {
    return struct {
        const Self = @This();

        const linux = std.os.linux;

        fd: posix.socket_t,

        /// UDP requires some extra state to perform operations. The state is
        /// opaque. This isn't part of xev.Completion because it is relatively
        /// large and would force ALL operations (not just UDP) to have a relatively
        /// large structure size and we didn't want to pay that cost.
        pub const State = struct {
            userdata: ?*anyopaque = null,
            op: union {
                recv: struct {
                    buf: xev.ReadBuffer,
                    addr_buffer: std.posix.sockaddr.storage = undefined,
                    msghdr: linux.msghdr,
                    iov: [1]posix.iovec,
                },

                send: struct {
                    buf: xev.WriteBuffer,
                    addr: net.Address,
                    msghdr: linux.msghdr_const,
                    iov: [1]posix.iovec_const,
                },
            },
        };

        const S = stream.Stream(xev, Self, .{
            .close = true,
            .poll = true,
        });
        pub const close = S.close;
        pub const poll = S.poll;

        /// Initialize a new UDP with the family from the given address. Only
        /// the family is used, the actual address has no impact on the created
        /// resource.
        pub fn init(addr: std.Io.net.IpAddress) !Self {
            const posix_addr = net.Address.fromIpAddress(addr);
            // On io_uring we don't use non-blocking sockets because we may
            // just get EAGAIN over and over from completions.
            const flags = flags: {
                var flags: u32 = posix.SOCK.DGRAM | posix.SOCK.CLOEXEC;
                if (xev.backend != .io_uring) flags |= posix.SOCK.NONBLOCK;
                break :flags flags;
            };

            return .{
                .fd = try xev_posix.socket(posix_addr.any.family, flags, 0),
            };
        }

        /// Initialize a UDP socket from a file descriptor.
        pub fn initFd(fd: posix.socket_t) Self {
            return .{
                .fd = fd,
            };
        }

        /// Bind the address to the socket.
        pub fn bind(self: Self, addr: std.Io.net.IpAddress) !void {
            const posix_addr = net.Address.fromIpAddress(addr);
            try posix.setsockopt(self.fd, posix.SOL.SOCKET, posix.SO.REUSEPORT, &std.mem.toBytes(@as(c_int, 1)));
            try posix.setsockopt(self.fd, posix.SOL.SOCKET, posix.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1)));
            try xev_posix.bind(self.fd, &posix_addr.any, posix_addr.getOsSockLen());
        }

        /// Read from the socket. This performs a single read. The callback must
        /// requeue the read if additional reads want to be performed. Additional
        /// reads simultaneously can be queued by calling this multiple times. Note
        /// that depending on the backend, the reads can happen out of order.
        pub fn read(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            buf: xev.ReadBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                addr: std.Io.net.IpAddress,
                s: Self,
                b: xev.ReadBuffer,
                r: xev.ReadError!usize,
            ) xev.CallbackAction,
        ) void {
            s.op = .{ .recv = undefined };
            s.* = .{
                .userdata = userdata,
                .op = .{
                    .recv = .{
                        .buf = buf,
                        .msghdr = .{
                            .name = @ptrCast(&s.op.recv.addr_buffer),
                            .namelen = @sizeOf(@TypeOf(s.op.recv.addr_buffer)),
                            .iov = &s.op.recv.iov,
                            .iovlen = 1,
                            .control = null,
                            .controllen = 0,
                            .flags = 0,
                        },
                        .iov = undefined,
                    },
                },
            };

            switch (s.op.recv.buf) {
                .slice => |v| {
                    s.op.recv.iov[0] = .{
                        .base = v.ptr,
                        .len = v.len,
                    };
                },

                .array => |*arr| {
                    s.op.recv.iov[0] = .{
                        .base = arr,
                        .len = arr.len,
                    };
                },
            }

            c.* = .{
                .op = .{
                    .recvmsg = .{
                        .fd = self.fd,
                        .msghdr = &s.op.recv.msghdr,
                    },
                },

                .userdata = s,
                .callback = (struct {
                    fn callback(
                        ud: ?*anyopaque,
                        l_inner: *xev.Loop,
                        c_inner: *xev.Completion,
                        r: xev.Result,
                    ) xev.CallbackAction {
                        const s_inner = @as(?*State, @ptrCast(@alignCast(ud))).?;
                        return @call(.always_inline, cb, .{
                            common.userdataValue(Userdata, s_inner.userdata),
                            l_inner,
                            c_inner,
                            s_inner,
                            net.Address.initPosix(@ptrCast(&s_inner.op.recv.addr_buffer)).toIpAddress(),
                            initFd(c_inner.op.recvmsg.fd),
                            s_inner.op.recv.buf,
                            if (r.recvmsg) |v| v else |err| err,
                        });
                    }
                }).callback,
            };

            // If we're dup-ing, then we ask the backend to manage the fd.
            switch (xev.backend) {
                .io_uring,
                .kqueue,
                .wasi_poll,
                .iocp,
                => {},

                .epoll => c.flags.dup = true,
            }

            loop.add(c);
        }

        /// Write to the socket. This performs a single write. Additional writes
        /// can be queued by calling this multiple times. Note that depending on the
        /// backend, writes can happen out of order.
        pub fn write(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            addr: std.Io.net.IpAddress,
            buf: xev.WriteBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                s: Self,
                b: xev.WriteBuffer,
                r: xev.WriteError!usize,
            ) xev.CallbackAction,
        ) void {
            const posix_addr = net.Address.fromIpAddress(addr);
            // Set the active field for runtime safety
            s.op = .{ .send = undefined };
            s.* = .{
                .userdata = userdata,
                .op = .{
                    .send = .{
                        .addr = posix_addr,
                        .buf = buf,
                        .msghdr = .{
                            .name = &s.op.send.addr.any,
                            .namelen = posix_addr.getOsSockLen(),
                            .iov = &s.op.send.iov,
                            .iovlen = 1,
                            .control = null,
                            .controllen = 0,
                            .flags = 0,
                        },
                        .iov = undefined,
                    },
                },
            };

            switch (s.op.send.buf) {
                .slice => |v| {
                    s.op.send.iov[0] = .{
                        .base = v.ptr,
                        .len = v.len,
                    };
                },

                .array => |*arr| {
                    s.op.send.iov[0] = .{
                        .base = &arr.array,
                        .len = arr.len,
                    };
                },
            }

            // On backends like epoll, you watch file descriptors for
            // specific events. Our implementation doesn't merge multiple
            // completions for a single fd, so we have to dup the fd. This
            // means we use more fds than we could optimally. This isn't a
            // problem with io_uring.

            c.* = .{
                .op = .{
                    .sendmsg = .{
                        .fd = self.fd,
                        .msghdr = &s.op.send.msghdr,
                    },
                },

                .userdata = s,
                .callback = (struct {
                    fn callback(
                        ud: ?*anyopaque,
                        l_inner: *xev.Loop,
                        c_inner: *xev.Completion,
                        r: xev.Result,
                    ) xev.CallbackAction {
                        const s_inner = @as(?*State, @ptrCast(@alignCast(ud))).?;
                        return @call(.always_inline, cb, .{
                            common.userdataValue(Userdata, s_inner.userdata),
                            l_inner,
                            c_inner,
                            s_inner,
                            initFd(c_inner.op.sendmsg.fd),
                            s_inner.op.send.buf,
                            if (r.sendmsg) |v| v else |err| err,
                        });
                    }
                }).callback,
            };

            // If we're dup-ing, then we ask the backend to manage the fd.
            switch (xev.backend) {
                .io_uring,
                .kqueue,
                .wasi_poll,
                .iocp,
                => {},

                .epoll => c.flags.dup = true,
            }

            loop.add(c);
        }

        test {
            _ = UDPTests(xev, Self);
        }
    };
}

fn UDPDynamic(comptime xev: type) type {
    return struct {
        const Self = @This();
        const FdType = if (builtin.os.tag == .windows)
            std.os.windows.HANDLE
        else
            posix.socket_t;

        backend: Union,

        pub const Union = xev.Union(&.{"UDP"});
        pub const State = xev.Union(&.{ "UDP", "State" });

        const S = stream.Stream(xev, Self, .{
            .close = true,
            .poll = true,
            .type = "UDP",
        });
        pub const close = S.close;
        pub const poll = S.poll;

        pub fn init(addr: std.Io.net.IpAddress) !Self {
            return .{ .backend = switch (xev.backend) {
                inline else => |tag| backend: {
                    const api = (comptime xev.superset(tag)).Api();
                    break :backend @unionInit(
                        Union,
                        @tagName(tag),
                        try api.UDP.init(addr),
                    );
                },
            } };
        }

        pub fn initFd(fdvalue: std.posix.pid_t) Self {
            return .{ .backend = switch (xev.backend) {
                inline else => |tag| backend: {
                    const api = (comptime xev.superset(tag)).Api();
                    break :backend @unionInit(
                        Union,
                        @tagName(tag),
                        api.UDP.initFd(fdvalue),
                    );
                },
            } };
        }

        pub fn bind(self: Self, addr: std.Io.net.IpAddress) !void {
            switch (xev.backend) {
                inline else => |tag| try @field(
                    self.backend,
                    @tagName(tag),
                ).bind(addr),
            }
        }

        pub fn fd(self: Self) FdType {
            switch (xev.backend) {
                inline else => |tag| return @field(
                    self.backend,
                    @tagName(tag),
                ).fd,
            }
        }

        pub fn read(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            buf: xev.ReadBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                addr: std.Io.net.IpAddress,
                s: Self,
                b: xev.ReadBuffer,
                r: xev.ReadError!usize,
            ) xev.CallbackAction,
        ) void {
            switch (xev.backend) {
                inline else => |tag| {
                    const api = (comptime xev.superset(tag)).Api();
                    const api_cb = (struct {
                        fn callback(
                            ud_inner: ?*Userdata,
                            l_inner: *api.Loop,
                            c_inner: *api.Completion,
                            st_inner: *api.UDP.State,
                            addr_inner: std.Io.net.IpAddress,
                            s_inner: api.UDP,
                            b_inner: api.ReadBuffer,
                            r_inner: api.ReadError!usize,
                        ) xev.CallbackAction {
                            return cb(
                                ud_inner,
                                @fieldParentPtr("backend", @as(
                                    *xev.Loop.Union,
                                    @fieldParentPtr(@tagName(tag), l_inner),
                                )),
                                @fieldParentPtr("value", @as(
                                    *xev.Completion.Union,
                                    @fieldParentPtr(@tagName(tag), c_inner),
                                )),
                                @fieldParentPtr(
                                    @tagName(tag),
                                    st_inner,
                                ),
                                addr_inner,
                                Self.initFd(s_inner.fd),
                                xev.ReadBuffer.fromBackend(tag, b_inner),
                                r_inner,
                            );
                        }
                    }).callback;

                    c.ensureTag(tag);
                    s.* = @unionInit(State, @tagName(tag), undefined);

                    @field(
                        self.backend,
                        @tagName(tag),
                    ).read(
                        &@field(loop.backend, @tagName(tag)),
                        &@field(c.value, @tagName(tag)),
                        &@field(s, @tagName(tag)),
                        buf.toBackend(tag),
                        Userdata,
                        userdata,
                        api_cb,
                    );
                },
            }
        }

        pub fn write(
            self: Self,
            loop: *xev.Loop,
            c: *xev.Completion,
            s: *State,
            addr: std.Io.net.IpAddress,
            buf: xev.WriteBuffer,
            comptime Userdata: type,
            userdata: ?*Userdata,
            comptime cb: *const fn (
                ud: ?*Userdata,
                l: *xev.Loop,
                c: *xev.Completion,
                s: *State,
                s: Self,
                b: xev.WriteBuffer,
                r: xev.WriteError!usize,
            ) xev.CallbackAction,
        ) void {
            switch (xev.backend) {
                inline else => |tag| {
                    const api = (comptime xev.superset(tag)).Api();
                    const api_cb = (struct {
                        fn callback(
                            ud_inner: ?*Userdata,
                            l_inner: *api.Loop,
                            c_inner: *api.Completion,
                            st_inner: *api.UDP.State,
                            s_inner: api.UDP,
                            b_inner: api.WriteBuffer,
                            r_inner: api.WriteError!usize,
                        ) xev.CallbackAction {
                            return cb(
                                ud_inner,
                                @fieldParentPtr("backend", @as(
                                    *xev.Loop.Union,
                                    @fieldParentPtr(@tagName(tag), l_inner),
                                )),
                                @fieldParentPtr("value", @as(
                                    *xev.Completion.Union,
                                    @fieldParentPtr(@tagName(tag), c_inner),
                                )),
                                @fieldParentPtr(
                                    @tagName(tag),
                                    st_inner,
                                ),
                                Self.initFd(s_inner.fd),
                                xev.WriteBuffer.fromBackend(tag, b_inner),
                                r_inner,
                            );
                        }
                    }).callback;

                    c.ensureTag(tag);
                    s.* = @unionInit(State, @tagName(tag), undefined);

                    @field(
                        self.backend,
                        @tagName(tag),
                    ).write(
                        &@field(loop.backend, @tagName(tag)),
                        &@field(c.value, @tagName(tag)),
                        &@field(s, @tagName(tag)),
                        addr,
                        buf.toBackend(tag),
                        Userdata,
                        userdata,
                        api_cb,
                    );
                },
            }
        }

        test {
            _ = UDPTests(xev, Self);
        }
    };
}

fn UDPTests(comptime xev: type, comptime Impl: type) type {
    return struct {
        test "UDP: Stream decls" {
            if (!@hasDecl(Impl, "S")) return;
            const Stream = Impl.S;
            inline for (@typeInfo(Stream).@"struct".decls) |decl| {
                const Decl = @TypeOf(@field(Stream, decl.name));
                if (Decl == void) continue;
                if (!@hasDecl(Impl, decl.name)) {
                    @compileError("missing decl: " ++ decl.name);
                }
            }
        }

        test "UDP: read/write" {
            if (builtin.os.tag == .freebsd) return error.SkipZigTest;
            const testing = std.testing;

            var tpool = ThreadPool.init(.{});
            defer tpool.deinit();
            defer tpool.shutdown();
            var loop = try xev.Loop.init(.{ .thread_pool = &tpool });
            defer loop.deinit();

            const address = try std.Io.net.IpAddress.parse("127.0.0.1", 3132);
            const server = try Impl.init(address);
            const client = try Impl.init(address);

            // Bind / Recv
            try server.bind(address);
            var c_read: xev.Completion = undefined;
            var s_read: Impl.State = undefined;
            var recv_buf: [128]u8 = undefined;
            var recv_len: usize = 0;
            server.read(&loop, &c_read, &s_read, .{ .slice = &recv_buf }, usize, &recv_len, (struct {
                fn callback(
                    ud: ?*usize,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    _: *Impl.State,
                    _: std.Io.net.IpAddress,
                    _: Impl,
                    _: xev.ReadBuffer,
                    r: xev.ReadError!usize,
                ) xev.CallbackAction {
                    ud.?.* = r catch unreachable;
                    return .disarm;
                }
            }).callback);

            // Send
            var send_buf = [_]u8{ 1, 1, 2, 3, 5, 8, 13 };
            var c_write: xev.Completion = undefined;
            var s_write: Impl.State = undefined;
            client.write(&loop, &c_write, &s_write, address, .{ .slice = &send_buf }, void, null, (struct {
                fn callback(
                    _: ?*void,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    _: *Impl.State,
                    _: Impl,
                    _: xev.WriteBuffer,
                    r: xev.WriteError!usize,
                ) xev.CallbackAction {
                    _ = r catch unreachable;
                    return .disarm;
                }
            }).callback);

            // Wait for the send/receive
            try loop.run(.until_done);
            try testing.expect(recv_len > 0);
            try testing.expectEqualSlices(u8, &send_buf, recv_buf[0..recv_len]);

            // Close
            server.close(&loop, &c_read, void, null, (struct {
                fn callback(
                    _: ?*void,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    _: Impl,
                    r: xev.CloseError!void,
                ) xev.CallbackAction {
                    _ = r catch unreachable;
                    return .disarm;
                }
            }).callback);
            client.close(&loop, &c_write, void, null, (struct {
                fn callback(
                    _: ?*void,
                    _: *xev.Loop,
                    _: *xev.Completion,
                    _: Impl,
                    r: xev.CloseError!void,
                ) xev.CallbackAction {
                    _ = r catch unreachable;
                    return .disarm;
                }
            }).callback);

            try loop.run(.until_done);
        }
    };
}