rice-c 0.4.2

ICE (RFC8445) implementation protocol
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
// Copyright (C) 2025 Matthew Waters <matthew@centricular.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! ICE Candidates

use std::ffi::{CStr, CString};

/// ICE candidate.
pub trait CandidateApi: sealed::CandidateAsC {
    /// The component
    fn component_id(&self) -> usize {
        unsafe { (*self.as_c()).component_id }
    }
    /// The type of the Candidate
    fn candidate_type(&self) -> CandidateType {
        unsafe { (*self.as_c()).candidate_type.into() }
    }
    /// The network transport
    fn transport(&self) -> TransportType {
        unsafe { (*self.as_c()).transport_type.into() }
    }

    /// The (unique) foundation
    fn foundation(&self) -> String {
        unsafe {
            CStr::from_ptr((*self.as_c()).foundation)
                .to_str()
                .unwrap()
                .to_owned()
        }
    }
    /// The priority
    fn priority(&self) -> u32 {
        unsafe { (*self.as_c()).priority }
    }
    /// The address to send to
    fn address(&self) -> crate::Address {
        unsafe { crate::Address::from_c_none((*self.as_c()).address) }
    }
    /// The address to send from
    fn base_address(&self) -> crate::Address {
        unsafe { crate::Address::from_c_none((*self.as_c()).base_address) }
    }
    /// Any related address that generated this candidate, e.g. STUN/TURN server
    fn related_address(&self) -> Option<crate::Address> {
        unsafe {
            let related = (*self.as_c()).related_address;
            if related.is_null() {
                None
            } else {
                Some(crate::Address::from_c_none(related))
            }
        }
    }
    /// The type of TCP candidate
    fn tcp_type(&self) -> TcpType {
        unsafe { (*self.as_c()).tcp_type.into() }
    }
    // TODO: extensions
}

/// Errors produced when parsing a candidate
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(i32)]
pub enum ParseCandidateError {
    /// Not a candidate message.
    NotCandidate = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_NOT_CANDIDATE,
    /// Invalid foundation value.
    BadFoundation = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_FOUNDATION,
    /// Invalid component id.
    BadComponentId = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_COMPONENT_ID,
    /// Invalid transport type.
    BadTransportType = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_TRANSPORT_TYPE,
    /// Invalid priority value.
    BadPriority = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_PRIORITY,
    /// Invalid network address.
    BadAddress = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_ADDRESS,
    /// Invalid candidate type.
    BadCandidateType = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_CANDIDATE_TYPE,
    /// Invalid extension format.
    BadExtension = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_EXTENSION,
    /// Data is not well formed.
    Malformed = crate::ffi::RICE_PARSE_CANDIDATE_ERROR_MALFORMED,
}

impl ParseCandidateError {
    pub(crate) fn from_c(
        value: crate::ffi::RiceParseCandidateError,
    ) -> Result<(), ParseCandidateError> {
        match value {
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_SUCCESS => Ok(()),
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_NOT_CANDIDATE => {
                Err(ParseCandidateError::NotCandidate)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_FOUNDATION => {
                Err(ParseCandidateError::BadFoundation)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_COMPONENT_ID => {
                Err(ParseCandidateError::BadComponentId)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_TRANSPORT_TYPE => {
                Err(ParseCandidateError::BadTransportType)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_PRIORITY => {
                Err(ParseCandidateError::BadPriority)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_ADDRESS => {
                Err(ParseCandidateError::BadAddress)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_CANDIDATE_TYPE => {
                Err(ParseCandidateError::BadCandidateType)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_EXTENSION => {
                Err(ParseCandidateError::BadExtension)
            }
            crate::ffi::RICE_PARSE_CANDIDATE_ERROR_MALFORMED => Err(ParseCandidateError::Malformed),
            val => panic!("Unknown RiceParseCandidateError value {val:x?}"),
        }
    }
}

mod sealed {
    pub trait CandidateAsC {
        fn as_c(&self) -> *const crate::ffi::RiceCandidate;
    }
}

/// An ICE candidate.
#[derive(Clone)]
pub struct Candidate {
    ffi: crate::ffi::RiceCandidate,
}

unsafe impl Send for Candidate {}
unsafe impl Sync for Candidate {}

impl core::fmt::Debug for Candidate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut dbg = f.debug_struct("Candidate");
        dbg.field("component_id", &self.component_id());
        dbg.field("candidate_type", &self.candidate_type());
        dbg.field("transport_type", &self.transport());
        dbg.field("foundation", &self.foundation());
        dbg.field("priority", &self.priority());
        dbg.field("address", &self.address());
        dbg.field("base_address", &self.base_address());
        dbg.field("related_address", &self.related_address());
        dbg.field("tcp_type", &self.tcp_type());
        // TODO: extensions
        dbg.finish()
    }
}

impl PartialEq<Candidate> for Candidate {
    fn eq(&self, other: &Candidate) -> bool {
        unsafe { crate::ffi::rice_candidate_eq(&self.ffi, &other.ffi) }
    }
}

impl PartialEq<CandidateOwned> for Candidate {
    fn eq(&self, other: &CandidateOwned) -> bool {
        unsafe { crate::ffi::rice_candidate_eq(&self.ffi, other.ffi) }
    }
}

impl Eq for Candidate {}

impl CandidateApi for Candidate {}
impl sealed::CandidateAsC for Candidate {
    fn as_c(&self) -> *const crate::ffi::RiceCandidate {
        &self.ffi
    }
}

impl Drop for Candidate {
    fn drop(&mut self) {
        unsafe { crate::ffi::rice_candidate_clear(&mut self.ffi) }
    }
}

impl Candidate {
    /// Builds the candidate
    ///
    /// # Examples
    ///
    /// ```
    /// # use rice_c::candidate::*;
    /// # use rice_c::Address;
    /// let addr: Address = "127.0.0.1:2345".parse().unwrap();
    /// let candidate = Candidate::builder(
    ///     1,
    ///     CandidateType::Host,
    ///     TransportType::Udp,
    ///     "foundation",
    ///     addr,
    /// )
    /// .priority(1234)
    /// .build();
    /// assert_eq!(candidate.to_sdp_string(), "a=candidate:foundation 1 UDP 1234 127.0.0.1 2345 typ host")
    /// ```
    pub fn builder(
        component_id: usize,
        ctype: CandidateType,
        ttype: TransportType,
        foundation: &str,
        address: crate::Address,
    ) -> CandidateBuilder {
        unsafe {
            let foundation = CString::new(foundation).unwrap();
            let mut ret = CandidateBuilder {
                ffi: crate::ffi::RiceCandidate::zeroed(),
            };
            let address = address.into_c_full();
            let res = crate::ffi::rice_candidate_init(
                &mut ret.ffi,
                component_id,
                ctype.into(),
                ttype.into(),
                foundation.as_ptr(),
                address,
            );
            if res != crate::ffi::RICE_ERROR_SUCCESS {
                let _address = crate::Address::from_c_full(address);
                panic!("Failed to crate ICE candidate!");
            }
            ret
        }
    }

    pub(crate) fn as_c(&self) -> *const crate::ffi::RiceCandidate {
        &self.ffi
    }

    pub(crate) unsafe fn from_c_none(candidate: *const crate::ffi::RiceCandidate) -> Self {
        unsafe {
            let mut ret = Self {
                ffi: crate::ffi::RiceCandidate::zeroed(),
            };
            crate::ffi::rice_candidate_copy_into(candidate, &mut ret.ffi);
            ret
        }
    }

    pub(crate) fn from_c_full(candidate: crate::ffi::RiceCandidate) -> Self {
        Self { ffi: candidate }
    }

    /// Copy this candidate into a heap allocated [`CandidateOwned`].
    pub fn to_owned(&self) -> CandidateOwned {
        unsafe {
            CandidateOwned {
                ffi: crate::ffi::rice_candidate_copy(&self.ffi),
            }
        }
    }

    /// Serialize this candidate to a string for use in SDP
    ///
    /// # Examples
    ///
    /// ```
    /// # use rice_c::candidate::*;
    /// # use rice_c::Address;
    /// let addr: Address = "127.0.0.1:2345".parse().unwrap();
    /// let candidate = Candidate::builder(
    ///     1,
    ///     CandidateType::Host,
    ///     TransportType::Udp,
    ///     "foundation",
    ///     addr,
    /// )
    /// .priority(1234)
    /// .build();
    /// assert_eq!(candidate.to_sdp_string(), "a=candidate:foundation 1 UDP 1234 127.0.0.1 2345 typ host")
    /// ```
    pub fn to_sdp_string(&self) -> String {
        unsafe {
            let res = crate::ffi::rice_candidate_to_sdp_string(&self.ffi);
            let s = CStr::from_ptr(res);
            let ret = s.to_str().unwrap().to_owned();
            crate::ffi::rice_string_free(res);
            ret
        }
    }

    /// Parse an SDP candidate string into a candidate.
    pub fn from_sdp_string(s: &str) -> Result<Candidate, ParseCandidateError> {
        let cand_str = std::ffi::CString::new(s).unwrap();
        unsafe {
            let mut ret = Candidate {
                ffi: crate::ffi::RiceCandidate::zeroed(),
            };
            let res =
                crate::ffi::rice_candidate_init_from_sdp_string(&mut ret.ffi, cand_str.as_ptr());
            ParseCandidateError::from_c(res)?;
            Ok(ret)
        }
    }
}

/// An ICE candidate.
///
/// Backed inside a heap allocation.
#[derive(Eq)]
pub struct CandidateOwned {
    ffi: *mut crate::ffi::RiceCandidate,
}

unsafe impl Send for CandidateOwned {}
unsafe impl Sync for CandidateOwned {}

impl core::fmt::Debug for CandidateOwned {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut dbg = f.debug_struct("CandidateOwned");
        dbg.field("component_id", &self.component_id());
        dbg.field("candidate_type", &self.candidate_type());
        dbg.field("transport_type", &self.transport());
        dbg.field("foundation", &self.foundation());
        dbg.field("priority", &self.priority());
        dbg.field("address", &self.address());
        dbg.field("base_address", &self.base_address());
        dbg.field("related_address", &self.related_address());
        dbg.field("tcp_type", &self.tcp_type());
        // TODO: extensions
        dbg.finish()
    }
}

impl PartialEq<CandidateOwned> for CandidateOwned {
    fn eq(&self, other: &CandidateOwned) -> bool {
        unsafe { crate::ffi::rice_candidate_eq(self.ffi, other.ffi) }
    }
}

impl PartialEq<Candidate> for CandidateOwned {
    fn eq(&self, other: &Candidate) -> bool {
        unsafe { crate::ffi::rice_candidate_eq(self.ffi, &other.ffi) }
    }
}

impl Clone for CandidateOwned {
    fn clone(&self) -> Self {
        unsafe {
            Self {
                ffi: crate::ffi::rice_candidate_copy(self.ffi),
            }
        }
    }
}

impl Drop for CandidateOwned {
    fn drop(&mut self) {
        unsafe { crate::ffi::rice_candidate_free(self.ffi) }
    }
}

impl CandidateApi for CandidateOwned {}
impl sealed::CandidateAsC for CandidateOwned {
    fn as_c(&self) -> *const crate::ffi::RiceCandidate {
        self.ffi
    }
}

impl CandidateOwned {
    pub(crate) fn as_c(&self) -> *const crate::ffi::RiceCandidate {
        self.ffi
    }

    /// Serialize this candidate to a string for use in SDP
    ///
    /// # Examples
    ///
    /// ```
    /// # use rice_c::candidate::*;
    /// # use rice_c::Address;
    /// let addr: Address = "127.0.0.1:2345".parse().unwrap();
    /// let candidate = Candidate::builder(
    ///     1,
    ///     CandidateType::Host,
    ///     TransportType::Udp,
    ///     "foundation",
    ///     addr,
    /// )
    /// .priority(1234)
    /// .build();
    /// assert_eq!(candidate.to_sdp_string(), "a=candidate:foundation 1 UDP 1234 127.0.0.1 2345 typ host")
    /// ```
    pub fn to_sdp_string(&self) -> String {
        unsafe {
            let res = crate::ffi::rice_candidate_to_sdp_string(self.ffi);
            let s = CStr::from_ptr(res);
            let ret = s.to_str().unwrap().to_owned();
            crate::ffi::rice_string_free(res);
            ret
        }
    }
}

/// A builder for a [`Candidate`]
#[derive(Debug)]
pub struct CandidateBuilder {
    ffi: crate::ffi::RiceCandidate,
}

impl CandidateBuilder {
    /// Consume this builder a construct a new [`Candidate`].
    pub fn build(self) -> Candidate {
        Candidate { ffi: self.ffi }
    }

    /// Specify the priority of the to be built candidate
    pub fn priority(mut self, priority: u32) -> Self {
        unsafe {
            crate::ffi::rice_candidate_set_priority(&mut self.ffi, priority);
            self
        }
    }

    /// Specify the base address of the to be built candidate
    pub fn base_address(mut self, base: crate::Address) -> Self {
        unsafe {
            crate::ffi::rice_candidate_set_base_address(&mut self.ffi, base.into_c_full());
            self
        }
    }

    /// Specify the related address of the to be built candidate
    pub fn related_address(mut self, related: crate::Address) -> Self {
        unsafe {
            crate::ffi::rice_candidate_set_related_address(&mut self.ffi, related.into_c_full());
            self
        }
    }

    /// Specify the type of TCP connection of the to be built candidate
    ///
    /// - This will panic at build() time if the transport type is not [`TransportType::Tcp`].
    /// - This will panic at build() time if this function is not called but the
    ///   transport type is [`TransportType::Tcp`]
    pub fn tcp_type(mut self, typ: TcpType) -> Self {
        unsafe {
            if self.ffi.transport_type != TransportType::Tcp.into() && typ != TcpType::None {
                panic!("Attempt made to set the TcpType of a non-TCP candidate");
            }
            crate::ffi::rice_candidate_set_tcp_type(&mut self.ffi, typ.into());
            self
        }
    }

    // TODO: extensions
}

/// The type of the candidate
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum CandidateType {
    /// The candidate is a local network interface
    Host = crate::ffi::RICE_CANDIDATE_TYPE_HOST,
    /// The candidate was discovered from incoming data
    PeerReflexive = crate::ffi::RICE_CANDIDATE_TYPE_PEER_REFLEXIVE,
    /// The candidate was discovered by asking an external server (STUN/TURN)
    ServerReflexive = crate::ffi::RICE_CANDIDATE_TYPE_SERVER_REFLEXIVE,
    /// The candidate will relay all data through an external server (TURN).
    Relayed = crate::ffi::RICE_CANDIDATE_TYPE_RELAYED,
}

impl From<crate::ffi::RiceCandidateType> for CandidateType {
    fn from(value: crate::ffi::RiceCandidateType) -> Self {
        match value {
            crate::ffi::RICE_CANDIDATE_TYPE_HOST => Self::Host,
            crate::ffi::RICE_CANDIDATE_TYPE_PEER_REFLEXIVE => Self::PeerReflexive,
            crate::ffi::RICE_CANDIDATE_TYPE_SERVER_REFLEXIVE => Self::ServerReflexive,
            crate::ffi::RICE_CANDIDATE_TYPE_RELAYED => Self::Relayed,
            val => panic!("Unknown candidate type {val:x?}"),
        }
    }
}

impl From<CandidateType> for crate::ffi::RiceCandidateType {
    fn from(value: CandidateType) -> Self {
        match value {
            CandidateType::Host => crate::ffi::RICE_CANDIDATE_TYPE_HOST,
            CandidateType::PeerReflexive => crate::ffi::RICE_CANDIDATE_TYPE_PEER_REFLEXIVE,
            CandidateType::ServerReflexive => crate::ffi::RICE_CANDIDATE_TYPE_SERVER_REFLEXIVE,
            CandidateType::Relayed => crate::ffi::RICE_CANDIDATE_TYPE_RELAYED,
        }
    }
}

/// The type of TCP candidate
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(u32)]
pub enum TcpType {
    /// Not a TCP candidate.
    None = crate::ffi::RICE_TCP_TYPE_NONE,
    /// The candidate address will connect to a remote address.
    Active = crate::ffi::RICE_TCP_TYPE_ACTIVE,
    /// The candidate will listen for incominng TCP connections.
    Passive = crate::ffi::RICE_TCP_TYPE_PASSIVE,
    /// Simultaneous open.  The candidate will both listen for incoming connections, and connect to
    /// remote addresses.
    So = crate::ffi::RICE_TCP_TYPE_SO,
}

impl From<crate::ffi::RiceTcpType> for TcpType {
    fn from(value: crate::ffi::RiceTcpType) -> Self {
        match value {
            crate::ffi::RICE_TCP_TYPE_NONE => Self::None,
            crate::ffi::RICE_TCP_TYPE_ACTIVE => Self::Active,
            crate::ffi::RICE_TCP_TYPE_PASSIVE => Self::Passive,
            crate::ffi::RICE_TCP_TYPE_SO => Self::So,
            val => panic!("Unknown tcp type value {val:x?}"),
        }
    }
}

impl From<TcpType> for crate::ffi::RiceTcpType {
    fn from(value: TcpType) -> Self {
        match value {
            TcpType::None => crate::ffi::RICE_TCP_TYPE_NONE,
            TcpType::Active => crate::ffi::RICE_TCP_TYPE_ACTIVE,
            TcpType::Passive => crate::ffi::RICE_TCP_TYPE_PASSIVE,
            TcpType::So => crate::ffi::RICE_TCP_TYPE_SO,
        }
    }
}

/// The transport type.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TransportType {
    /// UDP transport.
    Udp,
    /// TCP transport.
    Tcp,
}

impl core::fmt::Display for TransportType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{self:?}")
    }
}

impl From<crate::ffi::RiceTransportType> for TransportType {
    fn from(value: crate::ffi::RiceTransportType) -> Self {
        match value {
            crate::ffi::RICE_TRANSPORT_TYPE_UDP => Self::Udp,
            crate::ffi::RICE_TRANSPORT_TYPE_TCP => Self::Tcp,
            _ => panic!("Unknown transport type value"),
        }
    }
}

impl From<TransportType> for crate::ffi::RiceTransportType {
    fn from(value: TransportType) -> Self {
        match value {
            TransportType::Udp => crate::ffi::RICE_TRANSPORT_TYPE_UDP,
            TransportType::Tcp => crate::ffi::RICE_TRANSPORT_TYPE_TCP,
        }
    }
}

impl core::str::FromStr for TransportType {
    type Err = ParseTransportTypeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.eq_ignore_ascii_case("udp") {
            Ok(Self::Udp)
        } else if s.eq_ignore_ascii_case("tcp") {
            Ok(Self::Tcp)
        } else {
            Err(ParseTransportTypeError::UnknownTransport)
        }
    }
}

/// Errors when parsing a [`TransportType`]
#[derive(Copy, Clone, Debug, thiserror::Error, PartialEq, Eq)]
pub enum ParseTransportTypeError {
    /// An unknown transport value was provided
    #[error("Unknown transport value was provided")]
    UnknownTransport,
}

/// Paired local and remote candidate
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CandidatePair {
    /// The local [`Candidate`]
    pub local: CandidateOwned,
    /// The remote [`Candidate`]
    pub remote: CandidateOwned,
}

impl CandidatePair {
    /// Create a new [`CandidatePair`]
    pub fn new(local: CandidateOwned, remote: CandidateOwned) -> Self {
        Self { local, remote }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn candidate_type() {
        let _log = crate::tests::test_init_log();

        for (c, r) in [
            (crate::ffi::RICE_CANDIDATE_TYPE_HOST, CandidateType::Host),
            (
                crate::ffi::RICE_CANDIDATE_TYPE_SERVER_REFLEXIVE,
                CandidateType::ServerReflexive,
            ),
            (
                crate::ffi::RICE_CANDIDATE_TYPE_PEER_REFLEXIVE,
                CandidateType::PeerReflexive,
            ),
            (
                crate::ffi::RICE_CANDIDATE_TYPE_RELAYED,
                CandidateType::Relayed,
            ),
        ] {
            assert_eq!(CandidateType::from(c), r);
            assert_eq!(crate::ffi::RiceCandidateType::from(r), c);
        }
    }

    #[test]
    #[should_panic = "Unknown candidate type"]
    fn candidate_type_out_of_range() {
        let _log = crate::tests::test_init_log();
        let _ = CandidateType::from(u32::MAX);
    }

    #[test]
    fn tcp_type() {
        let _log = crate::tests::test_init_log();

        for (c, r) in [
            (crate::ffi::RICE_TCP_TYPE_NONE, TcpType::None),
            (crate::ffi::RICE_TCP_TYPE_ACTIVE, TcpType::Active),
            (crate::ffi::RICE_TCP_TYPE_PASSIVE, TcpType::Passive),
            (crate::ffi::RICE_TCP_TYPE_SO, TcpType::So),
        ] {
            assert_eq!(TcpType::from(c), r);
            assert_eq!(crate::ffi::RiceTcpType::from(r), c);
        }
    }

    #[test]
    #[should_panic = "Unknown tcp type value"]
    fn tcp_type_out_of_range() {
        let _log = crate::tests::test_init_log();
        let _ = TcpType::from(u32::MAX);
    }

    #[test]
    fn transport_type() {
        let _log = crate::tests::test_init_log();

        for (c, r) in [
            (crate::ffi::RICE_TRANSPORT_TYPE_UDP, TransportType::Udp),
            (crate::ffi::RICE_TRANSPORT_TYPE_TCP, TransportType::Tcp),
        ] {
            assert_eq!(TransportType::from(c), r);
            assert_eq!(crate::ffi::RiceTransportType::from(r), c);
        }
    }

    #[test]
    #[should_panic = "Unknown transport type value"]
    fn transport_type_out_of_range() {
        let _log = crate::tests::test_init_log();
        let _ = TransportType::from(u32::MAX);
    }

    #[test]
    fn parse_candidate_error() {
        let _log = crate::tests::test_init_log();

        for (c, r) in [
            (crate::ffi::RICE_PARSE_CANDIDATE_ERROR_SUCCESS, Ok(())),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_NOT_CANDIDATE,
                Err(ParseCandidateError::NotCandidate),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_FOUNDATION,
                Err(ParseCandidateError::BadFoundation),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_COMPONENT_ID,
                Err(ParseCandidateError::BadComponentId),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_TRANSPORT_TYPE,
                Err(ParseCandidateError::BadTransportType),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_PRIORITY,
                Err(ParseCandidateError::BadPriority),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_ADDRESS,
                Err(ParseCandidateError::BadAddress),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_CANDIDATE_TYPE,
                Err(ParseCandidateError::BadCandidateType),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_BAD_EXTENSION,
                Err(ParseCandidateError::BadExtension),
            ),
            (
                crate::ffi::RICE_PARSE_CANDIDATE_ERROR_MALFORMED,
                Err(ParseCandidateError::Malformed),
            ),
        ] {
            assert_eq!(ParseCandidateError::from_c(c), r);
        }
    }

    #[test]
    #[should_panic = "Unknown RiceParseCandidateError value"]
    fn parse_candidate_error_out_of_range() {
        let _log = crate::tests::test_init_log();
        let _ = ParseCandidateError::from_c(i32::MAX);
    }

    #[test]
    fn transport_type_from_str() {
        use core::str::FromStr;
        let _log = crate::tests::test_init_log();

        for (s, r) in [
            ("udp", Ok(TransportType::Udp)),
            ("UDP", Ok(TransportType::Udp)),
            ("tcp", Ok(TransportType::Tcp)),
            ("TCP", Ok(TransportType::Tcp)),
            ("random", Err(ParseTransportTypeError::UnknownTransport)),
        ] {
            assert_eq!(TransportType::from_str(s), r);
        }
    }

    fn base_address() -> crate::Address {
        "127.0.0.1:1000".parse().unwrap()
    }

    fn address() -> crate::Address {
        "127.0.0.2:2000".parse().unwrap()
    }

    fn related_address() -> crate::Address {
        "127.0.0.3:3000".parse().unwrap()
    }

    #[test]
    fn candidate_build() {
        let _log = crate::tests::test_init_log();

        let base = base_address();
        let addr = address();
        let related = related_address();
        let cand = Candidate::builder(
            1,
            CandidateType::PeerReflexive,
            TransportType::Tcp,
            "foundation",
            addr.clone(),
        )
        .base_address(base.clone())
        .related_address(related.clone())
        .tcp_type(TcpType::Active)
        .priority(1234)
        .build();
        assert_eq!(cand.component_id(), 1);
        assert_eq!(cand.candidate_type(), CandidateType::PeerReflexive);
        assert_eq!(cand.transport(), TransportType::Tcp);
        assert_eq!(cand.foundation(), "foundation");
        assert_eq!(cand.address(), addr);
        assert_eq!(cand.base_address(), base);
        assert_eq!(cand.related_address(), Some(related));
        assert_eq!(cand.tcp_type(), TcpType::Active);
        assert_eq!(cand.priority(), 1234);

        let cand_clone = cand.clone();
        assert_eq!(cand, cand_clone);
    }

    #[test]
    fn candidate_to_owned() {
        let _log = crate::tests::test_init_log();

        let base = base_address();
        let addr = address();
        let related = related_address();
        let cand = Candidate::builder(
            1,
            CandidateType::PeerReflexive,
            TransportType::Tcp,
            "foundation",
            addr.clone(),
        )
        .base_address(base.clone())
        .related_address(related.clone())
        .tcp_type(TcpType::Active)
        .priority(1234)
        .build();
        let owned = cand.to_owned();
        assert_eq!(cand, owned);
        assert_eq!(owned, cand);
    }

    #[test]
    fn candidate_string() {
        let _log = crate::tests::test_init_log();

        let addr = address();
        let related = related_address();
        let cand = Candidate::builder(
            1,
            CandidateType::PeerReflexive,
            TransportType::Tcp,
            "foundation",
            addr.clone(),
        )
        .related_address(related.clone())
        .tcp_type(TcpType::Active)
        .priority(1234)
        .build();

        let s = cand.to_sdp_string();
        println!("{s}");
        let parsed = Candidate::from_sdp_string(&s).unwrap();
        assert_eq!(parsed, cand);

        let owned = cand.to_owned();
        let s = cand.to_sdp_string();
        println!("{s}");
        let parsed = Candidate::from_sdp_string(&s).unwrap();
        assert_eq!(parsed, owned);
    }
}