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
//! UDS (local networking) service.
//!
//! The UDS service is used to handle local networking, i.e. peer-to-peer networking used for local multiplayer.
//! This module also covers some functionality used in Download Play (dlp); there is a specific module for DLP, but it can also be implemented manually using UDS.
#![doc(alias = "network")]
#![doc(alias = "dlplay")]

use std::error::Error as StdError;
use std::ffi::CString;
use std::fmt::{Debug, Display};
use std::mem::MaybeUninit;
use std::ops::FromResidual;
use std::ptr::null;
use std::sync::Mutex;

use crate::error::ResultCode;
use crate::services::ServiceReference;

use bitflags::bitflags;
use macaddr::MacAddr6;

bitflags! {
    /// Flags used for sending packets to a network.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct SendFlags: u8 {
        /// Unknown function according to `libctru`.
        const Default = ctru_sys::UDS_SENDFLAG_Default;
        /// Broadcast the data frame even when sending to a non-broadcast address.
        const Broadcast = ctru_sys::UDS_SENDFLAG_Broadcast;
    }
}

/// Error enum for generic errors within the [`Uds`] service.
#[non_exhaustive]
#[derive(Debug)]
pub enum Error {
    /// The provided username was too long.
    UsernameTooLong,
    /// The provided username contained a NULL byte.
    UsernameContainsNull(usize),
    /// Not connected to a network.
    NotConnected,
    /// No context bound.
    NoContext,
    /// Cannot send data on a network as a spectator.
    Spectator,
    /// No network created.
    NoNetwork,
    /// The provided app data buffer was too large.
    TooMuchAppData,
    /// The provided node ID does not reference a specific node.
    NotANode,
    /// ctru-rs error
    Lib(crate::Error),
}

impl From<crate::Error> for Error {
    fn from(value: crate::Error) -> Self {
        Error::Lib(value)
    }
}

impl<T> FromResidual<crate::Error> for Result<T, Error> {
    fn from_residual(residual: crate::Error) -> Self {
        Err(residual.into())
    }
}

impl From<std::ffi::NulError> for Error {
    fn from(value: std::ffi::NulError) -> Self {
        Error::UsernameContainsNull(value.nul_position())
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::UsernameTooLong =>
                    "provided username was too long (max 10 bytes, not code points)".into(),
                Self::UsernameContainsNull(pos) =>
                    format!("provided username contained a NULL byte at position {pos}"),
                Self::NotConnected => "not connected to a network".into(),
                Self::NoContext => "no context bound".into(),
                Self::Spectator => "cannot send data on a network as a spectator".into(),
                Self::NoNetwork => "not hosting a network".into(),
                Self::TooMuchAppData => "provided too much app data (max 200 bytes)".into(),
                Self::NotANode => "provided node ID was non-specific".into(),
                Self::Lib(e) => format!("ctru-rs error: {e}"),
            }
        )
    }
}

impl StdError for Error {}

/// Possible types of connection to a network.
#[doc(alias = "udsConnectionType")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum ConnectionType {
    /// A normal client. Can push packets to the network.
    Client = ctru_sys::UDSCONTYPE_Client,
    /// A spectator. Cannot push packets to the network,
    /// but doesn't need the passphrase to join.
    Spectator = ctru_sys::UDSCONTYPE_Spectator,
}

impl From<ConnectionType> for u8 {
    fn from(value: ConnectionType) -> Self {
        value as Self
    }
}

impl TryFrom<u8> for ConnectionType {
    type Error = ();

    fn try_from(value: u8) -> std::result::Result<Self, Self::Error> {
        match value {
            ctru_sys::UDSCONTYPE_Client => Ok(Self::Client),
            ctru_sys::UDSCONTYPE_Spectator => Ok(Self::Spectator),
            _ => Err(()),
        }
    }
}

/// ID for a node on the network.
#[doc(alias = "NetworkNodeID")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeID {
    /// No node ID set (not connected to a network).
    None,
    /// A normal node on the network, counting from 1 (the host) to 16, inclusive.
    Node(u8),
    /// Broadcast to all nodes
    Broadcast,
}

impl From<NodeID> for u16 {
    fn from(value: NodeID) -> Self {
        match value {
            NodeID::None => 0,
            NodeID::Node(node) => node as u16,
            NodeID::Broadcast => ctru_sys::UDS_BROADCAST_NETWORKNODEID as u16,
        }
    }
}

impl TryFrom<u16> for NodeID {
    type Error = ();

    fn try_from(value: u16) -> std::result::Result<Self, Self::Error> {
        match value as u32 {
            0 => Ok(Self::None),
            ctru_sys::UDS_HOST_NETWORKNODEID..=ctru_sys::UDS_MAXNODES => {
                Ok(Self::Node(value as u8))
            }
            ctru_sys::UDS_BROADCAST_NETWORKNODEID => Ok(Self::Broadcast),
            _ => Err(()),
        }
    }
}

/// Information about a network node.
#[doc(alias = "udsNodeInfo")]
#[derive(Copy, Clone)]
pub struct NodeInfo(ctru_sys::udsNodeInfo);

impl Debug for NodeInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "NodeInfo(")?;

        f.debug_struct("udsNodeInfo")
            .field("uds_friendcodeseed", &self.uds_friendcodeseed())
            .field("username", &self.username())
            .field("flag", &self.flag())
            .field("NetworkNodeID", &self.node_id())
            .finish()?;

        write!(f, ")")
    }
}

impl From<ctru_sys::udsNodeInfo> for NodeInfo {
    fn from(value: ctru_sys::udsNodeInfo) -> Self {
        Self(value)
    }
}

impl NodeInfo {
    /// Friend code seed associated with this network node.
    pub fn uds_friendcodeseed(&self) -> u64 {
        self.0.uds_friendcodeseed
    }

    /// Username associated with this network node.
    pub fn username(&self) -> String {
        String::from_utf16_lossy(unsafe { &self.0.__bindgen_anon_1.__bindgen_anon_1.username })
    }

    /// Flag associated with this network node.
    pub fn flag(&self) -> u8 {
        unsafe { self.0.__bindgen_anon_1.__bindgen_anon_1.flag }
    }

    /// Node ID associated with this network node.
    pub fn node_id(&self) -> NodeID {
        self.0
            .NetworkNodeID
            .try_into()
            .expect("UDS service should always provide a valid NetworkNodeID")
    }
}

/// Information returned from scanning for networks.
#[doc(alias = "udsNetworkScanInfo")]
#[derive(Copy, Clone)]
pub struct NetworkScanInfo(ctru_sys::udsNetworkScanInfo);

impl Debug for NetworkScanInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "NetworkScanInfo(")?;

        f.debug_struct("udsNetworkScanInfo")
            .field("datareply_entry", &self.datareply_entry())
            .field("network", &self.network())
            .field("nodes", &self.nodes())
            .finish()?;

        write!(f, ")")
    }
}

impl From<ctru_sys::udsNetworkScanInfo> for NetworkScanInfo {
    fn from(value: ctru_sys::udsNetworkScanInfo) -> Self {
        Self(value)
    }
}

impl NetworkScanInfo {
    /// NWM output structure.
    pub fn datareply_entry(&self) -> ctru_sys::nwmBeaconDataReplyEntry {
        self.0.datareply_entry
    }

    /// Get a reference to the NWM output structure.
    pub fn datareply_entry_ref(&self) -> &ctru_sys::nwmBeaconDataReplyEntry {
        &self.0.datareply_entry
    }

    /// Get a mutable reference to the NWM output structure.
    pub fn datareply_entry_mut(&mut self) -> &mut ctru_sys::nwmBeaconDataReplyEntry {
        &mut self.0.datareply_entry
    }

    /// Information about the network.
    pub fn network(&self) -> ctru_sys::udsNetworkStruct {
        self.0.network
    }

    /// Get a reference to the information about the network.
    pub fn network_ref(&self) -> &ctru_sys::udsNetworkStruct {
        &self.0.network
    }

    /// Get a mutable reference to the information about the network.
    pub fn network_mut(&mut self) -> &mut ctru_sys::udsNetworkStruct {
        &mut self.0.network
    }

    /// All nodes on the network (first node is the server,
    /// max 16, `None` means no node connected).
    pub fn nodes(&self) -> [Option<NodeInfo>; 16] {
        self.0.nodes.map(|n| {
            if n.uds_friendcodeseed != 0 {
                Some(n.into())
            } else {
                None
            }
        })
    }
}

/// Possible raw connection status values.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
#[non_exhaustive]
pub enum ConnectionStatusInfo {
    /// Not connected to any network.
    Disconnected = 3,
    /// Connected as a host.
    Host = 6,
    /// Connected as a client.
    Client = 9,
    /// Connected as a spectator.
    Spectator = 10,
    /// Unknown
    Unknown = 11,
}

impl From<ConnectionStatusInfo> for u32 {
    fn from(value: ConnectionStatusInfo) -> Self {
        value as Self
    }
}

impl TryFrom<u32> for ConnectionStatusInfo {
    type Error = ();

    fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
        match value {
            3 => Ok(Self::Disconnected),
            6 => Ok(Self::Host),
            9 => Ok(Self::Client),
            10 => Ok(Self::Spectator),
            11 => Ok(Self::Unknown),
            _ => Err(()),
        }
    }
}

/// Status of the connection.
#[doc(alias = "udsConnectionStatus")]
#[derive(Clone, Copy)]
pub struct ConnectionStatus(ctru_sys::udsConnectionStatus);

impl Debug for ConnectionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "ConnectionStatus(")?;

        f.debug_struct("udsConnectionStatus")
            .field("status", &self.status())
            .field("cur_node_id", &self.cur_node_id())
            .field("total_nodes", &self.total_nodes())
            .field("max_nodes", &self.max_nodes())
            .field("node_bitmask", &self.node_bitmask())
            .finish()?;

        write!(f, ")")
    }
}

impl From<ctru_sys::udsConnectionStatus> for ConnectionStatus {
    fn from(value: ctru_sys::udsConnectionStatus) -> Self {
        Self(value)
    }
}

impl ConnectionStatus {
    /// Raw status information.
    pub fn status(&self) -> Option<ConnectionStatusInfo> {
        self.0.status.try_into().ok()
    }

    /// Network node ID for the current device.
    pub fn cur_node_id(&self) -> NodeID {
        self.0
            .cur_NetworkNodeID
            .try_into()
            .expect("UDS service should always provide a valid NetworkNodeID")
    }

    /// Number of nodes connected to the network.
    pub fn total_nodes(&self) -> u8 {
        self.0.total_nodes
    }

    /// Maximum nodes allowed on this network.
    pub fn max_nodes(&self) -> u8 {
        self.0.max_nodes
    }

    /// Bitmask for which of the 16 possible nodes are connected
    /// to this network; bit 0 is the server, bit 1 is the first
    /// original client, etc.
    pub fn node_bitmask(&self) -> u16 {
        self.0.node_bitmask
    }
}

/// Status of the service handle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceStatus {
    /// Not connected to or hosting a network.
    Disconnected,
    /// Connected to a network.
    Client,
    /// Hosting a network.
    Server,
}

/// Handle to the UDS service.
pub struct Uds {
    _service_handler: ServiceReference,
    context: Option<ctru_sys::udsBindContext>,
    network: Option<ctru_sys::udsNetworkStruct>,
    scan_buf: Box<[u8; Self::SCAN_BUF_SIZE]>,
}

static UDS_ACTIVE: Mutex<()> = Mutex::new(());

impl Uds {
    /// Size of one frame.
    const RECV_FRAME_SIZE: usize = ctru_sys::UDS_DATAFRAME_MAXSIZE as usize;

    /// Size of receive buffer; max frame size * 8.
    const RECV_BUF_SIZE: u32 = ctru_sys::UDS_DEFAULT_RECVBUFSIZE;

    /// Shared memory size; must be slightly larger
    /// than `RECV_BUF_SIZE`.
    const SHAREDMEM_SIZE: usize = 0x3000;

    /// Buffer used while scanning for networks.
    /// This value is taken from the devkitPRO example.
    const SCAN_BUF_SIZE: usize = 0x4000;

    /// The maximum number of nodes that can ever be connected
    /// to a network (16). Can be further limited.
    const MAX_NODES: u8 = ctru_sys::UDS_MAXNODES as u8;

    /// The maximum amount of app data any server can provide.
    /// Limited by the size of a struct in libctru.
    const MAX_APPDATA_SIZE: usize = Self::size_of_call(|s: ctru_sys::udsNetworkStruct| s.appdata);

    const fn size_of_call<T, U>(_: fn(T) -> U) -> usize {
        std::mem::size_of::<U>()
    }

    /// Retrieve the current status of the service.
    pub fn service_status(&self) -> ServiceStatus {
        match (self.context, self.network) {
            (None, None) => ServiceStatus::Disconnected,
            (Some(_), None) => ServiceStatus::Client,
            (Some(_), Some(_)) => ServiceStatus::Server,
            _ => unreachable!(),
        }
    }

    /// Initialise a new service handle.
    /// No `new_with_buffer_size` function is provided, as there isn't really a
    /// reason to use any size other than the default.
    ///
    /// The `username` parameter should be a max 10-byte (not 10 code point!) UTF-8 string, converted to UTF-16 internally.
    /// Pass `None` to use the 3DS's configured username.
    ///
    /// # Errors
    ///
    /// This function will return an error if the [`Uds`] service is already being used,
    /// or if the provided username is invalid (longer than 10 bytes or contains a NULL byte).
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    ///
    /// let uds = Uds::new(None)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsInit")]
    pub fn new(username: Option<&str>) -> Result<Self, Error> {
        if let Some(n) = username {
            if n.len() > 10 {
                return Err(Error::UsernameTooLong);
            }
        }
        let cstr = username.map(CString::new).transpose()?;
        let handler = ServiceReference::new(
            &UDS_ACTIVE,
            || {
                let ptr = cstr.map(|c| c.as_ptr()).unwrap_or(null());

                ResultCode(unsafe { ctru_sys::udsInit(Self::SHAREDMEM_SIZE, ptr) })?;

                Ok(())
            },
            || unsafe {
                ctru_sys::udsExit();
            },
        )?;

        Ok(Self {
            _service_handler: handler,
            context: None,
            network: None,
            scan_buf: Box::new([0; Self::SCAN_BUF_SIZE]),
        })
    }

    /// Scan the UDS service for all available beacons broadcasting with the given IDs.
    ///
    /// This function must be called to obtain network objects that can later be connected to.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsScanBeacons")]
    pub fn scan(
        &mut self,
        comm_id: &[u8; 4],
        additional_id: Option<u8>,
        whitelist_macaddr: Option<MacAddr6>,
    ) -> crate::Result<Vec<NetworkScanInfo>> {
        self.scan_buf.fill(0);

        let mut networks = MaybeUninit::uninit();
        let mut total_networks = MaybeUninit::uninit();

        ResultCode(unsafe {
            ctru_sys::udsScanBeacons(
                self.scan_buf.as_mut_ptr().cast(),
                Self::SCAN_BUF_SIZE,
                networks.as_mut_ptr(),
                total_networks.as_mut_ptr(),
                u32::from_be_bytes(*comm_id),
                additional_id.unwrap_or(0),
                whitelist_macaddr
                    .map(|m| m.as_bytes().as_ptr())
                    .unwrap_or(null()),
                self.service_status() == ServiceStatus::Client,
            )
        })?;

        let networks = unsafe { networks.assume_init() };
        let total_networks = unsafe { total_networks.assume_init() };

        let networks = if total_networks > 0 {
            // Safety: `networks` is malloced in application memory with size = `total_networks`
            unsafe { Vec::from_raw_parts(networks, total_networks, total_networks) }
                .into_iter()
                .map(NetworkScanInfo::from)
                .collect()
        } else {
            vec![]
        };

        Ok(networks)
    }

    /// Retrieve app data for a network which the service is not connected to.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// let appdata = uds.network_appdata(&networks[0], None)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsGetNetworkStructApplicationData")]
    pub fn network_appdata(
        &self,
        network: &NetworkScanInfo,
        max_size: Option<usize>,
    ) -> crate::Result<Vec<u8>> {
        let mut appdata_buffer = vec![
            0u8;
            max_size
                .unwrap_or(Self::MAX_APPDATA_SIZE)
                .min(Self::MAX_APPDATA_SIZE)
        ];

        let mut actual_size = MaybeUninit::uninit();

        ResultCode(unsafe {
            ctru_sys::udsGetNetworkStructApplicationData(
                network.network_ref() as *const _,
                appdata_buffer.as_mut_ptr().cast(),
                appdata_buffer.len(),
                actual_size.as_mut_ptr(),
            )
        })?;

        let actual_size = unsafe { actual_size.assume_init() };

        appdata_buffer.truncate(actual_size);
        appdata_buffer.shrink_to_fit();

        Ok(appdata_buffer)
    }

    /// Retrieve app data for the currently connected network.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is not connected to a network.
    /// See [`Uds::connect_network()`] to connect to a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// let appdata = uds.appdata(None)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsGetApplicationData")]
    pub fn appdata(&self, max_size: Option<usize>) -> Result<Vec<u8>, Error> {
        if self.service_status() == ServiceStatus::Disconnected {
            return Err(Error::NotConnected);
        }

        let mut appdata_buffer = vec![
            0u8;
            max_size
                .unwrap_or(Self::MAX_APPDATA_SIZE)
                .min(Self::MAX_APPDATA_SIZE)
        ];

        let mut actual_size = MaybeUninit::uninit();

        ResultCode(unsafe {
            ctru_sys::udsGetApplicationData(
                appdata_buffer.as_mut_ptr().cast(),
                appdata_buffer.len(),
                actual_size.as_mut_ptr(),
            )
        })?;

        let actual_size = unsafe { actual_size.assume_init() };

        appdata_buffer.truncate(actual_size);
        appdata_buffer.shrink_to_fit();

        Ok(appdata_buffer)
    }

    /// Connect to a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsConnectNetwork")]
    pub fn connect_network(
        &mut self,
        network: &NetworkScanInfo,
        passphrase: &[u8],
        connection_type: ConnectionType,
        channel: u8,
    ) -> crate::Result<()> {
        let mut context = MaybeUninit::uninit();

        ResultCode(unsafe {
            ctru_sys::udsConnectNetwork(
                network.network_ref() as *const _,
                passphrase.as_ptr().cast(),
                passphrase.len(),
                context.as_mut_ptr(),
                NodeID::Broadcast.into(),
                connection_type as u8,
                channel,
                Self::RECV_BUF_SIZE,
            )
        })?;

        let context = unsafe { context.assume_init() };

        self.context.replace(context);

        Ok(())
    }

    /// Disconnect from a network.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is not connected to a network.
    /// See [`Uds::connect_network()`] to connect to a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// uds.disconnect_network()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsDisconnectNetwork")]
    pub fn disconnect_network(&mut self) -> Result<(), Error> {
        if self.service_status() != ServiceStatus::Client {
            return Err(Error::NotConnected);
        }

        if self.context.is_some() {
            self.unbind_context()?;
        }

        ResultCode(unsafe { ctru_sys::udsDisconnectNetwork() })?;

        Ok(())
    }

    /// Unbind the connection context.
    ///
    /// Normally, there's no reason to call this function,
    /// since [`Uds::disconnect_network()`] and [`Uds::destroy_network()`] both automatically unbind their contexts.
    ///
    /// # Errors
    ///
    /// This function will return an error if no context is currently bound (i.e. the service is neither connected to nor hosting a network).
    /// See [`Uds::connect_network()`] to connect to a network or [`Uds::create_network()`] to create one.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// uds.unbind_context()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsUnbind")]
    pub fn unbind_context(&mut self) -> Result<(), Error> {
        if let Some(mut ctx) = self.context {
            ResultCode(unsafe { ctru_sys::udsUnbind(&mut ctx as *mut _) })?;
        } else {
            return Err(Error::NoContext);
        }

        self.context = None;

        Ok(())
    }

    /// Returns the Wi-Fi channel currently in use.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is currently neither connected to nor hosting a network.
    /// See [`Uds::connect_network()`] to connect to a network or [`Uds::create_network()`] to create one.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// let channel = uds.channel()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsGetChannel")]
    pub fn channel(&self) -> Result<u8, Error> {
        if self.service_status() == ServiceStatus::Disconnected {
            return Err(Error::NotConnected);
        }

        let mut channel = MaybeUninit::uninit();

        ResultCode(unsafe { ctru_sys::udsGetChannel(channel.as_mut_ptr()) })?;

        let channel = unsafe { channel.assume_init() };

        Ok(channel)
    }

    /// Wait for a ConnectionStatus event to occur.
    ///
    /// If `next` is `true`, discard the current event (if any) and wait for the next one.
    ///
    /// If `wait` is `true`, block until an event is signalled, else return `false` if no event.
    ///
    /// Always returns `true`, unless `wait` is `false` and no event has been signalled.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is currently neither connected to nor hosting a network.
    /// See [`Uds::connect_network()`] to connect to a network or [`Uds::create_network()`] to create one.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// if uds.wait_status_event(false, false)? {
    ///     println!("Event signalled");
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsWaitConnectionStatusEvent")]
    pub fn wait_status_event(&self, next: bool, wait: bool) -> Result<bool, Error> {
        if self.service_status() == ServiceStatus::Disconnected {
            return Err(Error::NotConnected);
        }

        Ok(unsafe { ctru_sys::udsWaitConnectionStatusEvent(next, wait) })
    }

    /// Returns the current [`ConnectionStatus`] struct.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// if uds.wait_status_event(false, false)? {
    ///     println!("Connection status event signalled");
    ///     let status = uds.connection_status()?;
    ///     println!("Status: {status:#X?}");
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsGetConnectionStatus")]
    pub fn connection_status(&self) -> crate::Result<ConnectionStatus> {
        let mut status = MaybeUninit::uninit();

        ResultCode(unsafe { ctru_sys::udsGetConnectionStatus(status.as_mut_ptr()) })?;

        let status = unsafe { status.assume_init() };

        Ok(status.into())
    }

    /// Send a packet to the network.
    ///
    /// TODO: max size?
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is currently neither connected to nor hosting a network.
    /// See [`Uds::connect_network()`] to connect to a network or [`Uds::create_network()`] to create one.
    /// It will also return an error if the service is currently connected to a network as a spectator, as spectators cannot send data, only receive it.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, NodeID, SendFlags, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// uds.send_packet(b"Hello, World!", NodeID::Broadcast, 1, SendFlags::Default)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsSendTo")]
    pub fn send_packet(
        &self,
        packet: &[u8],
        address: NodeID,
        channel: u8,
        flags: SendFlags,
    ) -> Result<(), Error> {
        if self.service_status() == ServiceStatus::Disconnected {
            return Err(Error::NotConnected);
        }

        if self.context.unwrap().spectator {
            return Err(Error::Spectator);
        }

        let code = ResultCode(unsafe {
            ctru_sys::udsSendTo(
                address.into(),
                channel,
                flags.bits(),
                packet.as_ptr().cast(),
                packet.len(),
            )
        });

        if code.0
            != ctru_sys::MAKERESULT(
                ctru_sys::RL_STATUS as _,
                ctru_sys::RS_OUTOFRESOURCE as _,
                ctru_sys::RM_UDS as _,
                ctru_sys::RD_BUSY as _,
            )
        {
            code?;
        }

        Ok(())
    }

    /// Pull a packet from the network.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is currently neither connected to nor hosting a network.
    /// See [`Uds::connect_network()`] to connect to a network or [`Uds::create_network()`] to create one.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// let packet = uds.pull_packet()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsPullPacket")]
    pub fn pull_packet(&self) -> Result<Option<(Vec<u8>, NodeID)>, Error> {
        if self.service_status() == ServiceStatus::Disconnected {
            return Err(Error::NotConnected);
        }

        let mut frame = MaybeUninit::<[u8; Self::RECV_FRAME_SIZE]>::zeroed();

        let mut actual_size = MaybeUninit::uninit();
        let mut src_node_id = MaybeUninit::uninit();

        ResultCode(unsafe {
            ctru_sys::udsPullPacket(
                &self.context.unwrap() as *const _,
                frame.as_mut_ptr().cast(),
                Self::RECV_FRAME_SIZE,
                actual_size.as_mut_ptr(),
                src_node_id.as_mut_ptr(),
            )
        })?;

        let frame = unsafe { frame.assume_init() };
        let actual_size = unsafe { actual_size.assume_init() };
        let src_node_id = unsafe { src_node_id.assume_init() };

        Ok(if actual_size == 0 {
            None
        } else {
            // TODO: to_vec() first, then truncate() and shrink_to_fit()?
            Some((
                frame[..actual_size].to_vec(),
                src_node_id
                    .try_into()
                    .expect("UDS service should always provide a valid NetworkNodeID"),
            ))
        })
    }

    /// Create a new network.
    ///
    /// # Errors
    ///
    /// This function will return an error if the [`Uds`] service is already being used.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsCreateNetwork")]
    pub fn create_network(
        &mut self,
        comm_id: &[u8; 4],
        additional_id: Option<u8>,
        max_nodes: Option<u8>,
        passphrase: &[u8],
        channel: u8,
    ) -> crate::Result<()> {
        let mut network = MaybeUninit::uninit();
        unsafe {
            ctru_sys::udsGenerateDefaultNetworkStruct(
                network.as_mut_ptr(),
                u32::from_be_bytes(*comm_id),
                additional_id.unwrap_or(0),
                max_nodes.unwrap_or(Self::MAX_NODES).min(Self::MAX_NODES),
            )
        };

        let network = unsafe { network.assume_init() };

        let mut context = MaybeUninit::uninit();

        ResultCode(unsafe {
            ctru_sys::udsCreateNetwork(
                &network as *const _,
                passphrase.as_ptr().cast(),
                passphrase.len(),
                context.as_mut_ptr(),
                channel,
                Self::RECV_BUF_SIZE,
            )
        })?;

        let context = unsafe { context.assume_init() };

        self.network.replace(network);

        self.context.replace(context);

        Ok(())
    }

    /// Destroy the current network.
    ///
    /// # Errors
    ///
    /// This function will return an error if no network has been created.
    /// See [`Uds::create_network()`] to create a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// uds.destroy_network()?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsDestroyNetwork")]
    pub fn destroy_network(&mut self) -> Result<(), Error> {
        if self.service_status() != ServiceStatus::Server {
            return Err(Error::NoNetwork);
        }

        // should always be true
        if self.context.is_some() {
            self.unbind_context()?;
        }

        ResultCode(unsafe { ctru_sys::udsDestroyNetwork() })?;

        self.network = None;

        Ok(())
    }

    /// Set the app data for the currently hosted network.
    ///
    /// # Errors
    ///
    /// This function will return an error if no network has been created.
    /// See [`Uds::create_network()`] to create a network.
    /// This function will also return an error if the provided buffer is too large (see [`Uds::MAX_APPDATA_SIZE`]).
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// uds.set_appdata(b"Test appdata.\0")?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsSetApplicationData")]
    pub fn set_appdata(&self, data: &[u8]) -> Result<(), Error> {
        if self.service_status() != ServiceStatus::Server {
            return Err(Error::NoNetwork);
        }

        if data.len() > Self::MAX_APPDATA_SIZE {
            return Err(Error::TooMuchAppData);
        }

        ResultCode(unsafe { ctru_sys::udsSetApplicationData(data.as_ptr().cast(), data.len()) })?;

        Ok(())
    }

    /// Wait for a bind event to occur.
    ///
    /// If `next` is `true`, discard the current event (if any) and wait for the next one.
    ///
    /// If `wait` is `true`, block until an event is signalled, else return `false` if no event.
    ///
    /// Always returns `true`, unless `wait` is `false` and no event has been signalled.
    ///
    /// # Errors
    ///
    /// This function will return an error if the service is currently neither connected to nor hosting a network.
    /// See [`Uds::connect_network()`] to connect to a network or [`Uds::create_network()`] to create one.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{ConnectionType, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// let networks = uds.scan(b"HBW\x10", None, None)?;
    /// uds.connect_network(&networks[0], b"udsdemo passphrase c186093cd2652741\0", ConnectionType::Client, 1)?;
    /// if uds.wait_data_available(false, false)? {
    ///     println!("Data available");
    /// }
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsWaitConnectionStatusEvent")]
    pub fn wait_data_available(&self, next: bool, wait: bool) -> Result<bool, Error> {
        if self.service_status() == ServiceStatus::Disconnected {
            return Err(Error::NotConnected);
        }

        Ok(unsafe {
            ctru_sys::udsWaitDataAvailable(&self.context.unwrap() as *const _, next, wait)
        })
    }

    /// Eject a client from the network.
    ///
    /// # Errors
    ///
    /// This function will return an error if no network has been created.
    /// See [`Uds::create_network()`] to create a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{NodeID, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// uds.eject_client(NodeID::Node(2))?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsEjectClient")]
    pub fn eject_client(&self, address: NodeID) -> Result<(), Error> {
        if self.service_status() != ServiceStatus::Server {
            return Err(Error::NoNetwork);
        }

        ResultCode(unsafe { ctru_sys::udsEjectClient(address.into()) })?;

        Ok(())
    }

    /// Allow or disallow spectators on the network.
    ///
    /// Disallowing spectators will disconnect all spectators currently observing the network.
    ///
    /// # Errors
    ///
    /// This function will return an error if no network has been created.
    /// See [`Uds::create_network()`] to create a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// uds.allow_spectators(false)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsEjectSpectator")]
    #[doc(alias = "udsAllowSpectators")]
    pub fn allow_spectators(&mut self, allow: bool) -> Result<(), Error> {
        if self.service_status() != ServiceStatus::Server {
            return Err(Error::NoNetwork);
        }

        ResultCode(unsafe {
            if allow {
                ctru_sys::udsAllowSpectators()
            } else {
                ctru_sys::udsEjectSpectator()
            }
        })?;

        Ok(())
    }

    /// Allow or disallow new clients on the network.
    ///
    /// Disallowing new clients will not disconnect any currently connected clients.
    ///
    /// # Errors
    ///
    /// This function will return an error if no network has been created.
    /// See [`Uds::create_network()`] to create a network.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::Uds;
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// uds.allow_new_clients(false)?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsSetNewConnectionsBlocked")]
    pub fn allow_new_clients(&mut self, allow: bool) -> Result<(), Error> {
        if self.service_status() != ServiceStatus::Server {
            return Err(Error::NoNetwork);
        }

        ResultCode(unsafe { ctru_sys::udsSetNewConnectionsBlocked(!allow, true, false) })?;

        Ok(())
    }

    /// Returns the [`NodeInfo`] struct for the specified network node.
    ///
    /// # Errors
    ///
    /// This function will return an error if [`NodeID::None`] or [`NodeID::Broadcast`] is passed.
    ///
    /// # Example
    ///
    /// ```
    /// # let _runner = test_runner::GdbRunner::default();
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// #
    /// use ctru::services::uds::{NodeID, Uds};
    /// let mut uds = Uds::new(None)?;
    ///
    /// uds.create_network(b"HBW\x10", None, None, b"udsdemo passphrase c186093cd2652741\0", 1)?;
    /// let node_info = uds.node_info(NodeID::Node(2))?;
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[doc(alias = "udsGetNodeInformation")]
    pub fn node_info(&self, address: NodeID) -> Result<NodeInfo, Error> {
        let NodeID::Node(node) = address else {
            return Err(Error::NotANode);
        };

        let mut info = MaybeUninit::uninit();

        ResultCode(unsafe { ctru_sys::udsGetNodeInformation(node as u16, info.as_mut_ptr()) })?;

        let info = unsafe { info.assume_init() };

        Ok(info.into())
    }
}

impl Drop for Uds {
    #[doc(alias = "udsExit")]
    fn drop(&mut self) {
        match self.service_status() {
            ServiceStatus::Client => self.disconnect_network().unwrap(),
            ServiceStatus::Server => self.destroy_network().unwrap(),
            _ => {}
        };
        // ctru_sys::udsExit() is called by the ServiceHandle
    }
}