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
// Copyright (c) 2017, 2018 lumi <lumi@pew.im>
// Copyright (c) 2017, 2018, 2019 Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
// Copyright (c) 2017, 2018, 2019 Maxime “pep” Buquet <pep@bouah.net>
// Copyright (c) 2017, 2018 Astro <astro@spaceboyz.net>
// Copyright (c) 2017 Bastien Orivel <eijebong@bananium.fr>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![deny(missing_docs)]

//! Represents XMPP addresses, also known as JabberIDs (JIDs) for the [XMPP](https://xmpp.org/)
//! protocol. A [`Jid`] can have between one and three parts in the form `node@domain/resource`:
//! - the (optional) node part designates a specific account/service on a server, for example
//!   `username@server.com`
//! - the domain part designates a server, for example `irc.jabberfr.org`
//! - the (optional) resource part designates a more specific client, such as a participant in a
//!   groupchat (`jabberfr@chat.jabberfr.org/user`) or a specific client device associated with an
//!   account (`user@example.com/dino`)
//!
//! The [`Jid`] enum can be one of two variants, containing a more specific type:
//! - [`BareJid`] (`Jid::Bare` variant): a JID without a resource
//! - [`FullJid`] (`Jid::Full` variant): a JID with a resource
//!
//! Jids as per the XMPP protocol only ever contain valid UTF-8. However, creating any form of Jid
//! can fail in one of the following cases:
//! - wrong syntax: creating a Jid with an empty (yet declared) node or resource part, such as
//!   `@example.com` or `user@example.com/`
//! - stringprep error: some characters were invalid according to the stringprep algorithm, such as
//!   mixing left-to-write and right-to-left characters

use core::num::NonZeroU16;
use std::convert::TryFrom;
use std::fmt;
use std::str::FromStr;

#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};

mod error;
pub use crate::error::Error;

mod inner;
use inner::InnerJid;

mod parts;
pub use parts::{DomainPart, NodePart, ResourcePart};

/// An enum representing a Jabber ID. It can be either a `FullJid` or a `BareJid`.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Jid {
    /// Contains a [`BareJid`], without a resource part
    Bare(BareJid),

    /// Contains a [`FullJid`], with a resource part
    Full(FullJid),
}

impl FromStr for Jid {
    type Err = Error;

    fn from_str(s: &str) -> Result<Jid, Error> {
        Jid::new(s)
    }
}

impl From<BareJid> for Jid {
    fn from(bare_jid: BareJid) -> Jid {
        Jid::Bare(bare_jid)
    }
}

impl From<FullJid> for Jid {
    fn from(full_jid: FullJid) -> Jid {
        Jid::Full(full_jid)
    }
}

impl fmt::Display for Jid {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        match self {
            Jid::Bare(bare) => bare.fmt(fmt),
            Jid::Full(full) => full.fmt(fmt),
        }
    }
}

impl Jid {
    /// Constructs a Jabber ID from a string. This is of the form
    /// `node`@`domain`/`resource`, where node and resource parts are optional.
    /// If you want a non-fallible version, use [`Jid::from_parts`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use jid::Jid;
    /// # use jid::Error;
    ///
    /// # fn main() -> Result<(), Error> {
    /// let jid = Jid::new("node@domain/resource")?;
    ///
    /// assert_eq!(jid.node_str(), Some("node"));
    /// assert_eq!(jid.domain_str(), "domain");
    /// assert_eq!(jid.resource_str(), Some("resource"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(s: &str) -> Result<Jid, Error> {
        let inner = InnerJid::new(s)?;
        if inner.slash.is_some() {
            Ok(Jid::Full(FullJid { inner }))
        } else {
            Ok(Jid::Bare(BareJid { inner }))
        }
    }

    /// Returns the inner String of this JID.
    pub fn into_inner(self) -> String {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => inner.normalized,
        }
    }

    /// Build a [`Jid`] from typed parts. This method cannot fail because it uses parts that have
    /// already been parsed and stringprepped into [`NodePart`], [`DomainPart`], and [`ResourcePart`].
    /// This method allocates and does not consume the typed parts.
    pub fn from_parts(
        node: Option<&NodePart>,
        domain: &DomainPart,
        resource: Option<&ResourcePart>,
    ) -> Jid {
        if let Some(resource) = resource {
            Jid::Full(FullJid::from_parts(node, domain, resource))
        } else {
            Jid::Bare(BareJid::from_parts(node, domain))
        }
    }

    /// The optional node part of the JID, as a [`NodePart`]
    pub fn node(&self) -> Option<NodePart> {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => {
                inner.node().map(|s| NodePart::new_unchecked(s))
            }
        }
    }

    /// The optional node part of the JID, as a stringy reference
    pub fn node_str(&self) -> Option<&str> {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => inner.node(),
        }
    }

    /// The domain part of the JID, as a [`DomainPart`]
    pub fn domain(&self) -> DomainPart {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => {
                DomainPart::new_unchecked(inner.domain())
            }
        }
    }

    /// The domain part of the JID, as a stringy reference
    pub fn domain_str(&self) -> &str {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => inner.domain(),
        }
    }

    /// The optional resource part of the JID, as a [`ResourcePart`]. It is guaranteed to be present
    /// when the JID is a Full variant, which you can check with [`Jid::is_full`].
    pub fn resource(&self) -> Option<ResourcePart> {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => {
                inner.resource().map(|s| ResourcePart::new_unchecked(s))
            }
        }
    }

    /// The optional resource of the Jabber ID. It is guaranteed to be present when the JID is
    /// a Full variant, which you can check with [`Jid::is_full`].
    pub fn resource_str(&self) -> Option<&str> {
        match self {
            Jid::Bare(BareJid { inner }) | Jid::Full(FullJid { inner }) => inner.resource(),
        }
    }

    /// Allocate a new [`BareJid`] from this JID, discarding the resource.
    pub fn to_bare(&self) -> BareJid {
        match self {
            Jid::Full(jid) => jid.to_bare(),
            Jid::Bare(jid) => jid.clone(),
        }
    }

    /// Transforms this JID into a [`BareJid`], throwing away the resource.
    pub fn into_bare(self) -> BareJid {
        match self {
            Jid::Full(jid) => jid.into_bare(),
            Jid::Bare(jid) => jid,
        }
    }

    /// Checks if the JID contains a [`FullJid`]
    pub fn is_full(&self) -> bool {
        match self {
            Self::Full(_) => true,
            Self::Bare(_) => false,
        }
    }

    /// Checks if the JID contains a [`BareJid`]
    pub fn is_bare(&self) -> bool {
        !self.is_full()
    }
}

impl TryFrom<Jid> for FullJid {
    type Error = Error;

    fn try_from(jid: Jid) -> Result<Self, Self::Error> {
        match jid {
            Jid::Full(full) => Ok(full),
            Jid::Bare(_) => Err(Error::ResourceMissingInFullJid),
        }
    }
}

impl PartialEq<Jid> for FullJid {
    fn eq(&self, other: &Jid) -> bool {
        match other {
            Jid::Full(full) => self == full,
            Jid::Bare(_) => false,
        }
    }
}

impl PartialEq<Jid> for BareJid {
    fn eq(&self, other: &Jid) -> bool {
        match other {
            Jid::Full(_) => false,
            Jid::Bare(bare) => self == bare,
        }
    }
}

impl PartialEq<FullJid> for Jid {
    fn eq(&self, other: &FullJid) -> bool {
        match self {
            Jid::Full(full) => full == other,
            Jid::Bare(_) => false,
        }
    }
}

impl PartialEq<BareJid> for Jid {
    fn eq(&self, other: &BareJid) -> bool {
        match self {
            Jid::Full(_) => false,
            Jid::Bare(bare) => bare == other,
        }
    }
}

/// A struct representing a full Jabber ID, with a resource part.
///
/// A full JID is composed of 3 components, of which only the node is optional:
///
/// - the (optional) node part is the part before the (optional) `@`.
/// - the domain part is the mandatory part between the (optional) `@` and before the `/`.
/// - the resource part after the `/`.
///
/// Unlike a [`BareJid`], it always contains a resource, and should only be used when you are
/// certain there is no case where a resource can be missing.  Otherwise, use a [`Jid`] or
/// [`BareJid`].
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct FullJid {
    inner: InnerJid,
}

/// A struct representing a bare Jabber ID, without a resource part.
///
/// A bare JID is composed of 2 components, of which only the node is optional:
/// - the (optional) node part is the part before the (optional) `@`.
/// - the domain part is the mandatory part between the (optional) `@` and before the `/`.
///
/// Unlike a [`FullJid`], it can’t contain a resource, and should only be used when you are certain
/// there is no case where a resource can be set.  Otherwise, use a [`Jid`] or [`FullJid`].
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct BareJid {
    inner: InnerJid,
}

impl fmt::Debug for FullJid {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "FullJID({})", self)
    }
}

impl fmt::Debug for BareJid {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        write!(fmt, "BareJID({})", self)
    }
}

impl fmt::Display for FullJid {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        fmt.write_str(&self.inner.normalized)
    }
}

impl fmt::Display for BareJid {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        fmt.write_str(&self.inner.normalized)
    }
}

#[cfg(feature = "serde")]
impl Serialize for FullJid {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.inner.normalized)
    }
}

#[cfg(feature = "serde")]
impl Serialize for BareJid {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.inner.normalized)
    }
}

impl FromStr for FullJid {
    type Err = Error;

    fn from_str(s: &str) -> Result<FullJid, Error> {
        FullJid::new(s)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for FullJid {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        FullJid::from_str(&s).map_err(de::Error::custom)
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for BareJid {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        BareJid::from_str(&s).map_err(de::Error::custom)
    }
}

impl FullJid {
    /// Constructs a full Jabber ID containing all three components. This is of the form
    /// `node@domain/resource`, where node part is optional.
    /// If you want a non-fallible version, use [`FullJid::from_parts`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use jid::FullJid;
    /// # use jid::Error;
    ///
    /// # fn main() -> Result<(), Error> {
    /// let jid = FullJid::new("node@domain/resource")?;
    ///
    /// assert_eq!(jid.node_str(), Some("node"));
    /// assert_eq!(jid.domain_str(), "domain");
    /// assert_eq!(jid.resource_str(), "resource");
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(s: &str) -> Result<FullJid, Error> {
        let inner = InnerJid::new(s)?;
        if inner.slash.is_some() {
            Ok(FullJid { inner })
        } else {
            Err(Error::ResourceMissingInFullJid)
        }
    }

    /// Returns the inner String of this JID.
    pub fn into_inner(self) -> String {
        self.inner.normalized
    }

    /// Build a [`FullJid`] from typed parts. This method cannot fail because it uses parts that have
    /// already been parsed and stringprepped into [`NodePart`], [`DomainPart`], and [`ResourcePart`].
    /// This method allocates and does not consume the typed parts.
    pub fn from_parts(
        node: Option<&NodePart>,
        domain: &DomainPart,
        resource: &ResourcePart,
    ) -> FullJid {
        let (at, slash, normalized) = if let Some(node) = node {
            // Parts are never empty so len > 0 for NonZeroU16::new is always Some
            (
                NonZeroU16::new(node.0.len() as u16),
                NonZeroU16::new((node.0.len() + 1 + domain.0.len()) as u16),
                format!("{}@{}/{}", node.0, domain.0, resource.0),
            )
        } else {
            (
                None,
                NonZeroU16::new(domain.0.len() as u16),
                format!("{}/{}", domain.0, resource.0),
            )
        };

        let inner = InnerJid {
            normalized,
            at,
            slash,
        };

        FullJid { inner }
    }

    /// The optional node part of the JID, as a [`NodePart`]
    pub fn node(&self) -> Option<NodePart> {
        self.node_str().map(|s| NodePart::new_unchecked(s))
    }

    /// The optional node part of the JID, as a stringy reference
    pub fn node_str(&self) -> Option<&str> {
        self.inner.node()
    }

    /// The domain part of the JID, as a [`DomainPart`]
    pub fn domain(&self) -> DomainPart {
        DomainPart::new_unchecked(self.domain_str())
    }

    /// The domain part of the JID, as a stringy reference
    pub fn domain_str(&self) -> &str {
        self.inner.domain()
    }

    /// The optional resource part of the JID, as a [`ResourcePart`].  Since this is a full JID it
    /// is always present.
    pub fn resource(&self) -> ResourcePart {
        ResourcePart::new_unchecked(self.resource_str())
    }

    /// The optional resource of the Jabber ID.  Since this is a full JID it is always present.
    pub fn resource_str(&self) -> &str {
        self.inner.resource().unwrap()
    }

    /// Allocate a new [`BareJid`] from this full JID, discarding the resource.
    pub fn to_bare(&self) -> BareJid {
        let slash = self.inner.slash.unwrap().get() as usize;
        let normalized = self.inner.normalized[..slash].to_string();
        let inner = InnerJid {
            normalized,
            at: self.inner.at,
            slash: None,
        };
        BareJid { inner }
    }

    /// Transforms this full JID into a [`BareJid`], discarding the resource.
    pub fn into_bare(mut self) -> BareJid {
        let slash = self.inner.slash.unwrap().get() as usize;
        self.inner.normalized.truncate(slash);
        self.inner.normalized.shrink_to_fit();
        self.inner.slash = None;
        BareJid { inner: self.inner }
    }
}

impl FromStr for BareJid {
    type Err = Error;

    fn from_str(s: &str) -> Result<BareJid, Error> {
        BareJid::new(s)
    }
}

impl BareJid {
    /// Constructs a bare Jabber ID, containing two components. This is of the form
    /// `node`@`domain`, where node part is optional.
    /// If you want a non-fallible version, use [`BareJid::from_parts`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use jid::BareJid;
    /// # use jid::Error;
    ///
    /// # fn main() -> Result<(), Error> {
    /// let jid = BareJid::new("node@domain")?;
    ///
    /// assert_eq!(jid.node_str(), Some("node"));
    /// assert_eq!(jid.domain_str(), "domain");
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(s: &str) -> Result<BareJid, Error> {
        let inner = InnerJid::new(s)?;
        if inner.slash.is_none() {
            Ok(BareJid { inner })
        } else {
            Err(Error::ResourceInBareJid)
        }
    }

    /// Returns the inner String of this JID.
    pub fn into_inner(self) -> String {
        self.inner.normalized
    }

    /// Build a [`BareJid`] from typed parts. This method cannot fail because it uses parts that have
    /// already been parsed and stringprepped into [`NodePart`] and [`DomainPart`]. This method allocates
    /// and does not consume the typed parts.
    pub fn from_parts(node: Option<&NodePart>, domain: &DomainPart) -> BareJid {
        let (at, normalized) = if let Some(node) = node {
            // Parts are never empty so len > 0 for NonZeroU16::new is always Some
            (
                NonZeroU16::new(node.0.len() as u16),
                format!("{}@{}", node.0, domain.0),
            )
        } else {
            (None, domain.0.clone())
        };

        let inner = InnerJid {
            normalized,
            at,
            slash: None,
        };

        BareJid { inner }
    }

    /// The optional node part of the JID, as a [`NodePart`]
    pub fn node(&self) -> Option<NodePart> {
        self.node_str().map(|s| NodePart::new_unchecked(s))
    }

    /// The optional node part of the JID, as a stringy reference
    pub fn node_str(&self) -> Option<&str> {
        self.inner.node()
    }

    /// The domain part of the JID, as a [`DomainPart`]
    pub fn domain(&self) -> DomainPart {
        DomainPart::new_unchecked(self.domain_str())
    }

    /// The domain part of the JID, as a stringy reference
    pub fn domain_str(&self) -> &str {
        self.inner.domain()
    }

    /// Constructs a [`BareJid`] from the bare JID, by specifying a [`ResourcePart`].
    /// If you'd like to specify a stringy resource, use [`BareJid::with_resource_str`] instead.
    ///
    /// # Examples
    ///
    /// ```
    /// use jid::{BareJid, ResourcePart};
    ///
    /// let resource = ResourcePart::new("resource").unwrap();
    /// let bare = BareJid::new("node@domain").unwrap();
    /// let full = bare.with_resource(&resource);
    ///
    /// assert_eq!(full.node_str(), Some("node"));
    /// assert_eq!(full.domain_str(), "domain");
    /// assert_eq!(full.resource_str(), "resource");
    /// ```
    pub fn with_resource(&self, resource: &ResourcePart) -> FullJid {
        let slash = NonZeroU16::new(self.inner.normalized.len() as u16);
        let normalized = format!("{}/{resource}", self.inner.normalized);
        let inner = InnerJid {
            normalized,
            at: self.inner.at,
            slash,
        };

        FullJid { inner }
    }

    /// Constructs a [`FullJid`] from the bare JID, by specifying a stringy `resource`.
    /// If your resource has already been parsed into a [`ResourcePart`], use [`BareJid::with_resource`].
    ///
    /// # Examples
    ///
    /// ```
    /// use jid::BareJid;
    ///
    /// let bare = BareJid::new("node@domain").unwrap();
    /// let full = bare.with_resource_str("resource").unwrap();
    ///
    /// assert_eq!(full.node_str(), Some("node"));
    /// assert_eq!(full.domain_str(), "domain");
    /// assert_eq!(full.resource_str(), "resource");
    /// ```
    pub fn with_resource_str(&self, resource: &str) -> Result<FullJid, Error> {
        let resource = ResourcePart::new(resource)?;
        Ok(self.with_resource(&resource))
    }
}

#[cfg(feature = "minidom")]
use minidom::{IntoAttributeValue, Node};

#[cfg(feature = "minidom")]
impl IntoAttributeValue for Jid {
    fn into_attribute_value(self) -> Option<String> {
        Some(self.to_string())
    }
}

#[cfg(feature = "minidom")]
impl From<Jid> for Node {
    fn from(jid: Jid) -> Node {
        Node::Text(jid.to_string())
    }
}

#[cfg(feature = "minidom")]
impl IntoAttributeValue for FullJid {
    fn into_attribute_value(self) -> Option<String> {
        Some(self.to_string())
    }
}

#[cfg(feature = "minidom")]
impl From<FullJid> for Node {
    fn from(jid: FullJid) -> Node {
        Node::Text(jid.to_string())
    }
}

#[cfg(feature = "minidom")]
impl IntoAttributeValue for BareJid {
    fn into_attribute_value(self) -> Option<String> {
        Some(self.to_string())
    }
}

#[cfg(feature = "minidom")]
impl From<BareJid> for Node {
    fn from(jid: BareJid) -> Node {
        Node::Text(jid.to_string())
    }
}

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

    use std::collections::HashMap;

    macro_rules! assert_size (
        ($t:ty, $sz:expr) => (
            assert_eq!(::std::mem::size_of::<$t>(), $sz);
        );
    );

    #[cfg(target_pointer_width = "32")]
    #[test]
    fn test_size() {
        assert_size!(BareJid, 16);
        assert_size!(FullJid, 16);
        assert_size!(Jid, 20);
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn test_size() {
        assert_size!(BareJid, 32);
        assert_size!(FullJid, 32);
        assert_size!(Jid, 40);
    }

    #[test]
    fn can_parse_full_jids() {
        assert_eq!(
            FullJid::from_str("a@b.c/d"),
            Ok(FullJid::new("a@b.c/d").unwrap())
        );
        assert_eq!(
            FullJid::from_str("b.c/d"),
            Ok(FullJid::new("b.c/d").unwrap())
        );

        assert_eq!(
            FullJid::from_str("a@b.c"),
            Err(Error::ResourceMissingInFullJid)
        );
        assert_eq!(
            FullJid::from_str("b.c"),
            Err(Error::ResourceMissingInFullJid)
        );
    }

    #[test]
    fn can_parse_bare_jids() {
        assert_eq!(
            BareJid::from_str("a@b.c"),
            Ok(BareJid::new("a@b.c").unwrap())
        );
        assert_eq!(BareJid::from_str("b.c"), Ok(BareJid::new("b.c").unwrap()));
    }

    #[test]
    fn can_parse_jids() {
        let full = FullJid::from_str("a@b.c/d").unwrap();
        let bare = BareJid::from_str("e@f.g").unwrap();

        assert_eq!(Jid::from_str("a@b.c/d"), Ok(Jid::Full(full)));
        assert_eq!(Jid::from_str("e@f.g"), Ok(Jid::Bare(bare)));
    }

    #[test]
    fn full_to_bare_jid() {
        let bare: BareJid = FullJid::new("a@b.c/d").unwrap().to_bare();
        assert_eq!(bare, BareJid::new("a@b.c").unwrap());
    }

    #[test]
    fn bare_to_full_jid_str() {
        assert_eq!(
            BareJid::new("a@b.c")
                .unwrap()
                .with_resource_str("d")
                .unwrap(),
            FullJid::new("a@b.c/d").unwrap()
        );
    }

    #[test]
    fn bare_to_full_jid() {
        assert_eq!(
            BareJid::new("a@b.c")
                .unwrap()
                .with_resource(&ResourcePart::new("d").unwrap()),
            FullJid::new("a@b.c/d").unwrap()
        )
    }

    #[test]
    fn node_from_jid() {
        let jid = Jid::new("a@b.c/d").unwrap();

        assert_eq!(jid.node_str(), Some("a"),);

        assert_eq!(jid.node(), Some(NodePart::new("a").unwrap()));
    }

    #[test]
    fn domain_from_jid() {
        let jid = Jid::new("a@b.c").unwrap();

        assert_eq!(jid.domain_str(), "b.c");

        assert_eq!(jid.domain(), DomainPart::new("b.c").unwrap());
    }

    #[test]
    fn resource_from_jid() {
        let jid = Jid::new("a@b.c/d").unwrap();

        assert_eq!(jid.resource_str(), Some("d"),);

        assert_eq!(jid.resource(), Some(ResourcePart::new("d").unwrap()));
    }

    #[test]
    fn jid_to_full_bare() {
        let full = FullJid::new("a@b.c/d").unwrap();
        let bare = BareJid::new("a@b.c").unwrap();

        assert_eq!(FullJid::try_from(Jid::Full(full.clone())), Ok(full.clone()));
        assert_eq!(
            FullJid::try_from(Jid::Bare(bare.clone())),
            Err(Error::ResourceMissingInFullJid),
        );
        assert_eq!(Jid::Bare(full.clone().to_bare()), bare.clone());
        assert_eq!(Jid::Bare(bare.clone()), bare);
    }

    #[test]
    fn serialise() {
        assert_eq!(FullJid::new("a@b/c").unwrap().to_string(), "a@b/c");
        assert_eq!(BareJid::new("a@b").unwrap().to_string(), "a@b");
    }

    #[test]
    fn hash() {
        let _map: HashMap<Jid, String> = HashMap::new();
    }

    #[test]
    fn invalid_jids() {
        assert_eq!(BareJid::from_str(""), Err(Error::DomainEmpty));
        assert_eq!(BareJid::from_str("/c"), Err(Error::DomainEmpty));
        assert_eq!(BareJid::from_str("a@/c"), Err(Error::DomainEmpty));
        assert_eq!(BareJid::from_str("@b"), Err(Error::NodeEmpty));
        assert_eq!(BareJid::from_str("b/"), Err(Error::ResourceEmpty));

        assert_eq!(FullJid::from_str(""), Err(Error::DomainEmpty));
        assert_eq!(FullJid::from_str("/c"), Err(Error::DomainEmpty));
        assert_eq!(FullJid::from_str("a@/c"), Err(Error::DomainEmpty));
        assert_eq!(FullJid::from_str("@b"), Err(Error::NodeEmpty));
        assert_eq!(FullJid::from_str("b/"), Err(Error::ResourceEmpty));
        assert_eq!(
            FullJid::from_str("a@b"),
            Err(Error::ResourceMissingInFullJid)
        );
    }

    #[test]
    fn display_jids() {
        assert_eq!(FullJid::new("a@b/c").unwrap().to_string(), "a@b/c");
        assert_eq!(BareJid::new("a@b").unwrap().to_string(), "a@b");
        assert_eq!(
            Jid::Full(FullJid::new("a@b/c").unwrap()).to_string(),
            "a@b/c"
        );
        assert_eq!(Jid::Bare(BareJid::new("a@b").unwrap()).to_string(), "a@b");
    }

    #[cfg(feature = "minidom")]
    #[test]
    fn minidom() {
        let elem: minidom::Element = "<message xmlns='ns1' from='a@b/c'/>".parse().unwrap();
        let to: Jid = elem.attr("from").unwrap().parse().unwrap();
        assert_eq!(to, Jid::Full(FullJid::new("a@b/c").unwrap()));

        let elem: minidom::Element = "<message xmlns='ns1' from='a@b'/>".parse().unwrap();
        let to: Jid = elem.attr("from").unwrap().parse().unwrap();
        assert_eq!(to, Jid::Bare(BareJid::new("a@b").unwrap()));

        let elem: minidom::Element = "<message xmlns='ns1' from='a@b/c'/>".parse().unwrap();
        let to: FullJid = elem.attr("from").unwrap().parse().unwrap();
        assert_eq!(to, FullJid::new("a@b/c").unwrap());

        let elem: minidom::Element = "<message xmlns='ns1' from='a@b'/>".parse().unwrap();
        let to: BareJid = elem.attr("from").unwrap().parse().unwrap();
        assert_eq!(to, BareJid::new("a@b").unwrap());
    }

    #[cfg(feature = "minidom")]
    #[test]
    fn minidom_into_attr() {
        let full = FullJid::new("a@b/c").unwrap();
        let elem = minidom::Element::builder("message", "jabber:client")
            .attr("from", full.clone())
            .build();
        assert_eq!(elem.attr("from"), Some(full.to_string().as_str()));

        let bare = BareJid::new("a@b").unwrap();
        let elem = minidom::Element::builder("message", "jabber:client")
            .attr("from", bare.clone())
            .build();
        assert_eq!(elem.attr("from"), Some(bare.to_string().as_str()));

        let jid = Jid::Bare(bare.clone());
        let _elem = minidom::Element::builder("message", "jabber:client")
            .attr("from", jid)
            .build();
        assert_eq!(elem.attr("from"), Some(bare.to_string().as_str()));
    }

    #[test]
    fn stringprep() {
        let full = FullJid::from_str("Test@☃.coM/Test™").unwrap();
        let equiv = FullJid::new("test@☃.com/TestTM").unwrap();
        assert_eq!(full, equiv);
    }

    #[test]
    fn invalid_stringprep() {
        FullJid::from_str("a@b/🎉").unwrap_err();
    }

    #[test]
    fn jid_from_parts() {
        let node = NodePart::new("node").unwrap();
        let domain = DomainPart::new("domain").unwrap();
        let resource = ResourcePart::new("resource").unwrap();

        let jid = Jid::from_parts(Some(&node), &domain, Some(&resource));
        assert_eq!(jid, Jid::new("node@domain/resource").unwrap());

        let barejid = BareJid::from_parts(Some(&node), &domain);
        assert_eq!(barejid, BareJid::new("node@domain").unwrap());

        let fulljid = FullJid::from_parts(Some(&node), &domain, &resource);
        assert_eq!(fulljid, FullJid::new("node@domain/resource").unwrap());
    }

    #[test]
    #[cfg(feature = "serde")]
    fn jid_ser_de() {
        let jid: Jid = Jid::new("node@domain").unwrap();
        serde_test::assert_tokens(&jid, &[serde_test::Token::Str("node@domain")]);

        let jid: Jid = Jid::new("node@domain/resource").unwrap();
        serde_test::assert_tokens(&jid, &[serde_test::Token::Str("node@domain/resource")]);

        let jid: BareJid = BareJid::new("node@domain").unwrap();
        serde_test::assert_tokens(&jid, &[serde_test::Token::Str("node@domain")]);

        let jid: FullJid = FullJid::new("node@domain/resource").unwrap();
        serde_test::assert_tokens(&jid, &[serde_test::Token::Str("node@domain/resource")]);
    }
}