game-networking-sockets 0.2.0

Rust abstraction for Valve GameNetworkingSockets library.
Documentation
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
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
//! # Rust wrapper for Valve GameNetworkingSockets.
//!
//! Provides an abstraction over the low-level library.
//! There are multiple advantage to use this abstraction:
//! - Type safety: most of the low-level structures are wrapped and we leverage the type system to restrict the operations such that they are all **safe**.
//! - High level: the library abstract most of the structure in such a way that you don't have to deal with the low-level FFI plumbering required. The API is idiomatic, pure Rust.
//!
//! # Example
//!
//! ```
//! use gns::{GnsGlobal, GnsSocket, IsCreated};
//! use std::net::Ipv6Addr;
//! use std::time::Duration;
//!
//! // **uwrap** must be banned in production, we use it here to extract the most relevant part of the library.
//!
//! // Initial the global networking state. Note that this instance must be unique per-process.
//! let gns_global = GnsGlobal::get().unwrap();
//!
//! // Create a new [`GnsSocket`], the index type [`IsCreated`] is used to determine the state of the socket.
//! // The [`GnsSocket::new`] function is only available for the [`IsCreated`] state. This is the initial state of the socket.
//! let gns_socket = GnsSocket::<IsCreated>::new(gns_global);
//!
//! // Choose your own port
//! let port = 9001;
//!
//! // We now do a transition from [`IsCreated`] to the [`IsClient`] state. The [`GnsSocket::connect`] operation does this transition for us.
//! // Since we are now using a client socket, we have access to a different set of operations.
//! let client = gns_socket.connect(Ipv6Addr::LOCALHOST.into(), port).unwrap();
//!
//! // Now that we initiated a connection, there is three operation we must loop over:
//! // - polling for new messages
//! // - polling for connection status change
//! // - polling for callbacks (low-level callbacks required by the underlying library).
//! // Important to know, regardless of the type of socket, whether it is in [`IsClient`] or [`IsServer`] state, theses three operations are the same.
//! // The only difference is that polling for messages and status on the client only act on the client connection, while polling for messages and status on a server yield event for all connected clients.
//!
//! // You would loop on the below code.
//! // Run the low-level callbacks.
//! gns_global.poll_callbacks();
//!
//! // Receive a maximum of 100 messages on the client connection.
//! // For each messages, print it's payload.
//! for message in client.receive_messages::<100>().expect("failed to recv").into_iter() {
//!   println!("{}", core::str::from_utf8(message.payload()).unwrap());
//! }
//!
//! // Don't do anything with events.
//! // One would check the event for connection status, i.e. doing something when we are connected/disconnected from the server.
//! for _event in client.receive_events() {
//! }
//!
//! // Sleep a little bit.
//! std::thread::sleep(Duration::from_millis(10))
//! ```
//!
//! # Note
//!
//! Each [`GnsSocket`] registers a [`Weak<SegQueue<GnsConnectionEvent>>`] in [`GnsGlobal`]'s queue map so that incoming connection-state callbacks can find their owner. The entry is removed when the socket is dropped.

use crossbeam_queue::SegQueue;
pub use gns_sys as sys;
use std::sync::atomic::{AtomicI64, Ordering};
use std::{
    collections::HashMap,
    ffi::{c_void, CStr, CString},
    marker::PhantomData,
    mem::MaybeUninit,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    sync::{Arc, Mutex, OnceLock, RwLock, Weak},
    time::Duration,
};
use sys::*;

#[inline]
fn get_interface() -> *mut ISteamNetworkingSockets {
    unsafe { SteamAPI_SteamNetworkingSockets_v009() }
}

#[inline]
fn get_utils() -> *mut ISteamNetworkingUtils {
    unsafe { SteamAPI_SteamNetworkingUtils_v003() }
}

/// A network message number. Simple alias for documentation.
pub type GnsMessageNumber = u64;

/// Errors surfaced by the wrapper. Wraps Steam's [`EResult`] for API failures
/// and adds variants for setup paths that don't return an `EResult`.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum GnsError {
    #[error("GameNetworkingSockets_Init failed: {0}")]
    Init(String),
    #[error("listen failed: invalid handle")]
    Listen,
    #[error("connect failed: invalid handle")]
    Connect,
    #[error("receive failed: invalid connection or poll group handle")]
    Receive,
    #[error("accept failed: could not set connection poll group")]
    Accept,
    #[error("close failed: invalid connection handle")]
    Close,
    #[error("steam api: {0:?}")]
    Api(EResult),
    #[error("config: {0}")]
    Config(&'static str),
}

pub type GnsResult<T> = Result<T, GnsError>;

/// Map an `EResult` returned by an FFI call to a [`GnsResult`].
#[inline]
fn check(e: EResult) -> GnsResult<()> {
    match e {
        EResult::k_EResultOK => Ok(()),
        e => Err(GnsError::Api(e)),
    }
}

/// Wraps the initialization/destruction of the low-level *GameNetworkingSockets* and associated
/// singletons.
///
/// A reference can be retrieved via [`GnsGlobal::get()`], which will initialize
/// *GameNetworkingSockets* if it has not yet been initialized.
pub struct GnsGlobal {
    utils: GnsUtils,
    next_queue_id: AtomicI64,
    /// Per-socket event-queue registry. Reads dominate (one lookup per
    /// connection-state callback from the GNS service thread); writes
    /// happen only on socket creation / drop and on the rare race where
    /// a callback fires for a just-dropped socket. `RwLock` lets future
    /// observability paths read concurrently without contending.
    event_queues: RwLock<HashMap<i64, Weak<SegQueue<GnsConnectionEvent>>>>,
}

static GNS_GLOBAL: OnceLock<GnsGlobal> = OnceLock::new();

impl Drop for GnsGlobal {
    #[inline]
    fn drop(&mut self) {
        // Stop the GNS service thread and tear down internal state.
        // GNS does not support `_Init`/`_Kill`/`_Init` cycles across all
        // versions, so we only run this when the singleton itself is being
        // dropped (i.e. process exit / explicit static-clear in tests).
        unsafe { GameNetworkingSockets_Kill() }
    }
}

impl GnsGlobal {
    /// Try to acquire a reference to the [`GnsGlobal`] instance.
    ///
    /// If GnsGlobal has not yet been successfully initialized, a call to
    /// [`sys::GameNetworkingSockets_Init`] will be made. If successful, a reference to GnsGlobal
    /// will be returned.
    ///
    /// If GnsGlobal has already been initialized, this method returns a reference to the already
    /// created GnsGlobal instance.
    ///
    /// # Errors
    /// Returns [`GnsError::Init`] with the message produced by GNS if
    /// initialization fails.
    pub fn get() -> GnsResult<&'static Self> {
        // Fast path: no lock
        if let Some(g) = GNS_GLOBAL.get() {
            return Ok(g);
        }
        // use get_or_try_init once stabilized: https://github.com/rust-lang/rust/issues/109737
        static INIT_LOCK: Mutex<()> = Mutex::new(());
        let _guard = INIT_LOCK.lock().unwrap();
        if let Some(g) = GNS_GLOBAL.get() {
            return Ok(g);
        }
        unsafe {
            let mut error: SteamDatagramErrMsg = MaybeUninit::zeroed().assume_init();
            if !GameNetworkingSockets_Init(core::ptr::null(), &mut error) {
                return Err(GnsError::Init(
                    CStr::from_ptr(error.as_ptr())
                        .to_str()
                        .unwrap_or("")
                        .to_owned(),
                ));
            }
        }
        let _ = GNS_GLOBAL.set(GnsGlobal {
            utils: GnsUtils(()),
            next_queue_id: AtomicI64::new(0),
            event_queues: RwLock::new(HashMap::new()),
        });
        Ok(GNS_GLOBAL.get().expect("impossible; qed;"))
    }

    #[inline]
    pub fn poll_callbacks(&self) {
        unsafe {
            SteamAPI_ISteamNetworkingSockets_RunCallbacks(get_interface());
        }
    }

    #[inline]
    pub fn utils(&self) -> &GnsUtils {
        &self.utils
    }

    #[inline]
    pub fn queue_count(&self) -> usize {
        self.event_queues.read().unwrap().len()
    }

    #[inline]
    fn create_queue(&self) -> (i64, Arc<SegQueue<GnsConnectionEvent>>) {
        let queue = Arc::new(SegQueue::new());
        let queue_id = self.next_queue_id.fetch_add(1, Ordering::SeqCst);
        self.event_queues
            .write()
            .unwrap()
            .insert(queue_id, Arc::downgrade(&queue));
        (queue_id, queue)
    }
}

/// Opaque wrapper around the low-level [`sys::HSteamListenSocket`].
#[repr(transparent)]
pub(crate) struct GnsListenSocket(HSteamListenSocket);

/// Opaque wrapper around the low-level [`sys::HSteamNetPollGroup`].
#[repr(transparent)]
pub(crate) struct GnsPollGroup(HSteamNetPollGroup);

/// Initial state of a [`GnsSocket`].
/// This state represent a socket that has not been used as a Server or Client implementation.
/// Consequently, the state is empty.
pub struct IsCreated;

mod private {
    pub trait Sealed {}
    impl Sealed for super::IsServer {}
    impl Sealed for super::IsClient {}
}

/// Common functions available for any [`GnsSocket`] state that is implementing it.
/// Regardless of being a client or server, a ready socket will allow us to query for connection events as well as receive messages.
pub trait IsReady: private::Sealed {
    /// Return a reference to the connection event queue. The queue is thread-safe.
    fn queue(&self) -> &SegQueue<GnsConnectionEvent>;
    /// Receive up to `slots.len()` messages into `slots`. Returns the count
    /// actually initialized by GNS, or [`GnsError::Receive`] if the underlying
    /// handle is invalid.
    fn receive(&self, slots: &mut [MaybeUninit<*mut ISteamNetworkingMessage>]) -> GnsResult<usize>;
}

/// State of a [`GnsSocket`] that has been determined to be a server, usually via the [`GnsSocket::listen`] call.
/// In this state, the socket hold the data required to accept connections and poll them for messages.
pub struct IsServer {
    queue: Arc<SegQueue<GnsConnectionEvent>>,
    queue_id: i64,
    global: &'static GnsGlobal,
    listen_socket: GnsListenSocket,
    poll_group: GnsPollGroup,
}

impl Drop for IsServer {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            SteamAPI_ISteamNetworkingSockets_CloseListenSocket(
                get_interface(),
                self.listen_socket.0,
            );
            SteamAPI_ISteamNetworkingSockets_DestroyPollGroup(get_interface(), self.poll_group.0);
        }
        self.global
            .event_queues
            .write()
            .unwrap()
            .remove(&self.queue_id);
    }
}

impl IsReady for IsServer {
    #[inline]
    fn queue(&self) -> &SegQueue<GnsConnectionEvent> {
        &self.queue
    }

    fn receive(&self, slots: &mut [MaybeUninit<*mut ISteamNetworkingMessage>]) -> GnsResult<usize> {
        let result = unsafe {
            SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnPollGroup(
                get_interface(),
                self.poll_group.0,
                slots.as_mut_ptr() as _,
                slots.len() as _,
            ) as _
        };
        if result == usize::MAX {
            Err(GnsError::Receive)
        } else {
            Ok(result)
        }
    }
}

/// State of a [`GnsSocket`] that has been determined to be a client, usually via the [`GnsSocket::connect`] call.
/// In this state, the socket hold the data required to receive and send messages.
pub struct IsClient {
    queue: Arc<SegQueue<GnsConnectionEvent>>,
    queue_id: i64,
    global: &'static GnsGlobal,
    connection: GnsConnection,
}

impl Drop for IsClient {
    fn drop(&mut self) {
        unsafe {
            SteamAPI_ISteamNetworkingSockets_CloseConnection(
                get_interface(),
                self.connection.0,
                0,
                core::ptr::null(),
                false,
            );
        }
        self.global
            .event_queues
            .write()
            .unwrap()
            .remove(&self.queue_id);
    }
}

impl IsReady for IsClient {
    #[inline]
    fn queue(&self) -> &SegQueue<GnsConnectionEvent> {
        &self.queue
    }

    fn receive(&self, slots: &mut [MaybeUninit<*mut ISteamNetworkingMessage>]) -> GnsResult<usize> {
        let result = unsafe {
            SteamAPI_ISteamNetworkingSockets_ReceiveMessagesOnConnection(
                get_interface(),
                self.connection.0,
                slots.as_mut_ptr() as _,
                slots.len() as _,
            ) as _
        };
        if result == usize::MAX {
            Err(GnsError::Receive)
        } else {
            Ok(result)
        }
    }
}

pub struct ToReceive(());

pub struct ToSend(());

/// A single receive slot: an uninitialized cell that GNS fills with one
/// `*mut ISteamNetworkingMessage`. Build a buffer of these (e.g.
/// `[const { MessageSlot::uninit() }; 128]`) for zero-move
/// [`GnsSocket::receive_messages_into`].
pub type MessageSlot = MaybeUninit<*mut ISteamNetworkingMessage>;

/// Reconstruct the owned message stored in `slot`.
///
/// # Safety
/// `slot` must have been initialized by GNS (i.e. lie within the prefix length
/// it reported from `receive`) and must not have been taken already, otherwise
/// the message would be released more than once.
#[inline]
unsafe fn take_message(slot: &MessageSlot) -> GnsNetworkMessage<ToReceive> {
    GnsNetworkMessage(unsafe { slot.assume_init() }, PhantomData)
}

/// Shared iteration state over a buffer of receive slots. `slots[..len]` are
/// initialized; `pos` is the next slot to hand out. Centralizes the unsafe
/// take/release logic so the owning and borrowing iterators stay in sync.
struct SlotCursor {
    len: usize,
    pos: usize,
}

impl SlotCursor {
    fn next(&mut self, slots: &[MessageSlot]) -> Option<GnsNetworkMessage<ToReceive>> {
        if self.pos < self.len {
            // Safety: GNS initialized `slots[..len]`; `pos` strictly increases,
            // so each slot is taken at most once.
            let message = unsafe { take_message(&slots[self.pos]) };
            self.pos += 1;
            Some(message)
        } else {
            None
        }
    }

    #[inline]
    fn remaining(&self) -> usize {
        self.len - self.pos
    }

    /// Release every slot not yet handed out. Idempotent.
    fn drain_unconsumed(&mut self, slots: &[MessageSlot]) {
        for slot in &slots[self.pos..self.len] {
            // Safety: same invariant as `next` — these slots are initialized and
            // were never handed out, so each is released exactly once.
            drop(unsafe { take_message(slot) });
        }
        self.pos = self.len;
    }
}

/// Iterator over the messages produced by a single
/// [`GnsSocket::receive_messages`] call.
///
/// Owns the `K`-slot pointer buffer inline (no heap allocation) and yields
/// each [`GnsNetworkMessage<ToReceive>`] by value. Messages left unconsumed
/// when the iterator is dropped are released. See
/// [`GnsSocket::receive_messages_into`] for a variant that borrows a
/// caller-owned buffer, avoiding even the inline array move.
pub struct ReceivedMessages<const K: usize> {
    slots: [MessageSlot; K],
    cursor: SlotCursor,
}

impl<const K: usize> Iterator for ReceivedMessages<K> {
    type Item = GnsNetworkMessage<ToReceive>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.cursor.next(&self.slots)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.cursor.remaining();
        (remaining, Some(remaining))
    }
}

impl<const K: usize> ExactSizeIterator for ReceivedMessages<K> {}

impl<const K: usize> core::iter::FusedIterator for ReceivedMessages<K> {}

impl<const K: usize> Drop for ReceivedMessages<K> {
    #[inline]
    fn drop(&mut self) {
        self.cursor.drain_unconsumed(&self.slots);
    }
}

/// Iterator returned by [`GnsSocket::receive_messages_into`].
///
/// Borrows the caller's buffer for its whole lifetime — so the buffer cannot
/// be reused while messages are still outstanding — and yields each
/// [`GnsNetworkMessage<ToReceive>`] by value. No allocation occurs and the
/// pointer buffer is never moved; only the individual message pointers are.
/// Unconsumed messages are released on drop.
pub struct ReceivedMessagesInto<'a> {
    slots: &'a mut [MessageSlot],
    cursor: SlotCursor,
}

impl Iterator for ReceivedMessagesInto<'_> {
    type Item = GnsNetworkMessage<ToReceive>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.cursor.next(self.slots)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.cursor.remaining();
        (remaining, Some(remaining))
    }
}

impl ExactSizeIterator for ReceivedMessagesInto<'_> {}

impl core::iter::FusedIterator for ReceivedMessagesInto<'_> {}

impl Drop for ReceivedMessagesInto<'_> {
    #[inline]
    fn drop(&mut self) {
        self.cursor.drain_unconsumed(self.slots);
    }
}

bitflags::bitflags! {
    /// Type-safe wrapper over the GNS `k_nSteamNetworkingSend_*` flags.
    /// Carries the same bit values as the raw `c_int` constants.
    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
    pub struct SendFlags: i32 {
        const UNRELIABLE                  = sys::k_nSteamNetworkingSend_Unreliable;
        const NO_NAGLE                    = sys::k_nSteamNetworkingSend_NoNagle;
        const NO_DELAY                    = sys::k_nSteamNetworkingSend_NoDelay;
        const RELIABLE                    = sys::k_nSteamNetworkingSend_Reliable;
        const USE_CURRENT_THREAD          = sys::k_nSteamNetworkingSend_UseCurrentThread;
        const AUTO_RESTART_BROKEN_SESSION = sys::k_nSteamNetworkingSend_AutoRestartBrokenSession;
    }
}

/// A connection lane: priority (lower = higher priority, signed `int` in C)
/// and weight (relative scheduling weight within a priority class).
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct GnsLane {
    pub priority: i32,
    pub weight: u16,
}

impl GnsLane {
    #[inline]
    pub const fn new(priority: i32, weight: u16) -> Self {
        Self { priority, weight }
    }
}

/// A lane Id.
pub type GnsLaneId = u16;

/// Outcome of an individual message inside a [`GnsSocket::send_messages`] batch.
///
/// `Skipped` reflects GNS's batched-failure semantic: when a message earlier
/// in the same batch fails on connection X, every later message targeting X
/// is short-circuited (`pOutMessageNumberOrResult[i] = 0` per
/// `csteamnetworkingsockets.cpp:1364`). `m_pData` is *not* consumed in that
/// case, so we hand the original message back to the caller alongside
/// `Failed`.
#[must_use = "Failed/Skipped variants own a message that needs inspection or drop"]
pub enum SendOutcome {
    Sent(GnsMessageNumber),
    Failed(EResult, GnsNetworkMessage<ToSend>),
    Skipped(GnsNetworkMessage<ToSend>),
}

/// Owned byte buffer for outbound messages. GNS reads `m_pData`
/// asynchronously on its service thread after `SendMessages` returns,
/// so the message must own the bytes until GNS releases it.
///
/// `into_raw` returns `(ptr, len)` stored verbatim in `m_pData` /
/// `m_cbSize`. When GNS releases the message, the wrapper calls
/// [`from_raw`](Self::from_raw) with those same values to reconstruct
/// `Self`; the reconstructed value is then dropped.
///
/// This mirrors `Box::into_raw` / `Box::from_raw` and lets the
/// implementor express its free semantic via ordinary Rust `Drop`.
///
/// # Safety
/// `from_raw(p, n)` must be sound when `(p, n)` came from a previous
/// `into_raw` call on the same impl (i.e. `from_raw(into_raw(..))` must be an isomorphism).
/// The implementor must arrange for `into_raw` *not* to run `Self`'s `Drop`(because ownership is being transferred to GNS).
pub unsafe trait Payload: Send + 'static {
    fn into_raw(self) -> (*mut u8, usize);
    /// # Safety
    /// `ptr` and `len` must be the values returned by a prior
    /// [`into_raw`](Self::into_raw) call on this same impl, and that
    /// transferred ownership must not have already been reclaimed.
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self;
}

/// Monomorphized `m_pfnFreeData` callback installed for every
/// `GnsNetworkMessage<ToSend>`. Reads `m_pData` / `m_cbSize`,
/// reconstructs `P` via [`Payload::from_raw`], and lets `Drop` run.
extern "C" fn free_payload<P: Payload>(msg: *mut ISteamNetworkingMessage) {
    let ptr = unsafe { (*msg).m_pData } as *mut u8;
    let len = unsafe { (*msg).m_cbSize } as usize;
    // Safety: (ptr, len) were just written by `GnsNetworkMessage::<ToSend>::new`
    // from `P::into_raw`, and GNS releases each message at most once.
    drop(unsafe { P::from_raw(ptr, len) });
}

unsafe impl Payload for Box<[u8]> {
    #[inline]
    fn into_raw(self) -> (*mut u8, usize) {
        let len = self.len();
        let raw = Box::into_raw(self) as *mut u8;
        (raw, len)
    }
    #[inline]
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        let slice = core::ptr::slice_from_raw_parts_mut(ptr, len);
        unsafe { Box::from_raw(slice) }
    }
}

// Routes through `Box<[u8]>`: `into_boxed_slice` shrinks-to-fit (one
// realloc when `cap != len`) so `(ptr, len)` is enough to reconstruct.
unsafe impl Payload for Vec<u8> {
    #[inline]
    fn into_raw(self) -> (*mut u8, usize) {
        <Box<[u8]> as Payload>::into_raw(self.into_boxed_slice())
    }
    #[inline]
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        unsafe { Vec::from_raw_parts(ptr, len, len) }
    }
}

unsafe impl Payload for String {
    #[inline]
    fn into_raw(self) -> (*mut u8, usize) {
        <Vec<u8> as Payload>::into_raw(self.into_bytes())
    }
    #[inline]
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        unsafe { String::from_raw_parts(ptr, len, len) }
    }
}

unsafe impl Payload for Arc<[u8]> {
    #[inline]
    fn into_raw(self) -> (*mut u8, usize) {
        let len = self.len();
        let raw = Arc::into_raw(self) as *const u8 as *mut u8;
        (raw, len)
    }
    #[inline]
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        let slice = core::ptr::slice_from_raw_parts(ptr as *const u8, len);
        unsafe { Arc::from_raw(slice) }
    }
}

unsafe impl Payload for &'static [u8] {
    #[inline]
    fn into_raw(self) -> (*mut u8, usize) {
        (self.as_ptr() as *mut u8, self.len())
    }
    #[inline]
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        unsafe { core::slice::from_raw_parts(ptr as *const u8, len) }
    }
}

unsafe impl Payload for &'static str {
    #[inline]
    fn into_raw(self) -> (*mut u8, usize) {
        (self.as_ptr() as *mut u8, self.len())
    }
    #[inline]
    unsafe fn from_raw(ptr: *mut u8, len: usize) -> Self {
        let bytes = unsafe { core::slice::from_raw_parts(ptr as *const u8, len) };
        unsafe { core::str::from_utf8_unchecked(bytes) }
    }
}

/// Type-state-tagged GNS message. `ToReceive` instances are produced by
/// the library; `ToSend` instances are created via
/// [`GnsUtils::allocate_message`] and own their payload through
/// [`Payload`]. Both are released on drop.
#[repr(transparent)]
pub struct GnsNetworkMessage<T>(*mut ISteamNetworkingMessage, PhantomData<T>);

impl<T> Drop for GnsNetworkMessage<T> {
    #[inline]
    fn drop(&mut self) {
        if !self.0.is_null() {
            unsafe {
                SteamAPI_SteamNetworkingMessage_t_Release(self.0);
            }
        }
    }
}

impl<T> GnsNetworkMessage<T> {
    /// Extract the raw `*mut ISteamNetworkingMessage` and forget the wrapper.
    ///
    /// # Safety
    /// The caller takes over the message's release path: dropping the
    /// pointer's referent (e.g. via `SteamAPI_SteamNetworkingMessage_t_Release`)
    /// is now their responsibility. For `ToSend` messages this also means
    /// the `Payload`-installed `m_pfnFreeData` will run when the C side
    /// releases the message.
    #[inline]
    pub unsafe fn into_inner(self) -> *mut ISteamNetworkingMessage {
        self.0
    }

    #[inline]
    pub fn payload(&self) -> &[u8] {
        unsafe {
            core::slice::from_raw_parts((*self.0).m_pData as *const u8, (*self.0).m_cbSize as _)
        }
    }

    #[inline]
    pub fn message_number(&self) -> u64 {
        unsafe { (*self.0).m_nMessageNumber as _ }
    }

    #[inline]
    pub fn lane(&self) -> GnsLaneId {
        unsafe { (*self.0).m_idxLane }
    }

    #[inline]
    pub fn flags(&self) -> SendFlags {
        SendFlags::from_bits_retain(unsafe { (*self.0).m_nFlags })
    }

    #[inline]
    pub fn user_data(&self) -> u64 {
        unsafe { (*self.0).m_nUserData as _ }
    }

    #[inline]
    pub fn connection(&self) -> GnsConnection {
        GnsConnection(unsafe { (*self.0).m_conn })
    }

    #[inline]
    pub fn connection_user_data(&self) -> u64 {
        unsafe { (*self.0).m_nConnUserData as _ }
    }
}

impl GnsNetworkMessage<ToSend> {
    #[inline]
    fn new<P: Payload>(
        ptr: *mut ISteamNetworkingMessage,
        conn: GnsConnection,
        flags: SendFlags,
        payload: P,
    ) -> Self {
        let (data_ptr, len) = payload.into_raw();
        unsafe {
            (*ptr).m_pData = data_ptr as *mut c_void;
            (*ptr).m_cbSize = len as i32;
            (*ptr).m_pfnFreeData = Some(free_payload::<P>);
        }
        GnsNetworkMessage(ptr, PhantomData)
            .set_flags(flags)
            .set_connection(conn)
    }

    #[inline]
    pub fn set_connection(self, GnsConnection(conn): GnsConnection) -> Self {
        unsafe { (*self.0).m_conn = conn }
        self
    }

    #[inline]
    pub fn set_lane(self, lane: GnsLaneId) -> Self {
        unsafe { (*self.0).m_idxLane = lane }
        self
    }

    #[inline]
    pub fn set_flags(self, flags: SendFlags) -> Self {
        unsafe { (*self.0).m_nFlags = flags.bits() as _ }
        self
    }

    #[inline]
    pub fn set_user_data(self, userdata: u64) -> Self {
        unsafe { (*self.0).m_nUserData = userdata as _ }
        self
    }
}

#[repr(transparent)]
#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct GnsConnection(HSteamNetConnection);

impl GnsConnection {
    /// Wrap a raw `HSteamNetConnection` handle. Validity is enforced by GNS
    /// on use; an arbitrary handle that does not match a live connection
    /// will simply be rejected by the relevant API call.
    #[inline]
    pub const fn from_raw(handle: HSteamNetConnection) -> Self {
        Self(handle)
    }

    /// `true` if this is not the GNS invalid-connection sentinel (`0`).
    #[inline]
    pub fn is_valid(self) -> bool {
        self.0 != k_HSteamNetConnection_Invalid
    }
}

#[derive(Default, Copy, Clone)]
pub struct GnsConnectionInfo(SteamNetConnectionInfo_t);

impl GnsConnectionInfo {
    #[inline]
    pub fn state(&self) -> ESteamNetworkingConnectionState {
        self.0.m_eState
    }

    #[inline]
    pub fn end_reason(&self) -> u32 {
        self.0.m_eEndReason as u32
    }

    #[inline]
    pub fn end_debug(&self) -> &str {
        unsafe { CStr::from_ptr(self.0.m_szEndDebug.as_ptr()) }
            .to_str()
            .unwrap_or("")
    }

    #[inline]
    pub fn remote_address(&self) -> IpAddr {
        let ipv4 = unsafe { self.0.m_addrRemote.__bindgen_anon_1.m_ipv4 };
        if ipv4.m_8zeros == 0 && ipv4.m_0000 == 0 && ipv4.m_ffff == 0xffff {
            IpAddr::from(Ipv4Addr::from(ipv4.m_ip))
        } else {
            IpAddr::from(Ipv6Addr::from(unsafe {
                self.0.m_addrRemote.__bindgen_anon_1.m_ipv6
            }))
        }
    }

    #[inline]
    pub fn remote_port(&self) -> u16 {
        self.0.m_addrRemote.m_port
    }
}

#[derive(Debug, Default, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
pub struct GnsConnectionRealTimeLaneStatus(SteamNetConnectionRealTimeLaneStatus_t);

impl GnsConnectionRealTimeLaneStatus {
    #[inline]
    pub fn pending_bytes_unreliable(&self) -> u32 {
        self.0.m_cbPendingUnreliable as _
    }

    #[inline]
    pub fn pending_bytes_reliable(&self) -> u32 {
        self.0.m_cbPendingReliable as _
    }

    #[inline]
    pub fn bytes_sent_unacked_reliable(&self) -> u32 {
        self.0.m_cbSentUnackedReliable as _
    }

    #[inline]
    pub fn approximated_queue_time(&self) -> Duration {
        Duration::from_micros(self.0.m_usecQueueTime as _)
    }
}

#[derive(Default, Debug, Copy, Clone, PartialOrd, PartialEq)]
pub struct GnsConnectionRealTimeStatus(SteamNetConnectionRealTimeStatus_t);

impl GnsConnectionRealTimeStatus {
    #[inline]
    pub fn state(&self) -> ESteamNetworkingConnectionState {
        self.0.m_eState
    }

    #[inline]
    pub fn ping(&self) -> u32 {
        self.0.m_nPing as _
    }

    #[inline]
    pub fn quality_local(&self) -> f32 {
        self.0.m_flConnectionQualityLocal
    }

    #[inline]
    pub fn quality_remote(&self) -> f32 {
        self.0.m_flConnectionQualityRemote
    }

    #[inline]
    pub fn out_packets_per_sec(&self) -> f32 {
        self.0.m_flOutPacketsPerSec
    }

    #[inline]
    pub fn out_bytes_per_sec(&self) -> f32 {
        self.0.m_flOutBytesPerSec
    }

    #[inline]
    pub fn in_packets_per_sec(&self) -> f32 {
        self.0.m_flInPacketsPerSec
    }

    #[inline]
    pub fn in_bytes_per_sec(&self) -> f32 {
        self.0.m_flInBytesPerSec
    }

    #[inline]
    pub fn send_rate_bytes_per_sec(&self) -> u32 {
        self.0.m_nSendRateBytesPerSecond as _
    }

    #[inline]
    pub fn pending_bytes_unreliable(&self) -> u32 {
        self.0.m_cbPendingUnreliable as _
    }

    #[inline]
    pub fn pending_bytes_reliable(&self) -> u32 {
        self.0.m_cbPendingReliable as _
    }

    #[inline]
    pub fn bytes_sent_unacked_reliable(&self) -> u32 {
        self.0.m_cbSentUnackedReliable as _
    }

    #[inline]
    pub fn approximated_queue_time(&self) -> Duration {
        Duration::from_micros(self.0.m_usecQueueTime as _)
    }

    /// Returns the highest packet jitter experienced since the last time this
    /// information was fetched. The high water mark is cleared each time you
    /// fetch the info.
    ///
    /// Returns `None` if no jitter data is available (the underlying value is negative),
    /// or if the connection type doesn't support jitter measurement.
    #[inline]
    pub fn max_jitter_usec(&self) -> Option<i32> {
        let val = self.0.m_usecMaxJitter;
        if val < 0 {
            None
        } else {
            Some(val)
        }
    }
}

#[derive(Default, Copy, Clone)]
pub struct GnsConnectionEvent(SteamNetConnectionStatusChangedCallback_t);

impl GnsConnectionEvent {
    #[inline]
    pub fn old_state(&self) -> ESteamNetworkingConnectionState {
        self.0.m_eOldState
    }

    #[inline]
    pub fn connection(&self) -> GnsConnection {
        GnsConnection(self.0.m_hConn)
    }

    #[inline]
    pub fn info(&self) -> GnsConnectionInfo {
        GnsConnectionInfo(self.0.m_info)
    }
}

/// [`GnsSocket`] is the most important structure of this library.
/// This structure is used to create client ([`GnsSocket<IsClient>`]) and server ([`GnsSocket<IsServer>`]) sockets via the [`GnsSocket::connect`] and [`GnsSocket::listen`] functions.
/// The drop implementation make sure that everything related to this structure is correctly freed, except the [`GnsGlobal`] instance and the user has a strong guarantee that all the available operations over the socket are **safe**.
pub struct GnsSocket<S> {
    global: &'static GnsGlobal,
    state: S,
}

impl<S> GnsSocket<S>
where
    S: IsReady,
{
    /// Get a connection lane status.
    /// This call is possible only if lanes has been previously configured using configure_connection_lanes
    pub fn get_connection_real_time_status(
        &self,
        GnsConnection(conn): GnsConnection,
        nb_of_lanes: u32,
    ) -> GnsResult<(
        GnsConnectionRealTimeStatus,
        Vec<GnsConnectionRealTimeLaneStatus>,
    )> {
        let mut lanes: Vec<GnsConnectionRealTimeLaneStatus> =
            vec![Default::default(); nb_of_lanes as _];
        let mut status: GnsConnectionRealTimeStatus = Default::default();
        check(unsafe {
            SteamAPI_ISteamNetworkingSockets_GetConnectionRealTimeStatus(
                get_interface(),
                conn,
                &mut status as *mut GnsConnectionRealTimeStatus
                    as *mut SteamNetConnectionRealTimeStatus_t,
                nb_of_lanes as _,
                lanes.as_mut_ptr() as *mut SteamNetConnectionRealTimeLaneStatus_t,
            )
        })?;
        Ok((status, lanes))
    }

    pub fn get_connection_info(
        &self,
        GnsConnection(conn): GnsConnection,
    ) -> Option<GnsConnectionInfo> {
        let mut info: SteamNetConnectionInfo_t = Default::default();
        if unsafe {
            SteamAPI_ISteamNetworkingSockets_GetConnectionInfo(get_interface(), conn, &mut info)
        } {
            Some(GnsConnectionInfo(info))
        } else {
            None
        }
    }

    pub fn flush_messages_on_connection(
        &self,
        GnsConnection(conn): GnsConnection,
    ) -> GnsResult<()> {
        check(unsafe {
            SteamAPI_ISteamNetworkingSockets_FlushMessagesOnConnection(get_interface(), conn)
        })
    }

    /// Close a connection. `pszDebug` is forwarded to the peer if non-`None`;
    /// pass `None` to send no diagnostic string and avoid all allocation.
    ///
    /// # Errors
    /// Returns [`GnsError::Close`] if the connection handle is invalid (e.g.
    /// already closed).
    pub fn close_connection(
        &self,
        GnsConnection(conn): GnsConnection,
        reason: u32,
        debug: Option<&CStr>,
        linger: bool,
    ) -> GnsResult<()> {
        let debug_ptr = debug.map(|d| d.as_ptr()).unwrap_or(core::ptr::null());
        if unsafe {
            SteamAPI_ISteamNetworkingSockets_CloseConnection(
                get_interface(),
                conn,
                reason as _,
                debug_ptr,
                linger,
            )
        } {
            Ok(())
        } else {
            Err(GnsError::Close)
        }
    }

    /// Receive up to `K` messages, returning an iterator over the ones that
    /// were available. Each message is yielded by value, so the caller may keep
    /// it (store or forward it) or let it drop, which releases it back to GNS;
    /// any left unconsumed when the iterator is dropped are released too.
    ///
    /// The `K`-slot pointer buffer lives inline in the returned iterator, so
    /// this performs no heap allocation and never copies a payload. Use
    /// [`receive_messages_into`](Self::receive_messages_into) to reuse a single
    /// caller-owned buffer across calls and avoid even the inline array move.
    ///
    /// # Errors
    /// Returns [`GnsError::Receive`] if the underlying connection or poll
    /// group handle is invalid.
    pub fn receive_messages<const K: usize>(&self) -> GnsResult<ReceivedMessages<K>> {
        let mut slots: [MessageSlot; K] = [const { MessageSlot::uninit() }; K];
        let len = self.state.receive(&mut slots)?;
        Ok(ReceivedMessages {
            slots,
            cursor: SlotCursor { len, pos: 0 },
        })
    }

    /// Receive up to `buffer.len()` messages into a caller-owned `buffer`,
    /// returning an iterator over the ones that were available.
    ///
    /// This is the zero-allocation, zero-move variant of
    /// [`receive_messages`](Self::receive_messages): GNS fills `buffer` in
    /// place and the returned iterator borrows it, so reusing one buffer across
    /// a polling loop costs nothing per call.
    ///
    /// # Errors
    /// Returns [`GnsError::Receive`] if the underlying connection or poll
    /// group handle is invalid.
    pub fn receive_messages_into<'a>(
        &self,
        buffer: &'a mut [MessageSlot],
    ) -> GnsResult<ReceivedMessagesInto<'a>> {
        let len = self.state.receive(buffer)?;
        Ok(ReceivedMessagesInto {
            slots: buffer,
            cursor: SlotCursor { len, pos: 0 },
        })
    }

    /// Drain the pending connection events, returning an iterator over them.
    ///
    /// Unlike [`receive_messages`](Self::receive_messages) there is no buffer to
    /// supply: events arrive on an internal lock-free queue (populated by GNS's
    /// connection-status callback), so this just pops from that queue.
    pub fn receive_events(&self) -> impl Iterator<Item = GnsConnectionEvent> + '_ {
        core::iter::from_fn(|| self.state.queue().pop())
    }

    pub fn configure_connection_lanes(
        &self,
        GnsConnection(connection): GnsConnection,
        lanes: &[GnsLane],
    ) -> GnsResult<()> {
        let (priorities, weights): (Vec<i32>, Vec<u16>) =
            lanes.iter().map(|l| (l.priority, l.weight)).unzip();
        check(unsafe {
            SteamAPI_ISteamNetworkingSockets_ConfigureConnectionLanes(
                get_interface(),
                connection,
                lanes.len() as _,
                priorities.as_ptr(),
                weights.as_ptr(),
            )
        })
    }

    /// Dispatch a single message to its target connection.
    ///
    /// Convenience wrapper over [`send_messages`](Self::send_messages) for the
    /// common one-message case.
    pub fn send_message(&self, message: GnsNetworkMessage<ToSend>) -> GnsResult<GnsMessageNumber> {
        match self.send_messages(core::iter::once(message)).pop() {
            Some(SendOutcome::Sent(number)) => Ok(number),
            Some(SendOutcome::Failed(result, _)) => Err(GnsError::Api(result)),
            // A single message cannot be `Skipped` (that only happens to a
            // message queued behind an earlier failure on the same connection),
            // and `send_messages` always yields exactly one outcome per input.
            _ => Err(GnsError::Api(EResult::k_EResultFail)),
        }
    }

    /// Dispatch each message to its target connection. See [`SendOutcome`]
    /// for the per-message result shape. The returned `Vec` has one outcome
    /// per input message, in order.
    pub fn send_messages(
        &self,
        messages: impl IntoIterator<Item = GnsNetworkMessage<ToSend>>,
    ) -> Vec<SendOutcome> {
        // `bDeleteFailedMessages = false`: C consumes successful messages
        // and leaves the failed (or skipped) ones for us to re-wrap.
        // `ManuallyDrop` suspends our destructor across the FFI call.
        let mut raw: Vec<*mut ISteamNetworkingMessage> = messages
            .into_iter()
            .map(|message| {
                let message = core::mem::ManuallyDrop::new(message);
                message.0
            })
            .collect();
        let mut result = vec![0i64; raw.len()];
        unsafe {
            SteamAPI_ISteamNetworkingSockets_SendMessages(
                get_interface(),
                raw.len() as _,
                raw.as_mut_ptr(),
                result.as_mut_ptr(),
                false,
            );
        }
        result
            .into_iter()
            .zip(raw)
            .map(|(value, ptr)| {
                if value > 0 {
                    SendOutcome::Sent(value as _)
                } else if value < 0 {
                    // Sound: gns-sys is a pinned static submodule so the
                    // bindgen `EResult` mirrors every value GNS produces.
                    let result = unsafe { core::mem::transmute::<u32, EResult>((-value) as u32) };
                    SendOutcome::Failed(result, GnsNetworkMessage(ptr, PhantomData))
                } else {
                    SendOutcome::Skipped(GnsNetworkMessage(ptr, PhantomData))
                }
            })
            .collect()
    }
}

impl GnsSocket<IsCreated> {
    /// Unsafe, C-like callback, we use the user data to pass the queue ID, so we can find the
    /// correct queue in GnsGlobal.
    unsafe extern "C" fn on_connection_state_changed(
        info: &mut SteamNetConnectionStatusChangedCallback_t,
    ) {
        let gns_global = GnsGlobal::get()
            // GnsGlobal needs to be initialized to even reach this point in the first place.
            .expect("GnsGlobal should be initialized");

        let queue_id = info.m_info.m_nUserData as _;
        // Hot path: take the read lock, look up, push if upgradeable.
        let needs_purge = {
            let queues = gns_global.event_queues.read().unwrap();
            match queues.get(&queue_id).and_then(Weak::upgrade) {
                Some(queue) => {
                    queue.push(GnsConnectionEvent(*info));
                    false
                }
                None => queues.contains_key(&queue_id),
            }
        };
        // Cold path: race with socket drop, the entry is still in the
        // map but the queue is gone. Escalate to a write lock to purge.
        // `queue_id`s are monotonic (no reuse), so removing a no-longer-
        // present key is harmless if another thread beat us to it.
        if needs_purge {
            gns_global.event_queues.write().unwrap().remove(&queue_id);
        }
    }

    /// Initialize a new socket in [`IsCreated`] state.
    #[inline]
    pub fn new(global: &'static GnsGlobal) -> Self {
        GnsSocket {
            global,
            state: IsCreated,
        }
    }

    fn setup_common(
        address: IpAddr,
        port: u16,
        queue_id: int64,
    ) -> (SteamNetworkingIPAddr, [SteamNetworkingConfigValue_t; 2]) {
        let addr = SteamNetworkingIPAddr {
            __bindgen_anon_1: match address {
                IpAddr::V4(address) => SteamNetworkingIPAddr__bindgen_ty_2 {
                    m_ipv4: SteamNetworkingIPAddr_IPv4MappedAddress {
                        m_8zeros: 0,
                        m_0000: 0,
                        m_ffff: 0xffff,
                        m_ip: address.octets(),
                    },
                },
                IpAddr::V6(address) => SteamNetworkingIPAddr__bindgen_ty_2 {
                    m_ipv6: address.octets(),
                },
            },
            m_port: port,
        };
        let options = [SteamNetworkingConfigValue_t {
            m_eDataType: ESteamNetworkingConfigDataType::k_ESteamNetworkingConfig_Ptr,
            m_eValue: ESteamNetworkingConfigValue::k_ESteamNetworkingConfig_Callback_ConnectionStatusChanged,
            m_val: SteamNetworkingConfigValue_t__bindgen_ty_1 {
              m_ptr: Self::on_connection_state_changed as *const fn(&SteamNetConnectionStatusChangedCallback_t) as *mut c_void
            }
          }, SteamNetworkingConfigValue_t {
            m_eDataType: ESteamNetworkingConfigDataType::k_ESteamNetworkingConfig_Int64,
            m_eValue: ESteamNetworkingConfigValue::k_ESteamNetworkingConfig_ConnectionUserData,
            m_val: SteamNetworkingConfigValue_t__bindgen_ty_1 {
              m_int64: queue_id
            }
        }];
        (addr, options)
    }

    /// Listen for incoming connections, the socket transition from [`IsCreated`] to [`IsServer`], allowing a new set of server operations.
    pub fn listen(self, address: IpAddr, port: u16) -> GnsResult<GnsSocket<IsServer>> {
        let (queue_id, queue) = self.global.create_queue();
        let (addr, options) = Self::setup_common(address, port, queue_id);
        let listen_socket = unsafe {
            SteamAPI_ISteamNetworkingSockets_CreateListenSocketIP(
                get_interface(),
                &addr,
                options.len() as _,
                options.as_ptr(),
            )
        };
        if listen_socket == k_HSteamListenSocket_Invalid {
            Err(GnsError::Listen)
        } else {
            let poll_group =
                unsafe { SteamAPI_ISteamNetworkingSockets_CreatePollGroup(get_interface()) };
            if poll_group == k_HSteamNetPollGroup_Invalid {
                Err(GnsError::Listen)
            } else {
                Ok(GnsSocket {
                    global: self.global,
                    state: IsServer {
                        queue,
                        queue_id,
                        global: self.global,
                        listen_socket: GnsListenSocket(listen_socket),
                        poll_group: GnsPollGroup(poll_group),
                    },
                })
            }
        }
    }

    /// Connect to a remote host, the socket transition from [`IsCreated`] to [`IsClient`], allowing a new set of client operations.
    pub fn connect(self, address: IpAddr, port: u16) -> GnsResult<GnsSocket<IsClient>> {
        let (queue_id, queue) = self.global.create_queue();
        let (addr, options) = Self::setup_common(address, port, queue_id);
        let connection = unsafe {
            SteamAPI_ISteamNetworkingSockets_ConnectByIPAddress(
                get_interface(),
                &addr,
                options.len() as _,
                options.as_ptr(),
            )
        };
        if connection == k_HSteamNetConnection_Invalid {
            Err(GnsError::Connect)
        } else {
            Ok(GnsSocket {
                global: self.global,
                state: IsClient {
                    queue,
                    queue_id,
                    global: self.global,
                    connection: GnsConnection(connection),
                },
            })
        }
    }
}

impl GnsSocket<IsServer> {
    /// Accept an incoming connection. This operation is available only if the socket is in the [`IsServer`] state.
    pub fn accept(&self, connection: GnsConnection) -> GnsResult<()> {
        check(unsafe {
            SteamAPI_ISteamNetworkingSockets_AcceptConnection(get_interface(), connection.0)
        })?;
        if !unsafe {
            SteamAPI_ISteamNetworkingSockets_SetConnectionPollGroup(
                get_interface(),
                connection.0,
                self.state.poll_group.0,
            )
        } {
            // Both the poll group and the connection should be valid here, so
            // this is not expected to happen in practice
            return Err(GnsError::Accept);
        }
        Ok(())
    }
}

impl GnsSocket<IsClient> {
    /// Return the socket connection. This operation is available only if the socket is in the [`IsClient`] state.
    #[inline]
    pub fn connection(&self) -> GnsConnection {
        self.state.connection
    }
}

/// The configuration value used to define configure global variables in [`GnsUtils::set_global_config_value`]
pub enum GnsConfig<'a> {
    Float(f32),
    Int32(i32),
    /// Allocates a `CString` to enforce NUL-termination. Use [`GnsConfig::CStr`]
    /// to skip the allocation when you already have a `CStr`.
    String(&'a str),
    /// Zero-allocation string variant; `&CStr` already carries a trailing NUL.
    CStr(&'a CStr),
    Ptr(*mut c_void),
}

pub struct GnsUtils(());

type MsgPtr = *const ::std::os::raw::c_char;

/// User-supplied debug callback. `Send + Sync` because it is invoked from the
/// GNS service thread, and may capture state shared with the caller's threads.
type DebugCallback = dyn Fn(ESteamNetworkingSocketsDebugOutputType, &str) + Send + Sync + 'static;

/// Set once via [`GnsUtils::enable_debug_output`]; invoked from the GNS service
/// thread, so the underlying `OnceLock` is the synchronization point.
static DEBUG_CB: OnceLock<Box<DebugCallback>> = OnceLock::new();

unsafe extern "C" fn debug_trampoline(ty: ESteamNetworkingSocketsDebugOutputType, msg: MsgPtr) {
    if let Some(cb) = DEBUG_CB.get() {
        let s = unsafe { CStr::from_ptr(msg) }.to_str().unwrap_or("");
        cb(ty, s);
    }
}

impl GnsUtils {
    /// Install a debug callback. Subsequent calls are silently ignored —
    /// only the first registration wins. The callback runs on GNS's service
    /// thread; the `&str` is borrowed for the call duration only.
    ///
    /// The callback may capture state (it is stored as a boxed closure), but
    /// must therefore be `Send + Sync + 'static` since GNS invokes it from its
    /// own thread.
    pub fn enable_debug_output(
        &self,
        ty: ESteamNetworkingSocketsDebugOutputType,
        f: impl Fn(ESteamNetworkingSocketsDebugOutputType, &str) + Send + Sync + 'static,
    ) {
        let _ = DEBUG_CB.set(Box::new(f));
        unsafe {
            SteamAPI_ISteamNetworkingUtils_SetDebugOutputFunction(
                get_utils(),
                ty,
                Some(debug_trampoline),
            );
        }
    }

    /// Allocate a new outbound message, taking ownership of `payload`.
    /// The buffer is held until GNS releases the message, at which point
    /// the wrapper reconstructs `P` via [`Payload::from_raw`] and lets
    /// its `Drop` run. Zero-copy for already-owned heap buffers.
    #[inline]
    pub fn allocate_message<P: Payload>(
        &self,
        conn: GnsConnection,
        flags: SendFlags,
        payload: P,
    ) -> GnsNetworkMessage<ToSend> {
        let message_ptr = unsafe { SteamAPI_ISteamNetworkingUtils_AllocateMessage(get_utils(), 0) };
        GnsNetworkMessage::new(message_ptr, conn, flags, payload)
    }

    /// Set a global configuration value, i.e. k_ESteamNetworkingConfig_FakePacketLag_Send => 1000 ms
    pub fn set_global_config_value(
        &self,
        typ: ESteamNetworkingConfigValue,
        value: GnsConfig<'_>,
    ) -> GnsResult<()> {
        let result = match value {
            GnsConfig::Float(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetGlobalConfigValueFloat(get_utils(), typ, x)
            },
            GnsConfig::Int32(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetGlobalConfigValueInt32(get_utils(), typ, x)
            },
            GnsConfig::String(x) => {
                let c = CString::new(x).map_err(|_| GnsError::Config("interior NUL"))?;
                unsafe {
                    SteamAPI_ISteamNetworkingUtils_SetGlobalConfigValueString(
                        get_utils(),
                        typ,
                        c.as_ptr(),
                    )
                }
            }
            GnsConfig::CStr(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetGlobalConfigValueString(
                    get_utils(),
                    typ,
                    x.as_ptr(),
                )
            },
            GnsConfig::Ptr(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetGlobalConfigValuePtr(get_utils(), typ, x)
            },
        };
        if result {
            Ok(())
        } else {
            Err(GnsError::Config("SetGlobalConfigValue rejected"))
        }
    }

    /// Set a per-connection configuration value, e.g. k_ESteamNetworkingConfig_SendRateMin/Max on an individual accepted connection
    pub fn set_connection_config_value(
        &self,
        conn: GnsConnection,
        typ: ESteamNetworkingConfigValue,
        value: GnsConfig<'_>,
    ) -> GnsResult<()> {
        let result = match value {
            GnsConfig::Float(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetConnectionConfigValueFloat(
                    get_utils(),
                    conn.0,
                    typ,
                    x,
                )
            },
            GnsConfig::Int32(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetConnectionConfigValueInt32(
                    get_utils(),
                    conn.0,
                    typ,
                    x,
                )
            },
            GnsConfig::String(x) => {
                let c = CString::new(x).map_err(|_| GnsError::Config("interior NUL"))?;
                unsafe {
                    SteamAPI_ISteamNetworkingUtils_SetConnectionConfigValueString(
                        get_utils(),
                        conn.0,
                        typ,
                        c.as_ptr(),
                    )
                }
            }
            GnsConfig::CStr(x) => unsafe {
                SteamAPI_ISteamNetworkingUtils_SetConnectionConfigValueString(
                    get_utils(),
                    conn.0,
                    typ,
                    x.as_ptr(),
                )
            },
            GnsConfig::Ptr(_) => return Err(GnsError::Config("Ptr not supported per-connection")),
        };
        if result {
            Ok(())
        } else {
            Err(GnsError::Config("SetConnectionConfigValue rejected"))
        }
    }
}